Files
core/test/deno/shutdown.test.ts
T
chrnx ba57568a84
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / build (pull_request) Successful in 27s
CI / runtimes (deno) (pull_request) Successful in 20s
CI / runtimes (edge) (pull_request) Successful in 14s
feat(http): liveness and readiness probes with a drain window (CARD-17, #115)
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>
2026-10-23 00:54:04 -05:00

150 lines
6.2 KiB
TypeScript

// Real Deno integration test for the bounded close() serveDeno returns. app.close() cannot do this
// job on Deno — it returns at its `if (!server)` guard, because a Deno app is served through
// app.fetch and never through listen() — so the deadline lives on the transport that owns the
// handle. See issue #15.
//
// Run with: npm run test:deno
import 'reflect-metadata';
import { createApp, Route, Get, Module, Provider, needs } from '../../src/index.ts';
import { serveDeno } from '../../src/deno.ts';
@Route('/')
class Ctl {
@Get('/hang')
hang() {
return new Promise(() => {}); // never resolves — a stuck handler
}
@Get('/slow')
async slow() {
await new Promise((r) => setTimeout(r, 200)); // finite, so draining has something real to wait out
return { ok: true };
}
}
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
const portOf = (server: { addr?: { port: number } }): number => server.addr!.port;
// On Deno the deadline bounds the wait, not the connections — see the comment on serveDeno's
// force callback. This test asserts exactly that: close() returns on time, and does so without
// the uncaught BadResource that aborting a draining server produces. The test runner fails on
// that error even when the assertions pass, so a green run here is the real assertion.
Deno.test('serveDeno close({ timeoutMs }) returns on a stuck handler without forcing', async () => {
const server = await serveDeno(createApp({ modules: [M] }), { port: 0, onListen: () => {} });
fetch(`http://127.0.0.1:${portOf(server)}/hang`).catch(() => {});
await new Promise((r) => setTimeout(r, 50)); // let the request actually reach the handler
const start = Date.now();
await server.close({ timeoutMs: 300 });
const elapsed = Date.now() - start;
// The assertion that matters is the upper bound: without the deadline this never returns.
if (elapsed >= 2000) throw new Error(`close() took ${elapsed}ms — the deadline did not fire`);
if (elapsed < 250) throw new Error(`close() returned in ${elapsed}ms — it did not wait the deadline`);
});
Deno.test('serveDeno close() drains an in-flight request rather than cutting it', async () => {
const server = await serveDeno(createApp({ modules: [M] }), { port: 0, onListen: () => {} });
const inFlight = fetch(`http://127.0.0.1:${portOf(server)}/slow`).then((r) => r.json());
await new Promise((r) => setTimeout(r, 50)); // must be *in* the handler before we close
await server.close({ timeoutMs: 5000 });
const body = await inFlight;
if (body.ok !== true) throw new Error(`in-flight request was cut: ${JSON.stringify(body)}`);
});
Deno.test('a caller-supplied signal still aborts the server', async () => {
const ac = new AbortController();
const server = await serveDeno(createApp({ modules: [M] }), { port: 0, signal: ac.signal, onListen: () => {} });
ac.abort();
await server.finished; // hangs here if chaining the caller's signal into ours dropped it
});
// D7 of the teardown design: a teardown must run on every runtime that has a shutdown, and it must
// run from the close() the runtime actually uses. app.close() returns at its no-server guard here,
// so proving the Node path works proves nothing about this one — hence a Deno assertion of its own.
Deno.test('serveDeno close() runs registered teardown', async () => {
const closed: string[] = [];
const app = createApp({
modules: [M],
hooks: [{ onShutdown: () => void closed.push('hook') }],
plugins: [{
name: 'teardown-probe',
mount: (api) => api.onShutdown(async () => {
await new Promise((r) => setTimeout(r, 10));
closed.push('plugin');
}),
}],
});
const server = await serveDeno(app, { port: 0 });
await server.close({ timeoutMs: 2000 });
// Reverse registration order: the plugin registered after the hook, so it tears down first.
if (closed.join(',') !== 'plugin,hook') throw new Error(`expected plugin,hook — got ${closed.join(',')}`);
});
// The boot gate, which is why serveDeno is async. Before it, a provider that threw was memoized as
// a rejection and answered 500 to every request from the runtime, never reaching onError — so the
// failure looked like a runtime fault at 3am instead of a deploy that refused to start.
@Provider({ provides: 'key' })
class BadKey {
provide(): never {
throw new Error('no such key file');
}
}
@Route('/')
class NeedsKey {
@Get('/signed')
signed(@needs('key') key: string) {
return { key };
}
}
@Module({ mountpoint: '/', providers: [BadKey], controllers: [NeedsKey] })
class KeyModule {}
Deno.test('serveDeno rejects when a provider fails, instead of binding a port that 500s', async () => {
const app = createApp({ modules: [KeyModule] });
let message = '';
try {
await serveDeno(app, { port: 0, onListen: () => {} });
} catch (error) {
message = (error as Error).message;
}
if (!message.includes('no such key file')) {
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;
});