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:
5 files changed
+55
-36
No files matched your search
+18
-4
@@ -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<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 {
|
||||
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. */
|
||||
|
||||
+5
-12
@@ -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<string, PendingEntry>,
|
||||
manifest: Manifest,
|
||||
connId: string,
|
||||
timeoutMs: number,
|
||||
): Link {
|
||||
function buildLink(ws: any, pending: Map<string, PendingEntry>, 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<string, PendingEntry>();
|
||||
const connId = `c${connSeq++}`;
|
||||
let manifest: Manifest | undefined;
|
||||
|
||||
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 };
|
||||
clearTimeout(connectTimer);
|
||||
args.bus?.emit('mesh:connect', { name: args.url });
|
||||
resolve(buildLink(ws, pending, manifest, connId, timeoutMs));
|
||||
resolve(buildLink(ws, pending, manifest, timeoutMs));
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
+23
-15
@@ -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<string, unknown> {
|
||||
const result: Record<string, unknown> = {};
|
||||
/**
|
||||
* 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<Transport, 'ws'>;
|
||||
|
||||
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<HttpTransport, Record<string, unknown>> = {
|
||||
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<string, unknown> {
|
||||
const result: Record<string, unknown> = { '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<string, unknown> {
|
||||
}
|
||||
|
||||
/** 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 op: Record<string, unknown> = { responses: responses(route) };
|
||||
const op: Record<string, unknown> = { 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<string, Record<string, unknown>> = {};
|
||||
|
||||
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 {
|
||||
|
||||
+7
-2
@@ -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<string, string>,
|
||||
) {
|
||||
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 });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+2
-3
@@ -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<string, string> = { '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) };
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user