A modern and elegant dashboard for network traffic visualization and analysis.
fix(collector): add WebSocket heartbeat watchdog to detect dead connections
zj1123581321f5139b2efe28
diff --git a/apps/collector/src/modules/collector/gateway.collector.test.ts b/apps/collector/src/modules/collector/gateway.collector.test.tsnew file mode 100644index 0000000..e37e2d5--- /dev/null+++ b/apps/collector/src/modules/collector/gateway.collector.test.ts@@ -0,0 +1,98 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { WebSocketServer } from "ws";+import type { AddressInfo } from "node:net";+import { GatewayCollector } from "./gateway.collector.js";++describe("GatewayCollector heartbeat watchdog", () => {+ let servers: WebSocketServer[] = [];+ let collectors: GatewayCollector[] = [];++ const makeServer = () =>+ new Promise<WebSocketServer>((resolve) => {+ const wss = new WebSocketServer({ port: 0 });+ servers.push(wss);+ wss.on("listening", () => resolve(wss));+ });++ afterEach(async () => {+ for (const c of collectors) c.disconnect();+ collectors = [];+ await Promise.all(+ servers.map(+ (wss) =>+ new Promise<void>((r) => {+ // Force-close any client sockets first (a paused/half-dead socket+ // would otherwise keep wss.close() pending forever).+ for (const client of wss.clients) client.terminate();+ wss.close(() => r());+ }),+ ),+ );+ servers = [];+ });++ it("terminates and reconnects when the link goes silent (no data, no pong)", async () => {+ const wss = await makeServer();+ const port = (wss.address() as AddressInfo).port;++ let connectionCount = 0;+ wss.on("connection", (socket) => {+ connectionCount++;+ if (connectionCount === 1) {+ // Simulate a silently dropped TCP connection: stop reading the raw+ // socket so the server never auto-replies to pings and never sends+ // data, yet never emits a close/RST frame either. Without the+ // watchdog the client would stay "connected" forever.+ const raw = (socket as unknown as { _socket?: { pause(): void } })+ ._socket;+ raw?.pause();+ }+ });++ const collector = new GatewayCollector(1, {+ url: `ws://127.0.0.1:${port}`,+ reconnectInterval: 50,+ heartbeatInterval: 30,+ heartbeatTimeout: 90,+ });+ collectors.push(collector);+ collector.connect();++ // A reconnect (2nd connection) proves the dead first connection was+ // detected and torn down by the watchdog.+ await vi.waitFor(() => expect(connectionCount).toBeGreaterThanOrEqual(2), {+ timeout: 3000,+ interval: 25,+ });+ });++ it("keeps a healthy connection alive without spurious reconnects", async () => {+ const wss = await makeServer();+ const port = (wss.address() as AddressInfo).port;++ let connectionCount = 0;+ wss.on("connection", (socket) => {+ connectionCount++;+ // Healthy backend: stream data periodically. ws also auto-replies to+ // the client pings, so lastActivity stays fresh.+ const timer = setInterval(() => {+ socket.send(JSON.stringify({ connections: [] }));+ }, 20);+ socket.on("close", () => clearInterval(timer));+ });++ const collector = new GatewayCollector(2, {+ url: `ws://127.0.0.1:${port}`,+ reconnectInterval: 50,+ heartbeatInterval: 30,+ heartbeatTimeout: 90,+ });+ collectors.push(collector);+ collector.connect();++ await new Promise((r) => setTimeout(r, 400));+ // Still the original single connection: the watchdog must not tear down a+ // live link.+ expect(connectionCount).toBe(1);+ });+});diff --git a/apps/collector/src/modules/collector/gateway.collector.ts b/apps/collector/src/modules/collector/gateway.collector.tsindex 041ec3d..900791a 100644--- a/apps/collector/src/modules/collector/gateway.collector.ts+++ b/apps/collector/src/modules/collector/gateway.collector.ts@@ -10,10 +10,20 @@ import { BatchBuffer } from "./batch-buffer.js";const STALE_CONNECTION_TIMEOUT = 5 * 60 * 1000; // 5 minutesconst CLEANUP_INTERVAL = 2 * 60 * 1000; // 2 minutes+// Heartbeat watchdog: detect silently dropped TCP connections (gateway/router+// restart, NAT timeout) that never surface a WS "error"/"close" event. We ping+// the backend periodically and track when a frame last arrived; if the link+// stays silent past the timeout we force-terminate it so the existing+// reconnect logic kicks in. See issue #74.+const DEFAULT_HEARTBEAT_INTERVAL = 10_000; // ping + liveness check cadence (ms)+const DEFAULT_HEARTBEAT_TIMEOUT = 30_000; // terminate after this much silence (ms)+export interface CollectorOptions {url: string;token?: string;reconnectInterval?: number;+ heartbeatInterval?: number;+ heartbeatTimeout?: number;onData?: (data: ConnectionsData) => void;onError?: (error: Error) => void;}@@ -23,9 +33,13 @@ export class GatewayCollector {private url: string;private token?: string;private reconnectInterval: number;+ private heartbeatInterval: number;+ private heartbeatTimeout: number;private onData?: (data: ConnectionsData) => void;private onError?: (error: Error) => void;private reconnectTimer: NodeJS.Timeout | null = null;+ private heartbeatTimer: NodeJS.Timeout | null = null;+ private lastActivity = 0;private isClosing = false;private backendId: number;@@ -34,6 +48,16 @@ export class GatewayCollector {this.url = options.url;this.token = options.token;this.reconnectInterval = options.reconnectInterval || 5000;+ this.heartbeatInterval =+ options.heartbeatInterval ??+ parseInt(+ process.env.WS_HEARTBEAT_INTERVAL_MS || `${DEFAULT_HEARTBEAT_INTERVAL}`,+ );+ this.heartbeatTimeout =+ options.heartbeatTimeout ??+ parseInt(+ process.env.WS_HEARTBEAT_TIMEOUT_MS || `${DEFAULT_HEARTBEAT_TIMEOUT}`,+ );this.onData = options.onData;this.onError = options.onError;}@@ -60,9 +84,11 @@ export class GatewayCollector {this.ws.on("open", () => {console.log(`[Collector:${this.backendId}] WebSocket connected`);+ this.startHeartbeat();});this.ws.on("message", (data: WebSocket.Data) => {+ this.lastActivity = Date.now();try {const json = JSON.parse(data.toString()) as ConnectionsData;this.onData?.(json);@@ -74,6 +100,10 @@ export class GatewayCollector {}});+ this.ws.on("pong", () => {+ this.lastActivity = Date.now();+ });+this.ws.on("error", (err) => {console.error(`[Collector:${this.backendId}] WebSocket error:`,@@ -83,6 +113,7 @@ export class GatewayCollector {});this.ws.on("close", (code, reason) => {+ this.stopHeartbeat();console.log(`[Collector:${this.backendId}] WebSocket closed: ${code} ${reason}`,);@@ -92,6 +123,42 @@ export class GatewayCollector {});}+ private startHeartbeat() {+ this.stopHeartbeat();+ this.lastActivity = Date.now();+ this.heartbeatTimer = setInterval(() => {+ const ws = this.ws;+ if (!ws) return;++ const idle = Date.now() - this.lastActivity;+ if (idle > this.heartbeatTimeout) {+ console.warn(+ `[Collector:${this.backendId}] No data for ${idle}ms (timeout ` ++ `${this.heartbeatTimeout}ms); terminating dead connection`,+ );+ // terminate() forces an immediate close with no closing handshake and+ // emits "close", which runs scheduleReconnect().+ ws.terminate();+ return;+ }++ // Probe liveness; a live peer answers with a pong that refreshes+ // lastActivity. A half-dead socket stays silent and trips the timeout.+ try {+ ws.ping();+ } catch {+ // Socket already unusable; the timeout branch will reconnect it.+ }+ }, this.heartbeatInterval);+ }++ private stopHeartbeat() {+ if (this.heartbeatTimer) {+ clearInterval(this.heartbeatTimer);+ this.heartbeatTimer = null;+ }+ }+private scheduleReconnect() {if (this.reconnectTimer) return;console.log(@@ -105,6 +172,7 @@ export class GatewayCollector {disconnect() {this.isClosing = true;+ this.stopHeartbeat();if (this.reconnectTimer) {clearTimeout(this.reconnectTimer);this.reconnectTimer = null;