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

+64 -2
View File
@@ -115,9 +115,43 @@ export function parseMsgPush(
pkt: PacketInfo,
identity: IdentityService,
dedup?: SysMsgDedup,
): QQEventVariant[] {
return parseMsgPushInternal(
pkt,
identity,
dedup,
false,
);
}
export function parseMsgPushOrThrow(
pkt: PacketInfo,
identity: IdentityService,
dedup?: SysMsgDedup,
): QQEventVariant[] {
return parseMsgPushInternal(
pkt,
identity,
dedup,
true,
);
}
function parseMsgPushInternal(
pkt: PacketInfo,
identity: IdentityService,
dedup: SysMsgDedup | undefined,
throwDecoderErrors: boolean,
): QQEventVariant[] {
const ctx = buildContext(pkt, identity);
if (!ctx) return [];
if (!ctx) {
log.trace(() => [
'packet_branch serviceCmd=%j seqId=%d branch=push_context_invalid',
pkt.serviceCmd,
pkt.seqId,
]);
return [];
}
// #137/#266: mirror QQ NT `sys_msg_mgr.cc::ProcessRecvSysMsg` before
// dispatch. Its static routing table is the scope boundary: listed routes
@@ -127,6 +161,15 @@ export function parseMsgPush(
if (dedup) {
const dedupIdentity = deriveSysMsgDedupIdentity(ctx);
if (dedupIdentity && dedup.seenDuplicate(dedupIdentity)) {
log.trace(() => [
'packet_branch serviceCmd=%j seqId=%d branch=duplicate_system_push peer=%j chatType=%d messageSeq=%d messageRandom=%d',
pkt.serviceCmd,
pkt.seqId,
dedupIdentity.peerUid,
dedupIdentity.chatType,
dedupIdentity.sequence,
dedupIdentity.random,
]);
log.debug(
'dropped duplicate system push (peer=%s chatType=%d seq=%d msgType=%d/%d msgId=%d)',
dedupIdentity.peerUid,
@@ -140,13 +183,24 @@ export function parseMsgPush(
}
}
const events = registry.decode(ctx);
const events = throwDecoderErrors
? registry.decodeOrThrow(ctx)
: registry.decode(ctx);
const out = events.filter((ev) => {
if (!MESSAGE_KINDS.has(ev.kind)) return true;
// C2C control/system signal (#102): QQ NT routes these via OnRecvSysMsg and
// never shows them as a bubble. Drop by (msgType, c2cCmd) regardless of body
// — the precise discriminator, the group-invite "[空消息]" phantom being one.
if (isC2cControlPush(ctx.head)) {
log.trace(() => [
'packet_branch serviceCmd=%j seqId=%d branch=c2c_control_push msgType=%d subType=%d c2cCmd=%d messageSeq=%d',
pkt.serviceCmd,
pkt.seqId,
ctx.head.msgType,
ctx.head.subType,
ctx.head.c2cCmd,
ctx.head.sequence,
]);
const elemCount = (ev as { elements?: unknown[] }).elements?.length ?? 0;
if (elemCount > 0) {
log.debug('dropped c2c control push that carried %d element(s) (kind=%s seq=%d from=%d msgType=%d cmd=%d)',
@@ -170,6 +224,14 @@ export function parseMsgPush(
warnMissingC2cSequence(ev, ctx.fromUin);
return true;
}
log.trace(() => [
'packet_branch serviceCmd=%j seqId=%d branch=empty_message msgType=%d subType=%d messageSeq=%d',
pkt.serviceCmd,
pkt.seqId,
ctx.head.msgType,
ctx.head.subType,
ctx.head.sequence,
]);
return false;
});
+42 -9
View File
@@ -22,21 +22,54 @@ export class MsgPushRegistry {
}
decode(ctx: MsgPushContext): QQEventVariant[] {
const decoder = this.decoders_.get(ctx.head.msgType as PkgType);
if (!decoder) {
// Unrecognized PkgType: either we don't care about this notify, or
// the QQ NT client added a new variant. Surface at debug so a
// protocol change can be spotted without spamming production logs.
unknownLog.debug('no decoder for PkgType=%d subType=%d', ctx.head.msgType, ctx.head.subType);
return [];
}
try {
return decoder(ctx);
return this.runDecoder(ctx);
} catch (e) {
this.traceDecoderException(ctx, e);
log.error('decoder error for PkgType=%d subType=%d: %s',
ctx.head.msgType, ctx.head.subType,
e instanceof Error ? (e.stack ?? e.message) : String(e));
return [];
}
}
decodeOrThrow(ctx: MsgPushContext): QQEventVariant[] {
try {
return this.runDecoder(ctx);
} catch (e) {
this.traceDecoderException(ctx, e);
throw e;
}
}
private runDecoder(ctx: MsgPushContext): QQEventVariant[] {
const decoder = this.decoders_.get(ctx.head.msgType as PkgType);
if (!decoder) {
unknownLog.trace(() => [
'packet_branch branch=decoder_unregistered msgType=%d subType=%d messageSeq=%d',
ctx.head.msgType,
ctx.head.subType,
ctx.head.sequence,
]);
// Unrecognized PkgType: either we don't care about this notify, or
// the QQ NT client added a new variant. Surface at debug so a
// protocol change can be spotted without spamming production logs.
unknownLog.debug('no decoder for PkgType=%d subType=%d', ctx.head.msgType, ctx.head.subType);
return [];
}
return decoder(ctx);
}
private traceDecoderException(
ctx: MsgPushContext,
error: unknown,
): void {
log.trace(() => [
'packet_branch branch=decoder_exception msgType=%d subType=%d messageSeq=%d error=%j',
ctx.head.msgType,
ctx.head.subType,
ctx.head.sequence,
error instanceof Error ? error.message : String(error),
]);
}
}
+293 -26
View File
@@ -8,6 +8,7 @@ import { formatGroupRequestFlag, type GroupRequestInfo } from './qq-info';
const moduleLog = createLogger('Bridge');
const moduleEventLog = createLogger('Event');
const modulePacketLog = createLogger('Protocol.Packet');
// Notice kinds that get logged as a warning (operationally important
// state changes that an operator probably wants to see at default
@@ -25,6 +26,17 @@ type GroupMemberIdentityEvent = Extract<QQEventVariant, { kind: 'group_member_jo
export type CmdParser = (pkt: PacketInfo, identity: IdentityService) => QQEventVariant[];
class EnrichedDispatchError extends Error {
constructor(readonly originalError: unknown) {
super(
originalError instanceof Error
? originalError.message
: String(originalError),
);
this.name = 'EnrichedDispatchError';
}
}
export interface PacketPipelineDeps {
identity: IdentityService;
events: BridgeEventBus;
@@ -68,6 +80,7 @@ export class IncomingPacketPipeline {
private memberRefreshTasks_ = new Map<number, Promise<void>>();
private readonly log: Logger;
private readonly eventLog: Logger;
private readonly packetLog: Logger;
constructor(private readonly deps: PacketPipelineDeps) {
// Tag every line we emit with this Bridge's UIN so per-account file
@@ -77,6 +90,7 @@ export class IncomingPacketPipeline {
const bind = Number.isFinite(uinNum) && uinNum > 0 ? { uin: uinNum } : null;
this.log = bind ? moduleLog.child(bind) : moduleLog;
this.eventLog = bind ? moduleEventLog.child(bind) : moduleEventLog;
this.packetLog = bind ? modulePacketLog.child(bind) : modulePacketLog;
}
registerCmd(cmd: string, parser: CmdParser): void {
@@ -89,37 +103,254 @@ export class IncomingPacketPipeline {
return this.cmdHandlers_.has(cmd);
}
process(pkt: PacketInfo): void {
process(pkt: PacketInfo): Promise<void> {
const startedAt = Date.now();
const handlers = this.cmdHandlers_.get(pkt.serviceCmd);
if (!handlers) return;
if (!handlers) {
this.packetLog.trace(() => [
'packet_branch serviceCmd=%j seqId=%d branch=parser_unregistered',
pkt.serviceCmd,
pkt.seqId,
]);
this.packetLog.trace(() => [
'packet_terminal serviceCmd=%j seqId=%d outcome=dropped reason=parser_unregistered events=0 dispatched=0 elapsedMs=%d',
pkt.serviceCmd,
pkt.seqId,
Date.now() - startedAt,
]);
return Promise.resolve();
}
for (const handler of handlers) {
let eventCount = 0;
let dispatched = 0;
let parserErrors = 0;
let dispatchErrors = 0;
let enrichmentFailures = 0;
const enrichmentTasks: Promise<void>[] = [];
handlers.forEach((handler, index) => {
const parser = index + 1;
try {
const events = handler(pkt, this.deps.identity);
if (events.length === 0) {
this.packetLog.trace(() => [
'packet_branch serviceCmd=%j seqId=%d parser=%d branch=parser_zero_events',
pkt.serviceCmd,
pkt.seqId,
parser,
]);
return;
}
eventCount += events.length;
this.packetLog.trace(() => [
'packet_branch serviceCmd=%j seqId=%d parser=%d branch=parser_events events=%d',
pkt.serviceCmd,
pkt.seqId,
parser,
events.length,
]);
for (const event of events) {
if (this.needsPreDispatchIdentityRefresh(event)) {
void this.dispatchAfterIdentityRefresh(event).catch((err) => {
this.log.warn('dispatchAfterIdentityRefresh failed: %s',
err instanceof Error ? (err.stack ?? err.message) : String(err));
});
this.traceEnrichmentStarted(pkt, event, 'identity_refresh');
const task = this.dispatchAfterIdentityRefresh(pkt, event)
.then((count) => { dispatched += count; })
.catch((error) => {
if (error instanceof EnrichedDispatchError) {
dispatchErrors += 1;
this.traceDispatchFailure(
pkt,
event,
error.originalError,
);
} else {
enrichmentFailures += 1;
this.traceEnrichmentFailure(pkt, event, 'identity_refresh', error);
}
this.log.warn('dispatchAfterIdentityRefresh failed: %s',
error instanceof Error ? (error.stack ?? error.message) : String(error));
});
enrichmentTasks.push(task);
} else if (this.needsGroupInviteEnrich(event)) {
void this.dispatchGroupInvite(event).catch((err) => {
this.log.warn('dispatchGroupInvite failed: %s',
err instanceof Error ? (err.stack ?? err.message) : String(err));
});
this.traceEnrichmentStarted(pkt, event, 'group_invite');
const task = this.dispatchGroupInvite(pkt, event)
.then((count) => { dispatched += count; })
.catch((error) => {
if (error instanceof EnrichedDispatchError) {
dispatchErrors += 1;
this.traceDispatchFailure(
pkt,
event,
error.originalError,
);
} else {
enrichmentFailures += 1;
this.traceEnrichmentFailure(pkt, event, 'group_invite', error);
}
this.log.warn('dispatchGroupInvite failed: %s',
error instanceof Error ? (error.stack ?? error.message) : String(error));
});
enrichmentTasks.push(task);
} else {
// Snapshot the sender's cached group card BEFORE dispatch — the
// side-effects inside finishDispatch self-heal (overwrite) it, so we
// must read it first to detect a real change and surface group_card.
const cardBefore = this.groupCardBefore(event);
this.finishDispatch(event);
this.emitGroupCardChange(event, cardBefore);
try {
dispatched += this.dispatchEvent(pkt, event, 'sync');
} catch (error) {
dispatchErrors += 1;
this.traceDispatchFailure(
pkt,
event,
error,
);
this.log.error('dispatch error for %s event=%s: %s',
pkt.serviceCmd, event.kind,
error instanceof Error ? (error.stack ?? error.message) : String(error));
break;
}
}
}
} catch (e) {
this.log.error('handler error for %s: %s', pkt.serviceCmd, e instanceof Error ? (e.stack ?? e.message) : String(e));
} catch (error) {
parserErrors += 1;
this.packetLog.trace(() => [
'packet_branch serviceCmd=%j seqId=%d parser=%d branch=parser_exception error=%j',
pkt.serviceCmd,
pkt.seqId,
parser,
error instanceof Error ? error.message : String(error),
]);
this.log.error('handler error for %s: %s', pkt.serviceCmd,
error instanceof Error ? (error.stack ?? error.message) : String(error));
}
});
const finish = (): void => {
if (enrichmentFailures > 0 || dispatchErrors > 0) {
this.packetLog.trace(() => [
'packet_terminal serviceCmd=%j seqId=%d outcome=failed reason=%s events=%d dispatched=%d parserErrors=%d dispatchErrors=%d elapsedMs=%d',
pkt.serviceCmd,
pkt.seqId,
enrichmentFailures > 0 ? 'enrichment_failed' : 'dispatch_exception',
eventCount,
dispatched,
parserErrors,
dispatchErrors,
Date.now() - startedAt,
]);
return;
}
if (parserErrors > 0) {
this.packetLog.trace(() => [
'packet_terminal serviceCmd=%j seqId=%d outcome=failed reason=parser_exception events=%d dispatched=%d parserErrors=%d elapsedMs=%d',
pkt.serviceCmd,
pkt.seqId,
eventCount,
dispatched,
parserErrors,
Date.now() - startedAt,
]);
return;
}
if (dispatched > 0) {
this.packetLog.trace(() => [
'packet_terminal serviceCmd=%j seqId=%d outcome=completed reason=dispatch_complete events=%d dispatched=%d parserErrors=%d elapsedMs=%d',
pkt.serviceCmd,
pkt.seqId,
eventCount,
dispatched,
parserErrors,
Date.now() - startedAt,
]);
return;
}
this.packetLog.trace(() => [
'packet_terminal serviceCmd=%j seqId=%d outcome=%s reason=%s events=%d dispatched=0 parserErrors=%d elapsedMs=%d',
pkt.serviceCmd,
pkt.seqId,
parserErrors > 0 ? 'failed' : 'dropped',
parserErrors > 0 ? 'parser_exception' : 'no_events',
eventCount,
parserErrors,
Date.now() - startedAt,
]);
};
if (enrichmentTasks.length === 0) {
finish();
return Promise.resolve();
}
return Promise.all(enrichmentTasks).then(finish);
}
private traceEnrichmentStarted(
pkt: PacketInfo,
event: QQEventVariant,
enrichment: 'identity_refresh' | 'group_invite',
): void {
this.packetLog.trace(() => [
'packet_branch serviceCmd=%j seqId=%d branch=enrichment_started eventKind=%j enrichment=%j',
pkt.serviceCmd,
pkt.seqId,
event.kind,
enrichment,
]);
}
private traceEnrichmentFailure(
pkt: PacketInfo,
event: QQEventVariant,
enrichment: 'identity_refresh' | 'group_invite',
error: unknown,
): void {
this.packetLog.trace(() => [
'packet_branch serviceCmd=%j seqId=%d branch=enrichment_failed eventKind=%j enrichment=%j error=%j',
pkt.serviceCmd,
pkt.seqId,
event.kind,
enrichment,
error instanceof Error ? error.message : String(error),
]);
}
private traceDispatchFailure(
pkt: PacketInfo,
event: QQEventVariant,
error: unknown,
): void {
this.packetLog.trace(() => [
'packet_branch serviceCmd=%j seqId=%d branch=dispatch_exception eventKind=%j error=%j',
pkt.serviceCmd,
pkt.seqId,
event.kind,
error instanceof Error ? error.message : String(error),
]);
}
private traceDispatch(
pkt: PacketInfo,
eventKind: QQEventVariant['kind'],
mode: 'sync' | 'enriched' | 'derived',
): void {
this.packetLog.trace(() => [
'packet_branch serviceCmd=%j seqId=%d branch=dispatch eventKind=%j mode=%s',
pkt.serviceCmd,
pkt.seqId,
eventKind,
mode,
]);
}
private dispatchEvent(
pkt: PacketInfo,
event: QQEventVariant,
mode: 'sync' | 'enriched',
alreadyRefreshed = false,
): number {
// Snapshot the sender's cached group card BEFORE dispatch — the side-effects
// inside finishDispatch self-heal it, so the old value must be read first.
const cardBefore = this.groupCardBefore(event);
this.finishDispatch(event, alreadyRefreshed);
this.traceDispatch(pkt, event.kind, mode);
if (!this.emitGroupCardChange(event, cardBefore)) return 1;
this.traceDispatch(pkt, 'group_card_change', 'derived');
return 2;
}
private emit(event: QQEventVariant): void {
@@ -139,10 +370,10 @@ export class IncomingPacketPipeline {
* mirrors NapCat's `parseCardChangedEvent`. Requires a non-empty prior card
* (`cardBefore`) that differs from a non-empty new one, so a cold/unknown
* cache never fabricates a change on first contact. */
private emitGroupCardChange(event: QQEventVariant, cardBefore: string | undefined): void {
if (event.kind !== 'group_message') return;
private emitGroupCardChange(event: QQEventVariant, cardBefore: string | undefined): boolean {
if (event.kind !== 'group_message') return false;
const cardNew = event.senderCard ?? '';
if (!cardBefore || !cardNew || cardBefore === cardNew) return;
if (!cardBefore || !cardNew || cardBefore === cardNew) return false;
this.finishDispatch({
kind: 'group_card_change',
time: event.time,
@@ -152,6 +383,7 @@ export class IncomingPacketPipeline {
cardNew,
cardOld: cardBefore,
});
return true;
}
/**
@@ -192,19 +424,36 @@ export class IncomingPacketPipeline {
return event.kind === 'group_invite' && !!event.fromUid;
}
private async dispatchAfterIdentityRefresh(event: Extract<QQEventVariant, { kind: 'group_member_join' }>): Promise<void> {
private async dispatchAfterIdentityRefresh(
pkt: PacketInfo,
event: Extract<QQEventVariant, { kind: 'group_member_join' }>,
): Promise<number> {
let refreshed = false;
try {
refreshed = await this.prepareGroupMemberJoinIdentity(event);
} catch (e) {
this.packetLog.trace(() => [
'packet_branch serviceCmd=%j seqId=%d branch=enrichment_degraded eventKind=%j enrichment="identity_refresh" error=%j',
pkt.serviceCmd,
pkt.seqId,
event.kind,
e instanceof Error ? e.message : String(e),
]);
this.log.warn('failed to resolve group member join identity: group=%d uid=%s err=%s',
event.groupId, event.userUid ?? '', e instanceof Error ? e.message : String(e));
}
this.finishDispatch(event, refreshed);
try {
return this.dispatchEvent(pkt, event, 'enriched', refreshed);
} catch (error) {
throw new EnrichedDispatchError(error);
}
}
private async dispatchGroupInvite(event: Extract<QQEventVariant, { kind: 'group_invite' }>): Promise<void> {
private async dispatchGroupInvite(
pkt: PacketInfo,
event: Extract<QQEventVariant, { kind: 'group_invite' }>,
): Promise<number> {
const uid = event.fromUid;
if (uid) {
// Record the requester's identity up-front (synchronously), mirroring the
@@ -245,6 +494,13 @@ export class IncomingPacketPipeline {
source: 'group_request',
});
} else if (profileR.status === 'rejected') {
this.packetLog.trace(() => [
'packet_branch serviceCmd=%j seqId=%d branch=enrichment_degraded eventKind=%j enrichment="stranger_profile" error=%j',
pkt.serviceCmd,
pkt.seqId,
event.kind,
profileR.reason instanceof Error ? profileR.reason.message : String(profileR.reason),
]);
this.log.warn('failed to resolve stranger profile: uid=%s err=%s',
uid, profileR.reason instanceof Error ? profileR.reason.message : String(profileR.reason));
}
@@ -282,13 +538,24 @@ export class IncomingPacketPipeline {
}
}
} else if (requestR.status === 'rejected') {
this.packetLog.trace(() => [
'packet_branch serviceCmd=%j seqId=%d branch=enrichment_degraded eventKind=%j enrichment="group_join_request" error=%j',
pkt.serviceCmd,
pkt.seqId,
event.kind,
requestR.reason instanceof Error ? requestR.reason.message : String(requestR.reason),
]);
this.log.warn('failed to resolve group join request: groupId=%d uid=%s err=%s',
event.groupId, uid,
requestR.reason instanceof Error ? requestR.reason.message : String(requestR.reason));
}
}
this.finishDispatch(event);
try {
return this.dispatchEvent(pkt, event, 'enriched');
} catch (error) {
throw new EnrichedDispatchError(error);
}
}
private async prepareGroupMemberJoinIdentity(event: Extract<QQEventVariant, { kind: 'group_member_join' }>): Promise<boolean> {
@@ -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();
}
});
});