refactor(onebot): compile and seal the action registry
Compile canonical names, aliases, stream kinds, documentation, and raw reservations into one immutable registry. Reject duplicate, undeclared, mismatched, or late handler registration before requests can be dispatched.
This commit is contained in:
9 files changed
+613
-104
No files matched your search
@@ -0,0 +1,223 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { defineAction, defineStreamAction, type RegisteredActionSpec } from '../src/action-kit';
|
||||
import { ApiHandler, type ApiActionContext } from '../src/api-handler';
|
||||
import {
|
||||
ACTION_REGISTRY,
|
||||
HANDLE_QUICK_OPERATION_ACTION,
|
||||
RAW_ACTION_RESERVATIONS,
|
||||
compileActionRegistry,
|
||||
type ActionGroup,
|
||||
type RawActionReservation,
|
||||
} from '../src/actions';
|
||||
import { collectActionDocs } from '../src/action-docs';
|
||||
import { okResponse } from '../src/types';
|
||||
|
||||
type ActionNames = string | readonly [string, ...string[]];
|
||||
|
||||
function normal(name: ActionNames): RegisteredActionSpec {
|
||||
return defineAction({ name, params: {}, run: () => okResponse() });
|
||||
}
|
||||
|
||||
function stream(name: ActionNames): RegisteredActionSpec {
|
||||
return defineStreamAction({ name, params: {}, run: () => okResponse() });
|
||||
}
|
||||
|
||||
function groups(...actions: RegisteredActionSpec[]): readonly ActionGroup[] {
|
||||
return [{ category: 'test', actions }];
|
||||
}
|
||||
|
||||
function conflict(
|
||||
actionGroups: readonly ActionGroup[],
|
||||
raw: readonly RawActionReservation[] = [],
|
||||
): string {
|
||||
try {
|
||||
compileActionRegistry(actionGroups, raw);
|
||||
} catch (error) {
|
||||
if (error instanceof Error) return error.message;
|
||||
throw error;
|
||||
}
|
||||
throw new Error('expected registry compilation to fail');
|
||||
}
|
||||
|
||||
describe('compileActionRegistry namespace conflicts', () => {
|
||||
it('rejects canonical ↔ canonical', () => {
|
||||
const message = conflict(groups(normal('shared'), normal('shared')));
|
||||
expect(message).toContain('executable name "shared"');
|
||||
expect(message).toContain('canonical "shared" (name "shared", kind normal, role canonical)');
|
||||
});
|
||||
|
||||
it.each([
|
||||
['canonical first', [normal('shared'), normal(['owner', 'shared'])]],
|
||||
['alias first', [normal(['owner', 'shared']), normal('shared')]],
|
||||
] as const)('rejects canonical ↔ alias (%s)', (_label, specs) => {
|
||||
const message = conflict(groups(...specs));
|
||||
expect(message).toContain('canonical "shared" (name "shared", kind normal, role canonical)');
|
||||
expect(message).toContain('canonical "owner" (name "shared", kind normal, role alias)');
|
||||
});
|
||||
|
||||
it('rejects alias ↔ alias', () => {
|
||||
const message = conflict(groups(normal(['first', 'shared']), normal(['second', 'shared'])));
|
||||
expect(message).toContain('canonical "first" (name "shared", kind normal, role alias)');
|
||||
expect(message).toContain('canonical "second" (name "shared", kind normal, role alias)');
|
||||
});
|
||||
|
||||
it('rejects normal ↔ stream and reports both kinds', () => {
|
||||
const message = conflict(groups(normal('shared'), stream('shared')));
|
||||
expect(message).toContain('canonical "shared" (name "shared", kind normal, role canonical)');
|
||||
expect(message).toContain('canonical "shared" (name "shared", kind stream, role canonical)');
|
||||
});
|
||||
|
||||
it.each([
|
||||
['canonical', normal(HANDLE_QUICK_OPERATION_ACTION), 'role canonical'],
|
||||
['alias', normal(['owner', HANDLE_QUICK_OPERATION_ACTION]), 'role alias'],
|
||||
] as const)('rejects a declarative %s colliding with a reserved raw action', (_label, spec, role) => {
|
||||
const message = conflict(groups(spec), [
|
||||
{ name: HANDLE_QUICK_OPERATION_ACTION, canonical: HANDLE_QUICK_OPERATION_ACTION },
|
||||
]);
|
||||
expect(message).toContain(`name "${HANDLE_QUICK_OPERATION_ACTION}"`);
|
||||
expect(message).toContain(`kind normal, ${role}`);
|
||||
expect(message).toContain('kind raw, role raw');
|
||||
});
|
||||
|
||||
it('rejects duplicate raw reservations', () => {
|
||||
const message = conflict([], [
|
||||
{ name: 'raw', canonical: 'first-raw' },
|
||||
{ name: 'raw', canonical: 'second-raw' },
|
||||
]);
|
||||
expect(message).toContain('canonical "first-raw" (name "raw", kind raw, role raw)');
|
||||
expect(message).toContain('canonical "second-raw" (name "raw", kind raw, role raw)');
|
||||
});
|
||||
});
|
||||
|
||||
describe('compiled production Action registry', () => {
|
||||
it('preserves all 179 canonical Action docs', () => {
|
||||
expect(ACTION_REGISTRY.actions).toHaveLength(179);
|
||||
expect(collectActionDocs()).toHaveLength(179);
|
||||
});
|
||||
|
||||
it('resolves every executable name to exactly one canonical doc', () => {
|
||||
const docs = new Map(collectActionDocs().map((doc) => [doc.name, doc]));
|
||||
|
||||
for (const executable of ACTION_REGISTRY.executableNames) {
|
||||
expect(ACTION_REGISTRY.resolve(executable.name)).toBe(executable);
|
||||
if (executable.kind === 'raw') {
|
||||
expect(executable.name).toBe(HANDLE_QUICK_OPERATION_ACTION);
|
||||
expect(docs.has(executable.canonical)).toBe(false);
|
||||
continue;
|
||||
}
|
||||
|
||||
const doc = docs.get(executable.canonical);
|
||||
expect(doc, executable.name).toBeDefined();
|
||||
expect(executable.action.doc).toEqual(doc);
|
||||
expect(executable.action.kind).toBe(doc!.stream === true ? 'stream' : 'normal');
|
||||
expect([doc!.name, ...doc!.aliases]).toContain(executable.name);
|
||||
}
|
||||
});
|
||||
|
||||
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;
|
||||
|
||||
ACTION_REGISTRY.register(fakeHandler, {} as ApiActionContext);
|
||||
|
||||
expect(registered).toEqual(
|
||||
ACTION_REGISTRY.executableNames
|
||||
.filter((entry) => entry.kind !== 'raw')
|
||||
.map((entry) => [entry.name, entry.kind]),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('ApiHandler constructor-time registry transaction', () => {
|
||||
const handler = async () => okResponse();
|
||||
|
||||
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 () => {
|
||||
const api = new ApiHandler(
|
||||
{} as ApiActionContext,
|
||||
undefined,
|
||||
testRegistry(normal('__registry_normal__')),
|
||||
);
|
||||
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);
|
||||
});
|
||||
|
||||
it('keeps stream classification bound to the sealed compiled claim', () => {
|
||||
const api = new ApiHandler(
|
||||
{} as ApiActionContext,
|
||||
undefined,
|
||||
testRegistry(stream('__registry_stream__')),
|
||||
);
|
||||
expect(() => api.registerAction('__registry_stream__', handler)).toThrow(
|
||||
/Action registry is sealed/,
|
||||
);
|
||||
expect(api.isStreamAction('__registry_stream__')).toBe(true);
|
||||
});
|
||||
|
||||
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 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 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(
|
||||
{} 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/);
|
||||
});
|
||||
});
|
||||
@@ -5,13 +5,12 @@
|
||||
// from blowing the line width.
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||
import { ApiHandler } from '../src/api-handler';
|
||||
import { OidbError } from '@snowluma/protocol/oidb-service';
|
||||
import { subscribeLogs, type LogEntry } from '@snowluma/common/logger';
|
||||
import { summarizeParams } from '@snowluma/common/log-summary';
|
||||
import { createCompiledTestHandler, testAction } from './helpers/compiled-action-handler';
|
||||
|
||||
// Minimal context — we never reach the real action handlers; we
|
||||
// register our own via registerAction.
|
||||
// Minimal context — isolated test ActionSpecs never call these dependencies.
|
||||
function emptyContext(): any {
|
||||
return {
|
||||
bridge: {},
|
||||
@@ -79,8 +78,9 @@ describe('summarizeParams', () => {
|
||||
|
||||
describe('ApiHandler dispatch logging', () => {
|
||||
it('emits a debug entry under [Bridge.Action] when an action is called', async () => {
|
||||
const handler = new ApiHandler(emptyContext(), 12345);
|
||||
handler.registerAction('echo', async () => ({ status: 'ok', retcode: 0, data: null }));
|
||||
const handler = createCompiledTestHandler(emptyContext(), [
|
||||
testAction('echo', async () => ({ status: 'ok', retcode: 0, data: null })),
|
||||
], 12345);
|
||||
|
||||
await handler.handle('echo', { group_id: 67890, message: [1, 2, 3] });
|
||||
|
||||
@@ -93,10 +93,9 @@ describe('ApiHandler dispatch logging', () => {
|
||||
});
|
||||
|
||||
it('emits a warn line with the error stack when the handler throws', async () => {
|
||||
const handler = new ApiHandler(emptyContext(), 12345);
|
||||
handler.registerAction('boom', async () => {
|
||||
throw new Error('kapow');
|
||||
});
|
||||
const handler = createCompiledTestHandler(emptyContext(), [
|
||||
testAction('boom', async () => { throw new Error('kapow'); }),
|
||||
], 12345);
|
||||
|
||||
const result = await handler.handle('boom', {});
|
||||
expect(result.status).toBe('failed');
|
||||
@@ -113,16 +112,18 @@ describe('ApiHandler dispatch logging', () => {
|
||||
// maps to ONE policy here — ACTION_FAILED (100) + the error message —
|
||||
// instead of each action hand-rolling its own inconsistent try/catch.
|
||||
it('maps any handler throw to ACTION_FAILED (100) with the error message', async () => {
|
||||
const handler = new ApiHandler(emptyContext(), 12345);
|
||||
handler.registerAction('kaboom', async () => { throw new Error('permission denied'); });
|
||||
const handler = createCompiledTestHandler(emptyContext(), [
|
||||
testAction('kaboom', async () => { throw new Error('permission denied'); }),
|
||||
], 12345);
|
||||
|
||||
const result = await handler.handle('kaboom', {});
|
||||
expect(result).toMatchObject({ status: 'failed', retcode: 100, wording: 'permission denied' });
|
||||
});
|
||||
|
||||
it('surfaces the OidbError code + server message through error.message (no special-casing)', async () => {
|
||||
const handler = new ApiHandler(emptyContext(), 12345);
|
||||
handler.registerAction('oidb_boom', async () => { throw new OidbError(34, 'no permission', 0x11ec, 2); });
|
||||
const handler = createCompiledTestHandler(emptyContext(), [
|
||||
testAction('oidb_boom', async () => { throw new OidbError(34, 'no permission', 0x11ec, 2); }),
|
||||
], 12345);
|
||||
|
||||
const result = await handler.handle('oidb_boom', {});
|
||||
expect(result).toMatchObject({ status: 'failed', retcode: 100 });
|
||||
@@ -131,15 +132,16 @@ describe('ApiHandler dispatch logging', () => {
|
||||
});
|
||||
|
||||
it('renders a non-Error throw via String()', async () => {
|
||||
const handler = new ApiHandler(emptyContext(), 12345);
|
||||
handler.registerAction('weird', async () => { throw 'just a string'; });
|
||||
const handler = createCompiledTestHandler(emptyContext(), [
|
||||
testAction('weird', async () => { throw 'just a string'; }),
|
||||
], 12345);
|
||||
|
||||
const result = await handler.handle('weird', {});
|
||||
expect(result).toMatchObject({ status: 'failed', retcode: 100, wording: 'just a string' });
|
||||
});
|
||||
|
||||
it('logs unknown actions at debug level', async () => {
|
||||
const handler = new ApiHandler(emptyContext(), 99);
|
||||
const handler = createCompiledTestHandler(emptyContext(), [], 99);
|
||||
await handler.handle('not_a_real_action', {});
|
||||
|
||||
const entry = captured.find((e) => e.scope === 'Bridge.Action' && e.message.includes('unknown action'));
|
||||
@@ -148,8 +150,9 @@ describe('ApiHandler dispatch logging', () => {
|
||||
});
|
||||
|
||||
it('falls back to the module-level logger (no uin slot) when uin is omitted', async () => {
|
||||
const handler = new ApiHandler(emptyContext());
|
||||
handler.registerAction('ping', async () => ({ status: 'ok', retcode: 0, data: null }));
|
||||
const handler = createCompiledTestHandler(emptyContext(), [
|
||||
testAction('ping', async () => ({ status: 'ok', retcode: 0, data: null })),
|
||||
]);
|
||||
|
||||
await handler.handle('ping', {});
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { OneBotNetworkManager } from '../src/network/network-manager';
|
||||
import { ApiHandler, type ApiActionContext } from '../src/api-handler';
|
||||
import type { ApiActionContext } from '../src/api-handler';
|
||||
import { createCompiledTestHandler, testAction } from './helpers/compiled-action-handler';
|
||||
|
||||
// ApiHandler's register* only define handlers (closures) at construction — they
|
||||
// don't touch ctx — so a throwing proxy is a safe minimal context.
|
||||
@@ -39,8 +40,9 @@ describe('OneBotNetworkManager.subscribeDebug', () => {
|
||||
|
||||
describe('ApiHandler.setObserver', () => {
|
||||
it('fires after a successful action with {action, params, response, ms}', async () => {
|
||||
const h = new ApiHandler(fakeCtx());
|
||||
h.registerAction('ping', async () => ({ status: 'ok', retcode: 0, data: 'pong' }));
|
||||
const h = createCompiledTestHandler(fakeCtx(), [
|
||||
testAction('ping', async () => ({ status: 'ok', retcode: 0, data: 'pong' })),
|
||||
]);
|
||||
const recs: Array<{ action: string; response: { status: string } }> = [];
|
||||
h.setObserver((r) => recs.push(r as any));
|
||||
const res = await h.handle('ping', { x: 1 });
|
||||
@@ -51,8 +53,9 @@ describe('ApiHandler.setObserver', () => {
|
||||
});
|
||||
|
||||
it('fires on a thrown action with the failure response', async () => {
|
||||
const h = new ApiHandler(fakeCtx());
|
||||
h.registerAction('boom', async () => { throw new Error('kaboom'); });
|
||||
const h = createCompiledTestHandler(fakeCtx(), [
|
||||
testAction('boom', async () => { throw new Error('kaboom'); }),
|
||||
]);
|
||||
const recs: any[] = [];
|
||||
h.setObserver((r) => recs.push(r));
|
||||
await h.handle('boom', {});
|
||||
@@ -61,8 +64,9 @@ describe('ApiHandler.setObserver', () => {
|
||||
});
|
||||
|
||||
it('unsubscribe stops observation', async () => {
|
||||
const h = new ApiHandler(fakeCtx());
|
||||
h.registerAction('ping', async () => ({ status: 'ok', retcode: 0 }));
|
||||
const h = createCompiledTestHandler(fakeCtx(), [
|
||||
testAction('ping', async () => ({ status: 'ok', retcode: 0 })),
|
||||
]);
|
||||
const cb = vi.fn();
|
||||
const off = h.setObserver(cb);
|
||||
await h.handle('ping', {});
|
||||
@@ -72,8 +76,9 @@ describe('ApiHandler.setObserver', () => {
|
||||
});
|
||||
|
||||
it('a throwing observer does not break handle', async () => {
|
||||
const h = new ApiHandler(fakeCtx());
|
||||
h.registerAction('ping', async () => ({ status: 'ok', retcode: 0 }));
|
||||
const h = createCompiledTestHandler(fakeCtx(), [
|
||||
testAction('ping', async () => ({ status: 'ok', retcode: 0 })),
|
||||
]);
|
||||
h.setObserver(() => { throw new Error('observer boom'); });
|
||||
await expect(h.handle('ping', {})).resolves.toMatchObject({ status: 'ok' });
|
||||
});
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import { defineAction, type RegisteredActionSpec } from '../../src/action-kit';
|
||||
import { ApiHandler, type ApiActionContext } from '../../src/api-handler';
|
||||
import { compileActionRegistry, RAW_ACTION_RESERVATIONS } from '../../src/actions';
|
||||
import type { ApiResponse, JsonObject } from '../../src/types';
|
||||
|
||||
type TestActionRun = (
|
||||
params: JsonObject,
|
||||
context: ApiActionContext,
|
||||
) => Promise<ApiResponse> | ApiResponse;
|
||||
|
||||
/** A test-only normal ActionSpec that still travels through the complete
|
||||
* compiled-registry constructor path. */
|
||||
export function testAction(name: string, run: TestActionRun): RegisteredActionSpec {
|
||||
return defineAction({
|
||||
name,
|
||||
params: {},
|
||||
run: (_params, context, raw) => run(raw, context),
|
||||
});
|
||||
}
|
||||
|
||||
/** Construct an ApiHandler from an isolated but complete namespace. The raw
|
||||
* quick-operation reservation is mandatory, matching the production shape. */
|
||||
export function createCompiledTestHandler(
|
||||
context: ApiActionContext,
|
||||
specs: readonly RegisteredActionSpec[] = [],
|
||||
uin?: number,
|
||||
): ApiHandler {
|
||||
const registry = compileActionRegistry(
|
||||
[{ category: 'test', actions: specs }],
|
||||
RAW_ACTION_RESERVATIONS,
|
||||
);
|
||||
return new ApiHandler(context, uin, registry);
|
||||
}
|
||||
@@ -4,30 +4,30 @@
|
||||
// `stream:'stream-action'`), normal actions stay single-frame, and failures
|
||||
// terminate with an error frame. Wire format mirrors NapCat's Stream API.
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { ApiHandler, type ApiActionContext } from '../src/api-handler';
|
||||
import { defineAction, defineStreamAction, f } from '../src/action-kit';
|
||||
import type { ApiHandler, ApiActionContext } from '../src/api-handler';
|
||||
import { defineAction, defineStreamAction, f, type RegisteredActionSpec } from '../src/action-kit';
|
||||
import { okResponse, failedResponse } from '../src/types';
|
||||
import { wrapStreamFrame, wrapStreamTerminal, STREAM_MARK } from '../src/streaming';
|
||||
import { createCompiledTestHandler } from './helpers/compiled-action-handler';
|
||||
|
||||
function newHandler(): ApiHandler {
|
||||
// The real register* run lazily (handlers capture ctx, never call it at
|
||||
// registration), so an empty ctx is enough to exercise the dispatch seam.
|
||||
return new ApiHandler({} as ApiActionContext);
|
||||
function newHandler(...specs: RegisteredActionSpec[]): ApiHandler {
|
||||
// ActionSpecs bind during the constructor but call ctx only when dispatched.
|
||||
return createCompiledTestHandler({} as ApiActionContext, specs);
|
||||
}
|
||||
|
||||
const parse = (frames: string[]) => frames.map((f) => JSON.parse(f) as Record<string, unknown>);
|
||||
|
||||
describe('Stream API plumbing', () => {
|
||||
it('streams N intermediate frames + a terminal frame, all echo-tagged', async () => {
|
||||
const h = newHandler();
|
||||
defineStreamAction({
|
||||
const action = defineStreamAction({
|
||||
name: 'demo_stream',
|
||||
params: { n: f.uint() },
|
||||
run: async (p, _ctx, _raw, sink) => {
|
||||
for (let i = 0; i < p.n; i++) await sink.send({ type: 'stream', index: i });
|
||||
return okResponse({ type: 'response', total: p.n });
|
||||
},
|
||||
}).register(h, {} as ApiActionContext);
|
||||
});
|
||||
const h = newHandler(action);
|
||||
|
||||
const frames: string[] = [];
|
||||
await h.processStreamRequest(
|
||||
@@ -43,17 +43,17 @@ describe('Stream API plumbing', () => {
|
||||
});
|
||||
|
||||
it('marks the action as a stream action; normal actions are not', () => {
|
||||
const h = newHandler();
|
||||
defineStreamAction({ name: 'demo_stream', params: {}, run: () => okResponse({ type: 'response' }) }).register(h, {} as ApiActionContext);
|
||||
defineAction({ name: 'demo_normal', params: {}, run: () => okResponse({ ok: true }) }).register(h, {} as ApiActionContext);
|
||||
const streamAction = defineStreamAction({ name: 'demo_stream', params: {}, run: () => okResponse({ type: 'response' }) });
|
||||
const normalAction = defineAction({ name: 'demo_normal', params: {}, run: () => okResponse({ ok: true }) });
|
||||
const h = newHandler(streamAction, normalAction);
|
||||
expect(h.isStreamAction('demo_stream')).toBe(true);
|
||||
expect(h.isStreamAction('demo_normal')).toBe(false);
|
||||
expect(h.isStreamAction('nope')).toBe(false);
|
||||
});
|
||||
|
||||
it('a normal action through processStreamRequest emits exactly one un-marked frame', async () => {
|
||||
const h = newHandler();
|
||||
defineAction({ name: 'demo_normal', params: {}, run: () => okResponse({ ok: true }) }).register(h, {} as ApiActionContext);
|
||||
const action = defineAction({ name: 'demo_normal', params: {}, run: () => okResponse({ ok: true }) });
|
||||
const h = newHandler(action);
|
||||
|
||||
const frames: string[] = [];
|
||||
await h.processStreamRequest(JSON.stringify({ action: 'demo_normal', params: {}, echo: 'e2' }), (j) => frames.push(j));
|
||||
@@ -65,12 +65,12 @@ describe('Stream API plumbing', () => {
|
||||
});
|
||||
|
||||
it('a throwing stream action terminates with a single error frame', async () => {
|
||||
const h = newHandler();
|
||||
defineStreamAction({
|
||||
const action = defineStreamAction({
|
||||
name: 'demo_boom',
|
||||
params: {},
|
||||
run: async () => { throw new Error('boom'); },
|
||||
}).register(h, {} as ApiActionContext);
|
||||
});
|
||||
const h = newHandler(action);
|
||||
|
||||
const frames: string[] = [];
|
||||
await h.processStreamRequest(JSON.stringify({ action: 'demo_boom', params: {}, echo: 'e3' }), (j) => frames.push(j));
|
||||
@@ -82,15 +82,15 @@ describe('Stream API plumbing', () => {
|
||||
});
|
||||
|
||||
it('emits already-sent frames before the terminal error when a stream throws mid-way', async () => {
|
||||
const h = newHandler();
|
||||
defineStreamAction({
|
||||
const action = defineStreamAction({
|
||||
name: 'demo_partial',
|
||||
params: {},
|
||||
run: async (_p, _ctx, _raw, sink) => {
|
||||
await sink.send({ type: 'stream', index: 0 });
|
||||
throw new Error('mid');
|
||||
},
|
||||
}).register(h, {} as ApiActionContext);
|
||||
});
|
||||
const h = newHandler(action);
|
||||
|
||||
const frames: string[] = [];
|
||||
await h.processStreamRequest(JSON.stringify({ action: 'demo_partial', params: {} }), (j) => frames.push(j));
|
||||
@@ -102,8 +102,8 @@ describe('Stream API plumbing', () => {
|
||||
});
|
||||
|
||||
it('stream param validation fails terminate with an error frame', async () => {
|
||||
const h = newHandler();
|
||||
defineStreamAction({ name: 'demo_needs', params: { n: f.uint() }, run: () => okResponse({ type: 'response' }) }).register(h, {} as ApiActionContext);
|
||||
const action = defineStreamAction({ name: 'demo_needs', params: { n: f.uint() }, run: () => okResponse({ type: 'response' }) });
|
||||
const h = newHandler(action);
|
||||
|
||||
const frames: string[] = [];
|
||||
await h.processStreamRequest(JSON.stringify({ action: 'demo_needs', params: {} }), (j) => frames.push(j));
|
||||
@@ -112,16 +112,16 @@ describe('Stream API plumbing', () => {
|
||||
});
|
||||
|
||||
it('aborts a stream when isAlive turns false (client disconnect)', async () => {
|
||||
const h = newHandler();
|
||||
let sent = 0;
|
||||
defineStreamAction({
|
||||
const action = defineStreamAction({
|
||||
name: 'demo_abort',
|
||||
params: {},
|
||||
run: async (_p, _ctx, _raw, sink) => {
|
||||
for (let i = 0; i < 5; i++) { await sink.send({ type: 'stream', index: i }); sent++; }
|
||||
return okResponse({ type: 'response' });
|
||||
},
|
||||
}).register(h, {} as ApiActionContext);
|
||||
});
|
||||
const h = newHandler(action);
|
||||
|
||||
const frames: string[] = [];
|
||||
let alive = true;
|
||||
|
||||
Reference in new issue
Block a user