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:
14 files changed
+1066
-122
No files matched your search
@@ -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');
|
||||
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
Reference in new issue
Block a user