Files
core/test/bun/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

121 lines
4.4 KiB
TypeScript

// Real Bun integration test for the bounded close() serveBun returns. app.close() cannot do this
// job on Bun — it returns at its `if (!server)` guard, because a Bun 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:bun (or: bun test test/bun/)
import 'reflect-metadata';
import { test, expect } from 'bun:test';
import { createApp, Route, Get, Module, Provider, needs } from '../../src/index.ts';
import { serveBun } from '../../src/bun.ts';
@Route('/')
class Ctl {
@Get('/hang')
hang() {
return new Promise(() => {}); // never resolves — a stuck handler
}
@Get('/slow')
async slow() {
await Bun.sleep(200); // finite, so draining has something real to wait out
return { ok: true };
}
}
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
test('serveBun close({ timeoutMs }) gives up on a stuck handler and resolves', async () => {
const server = await serveBun(createApp({ modules: [M] }), { port: 0 });
fetch(`http://127.0.0.1:${server.port}/hang`).catch(() => {});
await Bun.sleep(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.
expect(elapsed).toBeLessThan(2000);
expect(elapsed).toBeGreaterThanOrEqual(250);
});
test('serveBun close() drains an in-flight request rather than cutting it', async () => {
const server = await serveBun(createApp({ modules: [M] }), { port: 0 });
const inFlight = fetch(`http://127.0.0.1:${server.port}/slow`).then((r) => r.json());
await Bun.sleep(50); // the request must be *in* the handler before we close, or it never got in
await server.close({ timeoutMs: 5000 });
expect(await inFlight).toEqual({ ok: true });
});
// D7 of the teardown design: proving the Node path works proves nothing here, because app.close()
// returns at its no-server guard on Bun. The teardown has to run from the close() Bun actually uses.
test('serveBun 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 Bun.sleep(10);
closed.push('plugin');
}),
}],
});
const server = await serveBun(app, { port: 0 });
await server.close({ timeoutMs: 2000 });
// Reverse registration order: the plugin registered after the hook, so it tears down first.
expect(closed).toEqual(['plugin', 'hook']);
});
// The boot gate, which is why serveBun 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 {}
test('serveBun rejects when a provider fails, instead of binding a port that 500s', async () => {
const app = createApp({ modules: [KeyModule] });
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;
});