|
| 1 | +import WebSocket, { type ClientOptions } from "isomorphic-ws"; |
| 2 | +import type { ClientRequestArgs } from "node:http"; |
| 3 | +import type { Logger } from "ts-log"; |
| 4 | + |
| 5 | +// Reconnect with expo backoff if we don't get a message or ping for 10 seconds |
| 6 | +const HEARTBEAT_TIMEOUT_DURATION = 10000; |
| 7 | + |
| 8 | +/** |
| 9 | + * This class wraps websocket to provide a resilient web socket client. |
| 10 | + * |
| 11 | + * It will reconnect if connection fails with exponential backoff. Also, it will reconnect |
| 12 | + * if it receives no ping request or regular message from server within a while as indication |
| 13 | + * of timeout (assuming the server sends either regularly). |
| 14 | + * |
| 15 | + * This class also logs events if logger is given and by replacing onError method you can handle |
| 16 | + * connection errors yourself (e.g: do not retry and close the connection). |
| 17 | + */ |
| 18 | +export class ResilientWebSocket { |
| 19 | + endpoint: string; |
| 20 | + wsClient: undefined | WebSocket; |
| 21 | + wsUserClosed: boolean; |
| 22 | + private wsOptions: ClientOptions | ClientRequestArgs | undefined; |
| 23 | + private wsFailedAttempts: number; |
| 24 | + private heartbeatTimeout: undefined | NodeJS.Timeout; |
| 25 | + private logger: undefined | Logger; |
| 26 | + |
| 27 | + onError: (error: Error) => void; |
| 28 | + onMessage: (data: WebSocket.Data) => void; |
| 29 | + onReconnect: () => void; |
| 30 | + constructor( |
| 31 | + endpoint: string, |
| 32 | + wsOptions?: ClientOptions | ClientRequestArgs, |
| 33 | + logger?: Logger |
| 34 | + ) { |
| 35 | + this.endpoint = endpoint; |
| 36 | + this.wsOptions = wsOptions; |
| 37 | + this.logger = logger; |
| 38 | + |
| 39 | + this.wsFailedAttempts = 0; |
| 40 | + this.onError = (error: Error) => { |
| 41 | + this.logger?.error(error); |
| 42 | + }; |
| 43 | + this.wsUserClosed = true; |
| 44 | + this.onMessage = () => {}; |
| 45 | + this.onReconnect = () => {}; |
| 46 | + } |
| 47 | + |
| 48 | + async send(data: any) { |
| 49 | + this.logger?.info(`Sending ${data}`); |
| 50 | + |
| 51 | + await this.waitForMaybeReadyWebSocket(); |
| 52 | + |
| 53 | + if (this.wsClient === undefined) { |
| 54 | + this.logger?.error( |
| 55 | + "Couldn't connect to the websocket server. Error callback is called." |
| 56 | + ); |
| 57 | + } else { |
| 58 | + this.wsClient?.send(data); |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + async startWebSocket() { |
| 63 | + if (this.wsClient !== undefined) { |
| 64 | + return; |
| 65 | + } |
| 66 | + |
| 67 | + this.logger?.info(`Creating Web Socket client`); |
| 68 | + |
| 69 | + this.wsClient = new WebSocket(this.endpoint, this.wsOptions); |
| 70 | + this.wsUserClosed = false; |
| 71 | + |
| 72 | + this.wsClient.onopen = () => { |
| 73 | + this.wsFailedAttempts = 0; |
| 74 | + this.resetHeartbeat(); |
| 75 | + }; |
| 76 | + |
| 77 | + this.wsClient.onerror = (event) => { |
| 78 | + this.onError(event.error); |
| 79 | + }; |
| 80 | + |
| 81 | + this.wsClient.onmessage = (event) => { |
| 82 | + this.resetHeartbeat(); |
| 83 | + this.onMessage(event.data); |
| 84 | + }; |
| 85 | + |
| 86 | + this.wsClient.onclose = async () => { |
| 87 | + if (this.heartbeatTimeout !== undefined) { |
| 88 | + clearTimeout(this.heartbeatTimeout); |
| 89 | + } |
| 90 | + |
| 91 | + if (this.wsUserClosed === false) { |
| 92 | + this.wsFailedAttempts += 1; |
| 93 | + this.wsClient = undefined; |
| 94 | + const waitTime = expoBackoff(this.wsFailedAttempts); |
| 95 | + |
| 96 | + this.logger?.error( |
| 97 | + `Connection closed unexpectedly or because of timeout. Reconnecting after ${waitTime}ms.` |
| 98 | + ); |
| 99 | + |
| 100 | + await sleep(waitTime); |
| 101 | + this.restartUnexpectedClosedWebsocket(); |
| 102 | + } else { |
| 103 | + this.logger?.info("The connection has been closed successfully."); |
| 104 | + } |
| 105 | + }; |
| 106 | + |
| 107 | + if (this.wsClient.on !== undefined) { |
| 108 | + // Ping handler is undefined in browser side |
| 109 | + this.wsClient.on("ping", () => { |
| 110 | + this.logger?.info("Ping received"); |
| 111 | + this.resetHeartbeat(); |
| 112 | + }); |
| 113 | + } |
| 114 | + } |
| 115 | + |
| 116 | + /** |
| 117 | + * Reset the heartbeat timeout. This is called when we receive any message (ping or regular) |
| 118 | + * from the server. If we don't receive any message within HEARTBEAT_TIMEOUT_DURATION, |
| 119 | + * we assume the connection is dead and reconnect. |
| 120 | + */ |
| 121 | + private resetHeartbeat() { |
| 122 | + if (this.heartbeatTimeout !== undefined) { |
| 123 | + clearTimeout(this.heartbeatTimeout); |
| 124 | + } |
| 125 | + |
| 126 | + this.heartbeatTimeout = setTimeout(() => { |
| 127 | + this.logger?.warn(`Connection timed out. Reconnecting...`); |
| 128 | + this.wsClient?.terminate(); |
| 129 | + this.restartUnexpectedClosedWebsocket(); |
| 130 | + }, HEARTBEAT_TIMEOUT_DURATION); |
| 131 | + } |
| 132 | + |
| 133 | + private async waitForMaybeReadyWebSocket() { |
| 134 | + let waitedTime = 0; |
| 135 | + while ( |
| 136 | + this.wsClient !== undefined && |
| 137 | + this.wsClient.readyState !== this.wsClient.OPEN |
| 138 | + ) { |
| 139 | + if (waitedTime > 5000) { |
| 140 | + this.wsClient.close(); |
| 141 | + return; |
| 142 | + } else { |
| 143 | + waitedTime += 10; |
| 144 | + await sleep(10); |
| 145 | + } |
| 146 | + } |
| 147 | + } |
| 148 | + |
| 149 | + private async restartUnexpectedClosedWebsocket() { |
| 150 | + if (this.wsUserClosed === true) { |
| 151 | + return; |
| 152 | + } |
| 153 | + |
| 154 | + await this.startWebSocket(); |
| 155 | + await this.waitForMaybeReadyWebSocket(); |
| 156 | + |
| 157 | + if (this.wsClient === undefined) { |
| 158 | + this.logger?.error( |
| 159 | + "Couldn't reconnect to websocket. Error callback is called." |
| 160 | + ); |
| 161 | + return; |
| 162 | + } |
| 163 | + |
| 164 | + this.onReconnect(); |
| 165 | + } |
| 166 | + |
| 167 | + closeWebSocket() { |
| 168 | + if (this.wsClient !== undefined) { |
| 169 | + const client = this.wsClient; |
| 170 | + this.wsClient = undefined; |
| 171 | + client.close(); |
| 172 | + } |
| 173 | + this.wsUserClosed = true; |
| 174 | + } |
| 175 | +} |
| 176 | + |
| 177 | +async function sleep(ms: number) { |
| 178 | + return new Promise((resolve) => setTimeout(resolve, ms)); |
| 179 | +} |
| 180 | + |
| 181 | +function expoBackoff(attempts: number): number { |
| 182 | + return 2 ** attempts * 100; |
| 183 | +} |
0 commit comments