feat(http): liveness and readiness probes with a drain window (CARD-17, #115)
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / build (pull_request) Successful in 27s
CI / runtimes (deno) (pull_request) Successful in 21s
CI / runtimes (edge) (pull_request) Successful in 14s

createApp({ health: true }) serves GET/HEAD /__live__ and /__ready__.
Ready reports booting until boot() resolves, ok or degraded (from
app.degraded()) after that, and draining from the moment close() starts.

Probes are answered by the adapters, ahead of the request gate and of
handle(): Node in serve() (src/http/server.ts), the Fetch path in
app.fetch before it awaits the boot. Otherwise ready could never say
booting. Being ahead of the gate means maxConcurrentRequests never sheds
a probe (D14). Being ahead of handle() means no step, provider, plugin or
onError runs, and no lifecycle event is emitted, so logRequests and
metrics never see a probe. Security headers still apply, plus
cache-control: no-store. Other methods get 405 with Allow: GET, HEAD.

A probe through app.fetch before any boot starts the boot without
awaiting it. 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.

health: { drainDelayMs } (D14) marks the app draining and keeps the
listener open for that long before connections drain. Without it, Node
closes idle keep-alive sockets at once, and a probe sees a reset rather
than the 503. The window is spent out of the close budget. serveDeno and
serveBun start the same window, through a symbol-keyed hook on the app,
before server.shutdown() / server.stop(false). workerd has no close(),
so it never reports draining.

While health is on, /__live__ and /__ready__ join the reserved-path
boot check that CARD-21 introduced, for local and mesh-spliced routes.
Invalid health values throw at createApp.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-10-23 00:57:10 -05:00
1 parent 09251496c0
commit f0530b15bb
15 files changed
+789 -10

No files matched your search

+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>,
});
}