7 Commits
Author SHA1 Message Date
chrnx 0adab69466 docs(changelog): record the tier-2 work in Unreleased
CI / dco (pull_request) Successful in 5s
CI / build (pull_request) Successful in 28s
CI / runtimes (bun) (pull_request) Successful in 14s
CI / runtimes (deno) (pull_request) Successful in 18s
CI / runtimes (edge) (pull_request) Successful in 12s
The event stream's contract, the read-only `events` token, the reserved framework names,
the unmatched-route label, the budget bookkeeping, and the `onError` crash.

Grouped by what a reader is looking for rather than one bullet per commit: the three
observability issues describe one contract and read better as one entry plus the two
fields it needed.

The reserved names get their own paragraph saying plainly that they **can fail an app
that boots today**, because a changelog that buries a breaking change under a feature
heading is how someone finds it from a stack trace instead.

Heading still `[Unreleased]`. The version and the date belong to the cut.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 11:08:47 -05:00
chrnx 1c4f3fb8cb perf(http): skip the request-budget bookkeeping when no budget is set
Every request registered a `close` listener and set an acquire flag, including in the
apps — most of them — that never set `maxConcurrentRequests`. `acquire()` returns `true`
unconditionally when the limit is unset and `release()` early-returns for the same reason,
so both the closure and the EventEmitter registration were pure overhead: a per-request
cost, on the hot path, for a feature that is off.

The gate exposes `limited` rather than each adapter re-deriving it from `opts`, because the
gate is what knows. `acquire()` cannot say it — its `true` means "admitted" and "not
counting" alike, which is exactly why a caller reading only the result pays either way.

With a budget configured nothing changes: the listener is what releases a slot when a
client disconnects mid-handler, and it comes back. The guard is about the unset case, not
about dropping the feature, and the test asserts both halves so a fix for one cannot
quietly become a regression in the other.

Verified non-vacuous: reverting `src/` fails the assertion with the listener it counts.

Closes #74.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 11:01:52 -05:00
chrnx 1e76921d49 feat(di): a read-only events token, and framework names nobody can take
Three things that turned out to be one decision.

## `@needs('events')`

`app.bus` is public and `Bus` is an exported type, but the bus was not a graph token, so
`@needs('bus')` failed at boot. There is a good reason for the difference — putting the
`Bus` in the graph hands `emit` to every node and turns a one-way observation channel into
something anything can forge events on — and it was written down nowhere, inferable only
by reading `provideBuiltins` and noticing what is absent.

The read-only half is a token now: `events`, bound to `{ on }`, the same narrowing plugins
already get. `@needs('events')` works the way `@needs('logger')` does, which is the
symmetry a reader expects, and `emit` still belongs to nobody.

A plugin remains the right home for observation and the docs say so, because it gets
`on` and `onShutdown` *together*. The token gives the subscribe half alone: a `@Provider`
that subscribes should release in `dispose()` — `on()` returns its own unsubscribe — and a
`@Step` should not subscribe at all, since it runs per request and would add a listener
each time.

## The boot error teaches it

Documenting it prevents the mistake for a reader; it does nothing for the person typing
`@needs('bus')`, which is who the issue was about. That need now fails with what it should
have used and why, rather than the generic "nothing provides it" plus a nearest-match that
has nothing near enough to suggest.

## Framework names are reserved

**Behaviour change.** Builtins were registered with `if (!runners.has(name))`, so a
provider called `logger` silently replaced the framework's own and every `@needs('logger')`
in the app got something that was not the logger core writes to — a divergence you
discover from a log line that never appeared. `logger`, `rooms`, `events` and `bus` are
reserved now, enforced in `setRunner`, which is the single point modules, plugins and mesh
exports all register through. Taking one is a boot error naming it.

`bus` is reserved without being provided, so `@needs('bus')` cannot resolve to whatever a
user happened to call `bus` and be wrong in silence.

This replaces a test that asserted the old shadowing as a feature.

Closes #67.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 10:57:47 -05:00
chrnx c00f714aa8 feat(bus): give an unmatched request a bounded route to be labelled by
`route:unmatched` was the one terminal request event carrying no `route`, so the only
subject a consumer could reach was `name` — and on that event `name` is the concrete,
caller-controlled path.

The cardinality doctrine is already written into the codebase and it is right: a metrics
consumer that labels a counter with a concrete path gets one label per distinct URL, and
unbounded label cardinality takes down the metrics backend rather than the application.
That reasoning applies hardest to exactly this event. A matched route's path is bounded by
the route table; an unmatched one is bounded by nothing at all, and a scanner walking
/aaa, /aab, /aac is a memory leak with a metrics backend attached.

The framework did not create the trap knowingly. It just left the one field that avoids
it empty, precisely where it mattered most.

`route:unmatched` and the `request:end` that follows it now both carry
`route: '<unmatched>'`, exported as `UNMATCHED_ROUTE` so nobody has to hardcode the
string to compare against it. A single series for every path that was never a route,
rather than a fallback each consumer invents and some get wrong. It cannot collide with a
pattern a user can declare, since those start with `/`.

Written down alongside it, because a field alone does not teach the rule: `name` is
caller-controlled and must not be a metric label — true of `request:start` too, which is
not terminal and so was never the one anyone counted. And `route:unmatched` is not a
synonym for failure: a static file served by `createApp({ static })` matched no route
either and answers 200, so the status comes from `request:end`, like everything else.

Closes #65.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 10:37:41 -05:00
chrnx 5294e62a5a fix(errors): an onError that throws degrades to the built-in renderer
`createApp({ onError })` is the advertised way to render errors, it runs on the request
path, and it ran with no boundary around it. A renderer that threw did not produce a 500
— it took the process with it, exit code 1.

This is #72 in a different callback, and easier to reach: not a cross-origin request, but
*any* request that produces an error. The stack from the reproduction goes through
`unmatchedOutcome`, so the renderer produces the 404 too — an app with a custom renderer
and no matching route was one request away from exiting.

It is also the worst-timed crash there was. The renderer only runs once something has
already gone wrong, so the failure mode read: an error occurs, the code written to report
it fails, and instead of a degraded report the server ends.

All six call sites funnel through `renderError`, so the guard goes there once. A renderer
that throws falls back to `errorToResponse` — the built-in rendering, which is exactly
what the option overrides and therefore the honest thing to fall back to. The original
error still gets its response; that is the whole point. The renderer's own failure is
logged separately and names both errors, because they are different errors and a reader
chasing the wrong one loses an afternoon.

Verified against the built `dist/` with the issue's own reproduction: `404`, process
alive, one error line naming the renderer.

`viewEngine` was checked in the same pass, since it is the other user callback on a render
path and its having a boundary was not something to assume. It has one — the pipeline's
catch covers it, so a broken engine is a 500. Asserted now rather than left to inference.

Amends the `request:failed` test added a commit ago, which asserted the crashing behaviour
as its baseline: a throwing renderer now yields the fallback's status rather than none.
The `finally` that carries the emission stays, demoted from first line of defence to
second — a failure whose reporting is what broke is the worst one to lose.

Closes #80.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 10:35:03 -05:00
chrnx 3930804fb3 feat(bus): give request:failed a status, and write down the three-event overlap
One request that throws emits three events, and nothing said which of them to count. The
obvious first implementation counts the failure twice — once from `request:failed` and
once from the `request:end` that follows it, under whatever status it invents for the one
that had none. `route:unmatched` overlaps the same way, so a 404 is two events and one
outcome. Both mistakes are silent: the metrics simply lie.

The division of labour is now stated on `EventPayload`, where a consumer reads it:
`request:end` is terminal, universal and carries the status the client received, so it is
the request counter; `request:failed` means *handler code threw*, which no status can
express on its own since a rendered 422 is also a throw; `route:unmatched` means no route
ran. The last two are additional, not alternatives.

`request:failed` also carries a `status` now, so an error counter can break down by
status without joining back through `requestId` for something the emitter already had.

Getting it required moving the emission after the render rather than before, and the two
reasons are worth keeping: `onError` may turn any throw into any status, so deriving one
from the error would be a guess a custom renderer makes wrong — and the emission sits in
`finally`, so a renderer that *throws* cannot swallow the event. That case is the only one
where the event has no status, and the field's doc says so rather than leaving a reader to
find out.

Closes #64.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 10:26:00 -05:00
chrnx 5d8363d225 feat(bus): guarantee that every request:end has a request:start
`request:start` had one emitter and `request:end` had three, so the pairing every
consumer would reasonably assume held by accident rather than by promise. The
`maxConcurrentRequests` merge added the first terminal path that breaks it: a shed
request emits `request:end` and nothing before it, because it never reaches `handle()`.

Both shed paths now emit the pair, through one shared `emitShedPair` rather than two
copies — the guarantee lives in one place, and the two adapters already had a duplicate
of this block between them.

## Why the pair rather than documenting `request:end` as standalone

Both were defensible and the alternative was seriously considered. It loses on one
concrete case: the obvious in-flight gauge.

    bus.on('request:start', () => inFlight++);
    bus.on('request:end',   () => inFlight--);

Without the guarantee that drifts negative the moment a server sheds — under load, which
is exactly when an operator is reading it, and it fails by producing a plausible wrong
number rather than an error. Documenting "do not do that" asks every consumer to read
the warning; guaranteeing the pair makes the obvious code correct.

Emitting a `start` for a shed request is not a fabrication, which was the objection worth
answering: the request *did* arrive. The gate refused it before the router, and
`request:start` says a request arrived, not that it routed.

The cost of the guarantee is that it binds every future emitter, and that is real. It is
paid down by `test/lifecycle-pairing.test.ts`, which enumerates every response shape —
200, 404, 500, 413, 204 preflight, and 503 on both adapters — and asserts the pair and
the shared `requestId`. The constraint is now something CI enforces rather than something
a contributor has to remember. Verified non-vacuous: dropping the `request:start`
emission fails the two shed rows and nothing else.

Also writes down, next to `LifecycleEvent` where a consumer reads it, the half of this
that is not new: `request:end` is terminal and universal and is the one to count;
`request:failed` and `route:unmatched` describe the same request and are additional.

