Files
core/src/pipeline.ts
T
chrnx 88945b0b1f
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / build (pull_request) Successful in 27s
CI / runtimes (deno) (pull_request) Successful in 20s
CI / runtimes (edge) (pull_request) Successful in 14s
feat(http)!: cookie decorators, setCookie, and string | string[] response headers (CARD-14, #113)
Reading a cookie meant parsing the Cookie header by hand, and a response
could not carry more than one Set-Cookie: response header values were
Record<string, string>, and the fetch adapters would have stringified an
array into one broken "a,b" cookie anyway.

- @cookie('name') / @cookies() sit next to @header/@headers as a new
  'cookies' arg source. The header is parsed on first use per request and
  cached on the context, so a route without a cookie argument never parses
  it. RFC 6265: first value wins, %-sequences decoded, malformed pairs
  skipped (never a 400), undecodable values kept raw. Several cookie lines
  are joined with "; ". The map has no prototype. @needs('cookies') reads
  the same map, and 'cookies' joins the seed-key allow-list.
- setCookie(name, value, options) serialises one Set-Cookie value with
  HttpOnly, SameSite=Lax, Path=/ and Secure by default (D10), and throws,
  naming the field, on anything that could inject a header or that browsers
  reject (sameSite none / partitioned without secure).
- Response header values widen to string | string[] (D11) across
  TransformerFn, ErrorResponse, HttpError(Like).headers, ResponseShape and
  the neutral outcome. Node writes a set-cookie array as one line per
  element and joins every other array with ", " before writeHead; the
  fetch adapters build a Headers and append each set-cookie element.
  mergeInjectedHeaders keeps arrays by reference and joins a vary array
  before merging it.
- OpenAPI maps a cookie argument to an in: cookie parameter.

BREAKING CHANGE: code that reads a header value from TransformerFn,
ErrorResponse, HttpError or ResponseShape as a string must handle string[].

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 01:00:43 -05:00

173 lines
7.3 KiB
TypeScript

import { Bus, type Correlation } from './bus';
import { renderError, type ErrorRenderer } from './transformers';
import { isAsyncIterable } from './channel';
import type { TransformerFn, Transport } from './metadata';
import { TransportMismatchError } from './signals';
import type { Logger } from './logger';
/** A single step in a request pipeline: a named unit whose `run` merges its output into the shared context. */
export interface PipelineStep {
name: string;
origin: string;
run: (ctx: any) => any;
}
/** A fully materialized HTTP response produced by a transformer. */
export interface ResponseShape {
status: number;
/** A value may be an array: `set-cookie` arrays are sent one line per element, others joined with `, `. */
headers: Record<string, string | string[]>;
body: string;
}
/** A streaming response; the async iterable is written to the socket and bypasses the transformer. */
export interface StreamResult {
stream: AsyncIterable<unknown>;
}
/** 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;
}
/**
* Run `steps` in order, merging each step's output into the context and emitting
* `request:step:enter`/`leave` on the bus. The single place steps are executed — every
* transport (HTTP, ws, mesh) goes through here so observability is uniform by construction.
*/
export async function runSteps(
steps: PipelineStep[],
seed: Record<string, unknown>,
bus: Bus,
correlation: Correlation = {},
): Promise<any> {
// context is intentionally `any`: each step merges arbitrary keys into the accumulator
const context: any = seed;
// One timestamp per boundary, not one pair per step: a step's end is the next one's start, so
// N steps need N+1 readings rather than 2N. Measured at 25.2ns vs 45.3ns per step, against a
// ~10.19us request — 0.25%, below the 0.3% run-to-run CV of the project's own benchmark, which
// is why this is always on instead of hiding behind a flag nobody could tune with evidence.
// Hoisted out of the loop: listeners are registered at boot, so re-deciding this per step buys
// nothing. When nothing is listening — the common case — the whole block below costs a branch
// instead of building four payloads and reading three clocks for an audience of nobody.
const watchingEnter = bus.hasListeners('request:step:enter');
const watchingLeave = bus.hasListeners('request:step:leave');
const watchingError = bus.hasListeners('request:step:error');
const timing = watchingLeave || watchingError;
let mark = timing ? performance.now() : 0;
for (const step of steps) {
if (watchingEnter) bus.emit('request:step:enter', { name: step.name, scope: step.origin, ...correlation });
try {
const output = await step.run(context);
Object.assign(context, output);
} catch (error) {
// Emitted here, where the step that failed is still known. The outer catch in runPipeline
// only sees "something in the pipeline threw" and used to report `name: 'pipeline'`, which
// threw away the one fact the event exists to carry. Rethrown unchanged — this observes.
if (watchingError) {
bus.emit('request:step:error', {
name: step.name,
scope: step.origin,
error,
durationMs: performance.now() - mark,
...correlation,
});
}
throw error;
}
if (timing) {
const now = performance.now();
if (watchingLeave)
bus.emit('request:step:leave', { name: step.name, scope: step.origin, durationMs: now - mark, ...correlation });
mark = now;
}
}
return context;
}
/**
* Run `steps` in order over a context seeded from `seed`, then invoke `handler`.
* An async-iterable handler result becomes a stream; anything else is run through `transformer`.
* Errors are caught, emitted on `bus`, and converted to an error response.
*/
export async function runPipeline(args: {
steps: PipelineStep[];
handler: (ctx: any) => unknown;
transformer: TransformerFn;
seed: Record<string, unknown>;
bus: Bus;
transport: Transport;
onError?: ErrorRenderer;
logger?: Logger;
correlation?: Correlation;
}): Promise<PipelineResult> {
const { steps, handler, transformer, seed, bus, transport, onError, logger, correlation = {} } = args;
// context is intentionally `any`: each step merges arbitrary keys into the accumulator
let context: any = { ...seed };
try {
context = await runSteps(steps, context, bus, correlation);
const result = await handler(context);
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) {
const req = (context.req ?? {}) as { method?: string; url?: string; headers?: Record<string, unknown> };
let status: number | undefined;
try {
const rendered = renderError(
error,
{ method: req.method ?? '', url: req.url ?? '', headers: (context.headers ?? req.headers ?? {}) as never },
onError,
logger,
);
status = rendered.status;
return rendered;
} finally {
// Both fire for a failing step, deliberately: `request:step:error` above marks the span,
// this marks the trace. A tracing exporter needs each, and only emitting the outer one is
// what produces a trace that says a request failed without saying where.
//
// Emitted after the render rather than before it, because the status is only decided there:
// `onError` may turn any throw into any status, so deriving one from the error would be a
// guess that a custom renderer makes wrong.
//
// In `finally` rather than after the call, so that nothing between here and the emit can cost
// us the only record that a request failed. `renderError` already contains a throwing
// `onError` and degrades to the built-in rendering, so this is a second line rather than the
// first — but a failure whose reporting is what broke is the worst one to lose.
if (bus.hasListeners('request:failed'))
bus.emit('request:failed', { name: correlation.route ?? 'pipeline', error, status, ...correlation });
}
}
}