// Live events over the backend WebSocket, with cursor replay (plan step 2.5). // Lifted from waiter_pwa/src/hooks/useWebSocket.js without changing behaviour; the waiter's // hook is now a thin wrapper around this. No React. // // Protocol (local_backend/routers/ws.py): // 1. connect to ws[s]://host/api/ws/connect (never a token in the address: phase 4.0) // 2. send { cursor: , ...credentials() } at once (0 = first connect / no history) // 3. the server replays missed events, then sends { type: "ready" } // — or { type: "refused", data: { code } } and closes (4001 sign in again, 4003 device) // 4. live events: { seq, type, data }; control events without seq: `device.updated`, and // before the server closes: `session.ended`, `device.revoked` (plan step 3.1a) // 5. keepalive: { type: "ping" } every 25 s (no answer needed) // On close: reconnect after 2 s, then ×1.5 each time up to 30 s; a successful open resets // it. The browser's `online` event reconnects at once. The cursor survives reloads through // the `cursor` store the app provides (the waiter keeps it in IndexedDB). // // const live = createLiveClient({ // url: () => wsUrl('/api/ws/connect'), // credentials: () => ({ token }), // a paired screen: ({ device: deviceToken, token: sessionToken }) // cursor: { load: async () => seq, save: seq => … }, // onEvent: (type, data) => …, onReady: () => …, onDisconnect: () => …, // onRefused: code => …, // e.g. 'device.revoked', 'auth.session_ended'; it keeps retrying // }) // live.start(); …; live.reconnect(); …; live.stop() export const INITIAL_RECONNECT_DELAY = 2_000 export const MAX_RECONNECT_DELAY = 30_000 /** ws(s):/// */ export function wsUrlFor(path, baseURL = '') { const base = baseURL || (typeof location !== 'undefined' ? location.origin : 'http://localhost') const u = new URL(path, base) u.protocol = u.protocol === 'https:' ? 'wss:' : 'ws:' return u.toString() } export function createLiveClient({ url, cursor, onEvent, onReady, onDisconnect, credentials, onRefused, WebSocketImpl = globalThis.WebSocket, windowTarget = typeof window !== 'undefined' ? window : null, timers = { setTimeout: (fn, ms) => setTimeout(fn, ms), clearTimeout: id => clearTimeout(id) }, }) { let ws = null let reconnectTimer = null let reconnectDelay = INITIAL_RECONNECT_DELAY let stopped = true let lastSeq = 0 function connect() { if (stopped) return if (ws) { ws.onclose = null // prevent a double reconnect ws.close() ws = null } const socket = new WebSocketImpl(typeof url === 'function' ? url() : url) ws = socket socket.onopen = () => { reconnectDelay = INITIAL_RECONNECT_DELAY const extra = Object.fromEntries(Object.entries(credentials?.() || {}).filter(([, v]) => v != null && v !== '')) socket.send(JSON.stringify({ cursor: lastSeq, ...extra })) // the server replays what we missed } socket.onmessage = e => { let msg try { msg = JSON.parse(e.data) } catch { return } if (msg.type === 'ping') return if (msg.type === 'ready') { onReady?.(); return } if (msg.type === 'refused') { onRefused?.(msg.data?.code); return } if (msg.seq && msg.seq > lastSeq) { lastSeq = msg.seq cursor?.save?.(msg.seq) } if (msg.type && msg.data !== undefined) onEvent?.(msg.type, msg.data) } socket.onerror = () => {} // onerror always comes before onclose; onclose reconnects socket.onclose = () => { ws = null onDisconnect?.() if (stopped) return // wait the current delay, then grow it for the attempt after reconnectTimer = timers.setTimeout(() => { reconnectDelay = Math.min(reconnectDelay * 1.5, MAX_RECONNECT_DELAY) connect() }, reconnectDelay) } } function onNetworkOnline() { timers.clearTimeout(reconnectTimer) reconnectDelay = INITIAL_RECONNECT_DELAY connect() } return { /** Load the saved cursor, then connect. */ async start() { if (!stopped) return stopped = false windowTarget?.addEventListener('online', onNetworkOnline) let seq = 0 try { seq = (await cursor?.load?.()) ?? 0 } catch { seq = 0 } lastSeq = seq if (!stopped) connect() }, /** Close for good (no reconnect). */ stop() { stopped = true timers.clearTimeout(reconnectTimer) windowTarget?.removeEventListener('online', onNetworkOnline) if (ws) { ws.onclose = null ws.close() ws = null } }, /** Reconnect now, with the backoff reset (e.g. the app came back to the foreground). */ reconnect() { timers.clearTimeout(reconnectTimer) reconnectDelay = INITIAL_RECONNECT_DELAY connect() }, get lastSeq() { return lastSeq }, get connected() { return !!ws && ws.readyState === 1 }, } }