diff --git a/packages/onebot/src/action-kit.ts b/packages/onebot/src/action-kit.ts index 1805a2bd..5d1dea7c 100644 --- a/packages/onebot/src/action-kit.ts +++ b/packages/onebot/src/action-kit.ts @@ -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` 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; +type Handler = (params: JsonObject, sink?: StreamSink) => Promise; /** * 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 extends RegisteredActionSpec { @@ -468,7 +467,7 @@ export interface ActionSpec extends RegisteredActionSpec { readonly params: S; /** Pure: coerce + validate + cross-field, no ctx, no I/O. The test surface. */ parse(raw: JsonObject): CoerceResult>; - /** 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(def: ActionDef): ActionSpec { 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 { name: string | readonly [string, ...string[]]; @@ -584,6 +579,7 @@ export interface StreamActionSpec extends RegisteredActionSpec { readonly names: readonly string[]; readonly params: S; parse(raw: JsonObject): CoerceResult>; + toHandler(ctx: ApiActionContext): Handler; } export function defineStreamAction(def: StreamActionDef): StreamActionSpec { @@ -600,20 +596,19 @@ export function defineStreamAction(def: StreamActionDef): 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 => { - 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( return defineAction({ ...def, params } as unknown as ActionDef>); } -// ─────────────────────────── 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): void { - for (const spec of specs) spec.register(h, ctx); -} diff --git a/packages/onebot/src/actions/index.ts b/packages/onebot/src/actions/index.ts index ef74f9a6..18ee07d3 100644 --- a/packages/onebot/src/actions/index.ts +++ b/packages/onebot/src/actions/index.ts @@ -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>, + ): ReadonlyMap; } 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>, + ) => bindActionRegistry(executableNames, ctx, api, rawFactories), }); } +function bindActionRegistry( + executableNames: readonly CompiledActionName[], + ctx: ApiActionContext, + api: ApiHandler, + rawFactories: Readonly>, +): ReadonlyMap { + const factoryNames = new Set(Object.keys(rawFactories)); + const handlers = new Map(); + + 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 }, diff --git a/packages/onebot/src/api-handler.ts b/packages/onebot/src/api-handler.ts index 010d1176..c8d39a44 100644 --- a/packages/onebot/src/api-handler.ts +++ b/packages/onebot/src/api-handler.ts @@ -96,7 +96,7 @@ export interface ApiActionContext { fetchPttText: (messageId: number) => Promise<{ text: string }>; } -type ActionHandler = (params: JsonObject, sink?: StreamSink) => Promise; +export type ActionHandler = (params: JsonObject, sink?: StreamSink) => Promise; 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(); - private readonly registry: CompiledActionRegistry; - private registrationOpen = true; + private readonly handlers: ReadonlyMap; /** 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 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 | 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. */ diff --git a/packages/onebot/tests/action-registry.test.ts b/packages/onebot/tests/action-registry.test.ts index 3483f6ff..5f9295ab 100644 --- a/packages/onebot/tests/action-registry.test.ts +++ b/packages/onebot/tests/action-registry.test.ts @@ -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); }); });