diff --git a/CHANGELOG.md b/CHANGELOG.md index c61d37f..18ad0c6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,28 @@ npm treats versions as semver and semver forbids leading zeros. ### Breaking +- **`serveDeno()` and `serveBun()` are async**, returning `Promise` and + `Promise`. They now boot the app before they bind, which is what `listen()` has + always done. + + They did not, and the documented fix was to remember to `await app.boot()` first. That made the + correct use of a core helper depend on reading a README, in a framework whose argument is that + order should not be something you have to get right. Forget it and a missing signing key is not a + failed deploy: the boot memo keeps the rejection, so the port binds, every request gets a 500 from + the runtime, and none of them reach `onError`. The server looks healthy to anything that only + checks whether it is listening. + + Migration is one keyword, and the value is unchanged: + + ```diff + - const server = serveDeno(app, { port }); + + const server = await serveDeno(app, { port }); + ``` + + Both runtimes support top-level `await`, so a module that serves at import time needs nothing + else. `edgeHandler` is deliberately untouched: on workerd there is no startup outside a request, + so there is no earlier moment to move the failure to. + - **A plugin is a named object.** `Plugin` is now `{ name, mount(api) }`; it was `(api) => void`. The name that `plugin:mounted` reports came from `fn.name`, which is `""` for an arrow returned straight from a factory, `"plugin"` for a `const`, and whatever a minifier leaves behind — so the @@ -57,11 +79,11 @@ npm treats versions as semver and semver forbids leading zeros. ### Added -- **`app.boot()`** runs the provider factories now instead of on the first request. `listen()` - always did this; `app.fetch`, `serveDeno`, `serveBun` and `edgeHandler` boot lazily, and the boot - memo keeps a rejection — so a bad key answered 500 on *every* request, from the runtime, without - reaching `onError`. `await app.boot()` before `Deno.serve`/`Bun.serve` turns that into a startup - failure. On workerd there is no startup outside a request, so calling it moves nothing. +- **`app.boot()`** runs the provider factories now instead of on the first request. `listen()`, + `serveDeno()` and `serveBun()` all call it for you (see Breaking, below). Call it by hand when you + drive `app.fetch` / `app.upgrade` from your own server: those boot lazily, and the boot memo keeps + a rejection, so a bad key answers 500 on *every* request, from the runtime, without reaching + `onError`. On workerd there is no startup outside a request, so calling it moves nothing. - **Errors are recognised by brand.** `HttpError` and `ValidationError` now carry `Symbol.for('green-tea.http-error')` and `Symbol.for('green-tea.validation-error')`, and `isHttpError` checks the brand instead of `instanceof`. An error thrown by code holding a diff --git a/bench/servers/green-tea-bun.ts b/bench/servers/green-tea-bun.ts index 2b5cbfa..729a919 100644 --- a/bench/servers/green-tea-bun.ts +++ b/bench/servers/green-tea-bun.ts @@ -30,5 +30,5 @@ class Bench { class BenchModule {} const app = createApp({ modules: [BenchModule], security: false }); -const server = serveBun(app, { port: 0, hostname: '0.0.0.0' }); +const server = await serveBun(app, { port: 0, hostname: '0.0.0.0' }); console.log(`READY ${server.port}`); diff --git a/bench/servers/green-tea-deno.ts b/bench/servers/green-tea-deno.ts index 70b0319..35fa75c 100644 --- a/bench/servers/green-tea-deno.ts +++ b/bench/servers/green-tea-deno.ts @@ -30,4 +30,4 @@ class Bench { class BenchModule {} const app = createApp({ modules: [BenchModule], security: false }); -serveDeno(app, { port: 0, hostname: '0.0.0.0', onListen: (a: { port: number }) => console.log(`READY ${a.port}`) }); +await serveDeno(app, { port: 0, hostname: '0.0.0.0', onListen: (a: { port: number }) => console.log(`READY ${a.port}`) }); diff --git a/src/app/types.ts b/src/app/types.ts index 2d0bb45..f21f6cb 100644 --- a/src/app/types.ts +++ b/src/app/types.ts @@ -62,11 +62,12 @@ export interface App { /** * Boots the providers now, instead of on the first request. * - * `listen()` already does this before it accepts a connection. Every other path — `app.fetch`, - * `app.upgrade`, `serveDeno`, `serveBun`, `edgeHandler` — boots lazily on the first request, and a - * provider that throws there fails *every* request, answered by the runtime with a 500 that never - * reaches `onError`. Calling this first turns that into a startup failure, which is where a bad - * key or an unreachable database belongs. + * The three serving helpers call it for you: `listen()` before it accepts a connection, + * `serveDeno()` and `serveBun()` before they bind. Calling it by hand is for the paths that have + * no startup of their own — `app.fetch` and `app.upgrade` driven by your own server, where a + * provider that throws fails *every* request, answered by the runtime with a 500 that never + * reaches `onError`, because the boot memo keeps the rejection. Calling this first turns that into + * a startup failure, which is where a bad key or an unreachable database belongs. * * Idempotent, and shares its memo with `listen()` and `fetch()`: calling both boots once. Unlike * `ready()`, it does run provider factories. diff --git a/src/bun.ts b/src/bun.ts index 32e8b06..99fec60 100644 --- a/src/bun.ts +++ b/src/bun.ts @@ -74,8 +74,20 @@ function bunSocket(ws: BunServerWebSocket): WsSocket { * (inbound channel, abort, WsRequest) is stashed on ws.data during the upgrade. * Bun.serve exposes no equivalent to Node's server.maxConnections; enforce connection caps at * the deployment platform or reverse proxy. + * + * **Boots before it binds**, which is why it is async — see the `await app.boot()` below. */ -export function serveBun(app: App, options?: BunServeShortOptions): BunServeResult { +export async function serveBun(app: App, options?: BunServeShortOptions): Promise { + // The same gate `listen()` runs before it binds a socket, and for the same reason: resolve the + // graph and run the provider factories here, so a missing key or an unreachable pool is a startup + // failure rather than a 500 on every request. + // + // Leaving it to `app.fetch` is not the lazier equivalent. The boot memo keeps a *rejection*, so + // the first request would fix the failure in place and the runtime would answer from it forever, + // without ever reaching `onError`. This was documented as something the caller should remember to + // do, which made the correct use of a core helper depend on reading a README. + await app.boot(); + const server = Bun.serve({ ...options, fetch(request, server) { diff --git a/src/deno.ts b/src/deno.ts index 323a61c..097af95 100644 --- a/src/deno.ts +++ b/src/deno.ts @@ -51,8 +51,20 @@ declare const Deno: { * WebSocket messages flow through app.upgrade over the shared neutral core. * Deno.serve exposes no equivalent to Node's server.maxConnections; enforce connection caps at * the deployment platform or reverse proxy. + * + * **Boots before it binds**, which is why it is async — see the `await app.boot()` below. */ -export function serveDeno(app: App, options?: DenoServeOptions): DenoServer { +export async function serveDeno(app: App, options?: DenoServeOptions): Promise { + // The same gate `listen()` runs before it binds a socket, and for the same reason: resolve the + // graph and run the provider factories here, so a missing key or an unreachable pool is a startup + // failure rather than a 500 on every request. + // + // Leaving it to `app.fetch` is not the lazier equivalent. The boot memo keeps a *rejection*, so + // the first request would fix the failure in place and the runtime would answer from it forever, + // without ever reaching `onError`. This was documented as something the caller should remember to + // do, which made the correct use of a core helper depend on reading a README. + await app.boot(); + // Deno's only force-close lever is the abort signal it was served with, so the adapter has to // own one to offer a deadline at all. A caller-supplied signal still works and still aborts the // server — it is chained into ours rather than replaced, so neither party loses its control. diff --git a/test/bun/mesh-reconnect.test.ts b/test/bun/mesh-reconnect.test.ts index cdb2e8c..5d01d85 100644 --- a/test/bun/mesh-reconnect.test.ts +++ b/test/bun/mesh-reconnect.test.ts @@ -48,9 +48,9 @@ function freePort(): number { } /** Boot a teapot on a fixed port; the handle kills it and leaves the port free again. */ -function startTeapot(port: number) { +async function startTeapot(port: number) { const app = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } }); - const server = serveBun(app, { port }); + const server = await serveBun(app, { port }); return { stop: async () => { @@ -64,7 +64,7 @@ const settle = (ms: number) => new Promise((r) => setTimeout(r, ms)); test('mesh on Bun: a teacup reconnects to a teapot that came back', async () => { const port = freePort(); - let teapot = startTeapot(port); + let teapot = await startTeapot(port); const teacup = createApp({ modules: [TeacupModule], @@ -88,7 +88,7 @@ test('mesh on Bun: a teacup reconnects to a teapot that came back', async () => const down = await teacup.fetch(new Request('http://x/api/local/who')); expect(down.status).toBe(503); - teapot = startTeapot(port); + teapot = await startTeapot(port); await settle(400); const after = await teacup.fetch(new Request('http://x/api/local/who', { headers: { 'x-token': 'xyz' } })); diff --git a/test/bun/mesh.test.ts b/test/bun/mesh.test.ts index d4410ab..1d98724 100644 --- a/test/bun/mesh.test.ts +++ b/test/bun/mesh.test.ts @@ -42,14 +42,14 @@ const controlUrl = (port: number) => `ws://127.0.0.1:${port}/__mesh__/control`; test('mesh on Bun: teacup resolves a Bun teapot through the graph', async () => { const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } }); - const tServer = serveBun(teapot, { port: 0 }); + const tServer = await serveBun(teapot, { port: 0 }); const teacup = createApp({ modules: [TeacupModule], experimental: true, mesh: { teapots: [{ url: controlUrl(tServer.port), secret: SECRET }] }, }); - const cServer = serveBun(teacup, { port: 0 }); + const cServer = await serveBun(teacup, { port: 0 }); try { const res = await fetch(`http://127.0.0.1:${cServer.port}/api/local/who`, { headers: { 'x-token': 'abc' } }); @@ -67,7 +67,7 @@ test('mesh on Bun: teacup resolves a Bun teapot through the graph', async () => test('mesh on Bun: a teapot refuses a bad secret over its control channel', async () => { const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } }); - const tServer = serveBun(teapot, { port: 0 }); + const tServer = await serveBun(teapot, { port: 0 }); const teacup = createApp({ modules: [TeacupModule], diff --git a/test/bun/shutdown.test.ts b/test/bun/shutdown.test.ts index 1644cf2..784207f 100644 --- a/test/bun/shutdown.test.ts +++ b/test/bun/shutdown.test.ts @@ -6,7 +6,7 @@ // 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 } from '../../src/index.ts'; +import { createApp, Route, Get, Module, Provider, needs } from '../../src/index.ts'; import { serveBun } from '../../src/bun.ts'; @Route('/') @@ -25,7 +25,7 @@ class Ctl { class M {} test('serveBun close({ timeoutMs }) gives up on a stuck handler and resolves', async () => { - const server = serveBun(createApp({ modules: [M] }), { port: 0 }); + 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 @@ -40,7 +40,7 @@ test('serveBun close({ timeoutMs }) gives up on a stuck handler and resolves', a }); test('serveBun close() drains an in-flight request rather than cutting it', async () => { - const server = serveBun(createApp({ modules: [M] }), { port: 0 }); + 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 @@ -65,10 +65,35 @@ test('serveBun close() runs registered teardown', async () => { }), }], }); - const server = serveBun(app, { port: 0 }); + 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/); +}); diff --git a/test/bun/ws.test.ts b/test/bun/ws.test.ts index e4cd4f9..336fa7f 100644 --- a/test/bun/ws.test.ts +++ b/test/bun/ws.test.ts @@ -26,7 +26,7 @@ class M {} test('serveBun: HTTP + WebSocket round-trip', async () => { const app = createApp({ modules: [M] }); - const server = serveBun(app, { port: 0 }); + const server = await serveBun(app, { port: 0 }); const port = server.port; try { const httpRes = await fetch(`http://127.0.0.1:${port}/rt/hello`); diff --git a/test/deno-adapter.test.ts b/test/deno-adapter.test.ts index 2c9083e..2758c02 100644 --- a/test/deno-adapter.test.ts +++ b/test/deno-adapter.test.ts @@ -32,7 +32,10 @@ it('snapshots connection metadata before Deno invalidates the upgraded request', // `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 = (closer: T): T => closer; - serveDeno({ upgrade, handleSignals } as unknown as App); + // `serveDeno` boots before it binds, so the stub needs the gate even though this test never + // exercises it. + const boot = vi.fn().mockResolvedValue(undefined); + await serveDeno({ upgrade, handleSignals, boot } as unknown as App); const info = { get remoteAddr() { if (upgraded) throw new TypeError('Request closed'); diff --git a/test/deno/mesh-hardening.test.ts b/test/deno/mesh-hardening.test.ts index 800f63f..59233a8 100644 --- a/test/deno/mesh-hardening.test.ts +++ b/test/deno/mesh-hardening.test.ts @@ -22,7 +22,7 @@ class TeapotModule {} async function startTeapot() { const app = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: 'good' } }); let port = 0; - const server = serveDeno(app, { port: 0, onListen: (addr) => (port = addr.port) }); + const server = await serveDeno(app, { port: 0, onListen: (addr) => (port = addr.port) }); await new Promise((r) => setTimeout(r, 50)); return { port: () => port, stop: async () => { await server.shutdown(); await app.close(); } }; diff --git a/test/deno/mesh-interop.test.ts b/test/deno/mesh-interop.test.ts index 423175e..49a3331 100644 --- a/test/deno/mesh-interop.test.ts +++ b/test/deno/mesh-interop.test.ts @@ -127,7 +127,7 @@ Deno.test('interop: a Node teacup consumes a Deno teapot', async () => { const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } }); let port = 0; const { serveDeno } = await import('../../src/deno.ts'); - const server = serveDeno(teapot, { + const server = await serveDeno(teapot, { port: 0, onListen: (addr) => { port = addr.port; diff --git a/test/deno/mesh-reconnect.test.ts b/test/deno/mesh-reconnect.test.ts index 7b031e6..d0a813c 100644 --- a/test/deno/mesh-reconnect.test.ts +++ b/test/deno/mesh-reconnect.test.ts @@ -49,7 +49,7 @@ function freePort(): number { /** Boot a teapot on a fixed port; the returned handle can kill it and leave the port free again. */ async function startTeapot(port: number) { const app = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } }); - const server = serveDeno(app, { port }); + const server = await serveDeno(app, { port }); await new Promise((r) => setTimeout(r, 50)); return { diff --git a/test/deno/mesh.test.ts b/test/deno/mesh.test.ts index 41d71ec..99bfe1e 100644 --- a/test/deno/mesh.test.ts +++ b/test/deno/mesh.test.ts @@ -46,7 +46,7 @@ class TeacupModule {} /** Starts an app on Deno and resolves once its port is known. */ async function serve(app: ReturnType) { let port = 0; - const server = serveDeno(app, { + const server = await serveDeno(app, { port: 0, onListen: (addr) => { port = addr.port; diff --git a/test/deno/shutdown.test.ts b/test/deno/shutdown.test.ts index b2c1e7a..769cfdf 100644 --- a/test/deno/shutdown.test.ts +++ b/test/deno/shutdown.test.ts @@ -5,7 +5,7 @@ // // Run with: npm run test:deno import 'reflect-metadata'; -import { createApp, Route, Get, Module } from '../../src/index.ts'; +import { createApp, Route, Get, Module, Provider, needs } from '../../src/index.ts'; import { serveDeno } from '../../src/deno.ts'; @Route('/') @@ -30,7 +30,7 @@ const portOf = (server: { addr?: { port: number } }): number => server.addr!.por // 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 = serveDeno(createApp({ modules: [M] }), { port: 0, onListen: () => {} }); + 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 @@ -45,7 +45,7 @@ Deno.test('serveDeno close({ timeoutMs }) returns on a stuck handler without for }); Deno.test('serveDeno close() drains an in-flight request rather than cutting it', async () => { - const server = serveDeno(createApp({ modules: [M] }), { port: 0, onListen: () => {} }); + 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 @@ -58,7 +58,7 @@ Deno.test('serveDeno close() drains an in-flight request rather than cutting it' Deno.test('a caller-supplied signal still aborts the server', async () => { const ac = new AbortController(); - const server = serveDeno(createApp({ modules: [M] }), { port: 0, signal: ac.signal, onListen: () => {} }); + 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 @@ -80,10 +80,44 @@ Deno.test('serveDeno close() runs registered teardown', async () => { }), }], }); - const server = serveDeno(app, { port: 0 }); + 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 || ''}`); + } +}); diff --git a/test/deno/ws.test.ts b/test/deno/ws.test.ts index 4bd39e4..059d6d4 100644 --- a/test/deno/ws.test.ts +++ b/test/deno/ws.test.ts @@ -37,7 +37,7 @@ Deno.test('serveDeno: HTTP + WebSocket round-trip through the graph', async () = const app = createApp({ modules: [M] }); let port = 0; - const server = serveDeno(app, { + const server = await serveDeno(app, { port: 0, onListen: (addr) => { port = addr.port; diff --git a/test/interop/_signal-app-deno.ts b/test/interop/_signal-app-deno.ts index be61e5e..6a1662f 100644 --- a/test/interop/_signal-app-deno.ts +++ b/test/interop/_signal-app-deno.ts @@ -23,7 +23,7 @@ const app = createApp({ // `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: () => {} }); +const server = await serveDeno(app, { port: 0, onListen: () => {} }); console.log(JSON.stringify({ ready: true })); void server;