feat(bridge): detect stalled receive paths
Arm receive monitoring only after an existing QQ heartbeat has been observed, preserving compatibility with sessions that do not expose the signal. Require 90 seconds of receive silence plus a 15-second confirmation window before reporting degradation. Any later inbound frame refreshes or restores health, including non-routable frames that still prove the receive path is alive. Bind watchdog state to the active account epoch so direct login switches and packet-driven account migration cannot inherit stale deadlines from a previous account. Forward health transitions to the bridge layer without reconnecting, reinjecting, or otherwise changing session recovery behavior. Add regression coverage for arming, recovery, sleep-resume confirmation, account migration, and invalid-UIN frames. Refs #233.
This commit is contained in:
4 files changed
+313
-3
No files matched your search
@@ -29,6 +29,7 @@ export interface BridgeManagerSink {
|
||||
onHookLogin(pid: number, uin: string, packetClient: PacketSender): void;
|
||||
onPacket(pkt: PacketInfo): void;
|
||||
onPidDisconnected(pid: number): void;
|
||||
onPidReceiveHealthChanged(pid: number, healthy: boolean): void;
|
||||
}
|
||||
|
||||
export type HookManagerDeps = {
|
||||
@@ -68,7 +69,7 @@ export type HookManagerDeps = {
|
||||
* Responsibilities:
|
||||
* - Route user commands (load/unload/refresh) to the matching session.
|
||||
* - Route watcher diff events to the matching session.
|
||||
* - Forward session events ('login' / 'disconnected') to BridgeManager.
|
||||
* - Forward session events ('login' / 'disconnected' / receive health) to BridgeManager.
|
||||
* - Retry stuck-in-connecting sessions on every watcher tick (so a
|
||||
* failed connect eventually recovers without a manual refresh).
|
||||
*
|
||||
@@ -297,6 +298,9 @@ export class HookManager {
|
||||
session.on('disconnected', (wasLoggedIn: boolean) => {
|
||||
if (wasLoggedIn) this.bridgeManager.onPidDisconnected(pid);
|
||||
});
|
||||
session.on('receive-health-changed', (healthy: boolean) => {
|
||||
this.bridgeManager.onPidReceiveHealthChanged(pid, healthy);
|
||||
});
|
||||
// status-changed fires on EVERY internal status mutation, including the
|
||||
// ones reached via login / disconnected / refresh — subscribing here
|
||||
// alone covers every transition the WebUI processes view cares about.
|
||||
|
||||
@@ -14,6 +14,14 @@ import type { HookProcessInfo, HookProcessStatus } from './types';
|
||||
* auto-login races/bypasses the pushed loginState frame). */
|
||||
const LOGIN_RECONCILE_INTERVAL_MS = 3000;
|
||||
|
||||
/** QQ emits this response periodically while its MSF receive path is healthy.
|
||||
* Seeing it once arms the watchdog; before that, silence is UNKNOWN rather
|
||||
* than unhealthy so QQ versions that do not expose this command cannot be
|
||||
* false-flagged. Any later recv packet proves the same end-to-end path. */
|
||||
const QQ_RECV_HEARTBEAT_CMD = 'trpc.qq_new_tech.status_svc.StatusService.SsoHeartBeat';
|
||||
const RECEIVE_STALE_AFTER_MS = 90_000;
|
||||
const RECEIVE_STALE_CONFIRM_MS = 15_000;
|
||||
|
||||
export type HookSessionDeps = {
|
||||
injector: {
|
||||
inject: (pid: number) => HookInjectResult;
|
||||
@@ -53,6 +61,7 @@ export type HookSessionDeps = {
|
||||
* Emitted events:
|
||||
* 'login' (uin, packetSender) — real-UIN login detected
|
||||
* 'disconnected' (wasLoggedIn) — connection dropped or torn down
|
||||
* 'receive-health-changed' (healthy) — receive path confirmed stale/recovered
|
||||
* 'status-changed' (status, error) — status field mutated
|
||||
* 'disposed' () — session stopped tracking this PID
|
||||
*/
|
||||
@@ -84,6 +93,11 @@ export class HookSession extends EventEmitter {
|
||||
private disposed = false;
|
||||
private loginProbeTimer: ReturnType<typeof setInterval> | null = null;
|
||||
private probing = false;
|
||||
private _receiveHealthy = true;
|
||||
private receiveWatchUin = '';
|
||||
private receiveWatchArmed = false;
|
||||
private receiveWatchTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private lastReceiveAt = 0;
|
||||
|
||||
constructor(pid: number, deps: HookSessionDeps) {
|
||||
super();
|
||||
@@ -103,6 +117,7 @@ export class HookSession extends EventEmitter {
|
||||
get uin(): string { return this._uin; }
|
||||
get method(): string { return this._method; }
|
||||
get isDisposed(): boolean { return this.disposed; }
|
||||
get receiveHealthy(): boolean { return this._receiveHealthy; }
|
||||
|
||||
attachProcessInfo(info: { name?: string; path?: string }): void {
|
||||
if (info.name) this._name = info.name;
|
||||
@@ -404,6 +419,7 @@ export class HookSession extends EventEmitter {
|
||||
|
||||
private tearDownClient(): void {
|
||||
this.stopLoginReconcile();
|
||||
this.resetReceiveWatch();
|
||||
const client = this.client;
|
||||
if (client) {
|
||||
client.removeAllListeners();
|
||||
@@ -423,7 +439,14 @@ export class HookSession extends EventEmitter {
|
||||
this.loggedIn = state.loggedIn && isRealUin(this._uin);
|
||||
// However login was observed (pushed frame or the active probe), the
|
||||
// safety net's job is done.
|
||||
if (this.loggedIn) this.stopLoginReconcile();
|
||||
if (this.loggedIn) {
|
||||
this.stopLoginReconcile();
|
||||
// A PID can switch accounts without an intermediate logout edge. Never
|
||||
// carry the previous account's heartbeat deadline into the new epoch.
|
||||
if (this.receiveWatchUin !== this._uin) this.resetReceiveWatch(this._uin);
|
||||
} else {
|
||||
this.resetReceiveWatch();
|
||||
}
|
||||
|
||||
// Only the connected/logged-in states are ours to set here; when fully
|
||||
// down we leave the status the teardown path already settled.
|
||||
@@ -494,6 +517,11 @@ export class HookSession extends EventEmitter {
|
||||
private handlePacket(packet: QqHookPacket): void {
|
||||
if (!this.loggedIn) return;
|
||||
const uin = packet.uin || this._uin;
|
||||
// Routing requires a real UIN, but even a frame carrying UIN=0 proves the
|
||||
// receive hook is alive. Attribute that evidence to the current epoch
|
||||
// without forwarding the malformed packet into BridgeManager.
|
||||
const receiveUin = isRealUin(uin) ? uin : (this.receiveWatchUin || this._uin);
|
||||
if (isRealUin(receiveUin)) this.noteReceiveActivity(packet.cmd, receiveUin);
|
||||
if (!isRealUin(uin)) return;
|
||||
if (!this.onPacket) return;
|
||||
// Re-shape the hook-client wire packet into BridgeManager's PacketInfo
|
||||
@@ -517,6 +545,85 @@ export class HookSession extends EventEmitter {
|
||||
this._error = error;
|
||||
this.emit('status-changed', status, error);
|
||||
}
|
||||
|
||||
private noteReceiveActivity(cmd: string, uin: string): void {
|
||||
// BridgeManager treats packet.uin as authoritative and may move this PID
|
||||
// before the next loginState edge. Keep the watchdog on that same epoch.
|
||||
if (this.receiveWatchUin !== uin) this.resetReceiveWatch(uin);
|
||||
|
||||
if (!this.receiveWatchArmed) {
|
||||
if (cmd !== QQ_RECV_HEARTBEAT_CMD) return;
|
||||
this.receiveWatchArmed = true;
|
||||
this.log.debug('receive health armed by QQ heartbeat: PID=%d UIN=%s', this.pid, this.receiveWatchUin);
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
const silentForMs = this.lastReceiveAt > 0 ? now - this.lastReceiveAt : 0;
|
||||
this.lastReceiveAt = now;
|
||||
this.scheduleReceiveStaleCheck();
|
||||
|
||||
if (!this._receiveHealthy) {
|
||||
this.setReceiveHealthy(true);
|
||||
this.log.info(
|
||||
'receive path recovered: PID=%d UIN=%s silentFor=%dms',
|
||||
this.pid,
|
||||
this.receiveWatchUin,
|
||||
silentForMs,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private scheduleReceiveStaleCheck(): void {
|
||||
if (this.receiveWatchTimer) clearTimeout(this.receiveWatchTimer);
|
||||
this.receiveWatchTimer = setTimeout(() => {
|
||||
this.receiveWatchTimer = null;
|
||||
if (!this.shouldWatchReceive()) return;
|
||||
|
||||
// A delayed event loop (notably system sleep/resume) lands here long
|
||||
// after the nominal 90s deadline. Do not flip health immediately: give
|
||||
// the real QQ heartbeat one short confirmation window to arrive.
|
||||
this.receiveWatchTimer = setTimeout(() => {
|
||||
this.receiveWatchTimer = null;
|
||||
if (!this.shouldWatchReceive()) return;
|
||||
const silentForMs = Date.now() - this.lastReceiveAt;
|
||||
if (silentForMs < RECEIVE_STALE_AFTER_MS + RECEIVE_STALE_CONFIRM_MS) {
|
||||
this.scheduleReceiveStaleCheck();
|
||||
return;
|
||||
}
|
||||
this.setReceiveHealthy(false);
|
||||
this.log.warn(
|
||||
'receive path stale: PID=%d UIN=%s lastRecvAt=%s silentFor=%dms; reporting good=false',
|
||||
this.pid,
|
||||
this.receiveWatchUin,
|
||||
new Date(this.lastReceiveAt).toISOString(),
|
||||
silentForMs,
|
||||
);
|
||||
}, RECEIVE_STALE_CONFIRM_MS);
|
||||
this.receiveWatchTimer.unref?.();
|
||||
}, RECEIVE_STALE_AFTER_MS);
|
||||
this.receiveWatchTimer.unref?.();
|
||||
}
|
||||
|
||||
private shouldWatchReceive(): boolean {
|
||||
return !this.disposed && this.connected && this.loggedIn && this.receiveWatchArmed;
|
||||
}
|
||||
|
||||
private setReceiveHealthy(healthy: boolean): void {
|
||||
if (this._receiveHealthy === healthy) return;
|
||||
this._receiveHealthy = healthy;
|
||||
this.emit('receive-health-changed', healthy);
|
||||
}
|
||||
|
||||
private resetReceiveWatch(uin = ''): void {
|
||||
if (this.receiveWatchTimer) {
|
||||
clearTimeout(this.receiveWatchTimer);
|
||||
this.receiveWatchTimer = null;
|
||||
}
|
||||
this.receiveWatchUin = uin;
|
||||
this.receiveWatchArmed = false;
|
||||
this.lastReceiveAt = 0;
|
||||
this._receiveHealthy = true;
|
||||
}
|
||||
}
|
||||
|
||||
function errMsg(value: unknown): string {
|
||||
|
||||
@@ -18,6 +18,7 @@ const flush = () => new Promise<void>(r => setImmediate(r));
|
||||
interface Harness {
|
||||
manager: HookManager;
|
||||
pipeWatcher: PipeWatcher;
|
||||
bridgeManager: BridgeManagerSink & { onPidReceiveHealthChanged: ReturnType<typeof vi.fn> };
|
||||
setProcesses: (next: number[]) => void;
|
||||
setLivePipes: (next: number[]) => void;
|
||||
onSessionsChanged: ReturnType<typeof vi.fn>;
|
||||
@@ -45,7 +46,8 @@ function makeManager(opts: { processes?: number[]; livePipes?: number[] } = {}):
|
||||
onPacket: vi.fn(),
|
||||
onHookLogin: vi.fn(),
|
||||
onPidDisconnected: vi.fn(),
|
||||
} as unknown as BridgeManagerSink;
|
||||
onPidReceiveHealthChanged: vi.fn(),
|
||||
} as unknown as BridgeManagerSink & { onPidReceiveHealthChanged: ReturnType<typeof vi.fn> };
|
||||
const onSessionsChanged = vi.fn();
|
||||
const manager = new HookManager({
|
||||
bridgeManager,
|
||||
@@ -61,6 +63,7 @@ function makeManager(opts: { processes?: number[]; livePipes?: number[] } = {}):
|
||||
return {
|
||||
manager,
|
||||
pipeWatcher,
|
||||
bridgeManager,
|
||||
onSessionsChanged,
|
||||
clientFactory,
|
||||
setProcesses: (next) => { pids = next; },
|
||||
@@ -171,3 +174,42 @@ describe('HookManager.onSessionsChanged', () => {
|
||||
manager.dispose();
|
||||
});
|
||||
});
|
||||
|
||||
describe('HookManager receive-health wiring (#233)', () => {
|
||||
it('forwards stale and recovered receive health for the owning PID', async () => {
|
||||
const ctx = makeManager({ processes: [4242], livePipes: [4242] });
|
||||
await ctx.pipeWatcher.start();
|
||||
await ctx.manager.loadProcess(4242);
|
||||
await ctx.manager.refreshProcess(4242);
|
||||
await flush();
|
||||
|
||||
const client = ctx.clientFactory.mock.results[0]!.value as EventEmitter;
|
||||
client.emit('loginState', { loggedIn: true, uin: '10001', uinNumber: 10001n });
|
||||
|
||||
vi.useFakeTimers({ toFake: ['setTimeout', 'Date'] });
|
||||
try {
|
||||
client.emit('packet', {
|
||||
seq: 1,
|
||||
error: 0,
|
||||
cmd: 'trpc.qq_new_tech.status_svc.StatusService.SsoHeartBeat',
|
||||
uin: '10001',
|
||||
body: Buffer.alloc(0),
|
||||
});
|
||||
vi.advanceTimersByTime(105_000);
|
||||
|
||||
expect(ctx.bridgeManager.onPidReceiveHealthChanged).toHaveBeenCalledWith(4242, false);
|
||||
|
||||
client.emit('packet', {
|
||||
seq: 2,
|
||||
error: 0,
|
||||
cmd: 'trpc.msg.olpush.OlPushService.MsgPush',
|
||||
uin: '10001',
|
||||
body: Buffer.alloc(0),
|
||||
});
|
||||
expect(ctx.bridgeManager.onPidReceiveHealthChanged).toHaveBeenLastCalledWith(4242, true);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
ctx.manager.dispose();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -652,6 +652,163 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () =>
|
||||
});
|
||||
});
|
||||
|
||||
describe('HookSession — end-to-end receive health (#233)', () => {
|
||||
const HEARTBEAT_CMD = 'trpc.qq_new_tech.status_svc.StatusService.SsoHeartBeat';
|
||||
const MESSAGE_CMD = 'trpc.msg.olpush.OlPushService.MsgPush';
|
||||
|
||||
async function startReceiveSession(onPacket?: PacketSink) {
|
||||
const ctx = makeSession({ pipeLive: true, onPacket });
|
||||
const healthChanges: boolean[] = [];
|
||||
ctx.session.on('receive-health-changed', (healthy: boolean) => healthChanges.push(healthy));
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await flush();
|
||||
ctx.currentClient().fireLogin('10001');
|
||||
return { ctx, healthChanges };
|
||||
}
|
||||
|
||||
function firePacket(
|
||||
ctx: ReturnType<typeof makeSession>,
|
||||
cmd: string,
|
||||
uin = '10001',
|
||||
seq = 1,
|
||||
): void {
|
||||
ctx.currentClient().firePacket({ seq, error: 0, cmd, uin, body: Buffer.alloc(0) });
|
||||
}
|
||||
|
||||
it('becomes unhealthy only after an observed QQ heartbeat stays silent, then recovers on the next packet', async () => {
|
||||
vi.useFakeTimers({ toFake: ['setTimeout', 'Date'] });
|
||||
const { ctx, healthChanges } = await startReceiveSession();
|
||||
|
||||
try {
|
||||
firePacket(ctx, HEARTBEAT_CMD);
|
||||
|
||||
vi.advanceTimersByTime(90_000);
|
||||
expect(ctx.session.receiveHealthy).toBe(true);
|
||||
|
||||
vi.advanceTimersByTime(15_000);
|
||||
expect(ctx.session.receiveHealthy).toBe(false);
|
||||
expect(healthChanges).toEqual([false]);
|
||||
|
||||
firePacket(ctx, MESSAGE_CMD, '10001', 2);
|
||||
|
||||
expect(ctx.session.receiveHealthy).toBe(true);
|
||||
expect(healthChanges).toEqual([false, true]);
|
||||
} finally {
|
||||
ctx.session.dispose();
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('does not arm the watchdog when this QQ session has never exposed its heartbeat', async () => {
|
||||
vi.useFakeTimers({ toFake: ['setTimeout', 'Date'] });
|
||||
const { ctx, healthChanges } = await startReceiveSession();
|
||||
|
||||
try {
|
||||
firePacket(ctx, MESSAGE_CMD);
|
||||
|
||||
vi.advanceTimersByTime(10 * 60_000);
|
||||
|
||||
expect(ctx.session.receiveHealthy).toBe(true);
|
||||
expect(healthChanges).toEqual([]);
|
||||
} finally {
|
||||
ctx.session.dispose();
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('uses the confirmation window to avoid a sleep-resume false alarm', async () => {
|
||||
vi.useFakeTimers({ toFake: ['setTimeout', 'Date'] });
|
||||
const { ctx, healthChanges } = await startReceiveSession();
|
||||
|
||||
try {
|
||||
firePacket(ctx, HEARTBEAT_CMD);
|
||||
|
||||
vi.advanceTimersByTime(90_000);
|
||||
vi.advanceTimersByTime(14_999);
|
||||
firePacket(ctx, HEARTBEAT_CMD, '10001', 2);
|
||||
vi.advanceTimersByTime(1);
|
||||
|
||||
expect(ctx.session.receiveHealthy).toBe(true);
|
||||
expect(healthChanges).toEqual([]);
|
||||
} finally {
|
||||
ctx.session.dispose();
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('does not carry an armed watchdog across a direct account switch', async () => {
|
||||
vi.useFakeTimers({ toFake: ['setTimeout', 'Date'] });
|
||||
const { ctx, healthChanges } = await startReceiveSession();
|
||||
|
||||
try {
|
||||
firePacket(ctx, HEARTBEAT_CMD);
|
||||
|
||||
ctx.currentClient().fireLogin('20002');
|
||||
vi.advanceTimersByTime(10 * 60_000);
|
||||
|
||||
expect(ctx.session.receiveHealthy).toBe(true);
|
||||
expect(healthChanges).toEqual([]);
|
||||
} finally {
|
||||
ctx.session.dispose();
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('requires the new account heartbeat after packet-driven PID migration', async () => {
|
||||
vi.useFakeTimers({ toFake: ['setTimeout', 'Date'] });
|
||||
const { ctx, healthChanges } = await startReceiveSession();
|
||||
|
||||
try {
|
||||
firePacket(ctx, HEARTBEAT_CMD);
|
||||
firePacket(ctx, MESSAGE_CMD, '20002', 2);
|
||||
vi.advanceTimersByTime(10 * 60_000);
|
||||
|
||||
expect(ctx.session.receiveHealthy).toBe(true);
|
||||
expect(healthChanges).toEqual([]);
|
||||
|
||||
firePacket(ctx, HEARTBEAT_CMD, '20002', 3);
|
||||
vi.advanceTimersByTime(105_000);
|
||||
|
||||
expect(ctx.session.receiveHealthy).toBe(false);
|
||||
expect(healthChanges).toEqual([false]);
|
||||
} finally {
|
||||
ctx.session.dispose();
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('counts an invalid-UIN frame as receive activity without routing it', async () => {
|
||||
vi.useFakeTimers({ toFake: ['setTimeout', 'Date'] });
|
||||
const onPacket = vi.fn();
|
||||
const { ctx, healthChanges } = await startReceiveSession(onPacket);
|
||||
|
||||
try {
|
||||
firePacket(ctx, HEARTBEAT_CMD);
|
||||
onPacket.mockClear();
|
||||
|
||||
vi.advanceTimersByTime(80_000);
|
||||
firePacket(ctx, 'trpc.status.invalid-uin-probe', '0', 2);
|
||||
vi.advanceTimersByTime(104_999);
|
||||
|
||||
expect(ctx.session.receiveHealthy).toBe(true);
|
||||
expect(onPacket).not.toHaveBeenCalled();
|
||||
|
||||
vi.advanceTimersByTime(1);
|
||||
expect(ctx.session.receiveHealthy).toBe(false);
|
||||
|
||||
firePacket(ctx, 'trpc.status.invalid-uin-probe', '0', 3);
|
||||
|
||||
expect(ctx.session.receiveHealthy).toBe(true);
|
||||
expect(healthChanges).toEqual([false, true]);
|
||||
expect(onPacket).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
ctx.session.dispose();
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('HookSession — login reconcile does not stack concurrent probes', () => {
|
||||
it('skips overlapping ticks while a slow probe is in flight', async () => {
|
||||
vi.useFakeTimers();
|
||||
|
||||
Reference in new issue
Block a user