Files
SnowLuma/packages/bridge/src/bridge-oidb.ts
T
DrSmoothl 0238bcb280 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.)
2026-05-22 23:15:20 +08:00

70 lines
2.3 KiB
TypeScript

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';
/**
* Build the OidbBase<T>-shaped TS value. Pure helper, no protobuf
* encoding happens here — pair with `encodeOidbEnv<T>` to produce the
* wire bytes.
*
* The `isUid` flag sets the envelope `reserved` field to 1; despite the
* name (kept for back-compat with the legacy API), `reserved = 1`
* empirically signals the UIN-form variant of an OIDB call. Omit
* (default false) for genuinely UID-keyed calls.
*/
export function makeOidbEnvelope<T>(
oidbCmd: number,
subCmd: number,
body: T,
isUid: boolean = false,
): OidbBase<T> {
return {
command: oidbCmd,
subCommand: subCmd,
errorCode: 0,
body,
errorMsg: '',
reserved: isUid ? 1 : 0,
};
}
/**
* Issue one OIDB request and return the raw response bytes.
*
* Typical usage:
* const env = makeOidbEnvelope<MyReq>(0x1253, 1, value);
* const buf = await runOidb(bridge, cmd, encodeOidbEnv<MyReq>(env));
* const resp = decodeOidbEnv<MyResp>(buf).body;
*
* Fire-and-check (no body decode):
* await runOidb(bridge, cmd, encodeOidbEnv<MyReq>(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<Uint8Array> {
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<OidbBaseMeta>(bytes);
const code = meta?.errorCode;
if (code && code !== 0) {
throw new Error(`OIDB error ${code}: ${meta?.errorMsg ?? ''}`);
}
}
return bytes;
}