refactor(oidb): migrate profile.ts OIDB cmds to namespaces

5 of profile.ts's methods were thin OIDB wrappers — migrated to the
new namespace pattern. The 5 non-OIDB methods (setOnlineStatus /
setDiyOnlineStatus / setAvatar / setGroupAvatar / fetchCustomFace)
stay on the facade unchanged — they hit `trpc.qq_new_tech.*`,
Highway, or `Faceroam.OpReq` directly and aren't in scope for the
OIDB-namespace refactor.

New namespaces (each with focused Pick<BridgeContext, …> deps):
  - SetProfile               (0x112A_2)  — needs identity for uin
  - SetSelfLongNick          (0x112A_2)  — same cmd different proto, ditto
  - SetInputStatus           (0xCD4_1)   — needs resolveUserUid
  - GetLike                  (0x7ED_12)  — needs identity + resolveUserUid
  - GetUnidirectionalFriendList (0xE17_0) — needs identity; non-standard
                                            wire name handled via the new
                                            wireName override on OidbCallSpec

Infrastructure tweak:
  - OidbCallSpec gains an optional `wireName(cmd, sub) → string`. Most
    cmds use the default `OidbSvcTrpcTcp.0xNNNN_N` scheme; 0xe17_0
    routes through `MQUpdateSvc_com_qq_ti.web.OidbSvc.0xe17_0`.

Test mock updates:
  - profile.test.ts moves the migrated cmds onto bridge.sendRawPacket
    mock (the new path bypasses the bridge-oidb runOidb mock). Non-OIDB
    cmds (setOnlineStatus, setAvatar, etc.) keep their existing mocks.
  - 36 new namespace-level tests in @snowluma/bridge covering serialize
    branches, deserialize edge cases, deps resolution, and e2e wire
    routing.

Verification:
  - pnpm -r typecheck: green
  - @snowluma/bridge: 12 files / 118 tests
  - @snowluma/core: 33 files / 302 tests
Wire shape unchanged across migrated cmds — same bytes produced.
This commit is contained in:
DrSmoothl committed 2026-05-22 23:29:55 +08:00
1 parent ff2b902cbd
commit a38f7ea26e
14 files changed
+760 -154

No files matched your search

