| 1 | import test from "node:test"; |
| 2 | import assert from "node:assert/strict"; |
| 3 | import { EventEmitter } from "node:events"; |
| 4 | import { |
| 5 | startWebSocketKeepalive, |
| 6 | DEFAULT_WS_PING_INTERVAL_MS |
| 7 | } from "../src/gateway/wsKeepalive.js"; |
| 8 | |
| 9 | class FakeSocket extends EventEmitter |
| 10 | { |
| 11 | constructor () |
| 12 | { |
| 13 | super(); |
| 14 | this.isAlive = undefined; |
| 15 | this.pingCount = 0; |
| 16 | this.terminated = false; |
| 17 | } |
| 18 | |
| 19 | ping () |
| 20 | { |
| 21 | this.pingCount += 1; |
| 22 | } |
| 23 | |
| 24 | terminate () |
| 25 | { |
| 26 | this.terminated = true; |
| 27 | } |
| 28 | } |
| 29 | |
| 30 | class FakeWss extends EventEmitter |
| 31 | { |
| 32 | constructor () |
| 33 | { |
| 34 | super(); |
| 35 | this.clients = new Set(); |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | test("startWebSocketKeepalive pings open sockets and terminates stale ones", () => |
| 40 | { |
| 41 | const wss = new FakeWss(); |
| 42 | const timers = []; |
| 43 | const keepalive = startWebSocketKeepalive(wss, { |
| 44 | intervalMs: 1000, |
| 45 | setIntervalFn (fn, ms) |
| 46 | { |
| 47 | timers.push({ fn, ms }); |
| 48 | return 1; |
| 49 | }, |
| 50 | clearIntervalFn () {} |
| 51 | }); |
| 52 | assert.equal(keepalive.intervalMs, 1000); |
| 53 | assert.equal(DEFAULT_WS_PING_INTERVAL_MS, 25_000); |
| 54 | assert.equal(timers.length, 1); |
| 55 | |
| 56 | const live = new FakeSocket(); |
| 57 | const stale = new FakeSocket(); |
| 58 | wss.clients.add(live); |
| 59 | wss.clients.add(stale); |
| 60 | wss.emit("connection", live); |
| 61 | wss.emit("connection", stale); |
| 62 | assert.equal(live.isAlive, true); |
| 63 | assert.equal(stale.isAlive, true); |
| 64 | |
| 65 | live.emit("pong"); |
| 66 | assert.equal(live.isAlive, true); |
| 67 | |
| 68 | // First tick: mark not alive and ping |
| 69 | timers[0].fn(); |
| 70 | assert.equal(live.isAlive, false); |
| 71 | assert.equal(stale.isAlive, false); |
| 72 | assert.equal(live.pingCount, 1); |
| 73 | assert.equal(stale.pingCount, 1); |
| 74 | assert.equal(stale.terminated, false); |
| 75 | |
| 76 | live.emit("pong"); |
| 77 | assert.equal(live.isAlive, true); |
| 78 | |
| 79 | // Second tick: live gets pinged again; stale (no pong) is terminated |
| 80 | timers[0].fn(); |
| 81 | assert.equal(live.terminated, false); |
| 82 | assert.equal(stale.terminated, true); |
| 83 | assert.equal(live.pingCount, 2); |
| 84 | |
| 85 | keepalive.stop(); |
| 86 | keepalive.stop(); // idempotent |
| 87 | }); |