fix(bridge): recover stale outbound sessions
Recover invalidated native send bindings from same-account receive evidence. Track outbound connection loss in status health and refresh the six public native artifacts from native build 94f2b63. Closes #342
This commit is contained in:
18 files changed
+196
-23
No files matched your search
@@ -81,7 +81,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' / receive health) to BridgeManager.
|
||||
* - Forward session events ('login' / 'disconnected' / transport health) to BridgeManager.
|
||||
* - Retry stuck-in-connecting sessions on every watcher tick (so a
|
||||
* failed connect eventually recovers without a manual refresh).
|
||||
* - Retry the bounded early-process auto-load race without retrying
|
||||
|
||||
@@ -1,8 +1,20 @@
|
||||
import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sender';
|
||||
import { QqHookClient, type QqHookSendReply } from './qq-hook-client';
|
||||
import {
|
||||
HookPipeRequestError,
|
||||
PIPE_STATUS_CONNECTION_UNAVAILABLE,
|
||||
QqHookClient,
|
||||
type QqHookSendReply,
|
||||
} from './qq-hook-client';
|
||||
|
||||
export type OutboundHealthListener = (healthy: boolean) => void;
|
||||
|
||||
export class HookPacketClient implements PacketSender {
|
||||
constructor(private readonly client: QqHookClient) { }
|
||||
private outboundHealthy = true;
|
||||
|
||||
constructor(
|
||||
private readonly client: QqHookClient,
|
||||
private readonly onOutboundHealthChanged?: OutboundHealthListener,
|
||||
) { }
|
||||
|
||||
async sendPacket(serviceCmd: string, body: Buffer, timeoutMs = 15000): Promise<SendPacketResult> {
|
||||
if (!this.client.isLoggedIn) {
|
||||
@@ -14,6 +26,7 @@ export class HookPacketClient implements PacketSender {
|
||||
wantReply: true,
|
||||
replyTimeoutMs: timeoutMs,
|
||||
}) as QqHookSendReply;
|
||||
this.setOutboundHealthy(true);
|
||||
return {
|
||||
success: reply.error === 0,
|
||||
gotResponse: true,
|
||||
@@ -22,6 +35,10 @@ export class HookPacketClient implements PacketSender {
|
||||
responseData: reply.body,
|
||||
};
|
||||
} catch (error) {
|
||||
if (error instanceof HookPipeRequestError
|
||||
&& error.status === PIPE_STATUS_CONNECTION_UNAVAILABLE) {
|
||||
this.setOutboundHealthy(false);
|
||||
}
|
||||
return {
|
||||
success: false,
|
||||
gotResponse: false,
|
||||
@@ -31,4 +48,10 @@ export class HookPacketClient implements PacketSender {
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
private setOutboundHealthy(healthy: boolean): void {
|
||||
if (this.outboundHealthy === healthy) return;
|
||||
this.outboundHealthy = healthy;
|
||||
this.onOutboundHealthChanged?.(healthy);
|
||||
}
|
||||
}
|
||||
@@ -69,7 +69,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
|
||||
* 'receive-health-changed' (healthy) — combined receive/request path health changed
|
||||
* 'status-changed' (status, error) — status field mutated
|
||||
* 'disposed' () — session stopped tracking this PID
|
||||
*/
|
||||
@@ -107,6 +107,7 @@ export class HookSession extends EventEmitter {
|
||||
private nextLoginHintAt = 0;
|
||||
private nextLoginIdentityObservationAt = 0;
|
||||
private _receiveHealthy = true;
|
||||
private _outboundHealthy = true;
|
||||
private receiveWatchUin = '';
|
||||
private receiveWatchArmed = false;
|
||||
private receiveWatchTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
@@ -130,7 +131,9 @@ 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; }
|
||||
get receiveHealthy(): boolean {
|
||||
return this._receiveHealthy && this._outboundHealthy;
|
||||
}
|
||||
|
||||
attachProcessInfo(info: { name?: string; path?: string }): void {
|
||||
if (info.name) this._name = info.name;
|
||||
@@ -499,7 +502,10 @@ export class HookSession extends EventEmitter {
|
||||
if (this.client?.isClosed) this.tearDownClient();
|
||||
if (!this.client) {
|
||||
this.client = this.makeClient(this.pid);
|
||||
this.sender = new HookPacketClient(this.client);
|
||||
this.sender = new HookPacketClient(
|
||||
this.client,
|
||||
healthy => this.setOutboundHealthy(healthy),
|
||||
);
|
||||
this.bound = false;
|
||||
}
|
||||
if (!this.bound) {
|
||||
@@ -582,6 +588,7 @@ export class HookSession extends EventEmitter {
|
||||
this.bound = false;
|
||||
this.connected = false;
|
||||
this.loggedIn = false;
|
||||
this._outboundHealthy = true;
|
||||
this.resetLoginHint();
|
||||
}
|
||||
|
||||
@@ -595,9 +602,13 @@ export class HookSession extends EventEmitter {
|
||||
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);
|
||||
if (this.receiveWatchUin !== this._uin) {
|
||||
this.resetReceiveWatch(this._uin);
|
||||
this._outboundHealthy = true;
|
||||
}
|
||||
} else {
|
||||
this.resetReceiveWatch();
|
||||
this._outboundHealthy = true;
|
||||
}
|
||||
|
||||
// Only the connected/logged-in states are ours to set here; when fully
|
||||
@@ -844,8 +855,29 @@ export class HookSession extends EventEmitter {
|
||||
|
||||
private setReceiveHealthy(healthy: boolean): void {
|
||||
if (this._receiveHealthy === healthy) return;
|
||||
const previous = this.receiveHealthy;
|
||||
this._receiveHealthy = healthy;
|
||||
this.emit('receive-health-changed', healthy);
|
||||
if (previous !== this.receiveHealthy) {
|
||||
this.emit('receive-health-changed', this.receiveHealthy);
|
||||
}
|
||||
}
|
||||
|
||||
private setOutboundHealthy(healthy: boolean): void {
|
||||
if (this._outboundHealthy === healthy) return;
|
||||
const previous = this.receiveHealthy;
|
||||
this._outboundHealthy = healthy;
|
||||
if (previous !== this.receiveHealthy) {
|
||||
this.emit('receive-health-changed', this.receiveHealthy);
|
||||
}
|
||||
if (healthy) {
|
||||
this.log.info('request path recovered: PID=%d UIN=%s', this.pid, this._uin);
|
||||
} else {
|
||||
this.log.warn(
|
||||
'request path unavailable: PID=%d UIN=%s; reporting good=false',
|
||||
this.pid,
|
||||
this._uin,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private resetReceiveWatch(uin = ''): void {
|
||||
|
||||
@@ -23,6 +23,7 @@ export const MAX_PIPE_MSG_BYTES = 65536;
|
||||
export const MAX_PIPE_BODY_BYTES = 16 * 1024 * 1024;
|
||||
export const DEFAULT_ACK_TIMEOUT_MS = 5000;
|
||||
export const DEFAULT_REPLY_TIMEOUT_MS = 30000;
|
||||
export const PIPE_STATUS_CONNECTION_UNAVAILABLE = -39;
|
||||
const DEFAULT_PIPE_PROBE_TIMEOUT_MS = 250;
|
||||
const packetLog = createLogger('QQHook.Packet');
|
||||
const runtimeLog = createLogger('QQHook.Runtime');
|
||||
@@ -273,8 +274,12 @@ function withTimeout<T>(promise: Promise<T>, timeoutMs: number, label: string):
|
||||
});
|
||||
}
|
||||
|
||||
class HookPipeRequestError extends Error {
|
||||
constructor(message: string) {
|
||||
export class HookPipeRequestError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
readonly status: number,
|
||||
readonly requestId: number,
|
||||
) {
|
||||
super(message);
|
||||
this.name = 'HookPipeRequestError';
|
||||
}
|
||||
@@ -1064,7 +1069,11 @@ export class QqHookClient extends EventEmitter {
|
||||
return;
|
||||
}
|
||||
if (frame.op === PipeOp.error) {
|
||||
const error = new HookPipeRequestError(frame.msg || `pipe error ${frame.status}`);
|
||||
const error = new HookPipeRequestError(
|
||||
frame.msg || `pipe error ${frame.status}`,
|
||||
frame.status,
|
||||
frame.requestId,
|
||||
);
|
||||
const ack = this.pendingAcks.get(frame.requestId);
|
||||
if (ack) {
|
||||
this.pendingAcks.delete(frame.requestId);
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { HookPacketClient } from '../src/hook-packet-client';
|
||||
import {
|
||||
HookPipeRequestError,
|
||||
PIPE_STATUS_CONNECTION_UNAVAILABLE,
|
||||
type QqHookClient,
|
||||
} from '../src/qq-hook-client';
|
||||
|
||||
function fakeClient(send: QqHookClient['send']): QqHookClient {
|
||||
return {
|
||||
isLoggedIn: true,
|
||||
send,
|
||||
} as unknown as QqHookClient;
|
||||
}
|
||||
|
||||
describe('HookPacketClient outbound health', () => {
|
||||
it('reports native connection loss once and recovers after a successful request', async () => {
|
||||
const healthChanged = vi.fn();
|
||||
const send = vi
|
||||
.fn<QqHookClient['send']>()
|
||||
.mockRejectedValueOnce(new HookPipeRequestError(
|
||||
'The QQ connection changed. Please restart QQ and try again.',
|
||||
PIPE_STATUS_CONNECTION_UNAVAILABLE,
|
||||
1,
|
||||
))
|
||||
.mockRejectedValueOnce(new HookPipeRequestError(
|
||||
'The QQ connection changed. Please restart QQ and try again.',
|
||||
PIPE_STATUS_CONNECTION_UNAVAILABLE,
|
||||
2,
|
||||
))
|
||||
.mockResolvedValueOnce({
|
||||
requestId: 3,
|
||||
error: 0,
|
||||
message: '',
|
||||
body: Buffer.from('ok'),
|
||||
});
|
||||
const sender = new HookPacketClient(fakeClient(send), healthChanged);
|
||||
|
||||
await expect(sender.sendPacket('Test.Command', Buffer.alloc(0)))
|
||||
.resolves.toMatchObject({ success: false, gotResponse: false });
|
||||
await sender.sendPacket('Test.Command', Buffer.alloc(0));
|
||||
await expect(sender.sendPacket('Test.Command', Buffer.alloc(0)))
|
||||
.resolves.toMatchObject({ success: true, gotResponse: true });
|
||||
|
||||
expect(healthChanged.mock.calls).toEqual([[false], [true]]);
|
||||
});
|
||||
|
||||
it('does not classify ordinary request rejection as connection loss', async () => {
|
||||
const healthChanged = vi.fn();
|
||||
const send = vi.fn<QqHookClient['send']>().mockRejectedValue(
|
||||
new HookPipeRequestError('This request is not valid.', -38, 1),
|
||||
);
|
||||
const sender = new HookPacketClient(fakeClient(send), healthChanged);
|
||||
|
||||
await expect(sender.sendPacket('Test.Command', Buffer.alloc(0)))
|
||||
.resolves.toMatchObject({ success: false, gotResponse: false });
|
||||
|
||||
expect(healthChanged).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -2,7 +2,12 @@ import { afterEach, describe, it, expect, vi } from 'vitest';
|
||||
import { EventEmitter } from 'events';
|
||||
import { HookSession } from '../src/hook-session';
|
||||
import type { ManualMapHandle } from '../src/injector';
|
||||
import type { QqHookClient, QqHookPacket } from '../src/qq-hook-client';
|
||||
import {
|
||||
HookPipeRequestError,
|
||||
PIPE_STATUS_CONNECTION_UNAVAILABLE,
|
||||
type QqHookClient,
|
||||
type QqHookPacket,
|
||||
} from '../src/qq-hook-client';
|
||||
import type { QqPortLoginInfo } from '../src/qq-port-probe';
|
||||
import type { PacketSender } from '@snowluma/common/packet-sender';
|
||||
import type { PacketSink } from '@snowluma/common/protocol-types';
|
||||
@@ -35,6 +40,7 @@ class FakeClient extends EventEmitter {
|
||||
shouldFailConnect = false;
|
||||
nativeReadyOnIdentityHint = false;
|
||||
identityHintFailures = 0;
|
||||
sendError: Error | null = null;
|
||||
readonly sentPackets: Array<{ serviceCmd: string; body: Buffer }> = [];
|
||||
readonly loginIdentityHints: string[] = [];
|
||||
private loginState = { loggedIn: false, uin: '0', uinNumber: 0n };
|
||||
@@ -58,6 +64,7 @@ class FakeClient extends EventEmitter {
|
||||
if (this.nativeReadyOnIdentityHint) this.fireLogin(uin);
|
||||
}
|
||||
async send(serviceCmd: string, body: Buffer) {
|
||||
if (this.sendError) throw this.sendError;
|
||||
this.sentPackets.push({ serviceCmd, body: Buffer.from(body) });
|
||||
return {
|
||||
requestId: this.sentPackets.length,
|
||||
@@ -1061,6 +1068,39 @@ describe('HookSession — end-to-end receive health (#233)', () => {
|
||||
ctx.currentClient().firePacket({ seq, error: 0, cmd, uin, body: Buffer.alloc(0) });
|
||||
}
|
||||
|
||||
it('reports native outbound loss as unhealthy and recovers on the next successful request', async () => {
|
||||
const { ctx, healthChanges } = await startReceiveSession();
|
||||
let sender: PacketSender | undefined;
|
||||
ctx.session.on('login', (_uin: string, nextSender: PacketSender) => {
|
||||
sender = nextSender;
|
||||
});
|
||||
|
||||
try {
|
||||
// Re-emit on a new account epoch so the test captures the session sender.
|
||||
ctx.currentClient().fireLogin('20002');
|
||||
ctx.currentClient().sendError = new HookPipeRequestError(
|
||||
'The QQ connection changed. Please restart QQ and try again.',
|
||||
PIPE_STATUS_CONNECTION_UNAVAILABLE,
|
||||
1,
|
||||
);
|
||||
|
||||
await sender!.sendPacket('Test.Command', Buffer.alloc(0));
|
||||
expect(ctx.session.receiveHealthy).toBe(false);
|
||||
expect(healthChanges).toEqual([false]);
|
||||
|
||||
// Incoming traffic alone must not conceal a still-broken send path.
|
||||
firePacket(ctx, HEARTBEAT_CMD, '20002');
|
||||
expect(ctx.session.receiveHealthy).toBe(false);
|
||||
|
||||
ctx.currentClient().sendError = null;
|
||||
await sender!.sendPacket('Test.Command', Buffer.alloc(0));
|
||||
expect(ctx.session.receiveHealthy).toBe(true);
|
||||
expect(healthChanges).toEqual([false, true]);
|
||||
} finally {
|
||||
ctx.session.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
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();
|
||||
|
||||
@@ -688,10 +688,19 @@ describe('QqHookClient — packet TRACE', () => {
|
||||
message: 'send ack 1 timed out after 25 ms',
|
||||
});
|
||||
|
||||
await expect(client.sendAndWait(
|
||||
const requestError = await client.sendAndWait(
|
||||
'Pipe.Error',
|
||||
Buffer.from([0xff]),
|
||||
)).rejects.toThrow('send ack 2 timed out after 25 ms');
|
||||
).then(
|
||||
() => null,
|
||||
(error: unknown) => error,
|
||||
);
|
||||
expect(requestError).toMatchObject({
|
||||
name: 'HookPipeRequestError',
|
||||
message: 'send ack 2 timed out after 25 ms',
|
||||
status: 12,
|
||||
requestId: 2,
|
||||
});
|
||||
|
||||
expect(traceMessages(entries)).toEqual(expect.arrayContaining([
|
||||
expect.stringMatching(/^packet_terminal serviceCmd="Ack\.Timeout" requestId=1 outcome=timeout reason=ack_timeout error="send ack 1 timed out after 25 ms" elapsedMs=\d+$/),
|
||||
|
||||
@@ -3,8 +3,8 @@ import type { BridgeContext } from './bridge-context';
|
||||
|
||||
export interface BridgeInterface extends BridgeContext {
|
||||
readonly activePid: number | null;
|
||||
/** False only when every attached QQ process is confirmed stale.
|
||||
* An unarmed watchdog remains true for compatibility. */
|
||||
/** False only when every attached QQ process has a confirmed receive or
|
||||
* request-path failure. An unarmed watchdog remains true for compatibility. */
|
||||
readonly receiveHealthy: boolean;
|
||||
/** Latest device snapshot observed on this Bridge lifecycle. `null` means
|
||||
* QQ has not emitted its cache notification since SnowLuma attached. */
|
||||
|
||||
@@ -6970,7 +6970,7 @@
|
||||
{
|
||||
"name": "get_status",
|
||||
"aliases": [],
|
||||
"returns": "运行状态。`online` 表示账号在线;`good` 仅在接收链路确认停滞时为 `false`。",
|
||||
"returns": "运行状态。`online` 表示账号在线;`good` 表示已确认的收发链路健康状态。",
|
||||
"returnsSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
@@ -6980,7 +6980,7 @@
|
||||
},
|
||||
"good": {
|
||||
"type": "boolean",
|
||||
"description": "接收链路健康状态;仅在确认停滞时为 false"
|
||||
"description": "收发链路健康状态;确认接收停滞或主动请求连接失效时为 false"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
|
||||
@@ -6973,7 +6973,7 @@ export const ACTIONS: CatalogAction[] = [
|
||||
{
|
||||
"name": "get_status",
|
||||
"aliases": [],
|
||||
"returns": "运行状态。`online` 表示账号在线;`good` 仅在接收链路确认停滞时为 `false`。",
|
||||
"returns": "运行状态。`online` 表示账号在线;`good` 表示已确认的收发链路健康状态。",
|
||||
"returnsSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
@@ -6983,7 +6983,7 @@ export const ACTIONS: CatalogAction[] = [
|
||||
},
|
||||
"good": {
|
||||
"type": "boolean",
|
||||
"description": "接收链路健康状态;仅在确认停滞时为 false"
|
||||
"description": "收发链路健康状态;确认接收停滞或主动请求连接失效时为 false"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
|
||||
@@ -27,12 +27,12 @@ export const actions = [
|
||||
defineAction({
|
||||
name: 'get_status',
|
||||
readOnly: true,
|
||||
returns: '运行状态。`online` 表示账号在线;`good` 仅在接收链路确认停滞时为 `false`。',
|
||||
returns: '运行状态。`online` 表示账号在线;`good` 表示已确认的收发链路健康状态。',
|
||||
returnsSchema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
online: { type: 'boolean', description: '是否在线' },
|
||||
good: { type: 'boolean', description: '接收链路健康状态;仅在确认停滞时为 false' },
|
||||
good: { type: 'boolean', description: '收发链路健康状态;确认接收停滞或主动请求连接失效时为 false' },
|
||||
},
|
||||
required: ['online', 'good'],
|
||||
},
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { ApiHandler, type ApiActionContext } from '../src/api-handler';
|
||||
|
||||
describe('get_status receive health (#233)', () => {
|
||||
describe('get_status transport health (#233, #342)', () => {
|
||||
it('keeps online true while reporting a stalled receive path as not good', async () => {
|
||||
const ctx = {
|
||||
isOnline: () => true,
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Reference in new issue
Block a user