Closes #73.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 10:21:34 -05:00
20 changed files with 1070 additions and 78 deletions

No files matched your search

+70
View File
@@ -45,6 +45,32 @@ npm treats versions as semver and semver forbids leading zeros.
into named functions cannot annotate what it receives; plus `Hooks` and `TeardownFn`. Types only — into named functions cannot annotate what it receives; plus `Hooks` and `TeardownFn`. Types only —
nothing at runtime moved and no existing export changed. nothing at runtime moved and no existing export changed.
- **The lifecycle stream has a contract now, not just events.** `request:end` is documented as
terminal and universal — it fires for every request shape and is the only one carrying the status
the client received, which makes it the request counter. `request:failed` means *handler code
threw*, which no status expresses on its own since a rendered `422` is also a throw, and
`route:unmatched` means *no route ran*. Both are **additional** to `request:end`, not alternatives
to it: one failing request emits three events and a 404 emits two, all sharing a `requestId`, and
an exporter that treats them as separate outcomes counts the same request twice. Silently — the
metrics just come out wrong.
`request:failed` now carries `status`, so an error counter can break down by status without
joining back through `requestId` for something the emitter already had. It is absent in exactly
one case: a custom `onError` that threw while producing it, where the framework does not know what
was sent and will not guess.
- **`@needs('events')` reaches the read-only half of the bus** — `{ on }`, the same narrowing
plugins already get, exported as the `Events` type. `app.bus` was public and a plugin could
subscribe, but the bus was not a graph token, so `@needs('bus')` failed at boot and nothing said
why. It still is not one, and that is the design: handing `emit` to every node turns a one-way
observation channel into something anything can forge events on. `@needs('bus')` now fails saying
exactly that, and pointing at the two things that do work.
A plugin remains the right home for observation, because it gets `on` and `onShutdown` *together*.
This token gives the subscribe half alone — `on()` returns its own unsubscribe for a `@Provider`
to release in `dispose()`, and a `@Step` should not subscribe at all, since it runs per request
and would add a listener each time.
### Changed ### Changed
- **A request's security and CORS headers are computed once.** They were derived twice per request - **A request's security and CORS headers are computed once.** They were derived twice per request
@@ -55,6 +81,37 @@ npm treats versions as semver and semver forbids leading zeros.
answer whose inputs had not changed in between, and made a predicate with a counter in it count answer whose inputs had not changed in between, and made a predicate with a counter in it count
double. double.
- **Every `request:end` is now preceded by a `request:start` carrying the same `requestId`.** The
pairing held by accident until `maxConcurrentRequests` arrived: `request:start` had a single
emitter, so nothing could break it, and a shed request emitted only the `request:end`. A consumer
that opens per-request state on the first and closes it on the second — an in-flight gauge, most
obviously — would have drifted under shedding, which is when an operator is reading it, and would
have done so by producing a plausible wrong number rather than an error. It is a guarantee now,
written next to `LifecycleEvent` and enforced by a test that enumerates every response shape.
- **An unmatched request carries a bounded `route`.** `route:unmatched` was the one terminal request
event with no `route`, so the only subject a consumer could reach was `name` — which on that event
is the concrete, caller-controlled path. A matched path is bounded by the route table; an
unmatched one is bounded by nothing, and a scanner walking `/aaa`, `/aab`, `/aac` is a memory leak
with a metrics backend attached. It and the `request:end` that follows now carry
`route: '<unmatched>'`, exported as `UNMATCHED_ROUTE`. Written down alongside it: `name` is
caller-controlled and must never be a metric label.
- **Framework token names are reserved.** `logger`, `rooms`, `events` and `bus` cannot be declared
by a module, plugin or mesh export; taking one is a boot error naming it. Built-ins used to be
registered only if the name was free, so a provider called `logger` silently replaced the
framework's own and every `@needs('logger')` in the app got something that was not the logger core
writes to — a divergence discovered from a log line that never appeared. `bus` is reserved without
being provided, so `@needs('bus')` cannot resolve to whatever a user happened to call `bus`.
**This can fail an app that boots today**, which is the point of it, and the fix is to rename.
- **No per-request bookkeeping when no request budget is set.** Every request registered a `close`
listener and set a flag for `maxConcurrentRequests`, which is opt-in and unlimited by default — so
most applications paid a closure and an `EventEmitter` registration per request, on the hot path,
for a feature that was off. Unchanged where a budget *is* configured: the listener is what
releases a slot when a client disconnects mid-handler.
### Fixed ### Fixed
- **A `cors.origins` predicate that throws no longer takes the process down.** The predicate runs on - **A `cors.origins` predicate that throws no longer takes the process down.** The predicate runs on
@@ -80,6 +137,19 @@ npm treats versions as semver and semver forbids leading zeros.
workerd, which offers neither, nothing changes and the guarded sites' "edge has no filesystem" workerd, which offers neither, nothing changes and the guarded sites' "edge has no filesystem"
story is finally the true one. story is finally the true one.
- **A custom `onError` that throws no longer takes the process down.** `createApp({ onError })` is
the advertised way to render errors, it runs on the request path, and it ran with no boundary — a
renderer that threw exited the process, exit code 1. It is the same shape as the CORS predicate
crash above and easier to reach: not a cross-origin request, but *any* request that produces an
error. The renderer produces the 404 too, so an app with a custom renderer and no matching route
was one request away from exiting.
It was also the worst-timed crash there was, since the renderer only runs once something has
already gone wrong: an error occurs, the code written to report it fails, and instead of a
degraded report the server ends. A renderer that throws now falls back to the built-in rendering —
which is exactly what the option overrides — so the original error still gets its response, and
the renderer's own failure is logged separately, naming both.
## [26.8.0-beta.1] - 2026-08-19 ## [26.8.0-beta.1] - 2026-08-19
### Added ### Added
+66 -18
View File
@@ -1,5 +1,5 @@
import type http from 'http'; import type http from 'http';
import { Bus } from '../bus'; import { Bus, type Events } from '../bus';
import { createDefaultLogger, logRequests, type Logger } from '../logger'; import { createDefaultLogger, logRequests, type Logger } from '../logger';
import { Container } from '../container'; import { Container } from '../container';
import { topoSort, subgraphFor, GraphNode, nearest } from '../graph'; import { topoSort, subgraphFor, GraphNode, nearest } from '../graph';
@@ -62,7 +62,7 @@ interface Registry {
exportedProviders: string[]; exportedProviders: string[];
exportedSteps: string[]; exportedSteps: string[];
exportedRoutes: RouteEntry[]; exportedRoutes: RouteEntry[];
setRunner(name: string, runner: Runner): void; setRunner(name: string, runner: Runner, framework?: boolean): void;
} }
/** /**
@@ -86,6 +86,8 @@ interface PipelineDeps {
planSteps(plan: RoutePlan): PipelineStep[]; planSteps(plan: RoutePlan): PipelineStep[];
bus: Bus; bus: Bus;
onError?: ErrorRenderer; onError?: ErrorRenderer;
/** Where a failing `onError` is reported — the renderer's error is not the request's. */
logger: Logger;
} }
/** /**
@@ -208,7 +210,7 @@ export function createApp(opts: {
const { providerNodes, stepNodes, runners, providerMeta, routePlans } = registry; const { providerNodes, stepNodes, runners, providerMeta, routePlans } = registry;
const teardown = buildTeardownRegistry(opts.hooks, opts.teardownTimeoutMs, opts.shutdownTimeoutMs); const teardown = buildTeardownRegistry(opts.hooks, opts.teardownTimeoutMs, opts.shutdownTimeoutMs);
mountPlugins(opts.plugins, bus, registry, teardown); mountPlugins(opts.plugins, bus, registry, teardown);
provideBuiltins(registry, logger); provideBuiltins(registry, logger, bus);
// For each route, resolve which providers/steps feed it via topo order. // For each route, resolve which providers/steps feed it via topo order.
// MVP: every route depends on every declared step + provider in the app graph. // MVP: every route depends on every declared step + provider in the app graph.
@@ -229,7 +231,7 @@ export function createApp(opts: {
const providedSeed = (plan: RoutePlan) => seedProviders(container, plan); const providedSeed = (plan: RoutePlan) => seedProviders(container, plan);
const planSteps = (plan: RoutePlan) => compilePlanSteps(runners, plan); const planSteps = (plan: RoutePlan) => compilePlanSteps(runners, plan);
const pipelineDeps: PipelineDeps = { providedSeed, planSteps, bus, onError: opts.onError }; const pipelineDeps: PipelineDeps = { providedSeed, planSteps, bus, onError: opts.onError, logger };
let meshControl: MeshControl | undefined; let meshControl: MeshControl | undefined;
// mesh teacup: connect remote teapots and splice their scopes/routes in, then finalize. // mesh teacup: connect remote teapots and splice their scopes/routes in, then finalize.
@@ -306,7 +308,7 @@ export function createApp(opts: {
}; };
const fetchFn = buildAppFetch( const fetchFn = buildAppFetch(
routePlans, routePlans,
{ providedSeed, planSteps, bus, onError: opts.onError }, { providedSeed, planSteps, bus, onError: opts.onError, logger },
fetchOpts, fetchOpts,
bootApp, bootApp,
devRoutes, devRoutes,
@@ -404,7 +406,12 @@ export function createApp(opts: {
function emptyRegistry(): Registry { function emptyRegistry(): Registry {
const runners = new Map<string, Runner>(); // node name -> runtime fn const runners = new Map<string, Runner>(); // node name -> runtime fn
const setRunner = (name: string, runner: Runner) => { const setRunner = (name: string, runner: Runner, framework = false) => {
if (!framework && RESERVED_TOKENS.has(name))
throw new Error(
`'${name}' is reserved by the framework and cannot be provided by a module, plugin or mesh export — ` +
`rename it. The framework's own '${name}' is what '@needs' resolves to.`,
);
if (runners.has(name)) if (runners.has(name))
throw new Error(`duplicate provider/step name '${name}' — names must be unique across modules and plugins`); throw new Error(`duplicate provider/step name '${name}' — names must be unique across modules and plugins`);
runners.set(name, runner); runners.set(name, runner);
@@ -593,22 +600,46 @@ function mountPlugins(plugins: Plugin[] | undefined, bus: Bus, registry: Registr
} }
/** Auto-provides a shared {@link Rooms} instance unless the user already declared a `rooms` provider. */ /** Auto-provides a shared {@link Rooms} instance unless the user already declared a `rooms` provider. */
function provideBuiltins(registry: Registry, logger: Logger): void { /**
* Token names the framework owns. Declaring one is a boot error, not a silent override.
*
* Builtins used to be registered with `if (!runners.has(name))`, so a provider called `logger`
* quietly replaced the framework's own and every `@needs('logger')` in the app got something else.
* That is the kind of thing that is discovered from a log line that never appeared.
*
* `bus` is reserved without being provided, on purpose. It is not a graph token — putting the `Bus`
* itself in the graph would hand `emit` to every node and turn a one-way observation channel into
* something anything can forge events on. Reserving the name means `@needs('bus')` can say that,
* instead of resolving to whatever a user happened to call `bus` and being wrong in silence.
*/
const RESERVED_TOKENS = new Set(['logger', 'rooms', 'events', 'bus']);
function provideBuiltins(registry: Registry, logger: Logger, bus: Bus): void {
const builtin = (name: string, value: () => Record<string, unknown>): void => {
registry.providerNodes.push({ name, needs: [], provides: [name], origin: 'builtin' });
registry.providerMeta.set(name, { optional: false });
registry.setRunner(name, value, true);
};
// `logger` is registered as an ordinary provider *in addition to* being framework infrastructure, // `logger` is registered as an ordinary provider *in addition to* being framework infrastructure,
// so a step or handler reaches it with `@needs('logger')` like any other dependency. It is the // so a step or handler reaches it with `@needs('logger')` like any other dependency. It is the
// same object createApp holds, not a second one — core cannot depend on the graph for something // same object createApp holds, not a second one — core cannot depend on the graph for something
// it must use while the graph is still resolving. // it must use while the graph is still resolving.
if (!registry.runners.has('logger')) { builtin('logger', () => ({ logger }));
registry.providerNodes.push({ name: 'logger', needs: [], provides: ['logger'], origin: 'builtin' });
registry.providerMeta.set('logger', { optional: false });
registry.setRunner('logger', () => ({ logger }));
}
if (registry.runners.has('rooms')) return;
const roomsInstance = new Rooms(); const roomsInstance = new Rooms();
registry.providerNodes.push({ name: 'rooms', needs: [], provides: ['rooms'], origin: 'builtin' }); builtin('rooms', () => ({ rooms: roomsInstance }));
registry.providerMeta.set('rooms', { optional: false });
registry.setRunner('rooms', () => ({ rooms: roomsInstance })); // merge object -> ctx.rooms // The read-only half of the bus, and only the read-only half: `on`, never `emit`. The same
// narrowing a plugin gets, for the same reason — an observation channel anything can write to is
// not one.
//
// A subscription is not like the other injectables, and the difference is the scope that reaches
// it. A `@Provider` runs once, so subscribing there is fine; a `@Step` runs *per request*, and a
// step that calls `on()` registers a listener on every one of them. `on()` returns its own
// unsubscribe for the provider that wants to clean up in `dispose()` — but a plugin, which gets
// `on` and `onShutdown` together, remains the right home for observation.
builtin('events', () => ({ events: { on: bus.on.bind(bus) } satisfies Events }));
} }
// Boot-time nudge: a route whose need-closure pulls this many steps is almost always a modeling // Boot-time nudge: a route whose need-closure pulls this many steps is almost always a modeling
@@ -666,6 +697,21 @@ function assertNeedsSatisfiable(routePlans: RoutePlan[], providerNodes: GraphNod
for (const plan of routePlans) { for (const plan of routePlans) {
for (const need of plan.needs) { for (const need of plan.needs) {
if (allowed.has(need)) continue; if (allowed.has(need)) continue;
// The generic message plus a nearest-match is right for a typo and useless here: nothing is
// spelled nearly enough like `bus` to suggest, and the reader's mistake is not a typo but a
// reasonable guess about the shape. `@needs('logger')` teaches that framework things are
// graph tokens, so `@needs('bus')` is the next instinct — and the boot error is the first
// news that it is not the same shape. Say why, where they are.
if (need === 'bus') {
throw new Error(
`handler '${plan.handlerName}' needs 'bus' — the Bus is not a graph token, because a node ` +
`that could reach it could also emit, and an observation channel anything can write to ` +
`is not one. Use @needs('events') for the read-only half ({ on }), or write a plugin, ` +
`which gets on() and onShutdown() together and is the right home for observation.`,
);
}
const hint = nearest(need, allowed); const hint = nearest(need, allowed);
throw new Error( throw new Error(
`handler '${plan.handlerName}' needs '${need}' but nothing (local or mesh) provides it${hint ? ` — did you mean '${hint}'?` : ''}`, `handler '${plan.handlerName}' needs '${need}' but nothing (local or mesh) provides it${hint ? ` — did you mean '${hint}'?` : ''}`,
@@ -1006,7 +1052,7 @@ function buildMeshControl(
if (!mesh?.secret || !hasExports) return undefined; if (!mesh?.secret || !hasExports) return undefined;
const { container, orderedProviders, orderedSteps } = deps; const { container, orderedProviders, orderedSteps } = deps;
const { bus, providedSeed, planSteps, onError } = deps.deps; const { bus, providedSeed, planSteps, onError, logger } = deps.deps;
const manifest = buildManifest({ providers: exportedProviders, steps: exportedSteps, routes: exportedRoutes }); const manifest = buildManifest({ providers: exportedProviders, steps: exportedSteps, routes: exportedRoutes });
const resolveScope = async (name: string, env: RequestEnvelope): Promise<unknown> => { const resolveScope = async (name: string, env: RequestEnvelope): Promise<unknown> => {
@@ -1045,6 +1091,7 @@ function buildMeshControl(
transformer: plan.transformer, transformer: plan.transformer,
bus, bus,
onError, onError,
logger,
transport: plan.transport, transport: plan.transport,
correlation: { correlation: {
requestId: env.correlation?.requestId, requestId: env.correlation?.requestId,
@@ -1070,7 +1117,7 @@ function buildMeshControl(
/** Compiles every non-ws route plan into an HTTP route that seeds and runs the pipeline, plus any remote routes. */ /** Compiles every non-ws route plan into an HTTP route that seeds and runs the pipeline, plus any remote routes. */
function buildHttpRoutes(routePlans: RoutePlan[], remoteRoutes: RouteDef[], deps: PipelineDeps): RouteDef[] { function buildHttpRoutes(routePlans: RoutePlan[], remoteRoutes: RouteDef[], deps: PipelineDeps): RouteDef[] {
const { providedSeed, planSteps, bus, onError } = deps; const { providedSeed, planSteps, bus, onError, logger } = deps;
const local = routePlans const local = routePlans
.filter((plan) => plan.transport !== 'ws') // buffer | sse | ndjson | negotiate .filter((plan) => plan.transport !== 'ws') // buffer | sse | ndjson | negotiate
@@ -1089,6 +1136,7 @@ function buildHttpRoutes(routePlans: RoutePlan[], remoteRoutes: RouteDef[], deps
transformer: plan.transformer, transformer: plan.transformer,
bus, bus,
onError, onError,
logger,
transport: plan.transport, transport: plan.transport,
// `route` is the pattern, never req.url — a metrics consumer labelling on concrete // `route` is the pattern, never req.url — a metrics consumer labelling on concrete
// paths gets one label per distinct URL, and that takes down the metrics backend. // paths gets one label per distinct URL, and that takes down the metrics backend.
+93 -3
View File
@@ -1,4 +1,28 @@
/** Names of every lifecycle event the framework emits over the {@link Bus}. */ /**
* Names of every lifecycle event the framework emits over the {@link Bus}.
*
* ### The request pair is a guarantee
*
* **Every `request:end` is preceded by a `request:start` carrying the same `requestId`.** A
* consumer may open per-request state on the first and close it on the second without checking
* whether the request got as far as a route — a shed `503` emits the pair as surely as a `200`
* does.
*
* This is a promise to emitters as much as to subscribers: a terminal path that emits one must
* emit the other, in that order. It held by accident until `maxConcurrentRequests` added the first
* terminal path that does not reach the router, and `test/lifecycle-pairing.test.ts` enumerates
* every response shape so that the next one cannot break it quietly. The alternative — documenting
* `request:end` as standalone — was rejected because it makes the obvious consumer wrong: an
* in-flight gauge counting `start` up and `end` down would drift negative under shedding, which is
* exactly when an operator is reading it.
*
* ### `request:end` is terminal and universal; the others are additional
*
* `request:end` fires for every dispatched request — handled, thrown and unmatched alike — and is
* the only one of these carrying the real status. **Count it, and nothing else.**
* `request:failed` and `route:unmatched` describe the *same* request and fire in addition to it, so
* a consumer that counts them as separate outcomes counts one request twice. See `EventPayload`.
*/
export type LifecycleEvent = export type LifecycleEvent =
| 'boot:provider:start' | 'boot:provider:start'
| 'boot:provider:ok' | 'boot:provider:ok'
@@ -17,12 +41,18 @@ export type LifecycleEvent =
// came up, and a deploy watching for trouble wants to tell those apart. // came up, and a deploy watching for trouble wants to tell those apart.
| 'mesh:boot:retry' | 'mesh:boot:retry'
| 'plugin:mounted' | 'plugin:mounted'
// Paired: see the guarantee above. `request:start` has no status and no duration — it says a
// request arrived, not that it routed.
| 'request:start' | 'request:start'
| 'request:end' | 'request:end'
// "handler code threw", and *additional* to the `request:end` that follows it — a rendered 422 is
// also a throw, which is a thing a status alone cannot express.
| 'request:failed' | 'request:failed'
| 'route:matched' | 'route:matched'
// Covers a 404 *and* a 405 — the report's `route.not_found` names one outcome and would // Covers a 404 *and* a 405 — the report's `route.not_found` names one outcome and would
// misreport the other, and "no route ran" is the fact a consumer actually wants. // misreport the other, and "no route ran" is the fact a consumer actually wants. It is also not
// a synonym for "the request failed": a static file served from `createApp({ static })` matched
// no route either, and answers 200. Read the status from the `request:end` that follows.
| 'route:unmatched'; | 'route:unmatched';
/** /**
@@ -31,8 +61,39 @@ export type LifecycleEvent =
* *
* Everything past `name` is optional and stays that way. Boot and mesh events have no request to * Everything past `name` is optional and stays that way. Boot and mesh events have no request to
* name, and requiring a shape they cannot fill would only mean inventing values for it. * name, and requiring a shape they cannot fill would only mean inventing values for it.
*
* ### One failed request produces three events
*
* A single request that throws emits `request:start`, then `request:failed`, then `request:end`.
* All three carry the same `requestId`, and the first implementation anyone writes counts the
* failure twice — once from `request:failed` and once from the `request:end` that follows it,
* under whatever status it invents for the one that had none. `route:unmatched` overlaps the same
* way: it fires *in addition to* the `request:end` that follows, so a 404 is two events and one
* outcome.
*
* The division of labour, which is the thing to build against:
*
* - **`request:end`** — terminal, universal, and the only one carrying the status the client
* received. This is the request counter and the latency histogram.
* - **`request:failed`** — *handler code threw*, which no status can express on its own: a
* rendered `422` is also a throw. This is a separate error counter, not a second request
* counter.
* - **`route:unmatched`** — *no route ran*, covering 404 and 405 alike. Also additional.
*
* `logRequests` gets this right and is worth reading as a reference (`src/logger.ts`): it takes
* the outcome from `request:end` and only the message from `request:failed`.
*/ */
export interface EventPayload { export interface EventPayload {
/**
* What the event is about, for a human reading a log line.
*
* **Never use this as a metric label.** On the request events it is caller-controlled: for a
* matched request it is the route pattern, but on `request:start` and `route:unmatched` it is
* built from the path that arrived. A matched path is bounded by the route table; an unmatched
* one is bounded by nothing at all, and a scanner walking `/aaa`, `/aab`, `/aac` becomes one
* label per distinct URL — a memory leak with a metrics backend attached. Label on {@link route},
* which is bounded by construction.
*/
name: string; name: string;
scope?: string; scope?: string;
error?: unknown; error?: unknown;
@@ -41,10 +102,23 @@ export interface EventPayload {
requestId?: string; requestId?: string;
/** A `traceparent` header carried verbatim. Core parses nothing — that is the exporter's job. */ /** A `traceparent` header carried verbatim. Core parses nothing — that is the exporter's job. */
traceId?: string; traceId?: string;
/** The matched *pattern* (`/users/:id`), never the concrete path — see {@link Correlation}. */ /**
* The matched *pattern* (`/users/:id`), never the concrete path — see {@link Correlation}.
*
* Bounded by the route table, which is what makes it the field to label a metric on. When nothing
* matched it is `'<unmatched>'` rather than absent, on `route:unmatched` and on the `request:end`
* that follows it: a single series for every path that was never a route, instead of a fallback
* each consumer invents and some get wrong. It cannot collide with a real pattern, which always
* starts with `/`.
*/
route?: string; route?: string;
method?: string; method?: string;
transport?: string; transport?: string;
/**
* The status the client received. Present on `request:end` always, and on `request:failed`
* except when a custom `onError` renderer threw while producing it — the one case where the
* framework does not know what was sent, and will not guess.
*/
status?: number; status?: number;
} }
@@ -58,6 +132,22 @@ export interface EventPayload {
*/ */
export type Correlation = Pick<EventPayload, 'requestId' | 'traceId' | 'route' | 'method' | 'transport'>; export type Correlation = Pick<EventPayload, 'requestId' | 'traceId' | 'route' | 'method' | 'transport'>;
/**
* The read-only half of the {@link Bus}, as `@needs('events')` hands it over.
*
* `on` and deliberately not `emit`: a channel anything can write to is not an observation channel,
* and the framework's own events would stop being trustworthy the moment a node could forge one.
* Plugins get exactly this same narrowing.
*
* `on` returns its own unsubscribe. Use it — a `@Provider` that subscribes should release in
* `dispose()`, and a `@Step` should not subscribe at all, since it runs once per request and would
* add a listener each time. A plugin, which gets `on` and `onShutdown` together, is the home this
* token exists to point at rather than replace.
*/
export interface Events {
on: Bus['on'];
}
/** In-process pub/sub for framework lifecycle events; observer failures are swallowed so they never break the pipeline. */ /** In-process pub/sub for framework lifecycle events; observer failures are swallowed so they never break the pipeline. */
export class Bus { export class Bus {
private readonly listeners = new Map<LifecycleEvent, Set<(p: EventPayload) => void>>(); private readonly listeners = new Map<LifecycleEvent, Set<(p: EventPayload) => void>>();
+1 -1
View File
@@ -129,7 +129,7 @@ function parseAcquired(
return parseRequestBody(acquired.bytes, contentType, duplicates, maxParts).then((parsed) => return parseRequestBody(acquired.bytes, contentType, duplicates, maxParts).then((parsed) =>
'error' in parsed 'error' in parsed
? { fail: renderError(new HttpError(parsed.status ?? 400, parsed.error), req, opts?.onError) } ? { fail: renderError(new HttpError(parsed.status ?? 400, parsed.error), req, opts?.onError, opts?.logger) }
: { body: parsed.body }, : { body: parsed.body },
); );
} }
+62 -2
View File
@@ -144,7 +144,7 @@ function errorOutcome(
opts: HttpOptions | undefined, opts: HttpOptions | undefined,
headers: Record<string, string> = {}, headers: Record<string, string> = {},
): HandleResult { ): HandleResult {
const rendered = renderError(error, req, opts?.onError); const rendered = renderError(error, req, opts?.onError, opts?.logger);
return { return {
injected, injected,
outcome: { outcome: {
@@ -192,6 +192,15 @@ async function unmatchedOutcome(
return errorOutcome(error, req, injected, opts, allow.length ? { allow: allow.join(', ') } : {}); return errorOutcome(error, req, injected, opts, allow.length ? { allow: allow.join(', ') } : {});
} }
/**
* The `route` reported for a request no route matched.
*
* A bounded value rather than an empty field, and deliberately unlike any pattern a user can
* declare — a route pattern starts with `/`, so this cannot collide with one. It aggregates as a
* single series where the concrete path would produce one per distinct URL.
*/
export const UNMATCHED_ROUTE = '<unmatched>';
/** What `dispatch` learned along the way that `handle` needs in order to describe the request afterwards. */ /** What `dispatch` learned along the way that `handle` needs in order to describe the request afterwards. */
interface Trace { interface Trace {
route?: string; route?: string;
@@ -234,6 +243,48 @@ export function handle(
return observedDispatch(routes, opts, req, bus, injected); return observedDispatch(routes, opts, req, bus, injected);
} }
/**
* Whether anything is listening for the request pair — the one check both adapters need before
* paying for a `performance.now()` on a request they are about to refuse.
*/
export function watchingRequests(bus: Bus | undefined): bus is Bus {
return bus !== undefined && (bus.hasListeners('request:start') || bus.hasListeners('request:end'));
}
/**
* Emits the lifecycle pair for a request shed before routing.
*
* A shed request never reaches {@link handle}, so `observedDispatch` — the emitter every other
* terminal path goes through — never sees it, and an adapter that emitted only `request:end` would
* be the first thing in the tree to break the pairing {@link LifecycleEvent} guarantees. Both
* events are emitted here, in order, so a consumer that opens per-`requestId` state on
* `request:start` and closes it on `request:end` does not start leaking half-open entries the first
* time a server sheds — under load, which is when it can least afford them.
*
* Each event keeps its own listener guard: the pairing is a promise to a subscriber of *both*, and
* costs nothing for a subscriber of one.
*/
export function emitShedPair(
bus: Bus,
req: { method: string; url: string; requestId?: string; traceId?: string },
startedAt: number,
): void {
const name = `${req.method} ${req.url}`;
if (bus.hasListeners('request:start'))
bus.emit('request:start', { name, method: req.method, requestId: req.requestId, traceId: req.traceId });
if (bus.hasListeners('request:end'))
bus.emit('request:end', {
name,
method: req.method,
status: 503,
durationMs: performance.now() - startedAt,
requestId: req.requestId,
traceId: req.traceId,
});
}
async function observedDispatch( async function observedDispatch(
routes: RouteDef[], routes: RouteDef[],
opts: HttpOptions | undefined, opts: HttpOptions | undefined,
@@ -301,9 +352,18 @@ async function dispatch(
const matched = resolveRoute(routes, req.method, path); const matched = resolveRoute(routes, req.method, path);
if (!matched) { if (!matched) {
// `name` here is the path that arrived, and it is the one value in this payload that must never
// become a metric label: a matched route's path is bounded by the route table, an unmatched one
// is bounded by nothing at all, and a scanner walking /aaa, /aab, /aac is a memory leak with a
// metrics backend attached. So the event carries a bounded `route` as well, and so does the
// `request:end` that follows it, rather than leaving every consumer to invent the same fallback
// and some of them to get it wrong.
if (trace) trace.route = UNMATCHED_ROUTE;
if (bus?.hasListeners('route:unmatched')) if (bus?.hasListeners('route:unmatched'))
bus.emit('route:unmatched', { bus.emit('route:unmatched', {
name: `${req.method} ${path}`, name: `${req.method} ${path}`,
route: UNMATCHED_ROUTE,
method: req.method, method: req.method,
requestId: req.requestId, requestId: req.requestId,
traceId: req.traceId, traceId: req.traceId,
@@ -350,7 +410,7 @@ async function dispatch(
traceId: req.traceId, traceId: req.traceId,
}); });
} catch (error) { } catch (error) {
result = renderError(error, req, opts?.onError); result = renderError(error, req, opts?.onError, opts?.logger);
} }
if (isStreamResult(result)) { if (isStreamResult(result)) {
+13
View File
@@ -5,6 +5,16 @@
* handler execution finishes; a returned stream does not hold the slot for the stream's lifetime. * handler execution finishes; a returned stream does not hold the slot for the stream's lifetime.
*/ */
export interface RequestGate { export interface RequestGate {
/**
* Whether a budget is actually configured.
*
* Exposed rather than left for each adapter to re-derive from `opts`, because the gate is what
* knows: `acquire()` returns `true` unconditionally when there is no limit, so a caller reading
* only its result cannot tell "admitted" from "not counting", and pays for the bookkeeping either
* way. `maxConcurrentRequests` is opt-in, so for most applications this is `false` and every
* per-request cost behind it should be skipped entirely.
*/
limited: boolean;
acquire(): boolean; acquire(): boolean;
release(): void; release(): void;
} }
@@ -12,8 +22,11 @@ export interface RequestGate {
/** Creates an unlimited gate when `limit` is undefined or non-positive. */ /** Creates an unlimited gate when `limit` is undefined or non-positive. */
export function createRequestGate(limit: number | undefined): RequestGate { export function createRequestGate(limit: number | undefined): RequestGate {
let active = 0; let active = 0;
const limited = limit !== undefined && limit > 0;
return { return {
limited,
acquire(): boolean { acquire(): boolean {
if (limit === undefined || limit <= 0) return true; if (limit === undefined || limit <= 0) return true;
if (active >= limit) return false; if (active >= limit) return false;
+35 -22
View File
@@ -7,7 +7,15 @@ import { readBody as readBodyBytes, deriveSecure, deriveIp } from './request';
import { pipeStream } from './stream'; import { pipeStream } from './stream';
import { attachWs } from './ws'; import { attachWs } from './ws';
import { mergeInjectedHeaders } from './headers'; import { mergeInjectedHeaders } from './headers';
import { handle, correlateRequest, computeInjected, type HandleResult, type Preflight } from './core'; import {
handle,
correlateRequest,
computeInjected,
emitShedPair,
watchingRequests,
type HandleResult,
type Preflight,
} from './core';
import type { BodyFailure, BodyReader } from './body'; import type { BodyFailure, BodyReader } from './body';
import type { RouteDef, WsRouteDef, MeshControl, HttpOptions } from './types'; import type { RouteDef, WsRouteDef, MeshControl, HttpOptions } from './types';
import { nodeRequire } from '../node-require'; import { nodeRequire } from '../node-require';
@@ -102,23 +110,22 @@ function createRequestHandler(cfg: HandlerConfig) {
let result: HandleResult | Preflight; let result: HandleResult | Preflight;
let acquired = false; let acquired = false;
const watchingEnd = bus?.hasListeners('request:end') ?? false; const watching = watchingRequests(bus);
const startedAt = watchingEnd ? performance.now() : 0; const startedAt = watching ? performance.now() : 0;
try { try {
if (!gate.acquire()) { if (!gate.acquire()) {
if (watchingEnd) { if (watching)
const method = req.method ?? 'GET'; emitShedPair(
const url = req.url ?? '/'; bus,
bus!.emit('request:end', { {
name: `${method} ${url}`, method: req.method ?? 'GET',
method, url: req.url ?? '/',
status: 503, requestId: correlation.requestId,
durationMs: performance.now() - startedAt, traceId: correlation.traceId,
requestId: correlation.requestId, },
traceId: correlation.traceId, startedAt,
}); );
}
res.writeHead(503, { res.writeHead(503, {
'content-type': 'application/json', 'content-type': 'application/json',
@@ -129,12 +136,18 @@ function createRequestHandler(cfg: HandlerConfig) {
return; return;
} }
acquired = true; // Both the flag and the listener are skipped when no budget is configured, which is most
res.once('close', () => { // applications: `maxConcurrentRequests` is opt-in and unlimited by default. A closure and an
if (!acquired) return; // EventEmitter registration per request, on the hot path, for a feature that is off is a cost
acquired = false; // with nothing on the other side of it.
gate.release(); if (gate.limited) {
}); acquired = true;
res.once('close', () => {
if (!acquired) return;
acquired = false;
gate.release();
});
}
result = await handle( result = await handle(
routes, routes,
@@ -191,7 +204,7 @@ function readRequestBytes(
return readBodyBytes(req, limit).then( return readBodyBytes(req, limit).then(
(bytes) => ({ bytes }), (bytes) => ({ bytes }),
(error: unknown) => { (error: unknown) => {
const rendered = renderError(error, errorRequest(req), opts?.onError); const rendered = renderError(error, errorRequest(req), opts?.onError, opts?.logger);
return { fail: { ...rendered, headers: { ...rendered.headers, connection: 'close' } } }; return { fail: { ...rendered, headers: { ...rendered.headers, connection: 'close' } } };
}, },
); );
+24 -15
View File
@@ -1,6 +1,14 @@
import type { StreamEncoder } from '../encoders'; import type { StreamEncoder } from '../encoders';
import { createRequestGate } from './request-gate'; import { createRequestGate } from './request-gate';
import { handle, computeInjected, correlateRequest, type HandleResult, type Preflight } from './core'; import {
handle,
computeInjected,
correlateRequest,
emitShedPair,
watchingRequests,
type HandleResult,
type Preflight,
} from './core';
import { mergeInjectedHeaders } from './headers'; import { mergeInjectedHeaders } from './headers';
import type { BodyFailure, BodyReader, MaybePromise } from './body'; import type { BodyFailure, BodyReader, MaybePromise } from './body';
import { HttpError } from '../signals'; import { HttpError } from '../signals';
@@ -69,7 +77,7 @@ function readFetchBytes(
url: url.pathname + url.search, url: url.pathname + url.search,
headers: headersToRecord(request.headers), headers: headersToRecord(request.headers),
}; };
return { fail: renderError(new HttpError(413, 'Payload Too Large'), errReq, opts?.onError) }; return { fail: renderError(new HttpError(413, 'Payload Too Large'), errReq, opts?.onError, opts?.logger) };
} }
return { bytes: arrayBuffer.byteLength === 0 ? undefined : Buffer.from(arrayBuffer) }; return { bytes: arrayBuffer.byteLength === 0 ? undefined : Buffer.from(arrayBuffer) };
@@ -143,21 +151,22 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
let result: HandleResult | Preflight; let result: HandleResult | Preflight;
let acquired = false; let acquired = false;
const watchingEnd = opts?.bus?.hasListeners('request:end') ?? false; const watching = watchingRequests(opts?.bus);
const startedAt = watchingEnd ? performance.now() : 0; const startedAt = watching ? performance.now() : 0;
try { try {
if (!gate.acquire()) { if (!gate.acquire()) {
if (watchingEnd) { if (watching)
opts!.bus!.emit('request:end', { emitShedPair(
name: `${request.method} ${path}`, opts!.bus!,
method: request.method, {
status: 503, method: request.method,
durationMs: performance.now() - startedAt, url: path,
requestId: correlation.requestId, requestId: correlation.requestId,
traceId: correlation.traceId, traceId: correlation.traceId,
}); },
} startedAt,
);
return new Response(JSON.stringify({ error: 'Service Unavailable' }), { return new Response(JSON.stringify({ error: 'Service Unavailable' }), {
status: 503, status: 503,
@@ -171,7 +180,7 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
}); });
} }
acquired = true; acquired = gate.limited;
result = await handle( result = await handle(
routes, routes,
+2 -1
View File
@@ -60,7 +60,7 @@ export {
// Bus & flow // Bus & flow
export { Bus } from './bus'; export { Bus } from './bus';
export type { LifecycleEvent, EventPayload, Correlation } from './bus'; export type { LifecycleEvent, EventPayload, Correlation, Events } from './bus';
export { flow, Flow } from './flow'; export { flow, Flow } from './flow';
export type { StepFn, CompiledFlow } from './flow'; export type { StepFn, CompiledFlow } from './flow';
@@ -81,6 +81,7 @@ export type { StreamEncoder } from './encoders';
// HTTP, security & validation // HTTP, security & validation
export type { RequestLimits } from './http'; export type { RequestLimits } from './http';
export { UNMATCHED_ROUTE } from './http/core';
export type { TlsOptions, CorsOptions, SecurityOptions } from './security'; export type { TlsOptions, CorsOptions, SecurityOptions } from './security';
export type { UploadedFile, MultipartBody } from './multipart'; export type { UploadedFile, MultipartBody } from './multipart';
export type { StandardSchemaV1 } from './standard-schema'; export type { StandardSchemaV1 } from './standard-schema';
+30 -11
View File
@@ -3,6 +3,7 @@ import { renderError, type ErrorRenderer } from './transformers';
import { isAsyncIterable } from './channel'; import { isAsyncIterable } from './channel';
import type { TransformerFn, Transport } from './metadata'; import type { TransformerFn, Transport } from './metadata';
import { TransportMismatchError } from './signals'; import { TransportMismatchError } from './signals';
import type { Logger } from './logger';
/** A single step in a request pipeline: a named unit whose `run` merges its output into the shared context. */ /** A single step in a request pipeline: a named unit whose `run` merges its output into the shared context. */
export interface PipelineStep { export interface PipelineStep {
@@ -113,9 +114,10 @@ export async function runPipeline(args: {
bus: Bus; bus: Bus;
transport: Transport; transport: Transport;
onError?: ErrorRenderer; onError?: ErrorRenderer;
logger?: Logger;
correlation?: Correlation; correlation?: Correlation;
}): Promise<PipelineResult> { }): Promise<PipelineResult> {
const { steps, handler, transformer, seed, bus, transport, onError, correlation = {} } = args; const { steps, handler, transformer, seed, bus, transport, onError, logger, correlation = {} } = args;
// context is intentionally `any`: each step merges arbitrary keys into the accumulator // context is intentionally `any`: each step merges arbitrary keys into the accumulator
let context: any = { ...seed }; let context: any = { ...seed };
@@ -137,16 +139,33 @@ export async function runPipeline(args: {
const transformed = transformer(result); const transformed = transformer(result);
return { status: transformed.status ?? 200, headers: transformed.headers ?? {}, body: transformed.body }; return { status: transformed.status ?? 200, headers: transformed.headers ?? {}, body: transformed.body };
} catch (error) { } catch (error) {
// Both fire for a failing step, deliberately: `request:step:error` above marks the span,
// this marks the trace. A tracing exporter needs each, and only emitting the outer one is
// what produces a trace that says a request failed without saying where.
if (bus.hasListeners('request:failed'))
bus.emit('request:failed', { name: correlation.route ?? 'pipeline', error, ...correlation });
const req = (context.req ?? {}) as { method?: string; url?: string; headers?: Record<string, unknown> }; const req = (context.req ?? {}) as { method?: string; url?: string; headers?: Record<string, unknown> };
return renderError( let status: number | undefined;
error,
{ method: req.method ?? '', url: req.url ?? '', headers: (context.headers ?? req.headers ?? {}) as never }, try {
onError, const rendered = renderError(
); error,
{ method: req.method ?? '', url: req.url ?? '', headers: (context.headers ?? req.headers ?? {}) as never },
onError,
logger,
);
status = rendered.status;
return rendered;
} finally {
// Both fire for a failing step, deliberately: `request:step:error` above marks the span,
// this marks the trace. A tracing exporter needs each, and only emitting the outer one is
// what produces a trace that says a request failed without saying where.
//
// Emitted after the render rather than before it, because the status is only decided there:
// `onError` may turn any throw into any status, so deriving one from the error would be a
// guess that a custom renderer makes wrong.
//
// In `finally` rather than after the call, so that nothing between here and the emit can cost
// us the only record that a request failed. `renderError` already contains a throwing
// `onError` and degrades to the built-in rendering, so this is a second line rather than the
// first — but a failure whose reporting is what broke is the worst one to lose.
if (bus.hasListeners('request:failed'))
bus.emit('request:failed', { name: correlation.route ?? 'pipeline', error, status, ...correlation });
}
} }
} }
+12 -1
View File
@@ -14,7 +14,18 @@ export interface ScopeNode {
export interface ScopeApi { export interface ScopeApi {
add(node: ScopeNode): void; add(node: ScopeNode): void;
} }
/** The capabilities handed to a plugin: event subscription, node registration, and teardown. */ /**
* The capabilities handed to a plugin: event subscription, node registration, and teardown.
*
* This is the home for observation, and the reason is the pairing: `bus.on` arrives next to
* `onShutdown`, so whatever a plugin subscribes to it can also release. A graph node can reach the
* same read-only slice through `@needs('events')`, but it gets the subscribe half without the
* unsubscribe half — and a `@Step` reaching it would register a listener per request.
*
* The `Bus` itself is deliberately not here and is not a graph token either: handing over `emit`
* would turn a one-way observation channel into something any node can forge events on.
* `@needs('bus')` fails at boot and says so.
*/
export interface PluginApi { export interface PluginApi {
bus: { on: Bus['on'] }; bus: { on: Bus['on'] };
scope: ScopeApi; scope: ScopeApi;
+29 -2
View File
@@ -1,6 +1,7 @@
import { isHttpError, ValidationError } from './signals'; import { isHttpError, ValidationError } from './signals';
import type { TransformerFn } from './metadata'; import type { TransformerFn } from './metadata';
import { flattenPath } from './standard-schema'; import { flattenPath } from './standard-schema';
import type { Logger } from './logger';
/** A ready-to-send HTTP response. */ /** A ready-to-send HTTP response. */
export interface ErrorResponse { export interface ErrorResponse {
@@ -60,6 +61,32 @@ export function errorToResponse(error: unknown): ErrorResponse {
} }
/** Render an error through the optional user {@link ErrorRenderer}, falling back to {@link errorToResponse}. */ /** Render an error through the optional user {@link ErrorRenderer}, falling back to {@link errorToResponse}. */
export function renderError(error: unknown, req: ErrorRequest, onError?: ErrorRenderer): ErrorResponse { export function renderError(
return onError?.(error, req) ?? errorToResponse(error); error: unknown,
req: ErrorRequest,
onError?: ErrorRenderer,
logger?: Logger,
): ErrorResponse {
if (!onError) return errorToResponse(error);
// `onError` is user code, it runs on the request path, and it runs *after something already went
// wrong* — which makes an unguarded throw here the worst-timed crash in the framework: the error
// occurs, the code written to report it fails, and the process ends instead of degrading.
//
// It is also easy to reach. This renders the 404 too, not just a thrown handler, so an app with a
// custom renderer and no matching route is one request away from exiting.
//
// A renderer that throws falls back to the built-in rendering, which is exactly what the option
// overrides and therefore the honest thing to fall back to: the original error still gets its
// response. The renderer's own failure is reported separately, because it is a different error
// from the request's and a reader chasing the wrong one loses an afternoon.
try {
return onError(error, req) ?? errorToResponse(error);
} catch (rendererError) {
logger?.error('createApp({ onError }) threw while rendering — falling back to the built-in renderer', {
err: rendererError instanceof Error ? rendererError.message : String(rendererError),
rendering: error instanceof Error ? error.message : String(error),
});
return errorToResponse(error);
}
} }
+6 -2
View File
@@ -603,7 +603,11 @@ describe('rooms auto-provide', () => {
expect(await fetch(`http://127.0.0.1:${port}/api/r/x`).then((r) => r.json())).toEqual({ ok: true }); expect(await fetch(`http://127.0.0.1:${port}/api/r/x`).then((r) => r.json())).toEqual({ ok: true });
s.close(); s.close();
}); });
it('a user-declared rooms provider wins (no duplicate-name throw)', () => { // This used to be allowed, and the user's provider silently replaced the framework's. The same
// held for `logger`, where every `@needs('logger')` in the app then got something that was not
// the logger core writes to — a divergence discovered from a log line that never appeared.
// Framework token names are reserved now, and taking one is a boot error.
it('refuses a user-declared rooms provider instead of silently replacing the built-in', () => {
@Provider({ provides: 'rooms' }) @Provider({ provides: 'rooms' })
class MyRooms { class MyRooms {
provide() { provide() {
@@ -618,7 +622,7 @@ describe('rooms auto-provide', () => {
} }
@Module({ mountpoint: '/api', providers: [MyRooms], controllers: [Ctl] }) @Module({ mountpoint: '/api', providers: [MyRooms], controllers: [Ctl] })
class M {} class M {}
expect(() => createApp({ modules: [M] })).not.toThrow(); expect(() => createApp({ modules: [M] })).toThrow(/'rooms' is reserved by the framework/);
}); });
}); });
+73
View File
@@ -0,0 +1,73 @@
// The three legitimate ways to reach the bus, exercised together in one app.
//
// `bus` became a reserved name and the `Bus` itself is still not a graph token, so this file's job
// is to prove that what closed is only the wrong door: observation from outside, from a plugin and
// from inside the graph all still work, and only `emit` stays where it was.
import 'reflect-metadata';
import { describe, it, expect } from 'vitest';
import { createApp, Route, Get, Module, needs } from '../src/index';
import type { Events, Plugin } from '../src/index';
@Route('/b')
class Ctl {
@Get('/x') x(@needs('events') events: Events) {
// Reaching it per request is allowed; *subscribing* per request is the thing the docs warn
// about, and nothing here does that.
return { hasOn: typeof events.on === 'function' };
}
}
describe('reaching the bus', () => {
it('works from outside, from a plugin and from the graph, all at once', async () => {
const fromOutside: string[] = [];
const fromPlugin: string[] = [];
const observer: Plugin = (api) => {
api.bus.on('request:end', (e) => fromPlugin.push(e.route ?? ''));
};
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M], plugins: [observer] });
// 1. from outside: the public `app.bus`, which keeps `emit` too.
app.bus.on('request:end', (e) => fromOutside.push(e.route ?? ''));
// 3. from the graph: the handler receives `events` and reports its shape.
const res = await app.fetch(new Request('http://x/b/x'));
expect(await res.json()).toEqual({ hasOn: true });
expect(fromOutside).toEqual(['/b/x']);
expect(fromPlugin).toEqual(['/b/x']);
await app.close();
});
it('keeps emit outside the graph and outside plugins, and only there', async () => {
let injected: Events | undefined;
const seen: string[] = [];
@Route('/e')
class Grab {
@Get('/x') x(@needs('events') events: Events) {
injected = events;
return {};
}
}
@Module({ mountpoint: '/', controllers: [Grab] })
class M {}
const app = createApp({ modules: [M] });
await app.fetch(new Request('http://x/e/x'));
// The graph's slice cannot forge an event...
expect((injected as unknown as { emit?: unknown }).emit).toBeUndefined();
// ...while the application that owns the app still can, which is what `app.bus` is for.
app.bus.on('plugin:mounted', (e) => seen.push(e.name));
app.bus.emit('plugin:mounted', { name: 'from the owner' });
expect(seen).toEqual(['from the owner']);
await app.close();
});
});
+73
View File
@@ -80,3 +80,76 @@ describe('HttpError body', () => {
server.close(); server.close();
}); });
}); });
// `onError` is user code, on the request path, running *after something already went wrong*. An
// unguarded throw here was the worst-timed crash in the framework: the error occurs, the code
// written to report it fails, and the process ends instead of degrading. It was also easy to
// reach — the renderer produces the 404 too, so an app with a custom renderer and no matching
// route was one request away from exiting.
describe('an onError that throws', () => {
const exploding: ErrorRenderer = () => {
throw new Error('renderer exploded');
};
@Route('/x')
class Boom {
@Get('/boom') boom() {
throw new HttpError(503, 'Service Unavailable');
}
}
@Module({ mountpoint: '/', controllers: [Boom] })
class BoomModule {}
it('falls back to the built-in rendering rather than losing the response', async () => {
const app = createApp({ modules: [BoomModule], onError: exploding });
const res = await app.fetch(new Request('http://x/x/boom'));
// The original error still gets its answer: the fallback is the rendering `onError` overrides.
expect(res.status).toBe(503);
expect(await res.json()).toEqual({ error: 'Service Unavailable' });
});
// The path that needed no thrown handler at all.
it('survives a 404, which the renderer also produces', async () => {
const app = createApp({ modules: [BoomModule], onError: exploding });
const res = await app.fetch(new Request('http://x/nothing-here'));
expect(res.status).toBe(404);
expect(await res.json()).toEqual({ error: 'Not Found' });
});
it('reports the renderer as the thing that failed, not the request', async () => {
const logged: Array<{ msg: string; fields?: Record<string, unknown> }> = [];
const logger = {
debug() {},
info() {},
warn() {},
error(msg: string, fields?: Record<string, unknown>) {
logged.push({ msg, fields });
},
};
const app = createApp({ modules: [BoomModule], onError: exploding, logger });
await app.fetch(new Request('http://x/x/boom'));
expect(logged).toHaveLength(1);
expect(logged[0].msg).toMatch(/onError/);
// Both errors named, because a reader chasing the wrong one loses an afternoon.
expect(logged[0].fields?.err).toBe('renderer exploded');
expect(logged[0].fields?.rendering).toBe('Service Unavailable');
});
it('answers over a real Node server instead of exiting the process', async () => {
const app = createApp({ modules: [BoomModule], onError: exploding });
const server = await app.listen(0);
const port = (server.address() as { port: number }).port;
const res = await fetch(`http://127.0.0.1:${port}/x/boom`);
expect(res.status).toBe(503);
// Still serving — the point of the whole test.
expect((await fetch(`http://127.0.0.1:${port}/nope`)).status).toBe(404);
await app.close();
});
});
+42
View File
@@ -1,5 +1,6 @@
import { describe, expect, it, test, vi } from 'vitest'; import { describe, expect, it, test, vi } from 'vitest';
import * as net from 'node:net'; import * as net from 'node:net';
import { ServerResponse } from 'node:http';
import { once } from 'node:events'; import { once } from 'node:events';
import { Bus } from '../src/bus'; import { Bus } from '../src/bus';
import { matchRoute, parseQuery, createHttpServer } from '../src/http'; import { matchRoute, parseQuery, createHttpServer } from '../src/http';
@@ -419,4 +420,45 @@ describe('request hardening', () => {
server.close(); server.close();
}); });
// `maxConcurrentRequests` is opt-in and unlimited by default, so the overwhelming majority of
// apps used to pay a closure and an EventEmitter registration per request for a feature that is
// off. Small in absolute terms, and on the hot path, which is why it is asserted rather than
// trusted: a `res.once('close')` is exactly the kind of line that comes back.
it('registers no per-request close listener when no request budget is configured', async () => {
const closeListeners: string[] = [];
// Typed loosely on purpose: `once` is an overloaded EventEmitter signature and the spy only
// needs to see the event name before handing the call straight back to the real one.
const proto = ServerResponse.prototype as unknown as {
once(event: string | symbol, listener: (...args: unknown[]) => void): unknown;
};
const realOnce = proto.once;
const spy = vi.spyOn(proto, 'once').mockImplementation(function (this: unknown, event, listener) {
if (event === 'close') closeListeners.push('close');
return realOnce.call(this, event, listener);
});
try {
const unlimited = createHttpServer([{ method: 'GET', pattern: '/ping', transport: 'buffer', handler }]);
await new Promise<void>((r) => unlimited.listen(0, r));
expect((await fetch(`${getUrl(unlimited)}/ping`)).status).toBe(200);
expect(closeListeners).toHaveLength(0);
unlimited.close();
// With a budget set, the listener is what releases the slot on a client disconnect, so it
// has to come back — the guard is about the unset case, not about dropping the feature.
const limited = createHttpServer(
[{ method: 'GET', pattern: '/ping', transport: 'buffer', handler }],
[], undefined, undefined,
{ limits: { maxConcurrentRequests: 4 } },
);
await new Promise<void>((r) => limited.listen(0, r));
expect((await fetch(`${getUrl(limited)}/ping`)).status).toBe(200);
expect(closeListeners.length).toBeGreaterThan(0);
limited.close();
} finally {
spy.mockRestore();
}
});
}); });
+185
View File
@@ -0,0 +1,185 @@
// The `request:start` / `request:end` pairing, asserted across every terminal path there is.
//
// The guarantee held by accident until `maxConcurrentRequests` arrived: `request:start` had a
// single emitter, so nothing could break it. It has more than one now, and a guarantee upheld by
// there being only one place to get it wrong is not a guarantee — it is a coincidence with good
// timing. This file is what makes the next terminal path fail loudly instead of quietly.
//
// Adding a response shape? Add a row. That is the whole maintenance contract.
import { describe, expect, it } from 'vitest';
import { Bus } from '../src/bus';
import { createHttpServer } from '../src/http';
import { buildFetch } from '../src/http/web';
interface Seen {
starts: string[];
ends: Array<{ requestId?: string; status?: number }>;
}
function watch(bus: Bus): Seen {
const seen: Seen = { starts: [], ends: [] };
bus.on('request:start', (e) => seen.starts.push(e.requestId ?? ''));
bus.on('request:end', (e) => seen.ends.push({ requestId: e.requestId, status: e.status }));
return seen;
}
const ok = async () => ({ status: 200, headers: {}, body: 'ok' });
const boom = async () => {
throw new Error('kaboom');
};
/** Every shape of request the framework can answer, and how to provoke it. */
const SHAPES: Array<{
name: string;
status: number;
routes: Parameters<typeof buildFetch>[0];
opts?: Parameters<typeof buildFetch>[1];
request: () => Request;
}> = [
{
name: 'matched handler',
status: 200,
routes: [{ method: 'GET', pattern: '/ok', transport: 'buffer', handler: ok }],
request: () => new Request('http://x/ok'),
},
{
name: 'unmatched route',
status: 404,
routes: [{ method: 'GET', pattern: '/ok', transport: 'buffer', handler: ok }],
request: () => new Request('http://x/nope'),
},
{
name: 'handler throws',
status: 500,
routes: [{ method: 'GET', pattern: '/boom', transport: 'buffer', handler: boom }],
request: () => new Request('http://x/boom'),
},
{
name: 'body over maxBodyBytes',
status: 413,
routes: [{ method: 'POST', pattern: '/echo', transport: 'buffer', handler: ok }],
opts: { limits: { maxBodyBytes: 8 } },
request: () => new Request('http://x/echo', { method: 'POST', body: 'x'.repeat(500) }),
},
{
name: 'CORS preflight',
status: 204,
routes: [{ method: 'GET', pattern: '/ok', transport: 'buffer', handler: ok }],
opts: { cors: { origins: '*' } },
request: () =>
new Request('http://x/ok', {
method: 'OPTIONS',
headers: { origin: 'https://a.com', 'access-control-request-method': 'GET' },
}),
},
];
describe('every terminal path emits request:start before request:end', () => {
for (const shape of SHAPES) {
it(`${shape.name} → ${shape.status}`, async () => {
const bus = new Bus();
const seen = watch(bus);
const fetchHandler = buildFetch(shape.routes, { ...shape.opts, bus });
const res = await fetchHandler(shape.request());
expect(res.status).toBe(shape.status);
expect(seen.starts).toHaveLength(1);
expect(seen.ends).toHaveLength(1);
// Same request, not two that happened to arrive together — the id is what a consumer keys on.
expect(seen.ends[0].requestId).toBe(seen.starts[0]);
});
}
// The path that broke the pairing, and the reason this file exists. It never reaches `handle()`,
// so the emitter every row above goes through never sees it.
it('shed over maxConcurrentRequests → 503', async () => {
const bus = new Bus();
const seen = watch(bus);
let release!: () => void;
const blocked = new Promise<void>((r) => (release = r));
const fetchHandler = buildFetch(
[{ method: 'GET', pattern: '/slow', transport: 'buffer', handler: async () => (await blocked, ok()) }],
{ bus, limits: { maxConcurrentRequests: 1 } },
);
const first = fetchHandler(new Request('http://x/slow'));
const shed = await fetchHandler(new Request('http://x/slow'));
expect(shed.status).toBe(503);
release();
await first;
const shedPair = seen.ends.find((e) => e.status === 503)!;
expect(shedPair).toBeDefined();
expect(seen.starts).toContain(shedPair.requestId);
});
// The Node adapter sheds through its own code path, so passing on `buildFetch` proves nothing
// about it — the two were separate emitters before they shared one.
it('shed over maxConcurrentRequests → 503, on the Node adapter', async () => {
const bus = new Bus();
const seen = watch(bus);
let release!: () => void;
let started!: () => void;
const blocked = new Promise<void>((r) => (release = r));
const firstStarted = new Promise<void>((r) => (started = r));
const server = createHttpServer(
[
{
method: 'GET',
pattern: '/slow',
transport: 'buffer',
handler: async () => {
started();
await blocked;
return { status: 200, headers: {}, body: 'ok' };
},
},
],
[],
bus,
undefined,
{ limits: { maxConcurrentRequests: 1 } },
);
await new Promise<void>((r) => server.listen(0, r));
const url = `http://127.0.0.1:${(server.address() as { port: number }).port}/slow`;
const first = fetch(url);
await firstStarted;
const shed = await fetch(url);
expect(shed.status).toBe(503);
release();
await first;
const shedPair = seen.ends.find((e) => e.status === 503)!;
expect(shedPair).toBeDefined();
expect(seen.starts).toContain(shedPair.requestId);
server.close();
});
// The invariant stated as a count rather than per row. Scoped to the enumerated shapes on
// purpose — the two shed paths have their own tests above, because they are the ones that need
// a blocked handler to provoke and the ones that broke it in the first place.
it('leaves no enumerated shape with an end whose start is missing', async () => {
const bus = new Bus();
const seen = watch(bus);
const fetchHandler = buildFetch(
[{ method: 'GET', pattern: '/ok', transport: 'buffer', handler: ok }],
{ bus, cors: { origins: '*' } },
);
for (const shape of SHAPES) {
const h = buildFetch(shape.routes, { ...shape.opts, bus });
await h(shape.request());
}
await fetchHandler(new Request('http://x/ok'));
expect(seen.ends).not.toHaveLength(0);
for (const end of seen.ends) expect(seen.starts).toContain(end.requestId);
expect(seen.starts).toHaveLength(seen.ends.length);
});
});
+95
View File
@@ -1,6 +1,7 @@
import { describe, it, expect } from 'vitest'; import { describe, it, expect } from 'vitest';
import { createApp, Provider, Step, Route, Get, Module, needs } from '../src/index'; import { createApp, Provider, Step, Route, Get, Module, needs } from '../src/index';
import type { EventPayload } from '../src/bus'; import type { EventPayload } from '../src/bus';
import { UNMATCHED_ROUTE } from '../src/index';
@Provider({ provides: 'db' }) @Provider({ provides: 'db' })
class Db { class Db {
@@ -175,6 +176,100 @@ describe('failure reporting', () => {
expect(requestFailures).toHaveLength(1); expect(requestFailures).toHaveLength(1);
expect(requestFailures[0].route).toBe('/bad/go'); expect(requestFailures[0].route).toBe('/bad/go');
expect(requestFailures[0].requestId).toBe(stepErrors[0].requestId); expect(requestFailures[0].requestId).toBe(stepErrors[0].requestId);
// Carries what was actually sent, so an error counter can break down by status without
// joining back to the `request:end` that follows it.
expect(requestFailures[0].status).toBe(500);
}); });
// The cardinality trap: `name` carries the path that arrived, which is bounded by nothing at all.
// A consumer labelling on `route` gets one bounded series for every path that was never a route;
// one labelling on `name` gets a series per scanner probe.
it('labels an unmatched request with a bounded route, on both events', async () => {
const app = createApp({ modules: [BadModule] });
const unmatched: EventPayload[] = [];
const ends: EventPayload[] = [];
app.bus.on('route:unmatched', (p) => unmatched.push(p));
app.bus.on('request:end', (p) => ends.push(p));
for (const probe of ['/aaa', '/aab', '/aac']) await app.fetch(new Request(`http://x${probe}`));
expect(unmatched).toHaveLength(3);
expect(ends).toHaveLength(3);
// Three distinct paths, one series.
expect(new Set(unmatched.map((e) => e.route))).toEqual(new Set([UNMATCHED_ROUTE]));
expect(new Set(ends.map((e) => e.route))).toEqual(new Set([UNMATCHED_ROUTE]));
// `name` still carries the concrete path, which is what makes it useful in a log and unusable
// as a label.
expect(new Set(unmatched.map((e) => e.name)).size).toBe(3);
// It cannot collide with a pattern a user can declare.
expect(UNMATCHED_ROUTE.startsWith('/')).toBe(false);
});
it('leaves a matched route labelled with its pattern, not the marker', async () => {
const app = createApp({ modules: [BadModule] });
const ends: EventPayload[] = [];
app.bus.on('request:end', (p) => ends.push(p));
await app.fetch(new Request('http://x/bad/go'));
expect(ends[0].route).toBe('/bad/go');
});
// The three-event overlap, asserted rather than described: one failing request, three events,
// one requestId. A consumer that counts `request:failed` and `request:end` as separate outcomes
// counts this request twice — which is the mistake the payload docs now name.
it('emits start, failed and end for one failing request, all sharing a requestId', async () => {
const app = createApp({ modules: [BadModule] });
const seen: Array<{ event: string; payload: EventPayload }> = [];
for (const event of ['request:start', 'request:failed', 'request:end'] as const)
app.bus.on(event, (payload) => seen.push({ event, payload }));
await app.fetch(new Request('http://x/bad/go'));
expect(seen.map((s) => s.event)).toEqual(['request:start', 'request:failed', 'request:end']);
expect(new Set(seen.map((s) => s.payload.requestId)).size).toBe(1);
// `request:end` is the terminal one and the only one that fires for every request shape; it is
// what a request counter counts.
expect(seen[2].payload.status).toBe(500);
});
// `onError` may turn any throw into any status, so a status derived from the error rather than
// from the render would be a guess that a custom renderer makes wrong.
it('reports the status a custom onError produced, not the one the error implied', async () => {
const app = createApp({
modules: [BadModule],
onError: () => ({ status: 418, headers: {}, body: 'teapot' }),
});
const failures: EventPayload[] = [];
app.bus.on('request:failed', (p) => failures.push(p));
const res = await app.fetch(new Request('http://x/bad/go'));
expect(res.status).toBe(418);
expect(failures).toHaveLength(1);
expect(failures[0].status).toBe(418);
});
// A renderer that throws must not swallow the event — the failure still happened, and losing the
// only record of it because the reporting of it broke is the worst possible trade. The status is
// the built-in renderer's, since that is what the request actually got.
it('still reports the failure when onError itself throws', async () => {
const app = createApp({
modules: [BadModule],
onError: () => {
throw new Error('renderer exploded');
},
});
const failures: EventPayload[] = [];
app.bus.on('request:failed', (p) => failures.push(p));
const res = await app.fetch(new Request('http://x/bad/go'));
expect(res.status).toBe(500);
expect(failures).toHaveLength(1);
expect(failures[0].status).toBe(500);
// The request's error, not the renderer's — they are different errors and the event names the
// one the request suffered.
expect((failures[0].error as Error).message).toBe('step exploded');
});
}); });
+141
View File
@@ -0,0 +1,141 @@
// Framework token names, and the read-only slice of the bus that `@needs` can reach.
//
// Two halves of one decision. The bus is not a graph token — a node that could reach it could also
// `emit`, and an observation channel anything can write to is not one — but `@needs('logger')`
// teaches that framework things *are* graph tokens, so reaching for `@needs('bus')` is the natural
// next move. Documenting that it does not work only reaches a reader; the boot error reaches the
// person writing it. And reserving the names stops a user's own `logger` from quietly becoming the
// one the whole app injects.
import 'reflect-metadata';
import { describe, it, expect } from 'vitest';
import { createApp, Provider, Step, Route, Get, Module, needs } from '../src/index';
import type { Events } from '../src/index';
@Route('/r')
class Ctl {
@Get('/x') x() {
return { ok: true };
}
}
describe('reserved framework tokens', () => {
for (const token of ['logger', 'rooms', 'events']) {
it(`refuses a provider that declares '${token}'`, () => {
@Provider({ provides: token })
class Shadow {
provide() {
return { [token]: { mine: true } };
}
}
@Module({ mountpoint: '/', providers: [Shadow], controllers: [Ctl] })
class M {}
expect(() => createApp({ modules: [M] })).toThrow(
new RegExp(`'${token}' is reserved by the framework`),
);
});
}
it("refuses a step that declares 'bus', a name the framework reserves without providing", () => {
@Step({ provides: 'bus' })
class Shadow {
run() {
return { bus: { mine: true } };
}
}
@Module({ mountpoint: '/', steps: [Shadow], controllers: [Ctl] })
class M {}
expect(() => createApp({ modules: [M] })).toThrow(/'bus' is reserved by the framework/);
});
it('leaves every other name alone', () => {
@Provider({ provides: 'buses' })
class Fine {
provide() {
return { buses: 1 };
}
}
@Module({ mountpoint: '/', providers: [Fine], controllers: [Ctl] })
class M {}
expect(() => createApp({ modules: [M] })).not.toThrow();
});
});
describe("@needs('bus')", () => {
it('fails at boot naming the read-only token and the plugin, not a nearest match', () => {
@Route('/b')
class Bad {
@Get('/x') x(@needs('bus') _bus: unknown) {
return {};
}
}
@Module({ mountpoint: '/', controllers: [Bad] })
class M {}
expect(() => createApp({ modules: [M] })).toThrow(/the Bus is not a graph token/);
expect(() => createApp({ modules: [M] })).toThrow(/@needs\('events'\)/);
expect(() => createApp({ modules: [M] })).toThrow(/plugin/);
});
});
describe("@needs('events')", () => {
it('hands over on() and nothing else — no emit to forge events with', async () => {
let injected: Events | undefined;
@Route('/e')
class Observer {
@Get('/x') x(@needs('events') events: Events) {
injected = events;
return { ok: true };
}
}
@Module({ mountpoint: '/', controllers: [Observer] })
class M {}
const app = createApp({ modules: [M] });
await app.fetch(new Request('http://x/e/x'));
expect(typeof injected?.on).toBe('function');
expect(Object.keys(injected!)).toEqual(['on']);
expect((injected as unknown as { emit?: unknown }).emit).toBeUndefined();
});
it('subscribes to the same bus the framework emits on, and hands back an unsubscribe', async () => {
const seen: string[] = [];
@Provider({ provides: 'watcher', needs: ['events'] })
class Watcher {
#off?: () => void;
provide(ctx: { events: Events }) {
this.#off = ctx.events.on('request:end', (e) => seen.push(e.route ?? ''));
return { watcher: true };
}
dispose() {
this.#off?.();
}
}
@Route('/e')
class Observed {
@Get('/y') y(@needs('watcher') _w: unknown) {
return { ok: true };
}
}
@Module({ mountpoint: '/', providers: [Watcher], controllers: [Observed] })
class M {}
const app = createApp({ modules: [M] });
await app.fetch(new Request('http://x/e/y'));
expect(seen).toEqual(['/e/y']);
// dispose() releases it, which is the half a plugin gets for free with onShutdown. Asserted by
// emitting after close and watching nothing arrive — clearing the array and finding it empty
// would prove only that clearing works.
await app.close();
seen.length = 0;
app.bus.emit('request:end', { name: 'after close', route: '/after' });
expect(seen).toEqual([]);
});
});
+18
View File
@@ -19,6 +19,24 @@ class Views {
class M {} class M {}
const app = createApp({ modules: [M], views: dir }); const app = createApp({ modules: [M], views: dir });
// Checked alongside the `onError` guard: `viewEngine` is the other user callback on a render path,
// and whether it had a boundary was not something to assume. It does — the pipeline's own catch
// covers it, so a broken engine is a 500 rather than a dead process. Asserted so it stays that way.
describe('a viewEngine that throws', () => {
it('renders a 500 instead of escaping the request', async () => {
const broken = createApp({
modules: [M],
views: dir,
viewEngine: () => {
throw new Error('engine exploded');
},
});
const res = await broken.fetch(new Request('http://x/user'));
expect(res.status).toBe(500);
expect(await res.json()).toEqual({ error: 'Internal Server Error' });
});
});
describe('@Html modes', () => { describe('@Html modes', () => {
it('string mode sends the handler return as text/html', async () => { it('string mode sends the handler return as text/html', async () => {
const res = await app.fetch(new Request('http://x/str')); const res = await app.fetch(new Request('http://x/str'));