diff --git a/packages/core/tests/actions/forward-file.test.ts b/packages/core/tests/actions/forward-file.test.ts index dd90cadf..30fe7c73 100644 --- a/packages/core/tests/actions/forward-file.test.ts +++ b/packages/core/tests/actions/forward-file.test.ts @@ -27,7 +27,6 @@ import { describe, it, expect, vi } from 'vitest'; import { gunzipSync } from 'zlib'; vi.mock('@snowluma/protocol/bridge-oidb', () => ({ - runOidb: vi.fn(async () => new Uint8Array()), makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })), encodeOidbEnv: vi.fn(() => new Uint8Array()), decodeOidbEnv: vi.fn(() => ({ body: {} })), diff --git a/packages/core/tests/actions/forward.test.ts b/packages/core/tests/actions/forward.test.ts index df76dacc..69f265d0 100644 --- a/packages/core/tests/actions/forward.test.ts +++ b/packages/core/tests/actions/forward.test.ts @@ -1,7 +1,6 @@ import { describe, it, expect, vi } from 'vitest'; vi.mock('@snowluma/protocol/bridge-oidb', () => ({ - runOidb: vi.fn(async () => new Uint8Array()), makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })), encodeOidbEnv: vi.fn(() => new Uint8Array()), decodeOidbEnv: vi.fn(() => ({ body: {} })), diff --git a/packages/core/tests/actions/group-message.test.ts b/packages/core/tests/actions/group-message.test.ts index 22824d5d..0230034e 100644 --- a/packages/core/tests/actions/group-message.test.ts +++ b/packages/core/tests/actions/group-message.test.ts @@ -13,7 +13,6 @@ import type { } from '@snowluma/proto-defs/oidb-actions/base'; vi.mock('@snowluma/protocol/bridge-oidb', () => ({ - runOidb: vi.fn(async () => new Uint8Array()), makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })), encodeOidbEnv: vi.fn(() => new Uint8Array()), decodeOidbEnv: vi.fn(() => ({ body: {} })), diff --git a/packages/core/tests/actions/interaction.test.ts b/packages/core/tests/actions/interaction.test.ts index 156196c8..b5c54e3b 100644 --- a/packages/core/tests/actions/interaction.test.ts +++ b/packages/core/tests/actions/interaction.test.ts @@ -33,7 +33,7 @@ describe('apis/interaction', () => { it('setReaction picks _1 for set and _2 for unset', async () => { // setReaction now forwards through the SetReaction namespace, which - // calls bridge.sendRawPacket directly (bypassing runOidb). + // calls bridge.sendRawPacket directly. const bridge = mockBridge(); const api = new InteractionApi(bridge as any); await api.setReaction(12345, 99, '128516', true); diff --git a/packages/core/tests/actions/profile.test.ts b/packages/core/tests/actions/profile.test.ts index 6ce24282..c9f536d0 100644 --- a/packages/core/tests/actions/profile.test.ts +++ b/packages/core/tests/actions/profile.test.ts @@ -12,18 +12,12 @@ import type { SetStatusResp, } from '@snowluma/proto-defs/oidb-actions/base'; -// `encodeOidbEnv` / `decodeOidbEnv` are proton-bound pass-through wrappers -// (substituted at the call site with the inlined codec). Mocking them on -// the module object is a no-op — proton has already inlined the call. -// We mock `runOidb` (non-generic) to return real proton-encoded bytes -// that the production-side codec actually decodes. vi.mock('@snowluma/protocol/bridge-oidb', async () => { const actual = await vi.importActual( '@snowluma/protocol/bridge-oidb', ); return { ...actual, - runOidb: vi.fn(async () => new Uint8Array()), makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })), }; }); @@ -47,8 +41,6 @@ import { mockBridge } from './_helpers'; describe('apis/profile', () => { beforeEach(() => { - vi.mocked(oidb.runOidb).mockReset(); - vi.mocked(oidb.runOidb).mockResolvedValue(new Uint8Array()); vi.mocked(oidb.makeOidbEnvelope).mockClear(); vi.mocked(highwayClient.fetchHighwaySession).mockClear(); vi.mocked(highwayClient.uploadHighwayHttp).mockClear(); diff --git a/packages/protocol/src/bridge-oidb.ts b/packages/protocol/src/bridge-oidb.ts index 98961527..50fe05ce 100644 --- a/packages/protocol/src/bridge-oidb.ts +++ b/packages/protocol/src/bridge-oidb.ts @@ -1,9 +1,4 @@ -import { protobuf_decode } from '@snowluma/proton'; -import type { OidbBase, OidbBaseMeta } from '@snowluma/proto-defs/oidb'; -// Sender capability is the minimal interface needed by runOidb. The -// concrete BridgeContext (and the Bridge class extending it) is -// structurally a superset, so callers keep passing `bridge` unchanged. -import type { OidbSender } from './oidb-service'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; /** * Build the OidbBase-shaped TS value. Pure helper, no protobuf @@ -31,39 +26,3 @@ export function makeOidbEnvelope( }; } -/** - * Issue one OIDB request and return the raw response bytes. - * - * Typical usage: - * const env = makeOidbEnvelope(0x1253, 1, value); - * const buf = await runOidb(bridge, cmd, encodeOidbEnv(env)); - * const resp = decodeOidbEnv(buf).body; - * - * Fire-and-check (no body decode): - * await runOidb(bridge, cmd, encodeOidbEnv(env)); - * - * Always peeks at the envelope errorCode via the non-generic - * `OidbBaseMeta` view so a server-side rejection cannot slip past - * silently. Returns the raw response bytes (empty `Uint8Array` if the - * packet carried no payload). - */ -export async function runOidb( - sender: OidbSender, - cmd: string, - envelopeBytes: Uint8Array, - timeoutMs?: number, -): Promise { - const result = await sender.sendRawPacket(cmd, envelopeBytes, timeoutMs); - if (!result.success) throw new Error(result.errorMessage || 'packet send failed'); - if (!result.gotResponse) throw new Error(result.errorMessage || 'no response'); - - const bytes = result.responseData ?? new Uint8Array(0); - if (bytes.length > 0) { - const meta = protobuf_decode(bytes); - const code = meta?.errorCode; - if (code && code !== 0) { - throw new Error(`OIDB error ${code}: ${meta?.errorMsg ?? ''}`); - } - } - return bytes; -} diff --git a/packages/protocol/src/highway/pipeline.ts b/packages/protocol/src/highway/pipeline.ts index 771abec2..1a301435 100644 --- a/packages/protocol/src/highway/pipeline.ts +++ b/packages/protocol/src/highway/pipeline.ts @@ -9,14 +9,11 @@ import type { NTV2ExtBizInfo, NTV2UploadInfo, NTV2UploadRespBody, - NTV2UploadRichMediaReq, - NTV2UploadRichMediaResp, } from '@snowluma/proto-defs/highway'; -import { OidbBase } from '@snowluma/proto-defs/oidb'; -import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; import crypto from 'crypto'; import type { BridgeContext } from '../bridge-context'; -import { makeOidbEnvelope } from '../bridge-oidb'; +import { OidbError } from '../oidb-service'; +import { Ntv2UploadRequest } from '../oidb-services/highway/ntv2-upload-request'; import { BufferChunkSource, FileChunkSource, buildHighwayExtend, fetchHighwaySession, uploadHighwayHttp } from './highway-client'; const moduleLog = createLogger('Highway'); @@ -189,7 +186,7 @@ async function runNtv2UploadOperation( params: NtV2UploadParams, setState: (failureReason: string, didPut?: boolean) => void, ): Promise { - const { bridge, isGroup, targetIdOrUid, oidbCmd, serviceCmd, uploads } = params; + const { bridge, isGroup, targetIdOrUid, oidbCmd, uploads } = params; const label = params.label ?? 'media'; const raw = bridge.identity?.uin; const uinNum = typeof raw === 'string' ? Number.parseInt(raw, 10) : 0; @@ -204,67 +201,30 @@ async function runNtv2UploadOperation( // `pb` when it's `true`, so `tryFast === false` omits field 2 — // the server reads that as "don't fast-upload" (the opt-in default). const requestUpload = async (tryFast: boolean): Promise => { - const body: NTV2UploadRichMediaReq = { - reqHead: { - common: { requestId: params.requestId, command: 100 }, - scene: { - requestType: 2, - businessType: params.businessType, - sceneType: isGroup ? 2 : 1, - ...(isGroup - ? { group: { groupUin: Number(targetIdOrUid) } } - : { c2c: { accountType: 2, targetUid: String(targetIdOrUid) } }), - }, - client: { agentType: 2 }, - }, - upload: { + setState('request_failed'); + try { + return await Ntv2UploadRequest.invoke(bridge, { + oidbCmd, + isGroup, + targetIdOrUid, + requestId: params.requestId, + businessType: params.businessType, uploadInfo: params.uploadInfo, - tryFastUploadCompleted: tryFast, - srvSendMsg: false, - clientRandomId: makeClientRandomId(), compatQmsgSceneType: params.compatQmsgSceneType, extBizInfo: params.extBizInfo, - clientSeq: 0, - noNeedCompatMsg: false, - }, - }; - - const env = makeOidbEnvelope(oidbCmd, 100, body, true); - const requestBytes = protobuf_encode>(env); - - setState('request_failed'); - const result = await bridge.sendRawPacket(serviceCmd, requestBytes); - log.trace(() => [ - 'highway_media_branch branch=oidb_response success=%s gotResponse=%s errorCode=%d errorMessage=%j responseBytes=%d', - result.success, - result.gotResponse, - result.errorCode, - result.errorMessage ?? '', - result.responseData?.byteLength ?? 0, - ]); - if (!result.success || !result.gotResponse || !result.responseData) { - throw new Error(result.errorMessage || `${label} upload request failed`); + tryFast, + clientRandomId: makeClientRandomId(), + }); + } catch (error) { + if (error instanceof OidbError) setState('oidb_rejected'); + else if (error instanceof Error && error.message.includes('missing msgInfo')) setState('response_invalid'); + else if (error instanceof Error && error.message.includes('upload failed')) setState('business_rejected'); + log.trace(() => [ + 'highway_media_branch branch=oidb_response error=%j', + error instanceof Error ? error.message : String(error), + ]); + throw error; } - - setState('response_decode_failed'); - const resp = protobuf_decode>(result.responseData); - if (!resp) throw new Error(`failed to decode ${label} upload response`); - if (resp.errorCode && resp.errorCode !== 0) { - setState('oidb_rejected'); - throw new Error(`OIDB error ${resp.errorCode}: ${resp.errorMsg ?? ''}`); - } - - const uploadBody = resp.body; - setState('response_invalid'); - if (!uploadBody) throw new Error(`${label} upload response body missing`); - if (uploadBody.respHead?.retCode && uploadBody.respHead.retCode !== 0) { - setState('business_rejected'); - throw new Error(uploadBody.respHead.message ?? `${label} upload failed`); - } - const upload = uploadBody.upload; - if (!upload) throw new Error(`${label} upload response body missing`); - if (!upload.msgInfo) throw new Error('upload response missing msgInfo'); - return upload; }; // Highway PUTs. Session is lazily fetched and cached — video does two diff --git a/packages/protocol/src/oidb-service.ts b/packages/protocol/src/oidb-service.ts index 5a3f1de7..ecb6548a 100644 --- a/packages/protocol/src/oidb-service.ts +++ b/packages/protocol/src/oidb-service.ts @@ -54,12 +54,15 @@ export interface OidbSender { * * One of `subCommand` (static) or `resolveSubCommand` (dynamic from * params and context) must be present. `resolveSubCommand` wins if both - * are given. + * are given. `resolveCommand` likewise wins over static `command`. */ export interface OidbCallSpec { command: number; + resolveCommand?(params: TParams, ctx: TCtx): number; subCommand?: number; resolveSubCommand?(params: TParams, ctx: TCtx): number; + /** Packet and body envelope codes treated as success in addition to 0. */ + acceptedEnvelopeCodes?: readonly number[]; /** Set OIDB envelope `reserved = 1` (UIN-form variant, see makeOidbEnvelope's isUid). */ uinForm?: boolean; /** Override the default `OidbSvcTrpcTcp.0xNNNN_N` wire name. A few @@ -79,6 +82,28 @@ export interface OidbCallSpec; } +function resolveOidbCall( + spec: OidbCallSpec, + params: TParams, + ctx: TCtx, +): { command: number; subCommand: number } { + const command = spec.resolveCommand + ? spec.resolveCommand(params, ctx) + : spec.command; + const subCommand = spec.resolveSubCommand + ? spec.resolveSubCommand(params, ctx) + : spec.subCommand!; + return { command, subCommand }; +} + +function isAcceptedEnvelopeCode( + spec: OidbCallSpec, + code: number | null | undefined, +): boolean { + if (code == null || code === 0) return true; + return spec.acceptedEnvelopeCodes?.includes(code) === true; +} + export class OidbError extends Error { constructor( readonly code: number, @@ -107,39 +132,40 @@ export async function invokeOidb { - const subCommand = spec.resolveSubCommand - ? spec.resolveSubCommand(params, ctx) - : spec.subCommand!; + const { command, subCommand } = resolveOidbCall(spec, params, ctx); const reqBody = await spec.serialize(ctx, params); - const env = makeOidbEnvelope(spec.command, subCommand, reqBody, spec.uinForm ?? false); + const env = makeOidbEnvelope(command, subCommand, reqBody, spec.uinForm ?? false); const reqBytes = spec.encode(env); const wireName = spec.wireName - ? spec.wireName(spec.command, subCommand) - : `OidbSvcTrpcTcp.0x${spec.command.toString(16)}_${subCommand}`; + ? spec.wireName(command, subCommand) + : `OidbSvcTrpcTcp.0x${command.toString(16)}_${subCommand}`; const result = await ctx.sendRawPacket(wireName, reqBytes, timeoutMs); if (!result.gotResponse) throw new Error(result.errorMessage || 'no response'); if (!result.success) { if (result.errorCode && result.errorCode !== 0) { - throw new OidbError( - result.errorCode, - result.errorMessage || '', - spec.command, - subCommand - ); + if (!isAcceptedEnvelopeCode(spec, result.errorCode)) { + throw new OidbError( + result.errorCode, + result.errorMessage || '', + command, + subCommand + ); + } + } else { + // success=false without an OIDB error code = the packet send itself failed; + // surface it instead of silently resolving with an undecoded response. + throw new Error(result.errorMessage || 'packet send failed'); } - // success=false without an OIDB error code = the packet send itself failed; - // surface it instead of silently resolving with an undecoded response. - throw new Error(result.errorMessage || 'packet send failed'); } const respBytes = result.responseData ?? new Uint8Array(0); if (respBytes.length > 0) { const meta = protobuf_decode(respBytes); const code = meta?.errorCode; - if (code && code !== 0) { - throw new OidbError(code, meta?.errorMsg ?? '', spec.command, subCommand); + if (code && code !== 0 && !isAcceptedEnvelopeCode(spec, code)) { + throw new OidbError(code, meta?.errorMsg ?? '', command, subCommand); } } @@ -163,15 +189,13 @@ export async function buildOidbRequest, params: TParams, ): Promise<{ wireName: string; bytes: Uint8Array }> { - const subCommand = spec.resolveSubCommand - ? spec.resolveSubCommand(params, ctx) - : spec.subCommand!; + const { command, subCommand } = resolveOidbCall(spec, params, ctx); const reqBody = await spec.serialize(ctx, params); - const env = makeOidbEnvelope(spec.command, subCommand, reqBody, spec.uinForm ?? false); + const env = makeOidbEnvelope(command, subCommand, reqBody, spec.uinForm ?? false); const bytes = spec.encode(env); const wireName = spec.wireName - ? spec.wireName(spec.command, subCommand) - : `OidbSvcTrpcTcp.0x${spec.command.toString(16)}_${subCommand}`; + ? spec.wireName(command, subCommand) + : `OidbSvcTrpcTcp.0x${command.toString(16)}_${subCommand}`; return { wireName, bytes }; } diff --git a/packages/protocol/src/oidb-services/contacts/set-friend-category.ts b/packages/protocol/src/oidb-services/contacts/set-friend-category.ts index 8a91cceb..182a35b6 100644 --- a/packages/protocol/src/oidb-services/contacts/set-friend-category.ts +++ b/packages/protocol/src/oidb-services/contacts/set-friend-category.ts @@ -1,21 +1,19 @@ import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; -import type { OidbBase, OidbBaseMeta } from '@snowluma/proto-defs/oidb'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; import type { OidbSetFriendCategoryRequest } from '@snowluma/proto-defs/oidb-actions/base'; -import { makeOidbEnvelope } from '../../bridge-oidb'; -import { OidbError, type OidbSender } from '../../oidb-service'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; /** * Move one friend into a category. * - * The desktop client treats 2001002 as an idempotent success result, so this - * call intentionally validates the response itself instead of using the - * generic OIDB helper that rejects every non-zero application code. + * The desktop client treats 2001002 as an idempotent success result. */ export namespace SetFriendCategory { export const command = 0x1255; export const subCommand = 0; export const uinForm = true; export const alreadyAppliedCode = 2_001_002; + export const acceptedEnvelopeCodes = [alreadyAppliedCode] as const; export interface Params { uid: string; @@ -29,35 +27,14 @@ export namespace SetFriendCategory { categoryId: params.categoryId, }); - function accepted(code: number | null | undefined): boolean { - return code == null || code === 0 || code === alreadyAppliedCode; - } + export const deserialize = (): void => undefined; - export async function invoke(deps: Deps, params: Params): Promise { - const body = serialize(deps, params); - const bytes = protobuf_encode>( - makeOidbEnvelope(command, subCommand, body, uinForm), - ); - const result = await deps.sendRawPacket('OidbSvcTrpcTcp.0x1255_0', bytes); + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); - if (!result.gotResponse) { - throw new Error(result.errorMessage || 'no response'); - } - if (!result.success && result.errorCode !== alreadyAppliedCode) { - if (result.errorCode) { - throw new OidbError(result.errorCode, result.errorMessage, command, subCommand); - } - throw new Error(result.errorMessage || 'packet send failed'); - } - if (!accepted(result.errorCode)) { - throw new OidbError(result.errorCode, result.errorMessage, command, subCommand); - } + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); - const response = result.responseData ?? new Uint8Array(0); - if (response.length === 0) return; - const meta = protobuf_decode(response); - if (!accepted(meta.errorCode)) { - throw new OidbError(meta.errorCode!, meta.errorMsg ?? '', command, subCommand); - } - } + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, SetFriendCategory, params); } diff --git a/packages/protocol/src/oidb-services/highway/ntv2-upload-request.ts b/packages/protocol/src/oidb-services/highway/ntv2-upload-request.ts new file mode 100644 index 00000000..ec988ca0 --- /dev/null +++ b/packages/protocol/src/oidb-services/highway/ntv2-upload-request.ts @@ -0,0 +1,83 @@ +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { + NTV2ExtBizInfo, + NTV2UploadInfo, + NTV2UploadRespBody, + NTV2UploadRichMediaReq, + NTV2UploadRichMediaResp, +} from '@snowluma/proto-defs/highway'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; + +/** + * NTV2 rich-media upload preflight. Image / PTT / video share one Req/Resp + * type; command (0x11C4 / 0x11C5 / …) comes from the caller. Highway PUTs + * stay in the pipeline. + */ +export namespace Ntv2UploadRequest { + export const command = 0; + export const subCommand = 100; + export const uinForm = true; + + export interface Params { + oidbCmd: number; + isGroup: boolean; + targetIdOrUid: string | number; + requestId: number; + businessType: number; + uploadInfo: NTV2UploadInfo[]; + compatQmsgSceneType: number; + extBizInfo: NTV2ExtBizInfo; + tryFast: boolean; + clientRandomId: bigint; + } + + export type Deps = OidbSender; + + export const resolveCommand = (params: Params): number => params.oidbCmd; + + export const serialize = (_ctx: Deps, params: Params): NTV2UploadRichMediaReq => ({ + reqHead: { + common: { requestId: params.requestId, command: 100 }, + scene: { + requestType: 2, + businessType: params.businessType, + sceneType: params.isGroup ? 2 : 1, + ...(params.isGroup + ? { group: { groupUin: Number(params.targetIdOrUid) } } + : { c2c: { accountType: 2, targetUid: String(params.targetIdOrUid) } }), + }, + client: { agentType: 2 }, + }, + upload: { + uploadInfo: params.uploadInfo, + tryFastUploadCompleted: params.tryFast, + srvSendMsg: false, + clientRandomId: params.clientRandomId, + compatQmsgSceneType: params.compatQmsgSceneType, + extBizInfo: params.extBizInfo, + clientSeq: 0, + noNeedCompatMsg: false, + }, + }); + + export const deserialize = (_ctx: Deps, body: NTV2UploadRichMediaResp): NTV2UploadRespBody => { + if (!body) throw new Error('media upload response body missing'); + if (body.respHead?.retCode && body.respHead.retCode !== 0) { + throw new Error(body.respHead.message ?? 'media upload failed'); + } + const upload = body.upload; + if (!upload) throw new Error('media upload response body missing'); + if (!upload.msgInfo) throw new Error('upload response missing msgInfo'); + return upload; + }; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, Ntv2UploadRequest, params); +} diff --git a/packages/protocol/tests/oidb-service.test.ts b/packages/protocol/tests/oidb-service.test.ts index d24f8044..23a44928 100644 --- a/packages/protocol/tests/oidb-service.test.ts +++ b/packages/protocol/tests/oidb-service.test.ts @@ -231,6 +231,33 @@ describe('invokeOidb', () => { const env = protobuf_decode>(bytes); expect(env.reserved ?? 0).toBe(0); }); + + it('treats registered envelope codes as success on the packet and body', async () => { + const spec = { ...staticSubSpec, acceptedEnvelopeCodes: [2_001_002] }; + const bodyBytes = protobuf_encode>({ + command: 0xEAC, subCommand: 1, errorCode: 2_001_002, errorMsg: 'already applied', + }); + await expect(invokeOidb(makeSender({ responseData: Buffer.from(bodyBytes) }), spec, { groupId: 1 })) + .resolves.toBeUndefined(); + await expect(invokeOidb(makeSender({ + success: false, + errorCode: 2_001_002, + errorMessage: 'already applied', + responseData: null, + }), spec, { groupId: 1 })).resolves.toBeUndefined(); + }); + + it('uses resolveCommand for the wire name and envelope command', async () => { + const spec = { + ...staticSubSpec, + command: 0, + resolveCommand: () => 0x11C5, + subCommand: 100, + }; + const sender = makeSender(); + await invokeOidb(sender, spec, { groupId: 1 }); + expect(sender.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x11c5_100'); + }); }); describe('buildOidbRequest', () => { diff --git a/packages/protocol/tests/oidb-services/highway/ntv2-upload-request.test.ts b/packages/protocol/tests/oidb-services/highway/ntv2-upload-request.test.ts new file mode 100644 index 00000000..4fefd53c --- /dev/null +++ b/packages/protocol/tests/oidb-services/highway/ntv2-upload-request.test.ts @@ -0,0 +1,57 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_encode } from '@snowluma/proton'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { NTV2UploadRichMediaResp } from '@snowluma/proto-defs/highway'; +import { OidbError } from '../../../src/oidb-service'; +import { Ntv2UploadRequest } from '../../../src/oidb-services/highway/ntv2-upload-request'; + +function packet(body: NTV2UploadRichMediaResp, errorCode = 0): SendPacketResult { + return { + success: true, + gotResponse: true, + errorCode: 0, + errorMessage: '', + responseData: Buffer.from(protobuf_encode>({ + command: 0x11C5, + subCommand: 100, + errorCode, + errorMsg: errorCode ? 'denied' : '', + body, + })), + }; +} + +const params: Ntv2UploadRequest.Params = { + oidbCmd: 0x11C5, + isGroup: false, + targetIdOrUid: 'u_peer', + requestId: 1, + businessType: 1, + uploadInfo: [], + compatQmsgSceneType: 1, + extBizInfo: {}, + tryFast: true, + clientRandomId: 1n, +}; + +describe('Ntv2UploadRequest', () => { + it('sends the resolved command on the default OIDB wire name', async () => { + const sendRawPacket = vi.fn(async () => packet({ + upload: { msgInfo: { msgInfoBody: [] } }, + })); + await Ntv2UploadRequest.invoke({ sendRawPacket }, params); + expect(sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x11c5_100'); + }); + + it('raises OidbError when the envelope is rejected', async () => { + const sendRawPacket = vi.fn(async () => packet({ upload: { msgInfo: {} } }, 42)); + await expect(Ntv2UploadRequest.invoke({ sendRawPacket }, params)).rejects.toBeInstanceOf(OidbError); + }); + + it('fails in deserialize when msgInfo is missing', async () => { + const sendRawPacket = vi.fn(async () => packet({ upload: { uKey: 'k' } })); + await expect(Ntv2UploadRequest.invoke({ sendRawPacket }, params)) + .rejects.toThrow('upload response missing msgInfo'); + }); +});