refactor(oidb): namespace-per-cmd service layer — vertical slice (3 cmds)

Introduce a new way to organise OIDB cmd implementations:

  - one TypeScript namespace per (cmd, subcmd) tuple
  - the namespace's exported members ARE the OidbCallSpec (structural
    typing — no `implements` clause)
  - a single invokeOidb() template method drives every call:
    envelope build → encode → send → errorCode check → decode →
    deserialize transformation
  - each namespace declares its own minimal `Deps` capability via
    Pick / intersection on BridgeContext (Interface Segregation):
    most cmds need only OidbSender (the `sendRawPacket` method)

The facade Api classes (InteractionApi etc.) stay for now, with the
migrated methods reduced to one-line forwarders that hand off to the
namespace. Callers still write `bridge.apis.X.Y(...)`; the OIDB
wire-encoding work just moved to a self-contained file per cmd.

Vertical slice scope: 3 cmds (the reaction line)
  - SetReaction              (0x9082_1 / _2; dynamic subcmd)
  - FetchReactionSummary     (0x9084_1)
  - GetEmojiLikes            (0x9083_1; legacy stub)

Infrastructure:
  - new packages/bridge/src/oidb-service.ts:
      OidbSender (sendRawPacket-only capability),
      OidbCallSpec<TReq, TResp, TParams, TResult>,
      invokeOidb(), buildOidbRequest(), parseOidbResponse(), OidbError
  - runOidb() refactored to accept OidbSender instead of BridgeContext
    (structurally compatible — no caller changes anywhere)
  - new OidbEmpty placeholder type in proto-defs/oidb.ts for cmds whose
    response carries no body (proton needs a real message interface,
    not `void` / `never`)
  - empty-body responses substituted with {} in invokeOidb so
    deserialize always receives a defined object

Tests (65 in @snowluma/bridge, all green):
  - oidb-service.test.ts (20): every helper branch — static + dynamic
    subcmd, uinForm flag, error code propagation as OidbError, empty
    body substitution, sender failure modes (success=false /
    gotResponse=false / both with and without errorMessage),
    timeoutMs propagation
  - set-reaction.test.ts: const declarations, dynamic subcmd both
    ways, type=1/2 boundary on code length, e2e envelope inspection
  - fetch-reaction-summary.test.ts: BigInt serialization, catalog-tail
    filtering, default emojiId/Type/lastReactionTime
  - get-emoji-likes.test.ts: BigInt serialization, default count /
    emojiType, base64 cookie round-trip, uin=0 filtering, isLast
    computation, e2e

Existing interaction.test.ts moved off the now-bypassed runOidb mock
onto sendRawPacket mock (the new invokeOidb path routes there).

Workspace-wide typecheck: green. Workspace test totals:
  proton  99/99, bridge 65/65, core 302/302, onebot 257/257
  (1 pre-existing onebot suite failure, network-manager native addon
  load — unrelated to this change.)
This commit is contained in:
DrSmoothl committed 2026-05-22 23:15:20 +08:00
1 parent c3675aef7c
commit 0238bcb280
14 files changed
+1066 -122

No files matched your search

