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:
4 files changed
+131
-189
No files matched your search
@@ -6,9 +6,8 @@
|
|||||||
// doc metadata. The handler receives typed, already-validated params.
|
// doc metadata. The handler receives typed, already-validated params.
|
||||||
//
|
//
|
||||||
// Narrow seam (ADR-0006): `ApiHandler` keeps dispatch / try-catch / response
|
// Narrow seam (ADR-0006): `ApiHandler` keeps dispatch / try-catch / response
|
||||||
// wrapping. `defineAction(...).register(h, ctx)` ultimately registers a plain
|
// wrapping. `toHandler(ctx)` produces the plain `(params, sink?) => ApiResponse`
|
||||||
// `(params) => Promise<ApiResponse>` via `ApiHandler.registerAction`, exactly
|
// that ActionRegistry.bind installs into the sealed handler table.
|
||||||
// like the legacy style — so old and new actions coexist during migration.
|
|
||||||
//
|
//
|
||||||
// Zero runtime npm deps (ADR-0004). Type inference via `InferParams` — no
|
// Zero runtime npm deps (ADR-0004). Type inference via `InferParams` — no
|
||||||
// hand-written param interface. Param contract is intentionally a second
|
// hand-written param interface. Param contract is intentionally a second
|
||||||
@@ -20,7 +19,7 @@
|
|||||||
|
|
||||||
import { RETCODE, failedResponse } from './types';
|
import { RETCODE, failedResponse } from './types';
|
||||||
import type { ApiResponse, JsonObject, JsonValue } 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';
|
import { type StreamSink, NOOP_SINK } from './streaming';
|
||||||
|
|
||||||
// ─────────────────────────── result currency ───────────────────────────
|
// ─────────────────────────── result currency ───────────────────────────
|
||||||
@@ -444,11 +443,11 @@ export interface ActionDoc {
|
|||||||
inputSchema: JsonSchema;
|
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
|
* 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
|
* 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.
|
* 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. */
|
/** Canonical name first, followed by every executable alias. */
|
||||||
readonly names: readonly string[];
|
readonly names: readonly string[];
|
||||||
describe(): ActionDoc;
|
describe(): ActionDoc;
|
||||||
register(h: ApiHandler, ctx: ApiActionContext): void;
|
toHandler(ctx: ApiActionContext): Handler;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ActionSpec<S extends Spec> extends RegisteredActionSpec {
|
export interface ActionSpec<S extends Spec> extends RegisteredActionSpec {
|
||||||
@@ -468,7 +467,7 @@ export interface ActionSpec<S extends Spec> extends RegisteredActionSpec {
|
|||||||
readonly params: S;
|
readonly params: S;
|
||||||
/** Pure: coerce + validate + cross-field, no ctx, no I/O. The test surface. */
|
/** Pure: coerce + validate + cross-field, no ctx, no I/O. The test surface. */
|
||||||
parse(raw: JsonObject): CoerceResult<InferParams<S>>;
|
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;
|
toHandler(ctx: ApiActionContext): Handler;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -553,20 +552,16 @@ export function defineAction<S extends Spec>(def: ActionDef<S>): ActionSpec<S> {
|
|||||||
inputSchema,
|
inputSchema,
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
register: (h, ctx) => {
|
|
||||||
const handler = toHandler(ctx);
|
|
||||||
for (const name of names) h.registerAction(name, handler);
|
|
||||||
},
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─────────────────────────── defineStreamAction ───────────────────────────
|
// ─────────────────────────── defineStreamAction ───────────────────────────
|
||||||
// A Stream API action (#163): same param contract + doc machinery as
|
// A Stream API action (#163): same param contract + doc machinery as
|
||||||
// `defineAction`, but `run` additionally receives a `StreamSink` to push
|
// `defineAction`, but `run` additionally receives a `StreamSink` to push
|
||||||
// intermediate frames, and it registers via `registerStreamAction` so the
|
// intermediate frames. `toHandler` is sink-aware so ActionRegistry.bind
|
||||||
// network adapter streams its output. The handler's return value is still the
|
// installs the same shape as a normal Action. The handler's return value is
|
||||||
// terminal `ApiResponse` (the final frame). Reuses `defineAction` for
|
// still the terminal `ApiResponse` (the final frame). Reuses `defineAction`
|
||||||
// parse/describe so the two stay in lock-step.
|
// for parse/describe so the two stay in lock-step.
|
||||||
|
|
||||||
interface StreamActionDef<S extends Spec> {
|
interface StreamActionDef<S extends Spec> {
|
||||||
name: string | readonly [string, ...string[]];
|
name: string | readonly [string, ...string[]];
|
||||||
@@ -584,6 +579,7 @@ export interface StreamActionSpec<S extends Spec> extends RegisteredActionSpec {
|
|||||||
readonly names: readonly string[];
|
readonly names: readonly string[];
|
||||||
readonly params: S;
|
readonly params: S;
|
||||||
parse(raw: JsonObject): CoerceResult<InferParams<S>>;
|
parse(raw: JsonObject): CoerceResult<InferParams<S>>;
|
||||||
|
toHandler(ctx: ApiActionContext): Handler;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function defineStreamAction<S extends Spec>(def: StreamActionDef<S>): StreamActionSpec<S> {
|
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'),
|
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 {
|
return {
|
||||||
kind: 'stream',
|
kind: 'stream',
|
||||||
names: base.names,
|
names: base.names,
|
||||||
params: def.params,
|
params: def.params,
|
||||||
parse: base.parse,
|
parse: base.parse,
|
||||||
|
toHandler,
|
||||||
describe: () => ({ ...base.describe(), stream: true }),
|
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>>);
|
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);
|
|
||||||
}
|
|
||||||
@@ -7,7 +7,7 @@
|
|||||||
// of that same compiled value; neither is allowed to rebuild its own list.
|
// of that same compiled value; neither is allowed to rebuild its own list.
|
||||||
|
|
||||||
import type { ActionDoc, RegisteredActionSpec } from '../action-kit';
|
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 infoActions } from './info';
|
||||||
import { actions as messageActions } from './message';
|
import { actions as messageActions } from './message';
|
||||||
import { actions as friendActions } from './friend';
|
import { actions as friendActions } from './friend';
|
||||||
@@ -67,6 +67,14 @@ export interface CompiledRawName extends ActionNameClaimBase {
|
|||||||
|
|
||||||
export type CompiledActionName = CompiledDeclarativeName | CompiledRawName;
|
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 {
|
export interface CompiledActionRegistry {
|
||||||
/** Canonical declarative actions in authored group/action order. */
|
/** Canonical declarative actions in authored group/action order. */
|
||||||
readonly actions: readonly CompiledAction[];
|
readonly actions: readonly CompiledAction[];
|
||||||
@@ -76,7 +84,12 @@ export interface CompiledActionRegistry {
|
|||||||
readonly categories: readonly { category: string; count: number }[];
|
readonly categories: readonly { category: string; count: number }[];
|
||||||
readonly rawActions: readonly CompiledRawName[];
|
readonly rawActions: readonly CompiledRawName[];
|
||||||
resolve(name: string): CompiledActionName | undefined;
|
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 {
|
function validateSpecProjection(spec: RegisteredActionSpec, doc: ActionDoc): void {
|
||||||
@@ -179,12 +192,60 @@ export function compileActionRegistry(
|
|||||||
categories: Object.freeze(categories),
|
categories: Object.freeze(categories),
|
||||||
rawActions: Object.freeze(rawActions),
|
rawActions: Object.freeze(rawActions),
|
||||||
resolve: (name: string) => byName.get(name),
|
resolve: (name: string) => byName.get(name),
|
||||||
register: (h: ApiHandler, ctx: ApiActionContext) => {
|
bind: (
|
||||||
for (const action of actions) action.spec.register(h, ctx);
|
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. */
|
/** Every declarative action, grouped by domain category. Authored input. */
|
||||||
export const ACTION_GROUPS: readonly ActionGroup[] = [
|
export const ACTION_GROUPS: readonly ActionGroup[] = [
|
||||||
{ category: '信息', actions: infoActions },
|
{ category: '信息', actions: infoActions },
|
||||||
|
|||||||
@@ -96,7 +96,7 @@ export interface ApiActionContext {
|
|||||||
fetchPttText: (messageId: number) => Promise<{ text: string }>;
|
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 {
|
interface RegisteredHandler {
|
||||||
readonly handler: ActionHandler;
|
readonly handler: ActionHandler;
|
||||||
@@ -116,9 +116,7 @@ export type ActionObserver = (rec: ActionRecord) => void;
|
|||||||
export class ApiHandler {
|
export class ApiHandler {
|
||||||
/** Handler + dispatch kind live in one record so stream classification can
|
/** Handler + dispatch kind live in one record so stream classification can
|
||||||
* never outlive or drift from the handler it describes. */
|
* never outlive or drift from the handler it describes. */
|
||||||
private readonly handlers = new Map<string, RegisteredHandler>();
|
private readonly handlers: ReadonlyMap<string, RegisteredHandler>;
|
||||||
private readonly registry: CompiledActionRegistry;
|
|
||||||
private registrationOpen = true;
|
|
||||||
/** Sticky instance-lifecycle gate. A failed transport close may restore its
|
/** Sticky instance-lifecycle gate. A failed transport close may restore its
|
||||||
* own listener for retry, but it must never reopen execution against a
|
* own listener for retry, but it must never reopen execution against a
|
||||||
* retiring Bridge/store generation. */
|
* retiring Bridge/store generation. */
|
||||||
@@ -139,91 +137,27 @@ export class ApiHandler {
|
|||||||
uin?: number,
|
uin?: number,
|
||||||
registry: CompiledActionRegistry = ACTION_REGISTRY,
|
registry: CompiledActionRegistry = ACTION_REGISTRY,
|
||||||
) {
|
) {
|
||||||
this.registry = registry;
|
|
||||||
this.log = typeof uin === 'number' && uin > 0 ? moduleLog.child({ uin }) : moduleLog;
|
this.log = typeof uin === 'number' && uin > 0 ? moduleLog.child({ uin }) : moduleLog;
|
||||||
try {
|
const rawFactories: Record<string, (api: ApiHandler) => ActionHandler> = {};
|
||||||
registry.register(this, context);
|
for (const raw of registry.rawActions) {
|
||||||
|
if (raw.name !== HANDLE_QUICK_OPERATION_ACTION) {
|
||||||
// The one non-ActionSpec handler: `.handle_quick_operation` needs the
|
throw new Error(
|
||||||
// ApiHandler itself (to re-drive actions via executeQuickOperation), which
|
`Action registry has no factory for raw action canonical "${raw.canonical}" `
|
||||||
// ActionSpec.run's (params, ctx) signature can't supply — so it's the sole
|
+ `(name "${raw.name}", kind raw)`,
|
||||||
// raw registration, kept here rather than in an action file's footer.
|
);
|
||||||
this.registerRawAction(HANDLE_QUICK_OPERATION_ACTION, async (params) => {
|
}
|
||||||
|
rawFactories[raw.name] = (api) => async (params) => {
|
||||||
const opContext = params.context as JsonObject | undefined;
|
const opContext = params.context as JsonObject | undefined;
|
||||||
const operation = params.operation as Record<string, unknown> | 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');
|
const { executeQuickOperation } = await import('./network/quick-operation');
|
||||||
await executeQuickOperation(opContext, operation, this);
|
await executeQuickOperation(opContext, operation, api);
|
||||||
return okResponse();
|
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. */
|
/** Whether `action` answers with a multi-frame Stream API response. */
|
||||||
|
|||||||
@@ -114,20 +114,18 @@ describe('compiled production Action registry', () => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
it('registers the exact compiled executable-name/kind projection at runtime', () => {
|
it('binds the exact compiled executable-name/kind projection', () => {
|
||||||
const registered: Array<[string, 'normal' | 'stream']> = [];
|
const api = { handle: vi.fn() } as unknown as ApiHandler;
|
||||||
const fakeHandler = {
|
const bound = ACTION_REGISTRY.bind({} as ApiActionContext, api, {
|
||||||
registerAction: (name: string) => { registered.push([name, 'normal']); },
|
[HANDLE_QUICK_OPERATION_ACTION]: () => async () => okResponse(),
|
||||||
registerStreamAction: (name: string) => { registered.push([name, 'stream']); },
|
});
|
||||||
} as unknown as ApiHandler;
|
|
||||||
|
|
||||||
ACTION_REGISTRY.register(fakeHandler, {} as ApiActionContext);
|
expect([...bound.entries()].map(([name, entry]) => [name, entry.kind])).toEqual(
|
||||||
|
ACTION_REGISTRY.executableNames.map((entry) => [entry.name, entry.kind]),
|
||||||
expect(registered).toEqual(
|
|
||||||
ACTION_REGISTRY.executableNames
|
|
||||||
.filter((entry) => entry.kind !== 'raw')
|
|
||||||
.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 () => {
|
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', () => {
|
describe('ActionRegistry.bind', () => {
|
||||||
const handler = async () => okResponse();
|
|
||||||
|
|
||||||
function testRegistry(...specs: RegisteredActionSpec[]) {
|
function testRegistry(...specs: RegisteredActionSpec[]) {
|
||||||
return compileActionRegistry(groups(...specs), RAW_ACTION_RESERVATIONS);
|
return compileActionRegistry(groups(...specs), RAW_ACTION_RESERVATIONS);
|
||||||
}
|
}
|
||||||
|
|
||||||
function withRegistration(
|
it('binds only names declared by the injected complete registry', async () => {
|
||||||
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 () => {
|
|
||||||
const api = new ApiHandler(
|
const api = new ApiHandler(
|
||||||
{} as ApiActionContext,
|
{} as ApiActionContext,
|
||||||
undefined,
|
undefined,
|
||||||
@@ -174,7 +163,6 @@ describe('ApiHandler constructor-time registry transaction', () => {
|
|||||||
);
|
);
|
||||||
expect((await api.handle('__registry_normal__', {})).status).toBe('ok');
|
expect((await api.handle('__registry_normal__', {})).status).toBe('ok');
|
||||||
expect(api.isStreamAction('__registry_normal__')).toBe(false);
|
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);
|
expect((await api.handle('__rogue__', {})).retcode).toBe(1404);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -184,61 +172,31 @@ describe('ApiHandler constructor-time registry transaction', () => {
|
|||||||
undefined,
|
undefined,
|
||||||
testRegistry(stream('__registry_stream__')),
|
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_stream__')).toBe(true);
|
||||||
|
expect(api.isStreamAction('__registry_normal__')).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('rejects a spec that registers an undeclared executable name', () => {
|
it('rejects a missing raw factory for a reserved name', () => {
|
||||||
const base = normal('declared');
|
const registry = testRegistry(normal('declared'));
|
||||||
const malicious = withRegistration(base, (api) => api.registerAction('rogue', handler));
|
expect(() => registry.bind({} as ApiActionContext, {} as ApiHandler, {})).toThrow(
|
||||||
expect(() => new ApiHandler(
|
/raw factory missing.*handle_quick_operation.*kind raw/,
|
||||||
{} as ApiActionContext,
|
);
|
||||||
undefined,
|
|
||||||
testRegistry(malicious),
|
|
||||||
)).toThrow(/not declared.*canonical "rogue".*name "rogue".*kind normal/);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('rejects a spec whose registration kind disagrees with its compiled claim', () => {
|
it('rejects an unexpected raw factory', () => {
|
||||||
const base = normal('declared');
|
const registry = compileActionRegistry(groups(normal('declared')));
|
||||||
const malicious = withRegistration(base, (api) => api.registerStreamAction('declared', handler));
|
expect(() => registry.bind({} as ApiActionContext, {} as ApiHandler, {
|
||||||
expect(() => new ApiHandler(
|
extra: () => async () => okResponse(),
|
||||||
{} as ApiActionContext,
|
})).toThrow(/unexpected raw factory.*extra.*kind raw/);
|
||||||
undefined,
|
|
||||||
testRegistry(malicious),
|
|
||||||
)).toThrow(/kind mismatch.*canonical "declared".*registry kind normal, registration kind stream/);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('rejects duplicate constructor-time handler binding', () => {
|
it('constructs an injected registry that has no raw reservation', async () => {
|
||||||
const base = normal('declared');
|
const api = new ApiHandler(
|
||||||
const malicious = withRegistration(base, (api) => {
|
|
||||||
api.registerAction('declared', handler);
|
|
||||||
api.registerAction('declared', handler);
|
|
||||||
});
|
|
||||||
expect(() => new ApiHandler(
|
|
||||||
{} as ApiActionContext,
|
{} as ApiActionContext,
|
||||||
undefined,
|
undefined,
|
||||||
testRegistry(malicious),
|
compileActionRegistry(groups(normal('declared'))),
|
||||||
)).toThrow(/canonical "declared".*kind normal.*conflicts with.*canonical "declared".*kind normal/);
|
);
|
||||||
});
|
expect((await api.handle('declared', {})).status).toBe('ok');
|
||||||
|
expect((await api.handle(HANDLE_QUICK_OPERATION_ACTION, {})).retcode).toBe(1404);
|
||||||
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/);
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
Reference in new issue
Block a user