Files
SnowLuma/packages/core/tests/highway/pipeline.test.ts
T
DrSmoothl 269cd6f081 refactor(core): extract NTV2 upload pipeline shared by image/ptt/video
The three highway uploaders — image-upload, ptt-upload, video-upload —
each implemented the same NTV2 envelope assembly, OIDB response decode,
error handling, and Highway PUT loop, with the only real per-format
differences being the file-info fields, the extBizInfo blob, and the
Highway command id. The duplicated boilerplate had drifted slightly
between files and any future NTQQ protocol change would have needed
parallel edits in three places.

New: packages/core/src/bridge/highway/pipeline.ts (249 lines).

  runNtv2Upload({ bridge, isGroup, targetIdOrUid, oidbCmd, serviceCmd,
                  requestId, businessType, uploadInfo, compatQmsgSceneType,
                  extBizInfo, uploads, label })
    -> awaited upload object

    Builds the full reqHead + upload envelope, sends through OIDB,
    decodes the response, runs the per-sub-file Highway PUTs (caching
    the Highway session across them — video uses two PUTs and now only
    fetches the session once), and surfaces a typed fastOnlyError when
    the server demands bytes but the caller passed a fingerprint.

  finalizeMediaMsgInfo(upload, defaultPic?) -> Uint8Array

    Encodes the outgoing commonElem MsgInfo. `defaultPic` is the
    image-only fallback: image fills bizType + textSummary when the
    server omits the pic ext-biz-info; ptt / video pass undefined.

  hexToBytes(hex), makeClientRandomId(): shared helpers used by every
  uploader's fingerprint payload + client-randomId generation.

MediaSubFileUpload models per-sub-file routing:
  - source: 'top'   -> upload.uKey + upload.ipv4s (main file)
  - source: N       -> upload.subFileInfos[N].uKey + .ipv4s (video thumb)
  - cmdId, bytes, md5, sha1, subFileIndex, fastOnlyError

Each upload file shrinks to its format-specific logic only:

  image-upload.ts:  237 -> 163  (-31%)
    format detection, picFormat mapping, pic/reserveTroop/reserveC2c
    extBizInfo, group/c2c command id choice, finalize with defaultPic.

  ptt-upload.ts:    300 -> 205  (-32%)
    silk transcoding, temp-file cleanup, NapCat-style bytesGeneralFlags
    (different per group/c2c), voiceFormat honouring.

  video-upload.ts:  584 -> 507  (-13%)
    Sha1StreamState (per-1MB streaming SHA1 for the main Highway PUT),
    ffmpeg-driven thumb extraction with FALLBACK_THUMB, the two-sub-file
    OIDB body (main mp4 + thumb jpg with subFileType 100), and the
    fastOnlyError asymmetry (main file has it; thumb always has bytes).
    Video stays the largest because its load step is genuinely the most
    work — the share-out gain here is in concentration, not line count.

Behavior preserved end-to-end. Same NTV2 OIDB cmd numbers (image
0x11C4/5, ptt 0x126E/D, video 0x11EA/9), same service-cmd strings,
same requestId (image=1, ptt=group:1/c2c:4, video=3), same
compatQmsgSceneType (image+ptt: isGroup?2:1; video: 2), same
NapCat-derived bytesGeneralFlags, same fastUpload fallback strings.

Adds 42 happy-path tests across 4 new files in tests/highway/ :

  pipeline.test.ts          22  envelope construction, response decode,
                                OIDB error paths, group vs c2c scene,
                                Highway PUT trigger + fast-path skip,
                                sub-file routing, session caching,
                                fastOnlyError fire / silent-skip,
                                finalize with/without defaultPic, helpers.
  image-upload.test.ts       7  group/c2c oidbCmd + cmdId mapping,
                                fingerprint payload shape, picFormat /
                                dimensions wiring, subType -> bizType.
  ptt-upload.test.ts         6  group requestId=1 / c2c requestId=4,
                                per-scene bytesGeneralFlags, voiceFormat
                                default and override, fingerprint
                                preconditions, finalize-without-pic.
  video-upload.test.ts       7  two-sub-file shape, thumb subFileInfos[0]
                                routing, fastOnlyError asymmetry,
                                uploadInfo[mp4+jpg] with subFileType 0+100,
                                FALLBACK_THUMB always has bytes.

Tests mock highway-client for transport and the pipeline module (for
per-uploader tests) so each suite hits exactly the contract it's
testing. Pipeline tests roundtrip a real OIDB envelope through
protobuf encode/decode to exercise the actual decode path.

285 tests pass (was 244). Same pre-existing macOS-arm64 websocket
addon failure, unrelated.
2026-05-12 17:46:56 +08:00

371 lines
13 KiB
TypeScript

