feat: beta-hardening — routing, degradation, mesh gate, uploads, @header
Restructure first: split the two oversized files by cohesion (http.ts 449
→ http/{router,request,stream,ws,server,types}; app.ts 556 → app/{types,
introspect,index}), rename cryptic locals, JSDoc the public API, and
extract helpers so no function exceeds the complexity gate (createApp
187 → <15, listen 113 → 6). Public import paths are unchanged (barrels).
On that structure, five features that close the biggest gaps vs
Express/Fastify/Nest for a comparable beta:
- routing: `:name*` catch-all, specificity precedence (static ▸ param ▸
catch-all, not registration order), and 405 + Allow when a path exists
under a different method (was 404)
- visible degradation: optional providers that fail boot are summarized on
listen() and queryable via app.degraded(), instead of a silent warn
- mesh is alpha — gated behind `experimental: true`; createApp throws if
`mesh` is configured without it
- multipart moves to the optional `busboy` peer dependency (clear 501 when
absent), keeping the core at one runtime dependency
- `@header('name')` as a singular alias of `@headers`
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
42 files changed
+2619
-1170
No files matched your search
@@ -0,0 +1,14 @@
|
||||
// Public surface of the HTTP module. Internal helpers (request parsing, streaming,
|
||||
// ws upgrade) live in sibling files and are composed by ./server.
|
||||
export type {
|
||||
RequestLimits,
|
||||
HttpOptions,
|
||||
RouteHandler,
|
||||
RouteDef,
|
||||
MatchedRoute,
|
||||
WsOpenCtx,
|
||||
WsRouteDef,
|
||||
MeshControl,
|
||||
} from './types';
|
||||
export { matchPattern, matchRoute, parseQuery } from './router';
|
||||
export { createHttpServer } from './server';
|
||||
@@ -0,0 +1,42 @@
|
||||
import http from 'http';
|
||||
import { HttpError } from '../signals';
|
||||
|
||||
/** Reads the full request body, enforcing the max-bytes ceiling (throws 413 if exceeded). */
|
||||
export async function readBody(req: http.IncomingMessage, maxBodyBytes: number): Promise<Buffer | undefined> {
|
||||
const chunks: Buffer[] = [];
|
||||
let total = 0;
|
||||
|
||||
for await (const chunk of req) {
|
||||
total += (chunk as Buffer).length;
|
||||
if (total > maxBodyBytes) throw new HttpError(413, 'Payload Too Large');
|
||||
chunks.push(chunk as Buffer);
|
||||
}
|
||||
|
||||
return chunks.length === 0 ? undefined : Buffer.concat(chunks);
|
||||
}
|
||||
|
||||
/** Returns the first comma-separated token of a header value (handles array-valued headers). */
|
||||
function firstToken(value: string | string[] | undefined): string | undefined {
|
||||
const first = Array.isArray(value) ? value[0] : value;
|
||||
return first?.split(',')[0].trim();
|
||||
}
|
||||
|
||||
/** Determines whether the request arrived over HTTPS, honoring `x-forwarded-proto` when proxy is trusted. */
|
||||
export function deriveSecure(req: http.IncomingMessage, trustProxy: boolean): boolean {
|
||||
if (trustProxy) {
|
||||
const proto = firstToken(req.headers['x-forwarded-proto']);
|
||||
if (proto) return proto === 'https';
|
||||
}
|
||||
|
||||
return (req.socket as any).encrypted === true;
|
||||
}
|
||||
|
||||
/** Resolves the client IP, honoring `x-forwarded-for` when proxy is trusted. */
|
||||
export function deriveIp(req: http.IncomingMessage, trustProxy: boolean): string {
|
||||
if (trustProxy) {
|
||||
const forwarded = firstToken(req.headers['x-forwarded-for']);
|
||||
if (forwarded) return forwarded;
|
||||
}
|
||||
|
||||
return req.socket.remoteAddress ?? '';
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import type { RouteDef, MatchedRoute } from './types';
|
||||
|
||||
/**
|
||||
* Matches a route pattern against a request path. Supports static segments, `:param` (one segment),
|
||||
* and a trailing `:name*` catch-all that captures the rest of the path (slashes included) into `params.name`.
|
||||
* @returns Extracted params (decoded) when the path matches, otherwise undefined.
|
||||
*/
|
||||
export function matchPattern(pattern: string, path: string): Record<string, string> | undefined {
|
||||
const pathSegs = path.split('/').filter(Boolean);
|
||||
const patternSegs = pattern.split('/').filter(Boolean);
|
||||
const params: Record<string, string> = {};
|
||||
|
||||
for (let i = 0; i < patternSegs.length; i++) {
|
||||
const seg = patternSegs[i];
|
||||
|
||||
// Trailing catch-all: capture every remaining segment (possibly none) as one decoded value.
|
||||
if (seg.startsWith(':') && seg.endsWith('*')) {
|
||||
params[seg.slice(1, -1)] = pathSegs.slice(i).map(decodeURIComponent).join('/');
|
||||
return params;
|
||||
}
|
||||
|
||||
if (i >= pathSegs.length) return undefined; // pattern longer than path
|
||||
|
||||
if (seg.startsWith(':')) params[seg.slice(1)] = decodeURIComponent(pathSegs[i]);
|
||||
else if (seg !== pathSegs[i]) return undefined;
|
||||
}
|
||||
|
||||
// No catch-all consumed the tail, so the lengths must match exactly.
|
||||
return patternSegs.length === pathSegs.length ? params : undefined;
|
||||
}
|
||||
|
||||
/** Splits a pattern into its fixed-prefix segment kinds (2 = static, 1 = param) and whether it ends in a catch-all. */
|
||||
function segScores(pattern: string): { catchAll: boolean; kinds: number[] } {
|
||||
const kinds: number[] = [];
|
||||
|
||||
for (const seg of pattern.split('/').filter(Boolean)) {
|
||||
if (seg.startsWith(':') && seg.endsWith('*')) return { catchAll: true, kinds };
|
||||
kinds.push(seg.startsWith(':') ? 1 : 2);
|
||||
}
|
||||
|
||||
return { catchAll: false, kinds };
|
||||
}
|
||||
|
||||
/** Orders two matching patterns by specificity: exact beats catch-all, then static beats param, then longer wins. */
|
||||
function moreSpecific(a: string, b: string): number {
|
||||
const scoreA = segScores(a);
|
||||
const scoreB = segScores(b);
|
||||
if (scoreA.catchAll !== scoreB.catchAll) return scoreA.catchAll ? -1 : 1;
|
||||
const length = Math.max(scoreA.kinds.length, scoreB.kinds.length);
|
||||
|
||||
for (let i = 0; i < length; i++) {
|
||||
const kindA = scoreA.kinds[i] ?? -1;
|
||||
const kindB = scoreB.kinds[i] ?? -1;
|
||||
if (kindA !== kindB) return kindA - kindB;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/** Finds the most specific route matching both method and path (static > param > catch-all; ties keep registration order). */
|
||||
export function matchRoute(routes: RouteDef[], method: string, path: string): MatchedRoute | undefined {
|
||||
let best: MatchedRoute | undefined;
|
||||
let bestPattern = '';
|
||||
|
||||
for (const route of routes) {
|
||||
if (route.method !== method) continue;
|
||||
const params = matchPattern(route.pattern, path);
|
||||
if (!params) continue;
|
||||
|
||||
if (!best || moreSpecific(route.pattern, bestPattern) > 0) {
|
||||
best = { params, def: route };
|
||||
bestPattern = route.pattern;
|
||||
}
|
||||
}
|
||||
|
||||
return best;
|
||||
}
|
||||
|
||||
/** Lists the distinct HTTP methods whose pattern matches the path — used to build a 405 `Allow` header. */
|
||||
export function allowedMethods(routes: RouteDef[], path: string): string[] {
|
||||
const methods = new Set<string>();
|
||||
for (const route of routes) if (matchPattern(route.pattern, path)) methods.add(route.method);
|
||||
return [...methods];
|
||||
}
|
||||
|
||||
/** Parses a URL's query string into a flat string map (last value wins for repeated keys). */
|
||||
export function parseQuery(url: string): Record<string, string> {
|
||||
const queryString = url.split('?')[1] ?? '';
|
||||
const out: Record<string, string> = {};
|
||||
for (const [key, value] of new URLSearchParams(queryString)) out[key] = value;
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
import http from 'http';
|
||||
import https from 'https';
|
||||
import { errorToResponse } from '../transformers';
|
||||
import { isHttpError } from '../signals';
|
||||
import { isStreamResult, type PipelineResult, type ResponseShape } from '../pipeline';
|
||||
import type { Bus } from '../bus';
|
||||
import { buildSecurityHeaders, mergeVary, resolveCors, corsPreflightHeaders } from '../security';
|
||||
import { parseMultipart, extractBoundary, collapseDuplicates } from '../multipart';
|
||||
import { matchRoute, allowedMethods, parseQuery } from './router';
|
||||
import { readBody, deriveSecure, deriveIp } from './request';
|
||||
import { pickEncoder, pipeStream } from './stream';
|
||||
import { attachWs } from './ws';
|
||||
import type { RouteDef, WsRouteDef, MatchedRoute, MeshControl, HttpOptions } from './types';
|
||||
|
||||
interface HandlerConfig {
|
||||
routes: RouteDef[];
|
||||
bus?: Bus;
|
||||
opts?: HttpOptions;
|
||||
maxBody: number;
|
||||
trustProxy: boolean;
|
||||
}
|
||||
|
||||
/** A ready-to-send error response produced while acquiring the request body. */
|
||||
type BodyFailure = { fail: { status: number; headers: Record<string, string>; body: string } };
|
||||
|
||||
/**
|
||||
* Builds an HTTP/HTTPS server that routes requests, parses bodies, streams results, and handles WebSocket upgrades.
|
||||
* @param routes HTTP route definitions.
|
||||
* @param wsRoutes WebSocket route definitions (requires the optional `ws` peer dependency).
|
||||
* @param bus Optional event bus for stream lifecycle events.
|
||||
* @param meshControl Optional mesh gateway hook for a reserved upgrade path.
|
||||
* @param opts Limits, TLS, security, CORS, and body-parsing options.
|
||||
*/
|
||||
export function createHttpServer(
|
||||
routes: RouteDef[],
|
||||
wsRoutes: WsRouteDef[] = [],
|
||||
bus?: Bus,
|
||||
meshControl?: MeshControl,
|
||||
opts?: HttpOptions,
|
||||
): http.Server {
|
||||
const maxBody = opts?.limits?.maxBodyBytes ?? 1_000_000;
|
||||
const trustProxy = opts?.trustProxy ?? false;
|
||||
const handler = createRequestHandler({ routes, bus, opts, maxBody, trustProxy });
|
||||
|
||||
// runtime-compatible; only @types differ (https.Server lacks the http-only timeout props)
|
||||
const server: http.Server = (opts?.tls
|
||||
? https.createServer(opts.tls as https.ServerOptions, handler)
|
||||
: http.createServer(handler)) as unknown as http.Server;
|
||||
server.requestTimeout = opts?.limits?.requestTimeoutMs ?? 30_000;
|
||||
server.headersTimeout = opts?.limits?.headersTimeoutMs ?? 10_000;
|
||||
server.keepAliveTimeout = opts?.limits?.keepAliveTimeoutMs ?? 5_000;
|
||||
attachWs(server, wsRoutes, bus, meshControl, opts?.streams);
|
||||
return server;
|
||||
}
|
||||
|
||||
/** Builds the request listener: security/CORS headers, routing, body parsing, then buffered or streamed response. */
|
||||
function createRequestHandler(cfg: HandlerConfig) {
|
||||
const { routes, bus, opts, maxBody, trustProxy } = cfg;
|
||||
|
||||
return async (req: http.IncomingMessage, res: http.ServerResponse): Promise<void> => {
|
||||
const url = req.url ?? '/';
|
||||
const path = url.split('?')[0];
|
||||
// Install the security-header patch BEFORE any routing/response so every path
|
||||
// (200, 404, error, stream) writes headers through the same patched writeHead.
|
||||
const secure = deriveSecure(req, trustProxy);
|
||||
const injected: Record<string, string> = { ...buildSecurityHeaders(opts?.security ?? true, secure) };
|
||||
patchResponseHeaders(res, injected);
|
||||
|
||||
// CORS is added to `injected` AFTER the patch is installed — the patch reads it lazily
|
||||
// by reference at writeHead time, so keys added here still land on every response.
|
||||
if (opts?.cors) Object.assign(injected, resolveCors(opts.cors, req));
|
||||
|
||||
if (opts?.cors && req.method === 'OPTIONS' && req.headers['access-control-request-method']) {
|
||||
res.writeHead(204, corsPreflightHeaders(opts.cors, req));
|
||||
res.end();
|
||||
return;
|
||||
}
|
||||
|
||||
const matched = matchRoute(routes, req.method ?? 'GET', path);
|
||||
|
||||
if (!matched) {
|
||||
// Path matches a route under a different method → 405 with Allow; otherwise 404.
|
||||
const allow = allowedMethods(routes, path);
|
||||
|
||||
if (allow.length) {
|
||||
res.writeHead(405, { 'content-type': 'application/json', allow: allow.join(', ') });
|
||||
res.end(JSON.stringify({ error: 'Method Not Allowed' }));
|
||||
return;
|
||||
}
|
||||
|
||||
res.writeHead(404, { 'content-type': 'application/json' });
|
||||
res.end(JSON.stringify({ error: 'Not Found' }));
|
||||
return;
|
||||
}
|
||||
|
||||
const acquired = await acquireBody(req, matched, opts, maxBody);
|
||||
|
||||
if ('fail' in acquired) {
|
||||
res.writeHead(acquired.fail.status, acquired.fail.headers);
|
||||
res.end(acquired.fail.body);
|
||||
return;
|
||||
}
|
||||
|
||||
let result: PipelineResult;
|
||||
|
||||
try {
|
||||
result = await matched.def.handler({
|
||||
method: req.method ?? 'GET',
|
||||
url,
|
||||
headers: req.headers,
|
||||
params: matched.params,
|
||||
query: parseQuery(url),
|
||||
body: acquired.body,
|
||||
protocol: secure ? 'https' : 'http',
|
||||
ip: deriveIp(req, trustProxy),
|
||||
});
|
||||
} catch (error) {
|
||||
result = errorToResponse(error);
|
||||
}
|
||||
|
||||
if (isStreamResult(result)) {
|
||||
const encoder = pickEncoder(matched.def.transport, String(req.headers.accept ?? ''));
|
||||
await pipeStream(res, result.stream, encoder, bus, matched.def.pattern, opts?.streams);
|
||||
return;
|
||||
}
|
||||
|
||||
const response: ResponseShape = result;
|
||||
res.writeHead(response.status, response.headers);
|
||||
res.end(response.body);
|
||||
};
|
||||
}
|
||||
|
||||
/** Reads and parses the request body, returning `{ body }` or a ready-to-send `{ fail }` error response. */
|
||||
async function acquireBody(
|
||||
req: http.IncomingMessage,
|
||||
matched: MatchedRoute,
|
||||
opts: HttpOptions | undefined,
|
||||
maxBody: number,
|
||||
): Promise<{ body: unknown } | BodyFailure> {
|
||||
let buf: Buffer | undefined;
|
||||
|
||||
try {
|
||||
buf = await readBody(req, maxBody);
|
||||
} catch (error) {
|
||||
const response = errorToResponse(error);
|
||||
return {
|
||||
fail: { status: response.status, headers: { ...response.headers, connection: 'close' }, body: response.body },
|
||||
};
|
||||
}
|
||||
|
||||
const contentType = String(req.headers['content-type'] ?? '');
|
||||
const duplicates = matched.def.bodyDuplicates ?? opts?.bodyDuplicates ?? 'last';
|
||||
const parsed = await parseRequestBody(buf, contentType, duplicates, opts?.limits?.maxParts ?? 1000);
|
||||
|
||||
if ('error' in parsed) {
|
||||
return {
|
||||
fail: {
|
||||
status: parsed.status ?? 400,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ error: parsed.error }),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
return { body: parsed.body };
|
||||
}
|
||||
|
||||
/**
|
||||
* Monkey-patches `res.writeHead` so injected (security/CORS) headers are authoritative on every response.
|
||||
* Handler headers that case-insensitively collide with an injected key are dropped; `Vary` is merged.
|
||||
* Reads `injected` by reference, so CORS keys added after installation still land.
|
||||
*/
|
||||
function patchResponseHeaders(res: http.ServerResponse, injected: Record<string, string>): void {
|
||||
const origWriteHead = res.writeHead.bind(res);
|
||||
|
||||
(res as any).writeHead = (status: number, arg2?: any, arg3?: any) => {
|
||||
// normalize (statusMessage?, headers?) overloads
|
||||
const handlerHeaders = (typeof arg2 === 'string' ? arg3 : arg2) as Record<string, any> | undefined;
|
||||
const merged: Record<string, any> = {};
|
||||
const injectedLower = new Set(Object.keys(injected).map((key) => key.toLowerCase()));
|
||||
let handlerVary: string | undefined;
|
||||
|
||||
if (handlerHeaders)
|
||||
for (const key of Object.keys(handlerHeaders)) {
|
||||
const lowerKey = key.toLowerCase();
|
||||
|
||||
if (lowerKey === 'vary') {
|
||||
handlerVary = handlerHeaders[key];
|
||||
continue;
|
||||
} // merged separately below
|
||||
|
||||
if (!injectedLower.has(lowerKey)) merged[key] = handlerHeaders[key];
|
||||
}
|
||||
|
||||
Object.assign(merged, injected);
|
||||
if (injected['vary']) merged['vary'] = mergeVary(handlerVary, injected['vary']);
|
||||
else if (handlerVary !== undefined) merged['vary'] = handlerVary; // preserve handler Vary when no CORS
|
||||
return typeof arg2 === 'string' ? origWriteHead(status, arg2, merged) : origWriteHead(status, merged);
|
||||
};
|
||||
}
|
||||
|
||||
/** Parse outcome: the decoded body, or an error message plus the status to send (400 unless set). */
|
||||
type ParseResult = { body: unknown } | { error: string; status?: number };
|
||||
|
||||
/**
|
||||
* Parses a raw request body by content type (JSON, urlencoded, multipart, or plain text).
|
||||
* @returns `{ body }` on success, or `{ error, status? }` on malformed input / missing multipart support.
|
||||
*/
|
||||
async function parseRequestBody(
|
||||
buf: Buffer | undefined,
|
||||
contentType: string,
|
||||
duplicates: 'array' | 'last',
|
||||
maxParts: number,
|
||||
): Promise<ParseResult> {
|
||||
if (buf !== undefined && contentType.includes('application/json')) {
|
||||
try {
|
||||
return { body: JSON.parse(buf.toString('utf8')) };
|
||||
} catch {
|
||||
return { error: 'Invalid JSON body' };
|
||||
}
|
||||
}
|
||||
|
||||
if (buf !== undefined && contentType.includes('application/x-www-form-urlencoded')) {
|
||||
return { body: collapseDuplicates(new URLSearchParams(buf.toString('utf8')), duplicates) };
|
||||
}
|
||||
|
||||
if (buf !== undefined && contentType.includes('multipart/form-data')) {
|
||||
const boundary = extractBoundary(contentType);
|
||||
if (!boundary) return { error: 'Invalid multipart body' };
|
||||
|
||||
try {
|
||||
return { body: await parseMultipart(buf, boundary, { maxParts, duplicates }) };
|
||||
} catch (error) {
|
||||
// HttpError = the busboy peer dep is missing (501); anything else = malformed input (400).
|
||||
if (isHttpError(error)) return { error: error.message, status: error.status };
|
||||
return { error: 'Invalid multipart body' };
|
||||
}
|
||||
}
|
||||
|
||||
const text = buf?.toString('utf8');
|
||||
return { body: text === '' ? undefined : text };
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import http from 'http';
|
||||
import { once } from 'events';
|
||||
import { sseEncoder, ndjsonEncoder, StreamEncoder } from '../encoders';
|
||||
import type { Transport } from '../metadata';
|
||||
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`. */
|
||||
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;
|
||||
}
|
||||
|
||||
/** Pipes an async-iterable result to the response as an HTTP stream, with keep-alive pings and backpressure handling. */
|
||||
export async function pipeStream(
|
||||
res: http.ServerResponse,
|
||||
stream: AsyncIterable<unknown>,
|
||||
encoder: StreamEncoder,
|
||||
bus?: Bus,
|
||||
name = '',
|
||||
streams?: Set<() => void>,
|
||||
): Promise<void> {
|
||||
res.writeHead(200, encoder.headers);
|
||||
res.flushHeaders(); // establish the stream immediately so idle-until-event sources (e.g. subscriptions) don't deadlock clients awaiting headers
|
||||
bus?.emit('stream:open', { name });
|
||||
const iterator = stream[Symbol.asyncIterator]();
|
||||
let ping: ReturnType<typeof setInterval> | undefined;
|
||||
|
||||
if (encoder.ping) {
|
||||
ping = setInterval(() => res.write(encoder.ping!()), PING_MS);
|
||||
ping.unref?.();
|
||||
}
|
||||
|
||||
const stop = () => {
|
||||
if (ping) clearInterval(ping);
|
||||
void Promise.resolve(iterator.return?.()).catch(() => {});
|
||||
};
|
||||
|
||||
res.on('close', stop);
|
||||
|
||||
const closer = () => {
|
||||
try {
|
||||
res.destroy();
|
||||
} catch {
|
||||
/* */
|
||||
}
|
||||
};
|
||||
|
||||
streams?.add(closer);
|
||||
const onClose = once(res, 'close');
|
||||
|
||||
try {
|
||||
while (true) {
|
||||
const { value, done } = await iterator.next();
|
||||
if (done) break;
|
||||
|
||||
if (!res.write(encoder.encode(value))) {
|
||||
await Promise.race([once(res, 'drain'), onClose]);
|
||||
if (res.destroyed) break; // let finally clean up
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
bus?.emit('stream:error', { name, error: err });
|
||||
const frame = encoder.encodeError(err);
|
||||
if (frame && !res.writableEnded) res.write(frame);
|
||||
} finally {
|
||||
if (ping) clearInterval(ping);
|
||||
streams?.delete(closer);
|
||||
if (!res.writableEnded && !res.destroyed) res.end();
|
||||
bus?.emit('stream:close', { name });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import http from 'http';
|
||||
import type { Transport } from '../metadata';
|
||||
import type { PipelineResult } from '../pipeline';
|
||||
import type { TlsOptions, SecurityOptions, CorsOptions } from '../security';
|
||||
|
||||
/** Per-request size and timeout ceilings applied by the server. */
|
||||
export interface RequestLimits {
|
||||
maxBodyBytes?: number; // default 1_000_000
|
||||
requestTimeoutMs?: number; // default 30_000
|
||||
headersTimeoutMs?: number; // default 10_000
|
||||
keepAliveTimeoutMs?: number; // default 5_000
|
||||
maxParts?: number; // default 1000
|
||||
}
|
||||
|
||||
/** Options controlling server construction: limits, TLS, proxy trust, security headers, CORS, and body parsing. */
|
||||
export interface HttpOptions {
|
||||
limits?: RequestLimits;
|
||||
streams?: Set<() => void>;
|
||||
tls?: TlsOptions;
|
||||
trustProxy?: boolean;
|
||||
security?: boolean | SecurityOptions;
|
||||
cors?: CorsOptions;
|
||||
bodyDuplicates?: 'array' | 'last';
|
||||
}
|
||||
|
||||
/** Handler for a matched HTTP route; receives a normalized request and resolves to a pipeline result. */
|
||||
export type RouteHandler = (req: {
|
||||
method: string;
|
||||
url: string;
|
||||
headers: Record<string, string | string[] | undefined>;
|
||||
params: Record<string, string>;
|
||||
query: Record<string, string>;
|
||||
body: unknown;
|
||||
protocol: 'http' | 'https';
|
||||
ip: string;
|
||||
}) => Promise<PipelineResult>;
|
||||
|
||||
/** A registered HTTP route: method, path pattern, streaming transport, and handler. */
|
||||
export interface RouteDef {
|
||||
method: string;
|
||||
pattern: string;
|
||||
transport: Transport;
|
||||
handler: RouteHandler;
|
||||
bodyDuplicates?: 'array' | 'last';
|
||||
}
|
||||
|
||||
/** Result of matching a request path against a route: extracted params plus the matched definition. */
|
||||
export interface MatchedRoute {
|
||||
params: Record<string, string>;
|
||||
def: RouteDef;
|
||||
}
|
||||
|
||||
/** Context passed to a WebSocket route's `open`: path params, inbound message stream, abort signal, and raw request. */
|
||||
export interface WsOpenCtx {
|
||||
params: Record<string, string>;
|
||||
inbound: AsyncIterable<unknown>;
|
||||
abort: AbortSignal;
|
||||
req: http.IncomingMessage;
|
||||
}
|
||||
|
||||
/** A registered WebSocket route: path pattern and an `open` that returns the outbound message stream. */
|
||||
export interface WsRouteDef {
|
||||
pattern: string;
|
||||
open: (ctx: WsOpenCtx) => Promise<AsyncIterable<unknown>>;
|
||||
}
|
||||
|
||||
/** Hook for a mesh gateway to take over WebSocket upgrades on a fixed path. */
|
||||
export interface MeshControl {
|
||||
path: string;
|
||||
handle(ws: any, req: http.IncomingMessage): void;
|
||||
}
|
||||
+180
@@ -0,0 +1,180 @@
|
||||
import http from 'http';
|
||||
import { channel } from '../channel';
|
||||
import { isHttpError } from '../signals';
|
||||
import type { Bus } from '../bus';
|
||||
import { matchPattern } from './router';
|
||||
import type { WsRouteDef, MeshControl } from './types';
|
||||
|
||||
/** Lazily loads the optional `ws` peer dependency's `WebSocketServer`, or null when it is not installed. */
|
||||
function loadWss(): any | null {
|
||||
try {
|
||||
// `ws` is an OPTIONAL peer dependency: lazy-required so installs without WebSocket
|
||||
// support don't fail. When absent this throws and we fall back to null (501 on upgrade).
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
return require('ws').WebSocketServer;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Writes a 501 Not Implemented status to the raw socket and destroys it. */
|
||||
function reject501(socket: any): void {
|
||||
socket.write('HTTP/1.1 501 Not Implemented\r\n\r\n');
|
||||
socket.destroy();
|
||||
}
|
||||
|
||||
/** Handles the mesh-control upgrade path; returns true when the request was for the mesh control endpoint. */
|
||||
function handleMeshUpgrade(
|
||||
wss: any,
|
||||
meshControl: MeshControl,
|
||||
path: string,
|
||||
req: http.IncomingMessage,
|
||||
socket: any,
|
||||
head: Buffer,
|
||||
): boolean {
|
||||
if (path !== meshControl.path) return false;
|
||||
|
||||
if (!wss) {
|
||||
reject501(socket);
|
||||
return true;
|
||||
}
|
||||
|
||||
wss.handleUpgrade(req, socket, head, (ws: any) => meshControl.handle(ws, req));
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Finds the first ws route whose pattern matches `path`, capturing its params. */
|
||||
function matchWsRoute(
|
||||
wsRoutes: WsRouteDef[],
|
||||
path: string,
|
||||
): { def: WsRouteDef; params: Record<string, string> | undefined } | undefined {
|
||||
return wsRoutes
|
||||
.map((candidate) => ({ def: candidate, params: matchPattern(candidate.pattern, path) }))
|
||||
.find((entry) => entry.params);
|
||||
}
|
||||
|
||||
/** Wires inbound message/close/error events into a channel and returns the channel plus its abort controller. */
|
||||
function wireInbound(ws: any): { inbound: ReturnType<typeof channel<unknown>>; abortController: AbortController } {
|
||||
const inbound = channel<unknown>();
|
||||
const abortController = new AbortController();
|
||||
ws.on('message', (data: Buffer) => inbound.push(data.toString()));
|
||||
ws.on('close', () => {
|
||||
inbound.close();
|
||||
abortController.abort();
|
||||
});
|
||||
ws.on('error', (err: unknown) => inbound.fail(err));
|
||||
|
||||
return { inbound, abortController };
|
||||
}
|
||||
|
||||
/** Registers the connection with the stream registry so it can be force-closed on shutdown. */
|
||||
function trackConnection(ws: any, streams?: Set<() => void>): void {
|
||||
const closer = () => {
|
||||
try {
|
||||
(ws.terminate ?? ws.close).call(ws);
|
||||
} catch {
|
||||
/* */
|
||||
}
|
||||
};
|
||||
|
||||
streams?.add(closer);
|
||||
ws.on('close', () => streams?.delete(closer));
|
||||
}
|
||||
|
||||
/** Drives the outbound async iterator, sending each yielded value over the socket until done or closed. */
|
||||
async function pumpOutbound(ws: any, iterator: AsyncIterator<unknown>): Promise<void> {
|
||||
while (true) {
|
||||
const { value, done } = await iterator.next();
|
||||
if (done) break;
|
||||
if (ws.readyState !== 1) break; // 1 = OPEN; stop if socket gone
|
||||
ws.send(typeof value === 'string' ? value : JSON.stringify(value));
|
||||
}
|
||||
|
||||
try {
|
||||
ws.close();
|
||||
} catch {
|
||||
/* already closed */
|
||||
}
|
||||
}
|
||||
|
||||
/** Closes the socket with the appropriate code after an outbound error (4000+status for HTTP errors, 1011 otherwise). */
|
||||
function closeOnError(ws: any, err: unknown): void {
|
||||
if (isHttpError(err)) {
|
||||
const reason = Buffer.from(String(err.message)).subarray(0, 120).toString();
|
||||
|
||||
try {
|
||||
ws.close(4000 + err.status, reason);
|
||||
} catch {
|
||||
/* already closed */
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
ws.close(1011);
|
||||
} catch {
|
||||
/* already closed */
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Runs the full per-connection lifecycle: inbound wiring, opening the route stream, and pumping outbound values. */
|
||||
async function openWsConnection(
|
||||
ws: any,
|
||||
route: { def: WsRouteDef; params: Record<string, string> | undefined },
|
||||
req: http.IncomingMessage,
|
||||
bus?: Bus,
|
||||
streams?: Set<() => void>,
|
||||
): Promise<void> {
|
||||
trackConnection(ws, streams);
|
||||
const { inbound, abortController } = wireInbound(ws);
|
||||
|
||||
const name = route.def.pattern;
|
||||
let iterator: AsyncIterator<unknown> | undefined;
|
||||
ws.on('close', () => {
|
||||
void Promise.resolve(iterator?.return?.()).catch(() => {});
|
||||
}); // force-cancel outbound
|
||||
bus?.emit('stream:open', { name });
|
||||
|
||||
try {
|
||||
const outbound = await route.def.open({ params: route.params!, inbound, abort: abortController.signal, req });
|
||||
iterator = outbound[Symbol.asyncIterator]();
|
||||
await pumpOutbound(ws, iterator);
|
||||
} catch (err) {
|
||||
bus?.emit('stream:error', { name, error: err });
|
||||
closeOnError(ws, err);
|
||||
} finally {
|
||||
abortController.abort();
|
||||
bus?.emit('stream:close', { name });
|
||||
}
|
||||
}
|
||||
|
||||
/** Attaches WebSocket upgrade handling to the server: routes to `wsRoutes` or a mesh control path. */
|
||||
export function attachWs(
|
||||
server: http.Server,
|
||||
wsRoutes: WsRouteDef[],
|
||||
bus?: Bus,
|
||||
meshControl?: MeshControl,
|
||||
streams?: Set<() => void>,
|
||||
): void {
|
||||
if (wsRoutes.length === 0 && !meshControl) return;
|
||||
const WebSocketServer = loadWss();
|
||||
const wss = WebSocketServer ? new WebSocketServer({ noServer: true }) : null;
|
||||
server.on('upgrade', (req, socket, head) => {
|
||||
const path = (req.url ?? '/').split('?')[0];
|
||||
|
||||
if (meshControl && handleMeshUpgrade(wss, meshControl, path, req, socket, head)) return;
|
||||
|
||||
const route = matchWsRoute(wsRoutes, path);
|
||||
|
||||
if (!route) {
|
||||
socket.destroy();
|
||||
return;
|
||||
}
|
||||
|
||||
if (!wss) {
|
||||
reject501(socket);
|
||||
return;
|
||||
}
|
||||
|
||||
wss.handleUpgrade(req, socket, head, (ws: any) => openWsConnection(ws, route, req, bus, streams));
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user