+17
View File
@@ -35,6 +35,22 @@
"types": "./src/bridge-oidb.ts",
"default": "./src/bridge-oidb.ts"
},
"./oidb-service": {
"types": "./src/oidb-service.ts",
"default": "./src/oidb-service.ts"
},
"./oidb-services/reaction/set-reaction": {
"types": "./src/oidb-services/reaction/set-reaction.ts",
"default": "./src/oidb-services/reaction/set-reaction.ts"
},
"./oidb-services/reaction/fetch-reaction-summary": {
"types": "./src/oidb-services/reaction/fetch-reaction-summary.ts",
"default": "./src/oidb-services/reaction/fetch-reaction-summary.ts"
},
"./oidb-services/reaction/get-emoji-likes": {
"types": "./src/oidb-services/reaction/get-emoji-likes.ts",
"default": "./src/oidb-services/reaction/get-emoji-likes.ts"
},
"./bridge-context": {
"types": "./src/bridge-context.ts",
"default": "./src/bridge-context.ts"
@@ -113,6 +129,7 @@
}
},
"scripts": {
"test": "vitest run",
"bench": "vitest bench --run",
"typecheck": "tsc --noEmit"
},
+6 -3
View File
@@ -1,6 +1,9 @@
import { protobuf_decode } from '@snowluma/proton';
import type { BridgeContext } from './bridge-context';
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';
/**
* Build the OidbBase<T>-shaped TS value. Pure helper, no protobuf
@@ -45,12 +48,12 @@ export function makeOidbEnvelope<T>(
* packet carried no payload).
*/
export async function runOidb(
bridge: BridgeContext,
sender: OidbSender,
cmd: string,
envelopeBytes: Uint8Array,
timeoutMs?: number,
): Promise<Uint8Array> {
const result = await bridge.sendRawPacket(cmd, envelopeBytes, timeoutMs);
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');
+143
View File
@@ -0,0 +1,143 @@
// OIDB service layer — the next architectural revision on top of the
// area-grouped Api facade pattern (InteractionApi / ProfileApi / …).
//
// Each OIDB cmd is modelled as a TypeScript namespace whose exported
// members ARE the `OidbCallSpec` shape (structural typing makes this
// implicit — no `implements` clause needed). The namespace also exports
// a thin `invoke()` that hands itself to `invokeOidb` for dispatch.
//
// Why namespace-as-spec instead of class:
// - stateless: no `new` overhead at the call site
// - no `this` binding, no implicit lifecycle
// - tree-shakes per-export (unused services drop out of the bundle)
// - spec ↔ code 1:1 (one file = one (cmd, subcmd) tuple)
//
// Why Pick-style minimal `Deps` per service:
// - Interface Segregation: a wire-only cmd doesn't see identity/events
// - tests mock only what's used (typically just `sendRawPacket`)
// - changes to BridgeContext don't bleed into services
// - the dep list IS the documentation of side-effects
import { protobuf_decode } from '@snowluma/proton';
import type { OidbBase, OidbBaseMeta } from '@snowluma/proto-defs/oidb';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { makeOidbEnvelope } from './bridge-oidb';
/**
* Capability narrow enough for any wire-only OIDB call. Anything that
* also needs identity / event bus / upload cache declares those via
* `Pick<BridgeContext, 'identity' | …>` and intersects with this.
*/
export interface OidbSender {
sendRawPacket(serviceCmd: string, body: Uint8Array, timeoutMs?: number): Promise<SendPacketResult>;
}
/**
* The shape every cmd namespace exports. Structural typing means a
* namespace whose top-level exports match these names + types IS an
* `OidbCallSpec` — no `implements` clause needed.
*
* One of `subCommand` (static) or `resolveSubCommand` (dynamic from
* params) must be present. `resolveSubCommand` wins if both are given.
*/
export interface OidbCallSpec<TReq, TResp, TParams, TResult> {
command: number;
subCommand?: number;
resolveSubCommand?(params: TParams): number;
/** Set OIDB envelope `reserved = 1` (UIN-form variant, see makeOidbEnvelope's isUid). */
uinForm?: boolean;
/** Business params → wire-shaped request body. */
serialize(params: TParams): TReq;
/** Wire-shaped response body → business result. */
deserialize(body: TResp): TResult;
/** Per-type protobuf encoder — concrete generic call so the Vite plugin can monomorphize. */
encode(env: OidbBase<TReq>): Uint8Array;
/** Per-type protobuf decoder. */
decode(bytes: Uint8Array): OidbBase<TResp>;
}
export class OidbError extends Error {
constructor(
readonly code: number,
readonly serverMsg: string,
readonly command: number,
readonly subCommand: number,
) {
super(`OIDB error ${code} on 0x${command.toString(16)}_${subCommand}: ${serverMsg}`);
this.name = 'OidbError';
}
}
/**
* Template method for every OIDB call. Builds the envelope, encodes it,
* sends through the supplied minimal sender capability, validates the
* envelope's `errorCode`, decodes the body, and hands the wire-shaped
* response to the spec's `deserialize` for transformation into the
* business result.
*/
export async function invokeOidb<TReq, TResp, TParams, TResult>(
sender: OidbSender,
spec: OidbCallSpec<TReq, TResp, TParams, TResult>,
params: TParams,
timeoutMs?: number,
): Promise<TResult> {
const subCommand = spec.resolveSubCommand
? spec.resolveSubCommand(params)
: spec.subCommand!;
const reqBody = spec.serialize(params);
const env = makeOidbEnvelope(spec.command, subCommand, reqBody, spec.uinForm ?? false);
const reqBytes = spec.encode(env);
const wireName = `OidbSvcTrpcTcp.0x${spec.command.toString(16)}_${subCommand}`;
const result = await sender.sendRawPacket(wireName, reqBytes, timeoutMs);
if (!result.success) throw new Error(result.errorMessage || 'packet send failed');
if (!result.gotResponse) throw new Error(result.errorMessage || 'no response');
const respBytes = result.responseData ?? new Uint8Array(0);
if (respBytes.length > 0) {
const meta = protobuf_decode<OidbBaseMeta>(respBytes);
const code = meta?.errorCode;
if (code && code !== 0) {
throw new OidbError(code, meta?.errorMsg ?? '', spec.command, subCommand);
}
}
// Server may legitimately respond with an empty envelope (ack-only
// cmds like 0x9082_1 — the response carries only `errorCode = 0`
// and no body). Substitute an empty placeholder so `deserialize`
// always receives a defined object; specs that read fields off the
// body must already guard with `?? []` etc.
const respBody = spec.decode(respBytes).body ?? ({} as TResp);
return spec.deserialize(respBody);
}
/**
* Build the request wire bytes for a spec without sending — useful for
* wire dump debugging, capability probing, and unit tests of the
* encode path.
*/
export function buildOidbRequest<TReq, TResp, TParams, TResult>(
spec: OidbCallSpec<TReq, TResp, TParams, TResult>,
params: TParams,
): { wireName: string; bytes: Uint8Array } {
const subCommand = spec.resolveSubCommand
? spec.resolveSubCommand(params)
: spec.subCommand!;
const reqBody = spec.serialize(params);
const env = makeOidbEnvelope(spec.command, subCommand, reqBody, spec.uinForm ?? false);
const bytes = spec.encode(env);
const wireName = `OidbSvcTrpcTcp.0x${spec.command.toString(16)}_${subCommand}`;
return { wireName, bytes };
}
/**
* Decode raw wire bytes into the business result via a spec's
* deserialize path — symmetric debug helper for buildOidbRequest.
*/
export function parseOidbResponse<TReq, TResp, TParams, TResult>(
spec: OidbCallSpec<TReq, TResp, TParams, TResult>,
bytes: Uint8Array,
): TResult {
return spec.deserialize(spec.decode(bytes).body ?? ({} as TResp));
}
@@ -0,0 +1,72 @@
// 0x9084_1 — fetch per-emoji reaction summary on a group message.
//
// Server returns the full summary unconditionally; the emoji_id /
// emoji_type / count fields in the request body are ignored by the
// summary handler but kept to mirror the working 0x9083_1 request shape
// (same `Pick` of fields the wire format prefers).
//
// "Used" entries carry (lastReactionTime, count, emojiType, emojiId).
// Catalog-tail entries (available reactions the server suggests but
// nobody has reacted with) carry only emojiType + emojiId — filtered
// out here so callers see only the meaningful subset.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
Oidb0x9084Req, Oidb0x9084Resp,
} from '@snowluma/proto-defs/oidb-actions/base';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export namespace FetchReactionSummary {
export const command = 0x9084;
export const subCommand = 1;
export interface Params {
groupId: number;
sequence: number;
}
export interface ReactionSummaryEntry {
emojiId: string;
emojiType: number;
count: number;
/** Unix epoch seconds of the most recent reaction. */
lastReactionTime: number;
}
export type Deps = OidbSender;
export const serialize = (p: Params): Oidb0x9084Req => ({
groupId: BigInt(p.groupId),
sequence: BigInt(p.sequence),
emojiId: '',
emojiType: 0,
cookie: new Uint8Array(0),
count: 0,
field12: 1,
});
export const deserialize = (body: Oidb0x9084Resp): ReactionSummaryEntry[] => {
const out: ReactionSummaryEntry[] = [];
for (const e of body.entries ?? []) {
const count = e.count ?? 0;
if (count <= 0) continue; // skip catalog-tail entries
out.push({
emojiId: e.emojiId ?? '',
emojiType: e.emojiType ?? 1,
count,
lastReactionTime: Number(e.lastReactionTime ?? 0n),
});
}
return out;
};
export const encode = (env: OidbBase<Oidb0x9084Req>): Uint8Array =>
protobuf_encode<OidbBase<Oidb0x9084Req>>(env);
export const decode = (bytes: Uint8Array): OidbBase<Oidb0x9084Resp> =>
protobuf_decode<OidbBase<Oidb0x9084Resp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<ReactionSummaryEntry[]> =>
invokeOidb(deps, FetchReactionSummary, params);
}
@@ -0,0 +1,71 @@
// 0x9083_1 — historic "fetch reactor user list" cmd. CONFIRMED to be
// a real server endpoint (errorCode=0, trace string echoes the cmd
// name), but its reply is always a 4-byte minimal ack `18 01 20 01`
// regardless of the message / emoji / whether the bot just set a
// reaction. The actual "who reacted" data is NOT served via SSO at
// all — NTQQ's own client uses a wrapper-internal cache. SnowLuma
// mirrors that with `ReactionStore` (fed from GroupMsgEmojiLikeEvent
// push) on the OneBot side.
//
// This namespace exists as a legacy stub so older callers don't crash
// — `invoke` always returns an empty user list. Newer code should
// query `ReactionStore` instead.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
Oidb0x9083Req, Oidb0x9083Resp,
} from '@snowluma/proto-defs/oidb-actions/base';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export namespace GetEmojiLikes {
export const command = 0x9083;
export const subCommand = 1;
export interface Params {
groupId: number;
sequence: number;
emojiId: string;
emojiType?: number;
count?: number;
/** Base64-encoded continuation cookie from a previous page. */
cookie?: string;
}
export interface Result {
users: Array<{ uin: number }>;
/** Base64 cookie for next page (empty when on last page). */
cookie: string;
isLast: boolean;
}
export type Deps = OidbSender;
export const serialize = (p: Params): Oidb0x9083Req => ({
groupId: BigInt(p.groupId),
sequence: BigInt(p.sequence),
emojiId: p.emojiId,
emojiType: p.emojiType ?? 1,
cookie: p.cookie ? Buffer.from(p.cookie, 'base64') : new Uint8Array(0),
field7: 0,
count: p.count ?? 10,
field12: 1,
});
export const deserialize = (body: Oidb0x9083Resp): Result => {
const users: Array<{ uin: number }> = (body.inner?.userInfo ?? [])
.map(u => ({ uin: Number(u?.uin ?? 0) }))
.filter(u => u.uin > 0);
const cookie = body.cookie ? Buffer.from(body.cookie).toString('base64') : '';
return { users, cookie, isLast: !cookie };
};
export const encode = (env: OidbBase<Oidb0x9083Req>): Uint8Array =>
protobuf_encode<OidbBase<Oidb0x9083Req>>(env);
export const decode = (bytes: Uint8Array): OidbBase<Oidb0x9083Resp> =>
protobuf_decode<OidbBase<Oidb0x9083Resp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<Result> =>
invokeOidb(deps, GetEmojiLikes, params);
}
@@ -0,0 +1,54 @@
// 0x9082 — set / unset emoji reaction on a group message.
// subCommand 1 = set, 2 = unset
//
// Cross-checked against LagrangeV2
// `Internal/Packets/Service/SetGroupReaction.cs`:
// field 2 groupUin (long)
// field 3 sequence (ulong)
// field 4 code (string) ← emoji id
// field 5 type (ulong) ← 1 for QQ-face short id, 2 for unicode codepoint
// (Heuristic on `code.length > 3` matches Lagrange's
// `GroupAddReactionEvent.IsEmoji` discriminator.)
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb';
import type { OidbGroupReaction } from '@snowluma/proto-defs/oidb-actions/base';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export namespace SetReaction {
export const command = 0x9082;
export interface Params {
groupId: number;
sequence: number;
/** Emoji code. 1–3 digits → QQ face (type=1); longer → unicode (type=2). */
code: string;
/** true = set reaction (subCommand 1), false = unset (subCommand 2). */
isSet: boolean;
}
/** Only the wire-send capability is needed. */
export type Deps = OidbSender;
export const resolveSubCommand = (p: Params): number => p.isSet ? 1 : 2;
export const serialize = (p: Params): OidbGroupReaction => ({
groupUin: p.groupId,
sequence: p.sequence,
code: p.code,
type: p.code.length > 3 ? 2 : 1,
field6: false,
field7: false,
});
export const deserialize = (_: OidbEmpty): void => {};
export const encode = (env: OidbBase<OidbGroupReaction>): Uint8Array =>
protobuf_encode<OidbBase<OidbGroupReaction>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbEmpty> =>
protobuf_decode<OidbBase<OidbEmpty>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, SetReaction, params);
}
+259
View File
@@ -0,0 +1,259 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb';
import type { OidbGroupReaction } from '@snowluma/proto-defs/oidb-actions/base';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import {
buildOidbRequest,
invokeOidb,
OidbError,
parseOidbResponse,
type OidbCallSpec,
type OidbSender,
} from '../src/oidb-service';
// Reused minimal spec — encodes a group-reaction-shaped request and
// reads back a void result. Exercises every spec branch.
const reactionSpec: OidbCallSpec<
OidbGroupReaction, OidbEmpty,
{ groupId: number; sequence: number; code: string; isSet: boolean }, void
> = {
command: 0x9082,
resolveSubCommand: p => p.isSet ? 1 : 2,
serialize: p => ({
groupUin: p.groupId,
sequence: p.sequence,
code: p.code,
type: p.code.length > 3 ? 2 : 1,
field6: false,
field7: false,
}),
deserialize: () => {},
encode: env => protobuf_encode<OidbBase<OidbGroupReaction>>(env),
decode: bytes => protobuf_decode<OidbBase<OidbEmpty>>(bytes),
};
// Static-subCommand variant for the branch test.
const staticSubSpec: OidbCallSpec<OidbGroupReaction, OidbEmpty, { groupId: number }, void> = {
command: 0xEAC,
subCommand: 1,
serialize: p => ({ groupUin: p.groupId, sequence: 0, code: '', type: 1, field6: false, field7: false }),
deserialize: () => {},
encode: env => protobuf_encode<OidbBase<OidbGroupReaction>>(env),
decode: bytes => protobuf_decode<OidbBase<OidbEmpty>>(bytes),
};
function makeSender(resp: Partial<SendPacketResult> = {}): OidbSender & { sendRawPacket: ReturnType<typeof vi.fn> } {
const defaultResp: SendPacketResult = {
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
responseData: Buffer.alloc(0),
};
return {
sendRawPacket: vi.fn(async () => ({ ...defaultResp, ...resp })),
};
}
describe('invokeOidb', () => {
it('uses resolveSubCommand when present and computes the wire name', async () => {
const sender = makeSender();
await invokeOidb(sender, reactionSpec, { groupId: 12345, sequence: 99, code: '76', isSet: true });
expect(sender.sendRawPacket).toHaveBeenCalledOnce();
const [wireName] = sender.sendRawPacket.mock.calls[0]!;
expect(wireName).toBe('OidbSvcTrpcTcp.0x9082_1');
});
it('flips wire name when resolveSubCommand returns a different subcmd', async () => {
const sender = makeSender();
await invokeOidb(sender, reactionSpec, { groupId: 1, sequence: 1, code: '76', isSet: false });
const [wireName] = sender.sendRawPacket.mock.calls[0]!;
expect(wireName).toBe('OidbSvcTrpcTcp.0x9082_2');
});
it('uses static subCommand when resolveSubCommand is absent', async () => {
const sender = makeSender();
await invokeOidb(sender, staticSubSpec, { groupId: 12345 });
const [wireName] = sender.sendRawPacket.mock.calls[0]!;
expect(wireName).toBe('OidbSvcTrpcTcp.0xeac_1');
});
it('encodes serialize() output into an OIDB envelope (cmd + subcmd land in fields 1/2)', async () => {
const sender = makeSender();
await invokeOidb(sender, reactionSpec, { groupId: 12345, sequence: 99, code: '76', isSet: true });
const [, bytes] = sender.sendRawPacket.mock.calls[0]!;
// First two top-level varint fields of the envelope should be the
// cmd (0x9082) and the resolved subcmd (1).
const env = protobuf_decode<OidbBase<OidbGroupReaction>>(bytes);
expect(env.command).toBe(0x9082);
expect(env.subCommand).toBe(1);
// proto3 default-false bool fields aren't serialized — they come back
// as null/undefined on decode, not the literal `false` we passed.
expect(env.body).toMatchObject({
groupUin: 12345, sequence: 99, code: '76', type: 1,
});
});
it('passes the body through deserialize for transformation', async () => {
type Echo = { tag: number };
const spec: OidbCallSpec<OidbGroupReaction, OidbGroupReaction, { code: string }, Echo> = {
command: 0x9082,
subCommand: 1,
serialize: p => ({ code: p.code }),
deserialize: b => ({ tag: b.type ?? 99 }),
encode: env => protobuf_encode<OidbBase<OidbGroupReaction>>(env),
decode: bytes => protobuf_decode<OidbBase<OidbGroupReaction>>(bytes),
};
// Server response: an OidbBase envelope whose body has type=5.
const responseEnvelope = protobuf_encode<OidbBase<OidbGroupReaction>>({
command: 0x9082, subCommand: 1,
body: { type: 5 } as OidbGroupReaction,
});
const sender = makeSender({ responseData: Buffer.from(responseEnvelope) });
const result = await invokeOidb(sender, spec, { code: 'x' });
expect(result).toEqual({ tag: 5 });
});
it('substitutes an empty body when the envelope has no field 4', async () => {
// Envelope with only command + errorCode = 0, no body.
const envBytes = protobuf_encode<OidbBase<OidbEmpty>>({ command: 0x9082, subCommand: 1 });
const sender = makeSender({ responseData: Buffer.from(envBytes) });
const deserialize = vi.fn(() => undefined);
const spec: OidbCallSpec<OidbGroupReaction, OidbEmpty, { code: string }, void> = {
command: 0x9082, subCommand: 1,
serialize: p => ({ code: p.code }),
deserialize,
encode: env => protobuf_encode<OidbBase<OidbGroupReaction>>(env),
decode: bytes => protobuf_decode<OidbBase<OidbEmpty>>(bytes),
};
await invokeOidb(sender, spec, { code: 'x' });
// deserialize must still receive a defined object (the substituted {}).
expect(deserialize).toHaveBeenCalledOnce();
expect(deserialize.mock.calls[0]![0]).toEqual({});
});
it('propagates timeoutMs to sendRawPacket', async () => {
const sender = makeSender();
await invokeOidb(sender, staticSubSpec, { groupId: 1 }, 5000);
expect(sender.sendRawPacket.mock.calls[0]![2]).toBe(5000);
});
it('rethrows the sender errorMessage when success=false', async () => {
const sender = makeSender({ success: false, errorMessage: 'boom' });
await expect(invokeOidb(sender, staticSubSpec, { groupId: 1 })).rejects.toThrow('boom');
});
it('falls back to "packet send failed" when success=false and errorMessage is empty', async () => {
const sender = makeSender({ success: false, errorMessage: '' });
await expect(invokeOidb(sender, staticSubSpec, { groupId: 1 })).rejects.toThrow('packet send failed');
});
it('rethrows when sender returns success=true but gotResponse=false', async () => {
const sender = makeSender({ success: true, gotResponse: false, errorMessage: 'timeout' });
await expect(invokeOidb(sender, staticSubSpec, { groupId: 1 })).rejects.toThrow('timeout');
});
it('falls back to "no response" when gotResponse=false and errorMessage is empty', async () => {
const sender = makeSender({ success: true, gotResponse: false, errorMessage: '' });
await expect(invokeOidb(sender, staticSubSpec, { groupId: 1 })).rejects.toThrow('no response');
});
it('raises OidbError when envelope errorCode != 0', async () => {
const errBytes = protobuf_encode<OidbBase<OidbEmpty>>({
command: 0x9082, subCommand: 1, errorCode: 42, errorMsg: 'no privilege',
});
const sender = makeSender({ responseData: Buffer.from(errBytes) });
let caught: unknown;
try { await invokeOidb(sender, staticSubSpec, { groupId: 1 }); }
catch (e) { caught = e; }
expect(caught).toBeInstanceOf(OidbError);
expect((caught as OidbError).code).toBe(42);
expect((caught as OidbError).serverMsg).toBe('no privilege');
expect((caught as OidbError).command).toBe(0xEAC);
expect((caught as OidbError).subCommand).toBe(1);
expect((caught as OidbError).message).toContain('OIDB error 42');
expect((caught as OidbError).message).toContain('0xeac_1');
});
it('skips OidbError check when response payload is empty', async () => {
// Server returns success=true but with zero-length payload (a
// legitimate "ack-only" response). invokeOidb must NOT try to
// decode envelope meta on empty bytes.
const sender = makeSender({ responseData: Buffer.alloc(0) });
// Should not throw.
await expect(invokeOidb(sender, staticSubSpec, { groupId: 1 })).resolves.toBeUndefined();
});
it('honours uinForm=true by flipping OIDB envelope reserved to 1', async () => {
const spec: OidbCallSpec<OidbGroupReaction, OidbEmpty, { groupId: number }, void> = {
...staticSubSpec,
uinForm: true,
};
const sender = makeSender();
await invokeOidb(sender, spec, { groupId: 1 });
const [, bytes] = sender.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbGroupReaction>>(bytes);
expect(env.reserved).toBe(1);
});
it('uses uinForm=false by default (envelope reserved=0)', async () => {
const sender = makeSender();
await invokeOidb(sender, staticSubSpec, { groupId: 1 });
const [, bytes] = sender.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbGroupReaction>>(bytes);
// proto3 default 0 may be omitted on the wire — expect either 0 or undefined.
expect(env.reserved ?? 0).toBe(0);
});
});
describe('buildOidbRequest', () => {
it('returns the same wire name + bytes that invokeOidb would send', async () => {
const sender = makeSender();
await invokeOidb(sender, reactionSpec, { groupId: 12345, sequence: 99, code: '128516', isSet: true });
const sentBytes = sender.sendRawPacket.mock.calls[0]![1];
const built = buildOidbRequest(reactionSpec, { groupId: 12345, sequence: 99, code: '128516', isSet: true });
expect(built.wireName).toBe('OidbSvcTrpcTcp.0x9082_1');
expect(Buffer.from(built.bytes).equals(Buffer.from(sentBytes))).toBe(true);
});
it('uses static subCommand when resolveSubCommand is absent', () => {
const built = buildOidbRequest(staticSubSpec, { groupId: 1 });
expect(built.wireName).toBe('OidbSvcTrpcTcp.0xeac_1');
});
});
describe('parseOidbResponse', () => {
it('decodes wire bytes via spec.decode and runs spec.deserialize on the body', () => {
const envBytes = protobuf_encode<OidbBase<OidbGroupReaction>>({
command: 0x9082, subCommand: 1, body: { type: 7 } as OidbGroupReaction,
});
type Echo = { type: number };
const spec: OidbCallSpec<OidbGroupReaction, OidbGroupReaction, void, Echo> = {
command: 0x9082, subCommand: 1,
serialize: () => ({} as OidbGroupReaction),
deserialize: b => ({ type: b.type ?? 0 }),
encode: env => protobuf_encode<OidbBase<OidbGroupReaction>>(env),
decode: bytes => protobuf_decode<OidbBase<OidbGroupReaction>>(bytes),
};
expect(parseOidbResponse(spec, envBytes)).toEqual({ type: 7 });
});
it('substitutes empty body when the envelope lacks one', () => {
const envBytes = protobuf_encode<OidbBase<OidbEmpty>>({ command: 0x9082, subCommand: 1 });
const deserialize = vi.fn(() => ({ ok: true }));
parseOidbResponse({ ...staticSubSpec, deserialize } as any, envBytes);
expect(deserialize).toHaveBeenCalledWith({});
});
});
describe('OidbError', () => {
it('formats message with hex cmd and decimal subcmd', () => {
const e = new OidbError(123, 'denied', 0x9084, 2);
expect(e.message).toBe('OIDB error 123 on 0x9084_2: denied');
expect(e.name).toBe('OidbError');
expect(e.code).toBe(123);
expect(e.serverMsg).toBe('denied');
expect(e.command).toBe(0x9084);
expect(e.subCommand).toBe(2);
});
});
@@ -0,0 +1,133 @@
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 { Oidb0x9084Req, Oidb0x9084Resp } from '@snowluma/proto-defs/oidb-actions/base';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { FetchReactionSummary } from '../../../src/oidb-services/reaction/fetch-reaction-summary';
function makeSender(resp?: Buffer) {
const defaultResp: SendPacketResult = {
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
responseData: resp ?? Buffer.alloc(0),
};
return { sendRawPacket: vi.fn(async () => defaultResp) };
}
describe('FetchReactionSummary namespace', () => {
it('declares command = 0x9084 and subCommand = 1', () => {
expect(FetchReactionSummary.command).toBe(0x9084);
expect(FetchReactionSummary.subCommand).toBe(1);
});
describe('serialize', () => {
it('encodes groupId/sequence as BigInt for uint_64 fields', () => {
const out = FetchReactionSummary.serialize({ groupId: 1022489779, sequence: 1730183 });
expect(out.groupId).toBe(1022489779n);
expect(out.sequence).toBe(1730183n);
});
it('passes empty / default values for the unused filter fields', () => {
const out = FetchReactionSummary.serialize({ groupId: 1, sequence: 1 });
expect(out.emojiId).toBe('');
expect(out.emojiType).toBe(0);
expect(out.count).toBe(0);
expect(out.field12).toBe(1);
});
it('emits a 0-length cookie buffer (no continuation)', () => {
const out = FetchReactionSummary.serialize({ groupId: 1, sequence: 1 });
expect(out.cookie).toBeInstanceOf(Uint8Array);
expect(out.cookie!.length).toBe(0);
});
});
describe('deserialize', () => {
it('keeps entries with count > 0 (used emojis)', () => {
const body: Oidb0x9084Resp = {
entries: [
{ lastReactionTime: 1779456439n, count: 3, emojiType: 1, emojiId: '76' },
{ lastReactionTime: 1779456962n, count: 1, emojiType: 1, emojiId: '124' },
],
};
expect(FetchReactionSummary.deserialize(body)).toEqual([
{ emojiId: '76', emojiType: 1, count: 3, lastReactionTime: 1779456439 },
{ emojiId: '124', emojiType: 1, count: 1, lastReactionTime: 1779456962 },
]);
});
it('filters out catalog-tail entries (count omitted ≡ 0)', () => {
const body: Oidb0x9084Resp = {
entries: [
{ lastReactionTime: 1n, count: 1, emojiType: 1, emojiId: '76' },
{ emojiType: 1, emojiId: '124' }, // catalog entry
{ emojiType: 1, emojiId: '66' }, // catalog entry
],
};
const out = FetchReactionSummary.deserialize(body);
expect(out).toHaveLength(1);
expect(out[0]!.emojiId).toBe('76');
});
it('returns an empty array when the response has no entries', () => {
expect(FetchReactionSummary.deserialize({})).toEqual([]);
});
it('defaults emojiId / emojiType to safe values when omitted', () => {
const body: Oidb0x9084Resp = {
entries: [{ count: 5, lastReactionTime: 1700000000n }],
};
const [entry] = FetchReactionSummary.deserialize(body);
expect(entry).toEqual({
emojiId: '', emojiType: 1, count: 5, lastReactionTime: 1700000000,
});
});
it('reports lastReactionTime=0 when omitted on a used entry (degenerate but defensive)', () => {
const body: Oidb0x9084Resp = { entries: [{ count: 2, emojiId: 'x', emojiType: 1 }] };
expect(FetchReactionSummary.deserialize(body)[0]!.lastReactionTime).toBe(0);
});
});
describe('invoke (e2e via mock sender)', () => {
it('sends to OidbSvcTrpcTcp.0x9084_1', async () => {
const sender = makeSender();
await FetchReactionSummary.invoke(sender, { groupId: 1, sequence: 1 });
expect(sender.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x9084_1');
});
it('end-to-end: encode → decode pipeline yields the parsed summary entries', async () => {
const respEnvelope = Buffer.from(protobuf_encode<OidbBase<Oidb0x9084Resp>>({
command: 0x9084, subCommand: 1,
body: {
entries: [
{ lastReactionTime: 1700000000n, count: 5, emojiType: 1, emojiId: '76' },
{ emojiType: 1, emojiId: '124' }, // catalog noise
],
},
}));
const sender = makeSender(respEnvelope);
const result = await FetchReactionSummary.invoke(sender, { groupId: 1, sequence: 1 });
expect(result).toEqual([
{ emojiId: '76', emojiType: 1, count: 5, lastReactionTime: 1700000000 },
]);
});
it('encodes the request envelope with groupId/sequence as uint_64', async () => {
const sender = makeSender();
await FetchReactionSummary.invoke(sender, { groupId: 1022489779, sequence: 1730183 });
const [, reqBytes] = sender.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<Oidb0x9084Req>>(reqBytes);
expect(env.command).toBe(0x9084);
expect(env.subCommand).toBe(1);
expect(env.body?.groupId).toBe(1022489779n);
expect(env.body?.sequence).toBe(1730183n);
});
it('returns an empty array when server responds with empty envelope', async () => {
const sender = makeSender();
const result = await FetchReactionSummary.invoke(sender, { groupId: 1, sequence: 1 });
expect(result).toEqual([]);
});
});
});
@@ -0,0 +1,158 @@
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 { Oidb0x9083Req, Oidb0x9083Resp } from '@snowluma/proto-defs/oidb-actions/base';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { GetEmojiLikes } from '../../../src/oidb-services/reaction/get-emoji-likes';
function makeSender(resp?: Buffer) {
const defaultResp: SendPacketResult = {
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
responseData: resp ?? Buffer.alloc(0),
};
return { sendRawPacket: vi.fn(async () => defaultResp) };
}
describe('GetEmojiLikes namespace', () => {
it('declares command = 0x9083 and subCommand = 1', () => {
expect(GetEmojiLikes.command).toBe(0x9083);
expect(GetEmojiLikes.subCommand).toBe(1);
});
describe('serialize', () => {
it('encodes groupId/sequence as BigInt for uint_64 fields', () => {
const out = GetEmojiLikes.serialize({
groupId: 12345, sequence: 99, emojiId: '76',
});
expect(out.groupId).toBe(12345n);
expect(out.sequence).toBe(99n);
});
it('passes emojiId through unchanged', () => {
const out = GetEmojiLikes.serialize({ groupId: 1, sequence: 1, emojiId: '128516' });
expect(out.emojiId).toBe('128516');
});
it('defaults emojiType to 1 when omitted', () => {
const out = GetEmojiLikes.serialize({ groupId: 1, sequence: 1, emojiId: 'x' });
expect(out.emojiType).toBe(1);
});
it('uses caller-supplied emojiType when present', () => {
const out = GetEmojiLikes.serialize({ groupId: 1, sequence: 1, emojiId: 'x', emojiType: 2 });
expect(out.emojiType).toBe(2);
});
it('defaults count to 10 when omitted', () => {
const out = GetEmojiLikes.serialize({ groupId: 1, sequence: 1, emojiId: 'x' });
expect(out.count).toBe(10);
});
it('uses caller-supplied count when present', () => {
const out = GetEmojiLikes.serialize({ groupId: 1, sequence: 1, emojiId: 'x', count: 50 });
expect(out.count).toBe(50);
});
it('decodes base64 cookie into the bytes field for continuation', () => {
const cookie = Buffer.from([0xCA, 0xFE]).toString('base64');
const out = GetEmojiLikes.serialize({ groupId: 1, sequence: 1, emojiId: 'x', cookie });
expect(out.cookie).toBeInstanceOf(Uint8Array);
expect(Buffer.from(out.cookie!).equals(Buffer.from([0xCA, 0xFE]))).toBe(true);
});
it('emits a 0-length cookie buffer for the first page (no cookie supplied)', () => {
const out = GetEmojiLikes.serialize({ groupId: 1, sequence: 1, emojiId: 'x' });
expect(out.cookie!.length).toBe(0);
});
it('sets field7=0 and field12=1 (magic values matching the historic wire shape)', () => {
const out = GetEmojiLikes.serialize({ groupId: 1, sequence: 1, emojiId: 'x' });
expect(out.field7).toBe(0);
expect(out.field12).toBe(1);
});
});
describe('deserialize', () => {
it('extracts users from inner.userInfo and base64-encodes the cookie', () => {
const result = GetEmojiLikes.deserialize({
inner: { userInfo: [{ uin: 10001n }, { uin: 20002n }] },
cookie: new Uint8Array([0xCA, 0xFE]),
});
expect(result.users).toEqual([{ uin: 10001 }, { uin: 20002 }]);
expect(result.cookie).toBe(Buffer.from([0xCA, 0xFE]).toString('base64'));
expect(result.isLast).toBe(false);
});
it('filters out users with uin=0 (placeholder / zero-value)', () => {
const result = GetEmojiLikes.deserialize({
inner: { userInfo: [{ uin: 10001n }, { uin: 0n }, { uin: 20002n }] },
});
expect(result.users).toEqual([{ uin: 10001 }, { uin: 20002 }]);
});
it('returns empty users + empty cookie + isLast=true when body has nothing', () => {
const result = GetEmojiLikes.deserialize({});
expect(result.users).toEqual([]);
expect(result.cookie).toBe('');
expect(result.isLast).toBe(true);
});
it('returns isLast=true when cookie is absent (final page)', () => {
const result = GetEmojiLikes.deserialize({
inner: { userInfo: [{ uin: 10001n }] },
});
expect(result.isLast).toBe(true);
});
it('handles missing userInfo entries field', () => {
const result = GetEmojiLikes.deserialize({ inner: {} });
expect(result.users).toEqual([]);
});
});
describe('invoke (e2e via mock sender)', () => {
it('sends to OidbSvcTrpcTcp.0x9083_1', async () => {
const sender = makeSender();
await GetEmojiLikes.invoke(sender, { groupId: 1, sequence: 1, emojiId: '76' });
expect(sender.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x9083_1');
});
it('end-to-end: encode → decode yields parsed user list + cookie', async () => {
const respEnvelope = Buffer.from(protobuf_encode<OidbBase<Oidb0x9083Resp>>({
command: 0x9083, subCommand: 1,
body: {
inner: { userInfo: [{ uin: 10001n }] },
cookie: new Uint8Array([0xDE, 0xAD]),
} as any,
}));
const sender = makeSender(respEnvelope);
const result = await GetEmojiLikes.invoke(sender, { groupId: 1, sequence: 1, emojiId: '76' });
expect(result.users).toEqual([{ uin: 10001 }]);
expect(result.cookie).toBe(Buffer.from([0xDE, 0xAD]).toString('base64'));
expect(result.isLast).toBe(false);
});
it('returns the legacy-stub empty result when server returns ack-only', async () => {
const sender = makeSender();
const result = await GetEmojiLikes.invoke(sender, { groupId: 1, sequence: 1, emojiId: '76' });
expect(result).toEqual({ users: [], cookie: '', isLast: true });
});
it('encodes the request envelope with proper field types', async () => {
const sender = makeSender();
await GetEmojiLikes.invoke(sender, {
groupId: 12345, sequence: 99, emojiId: '128516', emojiType: 2, count: 20,
});
const [, reqBytes] = sender.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<Oidb0x9083Req>>(reqBytes);
expect(env.command).toBe(0x9083);
expect(env.subCommand).toBe(1);
expect(env.body?.groupId).toBe(12345n);
expect(env.body?.sequence).toBe(99n);
expect(env.body?.emojiId).toBe('128516');
expect(env.body?.emojiType).toBe(2);
expect(env.body?.count).toBe(20);
});
});
});
@@ -0,0 +1,110 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { OidbGroupReaction } from '@snowluma/proto-defs/oidb-actions/base';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { SetReaction } from '../../../src/oidb-services/reaction/set-reaction';
function makeSender() {
const defaultResp: SendPacketResult = {
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
responseData: Buffer.alloc(0),
};
return { sendRawPacket: vi.fn(async () => defaultResp) };
}
describe('SetReaction namespace', () => {
it('declares command = 0x9082', () => {
expect(SetReaction.command).toBe(0x9082);
});
it('resolveSubCommand: isSet=true → 1, isSet=false → 2', () => {
expect(SetReaction.resolveSubCommand({ groupId: 1, sequence: 1, code: 'x', isSet: true })).toBe(1);
expect(SetReaction.resolveSubCommand({ groupId: 1, sequence: 1, code: 'x', isSet: false })).toBe(2);
});
describe('serialize', () => {
it('produces type=1 for short QQ-face codes (≤3 chars)', () => {
const out = SetReaction.serialize({ groupId: 12345, sequence: 99, code: '76', isSet: true });
expect(out).toEqual({
groupUin: 12345, sequence: 99, code: '76', type: 1, field6: false, field7: false,
});
});
it('produces type=1 for exactly 3-character codes (boundary)', () => {
const out = SetReaction.serialize({ groupId: 1, sequence: 1, code: '999', isSet: true });
expect(out.type).toBe(1);
});
it('produces type=2 for codes longer than 3 chars (unicode codepoint)', () => {
const out = SetReaction.serialize({ groupId: 1, sequence: 1, code: '128516', isSet: false });
expect(out.type).toBe(2);
});
it('passes through groupId/sequence/code verbatim', () => {
const out = SetReaction.serialize({ groupId: 999, sequence: 42, code: 'abc', isSet: true });
expect(out.groupUin).toBe(999);
expect(out.sequence).toBe(42);
expect(out.code).toBe('abc');
});
it('always sets field6/field7 to false (deferred behaviour)', () => {
const out = SetReaction.serialize({ groupId: 1, sequence: 1, code: 'x', isSet: true });
expect(out.field6).toBe(false);
expect(out.field7).toBe(false);
});
});
describe('deserialize', () => {
it('always returns void regardless of body content', () => {
expect(SetReaction.deserialize({})).toBeUndefined();
});
});
describe('encode / decode round trip', () => {
it('encode preserves groupUin/sequence/code/type in the envelope body', () => {
const env: OidbBase<OidbGroupReaction> = {
command: 0x9082, subCommand: 1,
body: { groupUin: 12345, sequence: 99, code: '76', type: 1 } as OidbGroupReaction,
};
const bytes = SetReaction.encode(env);
const decoded = SetReaction.decode(bytes);
expect(decoded.command).toBe(0x9082);
expect(decoded.subCommand).toBe(1);
});
});
describe('invoke (e2e via mock sender)', () => {
it('routes to OidbSvcTrpcTcp.0x9082_1 when isSet=true', async () => {
const sender = makeSender();
await SetReaction.invoke(sender, { groupId: 12345, sequence: 99, code: '76', isSet: true });
expect(sender.sendRawPacket).toHaveBeenCalledOnce();
expect(sender.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x9082_1');
});
it('routes to OidbSvcTrpcTcp.0x9082_2 when isSet=false', async () => {
const sender = makeSender();
await SetReaction.invoke(sender, { groupId: 12345, sequence: 99, code: '76', isSet: false });
expect(sender.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x9082_2');
});
it('packages the serialized body into the OIDB envelope wire', async () => {
const sender = makeSender();
await SetReaction.invoke(sender, { groupId: 12345, sequence: 99, code: '128516', isSet: true });
const [, bytes] = sender.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbGroupReaction>>(bytes);
expect(env.command).toBe(0x9082);
expect(env.subCommand).toBe(1);
expect(env.body).toMatchObject({
groupUin: 12345, sequence: 99, code: '128516', type: 2,
});
});
it('resolves to undefined (void)', async () => {
const sender = makeSender();
const result = await SetReaction.invoke(sender, { groupId: 1, sequence: 1, code: 'x', isSet: true });
expect(result).toBeUndefined();
});
});
});
+6 -8
View File
@@ -1,18 +1,16 @@
// Vitest config — only used by `pnpm bench` to drive the perf
// micro-benchmarks under `bench/`. There are no `*.test.ts` files in
// this package (bridge tests live in @snowluma/core's test suite by
// historical accident); if/when they migrate over, point
// `test.include` at them here.
// Vitest config — drives both `pnpm bench` and `pnpm test`.
// Tests live under `tests/`, benchmarks under `bench/`.
import protobufVitePlugin from '@snowluma/proton/vite';
import { defineConfig } from 'vitest/config';
export default defineConfig({
// proton's vite plugin inlines `protobuf_encode<T>` / `protobuf_decode<T>`
// call sites at build time. Required for tinybench-driven benches to
// hit the production code path rather than proton's runtime-fallback
// (which throws unless a runtime-map JSON is loaded).
// call sites at build time. Required for both tests and benchmarks
// to hit the production code path rather than proton's runtime
// fallback (which throws unless a runtime-map JSON is loaded).
plugins: [protobufVitePlugin()],
test: {
include: ['tests/**/*.test.ts'],
benchmark: {
include: ['bench/**/*.bench.ts'],
},
+19 -103
View File
@@ -5,28 +5,28 @@
// commit 13). The recall+markRead halves of `group-message.ts` were
// already absorbed into `MessageApi` back in commit 1.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { toHexUpper } from '@snowluma/common/hex';
import { createLogger } from '@snowluma/common/logger';
import { protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
Oidb0x9083Req,
Oidb0x9083Resp,
Oidb0x9084Req,
Oidb0x9084Resp,
OidbEssence,
OidbGroupReaction,
OidbLike,
OidbPoke,
} from '@snowluma/proto-defs/oidb-actions/base';
import type { BridgeContext } from '../bridge-context';
import type { Bridge } from '../bridge';
import { makeOidbEnvelope, runOidb } from '@snowluma/bridge/bridge-oidb';
// Vertical-slice migration: reaction-family OIDB calls now live as
// self-contained namespaces under @snowluma/bridge/oidb-services. The
// facade methods on this class are thin forwarders (1-line bodies) to
// preserve `bridge.apis.interaction.X()` ergonomics for callers that
// haven't migrated yet. The other (non-reaction) cmds still inline the
// envelope+encode+runOidb dance — they'll move in follow-up PRs.
import { SetReaction } from '@snowluma/bridge/oidb-services/reaction/set-reaction';
import { FetchReactionSummary } from '@snowluma/bridge/oidb-services/reaction/fetch-reaction-summary';
import { GetEmojiLikes } from '@snowluma/bridge/oidb-services/reaction/get-emoji-likes';
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
const log = createLogger('Interaction');
export class InteractionApi {
constructor(private readonly ctx: BridgeContext) {}
@@ -47,20 +47,8 @@ export class InteractionApi {
await runOidb(bridge, 'OidbSvcTrpcTcp.0x7e5_104', protobuf_encode<OidbBase<OidbLike>>(env));
}
async setReaction(groupId: number, sequence: number, code: string, isSet: boolean): Promise<void> {
const bridge = asBridge(this.ctx);
const subCmd = isSet ? 1 : 2;
const cmd = isSet ? 'OidbSvcTrpcTcp.0x9082_1' : 'OidbSvcTrpcTcp.0x9082_2';
// Same heuristic Lagrange.Core V2 uses (`GroupAddReactionEvent.IsEmoji`):
// QQ face ids are 1–3 digits ("76") → type=1, unicode codepoints are
// longer ("128516") → type=2. Server reads the type at field 5; sending
// it at the wrong field number triggers
// "invalid ReqBody.EmojiType: value must be greater than 0".
const type = code.length > 3 ? 2 : 1;
const env = makeOidbEnvelope<OidbGroupReaction>(0x9082, subCmd, {
groupUin: groupId, sequence, code, type, field6: false, field7: false,
});
await runOidb(bridge, cmd, protobuf_encode<OidbBase<OidbGroupReaction>>(env));
setReaction(groupId: number, sequence: number, code: string, isSet: boolean): Promise<void> {
return SetReaction.invoke(this.ctx, { groupId, sequence, code, isSet });
}
async setEssence(groupId: number, sequence: number, random: number, enable: boolean): Promise<void> {
@@ -79,56 +67,14 @@ export class InteractionApi {
count = 10,
cookie = '',
): Promise<{ users: Array<{ uin: number }>; cookie: string; isLast: boolean }> {
const bridge = asBridge(this.ctx);
const req: any = {
groupId: BigInt(groupId),
// sequence is uint_64 on the wire (matches LagrangeV2's
// SetGroupReactionRequest.Sequence:ulong). Caller still passes
// a JS number — bigint conversion lives here.
sequence: BigInt(sequence),
emojiType,
emojiId,
cookie: cookie ? Buffer.from(cookie, 'base64') : new Uint8Array(0),
field7: 0,
count,
field12: 1,
};
// Two rounds of wire-level probing against macOS NTQQ confirmed:
// - 0x9083_1 returns a 4-byte ack `18 01 20 01` (no user list)
// - 0x9084_1 returns a per-emoji reaction *summary* (emoji_id +
// count + last-reaction timestamp), no user IDs — see
// `fetchReactionSummary` below
// - 0x9082_3..5, 0x9083_0/2/3, 0x9084_2..5, 0x9085_1/2, 0x9087_1
// all reject with "no privilege": the cmds exist but aren't in
// the NTQQ client's capability bitmap, so the server blocks
// anything not registered at login. NTQQ's own
// `getMsgEmojiLikesList` uses a wrapper-internal cache, not SSO.
// So this OIDB path can never surface the user list. The real
// implementation lives in `ReactionStore` on the OneBot side, fed
// from `GroupMsgEmojiLikeEvent` push. This method is retained so
// legacy callers don't crash — they get an empty users array.
const env = makeOidbEnvelope<Oidb0x9083Req>(0x9083, 1, req);
const reqBytes = protobuf_encode<OidbBase<Oidb0x9083Req>>(env);
let respBytes: Uint8Array;
// Legacy stub: see `GetEmojiLikes` namespace comment for why this
// SSO path can never surface the user list. Real data lives in
// ReactionStore on the OneBot side.
try {
respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x9083_1', reqBytes);
} catch (e) {
log.debug(`getEmojiLikes 0x9083_1 threw: ${e instanceof Error ? e.message : String(e)}`);
return await GetEmojiLikes.invoke(this.ctx, { groupId, sequence, emojiId, emojiType, count, cookie });
} catch {
return { users: [], cookie: '', isLast: true };
}
const resp = protobuf_decode<OidbBase<Oidb0x9083Resp>>(respBytes).body;
const users: Array<{ uin: number }> = (resp?.inner?.userInfo ?? [])
.map(u => ({ uin: Number(u?.uin ?? 0) }))
.filter(u => u.uin > 0);
const respCookie = resp?.cookie ? Buffer.from(resp.cookie).toString('base64') : '';
if (users.length === 0) {
log.debug(
`getEmojiLikes empty (expected — use ReactionStore instead): `
+ `group=${groupId} seq=${sequence} emojiId=${emojiId} `
+ `respLen=${respBytes.length}`,
);
}
return { users, cookie: respCookie, isLast: !respCookie };
}
/**
@@ -147,40 +93,10 @@ export class InteractionApi {
* Catalog entries (available emojis with no count/timestamp) are
* filtered out — callers want the "used" subset.
*/
async fetchReactionSummary(
fetchReactionSummary(
groupId: number,
sequence: number,
): Promise<Array<{ emojiId: string; emojiType: number; count: number; lastReactionTime: number }>> {
const bridge = asBridge(this.ctx);
const req: any = {
groupId: BigInt(groupId),
sequence: BigInt(sequence),
// Match the request shape the 0x9083_1 path sends so the server
// routes us identically. `count`/`emojiId`/`emojiType` are
// ignored by the summary handler but harmless.
emojiId: '',
emojiType: 0,
cookie: new Uint8Array(0),
count: 0,
field12: 1,
};
const env = makeOidbEnvelope<Oidb0x9084Req>(0x9084, 1, req);
const reqBytes = protobuf_encode<OidbBase<Oidb0x9084Req>>(env);
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x9084_1', reqBytes);
const resp = protobuf_decode<OidbBase<Oidb0x9084Resp>>(respBytes).body;
const out: Array<{ emojiId: string; emojiType: number; count: number; lastReactionTime: number }> = [];
for (const e of resp?.entries ?? []) {
const count = e.count ?? 0;
// Filter the catalog tail. "Used" entries always have count > 0
// and a lastReactionTime; catalog entries have neither.
if (count <= 0) continue;
out.push({
emojiId: e.emojiId ?? '',
emojiType: e.emojiType ?? 1,
count,
lastReactionTime: Number(e.lastReactionTime ?? 0n),
});
}
return out;
return FetchReactionSummary.invoke(this.ctx, { groupId, sequence });
}
}
@@ -56,11 +56,13 @@ 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).
const bridge = mockBridge();
const api = new InteractionApi(bridge as any);
await api.setReaction(12345, 99, '128516', true);
await api.setReaction(12345, 99, '128516', false);
const cmds = vi.mocked(oidb.runOidb).mock.calls.map(c => c[1]);
const cmds = bridge.sendRawPacket.mock.calls.map((c: any[]) => c[0]);
expect(cmds).toEqual(['OidbSvcTrpcTcp.0x9082_1', 'OidbSvcTrpcTcp.0x9082_2']);
});
@@ -75,14 +77,15 @@ describe('apis/interaction', () => {
it('getEmojiLikes decodes user list, base64-encodes cookie, and reports isLast', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<Oidb0x9083Resp>>({
bridge.sendRawPacket.mockResolvedValueOnce({
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
responseData: Buffer.from(protobuf_encode<OidbBase<Oidb0x9083Resp>>({
body: {
inner: { userInfo: [{ uin: 10001n }, { uin: 20002n }] },
cookie: new Uint8Array([0xCA, 0xFE]),
} as any,
}),
);
})),
});
const out = await new InteractionApi(bridge as any).getEmojiLikes(12345, 99, '128516');
expect(out.users).toEqual([{ uin: 10001 }, { uin: 20002 }]);
expect(out.cookie).toBe(Buffer.from([0xCA, 0xFE]).toString('base64'));
@@ -91,9 +94,10 @@ describe('apis/interaction', () => {
it('getEmojiLikes reports isLast=true when no cookie comes back', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<Oidb0x9083Resp>>({ body: {} }),
);
bridge.sendRawPacket.mockResolvedValueOnce({
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
responseData: Buffer.from(protobuf_encode<OidbBase<Oidb0x9083Resp>>({ body: {} })),
});
const out = await new InteractionApi(bridge as any).getEmojiLikes(12345, 99, '128516');
expect(out.users).toEqual([]);
expect(out.isLast).toBe(true);
+6
View File
@@ -23,6 +23,12 @@ export interface OidbBaseMeta {
reserved?: pb<12, int_32>;
}
/** Placeholder body for OIDB cmds whose successful response carries no
* payload (only the envelope's errorCode matters). Used as the
* TResp parameter in OidbCallSpec for fire-and-forget cmds — proton
* needs a real message interface here, not `void` or `never`. */
export interface OidbEmpty {}
// Oidb.0xFD4_1 Friend list
export interface OidbFriendProperty {
code?: pb<1, uint_32>;