// A single, reused WebSocket connection to /connect, mirroring // android/.../data/transport/PipelinesClient.kt: requests are serialized, each // carries a client-generated stable id, replies are matched by id, and // unsolicited envelopes are dropped. There is no authentication of any kind. // // DOM-free on purpose: the browser app and the Node smoke test share this exact // module, so the smoke test exercises the real client, not a re-implementation. import { Protocol } from "./protocol.js"; /** A server `type:"error"` reply, surfaced with the server's own text. */ export class ProtocolError extends Error { constructor(message) { super(message); this.name = "ProtocolError"; } } /** No live WebSocket connection is available for the request. */ export class NotConnectedError extends Error { constructor(message = "Not connected to the Pipelines server") { super(message); this.name = "NotConnectedError"; } } const IDLE = "idle"; const CONNECTING = "connecting"; const CONNECTED = "connected"; const DISCONNECTED = "disconnected"; const NORMAL_CLOSURE = 1000; export class PipelinesClient extends EventTarget { #WebSocketImpl; #backoffBaseMs; #backoffMaxMs; #requestTimeoutMs; #random; #ws = null; #endpoint = null; #manualClose = false; #attempt = 0; #seq = 0; #pending = new Map(); // id -> { resolve, reject, timer } #queue = Promise.resolve(); #reconnectTimer = null; #state = { kind: IDLE, attempt: 0, reason: "", retrying: false }; constructor({ WebSocketImpl = globalThis.WebSocket, backoffBaseMs = 1000, backoffMaxMs = 30000, requestTimeoutMs = 30000, random = Math.random, } = {}) { super(); if (typeof WebSocketImpl !== "function") { throw new Error("No WebSocket implementation available"); } this.#WebSocketImpl = WebSocketImpl; this.#backoffBaseMs = backoffBaseMs; this.#backoffMaxMs = backoffMaxMs; this.#requestTimeoutMs = requestTimeoutMs; this.#random = random; } get state() { return { ...this.#state }; } #setState(next) { this.#state = next; this.dispatchEvent(new CustomEvent("state", { detail: this.state })); } /** Opens (or re-opens) the connection to a validated server URL. */ connect(validated) { if (!validated || !validated.valid) { throw new Error("server URL is not valid"); } this.#endpoint = validated.wsUrl; this.#manualClose = false; this.#attempt = 0; this.#clearReconnect(); this.#open(); } /** Explicit user disconnect: stops reconnection and closes the socket. */ disconnect() { this.#manualClose = true; this.#clearReconnect(); const socket = this.#ws; this.#ws = null; try { socket?.close(NORMAL_CLOSURE, "client closing"); } catch { /* already closed */ } this.#failPending("Disconnected"); this.#setState({ kind: IDLE, attempt: 0, reason: "", retrying: false }); } /** * Sends one request and awaits the reply with the matching id. Serialized by a * promise chain so concurrent screens cannot interleave frames. */ async call(request) { const run = this.#queue.then(() => this.#doCall(request)); // Keep the chain alive even when a call rejects. this.#queue = run.then( () => undefined, () => undefined, ); return run; } async #doCall(request) { const socket = this.#ws; if (!socket || this.#state.kind !== CONNECTED) throw new NotConnectedError(); const id = `web-${++this.#seq}`; const payload = JSON.stringify({ ...request, id }); const reply = new Promise((resolve, reject) => { const timer = setTimeout(() => { this.#pending.delete(id); reject(new Error(`request timed out after ${this.#requestTimeoutMs}ms`)); }, this.#requestTimeoutMs); this.#pending.set(id, { resolve, reject, timer }); }); try { socket.send(payload); const response = await reply; if (response.type === Protocol.ERROR) { throw new ProtocolError((response.error || "").trim() || "server error"); } return response; } finally { const entry = this.#pending.get(id); if (entry) { clearTimeout(entry.timer); this.#pending.delete(id); } } } #open() { const current = this.#endpoint; if (!current) return; this.#attempt += 1; this.#setState({ kind: CONNECTING, attempt: this.#attempt, reason: "", retrying: false, }); const socket = new this.#WebSocketImpl(current); this.#ws = socket; socket.onopen = () => { this.#attempt = 0; this.#setState({ kind: CONNECTED, attempt: 0, reason: "", retrying: false }); }; socket.onmessage = (event) => this.#onMessage(event.data); socket.onclose = (event) => { this.#handleClosed(`Connection closed (${event.code ?? "?"})`); }; socket.onerror = () => { // Browsers withhold detail here; onclose carries the outcome. }; } #onMessage(data) { if (typeof data !== "string") return; // the server is text-only let message; try { message = JSON.parse(data); } catch { return; // malformed frame: never misattribute it to a request } const entry = message.id ? this.#pending.get(message.id) : null; if (entry) { this.#pending.delete(message.id); clearTimeout(entry.timer); entry.resolve(message); } // Unsolicited envelopes (for example the connection's initial pipeline_list) // have no matching id and are intentionally dropped. } #failPending(reason) { for (const [id, entry] of this.#pending) { this.#pending.delete(id); clearTimeout(entry.timer); entry.reject(new Error(reason)); } } #handleClosed(reason) { this.#ws = null; this.#failPending(reason); if (this.#manualClose) { this.#setState({ kind: IDLE, attempt: 0, reason: "", retrying: false }); return; } this.#scheduleReconnect(reason); } #scheduleReconnect(reason) { if (this.#reconnectTimer) return; this.#setState({ kind: DISCONNECTED, attempt: this.#attempt, reason, retrying: true, }); const shift = Math.min(Math.max(this.#attempt - 1, 0), 6); const backoff = Math.min(this.#backoffBaseMs << shift, this.#backoffMaxMs); const jitter = Math.floor(this.#random() * 400); this.#reconnectTimer = setTimeout(() => { this.#reconnectTimer = null; if (!this.#manualClose && this.#endpoint) this.#open(); }, backoff + jitter); } #clearReconnect() { if (this.#reconnectTimer) { clearTimeout(this.#reconnectTimer); this.#reconnectTimer = null; } } }