feat: pipeline returns StreamResult for async-iterable handlers

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-06-27 15:15:05 -05:00
1 parent a3dad32384
commit a94a987a35
2 files changed
+38 -4

No files matched your search

+9 -1
View File
@@ -1,9 +1,16 @@
import { Bus } from './bus'; import { Bus } from './bus';
import { errorToResponse } from './transformers'; import { errorToResponse } from './transformers';
import { isAsyncIterable } from './channel';
import type { TransformerFn } from './metadata'; import type { TransformerFn } from './metadata';
export interface PipelineStep { name: string; origin: string; run: (ctx: any) => any } export interface PipelineStep { name: string; origin: string; run: (ctx: any) => any }
export interface ResponseShape { status: number; headers: Record<string, string>; body: string } export interface ResponseShape { status: number; headers: Record<string, string>; body: string }
export interface StreamResult { stream: AsyncIterable<unknown> }
export type PipelineResult = ResponseShape | StreamResult;
export function isStreamResult(r: PipelineResult): r is StreamResult {
return 'stream' in r;
}
export async function runPipeline(args: { export async function runPipeline(args: {
steps: PipelineStep[]; steps: PipelineStep[];
@@ -11,7 +18,7 @@ export async function runPipeline(args: {
transformer: TransformerFn; transformer: TransformerFn;
seed: Record<string, unknown>; seed: Record<string, unknown>;
bus: Bus; bus: Bus;
}): Promise<ResponseShape> { }): Promise<PipelineResult> {
const { steps, handler, transformer, seed, bus } = args; const { steps, handler, transformer, seed, bus } = args;
let ctx: any = { ...seed }; let ctx: any = { ...seed };
try { try {
@@ -22,6 +29,7 @@ export async function runPipeline(args: {
bus.emit('request:step:leave', { name: s.name, scope: s.origin }); bus.emit('request:step:leave', { name: s.name, scope: s.origin });
} }
const result = await handler(ctx); const result = await handler(ctx);
if (isAsyncIterable(result)) return { stream: result }; // stream path: transformer bypassed
const r = transformer(result); const r = transformer(result);
return { status: r.status ?? 200, headers: r.headers ?? {}, body: r.body }; return { status: r.status ?? 200, headers: r.headers ?? {}, body: r.body };
} catch (error) { } catch (error) {
+29 -3
View File
@@ -1,5 +1,5 @@
import { expect, test, vi } from 'vitest'; import { describe, expect, it, test, vi } from 'vitest';
import { runPipeline } from '../src/pipeline'; import { runPipeline, isStreamResult } from '../src/pipeline';
import { Bus } from '../src/bus'; import { Bus } from '../src/bus';
import { JsonTransformer } from '../src/transformers'; import { JsonTransformer } from '../src/transformers';
import { Unauthorized } from '../src/signals'; import { Unauthorized } from '../src/signals';
@@ -13,8 +13,11 @@ test('runs steps, accumulates ctx, transforms handler return', async () => {
steps: [{ name: 'auth', origin: 'mod', run: (ctx) => ({ user: ctx.req.token }) }], steps: [{ name: 'auth', origin: 'mod', run: (ctx) => ({ user: ctx.req.token }) }],
handler: (ctx) => ({ user: ctx.user }), handler: (ctx) => ({ user: ctx.user }),
}); });
expect(isStreamResult(res)).toBe(false);
if (!isStreamResult(res)) {
expect(res.status).toBe(200); expect(res.status).toBe(200);
expect(JSON.parse(res.body)).toEqual({ user: 'abc' }); expect(JSON.parse(res.body)).toEqual({ user: 'abc' });
}
}); });
test('a thrown HttpError short-circuits to an error response', async () => { test('a thrown HttpError short-circuits to an error response', async () => {
@@ -24,7 +27,8 @@ test('a thrown HttpError short-circuits to an error response', async () => {
steps: [{ name: 'auth', origin: 'mod', run: () => { throw new Unauthorized('no'); } }], steps: [{ name: 'auth', origin: 'mod', run: () => { throw new Unauthorized('no'); } }],
handler: () => ({ never: true }), handler: () => ({ never: true }),
}); });
expect(res.status).toBe(401); expect(isStreamResult(res)).toBe(false);
if (!isStreamResult(res)) expect(res.status).toBe(401);
}); });
test('emits enter/leave/error lifecycle events', async () => { test('emits enter/leave/error lifecycle events', async () => {
@@ -40,3 +44,25 @@ test('emits enter/leave/error lifecycle events', async () => {
expect(enter).toHaveBeenCalledWith(expect.objectContaining({ name: 'boom' })); expect(enter).toHaveBeenCalledWith(expect.objectContaining({ name: 'boom' }));
expect(error).toHaveBeenCalled(); expect(error).toHaveBeenCalled();
}); });
describe('runPipeline streaming', () => {
const bus = new Bus();
const noTransform = (v: unknown) => ({ body: String(v) });
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 });
expect(isStreamResult(res)).toBe(true);
if (isStreamResult(res)) {
const out: unknown[] = [];
for await (const v of res.stream) out.push(v);
expect(out).toEqual([1, 2]);
}
});
it('still buffers a normal return through the transformer', async () => {
const res = await runPipeline({ steps: [], handler: () => 'hi', transformer: () => ({ body: 'HI' }), seed: {}, bus });
expect(isStreamResult(res)).toBe(false);
if (!isStreamResult(res)) expect(res.body).toBe('HI');
});
});