feat(pipeline): transport is declared, not inferred (BREAKING) A route's declared transport is now the ground truth for what its handler may return — the old implicit "any handler returning an AsyncIterable streams" behavior (spec #2) is removed. - @Get/@Post/@Put/@Patch/@Delete (buffer) MUST return a value; returning an AsyncIterable -> 500 TransportMismatchError. - @Sse/@Ws MUST return an AsyncIterable; returning a value -> 500. - @Stream (negotiate) still tolerates both (client negotiates via Accept). - Extensible TRANSPORT_RETURN map (Record<Transport, ReturnContract>); runPipeline gains a required `transport` arg, wired at both call sites. - @Html (buffer) is covered by the general rule; its return contract (bare->string, template->object, file->void) is documented. BREAKING (pre-1.0): a return value no longer changes a route's wire contract. Declare @Sse/@Stream/@Ws to stream. 0 examples affected. 269 tests, tsc/lint/complexity green. Per-task + final opus review. Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
11 files changed
+151
-22
No files matched your search
@@ -34,6 +34,11 @@ green-tea uses calendar versioning: `YY.MM.PATCH`.
|
||||
fields such as `req.socket` / `req.rawHeaders` are no longer available on
|
||||
`ctx.req`; use `ctx.protocol` / `ctx.ip` / `ctx.query` / `ctx.headers`
|
||||
instead — all still provided.
|
||||
- **Breaking (pre-1.0): transport is now enforced by declaration.** A buffered route
|
||||
(`@Get`/`@Post`/`@Put`/`@Patch`/`@Delete`) whose handler returns an `AsyncIterable`, or a streaming
|
||||
route (`@Sse`/`@Ws`) whose handler returns a plain value, now fails with a 500 `TransportMismatchError`
|
||||
instead of silently switching behavior. `@Stream` still negotiates both. Declare `@Sse`/`@Stream`/`@Ws`
|
||||
to stream — a return value no longer changes a route's wire contract.
|
||||
|
||||
## [26.7.0-beta.0] - 2026-07-07
|
||||
|
||||
|
||||
@@ -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
@@ -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
@@ -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) {
|
||||
|
||||
@@ -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
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,36 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { createApp, Route, Get, Sse, Module } from '../src/index';
|
||||
|
||||
@Route('/api')
|
||||
class Ctl {
|
||||
@Get('/ok') ok() { return { ok: true }; } // buffered value — fine
|
||||
@Get('/leak') leak() { return (async function* () { yield 1; })(); } // buffered + iterable — 500
|
||||
@Sse('/stream') stream() { return (async function* () { yield { n: 1 }; })(); } // stream — fine
|
||||
@Sse('/empty') empty() { return { not: 'a stream' }; } // stream + value — 500
|
||||
}
|
||||
@Module({ mountpoint: '/', controllers: [Ctl] })
|
||||
class M {}
|
||||
const app = createApp({ modules: [M] });
|
||||
|
||||
describe('transport enforcement (integration)', () => {
|
||||
it('a normal buffered GET still returns its value', async () => {
|
||||
const res = await app.fetch(new Request('http://x/api/ok'));
|
||||
expect(res.status).toBe(200);
|
||||
expect(await res.json()).toEqual({ ok: true });
|
||||
});
|
||||
it('a buffered GET that returns an AsyncIterable is a 500 mismatch', async () => {
|
||||
const res = await app.fetch(new Request('http://x/api/leak'));
|
||||
expect(res.status).toBe(500);
|
||||
expect(await res.text()).toContain('must return a value');
|
||||
});
|
||||
it('a normal SSE stream still streams', async () => {
|
||||
const res = await app.fetch(new Request('http://x/api/stream'));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.headers.get('content-type')).toContain('text/event-stream');
|
||||
});
|
||||
it('an SSE route that returns a plain value is a 500 mismatch', async () => {
|
||||
const res = await app.fetch(new Request('http://x/api/empty'));
|
||||
expect(res.status).toBe(500);
|
||||
expect(await res.text()).toContain('must return an AsyncIterable');
|
||||
});
|
||||
});
|
||||
@@ -143,4 +143,4 @@ receive `undefined`. Boot fails loudly, so you never serve `undefined`.
|
||||
- Everything a handler can inject: [Argument decorators](/guides/arguments/) and the
|
||||
[decorator reference](/reference/decorators/).
|
||||
- Coerce and validate injected values with Standard Schema: [Validation](/guides/validation/).
|
||||
- Return an `AsyncIterable` to push data over time: [Streaming](/guides/streaming/).
|
||||
- Declare `@Sse` and return an `AsyncIterable` to push data over time: [Streaming](/guides/streaming/).
|
||||
@@ -62,10 +62,13 @@ class UserController {
|
||||
|
||||
Same filesystem requirement as file mode: Node/Deno/Bun only.
|
||||
|
||||
:::caution[Return a string or data, never an `AsyncIterable`]
|
||||
An `@Html` handler must return a string (bare mode) or a data object (template mode). Don't
|
||||
return an `AsyncIterable` — the pipeline detects async-iterable returns and streams them raw,
|
||||
bypassing the HTML transformer entirely, so your markup never gets wrapped or rendered.
|
||||
:::caution[Return the right shape for each mode — never an `AsyncIterable`]
|
||||
`@Html` is a buffered route, so its return contract follows the mode: bare `@Html` returns a
|
||||
`string`; `@Html('file.html', { template: true })` returns the data object rendered into the
|
||||
template; `@Html('file.html')` (no template) ignores the return entirely — annotate it `: void`
|
||||
by convention, e.g. `page(@needs('x')): void {}`. Returning an `AsyncIterable` from any `@Html`
|
||||
handler is the same buffered-route mismatch as any other `@Get`/`@Post`/`@Put`/`@Patch`/`@Delete`
|
||||
handler: a 500 `TransportMismatchError`, not a silent raw stream.
|
||||
:::
|
||||
|
||||
## The `views` base directory
|
||||
|
||||
@@ -28,7 +28,7 @@ Streaming bypasses the response transformer — the transport frames each value
|
||||
|
||||
## Streaming — SSE
|
||||
|
||||
Return an `AsyncIterable` and the pipeline streams it (the transformer is bypassed; the transport frames it, handles backpressure, and cleans up on disconnect).
|
||||
A route decorated `@Sse` streams — that's what triggers it, not the return value. It must return an `AsyncIterable`; the transport frames each value as an SSE event, handles backpressure, and cleans up on disconnect (the transformer is bypassed).
|
||||
|
||||
```typescript
|
||||
import { Route, Sse } from '@green-tea/core';
|
||||
@@ -104,11 +104,14 @@ Same `@Route`, same handler shape, same `AsyncIterable` — real-time is not a s
|
||||
|
||||
`rooms` is the built-in shared `Rooms` primitive (one instance app-wide). A typical chat handler pumps the `@inbound()` channel into `rooms.room(name)` and returns that same room as its outbound channel, so every joined socket multicasts to the others. A handshake `@Step` can read `?token=` and throw `Unauthorized` — which closes the socket with code **4401** (`4000 + status`). See [security](/guides/security/) for handshake authentication.
|
||||
|
||||
## The one rule to remember
|
||||
## Transport is declared, not inferred
|
||||
|
||||
```
|
||||
return a VALUE → buffered response (transformer → JSON)
|
||||
return an AsyncIterable → stream (SSE / WS)
|
||||
```
|
||||
A route streams **because** it's declared `@Sse`, `@Stream`, or `@Ws` — never because a handler happened to return an `AsyncIterable`. In most frameworks the return type decides the wire format; in green-tea the decorator decides, and the return value is enforced against it:
|
||||
|
||||
Return a value and you get a buffered JSON response; return an `AsyncIterable` and you get a stream. That's the whole contract.
|
||||
| Declare | Handler must return | Otherwise |
|
||||
|---|---|---|
|
||||
| `@Get` / `@Post` / `@Put` / `@Patch` / `@Delete` (buffered) | a value | returning an `AsyncIterable` fails with a 500 `TransportMismatchError` |
|
||||
| `@Sse` / `@Ws` (streaming) | an `AsyncIterable` | returning a plain value fails with a 500 `TransportMismatchError` |
|
||||
| `@Stream` (negotiate) | either | the client picks via `Accept` / `Upgrade` — no mismatch |
|
||||
|
||||
This is the anti-Express guarantee: your wire contract is what you **declared**, never a surprise sprung by a return value. A buffered route can't accidentally start streaming because someone returned a generator; a streaming route can't silently downgrade to a buffered response because someone forgot a `yield`. Declare `@Sse` / `@Stream` / `@Ws` to stream — the return value never changes a route's transport.
|
||||
@@ -35,7 +35,7 @@ Most frameworks make you keep the whole request in your head: which middleware r
|
||||
`app.explain('/users/:id')` prints the ordered chain; `GET /__graph__` renders it as a live diagram. Onboarding and audits are reading, not archaeology.
|
||||
</Card>
|
||||
<Card title="One primitive for real-time" icon="rocket">
|
||||
Return an `AsyncIterable` and the transport streams it — SSE, ndjson, or a WebSocket duplex — with backpressure and cleanup handled. No separate gateway.
|
||||
Declare `@Sse`, `@Stream`, or `@Ws` and return an `AsyncIterable` — the transport streams it (SSE, ndjson, or a WebSocket duplex) with backpressure and cleanup handled. No separate gateway.
|
||||
</Card>
|
||||
</CardGrid>
|
||||
|
||||
|
||||
Reference in new issue
Block a user