fix(bridge): preserve QQ runtime failures across session updates

Surface connection failures immediately to waiting requests and keep the original error visible until the session reconnects. Ignore late login updates from the failed connection.
This commit is contained in:
DrSmoothl committed 2026-10-31 18:28:05 +08:00
1 parent fcbb2661d1
commit 8ecf41ccb7
4 files changed
+269 -40

No files matched your search

@@ -30,6 +30,7 @@ class FakeClient extends EventEmitter {
isClosed = false;
isLoggedIn = false;
shouldFailConnect = false;
runtimeErrorOnConnect = false;
nativeReadyOnIdentityHint = false;
identityHintFailures = 0;
sendError: Error | null = null;
@@ -38,6 +39,10 @@ class FakeClient extends EventEmitter {
private loginState = { loggedIn: false, uin: '0', uinNumber: 0n };
async connectAll(_opts: { recv: boolean }): Promise<void> {
if (this.runtimeErrorOnConnect) {
this.emit('runtimeError', new Error('QQ service unavailable'));
}
if (this.shouldFailConnect) {
throw new Error('connect failed');
}
@@ -102,6 +107,7 @@ function makeSession(
pid?: number;
pipeLive?: boolean;
clientFailsConnect?: boolean;
runtimeErrorOnConnect?: boolean;
onPacket?: PacketSink;
detectLoginUin?: (pid: number) => Promise<string | null>;
nativeReadyOnIdentityHint?: boolean;
@@ -123,6 +129,7 @@ function makeSession(
injector,
makeClient: () => {
const c = new FakeClient();
c.runtimeErrorOnConnect = opts.runtimeErrorOnConnect ?? false;
if (opts.clientFailsConnect) {
c.shouldFailConnect = true;
@@ -152,6 +159,77 @@ function makeSession(
const flush = () => new Promise<void>((r) => setImmediate(r));
describe('HookSession runtime failure', () => {
it('retains an initialization error instead of waiting for login', async () => {
const { session } = makeSession({ pipeLive: true, runtimeErrorOnConnect: true });
await session.load();
session.onPipeUp();
await flush();
expect(session.toInfo()).toMatchObject({
status: 'error',
error: 'QQ service unavailable',
connected: false,
});
session.dispose();
});
it('keeps a late runtime error visible across refresh and login snapshots', async () => {
const { session, currentClient, setPipeLive } = makeSession({ pipeLive: true });
const disconnect = vi.fn();
session.on('disconnected', disconnect);
await session.load();
session.onPipeUp();
await flush();
currentClient().fireLogin('10001');
currentClient().emit('runtimeError', new Error('QQ service unavailable'));
currentClient().emit('error', new Error('connection closed'));
expect(session.error).toBe('QQ service unavailable');
currentClient().fireLogin('10001');
await session.refresh();
expect(session.toInfo()).toMatchObject({
status: 'error',
error: 'QQ service unavailable',
loggedIn: false,
});
setPipeLive(false);
await session.refresh();
expect(disconnect).toHaveBeenCalledExactlyOnceWith(true);
setPipeLive(true);
await session.refresh();
currentClient().fireLogin('10001');
expect(session.toInfo()).toMatchObject({ status: 'online', loggedIn: true, error: '' });
session.dispose();
});
it('retains the failure when the pipe closes and discards an in-flight login lookup', async () => {
let resolveLogin!: (uin: string) => void;
const { session, currentClient, setPipeLive } = makeSession({
pipeLive: true,
detectLoginUin: () =>
new Promise((resolve) => {
resolveLogin = resolve;
}),
});
await session.load();
session.onPipeUp();
await flush();
const client = currentClient();
client.emit('runtimeError', new Error('QQ service unavailable'));
resolveLogin('10001');
await flush();
expect(client.loginIdentityHints).toEqual([]);
setPipeLive(false);
await session.refresh();
expect(session.toInfo()).toMatchObject({
status: 'error',
error: 'QQ service unavailable',
loggedIn: false,
connected: false,
});
session.dispose();
});
});
describe('HookSession — runtime TRACE', () => {
it('records injection and existing-pipe load branches with unique terminals', async () => {
const entries: LogEntry[] = [];
+79 -4
View File
@@ -85,6 +85,7 @@ function readSendFrame(payload: Buffer): {
function mockControlPipe(
pid: number,
onWrite: (socket: net.Socket, payload: Buffer) => void,
...startupFrames: Buffer[]
): ReturnType<typeof vi.spyOn> {
return vi.spyOn(net, 'createConnection').mockImplementation((() => {
const socket = new Duplex({
@@ -101,10 +102,13 @@ function mockControlPipe(
queueMicrotask(() =>
socket.emit(
'data',
pipeFrame({
op: PipeOp.hello,
value0: BigInt(pid),
}),
Buffer.concat([
pipeFrame({
op: PipeOp.hello,
value0: BigInt(pid),
}),
...startupFrames,
]),
),
);
});
@@ -118,6 +122,77 @@ function traceMessages(entries: LogEntry[]): string[] {
.map((entry) => entry.message);
}
describe('runtime initialization failures', () => {
const failureFrame = pipeFrame({
op: PipeOp.error,
cmd: 'runtime',
status: -1,
message: 'QQ service unavailable',
});
it('rejects startup when a runtime failure follows hello in the same read', async () => {
const connection = mockControlPipe(778901, () => {}, failureFrame);
const client = new QqHookClient(778901);
const failure = vi.fn();
client.on('runtimeError', failure);
try {
await expect(client.connect()).rejects.toThrow('QQ service unavailable');
expect(failure).toHaveBeenCalledExactlyOnceWith(
expect.objectContaining({ status: -1, requestId: 0 }),
);
} finally {
client.close();
connection.mockRestore();
}
});
it('rejects pending and future requests on a runtime failure', async () => {
const connection = mockControlPipe(778902, (socket) => {
queueMicrotask(() => socket.emit('data', failureFrame));
});
const client = new QqHookClient(778902);
try {
await expect(client.sendAndWait('Test', Buffer.alloc(0))).rejects.toThrow(
'QQ service unavailable',
);
await expect(client.sendAndWait('Test', Buffer.alloc(0))).rejects.toThrow(
'QQ service unavailable',
);
await expect(client.startRecv()).rejects.toThrow('QQ service unavailable');
await expect(client.waitForLogin()).rejects.toThrow('QQ service unavailable');
} finally {
client.close();
connection.mockRestore();
}
});
it('rejects login and queued writes when the runtime fails as a connection resumes', async () => {
const onWrite = vi.fn();
const sockets = mockControlPipe(778903, onWrite);
const client = new QqHookClient(778903);
try {
await client.connect();
const waiting = client.waitForLogin({ timeoutMs: 100 });
const sending = client.sendNoReply('Test', Buffer.alloc(0), { ackTimeoutMs: 100 });
const settled = Promise.allSettled([waiting, sending]);
sockets.mock.results[0]!.value.emit('data', failureFrame);
const expected = {
status: 'rejected',
reason: expect.objectContaining({ message: 'QQ service unavailable' }),
};
expect(await settled).toEqual([expected, expected]);
expect(onWrite).not.toHaveBeenCalled();
} finally {
client.close();
sockets.mockRestore();
}
});
});
function runtimeTrace(entries: LogEntry[]): LogEntry[] {
return entries.filter((entry) => entry.level === 'trace' && entry.scope === 'QQHook.Runtime');
}