refactor: close type holes on the transport and error axes

- OpenApiRoute.transport was typed `string`, so the compiler could not check the
  transport branching at all. Type it Transport and key the documented 200 off a
  Record, so a new transport fails the build instead of silently going undocumented.
- pickEncoder fell through to ndjson for unknown transports; make the mapping
  exhaustive so a new transport cannot inherit the wrong wire format by accident.
- HttpError carries optional headers, removing the instanceof Redirect special case
  that coupled the error renderer to one subclass. Custom errors needing headers
  (retry-after, etag) no longer require touching transformers.
- Drop the module-global connSeq in mesh/link: `pending` is already per-connection,
  so a per-link counter suffices and connection ids stop depending on test order.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-07-15 14:37:03 -05:00
1 parent 9421b102d9
commit d56eeafcd8
5 files changed
+55 -36

No files matched your search

+18 -4
View File
@@ -6,11 +6,25 @@ import type { Bus } from '../bus';
const PING_MS = 15_000; 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<Transport, ((accept: string) => 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 { export function pickEncoder(transport: Transport, accept: string): StreamEncoder {
if (transport === 'sse') return sseEncoder; const pick = STREAM_ENCODERS[transport];
if (transport === 'ndjson') return ndjsonEncoder; if (!pick) throw new Error(`transport '${transport}' does not produce an HTTP stream`);
return accept.includes('text/event-stream') ? sseEncoder : ndjsonEncoder;
return pick(accept);
} }
/** Pipes an async-iterable result to the response as an HTTP stream, with keep-alive pings and backpressure handling. */ /** Pipes an async-iterable result to the response as an HTTP stream, with keep-alive pings and backpressure handling. */
+5 -12
View File
@@ -2,8 +2,6 @@ import type { Bus } from '../bus';
import { HttpError } from '../signals'; import { HttpError } from '../signals';
import { encode, decode, type Manifest, type RequestEnvelope, type Frame } from './protocol'; 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(). */ /** Client handle to a remote mesh server: its manifest, an RPC caller, and a close(). */
export interface Link { export interface Link {
manifest: Manifest; manifest: Manifest;
@@ -56,19 +54,15 @@ function sendRpc(
} }
/** Assemble the client-facing Link once the manifest arrives. */ /** Assemble the client-facing Link once the manifest arrives. */
function buildLink( function buildLink(ws: any, pending: Map<string, PendingEntry>, manifest: Manifest, timeoutMs: number): Link {
ws: any, // ids only need to be unique within this link: `pending` is per-connection, so a
pending: Map<string, PendingEntry>, // per-link counter suffices (no module-global sequence, no test-order coupling).
manifest: Manifest,
connId: string,
timeoutMs: number,
): Link {
let counter = 0; let counter = 0;
return { return {
manifest, manifest,
rpc(kind, name, ctx) { rpc(kind, name, ctx) {
const id = `${connId}:${counter++}`; const id = String(counter++);
return sendRpc(ws, pending, id, kind, name, ctx, timeoutMs); 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 = loadWs();
const ws = new WS(args.url); const ws = new WS(args.url);
const pending = new Map<string, PendingEntry>(); const pending = new Map<string, PendingEntry>();
const connId = `c${connSeq++}`;
let manifest: Manifest | undefined; let manifest: Manifest | undefined;
return new Promise<Link>((resolve, reject) => { return new Promise<Link>((resolve, reject) => {
@@ -134,7 +127,7 @@ export function connectLink(args: { url: string; secret: string; timeoutMs?: num
manifest = { scopes: frame.scopes, routes: frame.routes }; manifest = { scopes: frame.scopes, routes: frame.routes };
clearTimeout(connectTimer); clearTimeout(connectTimer);
args.bus?.emit('mesh:connect', { name: args.url }); args.bus?.emit('mesh:connect', { name: args.url });
resolve(buildLink(ws, pending, manifest, connId, timeoutMs)); resolve(buildLink(ws, pending, manifest, timeoutMs));
return; return;
} }
+23 -15
View File
@@ -1,10 +1,11 @@
import type { ArgSpec } from './params'; import type { ArgSpec } from './params';
import type { Transport } from './metadata';
/** Minimal per-route input the OpenAPI projection needs, derived from a route plan. */ /** Minimal per-route input the OpenAPI projection needs, derived from a route plan. */
export interface OpenApiRoute { export interface OpenApiRoute {
method: string; method: string;
pattern: string; pattern: string;
transport: string; transport: Transport;
args: ArgSpec[]; args: ArgSpec[];
} }
@@ -55,17 +56,23 @@ function argParams(args: ArgSpec[]): Parameter[] {
return params; return params;
} }
/** The success/error responses documented for a route, keyed by transport and whether any input is validated. */ /**
function responses(route: OpenApiRoute): Record<string, unknown> { * The documented `200` per transport. `ws` is absent by construction — ws routes are not
const result: Record<string, unknown> = {}; * 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<Transport, 'ws'>;
if (route.transport === 'sse') { const TRANSPORT_OK: Record<HttpTransport, Record<string, unknown>> = {
result['200'] = { description: 'Event stream', content: { 'text/event-stream': {} } }; buffer: { description: 'OK', content: { 'application/json': { schema: {} } } },
} else if (route.transport === 'ndjson' || route.transport === 'negotiate') { sse: { description: 'Event stream', content: { 'text/event-stream': {} } },
result['200'] = { description: 'Stream', content: { 'application/x-ndjson': {} } }; ndjson: { description: 'Stream', content: { 'application/x-ndjson': {} } },
} else { negotiate: { description: 'Stream', content: { 'application/x-ndjson': {} } },
result['200'] = { description: 'OK', content: { 'application/json': { schema: {} } } }; };
}
/** The success/error responses documented for a route, keyed by transport and whether any input is validated. */
function responses(route: OpenApiRoute, transport: HttpTransport): Record<string, unknown> {
const result: Record<string, unknown> = { '200': TRANSPORT_OK[transport] };
if (route.args.some((arg) => arg.schema)) result['422'] = { description: 'Validation failed' }; if (route.args.some((arg) => arg.schema)) result['422'] = { description: 'Validation failed' };
result['500'] = { description: 'Internal Server Error' }; result['500'] = { description: 'Internal Server Error' };
@@ -73,9 +80,9 @@ function responses(route: OpenApiRoute): Record<string, unknown> {
} }
/** Builds a single OpenAPI operation object for a route. */ /** Builds a single OpenAPI operation object for a route. */
function operation(route: OpenApiRoute): Record<string, unknown> { function operation(route: OpenApiRoute, transport: HttpTransport): Record<string, unknown> {
const parameters = [...pathParams(route.pattern), ...argParams(route.args)]; const parameters = [...pathParams(route.pattern), ...argParams(route.args)];
const op: Record<string, unknown> = { responses: responses(route) }; const op: Record<string, unknown> = { responses: responses(route, transport) };
if (parameters.length) op.parameters = parameters; if (parameters.length) op.parameters = parameters;
@@ -95,9 +102,10 @@ export function buildOpenApi(routes: OpenApiRoute[], info?: OpenApiInfo): OpenAp
const paths: Record<string, Record<string, unknown>> = {}; const paths: Record<string, Record<string, unknown>> = {};
for (const route of routes) { 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); const path = templatePath(route.pattern);
(paths[path] ??= {})[route.method.toLowerCase()] = operation(route); (paths[path] ??= {})[route.method.toLowerCase()] = operation(route, transport);
} }
return { return {
+7 -2
View File
@@ -1,11 +1,16 @@
import type { StandardIssue } from './standard-schema'; 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 { export class HttpError extends Error {
constructor( constructor(
readonly status: number, readonly status: number,
message?: string, message?: string,
readonly body?: unknown, readonly body?: unknown,
readonly headers?: Record<string, string>,
) { ) {
super(message ?? `HTTP ${status}`); super(message ?? `HTTP ${status}`);
this.name = new.target.name; this.name = new.target.name;
@@ -36,7 +41,7 @@ export class NotModified extends HttpError {
/** 302 redirect to `location`. */ /** 302 redirect to `location`. */
export class Redirect extends HttpError { export class Redirect extends HttpError {
constructor(readonly location: string) { constructor(readonly location: string) {
super(302); super(302, undefined, undefined, { location });
} }
} }
+2 -3
View File
@@ -1,4 +1,4 @@
import { isHttpError, Redirect, ValidationError } from './signals'; import { isHttpError, ValidationError } from './signals';
import type { TransformerFn } from './metadata'; import type { TransformerFn } from './metadata';
import { flattenPath } from './standard-schema'; import { flattenPath } from './standard-schema';
@@ -47,8 +47,7 @@ export function errorToResponse(error: unknown): ErrorResponse {
} }
if (isHttpError(error)) { if (isHttpError(error)) {
const headers: Record<string, string> = { 'content-type': 'application/json' }; const headers = { 'content-type': 'application/json', ...error.headers };
if (error instanceof Redirect) headers.location = error.location;
const payload = error.body !== undefined ? error.body : { error: error.message }; const payload = error.body !== undefined ? error.body : { error: error.message };
return { status: error.status, headers, body: JSON.stringify(payload) }; return { status: error.status, headers, body: JSON.stringify(payload) };
} }