Files
SnowLuma/packages/core/tests/highway/pipeline.test.ts
T
DrSmoothl f7a03ca05a refactor(bridge): extract protocol layer into @snowluma/bridge package
Phase 2 of the 4-package split (RoadMap #3). Moves ~35 files —
events / event-bus / identity-service / packet-pipeline / element-
builder / bridge-oidb / qq-info / msg-push/* / highway/* / web/* +
the bridge-side formatters — out of `packages/core/src/bridge/`
into the new `@snowluma/bridge` workspace package. Everything that
translates QQ wire bytes ↔ typed events/elements now lives there.

Why
---
- `packages/core/src/bridge/` was actually two layers: a low-level
  "protocol decoder + I/O" set (msg-push, highway, packet-pipeline,
  identity, element-builder) AND the Api-class host (bridge.ts +
  apis/*). The Api layer can't move without the protocol layer
  moving first, but the two had grown into one directory.
- Bridge-internal consumers (highway uploaders, OIDB envelope
  helper, element-builder, msg-push parsers) only ever needed
  `bridge.identity` + `bridge.sendRawPacket` + the upload-metadata
  cache. Splitting them out lets that minimal surface live in the
  bridge package as `BridgeContext` while the api-layer's extended
  context (with `apis: ApiHub`) stays in @snowluma/core.

What stays in @snowluma/core (apis layer):
  - bridge.ts          ── the god-class that composes the protocol
                          building blocks + mounts apis
  - bridge-interface.ts ── public façade for OneBot consumers
  - manager.ts          ── per-uin BridgeManager hub
  - apis/*              ── the 13 typed Api classes
  - bridge-context.ts (NEW) ── extends @snowluma/bridge's slim
                              BridgeContext with `apis: ApiHub` so
                              the 13 Api classes keep their typed
                              `this.ctx.apis.X.method()` access.

Layout
------
Moved via `git mv` (history preserved):
  events / event-bus / identity-service / packet-pipeline /
  element-builder / bridge-oidb / qq-info / msg-push/* /
  highway/* / web/*           → @snowluma/bridge/<sub>
  utils/event-format.ts        → @snowluma/bridge/format.ts

  (the last one renamed because the destination directory only has
  bridge-related files; `format.ts` reads cleaner than `event-format`.
  Listed as a rename in git's `RM` output — content unchanged.)

Layering fixes (functionality preserved, just type signatures)
--------------------------------------------------------------
- `element-builder.SendContext.bridge` → typed as `BridgeContext`
  instead of `Bridge`. Reads only `bridge.identity` and the
  upload-cache (both on BridgeContext); the concrete `Bridge`
  instance still passes via free upcast.
- `bridge-oidb.runOidb` signature widened from `Bridge` to
  `BridgeContext` — same reason.
- `highway/{highway-client,pipeline,image-upload,ptt-upload,
  video-upload}.ts` — same.
- `format.ts::formatReply` parameter typed as a new local
  `ReplyEventLookup` structural type (`{ findEvent(id): JsonObject |
  null }`) instead of `MessageStore` from @snowluma/onebot. The
  OneBot `MessageStore` is a structural superset; consumers pass
  it through unchanged.
- JSON value types moved to a new `@snowluma/common/json` subpath
  (consumed by format.ts) — `onebot/types.ts` re-exports them so
  external `import { JsonValue } from '<…>/onebot/types'` paths
  keep working.
- `UploadedFileMeta` interface moved from `core/src/bridge/bridge.ts`
  into `@snowluma/bridge/bridge-context.ts` — element-builder + the
  forward-builder both read the upload cache through BridgeContext,
  so the type has to live in @snowluma/bridge. `bridge.ts` keeps
  its re-export for back-compat.

Changes
-------
- New package `packages/bridge/` (package.json with per-file subpath
  exports mirroring legacy `core/src/bridge/<x>` layout 1:1,
  tsconfig.json, typecheck script).
- 35 `.ts` files moved via `git mv` (3 files counted by git as
  RM — rename + modify because Bridge → BridgeContext type swap).
- 150+ import sites rewritten across `packages/core/src` and
  `packages/core/tests`: `'../bridge/<x>'`, `'../../bridge/<x>'`,
  `'../src/bridge/<x>'`, `'@/bridge/web/<x>'`, and vitest
  `vi.mock(...)` literals all collapse to `@snowluma/bridge/<x>`.
- `@snowluma/core` depends on `@snowluma/bridge` (workspace:*).
- `@snowluma/bridge` depends on `@snowluma/common`,
  `@snowluma/proto-defs`, `@snowluma/proton`.
- `packages/core/src/utils/` directory removed (empty).

Verification
------------
- Full workspace `pnpm -r typecheck`: all 10 projects clean.
- core test suite: 552 passed / 552 total (pre-existing
  websocket-darwin-arm64.node addon failure unchanged — same
  baseline as the previous refactor commits).
- Vite build (with stubbed native binary): clean — 143 modules,
  2.84 MB bundle / 224 KB gzip, identical envelope to the
  pre-split build.

Phase 3 (next): OneBot + WebUI move into @snowluma/onebot. The
runnable `index.ts` stays in @snowluma/core as the application
entry, importing `OneBotManager` from `@snowluma/onebot`.
2026-05-21 08:41:34 +08:00

365 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';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
vi.mock('@snowluma/bridge/highway', () => ({
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 '@snowluma/bridge/highway';
import {
finalizeMediaMsgInfo,
hexToBytes,
makeClientRandomId,
runNtv2Upload,
type MediaSubFileUpload,
} from '@snowluma/bridge/highway/pipeline';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { EncodableMediaMsgInfo, NTV2UploadRichMediaReq, NTV2UploadRichMediaResp } from '@snowluma/proto-defs/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 {
return Buffer.from(protobuf_encode<OidbBase<NTV2UploadRichMediaResp>>({
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,
} as OidbBase<NTV2UploadRichMediaResp>));
}
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 decoded: any = protobuf_decode<OidbBase<NTV2UploadRichMediaReq>>(requestBytes as Uint8Array);
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 = protobuf_decode<OidbBase<NTV2UploadRichMediaReq>>(requestBytes as Uint8Array);
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 = protobuf_decode<EncodableMediaMsgInfo>(out);
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 = protobuf_decode<EncodableMediaMsgInfo>(out);
// An empty extBizInfo proto roundtrips to undefined; either way the
// pic field never got materialised.
expect(decoded?.extBizInfo?.pic ?? undefined).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);
});
});