UNPKG

@theia/core

Version:

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

212 lines • 8.81 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"; // Manages the socket the frontend logger's RPC rides on, so logging through an ILogger here // would be circular. /* eslint-disable @theia/named-logger-check */ import { Emitter } from '../../common/event.js'; import { io } from 'socket.io-client'; import { Endpoint } from '../endpoint.js'; import { ForwardingChannel } from '../../common/message-rpc/channel.js'; import { Uint8ArrayReadBuffer, Uint8ArrayWriteBuffer } from '../../common/message-rpc/uint8-array-message-buffer.js'; import { inject, injectable, postConstruct } from 'inversify'; import { FrontendIdProvider } from './frontend-id-provider.js'; import { FrontendApplicationConfigProvider } from '../frontend-application-config-provider.js'; import { SocketWriteBuffer } from '../../common/messaging/socket-write-buffer.js'; import { ConnectionManagementMessages } from '../../common/messaging/connection-management.js'; import { servicesPath } from '../../common/messaging/handler.js'; import { Disposable, DisposableCollection } from '../../common/disposable.js'; let WebSocketConnectionSource = class WebSocketConnectionSource { static { this.NO_CONNECTION = '<none>'; } get socket() { return this._socket; } get onConnectionDidOpen() { return this.onConnectionDidOpenEmitter.event; } get onSocketDidOpen() { return this.onSocketDidOpenEmitter.event; } get onSocketDidClose() { return this.onSocketDidCloseEmitter.event; } get onIncomingMessageActivity() { return this.onIncomingMessageActivityEmitter.event; } constructor() { this.onConnectionDidOpenEmitter = new Emitter(); this.onSocketDidOpenEmitter = new Emitter(); this.onSocketDidCloseEmitter = new Emitter(); this.onIncomingMessageActivityEmitter = new Emitter(); } openSocket() { const url = this.createWebSocketUrl(servicesPath); this._socket = this.createWebSocket(url); this._socket.on('connect', () => { this.onSocketDidOpenEmitter.fire(); this.handleSocketConnected(); }); this._socket.on('disconnect', () => { this.onSocketDidCloseEmitter.fire(); }); this._socket.on('error', reason => { if (this.currentChannel) { this.currentChannel.onErrorEmitter.fire(reason); } ; }); this._socket.connect(); } negogiateReconnect() { const reconnectListener = (hasConnection) => { this._socket.off(ConnectionManagementMessages.RECONNECT, reconnectListener); if (hasConnection) { console.info(`reconnect succeeded on ${this.socket.id}`); this.writeBuffer.flush(this.socket); } else { if (FrontendApplicationConfigProvider.get().reloadOnReconnect) { window.location.reload(); // this might happen in the preload module, when we have no window service yet } else { console.info(`reconnect failed on ${this.socket.id}`); this.currentChannel.onCloseEmitter.fire({ reason: 'reconnecting channel' }); this.currentChannel.close(); this.writeBuffer.drain(); this.socket.disconnect(); this.socket.connect(); this.negotiateInitialConnect(); } } }; this._socket.on(ConnectionManagementMessages.RECONNECT, reconnectListener); console.info(`sending reconnect on ${this.socket.id}`); this._socket.emit(ConnectionManagementMessages.RECONNECT, this.frontendIdProvider.getId()); } negotiateInitialConnect() { const initialConnectListener = () => { console.info(`initial connect received on ${this.socket.id}`); this._socket.off(ConnectionManagementMessages.INITIAL_CONNECT, initialConnectListener); this.connectNewChannel(); }; this._socket.on(ConnectionManagementMessages.INITIAL_CONNECT, initialConnectListener); console.info(`sending initial connect on ${this.socket.id}`); this._socket.emit(ConnectionManagementMessages.INITIAL_CONNECT, this.frontendIdProvider.getId()); } handleSocketConnected() { if (this.currentChannel) { this.negogiateReconnect(); } else { this.negotiateInitialConnect(); } } connectNewChannel() { if (this.currentChannel) { this.currentChannel.onCloseEmitter.fire({ reason: 'reconnecting channel' }); this.currentChannel.close(); } this.writeBuffer.drain(); this.currentChannel = this.createChannel(); this.onConnectionDidOpenEmitter.fire(this.currentChannel); } createChannel() { const toDispose = new DisposableCollection(); // eslint-disable-next-line @typescript-eslint/no-explicit-any const messageHandler = (data) => { this.onIncomingMessageActivityEmitter.fire(); if (this.currentChannel) { // 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.currentChannel.onMessageEmitter.fire(() => new Uint8ArrayReadBuffer(buffer)); } ; }; this._socket.on('message', messageHandler); toDispose.push(Disposable.create(() => { this.socket.off('message', messageHandler); })); const channel = new ForwardingChannel('any', () => { toDispose.dispose(); }, () => { const result = new Uint8ArrayWriteBuffer(); result.onCommit(buffer => { if (this.socket.connected) { this.socket.send(buffer); } else { this.writeBuffer.buffer(buffer); } }); return result; }); return channel; } /** * @param path The handler to reach in the backend. */ createWebSocketUrl(path) { // Since we are using Socket.io, the path should look like the following: // proto://domain.com/{path} return this.createEndpoint(path).getWebSocketUrl().withPath(path).toString(); } createHttpWebSocketUrl(path) { return this.createEndpoint(path).getRestUrl().toString(); } createEndpoint(path) { return new Endpoint({ path }); } /** * Creates a web socket for the given url */ createWebSocket(url) { return io(url, { path: this.createSocketIoPath(url), reconnection: true, reconnectionDelay: 1000, reconnectionDelayMax: 10000, reconnectionAttempts: Infinity }); } /** * Path for Socket.io to make its requests to. */ createSocketIoPath(url) { if (location.protocol === Endpoint.PROTO_FILE) { return '/socket.io'; } let { pathname } = location; if (!pathname.endsWith('/')) { pathname += '/'; } return pathname + 'socket.io'; } }; __decorate([ inject(FrontendIdProvider) ], WebSocketConnectionSource.prototype, "frontendIdProvider", void 0); __decorate([ inject(SocketWriteBuffer) ], WebSocketConnectionSource.prototype, "writeBuffer", void 0); __decorate([ postConstruct() ], WebSocketConnectionSource.prototype, "openSocket", null); WebSocketConnectionSource = __decorate([ injectable() ], WebSocketConnectionSource); export { WebSocketConnectionSource }; //# sourceMappingURL=ws-connection-source.js.map