From f613a6427be23d01b9d56d3a194f3a4af18158f1 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Fri, 10 Jul 2026 15:55:22 -0500 Subject: [PATCH] feat(pipeline): enforce return contract by declared transport Signed-off-by: Diego Resendez --- src/app/index.ts | 2 ++ src/index.ts | 10 +++++++++- src/pipeline.ts | 31 +++++++++++++++++++++++++++--- src/signals.ts | 13 +++++++++++++ test/pipeline.test.ts | 44 ++++++++++++++++++++++++++++++++++++++----- 5 files changed, 91 insertions(+), 9 deletions(-) diff --git a/src/app/index.ts b/src/app/index.ts index 18ce2a1..a624c6e 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -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, diff --git a/src/index.ts b/src/index.ts index de7e9c9..4beab8b 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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'; diff --git a/src/pipeline.ts b/src/pipeline.ts index 4810252..46a303f 100644 --- a/src/pipeline.ts +++ b/src/pipeline.ts @@ -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 = { + 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; bus: Bus; + transport: Transport; onError?: ErrorRenderer; }): Promise { - 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) { diff --git a/src/signals.ts b/src/signals.ts index e7556bb..29f5507 100644 --- a/src/signals.ts +++ b/src/signals.ts @@ -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; diff --git a/test/pipeline.test.ts b/test/pipeline.test.ts index 64abd00..24e7168 100644 --- a/test/pipeline.test.ts +++ b/test/pipeline.test.ts @@ -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); + }); +});