/** * Protocol-level WebSocket ping/pong keepalive so idle editor (and play) * sessions are not killed by proxies that drop quiet connections. * * Browsers auto-reply to WebSocket ping frames; the `ws` library surfaces pong. */ export const DEFAULT_WS_PING_INTERVAL_MS = 25_000; /** * @param {import("ws").WebSocketServer} wss * @param {{ intervalMs?: number, setIntervalFn?: typeof setInterval, clearIntervalFn?: typeof clearInterval }} [options] * @returns {{ stop: () => void, intervalMs: number }} */ export function startWebSocketKeepalive (wss, options = {}) { const intervalMs = options.intervalMs ?? DEFAULT_WS_PING_INTERVAL_MS; const setIntervalFn = options.setIntervalFn ?? setInterval; const clearIntervalFn = options.clearIntervalFn ?? clearInterval; const onConnection = (socket) => { socket.isAlive = true; socket.on("pong", () => { socket.isAlive = true; }); }; wss.on("connection", onConnection); for (const socket of wss.clients) { onConnection(socket); } const interval = setIntervalFn(() => { for (const socket of wss.clients) { if (socket.isAlive === false) { socket.terminate(); continue; } socket.isAlive = false; try { socket.ping(); } catch { try { socket.terminate(); } catch { /* ignore */ } } } }, intervalMs); if (typeof interval?.unref === "function") { interval.unref(); } const onClose = () => { stop(); }; wss.on("close", onClose); let stopped = false; function stop () { if (stopped) { return; } stopped = true; clearIntervalFn(interval); wss.off("connection", onConnection); wss.off("close", onClose); } return { stop, intervalMs }; }