repo_name
string
dataset
string
owner
string
lang
string
func_name
string
code
string
docstring
string
url
string
sha
string
libro
github_2023
weavefox
typescript
KernelConnection.requestExecute
requestExecute( content: KernelMessage.IExecuteRequestMsg['content'], disposeOnDone = true, metadata?: JSONObject, ): IShellFuture<KernelMessage.IExecuteRequestMsg, KernelMessage.IExecuteReplyMsg> { const defaults: JSONObject = { silent: false, store_history: true, user_expressions: {}, allow_stdin: true, stop_on_error: true, }; const msg = KernelMessage.createMessage({ msgType: 'execute_request', channel: 'shell', username: this._username, session: this._clientId, content: { ...defaults, ...content }, metadata, }); return this.sendShellMessage(msg, true, disposeOnDone) as IShellFuture< KernelMessage.IExecuteRequestMsg, KernelMessage.IExecuteReplyMsg >; }
/** * 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]] */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/kernel/kernel-connection.ts#L835-L859
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
KernelConnection.requestDebug
requestDebug( content: KernelMessage.IDebugRequestMsg['content'], disposeOnDone = true, ): IControlFuture<KernelMessage.IDebugRequestMsg, KernelMessage.IDebugReplyMsg> { const msg = KernelMessage.createMessage({ msgType: 'debug_request', channel: 'control', username: this._username, session: this._clientId, content, }); return this.sendControlMessage(msg, true, disposeOnDone) as IControlFuture< KernelMessage.IDebugRequestMsg, KernelMessage.IDebugReplyMsg >; }
/** * 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. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/kernel/kernel-connection.ts#L871-L886
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
KernelConnection.requestIsComplete
requestIsComplete( content: KernelMessage.IIsCompleteRequestMsg['content'], ): Promise<KernelMessage.IIsCompleteReplyMsg> { const msg = KernelMessage.createMessage({ msgType: 'is_complete_request', channel: 'shell', username: this._username, session: this._clientId, content, }); return Private.handleShellMessage( this, msg, ) as Promise<KernelMessage.IIsCompleteReplyMsg>; }
/** * 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. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/kernel/kernel-connection.ts#L897-L911
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
KernelConnection.requestCommInfo
requestCommInfo( content: KernelMessage.ICommInfoRequestMsg['content'], ): Promise<KernelMessage.ICommInfoReplyMsg> { const msg = KernelMessage.createMessage({ msgType: 'comm_info_request', channel: 'shell', username: this._username, session: this._clientId, content, }); return Private.handleShellMessage( this, msg, ) as Promise<KernelMessage.ICommInfoReplyMsg>; }
/** * Send a `comm_info_request` message. * * #### Notes * Fulfills with the `comm_info_reply` content when the shell reply is * received and validated. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/kernel/kernel-connection.ts#L920-L934
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
KernelConnection.sendInputReply
sendInputReply( content: KernelMessage.IInputReplyMsg['content'], parent_header: KernelMessage.IInputReplyMsg['parent_header'], ): void { const msg = KernelMessage.createMessage({ msgType: 'input_reply', channel: 'stdin', username: this._username, session: this._clientId, content, }); msg.parent_header = parent_header; this._sendMessage(msg); this.anyMessageEmitter.fire({ msg, direction: 'send' }); this.hasPendingInput = false; }
/** * 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). */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/kernel/kernel-connection.ts#L942-L959
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
KernelConnection.createComm
createComm(targetName: string, commId: string = v4()): IComm { if (!this.handleComms) { throw new Error('Comms are disabled on this kernel connection'); } if (this._comms.has(commId)) { throw new Error('Comm is already created'); } const comm = new CommHandler(targetName, commId, this, () => { this._unregisterComm(commId); }); this._comms.set(commId, comm); return comm; }
/** * 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. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/kernel/kernel-connection.ts#L968-L981
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
KernelConnection.hasComm
hasComm(commId: string): boolean { return this._comms.has(commId); }
/** * Check if a comm exists. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/kernel/kernel-connection.ts#L986-L988
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
KernelConnection.registerCommTarget
registerCommTarget( targetName: string, callback: ( comm: IComm, msg: KernelMessage.ICommOpenMsg, ) => void | PromiseLike<void>, ): void { if (!this.handleComms) { return; } this._targetRegistry[targetName] = callback; }
/** * 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. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/kernel/kernel-connection.ts#L1008-L1020
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
KernelConnection.removeCommTarget
removeCommTarget( targetName: string, callback: ( comm: IComm, msg: KernelMessage.ICommOpenMsg, ) => void | PromiseLike<void>, ): void { if (!this.handleComms) { return; } if (!this.isDisposed && this._targetRegistry[targetName] === callback) { delete this._targetRegistry[targetName]; } }
/** * 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. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/kernel/kernel-connection.ts#L1032-L1046
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
KernelConnection.registerMessageHook
registerMessageHook( msgId: string, hook: (msg: KernelMessage.IIOPubMessage) => boolean | PromiseLike<boolean>, ): Disposable { const future = this._futures?.get(msgId); if (future) { return future.registerMessageHook(hook); } return Disposable.NONE; }
/** * 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]]. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/kernel/kernel-connection.ts#L1071-L1080
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
KernelConnection.removeMessageHook
removeMessageHook( msgId: string, hook: (msg: KernelMessage.IIOPubMessage) => boolean | PromiseLike<boolean>, ): void { const future = this._futures?.get(msgId); if (future) { future.removeMessageHook(hook); } }
/** * Remove an IOPub message hook. * * @param msg_id - The parent_header message id the hook intercepted. * * @param hook - The callback invoked for the message. * */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/kernel/kernel-connection.ts#L1090-L1098
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
KernelConnection.removeInputGuard
removeInputGuard() { this.hasPendingInput = false; }
/** * Remove the input guard, if any. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/kernel/kernel-connection.ts#L1103-L1105
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
KernelConnection._handleDisplayId
protected async _handleDisplayId( displayId: string, msg: KernelMessage.IMessage, ): Promise<boolean> { const msgId = (msg.parent_header as KernelMessage.IHeader).msg_id; let parentIds = this._displayIdToParentIds.get(displayId); if (parentIds) { // We've seen it before, update existing outputs with same display_id // by handling display_data as update_display_data. const updateMsg: KernelMessage.IMessage = { header: deepCopy( msg.header as unknown as JSONObject, ) as unknown as KernelMessage.IHeader, parent_header: deepCopy( msg.parent_header as unknown as JSONObject, ) as unknown as KernelMessage.IHeader, metadata: deepCopy(msg.metadata), content: deepCopy(msg.content as JSONObject), channel: msg.channel, buffers: msg.buffers ? msg.buffers.slice() : [], }; (updateMsg.header as any).msg_type = 'update_display_data'; await Promise.all( parentIds.map(async (parentId) => { const future = this._futures && this._futures.get(parentId); if (future) { await future.handleMsg(updateMsg); } }), ); } // We're done here if it's update_display. if (msg.header.msg_type === 'update_display_data') { // It's an update, don't proceed to the normal display. return true; } // Regular display_data with id, record it for future updating // in _displayIdToParentIds for future lookup. parentIds = this._displayIdToParentIds.get(displayId) ?? []; if (parentIds.indexOf(msgId) === -1) { parentIds.push(msgId); } this._displayIdToParentIds.set(displayId, parentIds); // Add to our map of display ids for this message. const displayIds = this._msgIdToDisplayIds.get(msgId) ?? []; if (displayIds.indexOf(msgId) === -1) { displayIds.push(msgId); } this._msgIdToDisplayIds.set(msgId, displayIds); // Let the message propagate to the intended recipient. return false; }
/** * Handle a message with a display id. * * @returns Whether the message was handled. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/kernel/kernel-connection.ts#L1112-L1168
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
KernelConnection._createSocket
protected _clearSocket = (): void => { if (this._ws !== null) { // Clear the websocket event handlers and the socket itself. this._ws.onopen = this._noOp; this._ws.onclose = this._noOp; this._ws.onerror = this._noOp; this._ws.onmessage = this._noOp; this._ws.close(); this._ws = null; } }
/** * 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. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/kernel/kernel-connection.ts
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
KernelConnection._updateStatus
protected _updateStatus(status: KernelMessage.Status): void { if (this._status === status || this._status === 'dead') { return; } this._status = status; Private.logKernelStatus(this); this.statusChangedEmitter.fire(status); if (status === 'dead') { this.dispose(); } }
/** * Handle status iopub messages from the kernel. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/kernel/kernel-connection.ts#L1194-L1205
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
KernelConnection._sendPending
protected _sendPending(): void { // We check to make sure we are still connected each time. For // example, if a websocket buffer overflows, it may close, so we should // stop sending messages. while ( this.connectionStatus === 'connected' && this._kernelSession !== RESTARTING_KERNEL_SESSION && this._pendingMessages.length > 0 ) { this._sendMessage(this._pendingMessages[0], false); // We shift the message off the queue after the message is sent so that // if there is an exception, the message is still pending. this._pendingMessages.shift(); } }
/** * Send pending messages to the kernel. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/kernel/kernel-connection.ts#L1210-L1225
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
KernelConnection._clearKernelState
protected _clearKernelState(): void { this._kernelSession = ''; this._pendingMessages = []; this._futures.forEach((future) => { future.dispose(); }); this._comms.forEach((comm) => { comm.dispose(); }); this._msgChain = Promise.resolve(); this._futures = new Map< string, KernelFutureHandler< KernelMessage.IShellControlMessage, KernelMessage.IShellControlMessage > >(); this._comms = new Map<string, IComm>(); this._displayIdToParentIds.clear(); this._msgIdToDisplayIds.clear(); }
/** * Clear the internal state. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/kernel/kernel-connection.ts#L1230-L1250
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
KernelConnection._assertCurrentMessage
protected _assertCurrentMessage(msg: KernelMessage.IMessage) { this._errorIfDisposed(); if (msg.header.session !== this._kernelSession) { throw new Error(`Canceling handling of old message: ${msg.header.msg_type}`); } }
/** * 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. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/kernel/kernel-connection.ts#L1262-L1268
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
KernelConnection._handleCommOpen
protected async _handleCommOpen(msg: KernelMessage.ICommOpenMsg): Promise<void> { this._assertCurrentMessage(msg); const content = msg.content; const comm = new CommHandler(content.target_name, content.comm_id, this, () => { this._unregisterComm(content.comm_id); }); this._comms.set(content.comm_id, comm); try { const target = await Private.loadObject( content.target_name, content.target_module, this._targetRegistry, ); await target(comm, msg); } catch (e) { // Close the comm asynchronously. We cannot block message processing on // kernel messages to wait for another kernel message. comm.close(); console.error('Exception opening new comm', e); throw e; } }
/** * Handle a `comm_open` kernel message. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/kernel/kernel-connection.ts#L1273-L1295
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
KernelConnection._handleCommClose
protected async _handleCommClose(msg: KernelMessage.ICommCloseMsg): Promise<void> { this._assertCurrentMessage(msg); const content = msg.content; const comm = this._comms.get(content.comm_id); if (!comm) { console.error('Comm not found for comm id ' + content.comm_id); return; } this._unregisterComm(comm.commId); const onClose = comm.onClose; if (onClose) { // tslint:disable-next-line:await-promise await onClose(msg); } (comm as CommHandler).dispose(); }
/** * Handle 'comm_close' kernel message. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/kernel/kernel-connection.ts#L1300-L1315
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
KernelConnection._handleCommMsg
protected async _handleCommMsg(msg: KernelMessage.ICommMsgMsg): Promise<void> { this._assertCurrentMessage(msg); const content = msg.content; const comm = this._comms.get(content.comm_id); if (!comm) { return; } const onMsg = comm.onMsg; if (onMsg) { await onMsg(msg); } }
/** * Handle a 'comm_msg' kernel message. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/kernel/kernel-connection.ts#L1320-L1331
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
KernelConnection._unregisterComm
protected _unregisterComm(commId: string) { this._comms.delete(commId); }
/** * Unregister a comm instance. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/kernel/kernel-connection.ts#L1336-L1338
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
KernelConnection._updateConnectionStatus
protected _updateConnectionStatus(connectionStatus: ConnectionStatus): void { if (this._connectionStatus === connectionStatus) { return; } this._connectionStatus = connectionStatus; // If we are not 'connecting', reset any reconnection attempts. if (connectionStatus !== 'connecting') { this._reconnectAttempt = 0; clearTimeout(this._reconnectTimeout); } if (this.status !== 'dead') { if (connectionStatus === 'connected') { const restarting = this._kernelSession === RESTARTING_KERNEL_SESSION; // Send a kernel info request to make sure we send at least one // message to get kernel status back. Always request kernel info // first, to get kernel status back and ensure iopub is fully // established. If we are restarting, this message will skip the queue // and be sent immediately. const p = this.requestKernelInfo(); // Send any pending messages after the kernelInfo resolves, or after a // timeout as a failsafe. let sendPendingCalled = false; let timeoutHandle: any = null; const sendPendingOnce = () => { if (sendPendingCalled) { return; } sendPendingCalled = true; if (restarting && this._kernelSession === RESTARTING_KERNEL_SESSION) { // We were restarting and a message didn't arrive to set the // session, but we just assume the restart succeeded and send any // pending messages. // FIXME: it would be better to retry the kernel_info_request here this._kernelSession = ''; } if (timeoutHandle) { clearTimeout(timeoutHandle); } if (this._pendingMessages.length > 0) { this._sendPending(); } }; void p.then(sendPendingOnce); // FIXME: if sent while zmq subscriptions are not established, // kernelInfo may not resolve, so use a timeout to ensure we don't hang forever. // It may be preferable to retry kernelInfo rather than give up after one timeout. timeoutHandle = setTimeout(sendPendingOnce, KERNEL_INFO_TIMEOUT); } else { // If the connection is down, then we do not know what is happening // with the kernel, so set the status to unknown. this._updateStatus('unknown'); } } // Notify others that the connection status changed. this.connectionStatusChangedEmitter.fire(connectionStatus); }
/** * Handle connection status changes. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/kernel/kernel-connection.ts#L1449-L1512
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
KernelConnection._reconnect
protected _reconnect() { this._errorIfDisposed(); // Clear any existing reconnection attempt clearTimeout(this._reconnectTimeout); // Update the connection status and schedule a possible reconnection. if (this._reconnectAttempt < this._reconnectLimit) { this._updateConnectionStatus('connecting'); // The first reconnect attempt should happen immediately, and subsequent // attempts should pick a random number in a growing range so that we // don't overload the server with synchronized reconnection attempts // across multiple kernels. const timeout = Private.getRandomIntInclusive( 0, 1e3 * (Math.pow(2, this._reconnectAttempt) - 1), ); console.warn( `Connection lost, reconnecting in ${Math.floor(timeout / 1000)} seconds.`, ); // Try reconnection with subprotocols if the server had supported them. // Otherwise, try reconnection without subprotocols. const useProtocols = this._selectedProtocol !== '' ? true : false; this._reconnectTimeout = setTimeout(this._createSocket, timeout, useProtocols); this._reconnectAttempt += 1; } else { this._updateConnectionStatus('disconnected'); } // Clear the websocket event handlers and the socket itself. this._clearSocket(); }
/** * Attempt a connection if we have not exhausted connection attempts. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/kernel/kernel-connection.ts#L1605-L1637
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
KernelConnection._errorIfDisposed
protected _errorIfDisposed() { if (this.isDisposed) { throw new Error('Kernel connection is disposed'); } }
/** * Utility function to throw an error if this instance is disposed. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/kernel/kernel-connection.ts#L1642-L1646
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
LibroKernelManager.isReady
get isReady(): boolean { return this._isReady; }
/** * Test whether the manager is ready. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/kernel/libro-kernel-manager.ts#L90-L92
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
LibroKernelManager.ready
get ready(): Promise<void> { return this._ready; }
/** * A promise that fulfills when the manager is ready. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/kernel/libro-kernel-manager.ts#L97-L99
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
LibroKernelManager.startNew
async startNew( createOptions: IKernelOptions = {}, connectOptions: Omit<KernelConnectionOptions, 'model' | 'serverSettings'> = {}, ): Promise<IKernelConnection> { const model = await this.kernelRestAPI.startNew(createOptions); return this.connectToKernel({ ...connectOptions, model, }); }
/** * Start a new kernel. * * @param createOptions - The kernel creation options * * @param connectOptions - The kernel connection options * * @returns A promise that resolves with the kernel connection. * * #### Notes * The manager `serverSettings` will be always be used. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/kernel/libro-kernel-manager.ts#L113-L122
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
LibroKernelManager.runningChanged
get runningChanged(): ManaEvent<IKernelModel[]> { return this.runningChangedEmitter.event; }
/** * A signal emitted when the running kernels change. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/kernel/libro-kernel-manager.ts#L127-L129
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
LibroKernelManager.connectionFailure
get connectionFailure(): ManaEvent<Error> { return this.connectionFailureEmmiter.event; }
/** * A signal emitted when there is a connection failure. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/kernel/libro-kernel-manager.ts#L134-L136
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
LibroKernelManager.shutdown
async shutdown(id: string): Promise<void> { await this.kernelRestAPI.shutdownKernel(id); await this.refreshRunning(); }
/** * Shut down a kernel by id. * * @param id - The id of the target kernel. * * @returns A promise that resolves when the operation is complete. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/kernel/libro-kernel-manager.ts#L145-L148
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
LibroKernelManager.shutdownAll
async shutdownAll(): Promise<void> { // Update the list of models to make sure our list is current. await this.refreshRunning(); // Shut down all models. await Promise.all( [...this._models.keys()].map((id) => this.kernelRestAPI.shutdownKernel(id)), ); // Update the list of models to clear out our state. await this.refreshRunning(); }
/** * Shut down all kernels. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/kernel/libro-kernel-manager.ts#L153-L164
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
LibroKernelManager.isKernelAlive
async isKernelAlive(id: string): Promise<boolean> { try { const data = await this.kernelRestAPI.getKernelModel(id); return !!data; } catch { return false; } }
// 通过kernel id判断kernel是否仍然存在
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/kernel/libro-kernel-manager.ts#L174-L181
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
LibroKernelManager.refreshRunning
async refreshRunning(): Promise<void> { await getOrigin(this._pollModels).refresh(); await getOrigin(this._pollModels).tick; }
/** * Force a refresh of the running kernels. * * @returns A promise that resolves when the running list has been refreshed. * * #### Notes * This is not typically meant to be called by the user, since the * manager maintains its own internal state. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/kernel/libro-kernel-manager.ts#L220-L223
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
LibroKernelManager.requestRunning
protected async requestRunning(): Promise<void> { let models: KernelMeta[]; try { models = await this.kernelRestAPI.listRunning(); } catch (err: any) { // Handle network errors, as well as cases where we are on a // JupyterHub and the server is not running. JupyterHub returns a // 503 (<2.0) or 424 (>2.0) in that case. if ( err instanceof NetworkError || err.response?.status === 503 || err.response?.status === 424 ) { this.connectionFailureEmmiter.fire(err); } throw err; } if ( this._models.size === models.length && models.every((model) => { const existing = this._models.get(model.id); if (!existing) { return false; } return ( existing.connections === model.connections && existing.execution_state === model.execution_state && existing.last_activity === model.last_activity && existing.name === model.name && existing.reason === model.reason && existing.traceback === model.traceback ); }) ) { // Identical models list (presuming models does not contain duplicate // ids), so just return return; } this._models = new Map(models.map((x) => [x.id, x])); }
/** * Execute a request to the server to poll running kernels and update state. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/kernel/libro-kernel-manager.ts#L231-L273
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
KernelError.constructor
constructor(content: KernelMessage.IExecuteReplyMsg['content']) { const errorContent = content as KernelMessage.IReplyErrorContent; const errorName = errorContent.ename; const errorValue = errorContent.evalue; super(`KernelReplyNotOK: ${errorName} ${errorValue}`); this.errorName = errorName; this.errorValue = errorValue; this.traceback = errorContent.traceback; Object.setPrototypeOf(this, KernelError.prototype); }
/** * Construct the kernel error. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/kernel/libro-kernel-protocol.ts#L73-L83
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
KernelRestAPI.getKernelModel
async getKernelModel( id: string, serverSettings?: Partial<ISettings>, ): Promise<IKernelModel | undefined> { const settings = { ...this.serverConnection.settings, ...serverSettings }; const url = URL.join(settings.baseUrl, KERNEL_SERVICE_URL, encodeURIComponent(id)); const response = await this.serverConnection.makeRequest(url, {}, settings); if (response.status === 404) { return undefined; } else if (response.status !== 200) { const err = await createResponseError(response); throw err; } const data = await response.json(); validateModel(data); return data; }
/** * Get a full kernel model from the server by kernel id string. * * #### Notes * Uses the [Jupyter Notebook API](http://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter/notebook/master/notebook/services/api/api.yaml#!/kernels) and validates the response model. * * The promise is fulfilled on a valid response and rejected otherwise. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/kernel/restapi.ts#L24-L41
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
KernelRestAPI.startNew
async startNew( options: IKernelOptions = {}, serverSettings?: Partial<ISettings>, ): Promise<IKernelModel> { const settings = { ...this.serverConnection.settings, ...serverSettings }; const url = URL.join(settings.baseUrl, KERNEL_SERVICE_URL); const init = { method: 'POST', body: JSON.stringify(options), }; const response = await this.serverConnection.makeRequest(url, init, settings); if (response.status !== 201) { const err = await createResponseError(response); throw err; } const data = await response.json(); validateModel(data); return data; }
/** * Start a new kernel. * * @param options - The options used to create the kernel. * * @returns A promise that resolves with a kernel connection object. * * #### Notes * Uses the [Jupyter Notebook API](http://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter/notebook/master/notebook/services/api/api.yaml#!/kernels) and validates the response model. * * The promise is fulfilled on a valid response and rejected otherwise. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/kernel/restapi.ts#L55-L73
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
KernelRestAPI.listRunning
async listRunning(serverSettings?: Partial<ISettings>): Promise<KernelMeta[]> { const settings = { ...this.serverConnection.settings, ...serverSettings }; const url = URL.join(settings.baseUrl, KERNEL_SERVICE_URL); const response = await this.serverConnection.makeRequest(url, {}, settings); if (response.status !== 200) { const err = await createResponseError(response); throw err; } const data = await response.json(); validateModels(data); return data; }
/** * Fetch the running kernels. * * @param settings - The optional server settings. * * @returns A promise that resolves with the list of running kernels. * * #### Notes * Uses the [Jupyter Notebook API](http://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter/notebook/master/notebook/services/api/api.yaml#!/kernels) and validates the response model. * * The promise is fulfilled on a valid response and rejected otherwise. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/kernel/restapi.ts#L87-L98
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
KernelRestAPI.shutdownKernel
async shutdownKernel(id: string, serverSettings?: Partial<ISettings>): Promise<void> { const settings = { ...this.serverConnection.settings, ...serverSettings }; const url = URL.join(settings.baseUrl, KERNEL_SERVICE_URL, encodeURIComponent(id)); const init = { method: 'DELETE' }; const response = await this.serverConnection.makeRequest(url, init, settings); if (response.status === 404) { const msg = `The kernel "${id}" does not exist on the server`; console.warn(msg); } else if (response.status !== 204) { const err = await createResponseError(response); throw err; } }
/** * Shut down a kernel. * * @param id - The id of the running kernel. * * @param settings - The server settings for the request. * * @returns A promise that resolves when the kernel is shut down. * * * #### Notes * Uses the [Jupyter Notebook API](http://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter/notebook/master/notebook/services/api/api.yaml#!/kernels) and validates the response model. * * The promise is fulfilled on a valid response and rejected otherwise. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/kernel/restapi.ts#L115-L127
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
KernelRestAPI.restartKernel
async restartKernel(id: string, serverSettings?: Partial<ISettings>): Promise<void> { const settings = { ...this.serverConnection.settings, ...serverSettings }; const url = URL.join( settings.baseUrl, KERNEL_SERVICE_URL, encodeURIComponent(id), 'restart', ); const init = { method: 'POST' }; const response = await this.serverConnection.makeRequest(url, init, settings); if (response.status !== 200) { const err = await createResponseError(response); throw err; } const data = await response.json(); validateModel(data); }
/** * Restart a kernel. * * #### Notes * Uses the [Jupyter Notebook API](http://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter/notebook/master/notebook/services/api/api.yaml#!/kernels) and validates the response model. * * The promise is fulfilled on a valid response (and thus after a restart) and rejected otherwise. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/kernel/restapi.ts#L137-L154
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
KernelRestAPI.interruptKernel
async interruptKernel( id: string, serverSettings?: Partial<ISettings>, ): Promise<void> { const settings = { ...this.serverConnection.settings, ...serverSettings }; const url = URL.join( settings.baseUrl, KERNEL_SERVICE_URL, encodeURIComponent(id), 'interrupt', ); const init = { method: 'POST' }; const response = await this.serverConnection.makeRequest(url, init, settings); if (response.status !== 204) { const err = await createResponseError(response); throw err; } }
/** * Interrupt a kernel. * * #### Notes * Uses the [Jupyter Notebook API](http://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter/notebook/master/notebook/services/api/api.yaml#!/kernels) and validates the response model. * * The promise is fulfilled on a valid response and rejected otherwise. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/kernel/restapi.ts#L164-L181
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
deserializeBinary
function deserializeBinary(buf: ArrayBuffer): KernelMessage.IMessage { const data = new DataView(buf); // read the header: 1 + nbufs 32b integers const nbufs = data.getUint32(0); const offsets: number[] = []; if (nbufs < 2) { throw new Error('Invalid incoming Kernel Message'); } for (let i = 1; i <= nbufs; i++) { offsets.push(data.getUint32(i * 4)); } const jsonBytes = new Uint8Array(buf.slice(offsets[0], offsets[1])); const msg = JSON.parse(new TextDecoder('utf8').decode(jsonBytes)); // the remaining chunks are stored as DataViews in msg.buffers msg.buffers = []; for (let i = 1; i < nbufs; i++) { const start = offsets[i]; const stop = offsets[i + 1] || buf.byteLength; msg.buffers.push(new DataView(buf.slice(start, stop))); } return msg; }
/** * Deserialize a binary message to a Kernel Message. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/kernel/serialize.ts#L196-L217
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
serializeBinary
function serializeBinary(msg: KernelMessage.IMessage): ArrayBuffer { const offsets: number[] = []; const buffers: ArrayBuffer[] = []; const encoder = new TextEncoder(); let origBuffers: (ArrayBuffer | ArrayBufferView)[] = []; if (msg.buffers !== undefined) { origBuffers = msg.buffers; delete msg.buffers; } const jsonUtf8 = encoder.encode(JSON.stringify(msg)); buffers.push(jsonUtf8.buffer); for (let i = 0; i < origBuffers.length; i++) { // msg.buffers elements could be either views or ArrayBuffers // buffers elements are ArrayBuffers const b: any = origBuffers[i]; buffers.push(ArrayBuffer.isView(b) ? b.buffer : b); } const nbufs = buffers.length; offsets.push(4 * (nbufs + 1)); for (let i = 0; i + 1 < buffers.length; i++) { offsets.push(offsets[offsets.length - 1] + buffers[i].byteLength); } const msgBuf = new Uint8Array( offsets[offsets.length - 1] + buffers[buffers.length - 1].byteLength, ); // use DataView.setUint32 for network byte-order const view = new DataView(msgBuf.buffer); // write nbufs to first 4 bytes view.setUint32(0, nbufs); // write offsets to next 4 * nbufs bytes for (let i = 0; i < offsets.length; i++) { view.setUint32(4 * (i + 1), offsets[i]); } // write all the buffers at their respective offsets for (let i = 0; i < buffers.length; i++) { msgBuf.set(new Uint8Array(buffers[i]), offsets[i]); } return msgBuf.buffer; }
/** * Implement the binary serialization protocol. * * Serialize Kernel message to ArrayBuffer. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/kernel/serialize.ts#L224-L262
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
validateHeader
function validateHeader( header: KernelMessage.IHeader, ): asserts header is KernelMessage.IHeader { for (let i = 0; i < HEADER_FIELDS.length; i++) { validateProperty(header, HEADER_FIELDS[i], 'string'); } }
/** * Validate the header of a kernel message. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/kernel/validate.ts#L38-L44
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
validateIOPubContent
function validateIOPubContent( msg: KernelMessage.IIOPubMessage, ): asserts msg is KernelMessage.IIOPubMessage { if (msg.channel === 'iopub') { const fields = IOPUB_CONTENT_FIELDS[msg.header.msg_type]; // Check for unknown message type. if (fields === undefined) { return; } const names = Object.keys(fields); const content = msg.content; for (let i = 0; i < names.length; i++) { let args = fields[names[i]]; if (!Array.isArray(args)) { args = [args]; } validateProperty(content, names[i], ...args); } } }
/** * Validate content an kernel message on the iopub channel. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/kernel/validate.ts#L64-L83
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
KernelSpecManager.constructor
constructor(@inject(ServerManager) serverManager: ServerManager) { super(); this.serverManager = serverManager; this._pollSpecs = new Poll({ auto: false, factory: () => this.requestSpecs(), frequency: { interval: 61 * 1000, backoff: true, max: 300 * 1000, }, name: `@jupyterlab/services:KernelSpecManager#specs`, standby: 'when-hidden', // standby: options.standby ?? 'when-hidden', }); // Initialize internal data. this._ready = (async () => { await this.serverManager.ready; await getOrigin(this._pollSpecs).start(); await getOrigin(this._pollSpecs).tick; this._isReady = true; })(); }
/** * Construct a new kernel spec manager. * * @param options - The default options for kernel. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/kernelspec/manager.ts#L29-L51
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
KernelSpecManager.specsReady
get specsReady() { return this.specsDeferred.promise; }
// }
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/kernelspec/manager.ts#L72-L74
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
KernelSpecManager.specs
get specs(): ISpecModels | null { return this._specs; }
/** * Get the most recently fetched kernel specs. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/kernelspec/manager.ts#L79-L81
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
KernelSpecManager.specsChanged
get specsChanged(): ManaEvent<ISpecModels> { return this.specsChangedEmitter.event; }
/** * A signal emitted when the specs change. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/kernelspec/manager.ts#L86-L88
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
KernelSpecManager.connectionFailure
override get connectionFailure(): ManaEvent<Error> { return this.connectionFailureEmitter.event; }
/** * A signal emitted when there is a connection failure. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/kernelspec/manager.ts#L93-L95
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
KernelSpecManager.dispose
override dispose(): void { this._pollSpecs.dispose(); super.dispose(); }
/** * Dispose of the resources used by the manager. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/kernelspec/manager.ts#L100-L103
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
KernelSpecManager.refreshSpecs
async refreshSpecs(): Promise<void> { await this._pollSpecs.refresh(); await this._pollSpecs.tick; }
/** * Force a refresh of the specs from the server. * * @returns A promise that resolves when the specs are fetched. * * #### Notes * This is intended to be called only in response to a user action, * since the manager maintains its internal state. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/kernelspec/manager.ts#L114-L117
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
KernelSpecManager.requestSpecs
protected async requestSpecs(): Promise<void> { const specs = await this.kernelSpecRestAPI.getSpecs(this.serverSettings); if (specs) { this.specsDeferred.resolve(specs); } if (this.isDisposed) { return; } if (!this._specs || !deepEqual(specs, this._specs)) { this._specs = specs; this.specsChangedEmitter.fire(specs); } }
/** * Execute a request to the server to poll specs and update state. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/kernelspec/manager.ts#L122-L135
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
KernelSpecRestAPI.getSpecs
async getSpecs(serverSettings?: Partial<ISettings>): Promise<ISpecModels> { const settings = { ...this.serverConnection.settings, ...serverSettings }; const url = settings.baseUrl + KERNELSPEC_SERVICE_URL; // TODO: 当前URL.join 方法是坏的 // const url = URL.join(settings.baseUrl, KERNELSPEC_SERVICE_URL); const response = await this.serverConnection.makeRequest(url, {}, settings); if (response.status !== 200) { const err = await createResponseError(response); throw err; } const data = await response.json(); return validateSpecModels(data); }
/** * Fetch all of the kernel specs. * * @param settings - The optional server settings. * @param useCache - Whether to use the cache. If false, always request. * * @returns A promise that resolves with the kernel specs. * * #### Notes * Uses the [Jupyter Notebook API](http://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter/notebook/master/notebook/services/api/api.yaml#!/kernelspecs). */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/kernelspec/restapi.ts#L29-L42
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
JupyterResponseError.constructor
constructor( response: Response, message = `The response is invalid: ${response.status} ${response.statusText}`, traceback = '', ) { super(message); this.response = response; this.traceback = traceback; }
/** * Create a new response error. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/server/connection-error.ts#L17-L25
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
NetworkError.constructor
constructor(original: TypeError) { super(original.message); this.stack = original.stack; }
/** * Create a new network error. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/server/connection-error.ts#L35-L38
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
ServerConnection.makeRequest
makeRequest( baseUrl: string, init: RequestInit, settings: ISettings = this.settings, ): Promise<Response> { let url = baseUrl; // Handle notebook server requests. if (url.indexOf(settings.baseUrl) !== 0) { throw new Error('Can only be used for notebook server requests'); } // Use explicit cache buster when `no-store` is set since // not all browsers use it properly. const cache = init.cache ?? settings.init.cache; if (cache === 'no-store') { // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Bypassing_the_cache url += (/\?/.test(url) ? '&' : '?') + new Date().getTime(); } const request = new settings.Request(url, { ...settings.init, ...init }); // Handle authentication. Authentication can be overdetermined by // settings token and XSRF token. let authenticated = false; if (settings.token) { authenticated = true; request.headers.append('Authorization', `token ${settings.token}`); } if (typeof document !== 'undefined' && document?.cookie) { const xsrfToken = this.getCookie('_xsrf'); if (xsrfToken !== undefined) { authenticated = true; request.headers.append('X-XSRFToken', xsrfToken); } } // Set the content type if there is no given data and we are // using an authenticated connection. if (!request.headers.has('Content-Type') && authenticated) { request.headers.set('Content-Type', 'application/json'); } // Use `call` to avoid a `TypeError` in the browser. return settings.fetch.call(null, request).catch((e: TypeError) => { // Convert the TypeError into a more specific error. throw new NetworkError(e); }); // TODO: *this* is probably where we need a system-wide connectionFailure // signal we can hook into. }
/** * Handle a request. * * @param url - The url for the request. * * @param init - The overrides for the request init. * * @param settings - The settings object for the request. * * #### Notes * The `url` must start with `settings.baseUrl`. The `init` settings * take precedence over `settings.init`. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/server/server-connection.ts#L85-L134
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
ServerConnection.getCookie
getCookie(name: string): string | undefined { // From http://www.tornadoweb.org/en/stable/guide/security.html const matches = document.cookie.match('\\b' + name + '=([^;]*)\\b'); return matches?.[1]; }
/** * Get a cookie from the document. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/server/server-connection.ts#L139-L143
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
LibroSessionManager.running
get running(): Map<string, SessionIModel> { return this._models; }
// sessionId -> kernelConnection
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/session/libro-session-manager.ts#L61-L63
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
LibroSessionManager.requestRunning
protected async requestRunning(): Promise<void> { let models: SessionMeta[]; try { // eslint-disable-next-line @typescript-eslint/no-unused-vars models = await this.sessionRestAPI.listRunning(this.serverSettings); } catch (err: any) { // Handle network errors, as well as cases where we are on a // JupyterHub and the server is not running. JupyterHub returns a // 503 (<2.0) or 424 (>2.0) in that case. if ( err instanceof NetworkError || err.response?.status === 503 || err.response?.status === 424 ) { this._connectionFailure.fire(err); } throw err; } if ( this._models.size === models.length && models.every((model) => { const existing = this._models.get(model.id); if (!existing) { return false; } return ( existing.kernel?.id === model.kernel?.id && existing.kernel?.name === model.kernel?.name && existing.name === model.name && existing.path === model.path && existing.type === model.type ); }) ) { // Identical models list (presuming models does not contain duplicate // ids), so just return return; } this._models = new Map(models.map((x) => [x.id, x])); for (const [sessionId, kc] of this._sessionConnections) { if (!this._models.has(sessionId)) { let filePersistKey = ''; this.sessionIdMap.forEach((id, pk) => { if (id === sessionId) { filePersistKey = pk; return; } }); await this.storageService.setData(filePersistKey, undefined); kc.dispose(); this.sessionIdMap.delete(filePersistKey); } } }
/** * Execute a request to the server to poll running kernels and update state. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/session/libro-session-manager.ts#L109-L166
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
LibroSessionManager.connectionFailure
get connectionFailure(): Event<Error> { return this._connectionFailure.event; }
/** * A signal emitted when there is a connection failure. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/session/libro-session-manager.ts#L173-L175
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
LibroSessionManager.refreshRunning
async refreshRunning(): Promise<void> { await getOrigin(this._pollModels).refresh(); await getOrigin(this._pollModels).tick; }
/** * Force a refresh of the running sessions. * * @returns A promise that with the list of running sessions. * * #### Notes * This is not typically meant to be called by the user, since the * manager maintains its own internal state. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/session/libro-session-manager.ts#L318-L321
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
LibroSessionManager._patch
protected async _patch( body: DeepPartial<SessionIModel>, sessionId?: string, ): Promise<SessionIModel> { // TODO: 复用session const model = await this.sessionRestAPI.updateSession( { ...body, id: sessionId ?? '' }, this.serverSettings, ); // this.update(model); return model; }
/** * Send a PATCH to the server, updating the session path or the kernel. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/session/libro-session-manager.ts#L326-L337
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
LibroSessionManager.changeKernel
async changeKernel( fileInfo: IContentsModel, options: Partial<IKernelModel>, ): Promise<IKernelConnection | null> { let reuseSessionId = this.sessionIdMap.get(this.persistKey(fileInfo)); // shutdown 过后 if (!reuseSessionId) { const newSession = await this.sessionRestAPI.startSession( { name: fileInfo.name, kernel: { kernelName: options.name || fileInfo.content?.metadata?.kernelspec.name, }, path: fileInfo.path, type: fileInfo.type, } as ISessionOptions, this.serverSettings, ); await this.refreshRunning(); if (!newSession || !newSession.kernel) { return null; } reuseSessionId = newSession.id; this.sessionIdMap.set(this.persistKey(fileInfo), reuseSessionId!); } const model = await this._patch({ kernel: options } as any, reuseSessionId); if (!model || !model.kernel) { return null; } const optionsForConnectKernel = { model: { id: model.kernel.id, name: model.kernel.name, }, } as KernelConnectionOptions; await this.storageService.setData( this.persistKey(fileInfo), JSON.stringify({ sessionId: reuseSessionId, options: optionsForConnectKernel, } as PersistSessionMessage), ); const kernelConnection = await this.kernelManager.connectToKernel({ ...optionsForConnectKernel, serverSettings: this.serverSettings, }); this._sessionConnections.set(reuseSessionId!, kernelConnection); return kernelConnection; }
/** * Change the kernel. * * @param options - The name or id of the new kernel. * * #### Notes * This shuts down the existing kernel and creates a new kernel, * keeping the existing session ID and session path. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/session/libro-session-manager.ts#L348-L405
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
SessionRestAPI.startSession
async startSession( options: ISessionOptions, serverSettings?: Partial<ISettings>, ): Promise<SessionIModel> { const settings = { ...this.serverConnection.settings, ...serverSettings }; const url = URL.join(settings.baseUrl, SESSION_SERVICE_URL); const init = { method: 'POST', body: JSON.stringify(options), }; const response = await this.serverConnection.makeRequest(url, init, settings); if (response.status !== 201) { const err = await createResponseError(response); throw err; } const data = await response.json(); updateLegacySessionModel(data); validateModel(data); return data; }
/** * Create a new session, or return an existing session if the session path * already exists. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/session/restapi.ts#L58-L78
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
SessionRestAPI.listRunning
async listRunning(serverSettings?: Partial<ISettings>): Promise<SessionMeta[]> { const settings = { ...this.serverConnection.settings, ...serverSettings }; const url = URL.join(settings.baseUrl, SESSION_SERVICE_URL); const response = await this.serverConnection.makeRequest(url, {}, settings); if (response.status !== 200) { const err = await createResponseError(response); throw err; } const data = await response.json(); if (!Array.isArray(data)) { throw new Error('Invalid Session list'); } data.forEach((m) => { updateLegacySessionModel(m); validateModel(m); }); return data; }
/** * List the running sessions. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/session/restapi.ts#L83-L101
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
SessionRestAPI.updateSession
async updateSession( model: Pick<SessionIModel, 'id'> & DeepPartial<Omit<SessionIModel, 'id'>>, serverSettings?: Partial<ISettings>, ): Promise<SessionIModel> { const settings = { ...this.serverConnection.settings, ...serverSettings }; const url = getSessionUrl(settings.baseUrl, model.id); const init = { method: 'PATCH', body: JSON.stringify(model), }; const response = await this.serverConnection.makeRequest(url, init, settings); if (response.status !== 200) { const err = await createResponseError(response); throw err; } const data = await response.json(); updateLegacySessionModel(data); validateModel(data); return data; }
/** * Send a PATCH to the server, updating the session path or the kernel. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-kernel/src/session/restapi.ts#L106-L125
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
CodeEditorViewerOpenHandler.canHandle
canHandle(uri: URI, options?: ViewOpenHandlerOptions) { if (uri.scheme === 'file' && textFileTypes.includes(uri.path.ext.toLowerCase())) { return 100; } return Priority.IDLE; }
// TODO: 支持打开的文件扩展
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-lab/src/editor-viewer/code-editor-open-handler.ts#L21-L26
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
ImageViewerOpenHandler.canHandle
canHandle(uri: URI, _options?: ViewOpenHandlerOptions) { if (uri.scheme === 'file') { const ext = uri.path.ext; if (imageExtToTypes.has(ext.toLowerCase())) { return 100; } } return Priority.IDLE; }
// eslint-disable-next-line @typescript-eslint/no-unused-vars
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-lab/src/image-viewer/open-handler.ts#L22-L30
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
isLocationLink
function isLocationLink(object: any): object is LocationLink { return ( object !== undefined && 'targetUri' in object && 'targetRange' in object && 'targetSelectionRange' in object ); }
// Function to check if an object is a LocationLink
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-language-client/src/common/codeConverter.ts#L676-L683
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
equals
function equals( one: NotebookCell, other: NotebookCell, compareMetaData = true, ): boolean { if ( one.kind !== other.kind || one.document.uri.toString() !== other.document.uri.toString() || one.document.languageId !== other.document.languageId || !equalsExecution(one.executionSummary, other.executionSummary) ) { return false; } return ( !compareMetaData || (compareMetaData && equalsMetadata(one.metadata, other.metadata)) ); }
/** * We only sync kind, document, execution and metadata to the server. So we only need to compare those. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-language-client/src/common/notebook.ts#L291-L308
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
asTextDcouemnt
function asTextDcouemnt(value: ls.TextDocumentIdentifier): TextDocument { return { uri: URI.parse(value.uri), } as TextDocument; }
// new
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-language-client/src/common/protocolConverter.ts#L2554-L2558
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
WorkspaceEdit.renameFile
renameFile( from: vscode.Uri, to: vscode.Uri, options?: { readonly overwrite?: boolean; readonly ignoreIfExists?: boolean }, metadata?: vscode.WorkspaceEditEntryMetadata, ): void { this._edits.push({ _type: FileEditType.File, from, to, options, metadata }); }
// --- file
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-language-client/src/common/vscodeAdaptor/extHostTypes.ts#L809-L816
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
WorkspaceEdit.replaceNotebookMetadata
private replaceNotebookMetadata( uri: URI, value: Record<string, any>, metadata?: vscode.WorkspaceEditEntryMetadata, ): void { this._edits.push({ _type: FileEditType.Cell, metadata, uri, edit: { editType: CellEditType.DocumentMetadata, metadata: value }, notebookMetadata: value, }); }
// --- notebook
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-language-client/src/common/vscodeAdaptor/extHostTypes.ts#L852-L864
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
WorkspaceEdit.replace
replace( uri: URI, range: Range, newText: string, metadata?: vscode.WorkspaceEditEntryMetadata, ): void { this._edits.push({ _type: FileEditType.Text, uri, edit: new TextEdit(range, newText), metadata, }); }
// --- text
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-language-client/src/common/vscodeAdaptor/extHostTypes.ts#L903-L915
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
WorkspaceEdit.has
has(uri: URI): boolean { return this._edits.some( (edit) => edit._type === FileEditType.Text && edit.uri.toString() === uri.toString(), ); }
// --- text (Maplike)
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-language-client/src/common/vscodeAdaptor/extHostTypes.ts#L936-L941
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
DocumentConnectionManager.connection
protected async connection( language: string, languageServerId: TLanguageServerId, uris: IURIs, onCreate: (connection: LSPConnection) => void, capabilities: LspClientCapabilities, ): Promise<LSPConnection> { let connection = this._connections.get(languageServerId); if (!connection) { const socket = new WebSocket(uris.socket); const connection = this.lspConnectionFactory({ languageId: language, serverUri: uris.server, rootUri: uris.base, serverIdentifier: languageServerId, capabilities: capabilities, }); this._connections.set(languageServerId, connection); connection.connect(socket); onCreate(connection); } connection = this._connections.get(languageServerId)!; return connection; }
/** * Return (or create and initialize) the WebSocket associated with the language */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-lsp/src/connection-manager.ts#L82-L109
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
DocumentConnectionManager.initialized
get initialized(): Event<IDocumentConnectionData> { return this._initialized.event; }
/** * Signal emitted when the manager is initialized. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-lsp/src/connection-manager.ts#L149-L151
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
DocumentConnectionManager.connected
get connected(): Event<IDocumentConnectionData> { return this._connected.event; }
/** * Signal emitted when the manager is connected to the server */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-lsp/src/connection-manager.ts#L156-L158
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
DocumentConnectionManager.disconnected
get disconnected(): Event<IDocumentConnectionData> { return this._disconnected.event; }
/** * Connection temporarily lost or could not be fully established; a re-connection will be attempted; */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-lsp/src/connection-manager.ts#L163-L165
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
DocumentConnectionManager.closed
get closed(): Event<IDocumentConnectionData> { return this._closed.event; }
/** * Connection was closed permanently and no-reconnection will be attempted, e.g.: * - there was a serious server error * - user closed the connection, * - re-connection attempts exceeded, */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-lsp/src/connection-manager.ts#L173-L175
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
DocumentConnectionManager.documentsChanged
get documentsChanged(): Event<Map<VirtualDocument.uri, VirtualDocument>> { return this._documentsChanged.event; }
/** * Signal emitted when the document is changed. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-lsp/src/connection-manager.ts#L180-L182
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
DocumentConnectionManager.ready
get ready(): Promise<void> { return this.languageServerManager.ready; }
/** * Promise resolved when the language server manager is ready. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-lsp/src/connection-manager.ts#L187-L189
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
DocumentConnectionManager.solveUris
solveUris(virtualDocument: VirtualDocument, language: string): IURIs | undefined { const wsBase = PageConfig.getBaseUrl().replace(/^http/, 'ws'); const rootUri = PageConfig.getOption('rootUri'); const virtualDocumentsUri = PageConfig.getOption('virtualDocumentsUri'); const baseUri = virtualDocument.hasLspSupportedFile ? rootUri : virtualDocumentsUri; // for now take the best match only const matchingServers = this.languageServerManager.getMatchingServers({ language, }); const languageServerId = matchingServers.length === 0 ? null : matchingServers[0]; if (languageServerId === null) { return; } // workaround url-parse bug(s) (see https://github.com/jupyter-lsp/jupyterlab-lsp/issues/595) let documentUri = URL.join(baseUri, virtualDocument.uri); if (!documentUri.startsWith('file:///') && documentUri.startsWith('file://')) { documentUri = documentUri.replace('file://', 'file:///'); if ( documentUri.startsWith('file:///users/') && baseUri.startsWith('file:///Users/') ) { documentUri = documentUri.replace('file:///users/', 'file:///Users/'); } } return { base: baseUri, document: documentUri, server: URL.join('ws://jupyter-lsp', language), socket: URL.join(wsBase, 'lsp', 'ws', languageServerId), }; }
/** * Generate the URI of a virtual document from input * * @param virtualDocument - the virtual document * @param language - language of the document */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-lsp/src/connection-manager.ts#L197-L232
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
DocumentConnectionManager.connectDocumentSignals
connectDocumentSignals(virtualDocument: VirtualDocument): void { virtualDocument.foreignDocumentOpened(this.onForeignDocumentOpened, this); virtualDocument.foreignDocumentClosed(this.onForeignDocumentClosed, this); this.documents.set(virtualDocument.uri, virtualDocument); this._documentsChanged.fire(this.documents); }
/** * Helper to connect various virtual document signal with callbacks of * this class. * * @param virtualDocument - virtual document to be connected. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-lsp/src/connection-manager.ts#L240-L246
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
DocumentConnectionManager.disconnectDocumentSignals
disconnectDocumentSignals(virtualDocument: VirtualDocument, emit = true): void { this.documents.delete(virtualDocument.uri); for (const foreign of virtualDocument.foreignDocuments.values()) { this.disconnectDocumentSignals(foreign, false); } if (emit) { this._documentsChanged.fire(this.documents); } }
/** * Helper to disconnect various virtual document signal with callbacks of * this class. * * @param virtualDocument - virtual document to be disconnected. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-lsp/src/connection-manager.ts#L254-L263
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
DocumentConnectionManager.onForeignDocumentOpened
onForeignDocumentOpened(context: Document.IForeignContext): void { /** no-op */ }
// eslint-disable-next-line @typescript-eslint/no-unused-vars
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-lsp/src/connection-manager.ts#L269-L271
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
DocumentConnectionManager.onForeignDocumentClosed
onForeignDocumentClosed(context: Document.IForeignContext): void { const { foreignDocument } = context; this.unregisterDocument(foreignDocument.uri, false); this.disconnectDocumentSignals(foreignDocument); }
/** * Handle foreign document closed event. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-lsp/src/connection-manager.ts#L276-L280
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
DocumentConnectionManager.registerAdapter
registerAdapter(path: string, adapter: WidgetLSPAdapter<NotebookView>): void { this.adapters.set(path, adapter); adapter.onDispose(() => { if (adapter.virtualDocument) { this.documents.delete(adapter.virtualDocument.uri); } this.adapters.delete(path); }); }
/** * Register a widget adapter with this manager * * @param path - path to the inner document of the adapter * @param adapter - the adapter to be registered */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-lsp/src/connection-manager.ts#L288-L296
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
DocumentConnectionManager.updateConfiguration
updateConfiguration(allServerSettings: TLanguageServerConfigurations): void { this.languageServerManager.setConfiguration(allServerSettings); }
/** * Handles the settings that do not require an existing connection * with a language server (or can influence to which server the * connection will be created, e.g. `rank`). * * This function should be called **before** initialization of servers. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-lsp/src/connection-manager.ts#L305-L307
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
DocumentConnectionManager.updateServerConfigurations
updateServerConfigurations(allServerSettings: TLanguageServerConfigurations): void { let languageServerId: TServerKeys; for (languageServerId in allServerSettings) { if (!Object.prototype.hasOwnProperty.call(allServerSettings, languageServerId)) { continue; } const rawSettings = allServerSettings[languageServerId]!; const parsedSettings = expandDottedPaths(rawSettings.configuration || {}); const serverSettings: protocol.DidChangeConfigurationParams = { settings: parsedSettings, }; this.updateServerConfiguration(languageServerId, serverSettings); } }
/** * Handles the settings that the language servers accept using * `onDidChangeConfiguration` messages, which should be passed under * the "serverSettings" keyword in the setting registry. * Other configuration options are handled by `updateConfiguration` instead. * * This function should be called **after** initialization of servers. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-lsp/src/connection-manager.ts#L317-L334
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
DocumentConnectionManager.onNewConnection
onNewConnection = (connection: LSPConnection): void => { const errorSignalSlot = (e: any): void => { console.error(e); const error: Error = e.length && e.length >= 1 ? e[0] : new Error(); if (error.message.indexOf('code = 1005') !== -1) { console.error(`Connection failed for ${connection}`); this._forEachDocumentOfConnection(connection, (virtualDocument) => { console.error('disconnecting ' + virtualDocument.uri); this._closed.fire({ connection, virtualDocument }); this._ignoredLanguages.add(virtualDocument.language); console.error( `Cancelling further attempts to connect ${virtualDocument.uri} and other documents for this language (no support from the server)`, ); }); } else if (error.message.indexOf('code = 1006') !== -1) { console.error('Connection closed by the server'); } else { console.error('Connection error:', e); } }; connection.errorSignal(errorSignalSlot); const serverInitializedSlot = (): void => { // Initialize using settings stored in the SettingRegistry this._forEachDocumentOfConnection(connection, (virtualDocument) => { // TODO: is this still necessary, e.g. for status bar to update responsively? this._initialized.fire({ connection, virtualDocument }); }); this.updateServerConfigurations(this.initialConfigurations); }; connection.serverInitialized(serverInitializedSlot); const closeSignalSlot = (closedManually: boolean) => { if (!closedManually) { console.error('Connection unexpectedly disconnected'); } else { console.warn('Connection closed'); this._forEachDocumentOfConnection(connection, (virtualDocument) => { this._closed.fire({ connection, virtualDocument }); }); } }; connection.closeSignal(closeSignalSlot); }
/** * Fired the first time a connection is opened. These _should_ be the only * invocation of `.on` (once remaining LSPFeature.connection_handlers are made * singletons). */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-lsp/src/connection-manager.ts
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
DocumentConnectionManager.retryToConnect
async retryToConnect( options: ISocketConnectionOptions, reconnectDelay: number, retrialsLeft = -1, ): Promise<void> { const { virtualDocument } = options; if (this._ignoredLanguages.has(virtualDocument.language)) { return; } let interval = reconnectDelay * 1000; let success = false; while (retrialsLeft !== 0 && !success) { await this.connect(options) // eslint-disable-next-line @typescript-eslint/no-loop-func .then(() => { success = true; return; }) .catch((e) => { console.warn(e); }); console.warn('will attempt to re-connect in ' + interval / 1000 + ' seconds'); await sleep(interval); // gradually increase the time delay, up to 5 sec interval = interval < 5 * 1000 ? interval + 500 : interval; } }
/** * Retry to connect to the server each `reconnectDelay` seconds * and for `retrialsLeft` times. * TODO: presently no longer referenced. A failing connection would close * the socket, triggering the language server on the other end to exit. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-lsp/src/connection-manager.ts#L392-L423
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
DocumentConnectionManager.disconnect
disconnect(languageId: TLanguageServerId): void { this.disconnectServer(languageId); }
/** * Disconnect the connection to the language server of the requested * language. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-lsp/src/connection-manager.ts#L429-L431
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
DocumentConnectionManager.connect
async connect( options: ISocketConnectionOptions, firstTimeoutSeconds = 30, secondTimeoutMinutes = 5, ): Promise<ILSPConnection | undefined> { const connection = await this._connectSocket(options); const { virtualDocument } = options; if (!connection) { return; } if (!connection.isReady) { try { // user feedback hinted that 40 seconds was too short and some users are willing to wait more; // to make the best of both worlds we first check frequently (6.6 times a second) for the first // 30 seconds, and show the warning early in case if something is wrong; we then continue retrying // for another 5 minutes, but only once per second. await untilReady( () => connection.isReady, Math.round((firstTimeoutSeconds * 1000) / 150), 150, ); } catch { console.warn( `Connection to ${virtualDocument.uri} timed out after ${firstTimeoutSeconds} seconds, will continue retrying for another ${secondTimeoutMinutes} minutes`, ); try { await untilReady(() => connection.isReady, 60 * secondTimeoutMinutes, 1000); } catch { console.warn( `Connection to ${virtualDocument.uri} timed out again after ${secondTimeoutMinutes} minutes, giving up`, ); return; } } } this._connected.fire({ connection, virtualDocument }); return connection; }
/** * Create a new connection to the language server * @return A promise of the LSP connection */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-lsp/src/connection-manager.ts#L437-L476
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
DocumentConnectionManager.unregisterDocument
unregisterDocument(uri: string, emit = true): void { const connection = this.connections.get(uri); if (connection) { this.connections.delete(uri); const allConnection = new Set(this.connections.values()); if (!allConnection.has(connection)) { this.disconnect(connection.serverIdentifier as TLanguageServerId); connection.dispose(); } if (emit) { this._documentsChanged.fire(this.documents); } } }
/** * Disconnect the signals of requested virtual document uri. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-lsp/src/connection-manager.ts#L481-L495
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
DocumentConnectionManager.updateLogging
updateLogging( logAllCommunication: boolean, setTrace: AskServersToSendTraceNotifications, ): void { for (const connection of this.connections.values()) { connection.logAllCommunication = logAllCommunication; if (setTrace !== null) { connection.clientNotifications['$/setTrace'].fire({ value: setTrace }); } } }
/** * Enable or disable the logging feature of the language servers */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-lsp/src/connection-manager.ts#L500-L510
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
DocumentConnectionManager._connectSocket
protected async _connectSocket( options: ISocketConnectionOptions, ): Promise<LSPConnection | undefined> { const { language, capabilities, virtualDocument } = options; this.connectDocumentSignals(virtualDocument); const uris = this.solveUris(virtualDocument, language); const matchingServers = this.languageServerManager.getMatchingServers({ language, }); // for now use only the server with the highest rank. const languageServerId = matchingServers.length === 0 ? null : matchingServers[0]; // lazily load 1) the underlying library (1.5mb) and/or 2) a live WebSocket- // like connection: either already connected or potentially in the process // of connecting. if (!uris) { return; } const connection = await this.connection( language, languageServerId!, uris, this.onNewConnection, capabilities, ); // if connecting for the first time, all documents subsequent documents will // be re-opened and synced this.connections.set(virtualDocument.uri, connection); return connection; }
/** * Create the LSP connection for requested virtual document. * * @return Return the promise of the LSP connection. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-lsp/src/connection-manager.ts#L518-L552
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
DocumentConnectionManager._forEachDocumentOfConnection
protected _forEachDocumentOfConnection( connection: ILSPConnection, callback: (virtualDocument: VirtualDocument) => void, ) { for (const [virtualDocumentUri, currentConnection] of this.connections.entries()) { if (connection !== currentConnection) { continue; } callback(this.documents.get(virtualDocumentUri)!); } }
/** * Helper to apply callback on all documents of a connection. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-lsp/src/connection-manager.ts#L557-L567
371f9fa4903254d60ed3142e335dbf3f6d8d03e4