// Pipeline tests: runNtv2Upload + finalizeMediaMsgInfo.
//
// Highway transport (fetchHighwaySession / uploadHighwayHttp /
// buildHighwayExtend) is mocked so tests run without a real session.
// The OIDB response is built with real protobuf encoding so we exercise
// the actual decode path inside the pipeline.
import { describe, it, expect, vi, beforeEach } from 'vitest';
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 * as highway from '../../src/bridge/highway/highway-client';
import {
finalizeMediaMsgInfo,
hexToBytes,
makeClientRandomId,
runNtv2Upload,
type MediaSubFileUpload,
} from '../../src/bridge/highway/pipeline';
import { protoDecode, protoEncode } from '../../src/protobuf/decode';
import { makeOidbBaseSchema } from '../../src/bridge/proto/oidb';
import {
EncodableMediaMsgInfoSchema,
NTV2UploadRichMediaReqSchema,
NTV2UploadRichMediaRespSchema,
} from '../../src/bridge/proto/highway';
interface FakeUploadResponse {
upload?: {
uKey?: string;
ipv4s?: Array<{ ipv4?: string; port?: number }>;
msgInfo?: {
msgInfoBody?: Array<Record<string, unknown>>;
extBizInfo?: Record<string, unknown>;
};
subFileInfos?: Array<{
uKey?: string;
ipv4s?: Array<{ ipv4?: string; port?: number }>;
}>;
};
respHead?: { retCode?: number; message?: string };
}
function encodeOidbResponse(body: FakeUploadResponse, opts: { errorCode?: number; errorMsg?: string } = {}): Buffer {
const baseSchema = makeOidbBaseSchema(NTV2UploadRichMediaRespSchema);
return Buffer.from(protoEncode({
command: 0x11C4,
subCommand: 100,
errorCode: opts.errorCode ?? 0,
// The OIDB base schema types `body` as a generic ProtoDecoded record;
// the test shape is more specific, so we cast through unknown.
body: body as unknown as Record<string, unknown>,
errorMsg: opts.errorMsg ?? '',
reserved: 1,
}, baseSchema));
}
type SendPacketResult = {
success: boolean;
gotResponse: boolean;
errorCode: number;
errorMessage: string;
responseData: Buffer | null;
};
function makeBridge(opts: {
responseData?: Buffer | null;
success?: boolean;
errorMessage?: string;
} = {}) {
// Explicit two-arg signature so `mock.calls[0]` typechecks as
// [string, Uint8Array] rather than the inferred empty tuple.
const sendRawPacket = vi.fn<(cmd: string, body: Uint8Array) => Promise<SendPacketResult>>(
async () => ({
success: opts.success ?? true,
gotResponse: opts.responseData !== null,
errorCode: 0,
errorMessage: opts.errorMessage ?? '',
responseData: opts.responseData ?? Buffer.alloc(0),
}),
);
return { sendRawPacket };
}
function baseParams(overrides: Record<string, unknown> = {}) {
return {
bridge: makeBridge() as any,
isGroup: true,
targetIdOrUid: 12345,
oidbCmd: 0x11C4,
serviceCmd: 'OidbSvcTrpcTcp.0x11c4_100',
requestId: 1,
businessType: 1,
uploadInfo: [{ fileInfo: { fileName: 'a.jpg' }, subFileType: 0 }],
compatQmsgSceneType: 2,
extBizInfo: { pic: {} },
uploads: [] as MediaSubFileUpload[],
...overrides,
};
}
describe('pipeline — runNtv2Upload', () => {
beforeEach(() => {
vi.mocked(highway.fetchHighwaySession).mockClear();
vi.mocked(highway.uploadHighwayHttp).mockClear();
vi.mocked(highway.buildHighwayExtend).mockClear();
});
it('builds an NTV2 request body and dispatches to the configured serviceCmd', async () => {
const bridge = makeBridge({
responseData: encodeOidbResponse({ upload: { msgInfo: { msgInfoBody: [], extBizInfo: {} } } }),
});
await runNtv2Upload(baseParams({ bridge }));
expect(bridge.sendRawPacket).toHaveBeenCalledOnce();
const [serviceCmd, requestBytes] = bridge.sendRawPacket.mock.calls[0]!;
expect(serviceCmd).toBe('OidbSvcTrpcTcp.0x11c4_100');
expect((requestBytes as Uint8Array).length).toBeGreaterThan(0);
// The request roundtrips through the real OIDB envelope and carries
// the requestId / businessType / scene fields we passed.
const baseSchema = makeOidbBaseSchema(NTV2UploadRichMediaReqSchema);
const decoded: any = protoDecode(requestBytes as Uint8Array, baseSchema);
expect(decoded.command).toBe(0x11C4);
expect(decoded.body.reqHead.common.requestId).toBe(1);
expect(decoded.body.reqHead.scene.businessType).toBe(1);
expect(decoded.body.reqHead.scene.sceneType).toBe(2); // isGroup -> 2
expect(decoded.body.reqHead.scene.group.groupUin).toBe(12345);
});
it('builds a c2c body when isGroup is false', async () => {
const bridge = makeBridge({
responseData: encodeOidbResponse({ upload: { msgInfo: { msgInfoBody: [], extBizInfo: {} } } }),
});
await runNtv2Upload(baseParams({ bridge, isGroup: false, targetIdOrUid: 'recipient-uid' }));
const requestBytes = bridge.sendRawPacket.mock.calls[0]![1];
const decoded: any = protoDecode(requestBytes as Uint8Array, makeOidbBaseSchema(NTV2UploadRichMediaReqSchema));
expect(decoded.body.reqHead.scene.sceneType).toBe(1);
expect(decoded.body.reqHead.scene.c2c.targetUid).toBe('recipient-uid');
});
it('returns the decoded `upload` object on success', async () => {
const bridge = makeBridge({
responseData: encodeOidbResponse({
upload: {
uKey: 'fake-ukey',
msgInfo: { msgInfoBody: [{ fileExist: true }], extBizInfo: {} },
},
}),
});
const upload = await runNtv2Upload(baseParams({ bridge }));
expect(upload.uKey).toBe('fake-ukey');
expect(upload.msgInfo.msgInfoBody).toHaveLength(1);
});
it('throws on transport failure', async () => {
const bridge = makeBridge({ success: false, errorMessage: 'pipe broken', responseData: null });
await expect(runNtv2Upload(baseParams({ bridge })))
.rejects.toThrow(/pipe broken/);
});
it('throws on OIDB errorCode != 0', async () => {
const bridge = makeBridge({
responseData: encodeOidbResponse({}, { errorCode: 42, errorMsg: 'boom' }),
});
await expect(runNtv2Upload(baseParams({ bridge })))
.rejects.toThrow(/OIDB error 42/);
});
it('throws on body.respHead.retCode != 0', async () => {
const bridge = makeBridge({
responseData: encodeOidbResponse({
respHead: { retCode: 7, message: 'rate-limited' },
}),
});
await expect(runNtv2Upload(baseParams({ bridge })))
.rejects.toThrow(/rate-limited/);
});
it('throws "response body missing" when body.upload is absent', async () => {
const bridge = makeBridge({ responseData: encodeOidbResponse({}) });
await expect(runNtv2Upload(baseParams({ bridge, label: 'image' })))
.rejects.toThrow(/image upload response body missing/);
});
it('does NOT run Highway PUT when the server omits uKey (fast-path)', async () => {
const bridge = makeBridge({
responseData: encodeOidbResponse({
upload: { msgInfo: { msgInfoBody: [], extBizInfo: {} } /* no uKey */ },
}),
});
await runNtv2Upload(baseParams({
bridge,
uploads: [{
source: 'top',
cmdId: 1003,
bytes: new Uint8Array([1, 2, 3]),
md5: new Uint8Array(16),
sha1: new Uint8Array(20),
}],
}));
expect(highway.fetchHighwaySession).not.toHaveBeenCalled();
expect(highway.uploadHighwayHttp).not.toHaveBeenCalled();
});
it('runs Highway PUT for the top-level uKey', async () => {
const bridge = makeBridge({
responseData: encodeOidbResponse({
upload: {
uKey: 'ukey-xyz',
ipv4s: [{ ipv4: '1.2.3.4', port: 8080 }],
msgInfo: { msgInfoBody: [], extBizInfo: {} },
},
}),
});
await runNtv2Upload(baseParams({
bridge,
uploads: [{
source: 'top',
cmdId: 1003,
bytes: new Uint8Array([1, 2, 3]),
md5: new Uint8Array(16),
sha1: new Uint8Array(20),
}],
}));
expect(highway.fetchHighwaySession).toHaveBeenCalledOnce();
expect(highway.buildHighwayExtend).toHaveBeenCalledOnce();
expect(highway.uploadHighwayHttp).toHaveBeenCalledOnce();
});
it('routes sub-file uploads via upload.subFileInfos[N]', async () => {
const bridge = makeBridge({
responseData: encodeOidbResponse({
upload: {
uKey: 'main-ukey',
ipv4s: [{ ipv4: '1.1.1.1', port: 80 }],
msgInfo: { msgInfoBody: [], extBizInfo: {} },
subFileInfos: [
{ uKey: 'thumb-ukey', ipv4s: [{ ipv4: '2.2.2.2', port: 81 }] },
],
},
}),
});
await runNtv2Upload(baseParams({
bridge,
uploads: [
{ source: 'top', cmdId: 1001, bytes: new Uint8Array([1]), md5: new Uint8Array(16), sha1: new Uint8Array(20), subFileIndex: 0 },
{ source: 0, cmdId: 1002, bytes: new Uint8Array([2]), md5: new Uint8Array(16), sha1: new Uint8Array(20), subFileIndex: 1 },
],
}));
// Both Highway PUTs ran; only ONE Highway session was fetched.
expect(highway.fetchHighwaySession).toHaveBeenCalledOnce();
expect(highway.uploadHighwayHttp).toHaveBeenCalledTimes(2);
expect(highway.buildHighwayExtend).toHaveBeenCalledTimes(2);
// The two Highway PUTs received the right uKeys.
const extendCalls = vi.mocked(highway.buildHighwayExtend).mock.calls;
expect(extendCalls[0]![0]).toBe('main-ukey');
expect(extendCalls[1]![0]).toBe('thumb-ukey');
});
it('throws fastOnlyError when uKey is present but bytes are empty', async () => {
const bridge = makeBridge({
responseData: encodeOidbResponse({
upload: {
uKey: 'ukey-xyz',
msgInfo: { msgInfoBody: [], extBizInfo: {} },
},
}),
});
await expect(runNtv2Upload(baseParams({
bridge,
uploads: [{
source: 'top',
cmdId: 1003,
bytes: new Uint8Array(0),
md5: new Uint8Array(16),
sha1: new Uint8Array(20),
fastOnlyError: 'image fast-upload not available',
}],
}))).rejects.toThrow(/image fast-upload not available/);
});
it('silently skips a sub-file with empty bytes when no fastOnlyError is configured', async () => {
// This mirrors the video-thumb path where bytes are always synthesised
// (FALLBACK_THUMB) so we don't expect the check to fire even if the
// server returns an empty thumb uKey alongside a present main uKey.
const bridge = makeBridge({
responseData: encodeOidbResponse({
upload: {
uKey: 'main-ukey',
msgInfo: { msgInfoBody: [], extBizInfo: {} },
subFileInfos: [{ uKey: 'thumb-ukey' }],
},
}),
});
await runNtv2Upload(baseParams({
bridge,
uploads: [
{ source: 'top', cmdId: 1001, bytes: new Uint8Array([1]), md5: new Uint8Array(16), sha1: new Uint8Array(20) },
{ source: 0, cmdId: 1002, bytes: new Uint8Array(0), md5: new Uint8Array(16), sha1: new Uint8Array(20) },
],
}));
expect(highway.uploadHighwayHttp).toHaveBeenCalledOnce(); // only main
});
});
describe('pipeline — finalizeMediaMsgInfo', () => {
it('throws when msgInfo is missing', () => {
expect(() => finalizeMediaMsgInfo({})).toThrow(/missing msgInfo/);
});
it('encodes msgInfoBody + extBizInfo from the server response', () => {
const out = finalizeMediaMsgInfo({
msgInfo: {
msgInfoBody: [{ index: { fileType: 1 }, fileExist: true }],
extBizInfo: { busiType: 1 },
},
});
expect(out).toBeInstanceOf(Uint8Array);
expect(out.length).toBeGreaterThan(0);
});
it('with defaultPic, fills missing pic.bizType + pic.textSummary', () => {
// Encode the result and decode it back via the same schema to inspect
// what actually landed in the proto.
const out = finalizeMediaMsgInfo({
msgInfo: { msgInfoBody: [], extBizInfo: {} },
}, { bizType: 7, textSummary: '[image]' });
const decoded: any = protoDecode(out, EncodableMediaMsgInfoSchema);
expect(decoded.extBizInfo.pic.bizType).toBe(7);
expect(decoded.extBizInfo.pic.textSummary).toBe('[image]');
});
it('without defaultPic, leaves pic untouched when server omits it', () => {
const out = finalizeMediaMsgInfo({
msgInfo: { msgInfoBody: [], extBizInfo: {} },
});
const decoded: any = protoDecode(out, EncodableMediaMsgInfoSchema);
// An empty extBizInfo proto roundtrips to undefined; either way the
// pic field never got materialised.
expect(decoded?.extBizInfo?.pic).toBeUndefined();
});
});
describe('pipeline — helpers', () => {
it('hexToBytes roundtrips even-length hex', () => {
expect([...hexToBytes('deadbeef')]).toEqual([0xDE, 0xAD, 0xBE, 0xEF]);
});
it('hexToBytes left-pads odd-length hex with a leading zero', () => {
expect([...hexToBytes('abc')]).toEqual([0x0A, 0xBC]);
});
it('makeClientRandomId produces a non-zero positive BigInt', () => {
const id = makeClientRandomId();
expect(typeof id).toBe('bigint');
expect(id).toBeGreaterThan(0n);
expect(id).toBeLessThan(0x8000000000000000n);
});
});