diff --git a/src/http/stream.ts b/src/http/stream.ts index 9532fa2..f34783c 100644 --- a/src/http/stream.ts +++ b/src/http/stream.ts @@ -6,11 +6,25 @@ import type { Bus } from '../bus'; const PING_MS = 15_000; -/** Selects the stream encoder for a transport, falling back to the client's `Accept` header for `stream`. */ +/** + * Stream encoder per transport, or `null` for transports that never produce an HTTP stream. + * A new transport must add a row — the compiler fails until it does, so it can't silently + * inherit ndjson framing. + */ +const STREAM_ENCODERS: Record StreamEncoder) | null> = { + buffer: null, // a buffered handler returning a stream throws TransportMismatchError before reaching here + ws: null, // not an HTTP response; ws routes are served via upgrade, not handle() + sse: () => sseEncoder, + ndjson: () => ndjsonEncoder, + negotiate: (accept) => (accept.includes('text/event-stream') ? sseEncoder : ndjsonEncoder), +}; + +/** Selects the stream encoder for a transport, falling back to the client's `Accept` header for `negotiate`. */ export function pickEncoder(transport: Transport, accept: string): StreamEncoder { - if (transport === 'sse') return sseEncoder; - if (transport === 'ndjson') return ndjsonEncoder; - return accept.includes('text/event-stream') ? sseEncoder : ndjsonEncoder; + const pick = STREAM_ENCODERS[transport]; + if (!pick) throw new Error(`transport '${transport}' does not produce an HTTP stream`); + + return pick(accept); } /** Pipes an async-iterable result to the response as an HTTP stream, with keep-alive pings and backpressure handling. */ diff --git a/src/mesh/link.ts b/src/mesh/link.ts index 397364a..e946e65 100644 --- a/src/mesh/link.ts +++ b/src/mesh/link.ts @@ -2,8 +2,6 @@ import type { Bus } from '../bus'; import { HttpError } from '../signals'; import { encode, decode, type Manifest, type RequestEnvelope, type Frame } from './protocol'; -let connSeq = 0; // module-level: deterministic unique connection-id prefix (no Date.now/Math.random) - /** Client handle to a remote mesh server: its manifest, an RPC caller, and a close(). */ export interface Link { manifest: Manifest; @@ -56,19 +54,15 @@ function sendRpc( } /** Assemble the client-facing Link once the manifest arrives. */ -function buildLink( - ws: any, - pending: Map, - manifest: Manifest, - connId: string, - timeoutMs: number, -): Link { +function buildLink(ws: any, pending: Map, manifest: Manifest, timeoutMs: number): Link { + // ids only need to be unique within this link: `pending` is per-connection, so a + // per-link counter suffices (no module-global sequence, no test-order coupling). let counter = 0; return { manifest, rpc(kind, name, ctx) { - const id = `${connId}:${counter++}`; + const id = String(counter++); return sendRpc(ws, pending, id, kind, name, ctx, timeoutMs); }, @@ -103,7 +97,6 @@ export function connectLink(args: { url: string; secret: string; timeoutMs?: num const WS = loadWs(); const ws = new WS(args.url); const pending = new Map(); - const connId = `c${connSeq++}`; let manifest: Manifest | undefined; return new Promise((resolve, reject) => { @@ -134,7 +127,7 @@ export function connectLink(args: { url: string; secret: string; timeoutMs?: num manifest = { scopes: frame.scopes, routes: frame.routes }; clearTimeout(connectTimer); args.bus?.emit('mesh:connect', { name: args.url }); - resolve(buildLink(ws, pending, manifest, connId, timeoutMs)); + resolve(buildLink(ws, pending, manifest, timeoutMs)); return; } diff --git a/src/openapi.ts b/src/openapi.ts index 7eba251..4acf4f4 100644 --- a/src/openapi.ts +++ b/src/openapi.ts @@ -1,10 +1,11 @@ import type { ArgSpec } from './params'; +import type { Transport } from './metadata'; /** Minimal per-route input the OpenAPI projection needs, derived from a route plan. */ export interface OpenApiRoute { method: string; pattern: string; - transport: string; + transport: Transport; args: ArgSpec[]; } @@ -55,17 +56,23 @@ function argParams(args: ArgSpec[]): Parameter[] { return params; } -/** The success/error responses documented for a route, keyed by transport and whether any input is validated. */ -function responses(route: OpenApiRoute): Record { - const result: Record = {}; +/** + * The documented `200` per transport. `ws` is absent by construction — ws routes are not + * HTTP request/response and are filtered out before this runs. A new transport adds a row, + * and the compiler fails until it does. + */ +type HttpTransport = Exclude; - if (route.transport === 'sse') { - result['200'] = { description: 'Event stream', content: { 'text/event-stream': {} } }; - } else if (route.transport === 'ndjson' || route.transport === 'negotiate') { - result['200'] = { description: 'Stream', content: { 'application/x-ndjson': {} } }; - } else { - result['200'] = { description: 'OK', content: { 'application/json': { schema: {} } } }; - } +const TRANSPORT_OK: Record> = { + buffer: { description: 'OK', content: { 'application/json': { schema: {} } } }, + sse: { description: 'Event stream', content: { 'text/event-stream': {} } }, + ndjson: { description: 'Stream', content: { 'application/x-ndjson': {} } }, + negotiate: { description: 'Stream', content: { 'application/x-ndjson': {} } }, +}; + +/** The success/error responses documented for a route, keyed by transport and whether any input is validated. */ +function responses(route: OpenApiRoute, transport: HttpTransport): Record { + const result: Record = { '200': TRANSPORT_OK[transport] }; if (route.args.some((arg) => arg.schema)) result['422'] = { description: 'Validation failed' }; result['500'] = { description: 'Internal Server Error' }; @@ -73,9 +80,9 @@ function responses(route: OpenApiRoute): Record { } /** Builds a single OpenAPI operation object for a route. */ -function operation(route: OpenApiRoute): Record { +function operation(route: OpenApiRoute, transport: HttpTransport): Record { const parameters = [...pathParams(route.pattern), ...argParams(route.args)]; - const op: Record = { responses: responses(route) }; + const op: Record = { responses: responses(route, transport) }; if (parameters.length) op.parameters = parameters; @@ -95,9 +102,10 @@ export function buildOpenApi(routes: OpenApiRoute[], info?: OpenApiInfo): OpenAp const paths: Record> = {}; for (const route of routes) { - if (route.transport === 'ws') continue; // not an HTTP request/response + const transport = route.transport; + if (transport === 'ws') continue; // not an HTTP request/response; narrows to HttpTransport below const path = templatePath(route.pattern); - (paths[path] ??= {})[route.method.toLowerCase()] = operation(route); + (paths[path] ??= {})[route.method.toLowerCase()] = operation(route, transport); } return { diff --git a/src/signals.ts b/src/signals.ts index 29f5507..c34dfc1 100644 --- a/src/signals.ts +++ b/src/signals.ts @@ -1,11 +1,16 @@ import type { StandardIssue } from './standard-schema'; -/** Error carrying an HTTP status code and optional response body. Base of all signals. */ +/** + * Error carrying an HTTP status code and optional response body. Base of all signals. + * A subclass needing response headers (e.g. `location`, `retry-after`) sets `headers` + * rather than requiring a special case in the error renderer. + */ export class HttpError extends Error { constructor( readonly status: number, message?: string, readonly body?: unknown, + readonly headers?: Record, ) { super(message ?? `HTTP ${status}`); this.name = new.target.name; @@ -36,7 +41,7 @@ export class NotModified extends HttpError { /** 302 redirect to `location`. */ export class Redirect extends HttpError { constructor(readonly location: string) { - super(302); + super(302, undefined, undefined, { location }); } } diff --git a/src/transformers.ts b/src/transformers.ts index 328783b..eac5c81 100644 --- a/src/transformers.ts +++ b/src/transformers.ts @@ -1,4 +1,4 @@ -import { isHttpError, Redirect, ValidationError } from './signals'; +import { isHttpError, ValidationError } from './signals'; import type { TransformerFn } from './metadata'; import { flattenPath } from './standard-schema'; @@ -47,8 +47,7 @@ export function errorToResponse(error: unknown): ErrorResponse { } if (isHttpError(error)) { - const headers: Record = { 'content-type': 'application/json' }; - if (error instanceof Redirect) headers.location = error.location; + const headers = { 'content-type': 'application/json', ...error.headers }; const payload = error.body !== undefined ? error.body : { error: error.message }; return { status: error.status, headers, body: JSON.stringify(payload) }; }