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:
DrSmoothl committed 2026-07-30 20:11:02 +08:00
1 parent f9c4063fc5
commit 0d14408b6f
12 files changed
+1682 -88

No files matched your search

@@ -5,14 +5,25 @@
// is genuinely empty*, while still keeping (and warning about) a message that
// carried content we merely failed to decode.
import { describe, expect, it } from 'vitest';
import {
getLogLevel,
setLogLevel,
subscribeLogs,
type LogEntry,
} from '@snowluma/common/logger';
import type { PacketInfo } from '@snowluma/common/protocol-types';
import { protobuf_encode } from '@snowluma/proton';
import type { PushMsg, PushMsgBody } from '@snowluma/proto-defs/message';
import { afterEach, describe, expect, it } from 'vitest';
import type { IdentityService } from '../../src/identity-service';
import { parseMsgPush } from '../../src/msg-push';
const identity = { findFriend: () => undefined } as unknown as IdentityService;
const previousLogLevel = getLogLevel();
afterEach(() => {
setLogLevel(previousLogLevel);
});
function pushPacket(message: PushMsgBody): PacketInfo {
return {
@@ -26,14 +37,55 @@ function pushPacket(message: PushMsgBody): PacketInfo {
};
}
function traceMessages(entries: LogEntry[]): string[] {
return entries
.filter((entry) => entry.level === 'trace')
.map((entry) => entry.message);
}
describe('parseMsgPush — empty message drop (#102)', () => {
it('drops a genuinely empty friend message (group-invite phantom)', () => {
const out = parseMsgPush(pushPacket({
responseHead: { fromUin: 10001, fromUid: 'u_x' },
contentHead: { msgType: 166, subType: 0, sequence: 59962, timestamp: 1781540572, msgId: 1963990184 },
body: { richText: { elems: [] } },
}), identity);
expect(out).toEqual([]);
it('records an invalid push context before returning no events', () => {
const entries: LogEntry[] = [];
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
try {
const pkt = pushPacket({
responseHead: { fromUin: 10001, fromUid: 'u_x' },
});
expect(parseMsgPush(pkt, identity)).toEqual([]);
expect(traceMessages(entries)).toContain(
'packet_branch serviceCmd="trpc.msg.olpush.OlPushService.MsgPush" seqId=0 branch=push_context_invalid',
);
} finally {
unsubscribe();
}
});
it('records the precise branch when dropping a genuinely empty message', () => {
const entries: LogEntry[] = [];
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
try {
const out = parseMsgPush(pushPacket({
responseHead: { fromUin: 10001, fromUid: 'u_x' },
contentHead: {
msgType: 166,
subType: 0,
sequence: 59962,
timestamp: 1781540572,
msgId: 1963990184,
},
body: { richText: { elems: [] } },
}), identity);
expect(out).toEqual([]);
expect(traceMessages(entries)).toContain(
'packet_branch serviceCmd="trpc.msg.olpush.OlPushService.MsgPush" seqId=0 branch=empty_message msgType=166 subType=0 messageSeq=59962',
);
} finally {
unsubscribe();
}
});
it('keeps a friend message that actually has content', () => {
@@ -49,15 +101,33 @@ describe('parseMsgPush — empty message drop (#102)', () => {
});
});
it('drops a C2C control push by (msgType, c2cCmd) even when it carries content', () => {
it('records the precise branch for a C2C control push with content', () => {
// 166 + c2c_cmd ∈ {1,73,75,129,131,133,135,192} is a control/system signal
// QQ NT routes via OnRecvSysMsg, never a bubble — drop regardless of body.
const out = parseMsgPush(pushPacket({
responseHead: { fromUin: 10001, fromUid: 'u_x' },
contentHead: { msgType: 166, subType: 0, c2cCmd: 75, sequence: 200, timestamp: 1781540572, msgId: 3 },
body: { richText: { elems: [{ text: { str: 'noise' } }] } },
}), identity);
expect(out).toEqual([]);
const entries: LogEntry[] = [];
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
try {
const out = parseMsgPush(pushPacket({
responseHead: { fromUin: 10001, fromUid: 'u_x' },
contentHead: {
msgType: 166,
subType: 0,
c2cCmd: 75,
sequence: 200,
timestamp: 1781540572,
msgId: 3,
},
body: { richText: { elems: [{ text: { str: 'noise' } }] } },
}), identity);
expect(out).toEqual([]);
expect(traceMessages(entries)).toContain(
'packet_branch serviceCmd="trpc.msg.olpush.OlPushService.MsgPush" seqId=0 branch=c2c_control_push msgType=166 subType=0 c2cCmd=75 messageSeq=200',
);
} finally {
unsubscribe();
}
});
it('keeps a normal 166 message whose c2cCmd is not a control command', () => {
@@ -0,0 +1,82 @@
import {
getLogLevel,
setLogLevel,
subscribeLogs,
type LogEntry,
} from '@snowluma/common/logger';
import type { IdentityService } from '@snowluma/protocol/identity-service';
import type { MsgPushContext } from '@snowluma/protocol/msg-push/context';
import { PkgType } from '@snowluma/protocol/msg-push/enums';
import { MsgPushRegistry } from '@snowluma/protocol/msg-push/registry';
import { afterEach, describe, expect, it } from 'vitest';
const previousLogLevel = getLogLevel();
afterEach(() => {
setLogLevel(previousLogLevel);
});
function context(msgType: number): MsgPushContext {
return {
head: {
msgType,
subType: 7,
c2cCmd: 0,
sequence: 88,
ntMsgSeq: 0,
timestamp: 1,
msgId: 2,
},
fromUin: 20002,
fromUid: 'u_peer',
selfUin: 10001,
content: new Uint8Array(0),
body: undefined,
responseHead: undefined,
identity: {} as IdentityService,
isHistorical: false,
};
}
function traceMessages(entries: LogEntry[]): string[] {
return entries
.filter((entry) => entry.level === 'trace')
.map((entry) => entry.message);
}
describe('MsgPushRegistry TRACE branches', () => {
it('records an unregistered decoder with its message identity', () => {
const entries: LogEntry[] = [];
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
try {
const registry = new MsgPushRegistry();
expect(registry.decode(context(9999))).toEqual([]);
expect(traceMessages(entries)).toContain(
'packet_branch branch=decoder_unregistered msgType=9999 subType=7 messageSeq=88',
);
} finally {
unsubscribe();
}
});
it('records a decoder exception before failing open', () => {
const entries: LogEntry[] = [];
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
try {
const registry = new MsgPushRegistry();
registry.register(PkgType.PrivateMessage, () => {
throw new Error('fixture decode failed');
});
expect(registry.decode(context(PkgType.PrivateMessage))).toEqual([]);
expect(traceMessages(entries)).toContain(
'packet_branch branch=decoder_exception msgType=166 subType=7 messageSeq=88 error="fixture decode failed"',
);
} finally {
unsubscribe();
}
});
});
@@ -9,6 +9,12 @@
// message table, but only when given a dedup tracker (the live path). Ordinary
// chat routes remain outside that table even when their outer msgType matches.
import {
getLogLevel,
setLogLevel,
subscribeLogs,
type LogEntry,
} from '@snowluma/common/logger';
import { describe, expect, it } from 'vitest';
import type { PacketInfo } from '@snowluma/common/protocol-types';
import { protobuf_encode } from '@snowluma/proton';
@@ -211,6 +217,34 @@ describe('parseMsgPush — system-push dedup (#137)', () => {
expect(second).toEqual([]);
});
it('traces the actual duplicate branch before returning zero events', () => {
const previousLevel = getLogLevel();
const entries: LogEntry[] = [];
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
try {
const dedup = new SysMsgDedup();
const push = () => memberIncreasePush({
groupId: 700,
memberUin: 2854207029,
sequence: 800,
msgId: 555,
});
expect(parseMsgPush(push(), identity, dedup)).toHaveLength(1);
expect(parseMsgPush(push(), identity, dedup)).toEqual([]);
expect(entries.filter((entry) => entry.scope === 'MsgPush' && entry.level === 'trace'))
.toEqual([
expect.objectContaining({
message: 'packet_branch serviceCmd="trpc.msg.olpush.OlPushService.MsgPush" seqId=0 branch=duplicate_system_push peer="700" chatType=2 messageSeq=800 messageRandom=555',
}),
]);
} finally {
unsubscribe();
setLogLevel(previousLevel);
}
});
it('keeps both pushes when no dedup tracker is supplied (forward re-parse path)', () => {
const push = () => memberIncreasePush({ groupId: 700, memberUin: 2854207029, sequence: 800, msgId: 555 });
expect(parseMsgPush(push(), identity)).toHaveLength(1);
@@ -0,0 +1,343 @@
import {
currentRequestId,
getLogLevel,
runWithRequestId,
setLogLevel,
subscribeLogs,
type LogEntry,
} from '@snowluma/common/logger';
import type { PacketInfo } from '@snowluma/common/protocol-types';
import { BridgeEventBus } from '@snowluma/protocol/event-bus';
import type { QQEventVariant } from '@snowluma/protocol/events';
import { IdentityService } from '@snowluma/protocol/identity-service';
import type { MsgPushContext } from '@snowluma/protocol/msg-push/context';
import { PkgType } from '@snowluma/protocol/msg-push/enums';
import { MsgPushRegistry } from '@snowluma/protocol/msg-push/registry';
import { IncomingPacketPipeline } from '@snowluma/protocol/packet-pipeline';
import { afterEach, describe, expect, it, vi } from 'vitest';
const previousLogLevel = getLogLevel();
afterEach(() => {
setLogLevel(previousLogLevel);
vi.restoreAllMocks();
});
function packet(serviceCmd = 'Trace.Command'): PacketInfo {
return {
pid: 42,
uin: '10001',
serviceCmd,
seqId: 77,
retCode: 0,
fromClient: false,
body: Buffer.from([0x00, 0xff]),
};
}
function friendEvent(): QQEventVariant {
return {
kind: 'friend_message',
time: 1,
selfUin: 10001,
senderUin: 20002,
senderUid: 'u_peer',
senderNick: 'peer',
msgSeq: 1,
msgId: 2,
elements: [{ type: 'text', text: 'hi' }],
};
}
function msgPushContext(
identity: IdentityService,
): MsgPushContext {
return {
head: {
msgType: PkgType.PrivateMessage,
subType: 7,
c2cCmd: 0,
sequence: 88,
ntMsgSeq: 0,
timestamp: 1,
msgId: 2,
},
fromUin: 20002,
fromUid: 'u_peer',
selfUin: 10001,
content: new Uint8Array(0),
body: undefined,
responseHead: undefined,
identity,
isHistorical: false,
};
}
function makePipeline(opts: {
refreshMemberCache?: () => Promise<boolean>;
resolveStrangerProfile?: () => Promise<{ uin: number; nickname: string } | null>;
} = {}) {
const identity = IdentityService.memory('10001');
const events = new BridgeEventBus();
const pipeline = new IncomingPacketPipeline({
identity,
events,
refreshMemberCache: opts.refreshMemberCache ?? vi.fn(async () => false),
resolveStrangerProfile: opts.resolveStrangerProfile ?? vi.fn(async () => null),
resolveGroupJoinRequest: vi.fn(async () => null),
});
const dispatched: Array<{ event: QQEventVariant; req: number | undefined }> = [];
events.onAny((event) => {
dispatched.push({ event: event as QQEventVariant, req: currentRequestId() });
});
return { pipeline, dispatched, identity };
}
function packetTrace(entries: LogEntry[]): LogEntry[] {
return entries.filter((entry) => entry.level === 'trace' && entry.scope === 'Protocol.Packet');
}
describe('IncomingPacketPipeline TRACE lifecycle', () => {
it('records an unregistered command as one dropped terminal', async () => {
const entries: LogEntry[] = [];
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
try {
const { pipeline } = makePipeline();
await pipeline.process(packet('Unknown.Command'));
expect(packetTrace(entries).map((entry) => entry.message)).toEqual([
'packet_branch serviceCmd="Unknown.Command" seqId=77 branch=parser_unregistered',
expect.stringMatching(/^packet_terminal serviceCmd="Unknown\.Command" seqId=77 outcome=dropped reason=parser_unregistered events=0 dispatched=0 elapsedMs=\d+$/),
]);
} finally {
unsubscribe();
}
});
it('classifies a decoder exception as a parser failure terminal', async () => {
const entries: LogEntry[] = [];
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
try {
const { pipeline, identity } = makePipeline();
const registry = new MsgPushRegistry();
registry.register(PkgType.PrivateMessage, () => {
throw new Error('fixture decoder failed');
});
pipeline.registerCmd(
'Trace.Command',
() => registry.decodeOrThrow(msgPushContext(identity)),
);
await pipeline.process(packet());
expect(entries).toContainEqual(expect.objectContaining({
level: 'trace',
scope: 'MsgPush',
message: 'packet_branch branch=decoder_exception msgType=166 subType=7 messageSeq=88 error="fixture decoder failed"',
}));
expect(packetTrace(entries).map((entry) => entry.message)).toEqual([
'packet_branch serviceCmd="Trace.Command" seqId=77 parser=1 branch=parser_exception error="fixture decoder failed"',
expect.stringMatching(/^packet_terminal serviceCmd="Trace\.Command" seqId=77 outcome=failed reason=parser_exception events=0 dispatched=0 parserErrors=1 elapsedMs=\d+$/),
]);
} finally {
unsubscribe();
}
});
it('distinguishes zero events, parser exceptions, and synchronous dispatch', async () => {
const entries: LogEntry[] = [];
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
try {
const { pipeline, dispatched } = makePipeline();
pipeline.registerCmd('Trace.Command', () => []);
pipeline.registerCmd('Trace.Command', () => { throw new Error('fixture parser failed'); });
pipeline.registerCmd('Trace.Command', () => [friendEvent()]);
const completion = pipeline.process(packet());
expect(dispatched).toHaveLength(1);
await completion;
expect(packetTrace(entries).map((entry) => entry.message)).toEqual([
'packet_branch serviceCmd="Trace.Command" seqId=77 parser=1 branch=parser_zero_events',
'packet_branch serviceCmd="Trace.Command" seqId=77 parser=2 branch=parser_exception error="fixture parser failed"',
'packet_branch serviceCmd="Trace.Command" seqId=77 parser=3 branch=parser_events events=1',
'packet_branch serviceCmd="Trace.Command" seqId=77 branch=dispatch eventKind="friend_message" mode=sync',
expect.stringMatching(/^packet_terminal serviceCmd="Trace\.Command" seqId=77 outcome=failed reason=parser_exception events=1 dispatched=1 parserErrors=1 elapsedMs=\d+$/),
]);
} finally {
unsubscribe();
}
});
it('classifies a synchronous dispatch exception and emits one failed terminal', async () => {
const entries: LogEntry[] = [];
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
try {
const { pipeline, identity } = makePipeline();
vi.spyOn(identity, 'rememberRequestIdentity').mockImplementation(() => {
throw new Error('fixture dispatch failed');
});
pipeline.registerCmd('Trace.Command', () => [
friendEvent(),
friendEvent(),
]);
await pipeline.process(packet());
expect(packetTrace(entries).map((entry) => entry.message)).toEqual([
'packet_branch serviceCmd="Trace.Command" seqId=77 parser=1 branch=parser_events events=2',
'packet_branch serviceCmd="Trace.Command" seqId=77 branch=dispatch_exception eventKind="friend_message" error="fixture dispatch failed"',
expect.stringMatching(/^packet_terminal serviceCmd="Trace\.Command" seqId=77 outcome=failed reason=dispatch_exception events=2 dispatched=0 parserErrors=0 dispatchErrors=1 elapsedMs=\d+$/),
]);
expect(identity.rememberRequestIdentity).toHaveBeenCalledOnce();
} finally {
unsubscribe();
}
});
it('records degraded enrichment but still completes after dispatch', async () => {
const entries: LogEntry[] = [];
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
try {
const { pipeline, dispatched } = makePipeline({
refreshMemberCache: vi.fn(async () => {
throw new Error('fixture refresh failed');
}),
});
pipeline.registerCmd('Trace.Command', () => [{
kind: 'group_member_join',
time: 1,
selfUin: 10001,
groupId: 123,
userUin: 0,
operatorUin: 0,
userUid: 'u_new_member',
operatorUid: 'u_operator',
}]);
await pipeline.process(packet());
expect(dispatched).toHaveLength(1);
expect(packetTrace(entries).map((entry) => entry.message)).toEqual([
'packet_branch serviceCmd="Trace.Command" seqId=77 parser=1 branch=parser_events events=1',
'packet_branch serviceCmd="Trace.Command" seqId=77 branch=enrichment_started eventKind="group_member_join" enrichment="identity_refresh"',
'packet_branch serviceCmd="Trace.Command" seqId=77 branch=enrichment_degraded eventKind="group_member_join" enrichment="identity_refresh" error="fixture refresh failed"',
'packet_branch serviceCmd="Trace.Command" seqId=77 branch=dispatch eventKind="group_member_join" mode=enriched',
expect.stringMatching(/^packet_terminal serviceCmd="Trace\.Command" seqId=77 outcome=completed reason=dispatch_complete events=1 dispatched=1 parserErrors=0 elapsedMs=\d+$/),
]);
} finally {
unsubscribe();
}
});
it('distinguishes enrichment failure from enriched dispatch failure', async () => {
const enrichmentEntries: LogEntry[] = [];
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => enrichmentEntries.push(entry));
try {
const enrichment = makePipeline();
vi.spyOn(enrichment.identity, 'rememberRequestIdentity')
.mockImplementation(() => {
throw new Error('fixture enrichment failed');
});
enrichment.pipeline.registerCmd('Trace.Command', () => [{
kind: 'group_invite',
time: 1,
selfUin: 10001,
groupId: 123,
fromUin: 0,
fromUid: 'u_stranger',
subType: 'add',
message: '',
flag: 'add:123:u_stranger',
} as QQEventVariant]);
await enrichment.pipeline.process(packet());
expect(packetTrace(enrichmentEntries).map((entry) => entry.message)).toEqual([
'packet_branch serviceCmd="Trace.Command" seqId=77 parser=1 branch=parser_events events=1',
'packet_branch serviceCmd="Trace.Command" seqId=77 branch=enrichment_started eventKind="group_invite" enrichment="group_invite"',
'packet_branch serviceCmd="Trace.Command" seqId=77 branch=enrichment_failed eventKind="group_invite" enrichment="group_invite" error="fixture enrichment failed"',
expect.stringMatching(/^packet_terminal serviceCmd="Trace\.Command" seqId=77 outcome=failed reason=enrichment_failed events=1 dispatched=0 parserErrors=0 dispatchErrors=0 elapsedMs=\d+$/),
]);
enrichmentEntries.length = 0;
const dispatch = makePipeline();
vi.spyOn(dispatch.identity, 'rememberGroupMemberIdentity')
.mockImplementation(() => {
throw new Error('fixture enriched dispatch failed');
});
dispatch.pipeline.registerCmd('Trace.Command', () => [{
kind: 'group_member_join',
time: 1,
selfUin: 10001,
groupId: 123,
userUin: 0,
operatorUin: 0,
userUid: 'u_new_member',
operatorUid: 'u_operator',
}]);
await dispatch.pipeline.process(packet());
expect(packetTrace(enrichmentEntries).map((entry) => entry.message)).toEqual([
'packet_branch serviceCmd="Trace.Command" seqId=77 parser=1 branch=parser_events events=1',
'packet_branch serviceCmd="Trace.Command" seqId=77 branch=enrichment_started eventKind="group_member_join" enrichment="identity_refresh"',
'packet_branch serviceCmd="Trace.Command" seqId=77 branch=dispatch_exception eventKind="group_member_join" error="fixture enriched dispatch failed"',
expect.stringMatching(/^packet_terminal serviceCmd="Trace\.Command" seqId=77 outcome=failed reason=dispatch_exception events=1 dispatched=0 parserErrors=0 dispatchErrors=1 elapsedMs=\d+$/),
]);
} finally {
unsubscribe();
}
});
it('retains request context through asynchronous enrichment before terminal', async () => {
let release!: (value: { uin: number; nickname: string }) => void;
const profile = new Promise<{ uin: number; nickname: string }>((resolve) => { release = resolve; });
const entries: LogEntry[] = [];
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
try {
const { pipeline, dispatched } = makePipeline({
resolveStrangerProfile: () => profile,
});
pipeline.registerCmd('Trace.Command', () => [{
kind: 'group_invite',
time: 1,
selfUin: 10001,
groupId: 123,
fromUin: 0,
fromUid: 'u_stranger',
subType: 'add',
message: '',
flag: 'add:123:u_stranger',
} as QQEventVariant]);
const completion = runWithRequestId(5101, () => pipeline.process(packet()));
expect(dispatched).toHaveLength(0);
release({ uin: 20002, nickname: 'resolved' });
await completion;
expect(dispatched).toEqual([
expect.objectContaining({ req: 5101 }),
]);
expect(packetTrace(entries)).toEqual(
packetTrace(entries).map(() => expect.objectContaining({ req: 5101 })),
);
expect(packetTrace(entries).map((entry) => entry.message)).toEqual([
'packet_branch serviceCmd="Trace.Command" seqId=77 parser=1 branch=parser_events events=1',
'packet_branch serviceCmd="Trace.Command" seqId=77 branch=enrichment_started eventKind="group_invite" enrichment="group_invite"',
'packet_branch serviceCmd="Trace.Command" seqId=77 branch=dispatch eventKind="group_invite" mode=enriched',
expect.stringMatching(/^packet_terminal serviceCmd="Trace\.Command" seqId=77 outcome=completed reason=dispatch_complete events=1 dispatched=1 parserErrors=0 elapsedMs=\d+$/),
]);
} finally {
unsubscribe();
}
});
});