Merge pull request 'feat(http): liveness and readiness probes with a drain window (CARD-17, #115)' (#145) from feature/fprd-001c-health into develop
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 17s
CI / build (push) Successful in 27s
CI / runtimes (deno) (push) Successful in 20s
CI / runtimes (edge) (push) Successful in 14s
Promote → GitHub / push-github (push) Successful in 5s

This commit was merged in pull request #145.
This commit is contained in:
chrnx committed 2026-10-23 05:58:56 +00:00
commit 1da6bf2f99
15 files changed
+789 -10

No files matched your search

+20
View File
@@ -92,6 +92,26 @@ npm treats versions as semver and semver forbids leading zeros.
### Added
- **Health probes: `createApp({ health: true })`** (#115). Off by default. `GET`/`HEAD /__live__`
answers `200 {"status":"ok"}` whenever the process answers. `/__ready__` answers
`503 {"status":"booting"}` until `boot()` resolves, then `200 {"status":"ok"}` or
`200 {"status":"degraded","degraded":[…]}` (from `app.degraded()`), and
`503 {"status":"draining"}` from the moment `close()` starts: Node `app.close()`, and the
`close()` that `serveDeno()`/`serveBun()` return. Probes are answered by the adapter, ahead of
`maxConcurrentRequests` and the route table, so they are never shed and run no step, provider,
plugin or `onError`, and emit no lifecycle event (`logRequests` and metrics plugins do not see
them). Security headers still apply, plus `cache-control: no-store`; other methods get `405` with
`Allow: GET, HEAD`. While `health` is on, a route at either path fails the boot, local or spliced
from a teapot. A probe through `app.fetch` before the boot starts the boot without waiting for it.
`health: { drainDelayMs }` (default 0) keeps the listener open that long after `close()` starts,
with `/__ready__` already answering `503`, before connections drain. Without it Node closes idle
keep-alive connections at once, so a probe usually sees a refused connection rather than a `503`.
The window is spent out of the shutdown budget; `createApp` throws when `drainDelayMs` plus
`teardownTimeoutMs` exceeds `shutdownTimeoutMs`, and on any `health` value other than `true`,
`false` or `{ drainDelayMs?: number }`. On the edge there is no `close()`, so `/__ready__` never
reports `draining` there.
- **`limits.maxWsMessageBytes` and `limits.maxWsQueue`** (#107): per-connection bounds on inbound
WebSocket messages, in bytes and in unread messages, server-wide on every runtime. `createApp`
throws a `TypeError` for anything but a positive integer. Node and Bun refuse an oversized message
+1
View File
@@ -144,6 +144,7 @@ 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. WebSocket connections are bounded too: `maxWsMessageBytes` (default 1 MiB) closes a connection whose message is larger with `1009`, and `maxWsQueue` (default `16`) closes one that has that many unread inbound messages and receives another with `1013`, rather than dropping anything. Both are server-wide and must be positive integers. Node and Bun refuse an oversized message before buffering it (Bun before 1.4 drops the connection, so its peer sees `1006`; Bun 1.4 and later send `1009`); Deno and the edge check it after the runtime has received it. Worst case, a server buffers about `maxConnections × maxWsQueue × maxWsMessageBytes` of inbound messages — ≈ 15.6 GiB at the Node defaults.
- **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 })`.
- **Liveness and readiness probes.** `createApp({ health: true })` serves `/__live__` and `/__ready__`. Readiness reports `booting`, `ok`, `degraded` (optional providers that failed) or `draining` (from the moment `close()` starts). Probes are answered ahead of the pipeline: they are never shed and never show up in lifecycle events or request logs. `health: { drainDelayMs }` keeps the listener open for that window after `close()` starts, so a load balancer reads the `503` before connections drain. The edge never reports `draining`, because it has no `close()`.
- **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.
+73 -7
View File
@@ -8,7 +8,7 @@ import { runPipeline, runSteps, PipelineStep } from '../pipeline';
import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } from '../http';
import type { HttpOptions } from '../http';
import { trustedProxyClient } from '../http/peer';
import { buildFetch } from '../http/web';
import { answerFetchProbe, buildFetch } from '../http/web';
import {
boundInbound,
validateWsLimits,
@@ -53,6 +53,7 @@ import { inspectRoute, buildGraphView, explainRoute } from './introspect';
import { compilePattern, markRemoteRoute, normalizeRequestPath } from '../http/router';
import { routeConflict, type Precedence, type RouteConflict } from '../http/route-conflicts';
import { assertNotReserved, type ReservedPath } from '../http/reserved-paths';
import { HEALTH_DRAIN, HEALTH_RESERVED, resolveHealth, trackHealth, type HealthConfig } from '../http/health';
export type { App, InspectLine, ExplainNode, Explain, MeshConfig, Hooks } from './types';
@@ -122,6 +123,27 @@ export function createApp(opts: {
limits?: RequestLimits;
devGraph?: boolean;
devOpenapi?: boolean;
/**
* Serve `GET`/`HEAD` `/__live__` and `/__ready__` for load balancers and orchestrators (default: off).
*
* - `/__live__` answers `200 {"status":"ok"}` whenever the process answers.
* - `/__ready__` answers `503 {"status":"booting"}` until `boot()` resolves, then
* `200 {"status":"ok"}` or `200 {"status":"degraded","degraded":[…]}` (see `app.degraded()`),
* and `503 {"status":"draining"}` from the moment `close()` starts.
*
* Probes skip the pipeline: no step, provider, plugin or `onError` runs and no lifecycle event is
* emitted, so `logRequests` and metrics plugins never see them. `maxConcurrentRequests` never sheds
* them. Security headers still apply, plus `cache-control: no-store`; other methods get `405`.
* While on, a route at either path fails the boot.
*
* `drainDelayMs` (default 0) keeps the listener open that long after `close()` starts, with
* `/__ready__` already answering `503`, before connections drain. Without it Node closes idle
* keep-alive connections at once, so a probe usually sees a refused connection rather than a `503`.
* The window is spent out of the shutdown budget (`shutdownTimeoutMs`), not added to it.
*
* On the edge there is no `close()`, so `/__ready__` never reports `draining` there.
*/
health?: boolean | { drainDelayMs?: number };
overrides?: Record<string, unknown>;
tls?: TlsOptions;
trustProxy?: boolean;
@@ -209,6 +231,7 @@ export function createApp(opts: {
}
validateWsLimits(opts.limits);
const health = resolveHealth(opts.health, opts.shutdownTimeoutMs, opts.teardownTimeoutMs);
const bus = new Bus();
const logger = opts.logger ?? createDefaultLogger();
@@ -222,7 +245,7 @@ export function createApp(opts: {
const viewsCtx: ViewsContext = { views: opts.views, viewEngine: opts.viewEngine };
const registry = collectModules(opts.modules, viewsCtx);
const { providerNodes, stepNodes, runners, providerMeta, routePlans } = registry;
const reserved = reservedPaths();
const reserved = reservedPaths(health);
assertNoReservedRoutes(routePlans, reserved);
const teardown = buildTeardownRegistry(opts.hooks, opts.teardownTimeoutMs, opts.shutdownTimeoutMs);
mountPlugins(opts.plugins, bus, registry, teardown);
@@ -304,7 +327,7 @@ export function createApp(opts: {
// Boots exactly once, however first triggered (app.fetch, app.upgrade or listen()); calling
// several never double-boots (which would re-run provider factories and their side effects).
const bootApp = makeAppBooter(
const bootGraph = makeAppBooter(
registry,
opts.overrides,
() => orderedProviders,
@@ -313,6 +336,8 @@ export function createApp(opts: {
ready,
);
const { bootApp, healthProbe, drain } = trackHealth(health, bootGraph, () => [...degradedProviders]);
const staticResolver = opts.static ? buildStaticResolver(opts.static) : undefined;
const fetchOpts: HttpOptions = {
@@ -326,6 +351,7 @@ export function createApp(opts: {
bodyDuplicates: opts.bodyDuplicates,
onError: opts.onError,
static: staticResolver,
health: healthProbe,
};
const fetchFn = buildAppFetch(
routePlans,
@@ -362,6 +388,7 @@ export function createApp(opts: {
bodyDuplicates: opts.bodyDuplicates,
onError: opts.onError,
static: staticResolver,
health: healthProbe,
});
server.on('close', () => closeLinks(meshLinks));
await new Promise<void>((resolve) => server!.listen(port, resolve));
@@ -381,13 +408,16 @@ export function createApp(opts: {
removeSignalHandlers = undefined;
};
const close = (options: { timeoutMs?: number } = {}): Promise<void> => {
const close = async (options: { timeoutMs?: number } = {}): Promise<void> => {
clearSignalHandlers();
// `/__ready__` flips to draining first, and the listener stays open for the drain window.
const budget = await spendDrainWindow(drain, options, opts.shutdownTimeoutMs, server !== undefined);
return closeApp(
server,
meshLinks,
streams,
options,
budget,
opts.shutdownTimeoutMs,
logger,
teardown,
@@ -428,6 +458,7 @@ export function createApp(opts: {
return Object.assign(app, {
[WS_MAX_MESSAGE_BYTES]: wsMessageBytes(opts.limits),
[HEALTH_DRAIN]: drain,
});
}
@@ -635,14 +666,38 @@ function resolveTransformer(
return buildHtmlTransformer(html, viewsCtx);
}
/**
* Runs the drain window and returns the options `closeApp` should get for what is left.
*
* The window comes out of the close budget, so close() still returns within the timeout it was
* given. Adjusted only when there is a server: without one closeApp only runs teardown, and an
* explicit timeout there earns a warning the caller never asked for.
*/
async function spendDrainWindow(
drain: () => Promise<void>,
options: { timeoutMs?: number },
shutdownTimeoutMs: number | undefined,
hasServer: boolean,
): Promise<{ timeoutMs?: number }> {
const startedAt = Date.now();
await drain();
const waited = Date.now() - startedAt;
if (!hasServer || waited === 0) return options;
const budget = options.timeoutMs ?? shutdownTimeoutMs ?? 10_000;
return { timeoutMs: Math.max(0, budget - waited) };
}
/**
* The paths this app answers itself, ahead of the route table (D17).
*
* `/__mesh__/control` is reserved in every app, mesh or not: whether a route there is served must not
* depend on the runtime or on whether a mesh happens to be configured.
*/
function reservedPaths(): ReservedPath[] {
return [{ path: MESH_CONTROL_PATH, purpose: 'the mesh control channel' }];
function reservedPaths(health: HealthConfig | undefined): ReservedPath[] {
const mesh: ReservedPath = { path: MESH_CONTROL_PATH, purpose: 'the mesh control channel' };
// The probe paths only while health is on: with it off they are ordinary paths (CARD-17 rule 7).
return health ? [mesh, ...HEALTH_RESERVED] : [mesh];
}
/** Fails the boot when a declared route claims a reserved path (see {@link assertNotReserved}). */
@@ -1402,6 +1457,17 @@ function buildAppFetch(
let handler: ((request: Request) => Promise<Response>) | undefined;
return async (request: Request): Promise<Response> => {
// Before the boot, or `/__ready__` could never say `booting`: it would wait for the boot to end.
// The boot is still started, not awaited: on the edge, or under a bare `Deno.serve(app.fetch)`,
// nothing else may boot the app, and an orchestrator that waits for ready before sending traffic
// would wait forever. The rejection is dropped here only; the memo keeps it for real requests.
const probe = answerFetchProbe(request, fetchOpts);
if (probe) {
ensureBooted().catch(() => {});
return probe;
}
await ensureBooted(); // idempotent: no-op once any of fetch/upgrade/listen has booted
if (!handler) {
+9
View File
@@ -37,6 +37,15 @@ export interface Explain {
/** A running application instance with lifecycle, introspection and graph-export methods. */
export interface App {
listen(port: number): Promise<http.Server>;
/**
* Drains in-flight work, closes the server and mesh links, then runs teardown, all within
* `timeoutMs` (default `shutdownTimeoutMs`, else 10s).
*
* With `createApp({ health })` on, `/__ready__` answers `503 {"status":"draining"}` from the first
* line of this call, and the listener stays open for `health.drainDelayMs` before draining starts.
* That window is part of `timeoutMs`. On Deno and Bun the same happens in the `close()` that
* `serveDeno()`/`serveBun()` return.
*/
close(options?: { timeoutMs?: number }): Promise<void>;
/**
* Wires `SIGINT`/`SIGTERM` to `closer` and returns a close that also unregisters them — or
+6 -1
View File
@@ -2,6 +2,7 @@ import { channel } from './channel';
import type { Channel } from './channel';
import type { App } from './app/types';
import { WS_MAX_MESSAGE_BYTES, DEFAULT_MAX_WS_MESSAGE_BYTES, type WsSocket, type WsRequest } from './http/ws-core';
import { beginDrain } from './http/health';
import { decodeMessage, neutralSocket, toWsRequest, upgradeSafely } from './http/ws-adapter';
import { closeWithDeadline } from './http/shutdown';
import { setPeer } from './http/peer';
@@ -149,7 +150,11 @@ export async function serveBun(app: App, options?: BunServeShortOptions): Promis
// registry, which is what makes one `close()` enough here instead of two. Called without
// options on purpose: passing a timeout it cannot use to drain would only earn its warning,
// and the deadline below already bounds the whole call.
() => server.stop(false).then(() => app.close()),
// The drain window first: `/__ready__` answers 503 while the listener is still open (D14).
() =>
beginDrain(app)
.then(() => server.stop(false))
.then(() => app.close()),
() => void server.stop(true),
closeOptions.timeoutMs ?? 10_000,
(ms) =>
+6 -1
View File
@@ -1,4 +1,5 @@
import type { App } from './app/types';
import { beginDrain } from './http/health';
import { eventSocket, toWsRequest, upgradeSafely, type EventfulSocket } from './http/ws-adapter';
import { closeWithDeadline } from './http/shutdown';
import { setPeer } from './http/peer';
@@ -102,7 +103,11 @@ export async function serveDeno(app: App, options?: DenoServeOptions): Promise<D
// registry, which is what makes one `close()` enough here instead of two. Called without
// options on purpose: passing a timeout it cannot use to drain would only earn its warning,
// and the deadline below already bounds the whole call.
() => server.shutdown().then(() => app.close()),
// The drain window first: `/__ready__` answers 503 while the listener is still open (D14).
() =>
beginDrain(app)
.then(() => server.shutdown())
.then(() => app.close()),
// Nothing to force, and that is Deno's constraint rather than an omission here. Its two
// levers are mutually exclusive: aborting the serve signal after `shutdown()` is already
// pending throws `BadResource: Bad resource ID` from Deno's own abort listener, which
+170
View File
@@ -0,0 +1,170 @@
import type { ReservedPath } from './reserved-paths';
/** Liveness probe path: `200` whenever the process answers. */
export const LIVE_PATH = '/__live__';
/** Readiness probe path: `503` while booting or draining, `200` otherwise. */
export const READY_PATH = '/__ready__';
/** The probe paths, as reserved-path entries for the boot check (only while `health` is on). */
export const HEALTH_RESERVED: readonly ReservedPath[] = [
{ path: LIVE_PATH, purpose: 'the liveness probe, health: true' },
{ path: READY_PATH, purpose: 'the readiness probe, health: true' },
];
/**
* Where an app is in its life, as `/__ready__` reports it.
*
* `booting` until `boot()` resolves, `ready` after, `draining` from the moment `close()` starts.
* Moves forward only: a boot that finishes while draining does not make the app ready again.
*/
export type HealthPhase = 'booting' | 'ready' | 'draining';
/** What the adapters read to answer a probe. Lives on {@link HttpOptions}; absent when `health` is off. */
export interface HealthProbe {
phase(): HealthPhase;
/** Optional providers that failed to boot, as `app.degraded()` reports them. */
degraded(): string[];
}
/**
* Close-time hook on the app object for the adapters that own the server (`serveDeno`, `serveBun`):
* marks the app draining and resolves after `drainDelayMs`, so the listener stays open while
* `/__ready__` answers `503`. Idempotent — later calls share the first window. Symbol-keyed because it
* is adapter plumbing, not public API.
*/
export const HEALTH_DRAIN: unique symbol = Symbol.for('green-tea.health-drain');
/** Starts the drain window on `app` (see {@link HEALTH_DRAIN}); resolves at once when health is off. */
export function beginDrain(app: object): Promise<void> {
return (app as { [HEALTH_DRAIN]?: () => Promise<void> })[HEALTH_DRAIN]?.() ?? Promise.resolve();
}
/** A probe response, before the adapter merges in the injected security headers. */
export interface ProbeAnswer {
status: number;
headers: Record<string, string>;
body: string;
}
const JSON_NO_STORE = { 'content-type': 'application/json', 'cache-control': 'no-store' };
/** The readiness body and status for the current phase. */
function readiness(probe: HealthProbe): { status: number; body: object } {
const phase = probe.phase();
if (phase === 'booting') return { status: 503, body: { status: 'booting' } };
if (phase === 'draining') return { status: 503, body: { status: 'draining' } };
const degraded = probe.degraded();
return degraded.length
? { status: 200, body: { status: 'degraded', degraded } }
: { status: 200, body: { status: 'ok' } };
}
/**
* Answers `/__live__` or `/__ready__`, or returns `undefined` for any other path.
*
* Called by each adapter before the request gate and before `handle()`, so a probe runs no step,
* provider, plugin or `onError`, emits no lifecycle event, and is never shed by
* `maxConcurrentRequests`. `url` may carry a query string; only the exact path is a probe.
*/
export function answerProbe(method: string, url: string, probe: HealthProbe): ProbeAnswer | undefined {
const query = url.indexOf('?');
const path = query === -1 ? url : url.slice(0, query);
if (path !== LIVE_PATH && path !== READY_PATH) return undefined;
if (method !== 'GET' && method !== 'HEAD') {
return {
status: 405,
headers: { ...JSON_NO_STORE, allow: 'GET, HEAD' },
body: JSON.stringify({ error: 'Method Not Allowed' }),
};
}
const { status, body } = path === LIVE_PATH ? { status: 200, body: { status: 'ok' } } : readiness(probe);
return { status, headers: { ...JSON_NO_STORE }, body: method === 'HEAD' ? '' : JSON.stringify(body) };
}
/** `createApp({ health })`, normalised. `undefined` when health is off. */
export interface HealthConfig {
drainDelayMs: number;
}
/**
* Validates `createApp({ health })` and normalises it. Throws on anything but `true`, `false`,
* `undefined` or `{ drainDelayMs?: number }`, and on a `drainDelayMs` that does not fit in the shutdown
* budget next to the teardown reservation.
*/
export function resolveHealth(
health: unknown,
shutdownTimeoutMs: number | undefined,
teardownTimeoutMs: number | undefined,
): HealthConfig | undefined {
if (health === undefined || health === false) return undefined;
if (health === true) return { drainDelayMs: 0 };
if (typeof health !== 'object' || health === null || Array.isArray(health)) {
throw new Error(`health must be true, false or { drainDelayMs?: number } — got ${JSON.stringify(health)}`);
}
const unknown = Object.keys(health).filter((key) => key !== 'drainDelayMs');
if (unknown.length) {
throw new Error(
`health: unknown option ${unknown.map((key) => `'${key}'`).join(', ')} — only drainDelayMs is supported`,
);
}
const drainDelayMs = (health as { drainDelayMs?: unknown }).drainDelayMs ?? 0;
if (typeof drainDelayMs !== 'number' || !Number.isFinite(drainDelayMs) || drainDelayMs < 0) {
throw new Error(`health.drainDelayMs must be a non-negative number of milliseconds — got ${String(drainDelayMs)}`);
}
const budget = shutdownTimeoutMs ?? 10_000;
const reserved = teardownTimeoutMs ?? 0;
if (drainDelayMs + reserved > budget) {
throw new Error(
`health.drainDelayMs (${drainDelayMs}) plus teardownTimeoutMs (${reserved}) cannot exceed ` +
`shutdownTimeoutMs (${budget}) — the drain window is spent out of the shutdown budget, ` +
'so close() would have no time left to drain connections or run teardown.',
);
}
return { drainDelayMs };
}
/**
* The health state machine for one app: wraps `bootGraph` so a resolved boot marks it ready, and
* offers the drain that `close()` (and `serveDeno`/`serveBun` through {@link HEALTH_DRAIN}) starts.
* With health off the probe is absent and the drain resolves at once.
*/
export function trackHealth(
health: HealthConfig | undefined,
bootGraph: () => Promise<void>,
degraded: () => string[],
): { bootApp: () => Promise<void>; healthProbe: HealthProbe | undefined; drain: () => Promise<void> } {
// Forward only: a boot that resolves after close() started stays draining.
let phase: HealthPhase = 'booting';
// Shared by every drain call. Left referenced on purpose: the process must stay up for the window.
let drainWindow: Promise<void> | undefined;
const bootApp = async (): Promise<void> => {
await bootGraph();
if (phase === 'booting') phase = 'ready';
};
const drain = (): Promise<void> => {
if (!health) return Promise.resolve();
if (!drainWindow) {
phase = 'draining';
const ms = health.drainDelayMs;
drainWindow = ms > 0 ? new Promise((resolve) => setTimeout(resolve, ms)) : Promise.resolve();
}
return drainWindow;
};
return { bootApp, healthProbe: health ? { phase: () => phase, degraded } : undefined, drain };
}
+17
View File
@@ -20,6 +20,7 @@ import type { BodyFailure, BodyReader } from './body';
import type { RouteDef, WsRouteDef, MeshControl, HttpOptions } from './types';
import type { Logger } from '../logger';
import { nodeRequire } from '../node-require';
import { answerProbe } from './health';
interface HandlerConfig {
routes: RouteDef[];
@@ -116,6 +117,8 @@ function createRequestHandler(cfg: HandlerConfig) {
const injected = computeInjected(opts, { secure, headers: req.headers });
patchResponseHeaders(res, injected);
if (writeProbe(req, res, opts)) return;
let result: HandleResult | Preflight;
let acquired = false;
const watching = watchingRequests(bus);
@@ -203,6 +206,20 @@ function createRequestHandler(cfg: HandlerConfig) {
}
}
/**
* Answers a health probe and returns true, or returns false for any other request. Runs before the
* gate, so shedding never refuses a probe, and before `handle()`, so no step, plugin or lifecycle
* event sees one. Written through the patched writeHead, so the security headers still land.
*/
function writeProbe(req: http.IncomingMessage, res: http.ServerResponse, opts: HttpOptions | undefined): boolean {
const probe = opts?.health && answerProbe(req.method ?? 'GET', req.url ?? '/', opts.health);
if (!probe) return false;
res.writeHead(probe.status, probe.headers);
res.end(probe.body);
return true;
}
/**
* The last resort for a request whose handling rejected. Deliberately does not call `onError`: this
* runs because something already failed past the point where errors convert to a response, and user
+6
View File
@@ -1,4 +1,5 @@
import type { Transport } from '../metadata';
import type { HealthProbe } from './health';
import type { PipelineResult } from '../pipeline';
import type { ErrorRenderer } from '../transformers';
import type { TlsOptions, SecurityOptions, CorsOptions } from '../security';
@@ -62,6 +63,11 @@ export interface HttpOptions {
bodyDuplicates?: 'array' | 'last';
onError?: ErrorRenderer;
static?: StaticResolver;
/**
* Answers `/__live__` and `/__ready__` ahead of the gate and the route table (`createApp({ health })`).
* Absent when health is off, so no path is intercepted.
*/
health?: HealthProbe;
}
/** Handler for a matched HTTP route; receives a normalized request and resolves to a pipeline result. */
+23
View File
@@ -16,6 +16,7 @@ import { declaresOverLimit, type BodyFailure, type BodyReader, type MaybePromise
import { HttpError } from '../signals';
import { renderError, type ErrorRequest } from '../transformers';
import type { RouteDef, HttpOptions } from './types';
import { answerProbe } from './health';
/**
* Wraps an AsyncIterable as a web ReadableStream, encoding each value. Cancels the source on stream
@@ -326,3 +327,25 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
return outcomeToResponse(result, opts?.bus, correlation);
};
}
/**
* Answers a health probe through the Fetch API, or returns `undefined` for any other request (or when
* `health` is off). `app.fetch` calls this before awaiting the boot, which is what lets `/__ready__`
* report `booting` at all, and before the gate and `handle()`, for the same reasons as the Node adapter.
*/
export function answerFetchProbe(request: Request, opts: HttpOptions | undefined): Response | undefined {
if (!opts?.health) return undefined;
const url = new URL(request.url);
const probe = answerProbe(request.method, url.pathname + url.search, opts.health);
if (!probe) return undefined;
const injected = computeInjected(opts, {
secure: url.protocol === 'https:',
headers: headersToRecord(request.headers),
});
return new Response(probe.body || null, {
status: probe.status,
headers: mergeInjectedHeaders(probe.headers, injected) as Record<string, string>,
});
}
+21
View File
@@ -97,3 +97,24 @@ test('serveBun rejects when a provider fails, instead of binding a port that 500
await expect(serveBun(app, { port: 0 })).rejects.toThrow(/no such key file/);
});
// CARD-17 T5 (D14): close() marks the app draining before the server stops, and the drain window
// keeps the listener open long enough for a probe to read the 503.
test('serveBun close() with health.drainDelayMs: /__ready__ 503 draining, in-flight request 200', async () => {
const app = createApp({ modules: [M], health: { drainDelayMs: 300 } });
const server = await serveBun(app, { port: 0 });
const base = `http://127.0.0.1:${server.port}`;
expect((await fetch(`${base}/__ready__`)).status).toBe(200);
const inFlight = fetch(`${base}/slow`).then((r) => r.json());
await Bun.sleep(50);
const closing = server.close({ timeoutMs: 5000 });
const probe = await fetch(`${base}/__ready__`);
expect(probe.status).toBe(503);
expect(await probe.json()).toEqual({ status: 'draining' });
expect(await inFlight).toEqual({ ok: true });
await closing;
});
+26
View File
@@ -121,3 +121,29 @@ Deno.test('serveDeno rejects when a provider fails, instead of binding a port th
throw new Error(`expected serveDeno to reject with the provider's error, got: ${message || '<resolved>'}`);
}
});
// CARD-17 T5 (D14): close() marks the app draining before the server shuts down, and the drain window
// keeps the listener open long enough for a probe to read the 503.
Deno.test('serveDeno close() with health.drainDelayMs: /__ready__ 503 draining, in-flight request 200', async () => {
const app = createApp({ modules: [M], health: { drainDelayMs: 300 } });
const server = await serveDeno(app, { port: 0, onListen: () => {} });
const base = `http://127.0.0.1:${portOf(server)}`;
const ready = await fetch(`${base}/__ready__`);
if (ready.status !== 200) throw new Error(`ready before close: ${ready.status}`);
await ready.body?.cancel();
const inFlight = fetch(`${base}/slow`).then((r) => r.json());
await new Promise((r) => setTimeout(r, 50));
const closing = server.close({ timeoutMs: 5000 });
const probe = await fetch(`${base}/__ready__`);
const body = await probe.json();
if (probe.status !== 503 || body.status !== 'draining') {
throw new Error(`probe during close: ${probe.status} ${JSON.stringify(body)}`);
}
const done = await inFlight;
if (done.ok !== true) throw new Error(`in-flight request was cut: ${JSON.stringify(done)}`);
await closing;
});
+20 -1
View File
@@ -171,8 +171,27 @@ async function main() {
assert.equal(reservedRes.status, 500);
assert.match(await reservedRes.text(), /^route @Ws \/__mesh__\/control at Claims\.control uses the reserved path/);
// CARD-17 T10: live 200; ready booting → ok, with only probes reaching the isolate. There is no
// close() on workerd, so draining is never reported here (documented, not tested for). Any probe
// starts the boot, so ready is asked first to see `booting`.
const first = await mf.dispatchFetch('http://health/__ready__');
assert.equal(first.status, 503);
assert.deepEqual(await first.json(), { status: 'booting' });
const live = await mf.dispatchFetch('http://health/__live__');
assert.equal(live.status, 200);
assert.deepEqual(await live.json(), { status: 'ok' });
let ready = await mf.dispatchFetch('http://health/__ready__');
for (let i = 0; i < 20 && ready.status !== 200; i++) {
await ready.arrayBuffer();
await new Promise((resolve) => setTimeout(resolve, 25));
ready = await mf.dispatchFetch('http://health/__ready__');
}
assert.equal(ready.status, 200);
assert.deepEqual(await ready.json(), { status: 'ok' });
assert.equal(ready.headers.get('cache-control'), 'no-store');
console.log(
'edge (workerd via miniflare): HTTP 200 + body limits 413/413/200/413 + WS echo:hi + ws limits + cf-connecting-ip under trustProxy + reserved path — PASS',
'edge (workerd via miniflare): HTTP 200 + body limits 413/413/200/413 + WS echo:hi + ws limits + cf-connecting-ip under trustProxy + reserved path + health — PASS',
);
} finally {
await mf.dispose();
+2
View File
@@ -68,6 +68,8 @@ const handlers: Record<string, ReturnType<typeof edgeHandler>> = {
default: edgeHandler(app),
limited: edgeHandler(limited),
trusted: edgeHandler(trusted),
// CARD-17 T10: health probes, reached through the `health` host. Never booted by anything but probes.
health: edgeHandler(createApp({ modules: [M], health: true })),
};
// CARD-21 (D17): a route on the reserved mesh path must fail createApp inside workerd too. Built per
+389
View File
@@ -0,0 +1,389 @@
/**
* CARD-17 (#115, D14): `createApp({ health })` serves `/__live__` and `/__ready__` outside the pipeline,
* with booting / ok / degraded / draining states and a drain window on close(). Deno and Bun repeat
* the drain case (T5) in their own suites; workerd covers T10 in `test/edge/run.ts`.
*/
import 'reflect-metadata';
import { describe, it, expect, vi, afterEach } from 'vitest';
import http from 'http';
import type { AddressInfo } from 'net';
import { WebSocketServer } from 'ws';
import { createApp, Route, Get, Ws, Module, Provider } from '../src/index';
import type { Logger } from '../src/logger';
import type { Plugin } from '../src/plugin';
import { encode, decode, MESH_PROTOCOL_VERSION } from '../src/mesh/protocol';
const silentLogger = (): Logger => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() });
const sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));
let releaseSlow: () => void = () => {};
@Route('/')
class Ctl {
@Get('/ping') ping() {
return { ok: true };
}
// Held open until the test releases it: an in-flight request across close().
@Get('/slow') async slow() {
await new Promise<void>((resolve) => (releaseSlow = resolve));
return { slow: true };
}
}
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
type AppOpts = Parameters<typeof createApp>[0];
const make = (extra: Partial<AppOpts> = {}) => createApp({ modules: [M], logger: silentLogger(), ...extra });
async function probe(app: ReturnType<typeof createApp>, path: string, method = 'GET') {
const res = await app.fetch(new Request(`http://x${path}`, { method }));
const text = await res.text();
return { status: res.status, body: text ? JSON.parse(text) : undefined, headers: res.headers };
}
describe('CARD-17: health probes through app.fetch', () => {
it('T1: /__ready__ is 503 booting while a slow provider boots, /__live__ is 200', async () => {
let finish: () => void = () => {};
@Provider({ provides: 'slowDb' })
class SlowDb {
async provide() {
await new Promise<void>((resolve) => (finish = resolve));
return {};
}
}
@Module({ mountpoint: '/', controllers: [Ctl], providers: [SlowDb] })
class Slow {}
const app = createApp({ modules: [Slow], health: true, logger: silentLogger() });
const booting = app.boot();
await sleep(10);
expect(await probe(app, '/__ready__')).toMatchObject({ status: 503, body: { status: 'booting' } });
expect(await probe(app, '/__live__')).toMatchObject({ status: 200, body: { status: 'ok' } });
finish();
await booting;
expect(await probe(app, '/__ready__')).toMatchObject({ status: 200, body: { status: 'ok' } });
});
it('T1: a probe before any boot starts the boot without waiting for it', async () => {
let started = false;
@Provider({ provides: 'watched' })
class Watched {
provide() {
started = true;
return {};
}
}
@Module({ mountpoint: '/', controllers: [Ctl], providers: [Watched] })
class W {}
const app = createApp({ modules: [W], health: true, logger: silentLogger() });
expect((await probe(app, '/__ready__')).body).toEqual({ status: 'booting' });
await sleep(10);
expect(started).toBe(true);
expect((await probe(app, '/__ready__')).body).toEqual({ status: 'ok' });
});
it('a failed boot keeps /__ready__ at 503 booting and still fails real requests', async () => {
@Provider({ provides: 'broken' })
class Broken {
provide(): never {
throw new Error('no pool');
}
}
@Module({ mountpoint: '/', controllers: [Ctl], providers: [Broken] })
class B {}
const app = createApp({ modules: [B], health: true, logger: silentLogger() });
await probe(app, '/__ready__');
await sleep(10);
expect(await probe(app, '/__ready__')).toMatchObject({ status: 503, body: { status: 'booting' } });
await expect(app.fetch(new Request('http://x/ping'))).rejects.toThrow("provider 'broken' failed: no pool");
});
it('T2: booted with nothing degraded → 200 ok', async () => {
const app = make({ health: true });
await app.boot();
expect(await probe(app, '/__ready__')).toMatchObject({ status: 200, body: { status: 'ok' } });
});
it('T3: an optional provider failed → 200 degraded with its name', async () => {
@Provider({ provides: 'x', optional: true })
class X {
provide(): never {
throw new Error('down');
}
}
@Module({ mountpoint: '/', controllers: [Ctl], providers: [X] })
class D {}
const app = createApp({ modules: [D], health: true, logger: silentLogger() });
await app.boot();
expect(await probe(app, '/__ready__')).toMatchObject({
status: 200,
body: { status: 'degraded', degraded: ['x'] },
});
});
it('T7: POST /__ready__ → 405 with Allow: GET, HEAD; HEAD answers with no body', async () => {
const app = make({ health: true });
await app.boot();
const post = await probe(app, '/__ready__', 'POST');
expect(post.status).toBe(405);
expect(post.headers.get('allow')).toBe('GET, HEAD');
const head = await probe(app, '/__live__', 'HEAD');
expect(head.status).toBe(200);
expect(head.body).toBeUndefined();
});
it('security headers are injected, cache-control is no-store, a query string is ignored', async () => {
const app = make({ health: true });
await app.boot();
const res = await probe(app, '/__ready__?verbose=1');
expect(res.status).toBe(200);
expect(res.headers.get('cache-control')).toBe('no-store');
expect(res.headers.get('x-content-type-options')).toBe('nosniff');
});
it('T9 + rule 5: no lifecycle event, no plugin step, no log line for a probe', async () => {
const step = vi.fn(() => ({}));
const plugin: Plugin = {
name: 'global-step',
mount(api) {
api.scope.add({ kind: 'step', name: 'everywhere', needs: [], provides: [], run: step });
},
};
const logger = silentLogger();
const app = createApp({ modules: [M], plugins: [plugin], health: true, logRequests: true, logger });
await app.boot();
const emit = vi.spyOn(app.bus, 'emit');
for (let i = 0; i < 10; i++) await probe(app, i % 2 ? '/__live__' : '/__ready__');
expect(emit).not.toHaveBeenCalled();
expect(step).not.toHaveBeenCalled();
expect(logger.info).not.toHaveBeenCalled();
// the control: an ordinary request does run the step and log
await app.fetch(new Request('http://x/ping'));
expect(step).toHaveBeenCalled();
expect(logger.info).toHaveBeenCalled();
});
it('T6: probes answer while maxConcurrentRequests sheds everything else', async () => {
const app = make({ health: true, limits: { maxConcurrentRequests: 1 } });
await app.boot();
const held = app.fetch(new Request('http://x/slow'));
await sleep(10);
expect((await app.fetch(new Request('http://x/ping'))).status).toBe(503);
expect((await probe(app, '/__ready__')).status).toBe(200);
expect((await probe(app, '/__live__')).status).toBe(200);
releaseSlow();
expect((await held).status).toBe(200);
});
it('health off: the probe paths are ordinary paths (404)', async () => {
const app = make();
expect((await app.fetch(new Request('http://x/__ready__'))).status).toBe(404);
});
it('draining after close() on an app served through app.fetch', async () => {
const app = make({ health: true });
await app.boot();
await app.close();
expect(await probe(app, '/__ready__')).toMatchObject({ status: 503, body: { status: 'draining' } });
expect((await probe(app, '/__live__')).status).toBe(200);
});
});
describe('CARD-17: health option validation and reserved paths', () => {
it('invalid health values throw at createApp', () => {
expect(() => make({ health: 'yes' as never })).toThrow(/health must be true, false or \{ drainDelayMs/);
expect(() => make({ health: { drainDelayMs: -1 } })).toThrow(/drainDelayMs must be a non-negative number/);
expect(() => make({ health: { drainDelayMs: Number.NaN } })).toThrow(/non-negative number/);
expect(() => make({ health: { checks: [] } as never })).toThrow(/unknown option 'checks'/);
expect(() => make({ health: { drainDelayMs: 20_000 } })).toThrow(/cannot exceed shutdownTimeoutMs \(10000\)/);
expect(() => make({ health: { drainDelayMs: 600 }, shutdownTimeoutMs: 1000, teardownTimeoutMs: 500 })).toThrow(
/plus teardownTimeoutMs \(500\)/,
);
expect(() => make({ health: { drainDelayMs: 500 } })).not.toThrow();
expect(() => make({ health: false })).not.toThrow();
});
it('T8: @Get(/__live__) with health on fails createApp, naming the route', () => {
@Route('/')
class Own {
@Get('/__live__') live() {
return {};
}
}
@Module({ mountpoint: '/', controllers: [Own] })
class O {}
expect(() => createApp({ modules: [O], health: true })).toThrow(
'route GET /__live__ at Own.live uses the reserved path /__live__ (the liveness probe, health: true) — ' +
'green-tea answers that path itself on every runtime, so no route may declare it. Move the route.',
);
});
it('a route at /__ready__ (HTTP or WS) fails with health on and serves with it off', async () => {
@Route('/')
class Own {
@Get('/__ready__') ready() {
return { mine: true };
}
}
@Module({ mountpoint: '/', controllers: [Own] })
class O {}
@Route('/')
class OwnWs {
@Ws('/__ready__') ready() {
return (async function* () {})();
}
}
@Module({ mountpoint: '/', controllers: [OwnWs] })
class OW {}
expect(() => createApp({ modules: [O], health: true })).toThrow(/^route GET \/__ready__ at Own\.ready uses/);
expect(() => createApp({ modules: [OW], health: true })).toThrow(/^route @Ws \/__ready__ at OwnWs\.ready uses/);
const off = createApp({ modules: [O] });
expect(await (await off.fetch(new Request('http://x/__ready__'))).json()).toEqual({ mine: true });
});
it('a teapot route at /__ready__ fails the teacup splice while health is on', async () => {
const wss = new WebSocketServer({ port: 0 });
wss.on('connection', (ws) => {
ws.on('message', (data) => {
if (decode(data.toString()).type === 'hello') {
ws.send(
encode({
type: 'manifest',
v: MESH_PROTOCOL_VERSION,
steps: [],
routes: [{ method: 'GET', pattern: '/__ready__' }],
}),
);
}
});
});
const url = `ws://127.0.0.1:${(wss.address() as AddressInfo).port}/__mesh__/control`;
const teacup = createApp({
modules: [M],
health: true,
experimental: true,
mesh: { teapots: [{ url, secret: 's' }] },
logger: silentLogger(),
});
try {
await expect(teacup.ready()).rejects.toThrow(
`mesh: remote route 'GET /__ready__' from ${url} uses the reserved path /__ready__`,
);
} finally {
await teacup.close();
wss.close();
}
});
});
/** One request on `agent` (kept alive), resolving with status and body. */
function request(port: number, path: string, agent: http.Agent) {
return new Promise<{ status: number; body: string }>((resolve, reject) => {
const req = http.get({ host: '127.0.0.1', port, path, agent }, (res) => {
let body = '';
res.on('data', (chunk) => (body += chunk));
res.on('end', () => resolve({ status: res.statusCode ?? 0, body }));
});
req.on('error', reject);
});
}
describe('CARD-17: the Node listener', () => {
const agents: http.Agent[] = [];
afterEach(() => agents.splice(0).forEach((agent) => agent.destroy()));
it('serves the probes before the gate; listen() boots first, so the listener never says booting', async () => {
const app = make({ health: true });
const server = await app.listen(0);
const agent = new http.Agent({ keepAlive: true });
agents.push(agent);
try {
const port = (server.address() as AddressInfo).port;
expect(await request(port, '/__ready__', agent)).toEqual({ status: 200, body: '{"status":"ok"}' });
expect(await request(port, '/__live__', agent)).toEqual({ status: 200, body: '{"status":"ok"}' });
} finally {
await app.close();
}
});
it('T4: close() flips /__ready__ to 503 on a kept-alive connection while a slow request completes', async () => {
const app = make({ health: { drainDelayMs: 300 } });
const server = await app.listen(0);
const port = (server.address() as AddressInfo).port;
const agent = new http.Agent({ keepAlive: true, maxSockets: 1 });
const slowAgent = new http.Agent({ keepAlive: true });
agents.push(agent, slowAgent);
// Warm the probe connection so the next probe reuses it.
expect((await request(port, '/__ready__', agent)).status).toBe(200);
const slow = request(port, '/slow', slowAgent);
await sleep(20);
const closing = app.close();
const drained = await request(port, '/__ready__', agent);
expect(drained).toEqual({ status: 503, body: '{"status":"draining"}' });
releaseSlow();
expect(await slow).toEqual({ status: 200, body: '{"slow":true}' });
await closing;
});
it('T4 without drainDelayMs: close() still marks the app draining before it drains', async () => {
const app = make({ health: true });
await app.listen(0);
await app.close();
expect((await probe(app, '/__ready__')).body).toEqual({ status: 'draining' });
});
it('the drain window comes out of the close() budget', async () => {
const app = make({ health: { drainDelayMs: 200 } });
await app.listen(0);
const started = Date.now();
await app.close({ timeoutMs: 1000 });
const took = Date.now() - started;
expect(took).toBeGreaterThanOrEqual(190);
expect(took).toBeLessThan(1000);
});
it('a POST probe on the listener answers 405 with Allow', async () => {
const app = make({ health: true });
const server = await app.listen(0);
try {
const port = (server.address() as AddressInfo).port;
const res = await new Promise<http.IncomingMessage>((resolve) => {
const req = http.request({ host: '127.0.0.1', port, path: '/__ready__', method: 'POST' }, resolve);
req.end();
});
res.resume();
expect(res.statusCode).toBe(405);
expect(res.headers.allow).toBe('GET, HEAD');
expect(res.headers['cache-control']).toBe('no-store');
} finally {
await app.close();
}
});
});