Skip to content

Instantly share code, notes, and snippets.

@malobre
Created January 9, 2025 21:19
Show Gist options
  • Save malobre/0b5a8b0b1f1df8756d6820093179e4c1 to your computer and use it in GitHub Desktop.
Save malobre/0b5a8b0b1f1df8756d6820093179e4c1 to your computer and use it in GitHub Desktop.
A drop-in replacement for `WebSocket` with automatic reconnection using jittered exponential backoff.
// MIT License
//
// Copyright (c) 2025 Maël Obréjan
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// A drop-in replacement for `WebSocket` with automatic reconnection using jittered exponential backoff.
export class RobustWebSocket extends EventTarget {
static CONNECTING: typeof WebSocket.CONNECTING = WebSocket.CONNECTING;
static OPEN: typeof WebSocket.OPEN = WebSocket.OPEN;
static CLOSING: typeof WebSocket.CLOSING = WebSocket.CLOSING;
static CLOSED: typeof WebSocket.CLOSED = WebSocket.CLOSED;
#retryController = new AbortController();
#args: ConstructorParameters<typeof WebSocket>;
// @ts-expect-error: initialization happens when the constructor calls `#connect`.
//
// See:
// - <https://github.com/microsoft/TypeScript/issues/21132>
// - <https://github.com/microsoft/TypeScript/issues/24446>
// - <https://github.com/microsoft/TypeScript/issues/30462>
// - <https://github.com/microsoft/TypeScript/issues/32194>
// - <https://github.com/microsoft/TypeScript/issues/59997>
#socket: WebSocket;
#attempt = 0;
binaryType: WebSocket["binaryType"] = "blob";
onopen: WebSocket["onopen"] = null;
onmessage: WebSocket["onmessage"] = null;
onerror: WebSocket["onerror"] = null;
onclose: WebSocket["onclose"] = null;
backoffBase = 2_000;
backoffCap = 60_000;
constructor(...args: ConstructorParameters<typeof WebSocket>) {
super();
this.#args = args;
// NOTE: `this.#socket` is initialized in this call.
this.#connect();
}
#connect(): void {
this.#socket = new WebSocket(...this.#args);
this.#socket.binaryType = this.binaryType;
this.#socket.onopen = this.onopen;
this.#socket.onmessage = this.onmessage;
this.#socket.onerror = this.onerror;
this.#socket.onclose = this.onclose;
this.#socket.addEventListener("open", () => {
this.#attempt = 0;
this.dispatchEvent(new Event("open"));
});
this.#socket.addEventListener("message", (messageEvent) => {
this.dispatchEvent(
new MessageEvent("message", {
data: messageEvent.data,
}),
);
});
this.#socket.addEventListener("close", (closeEvent) => {
this.dispatchEvent(
new CloseEvent("close", {
code: closeEvent.code,
reason: closeEvent.reason,
wasClean: closeEvent.wasClean,
}),
);
if (this.#retryController.signal.aborted) return;
const backoff = new Promise((resolve) => {
const delay = Math.min(
Math.random() * this.backoffBase * 2 ** this.#attempt,
this.backoffCap,
);
setTimeout(resolve, delay);
});
const abortion = new Promise((_, reject) => {
this.#retryController.signal.addEventListener("abort", () => {
reject();
});
});
Promise.race([backoff, abortion]).then(
() => {
this.#attempt += 1;
this.#connect();
},
() => {
// silently ignore backoff abortion
},
);
});
}
close(
...args: Parameters<WebSocket["close"]>
): ReturnType<WebSocket["close"]> {
this.#retryController.abort();
this.#socket.close(...args);
}
send(...args: Parameters<WebSocket["send"]>): ReturnType<WebSocket["send"]> {
return this.#socket.send(...args);
}
get url(): WebSocket["url"] {
return this.#socket.url;
}
get readyState(): WebSocket["readyState"] {
return this.#socket.readyState;
}
get bufferedAmount(): WebSocket["bufferedAmount"] {
return this.#socket.bufferedAmount;
}
get extensions(): WebSocket["extensions"] {
return this.#socket.extensions;
}
get protocol(): WebSocket["protocol"] {
return this.#socket.protocol;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment