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:
DrSmoothl committed 2026-08-09 21:40:09 +08:00
1 parent 129b091081
commit 870e9a5fbc
18 files changed
+196 -23

No files matched your search

@@ -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();
});
});
+41 -1
View File
@@ -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();
+11 -2
View File
@@ -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+$/),