fix(onebot): heal half-open reverse-WS client with a transport heartbeat

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'.
This commit is contained in:
DrSmoothl committed 2026-07-07 21:20:07 +08:00
1 parent fd57eb4b6f
commit c09c6e0883
3 files changed
+326 -1

No files matched your search

+62
View File
@@ -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 '/';
@@ -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<WsClientNetwork> {
private socket: WebSocket | null = null;
@@ -20,6 +27,11 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
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<WsClientNetwork> {
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<WsClientNetwork> {
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<WsClientNetwork> {
});
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