feat(protocol): add byte-complete packet tracing
Capture complete packet request, reply, and push payloads during temporary TRACE sessions while preserving the existing non-persistent logging boundary. Correlate transport, parser, enrichment, drop, dispatch, timeout, and terminal outcomes with their real identifiers so exported logs can explain packet failures without relying on user descriptions. Lock byte completeness, lazy disabled behavior, concurrency, context propagation, and truthful terminal outcomes with regression coverage.
This commit is contained in:
12 files changed
+1682
-88
No files matched your search
@@ -3,7 +3,11 @@ import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sen
|
||||
import type { PacketInfo } from '@snowluma/common/protocol-types';
|
||||
import { BridgeEventBus } from '@snowluma/protocol/event-bus';
|
||||
import { IdentityService } from '@snowluma/protocol/identity-service';
|
||||
import { MSG_PUSH_CMD, parseMsgPush, SysMsgDedup } from '@snowluma/protocol/msg-push';
|
||||
import {
|
||||
MSG_PUSH_CMD,
|
||||
parseMsgPushOrThrow,
|
||||
SysMsgDedup,
|
||||
} from '@snowluma/protocol/msg-push';
|
||||
import { KICK_NT_CMD, parseKickNT } from '@snowluma/protocol/kick-nt';
|
||||
import { IncomingPacketPipeline, type CmdParser } from '@snowluma/protocol/packet-pipeline';
|
||||
import type { OnlineDeviceInfo } from '@snowluma/protocol/events';
|
||||
@@ -94,7 +98,14 @@ export class Bridge implements BridgeInterface {
|
||||
return null;
|
||||
},
|
||||
});
|
||||
this.pipeline.registerCmd(MSG_PUSH_CMD, (pkt, identity) => parseMsgPush(pkt, identity, this.sysMsgDedup_));
|
||||
this.pipeline.registerCmd(
|
||||
MSG_PUSH_CMD,
|
||||
(pkt, identity) => parseMsgPushOrThrow(
|
||||
pkt,
|
||||
identity,
|
||||
this.sysMsgDedup_,
|
||||
),
|
||||
);
|
||||
this.pipeline.registerCmd(KICK_NT_CMD, parseKickNT);
|
||||
this.events.on('online_devices_changed', (event) => {
|
||||
const snapshot = event.devices.map((device) => Object.freeze({ ...device }));
|
||||
@@ -215,8 +226,8 @@ export class Bridge implements BridgeInterface {
|
||||
getOnlineClients(): readonly Readonly<OnlineDeviceInfo>[] | null {
|
||||
return this.onlineClients_;
|
||||
}
|
||||
onPacket(pkt: PacketInfo): void {
|
||||
this.pipeline.process(pkt);
|
||||
onPacket(pkt: PacketInfo): Promise<void> {
|
||||
return this.pipeline.process(pkt);
|
||||
}
|
||||
|
||||
private async refreshMemberCache(groupId: number, refreshGroupList: boolean, forceMemberList: boolean): Promise<boolean> {
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import {
|
||||
createLogger,
|
||||
renderTraceBytes,
|
||||
runWithTraceRequest,
|
||||
} from '@snowluma/common/logger';
|
||||
import type { PacketSender } from '@snowluma/common/packet-sender';
|
||||
import type { PacketInfo } from '@snowluma/common/protocol-types';
|
||||
import { isRealUin } from '@snowluma/common/uin';
|
||||
@@ -13,6 +17,7 @@ interface QQSession {
|
||||
}
|
||||
|
||||
const log = createLogger('Bridge');
|
||||
const packetLog = createLogger('Bridge.Packet');
|
||||
|
||||
export class BridgeManager {
|
||||
private sessions_ = new Map<string, QQSession>();
|
||||
@@ -89,25 +94,97 @@ export class BridgeManager {
|
||||
}
|
||||
|
||||
onPacket(pkt: PacketInfo): void {
|
||||
if (!pkt.uin || !isRealUin(pkt.uin)) return;
|
||||
runWithTraceRequest(() => this.onPacketInContext(pkt));
|
||||
}
|
||||
|
||||
private onPacketInContext(pkt: PacketInfo): void {
|
||||
const startedAt = Date.now();
|
||||
packetLog.trace(() => [
|
||||
'packet_push serviceCmd=%j seqId=%d retCode=%d fromClient=%s pid=%d uin=%j length=%d body=%s',
|
||||
pkt.serviceCmd,
|
||||
pkt.seqId,
|
||||
pkt.retCode,
|
||||
pkt.fromClient,
|
||||
pkt.pid,
|
||||
pkt.uin,
|
||||
pkt.body.byteLength,
|
||||
renderTraceBytes(pkt.body),
|
||||
]);
|
||||
if (!pkt.uin || !isRealUin(pkt.uin)) {
|
||||
packetLog.trace(() => [
|
||||
'packet_terminal serviceCmd=%j seqId=%d outcome=dropped reason=invalid_uin events=0 dispatched=0 elapsedMs=%d',
|
||||
pkt.serviceCmd,
|
||||
pkt.seqId,
|
||||
Date.now() - startedAt,
|
||||
]);
|
||||
return;
|
||||
}
|
||||
const uin = pkt.uin;
|
||||
|
||||
// A packet may be the first trustworthy observation that a live PID moved
|
||||
// to another UIN. Apply the exact same ownership transition as login so a
|
||||
// PID can never remain attached to two Bridges.
|
||||
const client = pkt.pid > 0 ? this.packetClientForPid(pkt.pid) : null;
|
||||
const { session, created } = client
|
||||
? this.bindPid(pkt.pid, uin, client, 'packet')
|
||||
: this.ensureSession(uin);
|
||||
let completion: Promise<void>;
|
||||
let handedToPipeline = false;
|
||||
try {
|
||||
// A packet may be the first trustworthy observation that a live PID moved
|
||||
// to another UIN. Apply the exact same ownership transition as login so a
|
||||
// PID can never remain attached to two Bridges.
|
||||
const client = pkt.pid > 0 ? this.packetClientForPid(pkt.pid) : null;
|
||||
const { session, created } = client
|
||||
? this.bindPid(pkt.pid, uin, client, 'packet')
|
||||
: this.ensureSession(uin);
|
||||
|
||||
// Notify session started on first real packet
|
||||
if (created) {
|
||||
log.debug('session started: UIN=%s', uin);
|
||||
this.fireSessionStarted(uin, session.bridge);
|
||||
// Notify session started on first real packet
|
||||
if (created) {
|
||||
log.debug('session started: UIN=%s', uin);
|
||||
this.fireSessionStarted(uin, session.bridge);
|
||||
}
|
||||
|
||||
// Dispatch packet to bridge. The pipeline preserves synchronous parsing and
|
||||
// dispatch; its promise only marks completion of any async enrichment.
|
||||
handedToPipeline = true;
|
||||
completion = session.bridge.onPacket(pkt);
|
||||
} catch (error) {
|
||||
this.tracePacketFailure(
|
||||
pkt,
|
||||
startedAt,
|
||||
handedToPipeline
|
||||
? 'pipeline_failed'
|
||||
: 'routing_failed',
|
||||
error,
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
void completion.catch((error) => {
|
||||
this.tracePacketFailure(
|
||||
pkt,
|
||||
startedAt,
|
||||
'pipeline_failed',
|
||||
error,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
// Dispatch packet to bridge
|
||||
session.bridge.onPacket(pkt);
|
||||
private tracePacketFailure(
|
||||
pkt: PacketInfo,
|
||||
startedAt: number,
|
||||
reason: 'routing_failed' | 'pipeline_failed',
|
||||
error: unknown,
|
||||
): void {
|
||||
packetLog.trace(() => [
|
||||
'packet_terminal serviceCmd=%j seqId=%d outcome=failed reason=%s error=%j events=0 dispatched=0 elapsedMs=%d',
|
||||
pkt.serviceCmd,
|
||||
pkt.seqId,
|
||||
reason,
|
||||
error instanceof Error ? error.message : String(error),
|
||||
Date.now() - startedAt,
|
||||
]);
|
||||
log.error(
|
||||
'packet %s failed for %s: %s',
|
||||
reason === 'routing_failed'
|
||||
? 'routing'
|
||||
: 'pipeline',
|
||||
pkt.serviceCmd,
|
||||
error instanceof Error ? (error.stack ?? error.message) : String(error),
|
||||
);
|
||||
}
|
||||
|
||||
/** Bind PID + sender as one state transition. If the PID changed accounts,
|
||||
|
||||
@@ -1,9 +1,17 @@
|
||||
import {
|
||||
getLogLevel,
|
||||
setLogLevel,
|
||||
subscribeLogs,
|
||||
type LogEntry,
|
||||
} from '@snowluma/common/logger';
|
||||
import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sender';
|
||||
import type { PacketInfo } from '@snowluma/common/protocol-types';
|
||||
import { IdentityService } from '@snowluma/protocol/identity-service';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { BridgeManager } from '../src/bridge/manager';
|
||||
|
||||
const previousLogLevel = getLogLevel();
|
||||
|
||||
const OK_RESULT: SendPacketResult = {
|
||||
success: true,
|
||||
gotResponse: true,
|
||||
@@ -39,9 +47,127 @@ describe('BridgeManager PID ownership', () => {
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
setLogLevel(previousLogLevel);
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('records complete incoming packet bytes under one top-level TRACE request', async () => {
|
||||
const manager = new BridgeManager();
|
||||
const entries: LogEntry[] = [];
|
||||
const body = Buffer.from([
|
||||
0x00, 0xff, ...Array.from({ length: 160 }, (_, index) => (159 - index) & 0xff),
|
||||
]);
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
try {
|
||||
manager.onPacket({
|
||||
pid: 101,
|
||||
uin: '10001',
|
||||
serviceCmd: 'Trace\nCommand',
|
||||
seqId: 987,
|
||||
retCode: -5,
|
||||
fromClient: true,
|
||||
body,
|
||||
});
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
|
||||
const packetEntries = entries.filter((entry) =>
|
||||
entry.level === 'trace'
|
||||
&& (entry.scope === 'Bridge.Packet' || entry.scope === 'Protocol.Packet'));
|
||||
expect(packetEntries).toHaveLength(3);
|
||||
expect(packetEntries.map((entry) => entry.req)).toEqual([
|
||||
expect.any(Number),
|
||||
packetEntries[0]!.req,
|
||||
packetEntries[0]!.req,
|
||||
]);
|
||||
expect(packetEntries[0]!.message).toBe(
|
||||
`packet_push serviceCmd="Trace\\nCommand" seqId=987 retCode=-5 fromClient=true pid=101 uin="10001" length=${body.length} body=${body.toString('hex')}`,
|
||||
);
|
||||
expect(packetEntries[1]!.message).toBe(
|
||||
'packet_branch serviceCmd="Trace\\nCommand" seqId=987 branch=parser_unregistered',
|
||||
);
|
||||
expect(packetEntries[2]!.message).toMatch(
|
||||
/^packet_terminal serviceCmd="Trace\\nCommand" seqId=987 outcome=dropped reason=parser_unregistered events=0 dispatched=0 elapsedMs=\d+$/,
|
||||
);
|
||||
for (const entry of packetEntries) expect(entry.message).not.toContain('...');
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('records invalid UIN as a routed packet drop without creating a session', () => {
|
||||
const manager = new BridgeManager();
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
try {
|
||||
manager.onPacket({
|
||||
...packet(101, '0'),
|
||||
body: Buffer.from([0x00, 0xff]),
|
||||
});
|
||||
|
||||
expect(entries.filter((entry) => entry.scope === 'Bridge.Packet'))
|
||||
.toEqual(expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
level: 'trace',
|
||||
req: expect.any(Number),
|
||||
message: 'packet_push serviceCmd="Test.Unhandled" seqId=1 retCode=0 fromClient=false pid=101 uin="0" length=2 body=00ff',
|
||||
}),
|
||||
expect.objectContaining({
|
||||
level: 'trace',
|
||||
req: expect.any(Number),
|
||||
message: expect.stringMatching(/^packet_terminal serviceCmd="Test\.Unhandled" seqId=1 outcome=dropped reason=invalid_uin events=0 dispatched=0 elapsedMs=\d+$/),
|
||||
}),
|
||||
]));
|
||||
expect(manager.getSession('0')).toBeNull();
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('assigns distinct request ids to independent incoming packets', () => {
|
||||
const manager = new BridgeManager();
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
try {
|
||||
manager.onPacket(packet(101, '0'));
|
||||
manager.onPacket(packet(202, '0'));
|
||||
|
||||
const packetEntries = entries.filter((entry) =>
|
||||
entry.level === 'trace'
|
||||
&& entry.scope === 'Bridge.Packet');
|
||||
expect(packetEntries).toHaveLength(4);
|
||||
expect(packetEntries[0]!.req).toEqual(expect.any(Number));
|
||||
expect(packetEntries[1]!.req).toBe(packetEntries[0]!.req);
|
||||
expect(packetEntries[2]!.req).toEqual(expect.any(Number));
|
||||
expect(packetEntries[3]!.req).toBe(packetEntries[2]!.req);
|
||||
expect(packetEntries[2]!.req).not.toBe(packetEntries[0]!.req);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('does not render incoming packet bytes or allocate request IDs while TRACE is disabled', () => {
|
||||
const manager = new BridgeManager();
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('debug');
|
||||
const hex = vi.spyOn(Buffer.prototype, 'toString');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
try {
|
||||
manager.onPacket({
|
||||
...packet(0, '10001'),
|
||||
body: Buffer.from([0x00, 0xff]),
|
||||
});
|
||||
|
||||
expect(hex).not.toHaveBeenCalledWith('hex');
|
||||
expect(entries.some((entry) => entry.req !== undefined)).toBe(false);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
hex.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it('detaches a PID from its old UIN before starting its replacement session', () => {
|
||||
const manager = new BridgeManager();
|
||||
const first = makeSender();
|
||||
@@ -275,21 +401,37 @@ describe('BridgeManager PID ownership', () => {
|
||||
expect(closed).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('fails fast when Manager ownership references a PID whose Bridge sender is missing', () => {
|
||||
it('fails fast with a routing terminal when Manager ownership has no sender', () => {
|
||||
const manager = new BridgeManager();
|
||||
const sender = makeSender();
|
||||
manager.onHookLogin(101, '10001', sender.client);
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
try {
|
||||
manager.onHookLogin(101, '10001', sender.client);
|
||||
|
||||
// Deliberately violate the private ownership invariant through Bridge's
|
||||
// compatibility surface: Manager still maps PID 101 to this UIN, while
|
||||
// Bridge no longer owns either the PID or its sender.
|
||||
manager.getSession('10001')!.bridge.detachPid(101);
|
||||
// Deliberately violate the private ownership invariant through Bridge's
|
||||
// compatibility surface: Manager still maps PID 101 to this UIN, while
|
||||
// Bridge no longer owns either the PID or its sender.
|
||||
manager.getSession('10001')!.bridge.detachPid(101);
|
||||
|
||||
expect(() => manager.onPacket(packet(101, '10001'))).toThrowError(
|
||||
'BridgeManager invariant violated: PID=101 has no sender in UIN=10001 session',
|
||||
);
|
||||
expect(() => manager.onPidDisconnected(101)).toThrowError(
|
||||
'BridgeManager invariant violated: PID=101 is mapped to UIN=10001, but Bridge does not own the PID',
|
||||
);
|
||||
expect(() => manager.onPacket(packet(101, '10001'))).toThrowError(
|
||||
'BridgeManager invariant violated: PID=101 has no sender in UIN=10001 session',
|
||||
);
|
||||
const packetEntries = entries.filter((entry) =>
|
||||
entry.level === 'trace'
|
||||
&& entry.scope === 'Bridge.Packet');
|
||||
expect(packetEntries).toHaveLength(2);
|
||||
expect(packetEntries[0]!.req).toEqual(expect.any(Number));
|
||||
expect(packetEntries[1]).toMatchObject({
|
||||
req: packetEntries[0]!.req,
|
||||
message: expect.stringMatching(/^packet_terminal serviceCmd="Test\.Unhandled" seqId=1 outcome=failed reason=routing_failed error="BridgeManager invariant violated: PID=101 has no sender in UIN=10001 session" events=0 dispatched=0 elapsedMs=\d+$/),
|
||||
});
|
||||
expect(() => manager.onPidDisconnected(101)).toThrowError(
|
||||
'BridgeManager invariant violated: PID=101 is mapped to UIN=10001, but Bridge does not own the PID',
|
||||
);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user