import test from "node:test"; import assert from "node:assert/strict"; import { EventEmitter } from "node:events"; import { startWebSocketKeepalive, DEFAULT_WS_PING_INTERVAL_MS } from "../src/gateway/wsKeepalive.js"; class FakeSocket extends EventEmitter { constructor () { super(); this.isAlive = undefined; this.pingCount = 0; this.terminated = false; } ping () { this.pingCount += 1; } terminate () { this.terminated = true; } } class FakeWss extends EventEmitter { constructor () { super(); this.clients = new Set(); } } test("startWebSocketKeepalive pings open sockets and terminates stale ones", () => { const wss = new FakeWss(); const timers = []; const keepalive = startWebSocketKeepalive(wss, { intervalMs: 1000, setIntervalFn (fn, ms) { timers.push({ fn, ms }); return 1; }, clearIntervalFn () {} }); assert.equal(keepalive.intervalMs, 1000); assert.equal(DEFAULT_WS_PING_INTERVAL_MS, 25_000); assert.equal(timers.length, 1); const live = new FakeSocket(); const stale = new FakeSocket(); wss.clients.add(live); wss.clients.add(stale); wss.emit("connection", live); wss.emit("connection", stale); assert.equal(live.isAlive, true); assert.equal(stale.isAlive, true); live.emit("pong"); assert.equal(live.isAlive, true); // First tick: mark not alive and ping timers[0].fn(); assert.equal(live.isAlive, false); assert.equal(stale.isAlive, false); assert.equal(live.pingCount, 1); assert.equal(stale.pingCount, 1); assert.equal(stale.terminated, false); live.emit("pong"); assert.equal(live.isAlive, true); // Second tick: live gets pinged again; stale (no pong) is terminated timers[0].fn(); assert.equal(live.terminated, false); assert.equal(stale.terminated, true); assert.equal(live.pingCount, 2); keepalive.stop(); keepalive.stop(); // idempotent });