|
| 1 | +export const DEFAULT_WEBSOCKET_KEEPALIVE = 12_000; |
| 2 | +import type WebSocket from "ws"; |
| 3 | + |
| 4 | +export function handleWebSocketKeepalive( |
| 5 | + socket: WebSocket, |
| 6 | + preset: GraphileConfig.ResolvedPreset, |
| 7 | +): void { |
| 8 | + const keepaliveInterval = |
| 9 | + preset.grafserv?.websocketKeepalive ?? DEFAULT_WEBSOCKET_KEEPALIVE; |
| 10 | + if (!Number.isFinite(keepaliveInterval) || keepaliveInterval <= 0) { |
| 11 | + // Keepalive disabled |
| 12 | + return; |
| 13 | + } |
| 14 | + |
| 15 | + /** |
| 16 | + * Sending a ping and waiting for a pong are mutually exclusive, so this |
| 17 | + * timer is used for both. |
| 18 | + */ |
| 19 | + let timer: NodeJS.Timeout | null = null; |
| 20 | + |
| 21 | + /** |
| 22 | + * Cleans up the timer, always call this before re-assigning timer (to ensure |
| 23 | + * that an out-of-order pong doesn't cause two timers to run concurrently). |
| 24 | + */ |
| 25 | + const stopTimer = () => { |
| 26 | + if (timer != null) { |
| 27 | + clearTimeout(timer); |
| 28 | + timer = null; |
| 29 | + } |
| 30 | + }; |
| 31 | + |
| 32 | + /** First half of a heart beat - send ping */ |
| 33 | + const sendPing = () => { |
| 34 | + stopTimer(); |
| 35 | + // Schedule timeout |
| 36 | + timer = setTimeout(handleTimeout, keepaliveInterval); |
| 37 | + socket.ping(); |
| 38 | + }; |
| 39 | + /** Second half of a heart beat - receive pong */ |
| 40 | + const handlePong = () => { |
| 41 | + stopTimer(); |
| 42 | + // Schedule the next ping |
| 43 | + timer = setTimeout(sendPing, keepaliveInterval); |
| 44 | + }; |
| 45 | + |
| 46 | + /** Terminal handler, due to timeout */ |
| 47 | + const handleTimeout = () => { |
| 48 | + stopTimer(); |
| 49 | + releaseListeners(); |
| 50 | + // Kill the socket (after we've released the listeners) |
| 51 | + socket.terminate(); |
| 52 | + }; |
| 53 | + /** Terminal handler, due to natural socket close */ |
| 54 | + const handleClose = (_code: number, _reason: Buffer) => { |
| 55 | + stopTimer(); |
| 56 | + releaseListeners(); |
| 57 | + }; |
| 58 | + |
| 59 | + const releaseListeners = () => { |
| 60 | + socket.off("pong", handlePong); |
| 61 | + socket.off("close", handleClose); |
| 62 | + }; |
| 63 | + socket.on("pong", handlePong); |
| 64 | + socket.on("close", handleClose); |
| 65 | + |
| 66 | + // Schedule the first ping |
| 67 | + timer = setTimeout(sendPing, keepaliveInterval); |
| 68 | +} |
0 commit comments