@jupyterlab/services
Version:
Client APIs for the Jupyter services REST APIs
540 lines (539 loc) • 19.8 kB
TypeScript
import { JSONObject } from '@lumino/coreutils';
import { ISignal } from '@lumino/signaling';
import { ServerConnection } from '..';
import * as Kernel from './kernel';
import * as KernelMessage from './messages';
import { KernelSpec } from '../kernelspec';
/**
* Implementation of the Kernel object.
*
* #### Notes
* Messages from the server are handled in the order they were received and
* asynchronously. Any message handler can return a promise, and message
* handling will pause until the promise is fulfilled.
*/
export declare class KernelConnection implements Kernel.IKernelConnection {
/**
* Construct a kernel object.
*/
constructor(options: Kernel.IKernelConnection.IOptions);
get disposed(): ISignal<this, void>;
/**
* The server settings for the kernel.
*/
readonly serverSettings: ServerConnection.ISettings;
/**
* Handle comm messages
*
* #### Notes
* The comm message protocol currently has implicit assumptions that only
* one kernel connection is handling comm messages. This option allows a
* kernel connection to opt out of handling comms.
*
* See https://github.com/jupyter/jupyter_client/issues/263
*/
readonly handleComms: boolean;
/**
* A signal emitted when the kernel status changes.
*/
get statusChanged(): ISignal<this, KernelMessage.Status>;
/**
* A signal emitted when the kernel status changes.
*/
get connectionStatusChanged(): ISignal<this, Kernel.ConnectionStatus>;
/**
* A signal emitted for iopub kernel messages.
*
* #### Notes
* This signal is emitted after the iopub message is handled asynchronously.
*/
get iopubMessage(): ISignal<this, KernelMessage.IIOPubMessage>;
/**
* A signal emitted for unhandled kernel message.
*
* #### Notes
* This signal is emitted for a message that was not handled. It is emitted
* during the asynchronous message handling code.
*/
get unhandledMessage(): ISignal<this, KernelMessage.IMessage>;
/**
* The kernel model
*/
get model(): Kernel.IModel;
/**
* A signal emitted for any kernel message.
*
* #### Notes
* This signal is emitted when a message is received, before it is handled
* asynchronously.
*
* This message is emitted when a message is queued for sending (either in
* the websocket buffer, or our own pending message buffer). The message may
* actually be sent across the wire at a later time.
*
* The message emitted in this signal should not be modified in any way.
*/
get anyMessage(): ISignal<this, Kernel.IAnyMessageArgs>;
/**
* A signal emitted when a kernel has pending inputs from the user.
*/
get pendingInput(): ISignal<this, boolean>;
/**
* The id of the server-side kernel.
*/
get id(): string;
/**
* The name of the server-side kernel.
*/
get name(): string;
/**
* The client username.
*/
get username(): string;
/**
* The client unique id.
*/
get clientId(): string;
/**
* The current status of the kernel.
*/
get status(): KernelMessage.Status;
/**
* The current connection status of the kernel connection.
*/
get connectionStatus(): Kernel.ConnectionStatus;
/**
* Test whether the kernel has been disposed.
*/
get isDisposed(): boolean;
/**
* The cached kernel info.
*
* @returns A promise that resolves to the kernel info.
*/
get info(): Promise<KernelMessage.IInfoReply>;
/**
* The kernel spec.
*
* @returns A promise that resolves to the kernel spec.
*/
get spec(): Promise<KernelSpec.ISpecModel | undefined>;
/**
* Clone the current kernel with a new clientId.
*/
clone(options?: Pick<Kernel.IKernelConnection.IOptions, 'clientId' | 'username' | 'handleComms'>): Kernel.IKernelConnection;
/**
* Dispose of the resources held by the kernel.
*/
dispose(): void;
/**
* Send a shell message to the kernel.
*
* #### Notes
* Send a message to the kernel's shell channel, yielding a future object
* for accepting replies.
*
* If `expectReply` is given and `true`, the future is disposed when both a
* shell reply and an idle status message are received. If `expectReply`
* is not given or is `false`, the future is resolved when an idle status
* message is received.
* If `disposeOnDone` is not given or is `true`, the Future is disposed at this point.
* If `disposeOnDone` is given and `false`, it is up to the caller to dispose of the Future.
*
* All replies are validated as valid kernel messages.
*
* If the kernel status is `dead`, this will throw an error.
*/
sendShellMessage<T extends KernelMessage.ShellMessageType>(msg: KernelMessage.IShellMessage<T>, expectReply?: boolean, disposeOnDone?: boolean): Kernel.IShellFuture<KernelMessage.IShellMessage<T>>;
/**
* Send a control message to the kernel.
*
* #### Notes
* Send a message to the kernel's control channel, yielding a future object
* for accepting replies.
*
* If `expectReply` is given and `true`, the future is disposed when both a
* control reply and an idle status message are received. If `expectReply`
* is not given or is `false`, the future is resolved when an idle status
* message is received.
* If `disposeOnDone` is not given or is `true`, the Future is disposed at this point.
* If `disposeOnDone` is given and `false`, it is up to the caller to dispose of the Future.
*
* All replies are validated as valid kernel messages.
*
* If the kernel status is `dead`, this will throw an error.
*/
sendControlMessage<T extends KernelMessage.ControlMessageType>(msg: KernelMessage.IControlMessage<T>, expectReply?: boolean, disposeOnDone?: boolean): Kernel.IControlFuture<KernelMessage.IControlMessage<T>>;
private _sendKernelShellControl;
/**
* Send a message on the websocket.
*
* If queue is true, queue the message for later sending if we cannot send
* now. Otherwise throw an error.
*
* #### Notes
* As an exception to the queueing, if we are sending a kernel_info_request
* message while we think the kernel is restarting, we send the message
* immediately without queueing. This is so that we can trigger a message
* back, which will then clear the kernel restarting state.
*/
private _sendMessage;
/**
* Interrupt a kernel.
*
* #### Notes
* Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/kernels).
*
* The promise is fulfilled on a valid response and rejected otherwise.
*
* It is assumed that the API call does not mutate the kernel id or name.
*
* The promise will be rejected if the kernel status is `Dead` or if the
* request fails or the response is invalid.
*/
interrupt(): Promise<void>;
/**
* Request a kernel restart.
*
* #### Notes
* Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/kernels)
* and validates the response model.
*
* Any existing Future or Comm objects are cleared once the kernel has
* actually be restarted.
*
* The promise is fulfilled on a valid server response (after the kernel restarts)
* and rejected otherwise.
*
* It is assumed that the API call does not mutate the kernel id or name.
*
* The promise will be rejected if the request fails or the response is
* invalid.
*/
restart(): Promise<void>;
/**
* Reconnect to a kernel.
*
* #### Notes
* This may try multiple times to reconnect to a kernel, and will sever any
* existing connection.
*/
reconnect(): Promise<void>;
/**
* Shutdown a kernel.
*
* #### Notes
* Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/kernels).
*
* The promise is fulfilled on a valid response and rejected otherwise.
*
* On a valid response, disposes this kernel connection.
*
* If the kernel is already `dead`, disposes this kernel connection without
* a server request.
*/
shutdown(): Promise<void>;
/**
* Handles a kernel shutdown.
*
* #### Notes
* This method should be called if we know from outside information that a
* kernel is dead (for example, we cannot find the kernel model on the
* server).
*/
handleShutdown(): void;
/**
* Send a `kernel_info_request` message.
*
* #### Notes
* See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#kernel-info).
*
* Fulfills with the `kernel_info_response` content when the shell reply is
* received and validated.
*/
requestKernelInfo(): Promise<KernelMessage.IInfoReplyMsg | undefined>;
/**
* Send a `complete_request` message.
*
* #### Notes
* See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#completion).
*
* Fulfills with the `complete_reply` content when the shell reply is
* received and validated.
*/
requestComplete(content: KernelMessage.ICompleteRequestMsg['content']): Promise<KernelMessage.ICompleteReplyMsg>;
/**
* Send an `inspect_request` message.
*
* #### Notes
* See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#introspection).
*
* Fulfills with the `inspect_reply` content when the shell reply is
* received and validated.
*/
requestInspect(content: KernelMessage.IInspectRequestMsg['content']): Promise<KernelMessage.IInspectReplyMsg>;
/**
* Send a `history_request` message.
*
* #### Notes
* See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#history).
*
* Fulfills with the `history_reply` content when the shell reply is
* received and validated.
*/
requestHistory(content: KernelMessage.IHistoryRequestMsg['content']): Promise<KernelMessage.IHistoryReplyMsg>;
/**
* Send an `execute_request` message.
*
* #### Notes
* See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#execute).
*
* Future `onReply` is called with the `execute_reply` content when the
* shell reply is received and validated. The future will resolve when
* this message is received and the `idle` iopub status is received.
* The future will also be disposed at this point unless `disposeOnDone`
* is specified and `false`, in which case it is up to the caller to dispose
* of the future.
*
* **See also:** [[IExecuteReply]]
*/
requestExecute(content: KernelMessage.IExecuteRequestMsg['content'], disposeOnDone?: boolean, metadata?: JSONObject): Kernel.IShellFuture<KernelMessage.IExecuteRequestMsg, KernelMessage.IExecuteReplyMsg>;
/**
* Send an experimental `debug_request` message.
*
* @hidden
*
* #### Notes
* Debug messages are experimental messages that are not in the official
* kernel message specification. As such, this function is *NOT* considered
* part of the public API, and may change without notice.
*/
requestDebug(content: KernelMessage.IDebugRequestMsg['content'], disposeOnDone?: boolean): Kernel.IControlFuture<KernelMessage.IDebugRequestMsg, KernelMessage.IDebugReplyMsg>;
/**
* Send an `is_complete_request` message.
*
* #### Notes
* See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#code-completeness).
*
* Fulfills with the `is_complete_response` content when the shell reply is
* received and validated.
*/
requestIsComplete(content: KernelMessage.IIsCompleteRequestMsg['content']): Promise<KernelMessage.IIsCompleteReplyMsg>;
/**
* Send a `comm_info_request` message.
*
* #### Notes
* Fulfills with the `comm_info_reply` content when the shell reply is
* received and validated.
*/
requestCommInfo(content: KernelMessage.ICommInfoRequestMsg['content']): Promise<KernelMessage.ICommInfoReplyMsg>;
/**
* Send an `input_reply` message.
*
* #### Notes
* See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#messages-on-the-stdin-router-dealer-sockets).
*/
sendInputReply(content: KernelMessage.IInputReplyMsg['content'], parent_header: KernelMessage.IInputReplyMsg['parent_header']): void;
/**
* Create a new comm.
*
* #### Notes
* If a client-side comm already exists with the given commId, an error is thrown.
* If the kernel does not handle comms, an error is thrown.
*/
createComm(targetName: string, commId?: string): Kernel.IComm;
/**
* Check if a comm exists.
*/
hasComm(commId: string): boolean;
/**
* Register a comm target handler.
*
* @param targetName - The name of the comm target.
*
* @param callback - The callback invoked for a comm open message.
*
* @returns A disposable used to unregister the comm target.
*
* #### Notes
* Only one comm target can be registered to a target name at a time, an
* existing callback for the same target name will be overridden. A registered
* comm target handler will take precedence over a comm which specifies a
* `target_module`.
*
* If the callback returns a promise, kernel message processing will pause
* until the returned promise is fulfilled.
*/
registerCommTarget(targetName: string, callback: (comm: Kernel.IComm, msg: KernelMessage.ICommOpenMsg) => void | PromiseLike<void>): void;
/**
* Remove a comm target handler.
*
* @param targetName - The name of the comm target to remove.
*
* @param callback - The callback to remove.
*
* #### Notes
* The comm target is only removed if the callback argument matches.
*/
removeCommTarget(targetName: string, callback: (comm: Kernel.IComm, msg: KernelMessage.ICommOpenMsg) => void | PromiseLike<void>): void;
/**
* Register an IOPub message hook.
*
* @param msg_id - The parent_header message id the hook will intercept.
*
* @param hook - The callback invoked for the message.
*
* #### Notes
* The IOPub hook system allows you to preempt the handlers for IOPub
* messages that are responses to a given message id.
*
* The most recently registered hook is run first. A hook can return a
* boolean or a promise to a boolean, in which case all kernel message
* processing pauses until the promise is fulfilled. If a hook return value
* resolves to false, any later hooks will not run and the function will
* return a promise resolving to false. If a hook throws an error, the error
* is logged to the console and the next hook is run. If a hook is
* registered during the hook processing, it will not run until the next
* message. If a hook is removed during the hook processing, it will be
* deactivated immediately.
*
* See also [[IFuture.registerMessageHook]].
*/
registerMessageHook(msgId: string, hook: (msg: KernelMessage.IIOPubMessage) => boolean | PromiseLike<boolean>): void;
/**
* Remove an IOPub message hook.
*
* @param msg_id - The parent_header message id the hook intercepted.
*
* @param hook - The callback invoked for the message.
*
*/
removeMessageHook(msgId: string, hook: (msg: KernelMessage.IIOPubMessage) => boolean | PromiseLike<boolean>): void;
/**
* Remove the input guard, if any.
*/
removeInputGuard(): void;
/**
* Handle a message with a display id.
*
* @returns Whether the message was handled.
*/
private _handleDisplayId;
/**
* Forcefully clear the socket state.
*
* #### Notes
* This will clear all socket state without calling any handlers and will
* not update the connection status. If you call this method, you are
* responsible for updating the connection status as needed and recreating
* the socket if you plan to reconnect.
*/
private _clearSocket;
/**
* Handle status iopub messages from the kernel.
*/
private _updateStatus;
/**
* Send pending messages to the kernel.
*/
private _sendPending;
/**
* Clear the internal state.
*/
private _clearKernelState;
/**
* Check to make sure it is okay to proceed to handle a message.
*
* #### Notes
* Because we handle messages asynchronously, before a message is handled the
* kernel might be disposed or restarted (and have a different session id).
* This function throws an error in each of these cases. This is meant to be
* called at the start of an asynchronous message handler to cancel message
* processing if the message no longer is valid.
*/
private _assertCurrentMessage;
/**
* Handle a `comm_open` kernel message.
*/
private _handleCommOpen;
/**
* Handle 'comm_close' kernel message.
*/
private _handleCommClose;
/**
* Handle a 'comm_msg' kernel message.
*/
private _handleCommMsg;
/**
* Unregister a comm instance.
*/
private _unregisterComm;
/**
* Create the kernel websocket connection and add socket status handlers.
*/
private _createSocket;
/**
* Handle connection status changes.
*/
private _updateConnectionStatus;
private _handleMessage;
/**
* Attempt a connection if we have not exhausted connection attempts.
*/
private _reconnect;
/**
* Utility function to throw an error if this instance is disposed.
*/
private _errorIfDisposed;
/**
* Handle a websocket open event.
*/
private _onWSOpen;
/**
* Handle a websocket message, validating and routing appropriately.
*/
private _onWSMessage;
/**
* Handle a websocket close event.
*/
private _onWSClose;
get hasPendingInput(): boolean;
set hasPendingInput(value: boolean);
private _id;
private _name;
private _model;
private _status;
private _connectionStatus;
private _kernelSession;
private _clientId;
private _isDisposed;
/**
* Websocket to communicate with kernel.
*/
private _ws;
private _username;
private _reconnectLimit;
private _reconnectAttempt;
private _reconnectTimeout;
private _supportedProtocols;
private _selectedProtocol;
private _futures;
private _comms;
private _targetRegistry;
private _info;
private _pendingMessages;
private _specPromise;
private _statusChanged;
private _connectionStatusChanged;
private _disposed;
private _iopubMessage;
private _anyMessage;
private _pendingInput;
private _unhandledMessage;
private _displayIdToParentIds;
private _msgIdToDisplayIds;
private _msgChain;
private _hasPendingInput;
private _reason;
private _noOp;
}