UNPKG

@theia/core

Version:

Theia is a cloud & desktop IDE framework implemented in TypeScript.

190 lines • 8.75 kB
// ***************************************************************************** // Copyright (C) 2023 STMicroelectronics and others. // // This program and the accompanying materials are made available under the // terms of the Eclipse Public License v. 2.0 which is available at // http://www.eclipse.org/legal/epl-2.0. // // This Source Code may also be made available under the following Secondary // Licenses when the conditions for such availability set forth in the Eclipse // Public License v. 2.0 are satisfied: GNU General Public License, version 2 // with the GNU Classpath Exception which is available at // https://www.gnu.org/software/classpath/license.html. // // SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0 import { __decorate } from "tslib"; import { inject, injectable, named } from 'inversify'; import { ConnectionHandlers, MessagingContainer } from './default-messaging-service.js'; import { SocketWriteBuffer } from '../../common/messaging/socket-write-buffer.js'; import { AbstractChannel } from '../../common/message-rpc/channel.js'; import { Uint8ArrayReadBuffer, Uint8ArrayWriteBuffer } from '../../common/message-rpc/uint8-array-message-buffer.js'; import { BackendApplicationConfigProvider } from '../backend-application-config-provider.js'; import { WebsocketEndpoint } from './websocket-endpoint.js'; import { ConnectionManagementMessages } from '../../common/messaging/connection-management.js'; import { Disposable, DisposableCollection, ILogger } from '../../common/index.js'; let WebsocketFrontendConnectionService = class WebsocketFrontendConnectionService { constructor() { this.wsHandlers = new ConnectionHandlers(); this.connectionsByFrontend = new Map(); this.closeTimeouts = new Map(); this.channelsMarkedForClose = new Set(); } registerConnectionHandler(spec, callback) { this.websocketServer.registerConnectionHandler(spec, (params, socket) => this.handleConnection(socket, channel => callback(params, channel))); } async handleConnection(socket, channelCreatedHandler) { // eslint-disable-next-line prefer-const let reconnectListener; const initialConnectListener = (frontEndId) => { socket.off(ConnectionManagementMessages.INITIAL_CONNECT, initialConnectListener); socket.off(ConnectionManagementMessages.RECONNECT, reconnectListener); if (this.connectionsByFrontend.has(frontEndId)) { this.closeConnection(frontEndId, 'reconnecting same front end'); } const channel = this.createConnection(socket, frontEndId); this.handleSocketDisconnect(socket, channel, frontEndId); channelCreatedHandler(channel); socket.emit(ConnectionManagementMessages.INITIAL_CONNECT); }; reconnectListener = (frontEndId) => { socket.off(ConnectionManagementMessages.INITIAL_CONNECT, initialConnectListener); socket.off(ConnectionManagementMessages.RECONNECT, reconnectListener); const channel = this.connectionsByFrontend.get(frontEndId); if (channel) { this.logger.info(`Reconnecting to front end ${frontEndId}`); socket.emit(ConnectionManagementMessages.RECONNECT, true); channel.connect(socket); this.handleSocketDisconnect(socket, channel, frontEndId); const pendingTimeout = this.closeTimeouts.get(frontEndId); clearTimeout(pendingTimeout); this.closeTimeouts.delete(frontEndId); } else { this.logger.info(`Reconnecting failed for ${frontEndId}`); socket.emit(ConnectionManagementMessages.RECONNECT, false); } }; socket.on(ConnectionManagementMessages.INITIAL_CONNECT, initialConnectListener); socket.on(ConnectionManagementMessages.RECONNECT, reconnectListener); } closeConnection(frontEndId, reason) { this.logger.info(`closing connection for ${frontEndId}`); const connection = this.connectionsByFrontend.get(frontEndId); // not called when no connection is present this.connectionsByFrontend.delete(frontEndId); const pendingTimeout = this.closeTimeouts.get(frontEndId); clearTimeout(pendingTimeout); this.closeTimeouts.delete(frontEndId); connection.onCloseEmitter.fire({ reason }); connection.drainBuffer(); connection.close(); } createConnection(socket, frontEndId) { this.logger.info(`creating connection for ${frontEndId}`); const channel = this.container.get(ReconnectableSocketChannel); channel.connect(socket); this.connectionsByFrontend.set(frontEndId, channel); return channel; } handleSocketDisconnect(socket, channel, frontEndId) { socket.on('disconnect', evt => { this.logger.info('socket closed'); channel.disconnect(); const timeout = this.frontendConnectionTimeout(); const isMarkedForClose = this.channelsMarkedForClose.delete(frontEndId); if (timeout === 0 || isMarkedForClose) { this.closeConnection(frontEndId, evt); } else if (timeout > 0) { this.logger.info(`setting close timeout for id ${frontEndId} to ${timeout}`); const handle = setTimeout(() => { this.closeConnection(frontEndId, evt); }, timeout); this.closeTimeouts.set(frontEndId, handle); } else { // timeout < 0: never close the back end } }); } markForClose(channelId) { this.channelsMarkedForClose.add(channelId); } frontendConnectionTimeout() { const envValue = Number(process.env['FRONTEND_CONNECTION_TIMEOUT']); if (!isNaN(envValue)) { return envValue; } return BackendApplicationConfigProvider.get().frontendConnectionTimeout; } }; __decorate([ inject(WebsocketEndpoint) ], WebsocketFrontendConnectionService.prototype, "websocketServer", void 0); __decorate([ inject(MessagingContainer) ], WebsocketFrontendConnectionService.prototype, "container", void 0); __decorate([ inject(ILogger), named('core:WebsocketFrontendConnectionService') ], WebsocketFrontendConnectionService.prototype, "logger", void 0); WebsocketFrontendConnectionService = __decorate([ injectable() ], WebsocketFrontendConnectionService); export { WebsocketFrontendConnectionService }; let ReconnectableSocketChannel = class ReconnectableSocketChannel extends AbstractChannel { constructor() { super(...arguments); this.disposables = new DisposableCollection(); } connect(socket) { this.disposables.dispose(); this.disposables = new DisposableCollection(); this.socket = socket; const errorHandler = (err) => { this.onErrorEmitter.fire(err); }; this.disposables.push(Disposable.create(() => { socket.off('error', errorHandler); })); socket.on('error', errorHandler); // eslint-disable-next-line @typescript-eslint/no-explicit-any const dataListener = (data) => { // In the browser context socketIO receives binary messages as ArrayBuffers. // So we have to convert them to a Uint8Array before delegating the message to the read buffer. const buffer = data instanceof ArrayBuffer ? new Uint8Array(data) : data; this.onMessageEmitter.fire(() => new Uint8ArrayReadBuffer(buffer)); }; this.disposables.push(Disposable.create(() => { socket.off('message', dataListener); })); socket.on('message', dataListener); this.socketBuffer.flush(socket); } disconnect() { this.disposables.dispose(); this.socket = undefined; } drainBuffer() { this.socketBuffer.drain(); } getWriteBuffer() { const writeBuffer = new Uint8ArrayWriteBuffer(); writeBuffer.onCommit(data => { if (this.socket?.connected) { this.socket.send(data); } else { this.socketBuffer.buffer(data); } }); return writeBuffer; } }; __decorate([ inject(SocketWriteBuffer) ], ReconnectableSocketChannel.prototype, "socketBuffer", void 0); ReconnectableSocketChannel = __decorate([ injectable() ], ReconnectableSocketChannel); export { ReconnectableSocketChannel }; //# sourceMappingURL=websocket-frontend-connection-service.js.map