@@ -0,0 +1,135 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { Oidb0x7edReq, Oidb0x7edResp } from '@snowluma/proto-defs/oidb-actions/base';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { GetLike } from '../../../src/oidb-services/profile/get-like';
function makeDeps(opts: {
cachedSelfUid?: string | null;
resolveUserUid?: (uin: number) => Promise<string>;
responseBody?: Oidb0x7edResp;
} = {}) {
const responseData = opts.responseBody !== undefined
? Buffer.from(protobuf_encode<OidbBase<Oidb0x7edResp>>({ body: opts.responseBody }))
: Buffer.alloc(0);
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData };
return {
sendRawPacket: vi.fn(async () => r),
identity: { uin: '10001', selfUid: opts.cachedSelfUid ?? null } as any,
resolveUserUid: vi.fn(opts.resolveUserUid ?? (async (uin: number) => `uid-of-${uin}`)),
};
}
describe('GetLike namespace', () => {
it('declares 0x7ED_12', () => {
expect(GetLike.command).toBe(0x7ED);
expect(GetLike.subCommand).toBe(12);
});
describe('invoke (target uid resolution)', () => {
it('uses cached self uid when userId is omitted', async () => {
const deps = makeDeps({
cachedSelfUid: 'cached-self',
responseBody: { userLikeInfos: [{ uid: 'cached-self', time: 0n, favoriteInfo: {}, voteInfo: {} }] },
});
await GetLike.invoke(deps, {});
expect(deps.resolveUserUid).not.toHaveBeenCalled();
const [, bytes] = deps.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<Oidb0x7edReq>>(bytes);
expect(env.body?.targetUid).toBe('cached-self');
});
it('falls back to resolveUserUid for self when cache is empty', async () => {
const deps = makeDeps({
cachedSelfUid: null,
resolveUserUid: vi.fn(async () => 'fresh-self') as any,
responseBody: { userLikeInfos: [{ uid: 'fresh-self', time: 0n, favoriteInfo: {}, voteInfo: {} }] },
});
await GetLike.invoke(deps, {});
expect(deps.resolveUserUid).toHaveBeenCalledWith(10001);
});
it('resolves other users via resolveUserUid', async () => {
const deps = makeDeps({
responseBody: { userLikeInfos: [{ uid: 'uid-of-99999', time: 0n, favoriteInfo: {}, voteInfo: {} }] },
});
await GetLike.invoke(deps, { userId: 99999 });
expect(deps.resolveUserUid).toHaveBeenCalledWith(99999);
});
it('throws when self uin is invalid and cache is empty', async () => {
const deps = makeDeps({ cachedSelfUid: null });
deps.identity.uin = 'invalid';
await expect(GetLike.invoke(deps, {})).rejects.toThrow('self uid is unavailable');
});
});
describe('serialize', () => {
it('always sets basic=1, vote=1, favorite=1 (full breakdown query)', async () => {
const deps = makeDeps({
responseBody: { userLikeInfos: [{ uid: 'u', time: 0n, favoriteInfo: {}, voteInfo: {} }] },
});
await GetLike.invoke(deps, { userId: 1 });
const [, bytes] = deps.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<Oidb0x7edReq>>(bytes);
expect(env.body?.basic).toBe(1);
expect(env.body?.vote).toBe(1);
expect(env.body?.favorite).toBe(1);
});
it('threads start / limit through to the request', async () => {
const deps = makeDeps({
responseBody: { userLikeInfos: [{ uid: 'u', time: 0n, favoriteInfo: {}, voteInfo: {} }] },
});
await GetLike.invoke(deps, { userId: 1, start: 5, limit: 50 });
const [, bytes] = deps.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<Oidb0x7edReq>>(bytes);
expect(env.body?.start).toBe(5);
expect(env.body?.limit).toBe(50);
});
it('defaults start=0 / limit=10', async () => {
const deps = makeDeps({
responseBody: { userLikeInfos: [{ uid: 'u', time: 0n, favoriteInfo: {}, voteInfo: {} }] },
});
await GetLike.invoke(deps, { userId: 1 });
const [, bytes] = deps.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<Oidb0x7edReq>>(bytes);
expect(env.body?.start ?? 0).toBe(0);
expect(env.body?.limit).toBe(10);
});
});
describe('deserialize', () => {
it('shapes favorite + vote info with the expected key names', () => {
const out = GetLike.deserialize({
userLikeInfos: [{
uid: 'u', time: 1700000000n,
favoriteInfo: { totalCount: 5, lastTime: 1n, newCount: 1 },
voteInfo: { totalCount: 7, newCount: 2, lastTime: 2n },
}],
});
expect(out.uid).toBe('u');
expect(out.time).toBe(1700000000);
expect(out.favoriteInfo).toEqual({
total_count: 5, last_time: 1, today_count: 1, userInfos: [],
});
expect(out.voteInfo).toEqual({
total_count: 7, new_count: 2, new_nearby_count: 0, last_visit_time: 2, userInfos: [],
});
});
it('throws when there are no userLikeInfos', () => {
expect(() => GetLike.deserialize({})).toThrow('get profile like info empty');
expect(() => GetLike.deserialize({ userLikeInfos: [] })).toThrow('get profile like info empty');
});
it('defaults all count fields to 0 when omitted', () => {
const out = GetLike.deserialize({ userLikeInfos: [{ uid: 'u', time: 0n }] });
expect(out.favoriteInfo.total_count).toBe(0);
expect(out.voteInfo.total_count).toBe(0);
});
});
});
@@ -0,0 +1,76 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { Oidb0xe17Req, Oidb0xe17Resp } from '@snowluma/proto-defs/oidb-actions/base';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { GetUnidirectionalFriendList } from '../../../src/oidb-services/profile/get-unidirectional-friend-list';
function makeDeps(responseJson?: unknown) {
const responseData = responseJson !== undefined
? Buffer.from(protobuf_encode<OidbBase<Oidb0xe17Resp>>({
body: { jsonBody: JSON.stringify(responseJson) },
}))
: Buffer.alloc(0);
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData };
return {
sendRawPacket: vi.fn(async () => r),
identity: { uin: '10001' } as any,
};
}
describe('GetUnidirectionalFriendList namespace', () => {
it('declares 0xE17_0', () => {
expect(GetUnidirectionalFriendList.command).toBe(0xE17);
expect(GetUnidirectionalFriendList.subCommand).toBe(0);
});
it('overrides the wire name to MQUpdateSvc.OidbSvc.0xe17_0', async () => {
const deps = makeDeps({ rpt_block_list: [] });
await GetUnidirectionalFriendList.invoke(deps);
expect(deps.sendRawPacket.mock.calls[0]![0]).toBe('MQUpdateSvc_com_qq_ti.web.OidbSvc.0xe17_0');
});
describe('serialize', () => {
it('JSON-encodes the request body with the bot uin and fixed pagination', async () => {
const deps = makeDeps({ rpt_block_list: [] });
await GetUnidirectionalFriendList.invoke(deps);
const [, bytes] = deps.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<Oidb0xe17Req>>(bytes);
const parsed = JSON.parse(env.body?.jsonBody ?? '{}');
expect(parsed).toEqual({
uint64_uin: '10001',
uint64_top: 0,
uint32_req_num: 99,
bytes_cookies: '',
});
});
});
describe('deserialize', () => {
it('parses the embedded JSON body and returns rpt_block_list', () => {
const out = GetUnidirectionalFriendList.deserialize({
jsonBody: JSON.stringify({ rpt_block_list: [{ uin: 10001 }, { uin: 10002 }] }),
});
expect(out).toEqual([{ uin: 10001 }, { uin: 10002 }]);
});
it('returns [] when rpt_block_list is absent', () => {
const out = GetUnidirectionalFriendList.deserialize({ jsonBody: JSON.stringify({}) });
expect(out).toEqual([]);
});
it('throws when jsonBody is empty / missing', () => {
expect(() => GetUnidirectionalFriendList.deserialize({})).toThrow('get unidirectional friend list empty');
expect(() => GetUnidirectionalFriendList.deserialize({ jsonBody: '' })).toThrow('get unidirectional friend list empty');
});
});
describe('invoke (e2e)', () => {
it('returns the parsed block list', async () => {
const deps = makeDeps({ rpt_block_list: [{ uin: 999 }] });
const out = await GetUnidirectionalFriendList.invoke(deps);
expect(out).toEqual([{ uin: 999 }]);
});
});
});
@@ -0,0 +1,54 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { Oidb0xcd4Req } from '@snowluma/proto-defs/oidb-actions/base';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { SetInputStatus } from '../../../src/oidb-services/profile/set-input-status';
function makeDeps(uid: string | null = 'resolved-uid') {
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) };
return {
sendRawPacket: vi.fn(async () => r),
resolveUserUid: vi.fn(async () => uid as string),
};
}
describe('SetInputStatus namespace', () => {
it('declares 0xCD4_1', () => {
expect(SetInputStatus.command).toBe(0xCD4);
expect(SetInputStatus.subCommand).toBe(1);
});
describe('invoke', () => {
it('routes to OidbSvcTrpcTcp.0xcd4_1', async () => {
const deps = makeDeps();
await SetInputStatus.invoke(deps, { userId: 10001, eventType: 1 });
expect(deps.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0xcd4_1');
});
it('resolves the target uid before encoding', async () => {
const deps = makeDeps();
await SetInputStatus.invoke(deps, { userId: 10001, eventType: 1 });
expect(deps.resolveUserUid).toHaveBeenCalledWith(10001);
});
it('packages uid + chatType=0 + eventType into reqBody', async () => {
const deps = makeDeps('alice-uid');
await SetInputStatus.invoke(deps, { userId: 10001, eventType: 7 });
const [, bytes] = deps.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<Oidb0xcd4Req>>(bytes);
expect(env.body?.reqBody?.uid).toBe('alice-uid');
// chatType=0 is proto3 default — omitted on the wire, comes back as null/undefined.
expect(env.body?.reqBody?.chatType ?? 0).toBe(0);
expect(env.body?.reqBody?.eventType).toBe(7);
});
it('throws when the target uid cannot be resolved', async () => {
const deps = makeDeps(null);
await expect(SetInputStatus.invoke(deps, { userId: 10001, eventType: 1 }))
.rejects.toThrow('target uid not found');
expect(deps.sendRawPacket).not.toHaveBeenCalled();
});
});
});
@@ -0,0 +1,67 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { OidbSetProfile } from '@snowluma/proto-defs/oidb-actions/base';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { SetProfile } from '../../../src/oidb-services/profile/set-profile';
function makeDeps() {
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) };
return {
sendRawPacket: vi.fn(async () => r),
identity: { uin: '10001' } as any,
};
}
describe('SetProfile namespace', () => {
it('declares 0x112A_2', () => {
expect(SetProfile.command).toBe(0x112A);
expect(SetProfile.subCommand).toBe(2);
});
describe('invoke', () => {
it('is a no-op when both nickname and personalNote are undefined', async () => {
const deps = makeDeps();
await SetProfile.invoke(deps, {});
expect(deps.sendRawPacket).not.toHaveBeenCalled();
});
it('packages nickname into fieldId 20002', async () => {
const deps = makeDeps();
await SetProfile.invoke(deps, { nickname: 'New Nick' });
expect(deps.sendRawPacket).toHaveBeenCalledOnce();
const [wireName, bytes] = deps.sendRawPacket.mock.calls[0]!;
expect(wireName).toBe('OidbSvcTrpcTcp.0x112a_2');
const env = protobuf_decode<OidbBase<OidbSetProfile>>(bytes);
expect(env.body?.stringProfiles).toEqual([{ fieldId: 20002, value: 'New Nick' }]);
});
it('packages personalNote into fieldId 102', async () => {
const deps = makeDeps();
await SetProfile.invoke(deps, { personalNote: 'on vacation' });
const [, bytes] = deps.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbSetProfile>>(bytes);
expect(env.body?.stringProfiles).toEqual([{ fieldId: 102, value: 'on vacation' }]);
});
it('packages both fields together', async () => {
const deps = makeDeps();
await SetProfile.invoke(deps, { nickname: 'Foo', personalNote: 'Bar' });
const [, bytes] = deps.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbSetProfile>>(bytes);
expect(env.body?.stringProfiles).toEqual([
{ fieldId: 20002, value: 'Foo' },
{ fieldId: 102, value: 'Bar' },
]);
});
it('passes the bot uin in the request body', async () => {
const deps = makeDeps();
await SetProfile.invoke(deps, { nickname: 'x' });
const [, bytes] = deps.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbSetProfile>>(bytes);
expect(env.body?.uin).toBe(10001n);
});
});
});
@@ -0,0 +1,48 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { Oidb0x112aReq } from '@snowluma/proto-defs/oidb-actions/base';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { SetSelfLongNick } from '../../../src/oidb-services/profile/set-self-long-nick';
function makeDeps() {
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) };
return {
sendRawPacket: vi.fn(async () => r),
identity: { uin: '10001' } as any,
};
}
describe('SetSelfLongNick namespace', () => {
it('declares 0x112A_2', () => {
expect(SetSelfLongNick.command).toBe(0x112A);
expect(SetSelfLongNick.subCommand).toBe(2);
});
describe('invoke', () => {
it('routes to OidbSvcTrpcTcp.0x112a_2', async () => {
const deps = makeDeps();
await SetSelfLongNick.invoke(deps, { longNick: 'hello world' });
expect(deps.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x112a_2');
});
it('wraps the long nick in profile { tag: 102, value }', async () => {
const deps = makeDeps();
await SetSelfLongNick.invoke(deps, { longNick: 'hello world' });
const [, bytes] = deps.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<Oidb0x112aReq>>(bytes);
expect(env.body?.uin).toBe(10001n);
expect(env.body?.profile).toEqual({ tag: 102, value: 'hello world' });
});
it('coerces non-string longNick into a string (defensive)', async () => {
const deps = makeDeps();
// simulate a misbehaving caller passing a number
await SetSelfLongNick.invoke(deps, { longNick: 12345 as any });
const [, bytes] = deps.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<Oidb0x112aReq>>(bytes);
expect(env.body?.profile?.value).toBe('12345');
});
});
});