fix(onebot): apply the transport heartbeat to the reverse-WS server too

Symmetric with the ws-client fix (#208): the reverse-WS server now pings each
attached client and terminates one that goes fully silent for ~90s (2 unanswered
pings), reaping a half-open client that would otherwise linger in the connection
set. Reuses startHeartbeat with the same conservative, activity-reset tolerance,
so a client with live traffic is never dropped. The per-connection stop is kept
on the ForwardConn entry and cleared in both close() and the socket 'close'
handler; no shared instance state, so the #97 overlap does not apply here.
This commit is contained in:
DrSmoothl
2026-07-07 21:20:19 +08:00
parent c09c6e0883
commit 1914807770
2 changed files with 174 additions and 4 deletions
@@ -9,14 +9,22 @@ import {
} from '../event-filter';
import type { JsonObject, WsRole, WsServerNetwork } from '../types';
import { IOneBotNetworkAdapter, type AdapterStatus, type NetworkAdapterContext } from './adapter';
import { isAuthorized, normalizePath, parseRequestPath, rawDataToString, safeClose, safeSend, safeSendAsync } from './utils';
import { isAuthorized, normalizePath, parseRequestPath, rawDataToString, safeClose, safeSend, safeSendAsync, startHeartbeat } from './utils';
const moduleLog = createLogger('OneBot.WS-Server');
// Transport keepalive for each attached client, symmetric with the ws-client
// adapter: ping every 30s, reap a client only after 2 consecutive pings go
// unanswered — ~90s of total silence (see startHeartbeat for the +1-interval
// timing). Any inbound frame resets the counter — 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;
interface ForwardConn {
socket: WebSocket;
role: WsRole;
options: EventReportOptions;
stopHeartbeat: () => void;
}
export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
@@ -50,7 +58,10 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
this.isEnabled = false;
this.listening = false;
for (const ws of [...this.connections.keys()]) safeClose(ws);
for (const conn of this.connections.values()) {
conn.stopHeartbeat();
safeClose(conn.socket);
}
this.connections.clear();
this.wss?.close();
this.wss = null;
@@ -115,7 +126,15 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
}
const role = this.config.role ?? classifyForwardRole(request);
const conn: ForwardConn = { socket, role, options: this.options };
const stopHeartbeat = startHeartbeat(
socket,
{ intervalMs: HEARTBEAT_INTERVAL_MS, maxMissed: HEARTBEAT_MAX_MISSED },
() => {
this.log.warn('[%s] client silent for ~%ds, terminating half-open connection', this.name, HEARTBEAT_DEAD_AFTER_S);
socket.terminate(); // → 'close' → connections.delete; the client reconnects on its own
},
);
const conn: ForwardConn = { socket, role, options: this.options, stopHeartbeat };
this.connections.set(socket, conn);
socket.on('message', (raw: Buffer) => {
@@ -123,7 +142,10 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
this.log.warn('[%s] handleApiMessage threw: %s', this.name, err instanceof Error ? (err.stack ?? err.message) : String(err));
});
});
socket.on('close', () => this.connections.delete(socket));
socket.on('close', () => {
stopHeartbeat();
this.connections.delete(socket);
});
socket.on('error', (err: Error) => {
this.log.warn('[%s] socket error: %s', this.name, err instanceof Error ? err.message : String(err));
});
@@ -0,0 +1,148 @@
// Issue #208 (server side): symmetric transport keepalive for the reverse-WS
// SERVER. Each attached client is pinged; a client that goes fully silent for
// maxMissed consecutive intervals is terminated (and drops out of the
// connection set) so a half-open client can't wedge forever. A healthy or
// actively-messaging client must never be reaped — the same false-positive
// guard as the client adapter.
//
// Mock `@snowluma/websocket` (native addon isn't built in a plain checkout),
// mirroring network-bootstrap-meta.test.ts. Timers are faked and driven.
import { beforeEach, describe, expect, it, vi } from 'vitest';
const { FakeWebSocket, FakeWebSocketServer, servers } = vi.hoisted(() => {
// eslint-disable-next-line @typescript-eslint/no-require-imports
const { EventEmitter } = require('node:events') as typeof import('node:events');
const servers: FakeWebSocketServer[] = [];
class FakeWebSocket extends EventEmitter {
public readyState = 1; // OPEN
public pings = 0;
public terminated = false;
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');
}
close(): void { if (this.readyState < 2) this.readyState = 2; }
simulatePong(): void { this.emit('pong', Buffer.alloc(0)); }
simulateMessage(): void { this.emit('message', Buffer.from('{}'), false); }
}
class FakeWebSocketServer extends EventEmitter {
public closed = false;
constructor(_opts: unknown) { super(); servers.push(this); }
close(): void { this.closed = true; }
simulateConnection(socket: FakeWebSocket, request: unknown): void {
this.emit('connection', socket, request);
}
}
return { FakeWebSocket, FakeWebSocketServer, servers };
});
vi.mock('@snowluma/websocket', () => ({
WebSocket: FakeWebSocket,
WebSocketServer: FakeWebSocketServer,
}));
import { WsServerAdapter } from '../src/network/ws-server-adapter';
import type { NetworkAdapterContext } from '../src/network/adapter';
import type { WsServerNetwork } from '../src/types';
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<WsServerNetwork> = {}): WsServerNetwork {
return { enabled: true, host: '0.0.0.0', port: 8080, path: '/', role: 'Universal', ...over } as WsServerNetwork;
}
const REQUEST = { url: '/', headers: {} } as unknown;
function connect(): { adapter: WsServerAdapter; socket: InstanceType<typeof FakeWebSocket> } {
const adapter = new WsServerAdapter('ws', cfg(), ctx());
adapter.open();
const server = servers[servers.length - 1];
server.emit('listening'); // adapter marks itself listening → status 'ok'
const socket = new FakeWebSocket();
server.simulateConnection(socket, REQUEST);
return { adapter, socket };
}
describe('WsServerAdapter — transport heartbeat (issue #208)', () => {
beforeEach(() => { servers.length = 0; });
it('reaps a silent client only after maxMissed intervals, then drops it', () => {
vi.useFakeTimers();
try {
const { adapter, socket } = connect();
expect(adapter.describeStatus().detail).toBe('1 个客户端');
vi.advanceTimersByTime(INTERVAL * MAX_MISSED); // tolerated
expect(socket.terminated).toBe(false);
vi.advanceTimersByTime(INTERVAL); // threshold crossed
expect(socket.terminated).toBe(true);
expect(adapter.describeStatus().detail).toBe('0 个客户端');
} finally {
vi.useRealTimers();
}
});
it('never reaps a client that keeps ponging', () => {
vi.useFakeTimers();
try {
const { adapter, socket } = connect();
for (let i = 0; i < 10; i++) {
vi.advanceTimersByTime(INTERVAL);
socket.simulatePong();
}
expect(socket.terminated).toBe(false);
expect(adapter.describeStatus().detail).toBe('1 个客户端');
expect(socket.pings).toBeGreaterThan(0);
} finally {
vi.useRealTimers();
}
});
it('treats inbound messages as liveness', () => {
vi.useFakeTimers();
try {
const { adapter, socket } = connect();
for (let i = 0; i < 10; i++) {
vi.advanceTimersByTime(INTERVAL);
socket.simulateMessage();
}
expect(socket.terminated).toBe(false);
expect(adapter.describeStatus().detail).toBe('1 个客户端');
} finally {
vi.useRealTimers();
}
});
it('stops all client heartbeats on adapter close — no lingering pings', () => {
vi.useFakeTimers();
try {
const { adapter, socket } = connect();
adapter.close();
const pingsAtClose = socket.pings;
vi.advanceTimersByTime(INTERVAL * 5);
expect(socket.pings).toBe(pingsAtClose);
expect(socket.terminated).toBe(false); // closed cleanly, not reaped
} finally {
vi.useRealTimers();
}
});
});