| 1 | /** |
| 2 | * Protocol-level WebSocket ping/pong keepalive so idle editor (and play) |
| 3 | * sessions are not killed by proxies that drop quiet connections. |
| 4 | * |
| 5 | * Browsers auto-reply to WebSocket ping frames; the `ws` library surfaces pong. |
| 6 | */ |
| 7 | |
| 8 | export const DEFAULT_WS_PING_INTERVAL_MS = 25_000; |
| 9 | |
| 10 | /** |
| 11 | * @param {import("ws").WebSocketServer} wss |
| 12 | * @param {{ intervalMs?: number, setIntervalFn?: typeof setInterval, clearIntervalFn?: typeof clearInterval }} [options] |
| 13 | * @returns {{ stop: () => void, intervalMs: number }} |
| 14 | */ |
| 15 | export function startWebSocketKeepalive (wss, options = {}) |
| 16 | { |
| 17 | const intervalMs = options.intervalMs ?? DEFAULT_WS_PING_INTERVAL_MS; |
| 18 | const setIntervalFn = options.setIntervalFn ?? setInterval; |
| 19 | const clearIntervalFn = options.clearIntervalFn ?? clearInterval; |
| 20 | |
| 21 | const onConnection = (socket) => |
| 22 | { |
| 23 | socket.isAlive = true; |
| 24 | socket.on("pong", () => |
| 25 | { |
| 26 | socket.isAlive = true; |
| 27 | }); |
| 28 | }; |
| 29 | |
| 30 | wss.on("connection", onConnection); |
| 31 | for (const socket of wss.clients) |
| 32 | { onConnection(socket); } |
| 33 | |
| 34 | const interval = setIntervalFn(() => |
| 35 | { |
| 36 | for (const socket of wss.clients) |
| 37 | { |
| 38 | if (socket.isAlive === false) |
| 39 | { |
| 40 | socket.terminate(); |
| 41 | continue; |
| 42 | } |
| 43 | socket.isAlive = false; |
| 44 | try |
| 45 | { socket.ping(); } |
| 46 | catch |
| 47 | { |
| 48 | try |
| 49 | { socket.terminate(); } |
| 50 | catch |
| 51 | { /* ignore */ } |
| 52 | } |
| 53 | } |
| 54 | }, intervalMs); |
| 55 | |
| 56 | if (typeof interval?.unref === "function") |
| 57 | { interval.unref(); } |
| 58 | |
| 59 | const onClose = () => |
| 60 | { |
| 61 | stop(); |
| 62 | }; |
| 63 | wss.on("close", onClose); |
| 64 | |
| 65 | let stopped = false; |
| 66 | function stop () |
| 67 | { |
| 68 | if (stopped) |
| 69 | { return; } |
| 70 | stopped = true; |
| 71 | clearIntervalFn(interval); |
| 72 | wss.off("connection", onConnection); |
| 73 | wss.off("close", onClose); |
| 74 | } |
| 75 | |
| 76 | return { stop, intervalMs }; |
| 77 | } |