feat(runtime)!: serveDeno and serveBun boot before they bind
Both were synchronous and left the boot to the first request, with the fix documented as something the caller should remember: `await app.boot()` before `Deno.serve` / `Bun.serve`. That made the correct use of a core helper depend on reading a README, in a framework whose whole argument is that order should not be something you have to get right. The failure it leaves is the bad kind. `app.fetch` boots lazily and the boot memo keeps the *rejection*, so a missing signing key does not fail the deploy: the port binds, every request is answered 500 by the runtime, and none of them reach `onError`. Anything that health-checks by asking whether the process is listening sees a healthy server. `listen()` has always awaited `bootApp()` before binding its socket, with a comment saying it exists so Node and Deno/Bun serve an identical graph. They did not. Now the three helpers agree, and the two adapters return promises. `edgeHandler` is deliberately unchanged: on workerd there is no startup outside a request, so there is no earlier moment to move the failure to. Both new tests were confirmed to fail with the gate commented out — without it `serveBun` resolves instead of rejecting, and serveDeno binds a port that 500s. Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
18 files changed
+147
-38
No files matched your search
+27
-5
@@ -10,6 +10,28 @@ npm treats versions as semver and semver forbids leading zeros.
|
|||||||
|
|
||||||
### Breaking
|
### Breaking
|
||||||
|
|
||||||
|
- **`serveDeno()` and `serveBun()` are async**, returning `Promise<DenoServer>` and
|
||||||
|
`Promise<BunServeResult>`. 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`.
|
- **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
|
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
|
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
|
### Added
|
||||||
|
|
||||||
- **`app.boot()`** runs the provider factories now instead of on the first request. `listen()`
|
- **`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
|
`serveDeno()` and `serveBun()` all call it for you (see Breaking, below). Call it by hand when you
|
||||||
memo keeps a rejection — so a bad key answered 500 on *every* request, from the runtime, without
|
drive `app.fetch` / `app.upgrade` from your own server: those boot lazily, and the boot memo keeps
|
||||||
reaching `onError`. `await app.boot()` before `Deno.serve`/`Bun.serve` turns that into a startup
|
a rejection, so a bad key answers 500 on *every* request, from the runtime, without reaching
|
||||||
failure. On workerd there is no startup outside a request, so calling it moves nothing.
|
`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
|
- **Errors are recognised by brand.** `HttpError` and `ValidationError` now carry
|
||||||
`Symbol.for('green-tea.http-error')` and `Symbol.for('green-tea.validation-error')`, and
|
`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
|
`isHttpError` checks the brand instead of `instanceof`. An error thrown by code holding a
|
||||||
|
|||||||
@@ -30,5 +30,5 @@ class Bench {
|
|||||||
class BenchModule {}
|
class BenchModule {}
|
||||||
|
|
||||||
const app = createApp({ modules: [BenchModule], security: false });
|
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}`);
|
console.log(`READY ${server.port}`);
|
||||||
@@ -30,4 +30,4 @@ class Bench {
|
|||||||
class BenchModule {}
|
class BenchModule {}
|
||||||
|
|
||||||
const app = createApp({ modules: [BenchModule], security: false });
|
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}`) });
|
||||||
+6
-5
@@ -62,11 +62,12 @@ export interface App {
|
|||||||
/**
|
/**
|
||||||
* Boots the providers now, instead of on the first request.
|
* Boots the providers now, instead of on the first request.
|
||||||
*
|
*
|
||||||
* `listen()` already does this before it accepts a connection. Every other path — `app.fetch`,
|
* The three serving helpers call it for you: `listen()` before it accepts a connection,
|
||||||
* `app.upgrade`, `serveDeno`, `serveBun`, `edgeHandler` — boots lazily on the first request, and a
|
* `serveDeno()` and `serveBun()` before they bind. Calling it by hand is for the paths that have
|
||||||
* provider that throws there fails *every* request, answered by the runtime with a 500 that never
|
* no startup of their own — `app.fetch` and `app.upgrade` driven by your own server, where a
|
||||||
* reaches `onError`. Calling this first turns that into a startup failure, which is where a bad
|
* provider that throws fails *every* request, answered by the runtime with a 500 that never
|
||||||
* key or an unreachable database belongs.
|
* 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
|
* Idempotent, and shares its memo with `listen()` and `fetch()`: calling both boots once. Unlike
|
||||||
* `ready()`, it does run provider factories.
|
* `ready()`, it does run provider factories.
|
||||||
|
|||||||
+13
-1
@@ -74,8 +74,20 @@ function bunSocket(ws: BunServerWebSocket): WsSocket {
|
|||||||
* (inbound channel, abort, WsRequest) is stashed on ws.data during the upgrade.
|
* (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
|
* Bun.serve exposes no equivalent to Node's server.maxConnections; enforce connection caps at
|
||||||
* the deployment platform or reverse proxy.
|
* 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<BunServeResult> {
|
||||||
|
// 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({
|
const server = Bun.serve({
|
||||||
...options,
|
...options,
|
||||||
fetch(request, server) {
|
fetch(request, server) {
|
||||||
|
|||||||
+13
-1
@@ -51,8 +51,20 @@ declare const Deno: {
|
|||||||
* WebSocket messages flow through app.upgrade over the shared neutral core.
|
* 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
|
* Deno.serve exposes no equivalent to Node's server.maxConnections; enforce connection caps at
|
||||||
* the deployment platform or reverse proxy.
|
* 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<DenoServer> {
|
||||||
|
// 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
|
// 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
|
// 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.
|
// server — it is chained into ours rather than replaced, so neither party loses its control.
|
||||||
|
|||||||
@@ -48,9 +48,9 @@ function freePort(): number {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** Boot a teapot on a fixed port; the handle kills it and leaves the port free again. */
|
/** 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 app = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
|
||||||
const server = serveBun(app, { port });
|
const server = await serveBun(app, { port });
|
||||||
|
|
||||||
return {
|
return {
|
||||||
stop: async () => {
|
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 () => {
|
test('mesh on Bun: a teacup reconnects to a teapot that came back', async () => {
|
||||||
const port = freePort();
|
const port = freePort();
|
||||||
let teapot = startTeapot(port);
|
let teapot = await startTeapot(port);
|
||||||
|
|
||||||
const teacup = createApp({
|
const teacup = createApp({
|
||||||
modules: [TeacupModule],
|
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'));
|
const down = await teacup.fetch(new Request('http://x/api/local/who'));
|
||||||
expect(down.status).toBe(503);
|
expect(down.status).toBe(503);
|
||||||
|
|
||||||
teapot = startTeapot(port);
|
teapot = await startTeapot(port);
|
||||||
await settle(400);
|
await settle(400);
|
||||||
|
|
||||||
const after = await teacup.fetch(new Request('http://x/api/local/who', { headers: { 'x-token': 'xyz' } }));
|
const after = await teacup.fetch(new Request('http://x/api/local/who', { headers: { 'x-token': 'xyz' } }));
|
||||||
|
|||||||
@@ -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 () => {
|
test('mesh on Bun: teacup resolves a Bun teapot through the graph', async () => {
|
||||||
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
|
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({
|
const teacup = createApp({
|
||||||
modules: [TeacupModule],
|
modules: [TeacupModule],
|
||||||
experimental: true,
|
experimental: true,
|
||||||
mesh: { teapots: [{ url: controlUrl(tServer.port), secret: SECRET }] },
|
mesh: { teapots: [{ url: controlUrl(tServer.port), secret: SECRET }] },
|
||||||
});
|
});
|
||||||
const cServer = serveBun(teacup, { port: 0 });
|
const cServer = await serveBun(teacup, { port: 0 });
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const res = await fetch(`http://127.0.0.1:${cServer.port}/api/local/who`, { headers: { 'x-token': 'abc' } });
|
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 () => {
|
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 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({
|
const teacup = createApp({
|
||||||
modules: [TeacupModule],
|
modules: [TeacupModule],
|
||||||
|
|||||||
@@ -6,7 +6,7 @@
|
|||||||
// Run with: npm run test:bun (or: bun test test/bun/)
|
// Run with: npm run test:bun (or: bun test test/bun/)
|
||||||
import 'reflect-metadata';
|
import 'reflect-metadata';
|
||||||
import { test, expect } from 'bun:test';
|
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';
|
import { serveBun } from '../../src/bun.ts';
|
||||||
|
|
||||||
@Route('/')
|
@Route('/')
|
||||||
@@ -25,7 +25,7 @@ class Ctl {
|
|||||||
class M {}
|
class M {}
|
||||||
|
|
||||||
test('serveBun close({ timeoutMs }) gives up on a stuck handler and resolves', async () => {
|
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(() => {});
|
fetch(`http://127.0.0.1:${server.port}/hang`).catch(() => {});
|
||||||
await Bun.sleep(50); // let the request actually reach the handler
|
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 () => {
|
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());
|
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 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 });
|
await server.close({ timeoutMs: 2000 });
|
||||||
|
|
||||||
// Reverse registration order: the plugin registered after the hook, so it tears down first.
|
// Reverse registration order: the plugin registered after the hook, so it tears down first.
|
||||||
expect(closed).toEqual(['plugin', 'hook']);
|
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/);
|
||||||
|
});
|
||||||
+1
-1
@@ -26,7 +26,7 @@ class M {}
|
|||||||
|
|
||||||
test('serveBun: HTTP + WebSocket round-trip', async () => {
|
test('serveBun: HTTP + WebSocket round-trip', async () => {
|
||||||
const app = createApp({ modules: [M] });
|
const app = createApp({ modules: [M] });
|
||||||
const server = serveBun(app, { port: 0 });
|
const server = await serveBun(app, { port: 0 });
|
||||||
const port = server.port;
|
const port = server.port;
|
||||||
try {
|
try {
|
||||||
const httpRes = await fetch(`http://127.0.0.1:${port}/rt/hello`);
|
const httpRes = await fetch(`http://127.0.0.1:${port}/rt/hello`);
|
||||||
|
|||||||
@@ -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
|
// `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.
|
// it returns is exactly what `createApp` returns when `handleSignals` is left off.
|
||||||
const handleSignals = <T,>(closer: T): T => closer;
|
const handleSignals = <T,>(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 = {
|
const info = {
|
||||||
get remoteAddr() {
|
get remoteAddr() {
|
||||||
if (upgraded) throw new TypeError('Request closed');
|
if (upgraded) throw new TypeError('Request closed');
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ class TeapotModule {}
|
|||||||
async function startTeapot() {
|
async function startTeapot() {
|
||||||
const app = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: 'good' } });
|
const app = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: 'good' } });
|
||||||
let port = 0;
|
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));
|
await new Promise((r) => setTimeout(r, 50));
|
||||||
|
|
||||||
return { port: () => port, stop: async () => { await server.shutdown(); await app.close(); } };
|
return { port: () => port, stop: async () => { await server.shutdown(); await app.close(); } };
|
||||||
|
|||||||
@@ -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 } });
|
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
|
||||||
let port = 0;
|
let port = 0;
|
||||||
const { serveDeno } = await import('../../src/deno.ts');
|
const { serveDeno } = await import('../../src/deno.ts');
|
||||||
const server = serveDeno(teapot, {
|
const server = await serveDeno(teapot, {
|
||||||
port: 0,
|
port: 0,
|
||||||
onListen: (addr) => {
|
onListen: (addr) => {
|
||||||
port = addr.port;
|
port = addr.port;
|
||||||
|
|||||||
@@ -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. */
|
/** Boot a teapot on a fixed port; the returned handle can kill it and leave the port free again. */
|
||||||
async function startTeapot(port: number) {
|
async function startTeapot(port: number) {
|
||||||
const app = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
|
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));
|
await new Promise((r) => setTimeout(r, 50));
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -46,7 +46,7 @@ class TeacupModule {}
|
|||||||
/** Starts an app on Deno and resolves once its port is known. */
|
/** Starts an app on Deno and resolves once its port is known. */
|
||||||
async function serve(app: ReturnType<typeof createApp>) {
|
async function serve(app: ReturnType<typeof createApp>) {
|
||||||
let port = 0;
|
let port = 0;
|
||||||
const server = serveDeno(app, {
|
const server = await serveDeno(app, {
|
||||||
port: 0,
|
port: 0,
|
||||||
onListen: (addr) => {
|
onListen: (addr) => {
|
||||||
port = addr.port;
|
port = addr.port;
|
||||||
|
|||||||
@@ -5,7 +5,7 @@
|
|||||||
//
|
//
|
||||||
// Run with: npm run test:deno
|
// Run with: npm run test:deno
|
||||||
import 'reflect-metadata';
|
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';
|
import { serveDeno } from '../../src/deno.ts';
|
||||||
|
|
||||||
@Route('/')
|
@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
|
// 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.
|
// 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 () => {
|
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(() => {});
|
fetch(`http://127.0.0.1:${portOf(server)}/hang`).catch(() => {});
|
||||||
await new Promise((r) => setTimeout(r, 50)); // let the request actually reach the handler
|
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 () => {
|
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());
|
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 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 () => {
|
Deno.test('a caller-supplied signal still aborts the server', async () => {
|
||||||
const ac = new AbortController();
|
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();
|
ac.abort();
|
||||||
await server.finished; // hangs here if chaining the caller's signal into ours dropped it
|
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 });
|
await server.close({ timeoutMs: 2000 });
|
||||||
|
|
||||||
// Reverse registration order: the plugin registered after the hook, so it tears down first.
|
// 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(',')}`);
|
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>'}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -37,7 +37,7 @@ Deno.test('serveDeno: HTTP + WebSocket round-trip through the graph', async () =
|
|||||||
const app = createApp({ modules: [M] });
|
const app = createApp({ modules: [M] });
|
||||||
|
|
||||||
let port = 0;
|
let port = 0;
|
||||||
const server = serveDeno(app, {
|
const server = await serveDeno(app, {
|
||||||
port: 0,
|
port: 0,
|
||||||
onListen: (addr) => {
|
onListen: (addr) => {
|
||||||
port = addr.port;
|
port = addr.port;
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ const app = createApp({
|
|||||||
// `ready` is printed after `serveDeno` returns, not from `onListen` — Deno calls `onListen`
|
// `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
|
// 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.
|
// 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 }));
|
console.log(JSON.stringify({ ready: true }));
|
||||||
void server;
|
void server;
|
||||||
Reference in new issue
Block a user