From 7ec479bb889e88cd3d6dbc80e9bfd7304b0b5f11 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Mon, 18 May 2026 01:29:06 +0800 Subject: [PATCH] feat(logger): protocol-layer observability for highway and msg-push MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Highway upload path now emits per-type entry + shared pipeline ops: DEBUG [Highway.Image] uploading 234567 bytes md5=abc12345... → group 12345 DEBUG [Highway] image OIDB requires bytes, PUT 234567 bytes (sub=top) DEBUG [Highway] image PUT done in 1234ms -- or -- DEBUG [Highway] image fast-upload hit (server already had bytes) The three pipeline-side lines come from runNtv2Upload() and are shared across image/video/ptt; the per-type entry log lives in each *-upload.ts wrapper so the scope identifies the media kind. md5 is truncated to its first 8 hex chars for line width; PUT latency is reported in ms. MsgPush silent dispatch defaults are now visible at debug: DEBUG [MsgPush.Unknown] no decoder for PkgType=999 subType=0 DEBUG [MsgPush.Unknown] Event0x2DC unknown subType=42 DEBUG [MsgPush.Unknown] Event0x210 unknown subType=42 Captures protocol drift (new NT QQ subtypes) and "we forgot to register this PkgType" oversights, neither of which used to leave any trace in the log. All new lines are debug-level so console output (default info) stays unchanged; file transport sees them for post-mortem. --- .../core/src/bridge/highway/image-upload.ts | 15 ++ packages/core/src/bridge/highway/pipeline.ts | 17 ++ .../core/src/bridge/highway/ptt-upload.ts | 17 +- .../core/src/bridge/highway/video-upload.ts | 18 +- .../bridge/msg-push/decoders/event-0x210.ts | 4 + .../bridge/msg-push/decoders/event-0x2dc.ts | 4 + packages/core/src/bridge/msg-push/registry.ts | 9 +- .../core/tests/observability-logs.test.ts | 188 ++++++++++++++++++ 8 files changed, 266 insertions(+), 6 deletions(-) create mode 100644 packages/core/tests/observability-logs.test.ts diff --git a/packages/core/src/bridge/highway/image-upload.ts b/packages/core/src/bridge/highway/image-upload.ts index 4a670890..6d43e303 100644 --- a/packages/core/src/bridge/highway/image-upload.ts +++ b/packages/core/src/bridge/highway/image-upload.ts @@ -7,6 +7,7 @@ import type { Bridge } from '../bridge'; import type { MessageElement } from '../events'; +import { createLogger } from '../../utils/logger'; import { GROUP_IMAGE_CMD_ID, PRIVATE_IMAGE_CMD_ID } from './highway-client'; import { finalizeMediaMsgInfo, @@ -16,6 +17,14 @@ import { } from './pipeline'; import { computeHashes, detectImageFormat, loadBinarySource } from './utils'; +const moduleLog = createLogger('Highway.Image'); + +function loggerFor(bridge: Bridge) { + const raw = bridge.identity?.uin; + const uin = typeof raw === 'string' ? Number.parseInt(raw, 10) : 0; + return Number.isFinite(uin) && uin > 0 ? moduleLog.child({ uin }) : moduleLog; +} + interface ImageData { /** Empty when the caller is forwarding from cached fingerprints. */ bytes: Uint8Array; @@ -106,7 +115,13 @@ export async function uploadImageMsgInfo( targetIdOrUid: string | number, element: MessageElement, ): Promise { + const log = loggerFor(bridge); const image = await loadImage(element); + log.debug('uploading %d bytes md5=%s... → %s %s', + image.fileSize, + image.md5Hex.slice(0, 8), + isGroup ? 'group' : 'c2c', + String(targetIdOrUid)); const uploads: MediaSubFileUpload[] = [{ source: 'top', diff --git a/packages/core/src/bridge/highway/pipeline.ts b/packages/core/src/bridge/highway/pipeline.ts index ee4fd5d6..b04b6b32 100644 --- a/packages/core/src/bridge/highway/pipeline.ts +++ b/packages/core/src/bridge/highway/pipeline.ts @@ -25,6 +25,9 @@ import { NTV2UploadRichMediaRespSchema, } from '../proto/highway'; import { buildHighwayExtend, fetchHighwaySession, uploadHighwayHttp } from './highway-client'; +import { createLogger } from '../../utils/logger'; + +const moduleLog = createLogger('Highway'); // ─────────────── public types ─────────────── @@ -123,6 +126,11 @@ export function hexToBytes(hex: string): Uint8Array { export async function runNtv2Upload(params: NtV2UploadParams): Promise { const { bridge, isGroup, targetIdOrUid, oidbCmd, serviceCmd, uploads } = params; const label = params.label ?? 'media'; + const raw = bridge.identity?.uin; + const uinNum = typeof raw === 'string' ? Number.parseInt(raw, 10) : 0; + const log = Number.isFinite(uinNum) && uinNum > 0 + ? moduleLog.child({ uin: uinNum }) + : moduleLog; // Build the full body once. Pulling this in here means each format file // only specifies the seven fields that actually vary. @@ -184,6 +192,7 @@ export async function runNtv2Upload(params: NtV2UploadParams): Promise { return session; }; + let didPut = false; for (const sub of uploads) { const target = sub.source === 'top' ? upload : upload.subFileInfos?.[sub.source]; const uKey = target?.uKey ?? ''; @@ -203,7 +212,15 @@ export async function runNtv2Upload(params: NtV2UploadParams): Promise { sub.sha1 as any, // sha1 may be Uint8Array | Uint8Array[]; the helper accepts both sub.subFileIndex ?? 0, ); + log.debug('%s OIDB requires bytes, PUT %d bytes (sub=%s)', label, sub.bytes.length, String(sub.source)); + const t0 = Date.now(); await uploadHighwayHttp(bridge, await getSession(), sub.cmdId, sub.bytes, sub.md5, extend); + log.debug('%s PUT done in %dms', label, Date.now() - t0); + didPut = true; + } + + if (!didPut) { + log.debug('%s fast-upload hit (server already had bytes)', label); } return upload; diff --git a/packages/core/src/bridge/highway/ptt-upload.ts b/packages/core/src/bridge/highway/ptt-upload.ts index ccb617b8..b3cf868b 100644 --- a/packages/core/src/bridge/highway/ptt-upload.ts +++ b/packages/core/src/bridge/highway/ptt-upload.ts @@ -22,7 +22,13 @@ import { type MediaSubFileUpload, } from './pipeline'; -const log = createLogger('Ptt'); +const moduleLog = createLogger('Highway.Ptt'); + +function loggerFor(bridge: Bridge) { + const raw = bridge.identity?.uin; + const uin = typeof raw === 'string' ? Number.parseInt(raw, 10) : 0; + return Number.isFinite(uin) && uin > 0 ? moduleLog.child({ uin }) : moduleLog; +} export const PRIVATE_PTT_CMD_ID = 1007; export const GROUP_PTT_CMD_ID = 1008; @@ -105,7 +111,7 @@ async function loadPtt(element: MessageElement, tempDir: string): Promise { try { fs.unlinkSync(silk.path); } catch { /* ignore */ } }); - log.debug('converted record to silk: %s -> %s (duration=%ds)', inputPath, silk.path, silk.duration); + moduleLog.debug('converted record to silk: %s -> %s (duration=%ds)', inputPath, silk.path, silk.duration); } const silkBytes = new Uint8Array(fs.readFileSync(silk.path)); @@ -141,8 +147,15 @@ export async function uploadPttMsgInfo( targetIdOrUid: string | number, element: MessageElement, ): Promise { + const log = loggerFor(bridge); const tempDir = defaultPttTempDir(); const ptt = await loadPtt(element, tempDir); + log.debug('uploading %d bytes md5=%s... → %s %s duration=%ds', + ptt.fileSize, + ptt.md5Hex.slice(0, 8), + isGroup ? 'group' : 'c2c', + String(targetIdOrUid), + ptt.duration); try { const uploads: MediaSubFileUpload[] = [{ source: 'top', diff --git a/packages/core/src/bridge/highway/video-upload.ts b/packages/core/src/bridge/highway/video-upload.ts index a0778c6e..96191ad3 100644 --- a/packages/core/src/bridge/highway/video-upload.ts +++ b/packages/core/src/bridge/highway/video-upload.ts @@ -29,7 +29,13 @@ import { type MediaSubFileUpload, } from './pipeline'; -const log = createLogger('Video'); +const moduleLog = createLogger('Highway.Video'); + +function loggerFor(bridge: Bridge) { + const raw = bridge.identity?.uin; + const uin = typeof raw === 'string' ? Number.parseInt(raw, 10) : 0; + return Number.isFinite(uin) && uin > 0 ? moduleLog.child({ uin }) : moduleLog; +} export const PRIVATE_VIDEO_CMD_ID = 1001; export const PRIVATE_VIDEO_THUMB_CMD_ID = 1002; @@ -323,7 +329,7 @@ async function loadThumb(element: MessageElement, videoPath: string): Promise<{ try { thumbBytes = (await loadBinarySource(element.thumbUrl, 'video thumbnail')).bytes; } catch (err) { - log.warn('custom video thumbnail load failed: %s', err instanceof Error ? err.message : String(err)); + moduleLog.warn('custom video thumbnail load failed: %s', err instanceof Error ? err.message : String(err)); } } @@ -337,7 +343,7 @@ async function loadThumb(element: MessageElement, videoPath: string): Promise<{ thumbBytes = new Uint8Array(info.image); } } catch (err) { - log.warn('video thumbnail generation failed: %s', err instanceof Error ? err.message : String(err)); + moduleLog.warn('video thumbnail generation failed: %s', err instanceof Error ? err.message : String(err)); } } @@ -430,7 +436,13 @@ export async function uploadVideoMsgInfo( targetIdOrUid: string | number, element: MessageElement, ): Promise { + const log = loggerFor(bridge); const video = await loadVideo(element); + log.debug('uploading %d bytes md5=%s... → %s %s', + video.fileSize, + video.md5Hex.slice(0, 8), + isGroup ? 'group' : 'c2c', + String(targetIdOrUid)); try { const uploads: MediaSubFileUpload[] = [ { diff --git a/packages/core/src/bridge/msg-push/decoders/event-0x210.ts b/packages/core/src/bridge/msg-push/decoders/event-0x210.ts index 5343d4bb..cbce944f 100644 --- a/packages/core/src/bridge/msg-push/decoders/event-0x210.ts +++ b/packages/core/src/bridge/msg-push/decoders/event-0x210.ts @@ -14,6 +14,9 @@ import { Event0x210SubType } from '../enums'; import { resolveUidToUin, parseU64OrZero, buildTemplateMap, findTemplateValue, } from '../helpers'; +import { createLogger } from '../../../utils/logger'; + +const unknownLog = createLogger('MsgPush.Unknown'); export const decodeEvent0x210: MsgPushDecoder = (ctx) => { switch (ctx.head.subType as Event0x210SubType) { @@ -21,6 +24,7 @@ export const decodeEvent0x210: MsgPushDecoder = (ctx) => { case Event0x210SubType.FriendRecallNotice: return decodeFriendRecall(ctx); case Event0x210SubType.FriendPokeNotice: return decodeFriendPoke(ctx); } + unknownLog.debug('Event0x210 unknown subType=%d', ctx.head.subType); return []; }; diff --git a/packages/core/src/bridge/msg-push/decoders/event-0x2dc.ts b/packages/core/src/bridge/msg-push/decoders/event-0x2dc.ts index e8f485a8..7b072b83 100644 --- a/packages/core/src/bridge/msg-push/decoders/event-0x2dc.ts +++ b/packages/core/src/bridge/msg-push/decoders/event-0x2dc.ts @@ -16,6 +16,9 @@ import { resolveUidToUin, parseU64OrZero, buildTemplateMap, findTemplateValue, unwrapGroupNotifyPayload, } from '../helpers'; +import { createLogger } from '../../../utils/logger'; + +const unknownLog = createLogger('MsgPush.Unknown'); export const decodeEvent0x2DC: MsgPushDecoder = (ctx) => { switch (ctx.head.subType as Event0x2DCSubType) { @@ -24,6 +27,7 @@ export const decodeEvent0x2DC: MsgPushDecoder = (ctx) => { case Event0x2DCSubType.GroupGreyTipNotice: return decodeGroupGreyTip(ctx); case Event0x2DCSubType.GroupEssenceNotice: return decodeGroupEssence(ctx); } + unknownLog.debug('Event0x2DC unknown subType=%d', ctx.head.subType); return []; }; diff --git a/packages/core/src/bridge/msg-push/registry.ts b/packages/core/src/bridge/msg-push/registry.ts index 1ac309ec..4a3e9a18 100644 --- a/packages/core/src/bridge/msg-push/registry.ts +++ b/packages/core/src/bridge/msg-push/registry.ts @@ -9,6 +9,7 @@ import type { MsgPushContext } from './context'; import type { PkgType } from './enums'; const log = createLogger('MsgPush'); +const unknownLog = createLogger('MsgPush.Unknown'); export type MsgPushDecoder = (ctx: MsgPushContext) => QQEventVariant[]; @@ -27,7 +28,13 @@ export class MsgPushRegistry { decode(ctx: MsgPushContext): QQEventVariant[] { const decoder = this.decoders_.get(ctx.head.msgType as PkgType); - if (!decoder) return []; + 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); } catch (e) { diff --git a/packages/core/tests/observability-logs.test.ts b/packages/core/tests/observability-logs.test.ts new file mode 100644 index 00000000..ee3a871e --- /dev/null +++ b/packages/core/tests/observability-logs.test.ts @@ -0,0 +1,188 @@ +// Tests for the new PR5 observability log lines: +// - [Highway.Image] entry log on uploadImageMsgInfo +// - [Highway] fast-upload hit when OIDB returns no uKey +// - [Highway] OIDB-requires-bytes + PUT-done with elapsed ms +// - [MsgPush.Unknown] unrecognized PkgType +// - [MsgPush.Unknown] wrapper decoder unknown subType +// +// Highway transport is mocked the same way pipeline.test.ts does it so +// runNtv2Upload exercises real OIDB encode/decode but skips actual +// network I/O. + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { subscribeLogs, type LogEntry } from '../src/utils/logger'; + +vi.mock('../src/bridge/highway/highway-client', () => ({ + fetchHighwaySession: vi.fn(async () => ({ sessionId: 'fake-session' })), + uploadHighwayHttp: vi.fn(async () => undefined), + buildHighwayExtend: vi.fn(() => new Uint8Array([0xAA, 0xBB])), + PRIVATE_IMAGE_CMD_ID: 1003, + GROUP_IMAGE_CMD_ID: 1004, +})); + +import { + runNtv2Upload, + type MediaSubFileUpload, +} from '../src/bridge/highway/pipeline'; +import { protoEncode } from '../src/protobuf/decode'; +import { makeOidbBaseSchema } from '../src/bridge/proto/oidb'; +import { + NTV2UploadRichMediaRespSchema, +} from '../src/bridge/proto/highway'; +import { MsgPushRegistry } from '../src/bridge/msg-push/registry'; +import type { MsgPushContext } from '../src/bridge/msg-push/context'; +import { decodeEvent0x2DC } from '../src/bridge/msg-push/decoders/event-0x2dc'; + +function encodeOidbResponse(body: unknown): Buffer { + const baseSchema = makeOidbBaseSchema(NTV2UploadRichMediaRespSchema); + return Buffer.from(protoEncode({ + command: 0x11C4, subCommand: 100, errorCode: 0, + body: body as Record, + errorMsg: '', reserved: 1, + }, baseSchema)); +} + +function fakeBridge(responseData: Buffer, uin = '12345'): any { + return { + identity: { uin }, + sendRawPacket: vi.fn(async () => ({ + success: true, + gotResponse: true, + errorCode: 0, + errorMessage: '', + responseData, + })), + }; +} + +let captured: LogEntry[]; +let unsub: () => void; + +beforeEach(() => { + captured = []; + unsub = subscribeLogs((e) => captured.push(e)); +}); + +afterEach(() => { + unsub(); +}); + +describe('PR5 — highway pipeline logging', () => { + it('logs fast-upload hit when the server returns no uKey', async () => { + // upload.uKey absent → no PUT performed. + const bridge = fakeBridge(encodeOidbResponse({ + upload: { msgInfo: { msgInfoBody: [], extBizInfo: {} } }, + })); + + const params = { + bridge, + isGroup: true, + targetIdOrUid: 67890, + oidbCmd: 0x11C4, + serviceCmd: 'OidbSvcTrpcTcp.0x11c4_100', + requestId: 1, + businessType: 1, + uploadInfo: [{ fileInfo: { fileName: 'a.jpg' }, subFileType: 0 }], + compatQmsgSceneType: 2, + extBizInfo: { pic: {} }, + uploads: [{ + source: 'top', + cmdId: 1004, + bytes: new Uint8Array([1, 2, 3]), + md5: new Uint8Array(16), + sha1: new Uint8Array(20), + }] as MediaSubFileUpload[], + label: 'image', + }; + + await runNtv2Upload(params); + + const hit = captured.find((e) => + e.scope === 'Highway' && e.message.includes('fast-upload hit')); + expect(hit).toBeDefined(); + expect(hit!.uin).toBe(12345); + }); + + it('logs OIDB-requires-bytes and PUT-done with elapsed ms when uKey is present', async () => { + const bridge = fakeBridge(encodeOidbResponse({ + upload: { + uKey: 'server-needs-bytes-please', + ipv4s: [{ ipv4: '1.2.3.4', port: 80 }], + msgInfo: { msgInfoBody: [], extBizInfo: {} }, + }, + })); + + const params = { + bridge, + isGroup: true, + targetIdOrUid: 67890, + oidbCmd: 0x11C4, + serviceCmd: 'OidbSvcTrpcTcp.0x11c4_100', + requestId: 1, + businessType: 1, + uploadInfo: [{ fileInfo: { fileName: 'a.jpg' }, subFileType: 0 }], + compatQmsgSceneType: 2, + extBizInfo: { pic: {} }, + uploads: [{ + source: 'top', + cmdId: 1004, + bytes: new Uint8Array(1024), + md5: new Uint8Array(16), + sha1: new Uint8Array(20), + }] as MediaSubFileUpload[], + label: 'image', + }; + + await runNtv2Upload(params); + + const requiresBytes = captured.find((e) => + e.scope === 'Highway' && e.message.includes('OIDB requires bytes')); + const putDone = captured.find((e) => + e.scope === 'Highway' && /PUT done in \d+ms/.test(e.message)); + + expect(requiresBytes).toBeDefined(); + expect(putDone).toBeDefined(); + + const fastHit = captured.find((e) => + e.scope === 'Highway' && e.message.includes('fast-upload hit')); + expect(fastHit).toBeUndefined(); + }); +}); + +describe('PR5 — MsgPush unknown dispatch logging', () => { + it('logs an unknown PkgType under [MsgPush.Unknown]', () => { + const reg = new MsgPushRegistry(); + // No decoders registered → any pkgType is unknown. + const ctx = { + head: { msgType: 9999, subType: 0, timestamp: 0 }, + content: new Uint8Array(0), + identity: {} as any, + fromUin: 0, + selfUin: 0, + } as unknown as MsgPushContext; + + reg.decode(ctx); + + const entry = captured.find((e) => + e.scope === 'MsgPush.Unknown' && e.message.includes('PkgType=9999')); + expect(entry).toBeDefined(); + expect(entry!.level).toBe('debug'); + }); + + it('logs an unknown wrapper subType under [MsgPush.Unknown] (Event0x2DC)', () => { + const ctx = { + head: { msgType: 732, subType: 999, timestamp: 0 }, + content: new Uint8Array(0), + identity: {} as any, + fromUin: 0, + selfUin: 0, + } as unknown as MsgPushContext; + + decodeEvent0x2DC(ctx); + + const entry = captured.find((e) => + e.scope === 'MsgPush.Unknown' && /Event0x2DC unknown subType=999/.test(e.message)); + expect(entry).toBeDefined(); + expect(entry!.level).toBe('debug'); + }); +});