From c09c6e0883eeeaf28fda1c27d56f01ba997d116f Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Tue, 7 Jul 2026 21:20:07 +0800 Subject: [PATCH] fix(onebot): heal half-open reverse-WS client with a transport heartbeat MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A reverse-WS client could end up half-open after the peer restarted: still writable (events kept flowing out) but no longer readable, so inbound action frames silently never arrived and only a full restart recovered it (#208). The OneBot app-level meta heartbeat is a one-way push and cannot detect this. Add an RFC6455 ping/pong keepalive (startHeartbeat) wired into the ws-client adapter. It pings every 30s and declares the link dead only after 2 unanswered pings (~90s of total silence), then terminates the socket so the existing reconnect path runs. Any inbound activity — a pong OR a message — resets the counter, so a connection carrying real traffic is never reaped; the conservative tolerance keeps the false-positive rate near zero (a GC pause or latency spike is absorbed). The stop is per-socket and also held on the instance so close()/reload halt it immediately rather than waiting for the deferred 'close'; a symmetric identity guard on 'open' mirrors the #97 stale-socket guard on 'close'. --- packages/onebot/src/network/utils.ts | 62 +++++ .../onebot/src/network/ws-client-adapter.ts | 40 +++- .../onebot/tests/ws-client-heartbeat.test.ts | 225 ++++++++++++++++++ 3 files changed, 326 insertions(+), 1 deletion(-) create mode 100644 packages/onebot/tests/ws-client-heartbeat.test.ts diff --git a/packages/onebot/src/network/utils.ts b/packages/onebot/src/network/utils.ts index 64458964..d4e3d13b 100644 --- a/packages/onebot/src/network/utils.ts +++ b/packages/onebot/src/network/utils.ts @@ -49,6 +49,68 @@ export function safeClose(socket: WebSocket, code = 1000, reason = 'normal'): vo socket.close(code, reason); } +/** RFC6455 transport-level keepalive for a reverse-WS connection. + * + * The OneBot app-level `meta_event` heartbeat is a one-way outbound push, so it + * cannot detect a connection that is writable but no longer readable — a + * half-open link left behind when the peer restarts behind a proxy/NAT. In that + * state events keep flowing out while inbound action frames silently never + * arrive, and only a full restart recovers it (issue #208). + * + * This pings every `intervalMs` and counts consecutive silent intervals. ANY + * inbound activity — a pong OR a message — resets the counter, so a connection + * carrying real traffic is never reaped. Death is declared once `maxMissed` + * pings have gone unanswered, i.e. after roughly `(maxMissed + 1) * intervalMs` + * of total silence (the counter is checked at the top of each tick, so the + * tick that observes the threshold is one interval past the last ping). The + * tolerance plus a conservative interval keeps the false-positive rate near + * zero: a single GC pause, event-loop stall, or transient latency spike is + * absorbed (Node fires an overdue interval once, not N catch-up times), and + * death is declared only on genuine sustained silence. + * + * Returns an idempotent stop function; the timer is `unref`'d so it never keeps + * the process alive. */ +export function startHeartbeat( + socket: WebSocket, + opts: { intervalMs: number; maxMissed: number }, + onDead: () => void, +): () => void { + let missed = 0; + let stopped = false; + const onActivity = (): void => { missed = 0; }; + socket.on('pong', onActivity); + socket.on('message', onActivity); + + const timer = setInterval(() => { + if (missed >= opts.maxMissed) { + // `maxMissed` consecutive intervals with zero inbound traffic — the read + // direction is dead. Stop first so onDead()'s terminate→close→reconnect + // can't re-enter this tick. + stop(); + onDead(); + return; + } + missed += 1; + try { + socket.ping(); + } catch { + // Ping on an already-dead socket — treat as dead immediately. + stop(); + onDead(); + } + }, opts.intervalMs); + timer.unref?.(); + + function stop(): void { + if (stopped) return; + stopped = true; + clearInterval(timer); + socket.off?.('pong', onActivity); + socket.off?.('message', onActivity); + } + return stop; +} + export function normalizePath(pathValue: string | undefined): string { const path = (pathValue ?? '/').trim() || '/'; if (path === '/') return '/'; diff --git a/packages/onebot/src/network/ws-client-adapter.ts b/packages/onebot/src/network/ws-client-adapter.ts index 59682996..910e1495 100644 --- a/packages/onebot/src/network/ws-client-adapter.ts +++ b/packages/onebot/src/network/ws-client-adapter.ts @@ -8,10 +8,17 @@ import { } from '../event-filter'; import type { JsonObject, WsClientNetwork, WsRole } from '../types'; import { IOneBotNetworkAdapter, type AdapterStatus, type NetworkAdapterContext } from './adapter'; -import { rawDataToString, safeClose, safeSend, safeSendAsync } from './utils'; +import { rawDataToString, safeClose, safeSend, safeSendAsync, startHeartbeat } from './utils'; const moduleLog = createLogger('OneBot.WS-Client'); const DEFAULT_RECONNECT_INTERVAL_MS = 5000; +// Transport-level keepalive: ping every 30s, declare the link dead only after 2 +// consecutive pings go unanswered — ~90s of total silence (see startHeartbeat +// for the +1-interval timing). Conservative on purpose so transient jitter/GC +// never reaps a healthy connection. See issue #208. +const HEARTBEAT_INTERVAL_MS = 30_000; +const HEARTBEAT_MAX_MISSED = 2; +const HEARTBEAT_DEAD_AFTER_S = (HEARTBEAT_INTERVAL_MS * (HEARTBEAT_MAX_MISSED + 1)) / 1000; export class WsClientAdapter extends IOneBotNetworkAdapter { private socket: WebSocket | null = null; @@ -20,6 +27,11 @@ export class WsClientAdapter extends IOneBotNetworkAdapter { private options: EventReportOptions; private role: WsRole; private explicitlyClosed = false; + // Stop fn for the CURRENT socket's keepalive, so close()/reload can halt it + // immediately instead of waiting for the deferred 'close' event. The per-socket + // closure in connect() still owns the #97 stale-socket case; this is idempotent + // with it (both call the same stop). + private heartbeatStop: (() => void) | null = null; constructor(name: string, config: WsClientNetwork, ctx: NetworkAdapterContext) { super(name, config, ctx, moduleLog); @@ -41,6 +53,8 @@ export class WsClientAdapter extends IOneBotNetworkAdapter { this.isEnabled = false; this.connected = false; this.cancelReconnect(); + this.heartbeatStop?.(); + this.heartbeatStop = null; if (this.socket) { safeClose(this.socket); this.socket = null; @@ -90,11 +104,30 @@ export class WsClientAdapter extends IOneBotNetworkAdapter { const socket = new WebSocket(this.config.url, { headers }); this.socket = socket; + // Per-socket so a hot-reload overlap (old close firing after the new socket + // is assigned, see #97) can only ever stop its own keepalive. + let stopHeartbeat: (() => void) | null = null; socket.on('open', () => { + // Symmetric with the 'close' guard (#97): if this socket was already + // replaced, a late 'open' must not flip `connected` or install a stale + // heartbeat onto the current connection's slot. + if (this.socket !== socket) return; this.connected = true; this.log.info('[%s] connected %s', this.name, this.config.url); this.sendBootstrapMetaEvents(socket); + // Only meaningful once OPEN — ping() no-ops before the handshake completes. + stopHeartbeat = startHeartbeat( + socket, + { intervalMs: HEARTBEAT_INTERVAL_MS, maxMissed: HEARTBEAT_MAX_MISSED }, + () => { + if (this.explicitlyClosed || !this.isEnabled) return; + this.log.warn('[%s] no inbound response for ~%ds, reconnecting half-open connection %s', this.name, HEARTBEAT_DEAD_AFTER_S, this.config.url); + // terminate → 'close' → scheduleReconnect, reusing the normal path. + socket.terminate(); + }, + ); + this.heartbeatStop = stopHeartbeat; }); socket.on('message', (raw: Buffer) => { @@ -104,6 +137,11 @@ export class WsClientAdapter extends IOneBotNetworkAdapter { }); socket.on('close', () => { + stopHeartbeat?.(); + // Drop the instance handle only if it still points at THIS socket's stop + // (a newer socket may already own it after a hot-reload overlap). + if (this.heartbeatStop === stopHeartbeat) this.heartbeatStop = null; + stopHeartbeat = null; // Ignore close events from a socket that is no longer the current // connection. A hot reload (signature change) calls close() then open() // back-to-back; the old socket's `'close'` event fires AFTER the new diff --git a/packages/onebot/tests/ws-client-heartbeat.test.ts b/packages/onebot/tests/ws-client-heartbeat.test.ts new file mode 100644 index 00000000..2930d08e --- /dev/null +++ b/packages/onebot/tests/ws-client-heartbeat.test.ts @@ -0,0 +1,225 @@ +// Issue #208: after a reverse-WS reconnect the link could end up half-open — +// writable (events keep flowing out) but not readable (inbound action frames +// never arrive), a state only a full restart recovered. The fix adds a +// transport-level ping/pong keepalive that reconnects a genuinely silent link. +// +// These tests pin BOTH sides of the contract: it must reconnect a dead link, +// and — the harder half — it must NOT reap a healthy one. The false-positive +// guards are the point: death is declared only after `maxMissed` consecutive +// intervals with zero inbound traffic (pong OR message), so pong round-trips +// and live message flow both keep a connection alive indefinitely. +// +// Mock `@snowluma/websocket` (native addon isn't built in a plain checkout), +// mirroring ws-client-stale-close.test.ts. Timers are faked and driven. + +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +const { FakeWebSocket, instances } = vi.hoisted(() => { + // eslint-disable-next-line @typescript-eslint/no-require-imports + const { EventEmitter } = require('node:events') as typeof import('node:events'); + const instances: FakeWebSocket[] = []; + + class FakeWebSocket extends EventEmitter { + public readyState = 1; // 1 = OPEN, 2 = CLOSING, 3 = CLOSED + public pings = 0; + public terminated = false; + public readonly url: string; + + constructor(url: string, _opts: unknown) { + super(); + this.url = url; + instances.push(this); + } + + send(_payload: string, cb?: (err?: Error | null) => void): void { cb?.(null); } + ping(): void { this.pings += 1; } + terminate(): void { + if (this.readyState === 3) return; + this.terminated = true; + this.readyState = 3; + this.emit('close'); // real terminate → destroy → deferred 'close'; sync here + } + close(code = 1000, reason = 'normal'): void { + void code; void reason; + if (this.readyState >= 2) return; + this.readyState = 2; // do NOT auto-emit 'close' (matches the real deferral) + } + + simulateOpen(): void { this.emit('open'); } + simulatePong(): void { this.emit('pong', Buffer.alloc(0)); } + simulateMessage(): void { this.emit('message', Buffer.from('{}'), false); } + simulateClose(): void { this.readyState = 3; this.emit('close'); } + } + + return { FakeWebSocket, instances }; +}); + +vi.mock('@snowluma/websocket', () => ({ WebSocket: FakeWebSocket })); + +import { WsClientAdapter } from '../src/network/ws-client-adapter'; +import type { NetworkAdapterContext } from '../src/network/adapter'; +import type { WsClientNetwork } from '../src/types'; + +// Must match the adapter's module constants. +const INTERVAL = 30_000; +const MAX_MISSED = 2; + +function ctx(): NetworkAdapterContext { + return { + uin: '10001', + api: { processStreamRequest: async () => {} } as never, + buildLifecycleEvent: () => ({}), + buildHeartbeatEvent: () => ({}), + }; +} + +function cfg(over: Partial = {}): WsClientNetwork { + return { + enabled: true, + url: 'ws://127.0.0.1:8080/', + role: 'Universal', + reconnectIntervalMs: 1000, + ...over, + } as WsClientNetwork; +} + +describe('WsClientAdapter — transport heartbeat (issue #208)', () => { + beforeEach(() => { instances.length = 0; }); + + it('reconnects a silent (half-open) connection, but only after maxMissed intervals', () => { + vi.useFakeTimers(); + try { + const adapter = new WsClientAdapter('ws', cfg(), ctx()); + adapter.open(); + const a = instances[0]; + a.simulateOpen(); + + // maxMissed silent intervals are TOLERATED — the counter absorbs transient + // jitter/GC without reaping. Still alive here. + vi.advanceTimersByTime(INTERVAL * MAX_MISSED); + expect(a.terminated).toBe(false); + expect(instances).toHaveLength(1); + + // The next silent interval crosses the threshold: terminate → 'close' → + // scheduleReconnect (no new socket until the reconnect interval elapses). + vi.advanceTimersByTime(INTERVAL); + expect(a.terminated).toBe(true); + expect(instances).toHaveLength(1); + + vi.advanceTimersByTime(1000); + expect(instances).toHaveLength(2); // reconnect spun up a fresh socket + expect(instances[1]).not.toBe(a); + } finally { + vi.useRealTimers(); + } + }); + + it('never reaps a healthy connection whose pong lags a full interval', () => { + vi.useFakeTimers(); + try { + const adapter = new WsClientAdapter('ws', cfg(), ctx()); + adapter.open(); + const a = instances[0]; + a.simulateOpen(); + + // Each cycle lets TWO intervals pass with no pong (missed climbs 0→1→2) + // before a pong arrives, so a non-zero `missed` is carried across a check + // boundary. A broken 1-strike (`missed >= 1`) impl reaps on the 2nd tick; + // the real 2-strike tolerance survives (the fatal `>= 2` check never sees + // 2 because the pong resets first). + for (let i = 0; i < 10; i++) { + vi.advanceTimersByTime(INTERVAL); // silent tick → missed = 1 + vi.advanceTimersByTime(INTERVAL); // silent tick → missed = 2 (still alive) + a.simulatePong(); // pong resets missed → 0 + } + + expect(a.terminated).toBe(false); + expect(instances).toHaveLength(1); + expect(a.pings).toBeGreaterThan(0); // it WAS actively probing + } finally { + vi.useRealTimers(); + } + }); + + it('treats inbound message traffic as liveness (no pong needed)', () => { + vi.useFakeTimers(); + try { + const adapter = new WsClientAdapter('ws', cfg(), ctx()); + adapter.open(); + const a = instances[0]; + a.simulateOpen(); + + // No pongs at all, but a message arrives every interval. A busy link is + // provably alive, so it must never be reaped. + for (let i = 0; i < 10; i++) { + vi.advanceTimersByTime(INTERVAL); + a.simulateMessage(); + } + + expect(a.terminated).toBe(false); + expect(instances).toHaveLength(1); + } finally { + vi.useRealTimers(); + } + }); + + it('close() proactively stops the heartbeat — no lingering pings on the socket', () => { + vi.useFakeTimers(); + try { + const adapter = new WsClientAdapter('ws', cfg(), ctx()); + adapter.open(); + const a = instances[0]; + a.simulateOpen(); + vi.advanceTimersByTime(INTERVAL); // one real tick → a.pings === 1 + + // close() must halt the keepalive immediately, NOT wait for the deferred + // 'close' event (a real ws defers it). No further pings, no reap. + adapter.close(); + const pingsAtClose = a.pings; + vi.advanceTimersByTime(INTERVAL * 5); + expect(a.pings).toBe(pingsAtClose); + expect(a.terminated).toBe(false); + expect(adapter.describeStatus().status).toBe('disabled'); + } finally { + vi.useRealTimers(); + } + }); + + it('a hot-reload does not let the old socket heartbeat reap the new one (#97 + #208)', async () => { + vi.useFakeTimers(); + try { + const adapter = new WsClientAdapter('ws', cfg(), ctx()); + adapter.open(); + const a = instances[0]; + a.simulateOpen(); + vi.advanceTimersByTime(INTERVAL); // a's heartbeat has ticked once + + // Hot reload (URL change) → base class close() then open(); close() stops + // a's heartbeat proactively before b is created. + await adapter.reload(cfg({ url: 'ws://127.0.0.1:8081/' })); + expect(instances).toHaveLength(2); + const b = instances[1]; + b.simulateOpen(); + + const aPingsAfterReload = a.pings; + // Advance well past a's would-be death window. a's heartbeat was stopped by + // the reload, so it never pings/terminates; b keeps its own healthy loop. + for (let i = 0; i < 6; i++) { + vi.advanceTimersByTime(INTERVAL); + b.simulatePong(); + } + // Stale socket's delayed close finally lands — must not disturb b. + a.simulateClose(); + vi.advanceTimersByTime(INTERVAL); + b.simulatePong(); // b stays healthy through the stale event + + expect(a.pings).toBe(aPingsAfterReload); // a's timer never fired again + expect(a.terminated).toBe(false); + expect(b.terminated).toBe(false); + expect(instances).toHaveLength(2); // no stray reconnect socket + expect(adapter.describeStatus().status).toBe('ok'); + } finally { + vi.useRealTimers(); + } + }); +});