Merge pull request 'Tier 1 for 26.9.0-beta.1: the four that block the cut' (#78) from beta/tier-1 into develop
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 13s
CI / build (push) Successful in 30s
CI / runtimes (deno) (push) Successful in 18s
CI / runtimes (edge) (push) Successful in 14s

This commit was merged in pull request #78.
This commit is contained in:
chrnx committed 2026-09-01 14:44:41 +00:00
commit f08956bea8
30 files changed
+880 -85

No files matched your search

+2 -1
View File
@@ -144,7 +144,8 @@ without growing the runtime dependency tree past `reflect-metadata`:
- **Resource ceilings, with safe defaults.** `limits` caps body size (`413`), multipart parts, concurrent Node connections (default `1000`; `<= 0` leaves connections unlimited), and the request / headers / keep-alive timeouts — defaulting to `30s` / `10s` / `5s`, tighter than Node's own two-minute default. `maxConcurrentRequests` is opt-in and applies per server or Fetch adapter instance; when set, excess in-flight requests receive `503` and `Retry-After: 1`. It bounds concurrently executing handlers, so a handler that never returns continues to hold its slot; on Node, a client disconnect releases that slot. Long-lived streams and WebSocket upgrades do not hold that request budget. When Node's connection cap is reached, excess sockets are destroyed without an HTTP response. Deno and Bun expose no equivalent active-socket cap, so enforce one at the deployment platform or reverse proxy there.
- **Observability without an integration.** Every request carries an id and a trace id through every lifecycle event, each step reports its own duration, and `createApp({ logger })` accepts any logger — the default writes structured JSON. Nothing in core writes to `console`. Metrics and tracing exporters read the same stream from outside core.
- **Graceful shutdown, with a deadline.** `app.close()` drains in-flight requests and closes live streams and mesh links, then warns and force-closes whatever is still open after 10 seconds — so a stuck handler cannot hold a deploy open forever. Change the number per call with `close({ timeoutMs })` or for the whole app with `createApp({ shutdownTimeoutMs })`. Connection *draining* is Node-only; on Deno and Bun the server `serveDeno()`/`serveBun()` returns carries the same `close({ timeoutMs })`.
- **Shutdown is an extension point, not a `SIGTERM` handler you write.** A provider that opened a pool closes it in `dispose()`; a plugin registers `onShutdown(...)`; an application that wants neither passes `createApp({ hooks: [{ onShutdown }] })`. All three land in one registry, run in reverse boot order — a `cache` that needs `db` closes first — and are *awaited*, unlike a `bus.on` listener. A failure is logged and the rest still run, because one broken teardown must not leave the process up. Everything happens inside `close()`'s deadline; `createApp({ teardownTimeoutMs })` reserves a slice of it when a connection must get its chance. *Not available on the edge* — workerd has no shutdown to hook.
- **Shutdown is an extension point.** A provider that opened a pool closes it in `dispose()`; a plugin registers `onShutdown(...)`; an application that wants neither passes `createApp({ hooks: [{ onShutdown }] })`. All three land in one registry, run in reverse boot order — a `cache` that needs `db` closes first — and are *awaited*, unlike a `bus.on` listener. A failure is logged and the rest still run, because one broken teardown must not leave the process up. Everything happens inside `close()`'s deadline; `createApp({ teardownTimeoutMs })` reserves a slice of it when a connection must get its chance. *Not available on the edge* — workerd has no shutdown to hook.
- **The `SIGTERM` handler is yours to keep or to hand over.** All of the above runs from `close()`, and something has to call it — a container `SIGKILL`ed after its grace period skips every `dispose()` and reports nothing. Write the handler yourself and keep the control, or set `createApp({ handleSignals: true })` and the framework registers `SIGINT`/`SIGTERM` to close and exit for you. Off by default, because a library that installs process-wide handlers behind your back is worse than one that installs none. Turning it on also absorbs the last runtime difference an app has: `process.on` on Node and Bun, `Deno.addSignalListener` on Deno, and the matching `exit` for each — `listen()`, `serveDeno()` and `serveBun()` each wire it to the closer that drains *their* server. `close()` unregisters, so a second Ctrl-C ends a teardown that is stuck.
- **Testable by construction.** `createApp({ overrides: { db: fakeDb } })` swaps any node in one line.
- **Dual ESM + CommonJS.** Ships both builds behind an `exports` map — `import` and `require` both resolve, with matching type declarations.
+60 -3
View File
@@ -13,6 +13,7 @@ import { isAsyncIterable } from '../channel';
import { JsonTransformer, type ErrorRenderer } from '../transformers';
import { mountPlugin, Plugin, ScopeApi, ScopeNode } from '../plugin';
import { TeardownRegistry } from '../lifecycle';
import { installSignalHandlers } from '../http/signals-shutdown';
import type { Hooks } from './types';
import {
Ctor,
@@ -40,7 +41,7 @@ import type { App, InspectLine, Explain, RoutePlan, MeshConfig } from './types';
import { inspectRoute, buildGraphView, explainRoute } from './introspect';
import { compilePattern } from '../http/router';
export type { App, InspectLine, ExplainNode, Explain, MeshConfig } from './types';
export type { App, InspectLine, ExplainNode, Explain, MeshConfig, Hooks } from './types';
type Runner = (ctx: any) => any;
@@ -139,6 +140,25 @@ export function createApp(opts: {
* Must not exceed `shutdownTimeoutMs`; `createApp` throws rather than clamping silently.
*/
teardownTimeoutMs?: number;
/**
* Register `SIGINT`/`SIGTERM` to run `close()` and exit the process (default: `false`).
*
* Off by default because a library that installs process-wide handlers behind your back is worse
* than one that installs none — when the process exits is the application's call, not ours. Turn
* it on and the framework absorbs the last runtime difference an app otherwise has: `process.on`
* on Node and Bun, `Deno.addSignalListener` on Deno, and the matching `exit` for each.
*
* Leaving it off is a supported choice, not a gap — write the handler yourself if you want the
* control. What is *not* optional either way is that something calls `close()`: the teardown
* registry only runs from there, so a container `SIGKILL`ed after its grace period skips every
* `dispose()` the registry so carefully ordered, and reports nothing.
*
* Registered by `listen()`, `serveDeno()` and `serveBun()`, and taken back off by `close()` —
* so a *second* signal arriving mid-shutdown falls through to the platform default and ends the
* process at once. Ctrl-C twice is the way out of a teardown that is stuck; once is the way to
* let it finish.
*/
handleSignals?: boolean;
/**
* Where every framework diagnostic is written (default: structured JSON, human-readable on a TTY).
*
@@ -319,15 +339,52 @@ export function createApp(opts: {
});
server.on('close', () => closeLinks(meshLinks));
await new Promise<void>((resolve) => server!.listen(port, resolve));
// After the socket is up, so a boot that throws never leaves a handler behind pointing at an
// app that never served.
handleSignals(close);
return server;
};
const close = (options: { timeoutMs?: number } = {}): Promise<void> =>
closeApp(server, meshLinks, streams, options, opts.shutdownTimeoutMs, logger, teardown, opts.teardownTimeoutMs);
// Torn down by whichever close runs first, signal-driven or hand-called. On Deno that is
// load-bearing rather than tidy: a live `Deno.addSignalListener` keeps the process up, so an app
// that closed itself and expected to exit would simply hang.
let removeSignalHandlers: (() => void) | undefined;
const clearSignalHandlers = (): void => {
removeSignalHandlers?.();
removeSignalHandlers = undefined;
};
const close = (options: { timeoutMs?: number } = {}): Promise<void> => {
clearSignalHandlers();
return closeApp(
server,
meshLinks,
streams,
options,
opts.shutdownTimeoutMs,
logger,
teardown,
opts.teardownTimeoutMs,
);
};
const handleSignals = <T extends (options?: { timeoutMs?: number }) => Promise<void>>(closer: T): T => {
if (!opts.handleSignals) return closer;
const wrapped = ((options?: { timeoutMs?: number }) => {
clearSignalHandlers();
return closer(options);
}) as T;
removeSignalHandlers = installSignalHandlers(() => wrapped(), logger);
return wrapped;
};
return {
listen,
close,
handleSignals,
ready,
fetch: fetchFn,
upgrade: upgradeFn,
+9
View File
@@ -38,6 +38,15 @@ export interface Explain {
export interface App {
listen(port: number): Promise<http.Server>;
close(options?: { timeoutMs?: number }): Promise<void>;
/**
* Wires `SIGINT`/`SIGTERM` to `closer` and returns a close that also unregisters them — or
* returns `closer` untouched when `createApp({ handleSignals })` was not set.
*
* `listen()`, `serveDeno()` and `serveBun()` each call this with the closer that actually drains
* their server, which is why the option is declared once on `createApp` and works on all three.
* Call it yourself only if you serve the app some other way.
*/
handleSignals<T extends (options?: { timeoutMs?: number }) => Promise<void>>(closer: T): T;
/**
* Resolves the dependency graph, then returns. For a mesh app that means connecting to its
* teapots and splicing their scopes in — a mesh graph is not knowable without asking. For every
+5 -1
View File
@@ -117,7 +117,10 @@ export function serveBun(app: App, options?: BunServeShortOptions): BunServeResu
// Object.assign rather than a fresh object: Bun.serve returns more than the ambient above
// declares (reload, ref, unref, …), and rebuilding would silently drop whatever we did not name.
return Object.assign(server, {
close: (closeOptions: { timeoutMs?: number } = {}): Promise<void> =>
// Through `app.handleSignals` so that `createApp({ handleSignals: true })` reaches this
// runtime's own signal API — and so the close it returns takes the handlers back off, which
// Deno requires to exit at all.
close: app.handleSignals((closeOptions: { timeoutMs?: number } = {}): Promise<void> =>
closeWithDeadline(
// Drain, then hand over to the app so registered teardown runs — D7 of the teardown design.
// `app.close()` returns at its no-server guard on Bun, but still drains the teardown
@@ -133,5 +136,6 @@ export function serveBun(app: App, options?: BunServeShortOptions): BunServeResu
runtime: 'bun',
}),
),
),
});
}
+5 -1
View File
@@ -76,7 +76,10 @@ export function serveDeno(app: App, options?: DenoServeOptions): DenoServer {
// Object.assign rather than a fresh object: Deno.serve returns more than the ambient above
// declares (addr, ref, unref, …), and rebuilding would silently drop whatever we did not name.
return Object.assign(server, {
close: (closeOptions: { timeoutMs?: number } = {}): Promise<void> =>
// Through `app.handleSignals` so that `createApp({ handleSignals: true })` reaches this
// runtime's own signal API — and so the close it returns takes the handlers back off, which
// Deno requires to exit at all.
close: app.handleSignals((closeOptions: { timeoutMs?: number } = {}): Promise<void> =>
closeWithDeadline(
// Drain, then hand over to the app so registered teardown runs — D7 of the teardown design.
// `app.close()` returns at its no-server guard on Deno, but still drains the teardown
@@ -101,5 +104,6 @@ export function serveDeno(app: App, options?: DenoServeOptions): DenoServer {
{ timeoutMs: ms, runtime: 'deno' },
),
),
),
});
}
+18 -10
View File
@@ -9,6 +9,7 @@ import { acquireBody, type BodyReader } from './body';
import type { RouteDef, HttpOptions } from './types';
import type { StreamEncoder } from '../encoders';
import type { Bus } from '../bus';
import { nodeRequire } from '../node-require';
/**
* `randomUUID`, from wherever this runtime keeps it. Resolved once, at import.
@@ -23,15 +24,15 @@ import type { Bus } from '../bus';
* CI's Node 18 job caught it; every newer Node and every other runtime hides it, which is exactly
* why that job is pinned to the floor rather than to the current release.
*
* The fallback is reached only by a runtime that lacks the global, so workerd never evaluates the
* `require` — and the ESM build has a real one, from the `createRequire` banner in `tsup.config.ts`.
* The fallback is reached only by a runtime that lacks the global, so workerd never evaluates it.
* It goes through {@link nodeRequire} rather than a bare `require`, which is what makes it work on
* every distribution of this package and not just the bundled ones.
*/
const randomUUID: () => string = (() => {
const webCrypto = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;
if (typeof webCrypto?.randomUUID === 'function') return () => webCrypto.randomUUID!();
// eslint-disable-next-line @typescript-eslint/no-require-imports
return (require('node:crypto') as { randomUUID: () => string }).randomUUID;
return nodeRequire<{ randomUUID: () => string }>('node:crypto').randomUUID;
})();
/**
@@ -132,7 +133,7 @@ export function computeInjected(
req: { secure: boolean; headers: Record<string, string | string[] | undefined> },
): Record<string, string> {
const injected: Record<string, string> = { ...buildSecurityHeaders(opts?.security ?? true, req.secure) };
if (opts?.cors) Object.assign(injected, resolveCors(opts.cors, req));
if (opts?.cors) Object.assign(injected, resolveCors(opts.cors, req, opts.logger));
return injected;
}
@@ -211,6 +212,7 @@ export function handle(
routes: RouteDef[],
opts: HttpOptions | undefined,
req: NeutralRequest,
injected?: Record<string, string>,
): Promise<HandleResult | Preflight> {
const bus = opts?.bus;
@@ -226,10 +228,10 @@ export function handle(
bus.hasListeners('route:unmatched')
)
) {
return dispatch(routes, opts, req, undefined, undefined);
return dispatch(routes, opts, req, undefined, undefined, injected);
}
return observedDispatch(routes, opts, req, bus);
return observedDispatch(routes, opts, req, bus, injected);
}
async function observedDispatch(
@@ -237,6 +239,7 @@ async function observedDispatch(
opts: HttpOptions | undefined,
req: NeutralRequest,
bus: Bus,
injected?: Record<string, string>,
): Promise<HandleResult | Preflight> {
const watchingEnd = bus.hasListeners('request:end');
const startedAt = watchingEnd ? performance.now() : 0;
@@ -250,7 +253,7 @@ async function observedDispatch(
traceId: req.traceId,
});
const result = await dispatch(routes, opts, req, bus, trace);
const result = await dispatch(routes, opts, req, bus, trace, injected);
if (watchingEnd) {
// A preflight is a 204 the router never routed; a stream has no status of its own and is a 200
@@ -276,8 +279,13 @@ async function dispatch(
req: NeutralRequest,
bus: Bus | undefined,
trace: Trace | undefined,
precomputed?: Record<string, string>,
): Promise<HandleResult | Preflight> {
const injected = computeInjected(opts, req);
// Both adapters compute this before routing, because a response written above `handle()` — a
// shed 503, a 413 from the body reader — has to carry the same headers as one written below it.
// Recomputing here would run `security` and, worse, the `origins` predicate a second time for
// one request. `computeInjected` stays as the fallback for callers that have nothing yet.
const injected = precomputed ?? computeInjected(opts, req);
let path: string;
try {
@@ -287,7 +295,7 @@ async function dispatch(
}
if (opts?.cors && req.method === 'OPTIONS' && req.headers['access-control-request-method']) {
return { preflight: corsPreflightHeaders(opts.cors, req) };
return { preflight: corsPreflightHeaders(opts.cors, req, injected) };
}
const matched = resolveRoute(routes, req.method, path);
+23 -21
View File
@@ -3,14 +3,14 @@ import type https from 'https';
import { createRequestGate } from './request-gate';
import { renderError, type ErrorRequest } from '../transformers';
import type { Bus } from '../bus';
import { buildSecurityHeaders, resolveCors } from '../security';
import { readBody as readBodyBytes, deriveSecure, deriveIp } from './request';
import { pipeStream } from './stream';
import { attachWs } from './ws';
import { mergeInjectedHeaders } from './headers';
import { handle, correlateRequest, type HandleResult, type Preflight } from './core';
import { handle, correlateRequest, computeInjected, type HandleResult, type Preflight } from './core';
import type { BodyFailure, BodyReader } from './body';
import type { RouteDef, WsRouteDef, MeshControl, HttpOptions } from './types';
import { nodeRequire } from '../node-require';
interface HandlerConfig {
routes: RouteDef[];
@@ -44,10 +44,8 @@ export function createHttpServer(
// Node http/https are loaded lazily so importing createApp stays edge/workerd-safe
// (workerd's nodejs_compat provides no node:http/node:https). This path only runs under listen().
// eslint-disable-next-line @typescript-eslint/no-require-imports
const nodeHttp = require('http') as typeof import('http');
// eslint-disable-next-line @typescript-eslint/no-require-imports
const nodeHttps = require('https') as typeof import('https');
const nodeHttp = nodeRequire<typeof import('http')>('http');
const nodeHttps = nodeRequire<typeof import('https')>('https');
// runtime-compatible; only @types differ (https.Server lacks the http-only timeout props)
const server: http.Server = (opts?.tls
@@ -96,13 +94,12 @@ function createRequestHandler(cfg: HandlerConfig) {
const secure = deriveSecure(req, trustProxy);
// Derived before the body is read, so a 413 rejected below still carries an identity.
const correlation = correlateRequest(req.headers);
const injected: Record<string, string> = { ...buildSecurityHeaders(opts?.security ?? true, secure) };
// One computation for the whole request: this object is patched into every response below, and
// handed to `handle()` so routing does not derive it a second time — `security` is pure, but
// `cors.origins` may be a predicate with a network call in it.
const injected = computeInjected(opts, { secure, headers: req.headers });
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));
let result: HandleResult | Preflight;
let acquired = false;
const watchingEnd = bus?.hasListeners('request:end') ?? false;
@@ -139,16 +136,21 @@ function createRequestHandler(cfg: HandlerConfig) {
gate.release();
});
result = await handle(routes, opts, {
...correlation,
method: req.method ?? 'GET',
url: req.url ?? '/',
headers: req.headers,
readBody,
source: req,
secure,
ip: deriveIp(req, trustProxy),
});
result = await handle(
routes,
opts,
{
...correlation,
method: req.method ?? 'GET',
url: req.url ?? '/',
headers: req.headers,
readBody,
source: req,
secure,
ip: deriveIp(req, trustProxy),
},
injected,
);
} finally {
if (acquired) {
acquired = false;
+125
View File
@@ -0,0 +1,125 @@
// src/http/signals-shutdown.ts — SIGINT/SIGTERM → close(), opt-in, one spelling per runtime.
import type { Logger } from '../logger';
/** The two signals an orchestrator actually sends: Ctrl-C, and every container runtime's stop. */
const SIGNALS = ['SIGINT', 'SIGTERM'] as const;
type Signal = (typeof SIGNALS)[number];
interface SignalApi {
runtime: string;
on(signal: Signal, handler: () => void): void;
off(signal: Signal, handler: () => void): void;
exit(code: number): void;
}
interface DenoSignals {
addSignalListener(signal: Signal, handler: () => void): void;
removeSignalListener(signal: Signal, handler: () => void): void;
exit(code: number): void;
}
interface ProcessSignals {
on(signal: Signal, handler: () => void): unknown;
off?(signal: Signal, handler: () => void): unknown;
removeListener?(signal: Signal, handler: () => void): unknown;
exit(code: number): void;
}
/**
* Deno first, on purpose. Its `node:process` shim does carry signal support, but `Deno.exit` and
* `Deno.addSignalListener` are the APIs Deno itself documents, and a listener registered natively
* is the one `removeSignalListener` can take back — which matters here, because a Deno signal
* listener holds the process open until it is removed. Node and Bun share `process`.
*/
function signalApi(): SignalApi | undefined {
const deno = (globalThis as { Deno?: DenoSignals }).Deno;
if (typeof deno?.addSignalListener === 'function')
return {
runtime: 'deno',
on: (signal, handler) => deno.addSignalListener(signal, handler),
off: (signal, handler) => deno.removeSignalListener(signal, handler),
exit: (code) => deno.exit(code),
};
const proc = (globalThis as { process?: ProcessSignals }).process;
if (typeof proc?.on === 'function' && typeof proc.exit === 'function') {
const remove = proc.off ?? proc.removeListener;
return {
runtime: 'node',
on: (signal, handler) => void proc.on(signal, handler),
off: (signal, handler) => void remove?.call(proc, signal, handler),
exit: (code) => proc.exit(code),
};
}
return undefined;
}
/**
* Registers SIGINT/SIGTERM to run `close` and then exit. Returns the function that takes those
* handlers back off — which is not optional bookkeeping on Deno, where a live signal listener keeps
* the process from exiting on its own.
*
* The close is expected to unregister first thing, which leaves a **second signal falling through
* to the platform default** — an immediate end to the process, teardown or no teardown. That is
* the escape hatch, and it is deliberate: a developer pressing Ctrl-C twice wants out now, and
* swallowing it for the length of a 10s shutdown budget would read as a hang. An orchestrator
* sends `SIGTERM` once and then `SIGKILL`, so it never reaches this path.
*
* If the close throws, the process still exits — with 1, because a shutdown that failed halfway is
* not a clean one and an orchestrator should be told.
*/
export function installSignalHandlers(close: () => Promise<void>, logger: Logger): () => void {
const api = signalApi();
if (!api) {
logger.warn(
'handleSignals: this runtime delivers no process signals, so nothing was registered — call close() yourself',
);
return () => {};
}
const registered: Array<[Signal, () => void]> = [];
const remove = (): void => {
while (registered.length) {
const [signal, handler] = registered.pop()!;
api.off(signal, handler);
}
};
for (const signal of SIGNALS) {
const handler = (): void => {
logger.info(`${signal} received — closing`, { signal, runtime: api.runtime });
void close().then(
() => api.exit(0),
(error: unknown) => {
logger.error(`shutdown failed after ${signal}`, {
signal,
err: error instanceof Error ? error.message : String(error),
});
api.exit(1);
},
);
};
try {
api.on(signal, handler);
registered.push([signal, handler]);
} catch (error) {
// Deno throws for SIGTERM on Windows, where the signal does not exist. Registering what the
// platform does have beats refusing to start over the one it does not.
logger.warn(`handleSignals: ${signal} is unavailable on this platform — skipping it`, {
signal,
err: error instanceof Error ? error.message : String(error),
});
}
}
return remove;
}
+25 -17
View File
@@ -173,23 +173,31 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
acquired = true;
result = await handle(routes, opts, {
...correlation,
method: request.method,
url: path,
headers,
readBody,
source: request,
secure,
// Mirrors Node's `deriveIp` (src/http/request.ts): only trust `x-forwarded-for` when the proxy is
// trusted, and take its first hop — an untrusted XFF is client-spoofable, and there's no socket
// peer address to fall back to on the fetch path, so the untrusted case is simply ''.
ip: opts?.trustProxy
? String(headers['x-forwarded-for'] ?? '')
.split(',')[0]
.trim()
: '',
});
result = await handle(
routes,
opts,
{
...correlation,
method: request.method,
url: path,
headers,
readBody,
source: request,
secure,
// Mirrors Node's `deriveIp` (src/http/request.ts): only trust `x-forwarded-for` when the
// proxy is trusted, and take its first hop — an untrusted XFF is client-spoofable, and
// there's no socket peer address to fall back to on the fetch path, so the untrusted case
// is simply ''.
ip: opts?.trustProxy
? String(headers['x-forwarded-for'] ?? '')
.split(',')[0]
.trim()
: '',
},
// Already computed above for the shed-503 path; handing it down keeps `cors.origins` to
// one call per request.
injected,
);
} finally {
// Release when routing/handling finishes, not when a returned stream finishes.
// Long-lived streams therefore do not permanently consume the request budget.
+2 -2
View File
@@ -1,6 +1,7 @@
import { channel } from '../channel';
import type { App } from '../app/types';
import type { WsRequest, WsSocket } from './ws-core';
import { nodeRequire } from '../node-require';
/**
* Shared plumbing for the runtime adapters (Bun/Deno/edge) that bridge a host WebSocket
@@ -123,8 +124,7 @@ export function loadWebSocketCtor(): SocketCtor {
if (platform) return platform;
// eslint-disable-next-line @typescript-eslint/no-require-imports
return require('ws') as SocketCtor;
return nodeRequire<SocketCtor>('ws');
}
/**
+2 -2
View File
@@ -3,14 +3,14 @@ import { channel } from '../channel';
import type { Bus } from '../bus';
import { runWsConnection, matchWsRoute, trackUntil, type WsSocket, type WsRequest } from './ws-core';
import type { WsRouteDef, MeshControl } from './types';
import { nodeRequire } from '../node-require';
/** 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;
return nodeRequire<{ WebSocketServer: unknown }>('ws').WebSocketServer;
} catch {
return null;
}
+4 -2
View File
@@ -40,8 +40,10 @@ export {
Options,
Html,
} from './metadata';
export type { Transport, HttpMethod, RouteDecorator } from './metadata';
export type { Plugin } from './plugin';
export type { Transport, HttpMethod, RouteDecorator, TransformerFn } from './metadata';
export type { Plugin, PluginApi, ScopeApi, ScopeNode } from './plugin';
export type { Hooks } from './app';
export type { TeardownFn } from './lifecycle';
// Transformers & error signals
export { JsonTransformer } from './transformers';
+2 -2
View File
@@ -1,6 +1,7 @@
// src/multipart.ts — multipart/form-data parsing on top of the optional `busboy` peer dependency.
import { Readable } from 'stream';
import { HttpError } from './signals';
import { nodeRequire } from './node-require';
/** A single uploaded file part decoded from a multipart body. */
export interface UploadedFile {
@@ -67,8 +68,7 @@ function loadBusboy(): ((cfg: unknown) => NodeJS.WritableStream & NodeJS.EventEm
try {
// `busboy` is an OPTIONAL peer dependency: only multipart uploads need it, so it is
// lazy-required and its absence surfaces as a clear 501 rather than a load-time crash.
// eslint-disable-next-line @typescript-eslint/no-require-imports
return require('busboy');
return nodeRequire('busboy');
} catch {
return null;
}
+44
View File
@@ -0,0 +1,44 @@
// src/node-require.ts — one `require` that survives being published as source.
type Require = <T>(id: string) => T;
interface NodeProcess {
cwd?: () => string;
getBuiltinModule?: (id: string) => unknown;
}
let cached: Require | null | undefined;
function resolveRequire(): Require | undefined {
// The CJS build has a native one, and tsup gives the ESM build one through a `createRequire`
// banner (tsup.config.ts). Both npm paths stop here.
if (typeof require === 'function') return require as Require;
// JSR publishes `src/` and runs no bundler, so on that path nothing ever defined `require`.
// `process.getBuiltinModule` is the way back: Node 22.3+, Deno and Bun all expose it, and all
// three do it *synchronously* — which is the whole requirement, since every caller here sits on
// a sync path that a dynamic `import()` could not serve.
const proc = (globalThis as { process?: NodeProcess }).process;
const nodeModule = proc?.getBuiltinModule?.('node:module') as
{ createRequire?: (from: string) => Require } | undefined;
if (!nodeModule?.createRequire || !proc?.cwd) return undefined;
// Resolve from the application's directory rather than from this file: served from JSR this
// module lives under an `https://` URL with no `node_modules` beneath it, while an optional peer
// dependency such as `busboy` is installed in the app that asked for it.
return nodeModule.createRequire(`${proc.cwd()}/`);
}
/**
* Loads a Node builtin or an installed package, synchronously.
*
* Throws on a runtime that can offer neither — workerd, where `node:fs` and `busboy` are genuinely
* out of reach. Every caller already guards for that and reports it in its own terms; what they
* must not do is report it when the module is in fact reachable, which is what a bare `require`
* caused on JSR by failing with `ReferenceError` before any of them was consulted.
*/
export function nodeRequire<T>(id: string): T {
if (cached === undefined) cached = resolveRequire() ?? null;
if (cached === null) throw new Error(`cannot load '${id}': this runtime provides no CommonJS require`);
return cached<T>(id);
}
+26 -5
View File
@@ -1,5 +1,7 @@
// src/security.ts — pure header computation, no server deps
import type { Logger } from './logger';
/** TLS material for an HTTPS server. */
export interface TlsOptions {
key: Buffer | string;
@@ -75,22 +77,36 @@ export function buildSecurityHeaders(opts: boolean | SecurityOptions, secure: bo
return headers;
}
function originAllowed(spec: CorsOptions['origins'], origin: string): boolean {
function originAllowed(spec: CorsOptions['origins'], origin: string, logger?: Logger): boolean {
if (spec === '*') return true;
if (typeof spec === 'function') return spec(origin);
if (Array.isArray(spec)) return spec.includes(origin);
return spec === origin;
if (typeof spec !== 'function') return spec === origin;
// The predicate is user code on the request path — a Redis allowlist, a tenant lookup — and it runs
// before the region where errors convert to a response, so a throw here would leave the request
// listener as an unhandled rejection and take the process down. Deny instead: a lookup that failed
// has not said yes, and a broken allowlist must never widen into an open one.
try {
return spec(origin);
} catch (error) {
logger?.warn(`cors: the origins predicate threw for ${origin} — treating the origin as not allowed`, {
origin,
err: error instanceof Error ? error.message : String(error),
});
return false;
}
}
/** Compute CORS response headers for a request. Returns `{}` when the origin is not allowed. */
export function resolveCors(
opts: CorsOptions,
req: { headers: Record<string, string | string[] | undefined> },
logger?: Logger,
): Headers {
const headers: Headers = {};
const rawOrigin = req.headers['origin'];
const origin = Array.isArray(rawOrigin) ? rawOrigin[0] : rawOrigin;
if (!origin || !isValidOrigin(origin) || !originAllowed(opts.origins, origin)) return headers;
if (!origin || !isValidOrigin(origin) || !originAllowed(opts.origins, origin, logger)) return headers;
// credentials => never '*'; echo concrete origin. Also echo when allowlist is dynamic.
if (opts.credentials) {
@@ -112,8 +128,13 @@ export function resolveCors(
export function corsPreflightHeaders(
opts: CorsOptions,
req: { headers: Record<string, string | string[] | undefined> },
resolved?: Headers,
): Headers {
const headers = resolveCors(opts, req);
// The caller has almost always resolved CORS already, one layer up, to seed the headers every
// response carries. Re-deriving here would consult `origins` a second time for the same request —
// and `origins` may be a predicate doing a network lookup. Copied rather than used in place: the
// preflight-only keys below belong to this 204, not to the shared object.
const headers: Headers = { ...resolved };
if (!headers['access-control-allow-origin']) return headers; // origin not allowed → bare 204
headers['access-control-allow-methods'] = (opts.methods ?? ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS']).join(
', ',
+8 -9
View File
@@ -3,6 +3,7 @@
import type { TransformerFn } from './metadata';
import type { HtmlMeta } from './metadata';
import { nodeRequire } from './node-require';
/** Escape the five HTML-significant characters so interpolated data can't inject markup. */
export function escapeHtml(s: string): string {
@@ -58,12 +59,12 @@ export interface ViewsContext {
/** Reads a view file at boot (lazy fs). Relative paths resolve against `views` (default cwd); absolute as-is.
* node:fs/node:path are loaded lazily so importing the barrel stays edge/workerd-safe
* (workerd's nodejs_compat provides no filesystem). This path only runs for path/template `@Html` modes. */
* (workerd's nodejs_compat provides no filesystem). This path only runs for path/template `@Html` modes.
* Unguarded on purpose: `@Html('file')` cannot degrade into anything useful, so a runtime with no
* filesystem should hear about it here rather than at the first request. */
function readViewFile(views: string | undefined, path: string): string {
// eslint-disable-next-line @typescript-eslint/no-require-imports
const nodePath = require('node:path') as typeof import('node:path');
// eslint-disable-next-line @typescript-eslint/no-require-imports
const fs = require('node:fs') as typeof import('node:fs');
const nodePath = nodeRequire<typeof import('node:path')>('node:path');
const fs = nodeRequire<typeof import('node:fs')>('node:fs');
const base = views ?? process.cwd();
const full = nodePath.isAbsolute(path) ? path : nodePath.resolve(base, path);
@@ -94,10 +95,8 @@ export function buildStaticResolver(root: string | true): StaticResolver {
let nodePath: typeof import('node:path');
try {
// eslint-disable-next-line @typescript-eslint/no-require-imports
fs = require('node:fs');
// eslint-disable-next-line @typescript-eslint/no-require-imports
nodePath = require('node:path');
fs = nodeRequire('node:fs');
nodePath = nodeRequire('node:path');
} catch {
throw new Error(
'`static` needs a filesystem and is unavailable on this runtime (edge). Remove it or serve assets from a CDN.',
+4 -1
View File
@@ -29,7 +29,10 @@ it('snapshots connection metadata before Deno invalidates the upgraded request',
});
const upgrade = vi.fn().mockResolvedValue(undefined);
serveDeno({ upgrade } as unknown as App);
// `handleSignals` is a pass-through here: this test is about upgrade metadata, and the identity
// it returns is exactly what `createApp` returns when `handleSignals` is left off.
const handleSignals = <T,>(closer: T): T => closer;
serveDeno({ upgrade, handleSignals } as unknown as App);
const info = {
get remoteAddr() {
if (upgraded) throw new TypeError('Request closed');
+53
View File
@@ -0,0 +1,53 @@
// `createApp({ handleSignals: true })` under the real Deno runtime.
//
// Deno is the runtime this option exists for. Node and Bun share `process.on`/`process.exit`; Deno
// has `Deno.addSignalListener`/`Deno.exit`, and its listeners hold the process open until removed —
// so an app that closed itself and forgot to unregister would hang here and nowhere else.
//
// Run with: npm run test:deno
import { assert, assertEquals } from 'jsr:@std/assert';
const HARNESS = 'test/interop/_signal-app-deno.ts';
async function run(): Promise<{ code: number; lines: string[] }> {
const child = new Deno.Command('deno', {
args: ['run', '--allow-all', '--no-check', HARNESS],
stdout: 'piped',
stderr: 'inherit',
}).spawn();
const lines: string[] = [];
let buffered = '';
let signalled = false;
const reader = child.stdout.pipeThrough(new TextDecoderStream()).getReader();
const pump = (async () => {
while (true) {
const { value, done } = await reader.read();
if (done) break;
buffered += value;
const parts = buffered.split('\n');
buffered = parts.pop() ?? '';
for (const line of parts.filter(Boolean)) {
lines.push(line);
if (!signalled && line.includes('"ready"')) {
signalled = true;
child.kill('SIGTERM');
}
}
}
})();
const status = await child.status;
await pump;
return { code: status.code, lines };
}
Deno.test('SIGTERM runs teardown and exits 0 through Deno.addSignalListener', async () => {
const { code, lines } = await run();
assert(
lines.some((l) => l.includes('"disposed"')),
`dispose() never ran — got: ${lines.join(' | ')}`,
);
assertEquals(code, 0);
});
+76
View File
@@ -0,0 +1,76 @@
// `@Html` and `static` under the real Deno runtime, importing `src/` the way JSR serves it.
//
// This is the shape the JSR package actually ships: no bundler ran, so tsup's `createRequire`
// banner (tsup.config.ts) never existed and the lazy `require('node:fs')` in `src/views.ts` has
// nothing to resolve. Every other Deno test here imports `src/` too, but none of them touches a
// path that loads a Node builtin lazily — which is how a package that dies at boot on Deno kept a
// green suite. Run with: npm run test:deno
import 'npm:reflect-metadata';
import { assertEquals, assertStringIncludes } from 'jsr:@std/assert';
import { createApp, Route, Get, Html, Module } from '../../src/index.ts';
// Committed fixtures rather than a temp dir, so the suite keeps running without `--allow-write`.
const dir = 'test/fixtures/views';
@Route('/')
class Views {
@Get('/dash') @Html('dash.html') dash() {}
@Get('/user') @Html('user.html', { template: true }) user() {
return { name: 'Deno' };
}
}
@Module({ mountpoint: '/', controllers: [Views] })
class M {}
Deno.test("@Html file mode reads the file — the require path resolves without tsup's banner", async () => {
const app = createApp({ modules: [M], views: dir });
const res = await app.fetch(new Request('http://x/dash'));
assertEquals(res.status, 200);
assertEquals(await res.text(), '<h1>Dash</h1>');
await app.close();
});
Deno.test('@Html template mode renders', async () => {
const app = createApp({ modules: [M], views: dir });
const res = await app.fetch(new Request('http://x/user'));
assertStringIncludes(await res.text(), 'Hi Deno');
await app.close();
});
// Deno has a filesystem, so `static` must not report the runtime as the reason for anything.
Deno.test('static: true builds a resolver instead of blaming the runtime', async () => {
const app = createApp({ modules: [], static: dir });
const res = await app.fetch(new Request('http://x/asset.txt'));
assertEquals(res.status, 200);
assertEquals(await res.text(), 'served');
await app.close();
});
// The other half of the shim: `node:fs` above comes from `process.getBuiltinModule`, but `busboy`
// is an npm package and has to be resolved from the application's own `node_modules`. On JSR that
// failed as a `ReferenceError` under the catch that reports "busboy not installed" — the one
// diagnosis guaranteed to send a reader to reinstall a package they already have.
Deno.test('multipart resolves the busboy peer dependency instead of reporting it missing', async () => {
const { createApp: create, Route: R, Post, Module: Mod, body } = await import('../../src/index.ts');
@R('/')
class Upload {
@Post('/up') up(@body() b: { fields: Record<string, string>; files: Record<string, { filename: string }> }) {
return { name: b.fields.name, filename: b.files.file.filename };
}
}
@Mod({ mountpoint: '/', controllers: [Upload] })
class UploadMod {}
const app = create({ modules: [UploadMod] });
const form = new FormData();
form.set('name', 'joe');
form.set('file', new Blob([new Uint8Array([1, 2, 3])], { type: 'image/png' }), 'p.png');
const res = await app.fetch(new Request('http://x/up', { method: 'POST', body: form }));
assertEquals(res.status, 200);
assertEquals(await res.json(), { name: 'joe', filename: 'p.png' });
await app.close();
});
+1
View File
@@ -0,0 +1 @@
served
+1
View File
@@ -0,0 +1 @@
<h1>Dash</h1>
+1
View File
@@ -0,0 +1 @@
<h1>Hi {{ name }}</h1>
+67
View File
@@ -352,4 +352,71 @@ describe('request hardening', () => {
expect(await res.json()).toEqual({ a: '1', b: 'two' });
server.close();
});
it('a cors.origins predicate that throws answers the request instead of taking the process down', async () => {
const warn = vi.fn();
const server = createHttpServer(
[{ method: 'GET', pattern: '/ping', transport: 'buffer', handler }],
[],
undefined,
undefined,
{
cors: {
origins: () => {
throw new Error('lookup failed');
},
},
logger: { debug: vi.fn(), info: vi.fn(), warn, error: vi.fn() } as any,
},
);
await new Promise<void>((r) => server.listen(0, r));
// Only a request carrying an Origin reaches the predicate — which is why a suite that forgets
// the header watches this crash in production instead.
const res = await fetch(`${getUrl(server)}/ping`, { headers: { origin: 'https://a.com' } });
expect(res.status).toBe(200);
expect(res.headers.get('access-control-allow-origin')).toBeNull();
expect(warn).toHaveBeenCalled();
// The security headers still land: one broken predicate must not strip the rest.
expect(res.headers.get('x-content-type-options')).toBe('nosniff');
server.close();
});
// `origins` is a predicate because the shapes it exists for are lookups — an allowlist in Redis, a
// tenant query. Running one twice for a GET and three times for a preflight charges the caller's
// latency budget and their backend for an answer whose inputs did not change in between.
it('consults a cors.origins predicate once per request, not once per header computation', async () => {
let calls = 0;
const server = createHttpServer(
[{ method: 'GET', pattern: '/ping', transport: 'buffer', handler }],
[], undefined, undefined,
{ cors: { origins: () => { calls++; return true; } } },
);
await new Promise<void>((r) => server.listen(0, r));
const origin = { origin: 'https://a.com' };
const plain = await fetch(`${getUrl(server)}/ping`, { headers: origin });
expect(plain.headers.get('access-control-allow-origin')).toBe('https://a.com');
expect(calls).toBe(1);
calls = 0;
const preflight = await fetch(`${getUrl(server)}/ping`, {
method: 'OPTIONS', headers: { ...origin, 'access-control-request-method': 'GET' },
});
expect(preflight.status).toBe(204);
expect(preflight.headers.get('access-control-allow-methods')).toContain('GET');
expect(preflight.headers.get('access-control-allow-origin')).toBe('https://a.com');
expect(calls).toBe(1);
// No Origin header never reaches the predicate at all — that part was already right.
calls = 0;
await fetch(`${getUrl(server)}/ping`);
expect(calls).toBe(0);
server.close();
});
});
+29
View File
@@ -0,0 +1,29 @@
// Not a test — a Deno app with `handleSignals: true`, spawned by test/deno/signals.test.ts.
// Deno's test runner only discovers *.test.ts, so this file is ignored by `deno test`.
//
// It exists because Deno is where the signal API actually differs: `Deno.addSignalListener` and
// `Deno.exit` rather than `process.on`/`process.exit`, and a listener that holds the process open
// until it is removed. Node passing says nothing about any of that.
import 'npm:reflect-metadata';
import { createApp, Module } from '../../src/index.ts';
import { serveDeno } from '../../src/deno.ts';
@Module({ mountpoint: '/', controllers: [] })
class Mod {}
// A hook rather than a provider's `dispose()`: on Deno nothing boots until the first request, so an
// unvisited app has no provider to dispose and the run would pass without proving anything. The
// hook registers at `createApp`, which makes "teardown ran" mean "close() was reached".
const app = createApp({
modules: [Mod],
handleSignals: true,
hooks: [{ onShutdown: () => console.log(JSON.stringify({ disposed: true })) }],
});
// `ready` is printed after `serveDeno` returns, not from `onListen` — Deno calls `onListen`
// synchronously from inside `Deno.serve`, so a parent that signals on that line races the handler
// registration that happens a few statements later and wins.
const server = serveDeno(app, { port: 0, onListen: () => {} });
console.log(JSON.stringify({ ready: true }));
void server;
+41
View File
@@ -0,0 +1,41 @@
// Not a test — a Node app with `handleSignals: true`, spawned by shutdown-signals.test.ts.
//
// Signal handling can only be told apart from doing nothing by a real process that really gets a
// real signal: an in-process test would have to fire the handler by hand, and the handler's whole
// job is to exit the process it is running in.
//
// Prints one JSON line per event on stdout: {"ready":port}, then {"disposed":n} per dispose call.
import 'reflect-metadata';
import { createApp, Provider, Route, Get, Module } from '../../src/index';
const SLOW = Number(process.env.DISPOSE_DELAY_MS ?? 0);
let disposals = 0;
@Provider({ provides: 'db' })
class Db {
provide() {
return { db: { name: 'db' } };
}
async dispose() {
if (SLOW) await new Promise((r) => setTimeout(r, SLOW));
disposals++;
console.log(JSON.stringify({ disposed: disposals }));
}
}
@Route('/')
class Api {
@Get('/ping') ping() {
return { ok: true };
}
}
@Module({ mountpoint: '/', controllers: [Api], providers: [Db] })
class Mod {}
const app = createApp({ modules: [Mod], handleSignals: process.env.HANDLE_SIGNALS !== 'false' });
void app.listen(0).then((server) => {
console.log(JSON.stringify({ ready: (server.address() as { port: number }).port }));
});
+28 -1
View File
@@ -1,4 +1,4 @@
import { describe, it, expect } from 'vitest';
import { describe, it, expect, vi } from 'vitest';
import { buildSecurityHeaders, resolveCors, mergeVary, isValidOrigin } from '../src/security';
describe('buildSecurityHeaders', () => {
@@ -51,6 +51,33 @@ describe('resolveCors', () => {
const r = resolveCors({ origins: () => true }, req('https://a.com\r\nX: y') as any);
expect(r['access-control-allow-origin']).toBeUndefined();
});
// An `origins` predicate is the whole reason the option takes a function: an allowlist in Redis, a
// tenant lookup, a regex over a parsed URL. Every one of those has a failure mode, and it runs on
// the request path — so a throw must not leave the boundary.
describe('a predicate that throws', () => {
const boom = () => {
throw new Error('lookup failed');
};
it('denies the origin rather than escaping the request path', () => {
expect(() => resolveCors({ origins: boom }, req('https://a.com') as any)).not.toThrow();
expect(resolveCors({ origins: boom }, req('https://a.com') as any)).toEqual({});
});
it('fails closed even when credentials are on — a broken allowlist is not an open one', () => {
const r = resolveCors({ origins: boom, credentials: true }, req('https://a.com') as any);
expect(r['access-control-allow-origin']).toBeUndefined();
expect(r['access-control-allow-credentials']).toBeUndefined();
});
it('reports the failure through the logger instead of swallowing it', () => {
const logger = { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() };
resolveCors({ origins: boom }, req('https://a.com') as any, logger as any);
expect(logger.warn).toHaveBeenCalledOnce();
expect(logger.warn.mock.calls[0][0]).toMatch(/cors/i);
});
});
});
describe('isValidOrigin', () => {
+112
View File
@@ -0,0 +1,112 @@
import { describe, it, expect, afterEach } from 'vitest';
import { spawn, type ChildProcess } from 'node:child_process';
import { createApp, Module } from '../src';
@Module({ mountpoint: '/', controllers: [] })
class Empty {}
let app: ReturnType<typeof createApp> | undefined;
let child: ChildProcess | undefined;
afterEach(async () => {
await app?.close();
app = undefined;
child?.kill('SIGKILL');
child = undefined;
});
const disposed = (r: { lines: string[] }) => r.lines.filter((l) => l.includes('"disposed"'));
const handled = (r: { lines: string[] }) => r.lines.some((l) => l.includes('received — closing'));
const listeners = () => process.listenerCount('SIGINT') + process.listenerCount('SIGTERM');
describe('handleSignals registration', () => {
it('registers nothing by default — a library must not own when the process exits', async () => {
const before = listeners();
app = createApp({ modules: [Empty] });
await app.listen(0);
expect(listeners()).toBe(before);
});
it('registers SIGINT and SIGTERM when asked, and takes both back off in close()', async () => {
const before = listeners();
const opted = createApp({ modules: [Empty], handleSignals: true });
await opted.listen(0);
expect(listeners()).toBe(before + 2);
// Not tidiness: on Deno a live signal listener holds the process open, so an app that closed
// itself and expected to exit would hang. Node is where it is observable.
await opted.close();
expect(listeners()).toBe(before);
});
});
/** Boots the harness app, waits for its `ready` line, and resolves once it has exited. */
function runHarness(signal: NodeJS.Signals, env: NodeJS.ProcessEnv = {}, sendTwice = false) {
return new Promise<{ code: number | null; signal: NodeJS.Signals | null; lines: string[] }>((resolve, reject) => {
// `process.execPath -r tsx/cjs`, not `npx tsx`: a wrapper puts the app one process further
// down, and on Linux the signal then lands on the wrapper while the app never hears it — which
// is exactly how this passed locally and failed in CI. `-r` rather than `--import`/`--loader`
// because it is the one form that works on both the Node 18 floor CI builds against and the
// current release.
const proc = spawn(process.execPath, ['-r', 'tsx/cjs', 'test/interop/_signal-app.ts'], {
env: { ...process.env, ...env },
stdio: ['ignore', 'pipe', 'inherit'],
});
child = proc;
const lines: string[] = [];
let ready = false;
let buffered = '';
proc.stdout.on('data', (chunk: Buffer) => {
buffered += chunk.toString();
const parts = buffered.split('\n');
buffered = parts.pop() ?? '';
for (const line of parts.filter(Boolean)) {
lines.push(line);
if (!ready && line.includes('"ready"')) {
ready = true;
proc.kill(signal);
if (sendTwice) setTimeout(() => proc.kill(signal), 20);
}
}
});
proc.on('error', reject);
proc.on('exit', (code, exitSignal) => resolve({ code, signal: exitSignal, lines }));
});
}
// These need a real process because the handler's job is to exit the one it runs in — firing it by
// hand in the test runner would either take the runner down or prove nothing.
describe('handleSignals end to end', () => {
it('SIGTERM runs teardown and exits 0', { timeout: 20_000 }, async () => {
const r = await runHarness('SIGTERM');
expect(disposed(r)).toHaveLength(1);
expect(r.code).toBe(0);
});
it('SIGINT does the same — Ctrl-C is not a different kind of shutdown', { timeout: 20_000 }, async () => {
const r = await runHarness('SIGINT');
expect(disposed(r)).toHaveLength(1);
expect(r.code).toBe(0);
});
// The escape hatch, and the reason `close()` unregisters before it starts draining: a second
// signal finds no handler and gets the platform default. Ctrl-C twice ends a stuck teardown
// rather than waiting out the whole shutdown budget.
it('lets a second signal end a shutdown that is still draining', { timeout: 20_000 }, async () => {
const r = await runHarness('SIGTERM', { DISPOSE_DELAY_MS: '2000' }, true);
expect(handled(r)).toBe(true); // the first signal was ours
expect(disposed(r)).toHaveLength(0); // the second one did not wait for the 2s dispose
expect(r.code).not.toBe(0);
});
it('leaves the process to its default fate when handleSignals is off', { timeout: 20_000 }, async () => {
const r = await runHarness('SIGTERM', { HANDLE_SIGNALS: 'false' });
expect(handled(r)).toBe(false); // nothing of ours ran at all
expect(disposed(r)).toHaveLength(0);
expect(r.code).not.toBe(0);
});
});
+68
View File
@@ -0,0 +1,68 @@
// Every extension point the docs tell a user to write must be *typeable* from the package, not just
// callable. A decorator whose argument type is not exported can be passed a literal and nothing
// else — the shape has to be redeclared inline, or borrowed off a value with
// `typeof JsonTransformer`, which works and reads like a trick because it is one.
//
// This file's job is to fail to compile if one of them stops being exported.
import { test, expect } from 'vitest';
import {
JsonTransformer,
type TransformerFn,
type Plugin,
type PluginApi,
type ScopeApi,
type ScopeNode,
type Hooks,
type TeardownFn,
type ErrorRenderer,
type StreamEncoder,
} from '../../src';
// @Transformer(fn) — the case that started this. Prometheus scrapes text, so a /metrics route
// needs its own transformer, and this is the annotation that was impossible to write.
const prometheusText: TransformerFn = (value) => ({
status: 200,
headers: { 'content-type': 'text/plain; version=0.0.4; charset=utf-8' },
body: String(value),
});
// A plugin split into named functions rather than one inline arrow: `Plugin` alone types the
// arrow, and nothing typed its argument.
function subscribe(api: PluginApi): void {
api.bus.on('request:end', () => {});
api.onShutdown(flush);
}
const flush: TeardownFn = () => {};
function contribute(scope: ScopeApi): void {
const node: ScopeNode = { kind: 'provider', name: 'metrics', needs: [], provides: ['metrics'], run: () => ({}) };
scope.add(node);
}
const metricsPlugin: Plugin = (api) => {
subscribe(api);
contribute(api.scope);
};
// createApp({ hooks }) — declared as a value, which is the point of the option.
const hooks: Hooks[] = [{ onShutdown: flush }];
// The two neighbouring extension points, already exported. Here so a future barrel edit that drops
// one is caught by the same test rather than by a user.
const renderError: ErrorRenderer = () => ({ status: 500, headers: {}, body: 'boom' });
const encoder: StreamEncoder = {
headers: {},
encode: (item) => String(item),
encodeError: (err) => String(err),
};
test('every extension point is typeable from the package barrel', () => {
expect(prometheusText('x').body).toBe('x');
expect(typeof metricsPlugin).toBe('function');
expect(hooks).toHaveLength(1);
expect(renderError(new Error('boom'), {} as never)?.status).toBe(500);
expect(encoder.encode(1)).toBe('1');
// The workaround the missing export forced, kept as a reminder of what it replaced.
expect(typeof JsonTransformer).toBe('function');
});
+38 -6
View File
@@ -52,8 +52,10 @@ describe('asReadableStream', () => {
});
describe('buildFetch request gate', () => {
it('does not permanently exhaust the gate when CORS setup throws', async () => {
let attempts = 0;
it('rides out a transient CORS predicate failure without leaking a gate slot', async () => {
// A flag rather than an attempt counter: `computeInjected` runs both in this adapter and again
// inside `handle()`, so the predicate is consulted more than once per request.
let lookupDown = true;
const fetchHandler = buildFetch(
[
@@ -68,8 +70,7 @@ describe('buildFetch request gate', () => {
limits: { maxConcurrentRequests: 2 },
cors: {
origins: () => {
attempts++;
if (attempts <= 2) throw new Error('transient CORS failure');
if (lookupDown) throw new Error('transient CORS failure');
return true;
},
},
@@ -81,11 +82,20 @@ describe('buildFetch request gate', () => {
headers: { origin: 'https://example.com' },
});
await expect(fetchHandler(request())).rejects.toThrow('transient CORS failure');
await expect(fetchHandler(request())).rejects.toThrow('transient CORS failure');
// While the lookup is down the origin is denied — the request is answered, just without the
// header that would let the browser read it. A failed lookup has not said yes.
for (let i = 0; i < 2; i++) {
const denied = await fetchHandler(request());
expect(denied.status).toBe(200);
expect(denied.headers.get('access-control-allow-origin')).toBeNull();
}
// Once the lookup recovers the origin is allowed again, which also proves the two failures
// returned their slots: a budget of 2 that leaked would have shed this one.
lookupDown = false;
const recovered = await fetchHandler(request());
expect(recovered.status).toBe(200);
expect(recovered.headers.get('access-control-allow-origin')).toBe('https://example.com');
});
it('rejects requests above maxConcurrentRequests and releases the slot afterwards', async () => {
@@ -156,6 +166,28 @@ describe('buildFetch request gate', () => {
const afterRelease = await fetchHandler(new Request('http://localhost/slow'));
expect(afterRelease.status).toBe(200);
});
it('consults a cors.origins predicate once per request on the fetch path too', async () => {
let calls = 0;
const fetchHandler = buildFetch(
[{ method: 'GET', pattern: '/ok', transport: 'buffer',
handler: async () => ({ status: 200, headers: {}, body: 'ok' }) }],
{ cors: { origins: () => { calls++; return true; } } },
);
const res = await fetchHandler(new Request('http://localhost/ok', { headers: { origin: 'https://a.com' } }));
expect(res.headers.get('access-control-allow-origin')).toBe('https://a.com');
expect(calls).toBe(1);
calls = 0;
const preflight = await fetchHandler(new Request('http://localhost/ok', {
method: 'OPTIONS',
headers: { origin: 'https://a.com', 'access-control-request-method': 'GET' },
}));
expect(preflight.status).toBe(204);
expect(preflight.headers.get('access-control-allow-methods')).toContain('GET');
expect(calls).toBe(1);
});
it('releases the slot when a streaming handler returns', async () => {
async function* stream() {
yield { n: 1 };
+1 -1
View File
@@ -15,5 +15,5 @@
"forceConsistentCasingInFileNames": true
},
"include": ["src", "test", "example"],
"exclude": ["test/deno", "test/bun", "test/edge"]
"exclude": ["test/deno", "test/bun", "test/edge", "test/interop/_signal-app-deno.ts"]
}