feat(pipeline): enforce return contract by declared transport

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-07-10 15:55:22 -05:00
1 parent 35861f0fc1
commit f613a6427b
5 files changed
+91 -9

No files matched your search

+2
View File
@@ -635,6 +635,7 @@ function buildMeshControl(
transformer: plan.transformer,
bus,
onError,
transport: plan.transport,
seed: { ...provided, req: env, params: env.params, query: env.query, body: env.body, headers: env.headers },
});
@@ -671,6 +672,7 @@ function buildHttpRoutes(routePlans: RoutePlan[], remoteRoutes: RouteDef[], deps
transformer: plan.transformer,
bus,
onError,
transport: plan.transport,
seed: {
...provided,
req,
+9 -1
View File
@@ -44,7 +44,15 @@ export type { Plugin } from './plugin';
// Transformers & error signals
export { JsonTransformer } from './transformers';
export type { ErrorRenderer, ErrorRequest, ErrorResponse } from './transformers';
export { HttpError, Unauthorized, NotFound, Redirect, NotModified, ValidationError } from './signals';
export {
HttpError,
Unauthorized,
NotFound,
Redirect,
NotModified,
ValidationError,
TransportMismatchError,
} from './signals';
// Bus & flow
export { Bus } from './bus';
+28 -3
View File
@@ -1,7 +1,8 @@
import { Bus } from './bus';
import { renderError, type ErrorRenderer } from './transformers';
import { isAsyncIterable } from './channel';
import type { TransformerFn } from './metadata';
import type { TransformerFn, Transport } from './metadata';
import { TransportMismatchError } from './signals';
/** A single step in a request pipeline: a named unit whose `run` merges its output into the shared context. */
export interface PipelineStep {
@@ -22,6 +23,18 @@ export interface StreamResult {
/** The outcome of {@link runPipeline}: either a buffered response or a stream. */
export type PipelineResult = ResponseShape | StreamResult;
/** What a route's declared transport requires its handler to return. */
export type ReturnContract = 'buffer' | 'stream' | 'either';
/** Return contract per transport. A new transport just adds a row. `ws` never reaches runPipeline (filtered earlier). */
export const TRANSPORT_RETURN: Record<Transport, ReturnContract> = {
buffer: 'buffer',
sse: 'stream',
ndjson: 'stream',
ws: 'stream',
negotiate: 'either',
};
/** Type guard narrowing a {@link PipelineResult} to a {@link StreamResult}. */
export function isStreamResult(result: PipelineResult): result is StreamResult {
return 'stream' in result;
@@ -38,9 +51,10 @@ export async function runPipeline(args: {
transformer: TransformerFn;
seed: Record<string, unknown>;
bus: Bus;
transport: Transport;
onError?: ErrorRenderer;
}): Promise<PipelineResult> {
const { steps, handler, transformer, seed, bus, onError } = args;
const { steps, handler, transformer, seed, bus, transport, onError } = args;
// context is intentionally `any`: each step merges arbitrary keys into the accumulator
let context: any = { ...seed };
@@ -53,7 +67,18 @@ export async function runPipeline(args: {
}
const result = await handler(context);
if (isAsyncIterable(result)) return { stream: result }; // stream path: transformer bypassed
const streaming = isAsyncIterable(result);
const contract = TRANSPORT_RETURN[transport];
if (contract === 'buffer' && streaming) {
throw new TransportMismatchError(transport, 'stream', context.req as { method?: string; url?: string });
}
if (contract === 'stream' && !streaming) {
throw new TransportMismatchError(transport, 'value', context.req as { method?: string; url?: string });
}
if (streaming) return { stream: result }; // stream path: transformer bypassed
const transformed = transformer(result);
return { status: transformed.status ?? 200, headers: transformed.headers ?? {}, body: transformed.body };
} catch (error) {
+13
View File
@@ -50,6 +50,19 @@ export class ValidationError extends HttpError {
}
}
/** Thrown when a handler's return value contradicts its route's declared transport (a programming error). */
export class TransportMismatchError extends HttpError {
constructor(transport: string, got: 'stream' | 'value', req?: { method?: string; url?: string }) {
const where = req?.method && req?.url ? ` (${req.method} ${req.url})` : '';
const expected = got === 'stream' ? 'return a value' : 'return an AsyncIterable';
const fix =
got === 'stream'
? 'buffered routes (@Get/@Post/@Put/@Patch/@Delete) must return a value — to stream, declare @Sse, @Stream, or @Ws'
: 'streaming routes (@Sse/@Ws) must return an AsyncIterable (e.g. an async generator or channel())';
super(500, `Transport '${transport}'${where} must ${expected}, but the handler returned a ${got}. ${fix}.`);
}
}
/** Type guard: true if `error` is an {@link HttpError}. */
export function isHttpError(error: unknown): error is HttpError {
return error instanceof HttpError;
+39 -5
View File
@@ -9,7 +9,7 @@ const base = { transformer: JsonTransformer, seed: { req: { token: 'abc' } } };
test('runs steps, accumulates ctx, transforms handler return', async () => {
const bus = new Bus();
const res = await runPipeline({
...base, bus,
...base, bus, transport: 'buffer',
steps: [{ name: 'auth', origin: 'mod', run: (ctx) => ({ user: ctx.req.token }) }],
handler: (ctx) => ({ user: ctx.user }),
});
@@ -23,7 +23,7 @@ test('runs steps, accumulates ctx, transforms handler return', async () => {
test('a thrown HttpError short-circuits to an error response', async () => {
const bus = new Bus();
const res = await runPipeline({
...base, bus,
...base, bus, transport: 'buffer',
steps: [{ name: 'auth', origin: 'mod', run: () => { throw new Unauthorized('no'); } }],
handler: () => ({ never: true }),
});
@@ -37,7 +37,7 @@ test('emits enter/leave/error lifecycle events', async () => {
bus.on('request:step:enter', enter);
bus.on('request:step:error', error);
await runPipeline({
...base, bus,
...base, bus, transport: 'buffer',
steps: [{ name: 'boom', origin: 'mod', run: () => { throw new Unauthorized(); } }],
handler: () => ({}),
});
@@ -51,7 +51,7 @@ describe('runPipeline streaming', () => {
it('returns a StreamResult when the handler returns an AsyncIterable (transformer bypassed)', async () => {
async function* gen() { yield 1; yield 2; }
const res = await runPipeline({ steps: [], handler: () => gen(), transformer: noTransform, seed: {}, bus });
const res = await runPipeline({ steps: [], handler: () => gen(), transformer: noTransform, seed: {}, bus, transport: 'sse' });
expect(isStreamResult(res)).toBe(true);
if (isStreamResult(res)) {
const out: unknown[] = [];
@@ -61,8 +61,42 @@ describe('runPipeline streaming', () => {
});
it('still buffers a normal return through the transformer', async () => {
const res = await runPipeline({ steps: [], handler: () => 'hi', transformer: () => ({ body: 'HI' }), seed: {}, bus });
const res = await runPipeline({ steps: [], handler: () => 'hi', transformer: () => ({ body: 'HI' }), seed: {}, bus, transport: 'buffer' });
expect(isStreamResult(res)).toBe(false);
if (!isStreamResult(res)) expect(res.body).toBe('HI');
});
});
describe('runPipeline transport enforcement', () => {
const bus = new Bus();
const noTransform = (v: unknown) => ({ body: String(v) });
async function* gen() { yield 1; }
it('renders a 500 mismatch when a buffered route returns an AsyncIterable', async () => {
const res = await runPipeline({ steps: [], handler: () => gen(), transformer: noTransform, seed: {}, bus, transport: 'buffer' });
expect(isStreamResult(res)).toBe(false);
if (!isStreamResult(res)) {
expect(res.status).toBe(500);
expect(res.body).toContain('must return a value');
}
});
it('renders a 500 mismatch when a streaming route returns a non-iterable', async () => {
const res = await runPipeline({ steps: [], handler: () => ({ x: 1 }), transformer: noTransform, seed: {}, bus, transport: 'sse' });
expect(isStreamResult(res)).toBe(false);
if (!isStreamResult(res)) {
expect(res.status).toBe(500);
expect(res.body).toContain('must return an AsyncIterable');
}
});
it('negotiate tolerates a value (buffered)', async () => {
const res = await runPipeline({ steps: [], handler: () => 'hi', transformer: noTransform, seed: {}, bus, transport: 'negotiate' });
expect(isStreamResult(res)).toBe(false);
});
it('negotiate tolerates an AsyncIterable (stream)', async () => {
const res = await runPipeline({ steps: [], handler: () => gen(), transformer: noTransform, seed: {}, bus, transport: 'negotiate' });
expect(isStreamResult(res)).toBe(true);
});
});