refactor(onebot): compile a sealed Action handler bind

The registry already froze names, kinds, and raw reservations, but
handlers were a second mutable map filled through registerAction.

bind(ctx, api, rawFactories) now returns the complete name-to-handler
table. Stream actions expose toHandler. ApiHandler only installs and
dispatches. The public register ports are gone.
This commit is contained in:
DrSmoothl committed 2026-08-16 21:30:10 +08:00
1 parent b1730d74cd
commit 30f0ae8571
4 files changed
+131 -189

No files matched your search

+19 -30
View File
@@ -6,9 +6,8 @@
// doc metadata. The handler receives typed, already-validated params.
//
// Narrow seam (ADR-0006): `ApiHandler` keeps dispatch / try-catch / response
// wrapping. `defineAction(...).register(h, ctx)` ultimately registers a plain
// `(params) => Promise<ApiResponse>` via `ApiHandler.registerAction`, exactly
// like the legacy style — so old and new actions coexist during migration.
// wrapping. `toHandler(ctx)` produces the plain `(params, sink?) => ApiResponse`
// that ActionRegistry.bind installs into the sealed handler table.
//
// Zero runtime npm deps (ADR-0004). Type inference via `InferParams` — no
// hand-written param interface. Param contract is intentionally a second
@@ -20,7 +19,7 @@
import { RETCODE, failedResponse } from './types';
import type { ApiResponse, JsonObject, JsonValue } from './types';
import type { ApiActionContext, ApiHandler } from './api-handler';
import type { ApiActionContext } from './api-handler';
import { type StreamSink, NOOP_SINK } from './streaming';
// ─────────────────────────── result currency ───────────────────────────
@@ -444,11 +443,11 @@ export interface ActionDoc {
inputSchema: JsonSchema;
}
type Handler = (params: JsonObject) => Promise<ApiResponse>;
type Handler = (params: JsonObject, sink?: StreamSink) => Promise<ApiResponse>;
/**
* The narrow shape both `ActionSpec` and `StreamActionSpec` share — enough to
* register a spec onto an `ApiHandler` and to collect its docs. The action
* bind a spec through ActionRegistry and to collect its docs. The action
* registry barrel (`actions/index.ts`) is typed against this so it can hold
* both kinds in one flat list without coupling to either concrete generic.
*/
@@ -459,7 +458,7 @@ export interface RegisteredActionSpec {
/** Canonical name first, followed by every executable alias. */
readonly names: readonly string[];
describe(): ActionDoc;
register(h: ApiHandler, ctx: ApiActionContext): void;
toHandler(ctx: ApiActionContext): Handler;
}
export interface ActionSpec<S extends Spec> extends RegisteredActionSpec {
@@ -468,7 +467,7 @@ export interface ActionSpec<S extends Spec> extends RegisteredActionSpec {
readonly params: S;
/** Pure: coerce + validate + cross-field, no ctx, no I/O. The test surface. */
parse(raw: JsonObject): CoerceResult<InferParams<S>>;
/** Bind ctx and produce the `(params) => ApiResponse` for `registerAction`. */
/** Bind ctx and produce the handler ActionRegistry.bind installs. */
toHandler(ctx: ApiActionContext): Handler;
}
@@ -553,20 +552,16 @@ export function defineAction<S extends Spec>(def: ActionDef<S>): ActionSpec<S> {
inputSchema,
};
},
register: (h, ctx) => {
const handler = toHandler(ctx);
for (const name of names) h.registerAction(name, handler);
},
};
}
// ─────────────────────────── defineStreamAction ───────────────────────────
// A Stream API action (#163): same param contract + doc machinery as
// `defineAction`, but `run` additionally receives a `StreamSink` to push
// intermediate frames, and it registers via `registerStreamAction` so the
// network adapter streams its output. The handler's return value is still the
// terminal `ApiResponse` (the final frame). Reuses `defineAction` for
// parse/describe so the two stay in lock-step.
// intermediate frames. `toHandler` is sink-aware so ActionRegistry.bind
// installs the same shape as a normal Action. The handler's return value is
// still the terminal `ApiResponse` (the final frame). Reuses `defineAction`
// for parse/describe so the two stay in lock-step.
interface StreamActionDef<S extends Spec> {
name: string | readonly [string, ...string[]];
@@ -584,6 +579,7 @@ export interface StreamActionSpec<S extends Spec> extends RegisteredActionSpec {
readonly names: readonly string[];
readonly params: S;
parse(raw: JsonObject): CoerceResult<InferParams<S>>;
toHandler(ctx: ApiActionContext): Handler;
}
export function defineStreamAction<S extends Spec>(def: StreamActionDef<S>): StreamActionSpec<S> {
@@ -600,20 +596,19 @@ export function defineStreamAction<S extends Spec>(def: StreamActionDef<S>): Str
run: () => failedResponse(RETCODE.INTERNAL_ERROR, 'stream action dispatched without a sink'),
});
const toHandler = (ctx: ApiActionContext): Handler => async (params, sink) => {
const r = base.parse(params);
if (!r.ok) return failedResponse(RETCODE.BAD_REQUEST, wording(r));
return def.run(r.value, ctx, params, sink ?? NOOP_SINK);
};
return {
kind: 'stream',
names: base.names,
params: def.params,
parse: base.parse,
toHandler,
describe: () => ({ ...base.describe(), stream: true }),
register: (h, ctx) => {
const handler = async (params: JsonObject, sink?: StreamSink): Promise<ApiResponse> => {
const r = base.parse(params);
if (!r.ok) return failedResponse(RETCODE.BAD_REQUEST, wording(r));
return def.run(r.value, ctx, params, sink ?? NOOP_SINK);
};
for (const name of base.names) h.registerStreamAction(name, handler);
},
};
}
@@ -656,10 +651,4 @@ export function groupUserAction<S extends Spec>(
return defineAction({ ...def, params } as unknown as ActionDef<WithGroupUser<S>>);
}
// ─────────────────────────── registration helper ───────────────────────────
/** Register many specs onto an ApiHandler. Coexists with legacy
* `h.registerAction(name, fn)` in the same `register(h, ctx)`. */
export function registerActions(h: ApiHandler, ctx: ApiActionContext, specs: ReadonlyArray<RegisteredActionSpec>): void {
for (const spec of specs) spec.register(h, ctx);
}
+66 -5
View File
@@ -7,7 +7,7 @@
// of that same compiled value; neither is allowed to rebuild its own list.
import type { ActionDoc, RegisteredActionSpec } from '../action-kit';
import type { ApiActionContext, ApiHandler } from '../api-handler';
import type { ActionHandler, ApiActionContext, ApiHandler } from '../api-handler';
import { actions as infoActions } from './info';
import { actions as messageActions } from './message';
import { actions as friendActions } from './friend';
@@ -67,6 +67,14 @@ export interface CompiledRawName extends ActionNameClaimBase {
export type CompiledActionName = CompiledDeclarativeName | CompiledRawName;
export type RawActionFactory = (api: ApiHandler) => ActionHandler;
export interface BoundAction {
readonly handler: ActionHandler;
readonly canonical: string;
readonly kind: CompiledActionKind;
}
export interface CompiledActionRegistry {
/** Canonical declarative actions in authored group/action order. */
readonly actions: readonly CompiledAction[];
@@ -76,7 +84,12 @@ export interface CompiledActionRegistry {
readonly categories: readonly { category: string; count: number }[];
readonly rawActions: readonly CompiledRawName[];
resolve(name: string): CompiledActionName | undefined;
register(h: ApiHandler, ctx: ApiActionContext): void;
/** Produce the sealed executable table. Extra or missing raw factories fail. */
bind(
ctx: ApiActionContext,
api: ApiHandler,
rawFactories: Readonly<Record<string, RawActionFactory>>,
): ReadonlyMap<string, BoundAction>;
}
function validateSpecProjection(spec: RegisteredActionSpec, doc: ActionDoc): void {
@@ -179,12 +192,60 @@ export function compileActionRegistry(
categories: Object.freeze(categories),
rawActions: Object.freeze(rawActions),
resolve: (name: string) => byName.get(name),
register: (h: ApiHandler, ctx: ApiActionContext) => {
for (const action of actions) action.spec.register(h, ctx);
},
bind: (
ctx: ApiActionContext,
api: ApiHandler,
rawFactories: Readonly<Record<string, RawActionFactory>>,
) => bindActionRegistry(executableNames, ctx, api, rawFactories),
});
}
function bindActionRegistry(
executableNames: readonly CompiledActionName[],
ctx: ApiActionContext,
api: ApiHandler,
rawFactories: Readonly<Record<string, RawActionFactory>>,
): ReadonlyMap<string, BoundAction> {
const factoryNames = new Set(Object.keys(rawFactories));
const handlers = new Map<string, BoundAction>();
for (const claim of executableNames) {
if (claim.kind === 'raw') {
const factory = rawFactories[claim.name];
if (!factory) {
throw new Error(
`Action registry raw factory missing: canonical "${claim.canonical}" `
+ `(name "${claim.name}", kind raw)`,
);
}
factoryNames.delete(claim.name);
handlers.set(claim.name, Object.freeze({
handler: factory(api),
canonical: claim.canonical,
kind: 'raw',
}));
continue;
}
const handler = claim.action.spec.toHandler(ctx);
handlers.set(claim.name, Object.freeze({
handler,
canonical: claim.canonical,
kind: claim.kind,
}));
}
if (factoryNames.size > 0) {
const extra = [...factoryNames][0]!;
throw new Error(
`Action registry unexpected raw factory: canonical "${extra}" `
+ `(name "${extra}", kind raw)`,
);
}
return handlers;
}
/** Every declarative action, grouped by domain category. Authored input. */
export const ACTION_GROUPS: readonly ActionGroup[] = [
{ category: '信息', actions: infoActions },
+17 -83
View File
@@ -96,7 +96,7 @@ export interface ApiActionContext {
fetchPttText: (messageId: number) => Promise<{ text: string }>;
}
type ActionHandler = (params: JsonObject, sink?: StreamSink) => Promise<import('./types').ApiResponse>;
export type ActionHandler = (params: JsonObject, sink?: StreamSink) => Promise<import('./types').ApiResponse>;
interface RegisteredHandler {
readonly handler: ActionHandler;
@@ -116,9 +116,7 @@ export type ActionObserver = (rec: ActionRecord) => void;
export class ApiHandler {
/** Handler + dispatch kind live in one record so stream classification can
* never outlive or drift from the handler it describes. */
private readonly handlers = new Map<string, RegisteredHandler>();
private readonly registry: CompiledActionRegistry;
private registrationOpen = true;
private readonly handlers: ReadonlyMap<string, RegisteredHandler>;
/** Sticky instance-lifecycle gate. A failed transport close may restore its
* own listener for retry, but it must never reopen execution against a
* retiring Bridge/store generation. */
@@ -139,91 +137,27 @@ export class ApiHandler {
uin?: number,
registry: CompiledActionRegistry = ACTION_REGISTRY,
) {
this.registry = registry;
this.log = typeof uin === 'number' && uin > 0 ? moduleLog.child({ uin }) : moduleLog;
try {
registry.register(this, context);
// The one non-ActionSpec handler: `.handle_quick_operation` needs the
// ApiHandler itself (to re-drive actions via executeQuickOperation), which
// ActionSpec.run's (params, ctx) signature can't supply — so it's the sole
// raw registration, kept here rather than in an action file's footer.
this.registerRawAction(HANDLE_QUICK_OPERATION_ACTION, async (params) => {
const rawFactories: Record<string, (api: ApiHandler) => ActionHandler> = {};
for (const raw of registry.rawActions) {
if (raw.name !== HANDLE_QUICK_OPERATION_ACTION) {
throw new Error(
`Action registry has no factory for raw action canonical "${raw.canonical}" `
+ `(name "${raw.name}", kind raw)`,
);
}
rawFactories[raw.name] = (api) => async (params) => {
const opContext = params.context as JsonObject | undefined;
const operation = params.operation as Record<string, unknown> | undefined;
if (!opContext || !operation) return failedResponse(RETCODE.BAD_REQUEST, 'context and operation are required');
if (!opContext || !operation) {
return failedResponse(RETCODE.BAD_REQUEST, 'context and operation are required');
}
const { executeQuickOperation } = await import('./network/quick-operation');
await executeQuickOperation(opContext, operation, this);
await executeQuickOperation(opContext, operation, api);
return okResponse();
});
this.assertRegistryFullyBound();
} finally {
// registerAction/registerStreamAction are the constructor-time port used
// by ActionSpec. Once construction finishes (successfully or not), the
// runtime namespace is immutable and cannot bypass the compiled registry.
this.registrationOpen = false;
}
}
registerAction(action: string, handler: ActionHandler): void {
this.registerHandler(action, handler, 'normal');
}
/** Register a Stream API action — dispatched exactly like a normal action,
* but flagged so adapters stream its frames (the handler receives a sink). */
registerStreamAction(action: string, handler: ActionHandler): void {
this.registerHandler(action, handler, 'stream');
}
private registerRawAction(action: string, handler: ActionHandler): void {
this.registerHandler(action, handler, 'raw');
}
private registerHandler(action: string, handler: ActionHandler, kind: CompiledActionKind): void {
if (!this.registrationOpen) {
throw new Error(
`Action registry is sealed; cannot register canonical "${action}" (name "${action}", kind ${kind})`,
);
}
const claim = this.registry.resolve(action);
if (!claim) {
throw new Error(
`Action registration is not declared by the compiled registry: `
+ `canonical "${action}" (name "${action}", kind ${kind})`,
);
}
const canonical = claim.canonical;
const existing = this.handlers.get(action);
if (existing) {
throw new Error(
`Action handler conflict for executable name "${action}": `
+ `canonical "${existing.canonical}" (name "${action}", kind ${existing.kind}) conflicts with `
+ `canonical "${canonical}" (name "${action}", kind ${kind})`,
);
}
if (claim.kind !== kind) {
throw new Error(
`Action handler kind mismatch for canonical "${canonical}" (name "${action}"): `
+ `registry kind ${claim.kind}, registration kind ${kind}`,
);
}
this.handlers.set(action, { handler, canonical, kind });
}
private assertRegistryFullyBound(): void {
for (const claim of this.registry.executableNames) {
if (this.handlers.has(claim.name)) continue;
throw new Error(
`Action registry claim has no handler: canonical "${claim.canonical}" `
+ `(name "${claim.name}", kind ${claim.kind})`,
);
}
if (this.handlers.size !== this.registry.executableNames.length) {
throw new Error(
`Action registry binding count mismatch: ${this.handlers.size} handlers for `
+ `${this.registry.executableNames.length} executable names`,
);
};
}
this.handlers = registry.bind(context, this, rawFactories);
}
/** Whether `action` answers with a multi-frame Stream API response. */
+29 -71
View File
@@ -114,20 +114,18 @@ describe('compiled production Action registry', () => {
}
});
it('registers the exact compiled executable-name/kind projection at runtime', () => {
const registered: Array<[string, 'normal' | 'stream']> = [];
const fakeHandler = {
registerAction: (name: string) => { registered.push([name, 'normal']); },
registerStreamAction: (name: string) => { registered.push([name, 'stream']); },
} as unknown as ApiHandler;
it('binds the exact compiled executable-name/kind projection', () => {
const api = { handle: vi.fn() } as unknown as ApiHandler;
const bound = ACTION_REGISTRY.bind({} as ApiActionContext, api, {
[HANDLE_QUICK_OPERATION_ACTION]: () => async () => okResponse(),
});
ACTION_REGISTRY.register(fakeHandler, {} as ApiActionContext);
expect(registered).toEqual(
ACTION_REGISTRY.executableNames
.filter((entry) => entry.kind !== 'raw')
.map((entry) => [entry.name, entry.kind]),
expect([...bound.entries()].map(([name, entry]) => [name, entry.kind])).toEqual(
ACTION_REGISTRY.executableNames.map((entry) => [entry.name, entry.kind]),
);
for (const executable of ACTION_REGISTRY.executableNames) {
expect(bound.get(executable.name)?.canonical).toBe(executable.canonical);
}
});
it('validates and forwards get_group_system_msg filters', async () => {
@@ -152,21 +150,12 @@ describe('compiled production Action registry', () => {
});
});
describe('ApiHandler constructor-time registry transaction', () => {
const handler = async () => okResponse();
describe('ActionRegistry.bind', () => {
function testRegistry(...specs: RegisteredActionSpec[]) {
return compileActionRegistry(groups(...specs), RAW_ACTION_RESERVATIONS);
}
function withRegistration(
base: RegisteredActionSpec,
register: RegisteredActionSpec['register'],
): RegisteredActionSpec {
return { kind: base.kind, names: base.names, describe: base.describe, register };
}
it('binds only names declared by the injected complete registry, then seals', async () => {
it('binds only names declared by the injected complete registry', async () => {
const api = new ApiHandler(
{} as ApiActionContext,
undefined,
@@ -174,7 +163,6 @@ describe('ApiHandler constructor-time registry transaction', () => {
);
expect((await api.handle('__registry_normal__', {})).status).toBe('ok');
expect(api.isStreamAction('__registry_normal__')).toBe(false);
expect(() => api.registerAction('__rogue__', handler)).toThrow(/Action registry is sealed/);
expect((await api.handle('__rogue__', {})).retcode).toBe(1404);
});
@@ -184,61 +172,31 @@ describe('ApiHandler constructor-time registry transaction', () => {
undefined,
testRegistry(stream('__registry_stream__')),
);
expect(() => api.registerAction('__registry_stream__', handler)).toThrow(
/Action registry is sealed/,
);
expect(api.isStreamAction('__registry_stream__')).toBe(true);
expect(api.isStreamAction('__registry_normal__')).toBe(false);
});
it('rejects a spec that registers an undeclared executable name', () => {
const base = normal('declared');
const malicious = withRegistration(base, (api) => api.registerAction('rogue', handler));
expect(() => new ApiHandler(
{} as ApiActionContext,
undefined,
testRegistry(malicious),
)).toThrow(/not declared.*canonical "rogue".*name "rogue".*kind normal/);
it('rejects a missing raw factory for a reserved name', () => {
const registry = testRegistry(normal('declared'));
expect(() => registry.bind({} as ApiActionContext, {} as ApiHandler, {})).toThrow(
/raw factory missing.*handle_quick_operation.*kind raw/,
);
});
it('rejects a spec whose registration kind disagrees with its compiled claim', () => {
const base = normal('declared');
const malicious = withRegistration(base, (api) => api.registerStreamAction('declared', handler));
expect(() => new ApiHandler(
{} as ApiActionContext,
undefined,
testRegistry(malicious),
)).toThrow(/kind mismatch.*canonical "declared".*registry kind normal, registration kind stream/);
it('rejects an unexpected raw factory', () => {
const registry = compileActionRegistry(groups(normal('declared')));
expect(() => registry.bind({} as ApiActionContext, {} as ApiHandler, {
extra: () => async () => okResponse(),
})).toThrow(/unexpected raw factory.*extra.*kind raw/);
});
it('rejects duplicate constructor-time handler binding', () => {
const base = normal('declared');
const malicious = withRegistration(base, (api) => {
api.registerAction('declared', handler);
api.registerAction('declared', handler);
});
expect(() => new ApiHandler(
it('constructs an injected registry that has no raw reservation', async () => {
const api = new ApiHandler(
{} as ApiActionContext,
undefined,
testRegistry(malicious),
)).toThrow(/canonical "declared".*kind normal.*conflicts with.*canonical "declared".*kind normal/);
});
it('rejects a compiled claim that did not bind a handler', () => {
const base = normal('declared');
const malicious = withRegistration(base, () => {});
expect(() => new ApiHandler(
{} as ApiActionContext,
undefined,
testRegistry(malicious),
)).toThrow(/claim has no handler.*canonical "declared".*name "declared".*kind normal/);
});
it('requires the raw quick-operation reservation in an injected registry', () => {
const incomplete = compileActionRegistry(groups(normal('declared')));
expect(() => new ApiHandler(
{} as ApiActionContext,
undefined,
incomplete,
)).toThrow(/not declared.*handle_quick_operation.*kind raw/);
compileActionRegistry(groups(normal('declared'))),
);
expect((await api.handle('declared', {})).status).toBe('ok');
expect((await api.handle(HANDLE_QUICK_OPERATION_ACTION, {})).retcode).toBe(1404);
});
});