| b69ab31 | | | 1 | /** |
| b69ab31 | | | 2 | * Copyright (c) Meta Platforms, Inc. and affiliates. |
| b69ab31 | | | 3 | * |
| b69ab31 | | | 4 | * This source code is licensed under the MIT license found in the |
| b69ab31 | | | 5 | * LICENSE file in the root directory of this source tree. |
| b69ab31 | | | 6 | */ |
| b69ab31 | | | 7 | |
| b69ab31 | | | 8 | import type {Disposable, MessageBusStatus, PlatformName} from './types'; |
| b69ab31 | | | 9 | |
| b69ab31 | | | 10 | import {CLOSED_AND_SHOULD_NOT_RECONNECT_CODE} from 'isl-server/src/constants'; |
| b69ab31 | | | 11 | import {logger} from './logger'; |
| b69ab31 | | | 12 | |
| b69ab31 | | | 13 | export class LocalWebSocketEventBus { |
| b69ab31 | | | 14 | static MAX_RECONNECT_CHECK_TIME_MS = 60000; |
| b69ab31 | | | 15 | static DEFAULT_RECONNECT_CHECK_TIME_MS = 100; |
| b69ab31 | | | 16 | |
| b69ab31 | | | 17 | private websocket: WebSocket; |
| b69ab31 | | | 18 | private status: MessageBusStatus = {type: 'initializing'}; |
| b69ab31 | | | 19 | private exponentialReconnectDelay = LocalWebSocketEventBus.DEFAULT_RECONNECT_CHECK_TIME_MS; |
| b69ab31 | | | 20 | private queuedMessages: Array<string | ArrayBuffer> = []; |
| b69ab31 | | | 21 | |
| b69ab31 | | | 22 | // A sub-state of "status", used by `startConnection` to avoid creating multiple |
| b69ab31 | | | 23 | // websockets while connecting. |
| b69ab31 | | | 24 | // |
| b69ab31 | | | 25 | // status.type: | 'initializing' | 'open' | 'reconnecting' | 'open' |
| b69ab31 | | | 26 | // opening: | true | false | false | true | false |
| b69ab31 | | | 27 | // ^^^^^^^ reconnect setTimeout |
| b69ab31 | | | 28 | private opening = false; |
| b69ab31 | | | 29 | |
| b69ab31 | | | 30 | private handlers: Array<(event: MessageEvent<string>) => void | Promise<void>> = []; |
| b69ab31 | | | 31 | private statusChangeHandlers: Array<(newStatus: MessageBusStatus) => unknown> = []; |
| b69ab31 | | | 32 | |
| b69ab31 | | | 33 | private disposed = false; |
| b69ab31 | | | 34 | |
| b69ab31 | | | 35 | /** |
| b69ab31 | | | 36 | * @param host to use when creating the Web Socket to talk to the server. Should |
| b69ab31 | | | 37 | * include the hostname and optionally, a port, e.g., "localhost:3001" or "example.com". |
| b69ab31 | | | 38 | */ |
| b69ab31 | | | 39 | constructor( |
| b69ab31 | | | 40 | private host: string, |
| b69ab31 | | | 41 | private WebSocketType: typeof WebSocket, |
| b69ab31 | | | 42 | private params: {token?: string; cwd?: string; sessionId?: string; platformName: PlatformName}, |
| b69ab31 | | | 43 | ) { |
| b69ab31 | | | 44 | // startConnection already assigns to websocket, but we do it here so typescript knows websocket is always defined |
| b69ab31 | | | 45 | this.websocket = this.startConnection(); |
| b69ab31 | | | 46 | } |
| b69ab31 | | | 47 | |
| b69ab31 | | | 48 | public dispose() { |
| b69ab31 | | | 49 | if (this.disposed) { |
| b69ab31 | | | 50 | return; |
| b69ab31 | | | 51 | } |
| b69ab31 | | | 52 | this.disposed = true; |
| b69ab31 | | | 53 | this.websocket.close(); |
| b69ab31 | | | 54 | } |
| b69ab31 | | | 55 | |
| b69ab31 | | | 56 | private startConnection(): WebSocket { |
| b69ab31 | | | 57 | if (this.disposed || this.opening || this.status.type === 'open') { |
| b69ab31 | | | 58 | return this.websocket; |
| b69ab31 | | | 59 | } |
| b69ab31 | | | 60 | const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'; |
| b69ab31 | | | 61 | const wsUrl = new URL(`${wsProtocol}//${this.host}/ws`); |
| b69ab31 | | | 62 | const token = this.params.token; |
| b69ab31 | | | 63 | if (token) { |
| b69ab31 | | | 64 | wsUrl.searchParams.append('token', token); |
| b69ab31 | | | 65 | } |
| b69ab31 | | | 66 | const cwdParam = this.params.cwd; |
| b69ab31 | | | 67 | if (cwdParam) { |
| b69ab31 | | | 68 | const cwd = decodeURIComponent(cwdParam); |
| b69ab31 | | | 69 | wsUrl.searchParams.append('cwd', cwd); |
| b69ab31 | | | 70 | } |
| b69ab31 | | | 71 | const sessionIdParam = this.params.sessionId; |
| b69ab31 | | | 72 | if (sessionIdParam) { |
| b69ab31 | | | 73 | const sessionId = decodeURIComponent(sessionIdParam); |
| b69ab31 | | | 74 | wsUrl.searchParams.append('sessionId', sessionId); |
| b69ab31 | | | 75 | } |
| b69ab31 | | | 76 | const platformName = this.params.platformName; |
| b69ab31 | | | 77 | if (platformName) { |
| b69ab31 | | | 78 | wsUrl.searchParams.append('platform', platformName); |
| b69ab31 | | | 79 | } |
| b69ab31 | | | 80 | this.websocket = new this.WebSocketType(wsUrl.href); |
| b69ab31 | | | 81 | this.opening = true; |
| b69ab31 | | | 82 | this.websocket.addEventListener('open', event => { |
| b69ab31 | | | 83 | logger.info('websocket open', event); |
| b69ab31 | | | 84 | this.opening = false; |
| b69ab31 | | | 85 | this.exponentialReconnectDelay = LocalWebSocketEventBus.DEFAULT_RECONNECT_CHECK_TIME_MS; |
| b69ab31 | | | 86 | |
| b69ab31 | | | 87 | this.websocket.addEventListener('message', e => { |
| b69ab31 | | | 88 | for (const handler of this.handlers) { |
| b69ab31 | | | 89 | handler(e); |
| b69ab31 | | | 90 | } |
| b69ab31 | | | 91 | }); |
| b69ab31 | | | 92 | |
| b69ab31 | | | 93 | // if any messages were sent while reconnecting, they were queued up. |
| b69ab31 | | | 94 | // Send them all now that we've reconnected |
| b69ab31 | | | 95 | while (this.queuedMessages.length > 0) { |
| b69ab31 | | | 96 | const queuedMessage = this.queuedMessages[0]; |
| b69ab31 | | | 97 | this.websocket.send(queuedMessage); |
| b69ab31 | | | 98 | // only dequeue after successfully sending the message |
| b69ab31 | | | 99 | this.queuedMessages.shift(); |
| b69ab31 | | | 100 | } |
| b69ab31 | | | 101 | |
| b69ab31 | | | 102 | this.setStatus({type: 'open'}); |
| b69ab31 | | | 103 | }); |
| b69ab31 | | | 104 | |
| b69ab31 | | | 105 | this.websocket.addEventListener('close', event => { |
| b69ab31 | | | 106 | this.opening = false; |
| b69ab31 | | | 107 | if (event.code === CLOSED_AND_SHOULD_NOT_RECONNECT_CODE) { |
| b69ab31 | | | 108 | // Don't schedule reconnect if the server told us this is a permanent failure, |
| b69ab31 | | | 109 | // e.g. invalid token |
| b69ab31 | | | 110 | this.setStatus({type: 'error', error: event.reason}); |
| b69ab31 | | | 111 | return; |
| b69ab31 | | | 112 | } |
| b69ab31 | | | 113 | if (!this.disposed) { |
| b69ab31 | | | 114 | this.scheduleReconnect(); |
| b69ab31 | | | 115 | } |
| b69ab31 | | | 116 | }); |
| b69ab31 | | | 117 | |
| b69ab31 | | | 118 | return this.websocket; |
| b69ab31 | | | 119 | } |
| b69ab31 | | | 120 | |
| b69ab31 | | | 121 | private setStatus(status: MessageBusStatus) { |
| b69ab31 | | | 122 | this.status = status; |
| b69ab31 | | | 123 | this.statusChangeHandlers.forEach(handler => handler(status)); |
| b69ab31 | | | 124 | } |
| b69ab31 | | | 125 | |
| b69ab31 | | | 126 | private scheduleReconnect() { |
| b69ab31 | | | 127 | this.setStatus({type: 'reconnecting'}); |
| b69ab31 | | | 128 | logger.info(`websocket connection closed. Retrying in ${this.exponentialReconnectDelay}ms`); |
| b69ab31 | | | 129 | setTimeout(() => { |
| b69ab31 | | | 130 | this.startConnection(); |
| b69ab31 | | | 131 | }, this.exponentialReconnectDelay); |
| b69ab31 | | | 132 | |
| b69ab31 | | | 133 | this.exponentialReconnectDelay = Math.min( |
| b69ab31 | | | 134 | this.exponentialReconnectDelay * 2, |
| b69ab31 | | | 135 | LocalWebSocketEventBus.MAX_RECONNECT_CHECK_TIME_MS, |
| b69ab31 | | | 136 | ); |
| b69ab31 | | | 137 | } |
| b69ab31 | | | 138 | |
| b69ab31 | | | 139 | onMessage(handler: (event: MessageEvent<string>) => void | Promise<void>): Disposable { |
| b69ab31 | | | 140 | // we need to track handlers ourself instead of directly calling this.websocket.addEventListener here, |
| b69ab31 | | | 141 | // since we'll get a new WebSocket on reconnect. |
| b69ab31 | | | 142 | this.handlers.push(handler); |
| b69ab31 | | | 143 | const dispose = () => { |
| b69ab31 | | | 144 | const foundIndex = this.handlers.indexOf(handler); |
| b69ab31 | | | 145 | if (foundIndex !== -1) { |
| b69ab31 | | | 146 | this.handlers.splice(foundIndex, 1); |
| b69ab31 | | | 147 | } |
| b69ab31 | | | 148 | }; |
| b69ab31 | | | 149 | return {dispose}; |
| b69ab31 | | | 150 | } |
| b69ab31 | | | 151 | |
| b69ab31 | | | 152 | postMessage(message: string) { |
| b69ab31 | | | 153 | if (this.status.type === 'open') { |
| b69ab31 | | | 154 | this.websocket.send(message); |
| b69ab31 | | | 155 | } else { |
| b69ab31 | | | 156 | this.queuedMessages.push(message); |
| b69ab31 | | | 157 | } |
| b69ab31 | | | 158 | } |
| b69ab31 | | | 159 | |
| b69ab31 | | | 160 | onChangeStatus(handler: (newStatus: MessageBusStatus) => void | Promise<void>): Disposable { |
| b69ab31 | | | 161 | this.statusChangeHandlers.push(handler); |
| b69ab31 | | | 162 | handler(this.status); // seed with current status |
| b69ab31 | | | 163 | const dispose = () => { |
| b69ab31 | | | 164 | const foundIndex = this.statusChangeHandlers.indexOf(handler); |
| b69ab31 | | | 165 | if (foundIndex !== -1) { |
| b69ab31 | | | 166 | this.statusChangeHandlers.splice(foundIndex, 1); |
| b69ab31 | | | 167 | } |
| b69ab31 | | | 168 | }; |
| b69ab31 | | | 169 | return {dispose}; |
| b69ab31 | | | 170 | } |
| b69ab31 | | | 171 | |
| b69ab31 | | | 172 | forceDisconnect(durationMs = 1000) { |
| b69ab31 | | | 173 | this.websocket.close(); |
| b69ab31 | | | 174 | this.exponentialReconnectDelay = durationMs; |
| b69ab31 | | | 175 | this.scheduleReconnect(); |
| b69ab31 | | | 176 | } |
| b69ab31 | | | 177 | } |