diff --git a/CHANGELOG.md b/CHANGELOG.md index c9da57f..9acbf26 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 — 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 - **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 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: ''`, 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 - **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" 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 ### Added diff --git a/src/app/index.ts b/src/app/index.ts index 6da0056..926e141 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -1,5 +1,5 @@ import type http from 'http'; -import { Bus } from '../bus'; +import { Bus, type Events } from '../bus'; import { createDefaultLogger, logRequests, type Logger } from '../logger'; import { Container } from '../container'; import { topoSort, subgraphFor, GraphNode, nearest } from '../graph'; @@ -62,7 +62,7 @@ interface Registry { exportedProviders: string[]; exportedSteps: string[]; 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[]; bus: Bus; 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 teardown = buildTeardownRegistry(opts.hooks, opts.teardownTimeoutMs, opts.shutdownTimeoutMs); 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. // 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 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; // mesh teacup: connect remote teapots and splice their scopes/routes in, then finalize. @@ -306,7 +308,7 @@ export function createApp(opts: { }; const fetchFn = buildAppFetch( routePlans, - { providedSeed, planSteps, bus, onError: opts.onError }, + { providedSeed, planSteps, bus, onError: opts.onError, logger }, fetchOpts, bootApp, devRoutes, @@ -404,7 +406,12 @@ export function createApp(opts: { function emptyRegistry(): Registry { const runners = new Map(); // 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)) throw new Error(`duplicate provider/step name '${name}' — names must be unique across modules and plugins`); 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. */ -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): 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, // 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 // it must use while the graph is still resolving. - if (!registry.runners.has('logger')) { - registry.providerNodes.push({ name: 'logger', needs: [], provides: ['logger'], origin: 'builtin' }); - registry.providerMeta.set('logger', { optional: false }); - registry.setRunner('logger', () => ({ logger })); - } + builtin('logger', () => ({ logger })); - if (registry.runners.has('rooms')) return; const roomsInstance = new Rooms(); - registry.providerNodes.push({ name: 'rooms', needs: [], provides: ['rooms'], origin: 'builtin' }); - registry.providerMeta.set('rooms', { optional: false }); - registry.setRunner('rooms', () => ({ rooms: roomsInstance })); // merge object -> ctx.rooms + builtin('rooms', () => ({ rooms: roomsInstance })); + + // 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 @@ -666,6 +697,21 @@ function assertNeedsSatisfiable(routePlans: RoutePlan[], providerNodes: GraphNod for (const plan of routePlans) { for (const need of plan.needs) { 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); throw new Error( `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; 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 resolveScope = async (name: string, env: RequestEnvelope): Promise => { @@ -1045,6 +1091,7 @@ function buildMeshControl( transformer: plan.transformer, bus, onError, + logger, transport: plan.transport, correlation: { 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. */ 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 .filter((plan) => plan.transport !== 'ws') // buffer | sse | ndjson | negotiate @@ -1089,6 +1136,7 @@ function buildHttpRoutes(routePlans: RoutePlan[], remoteRoutes: RouteDef[], deps transformer: plan.transformer, bus, onError, + logger, transport: plan.transport, // `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. diff --git a/src/bus.ts b/src/bus.ts index 0d248ee..8ae39c3 100644 --- a/src/bus.ts +++ b/src/bus.ts @@ -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 = | 'boot:provider:start' | 'boot:provider:ok' @@ -17,12 +41,18 @@ export type LifecycleEvent = // came up, and a deploy watching for trouble wants to tell those apart. | 'mesh:boot:retry' | '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: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' | 'route:matched' // 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'; /** @@ -31,8 +61,39 @@ export type LifecycleEvent = * * 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. + * + * ### 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 { + /** + * 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; scope?: string; error?: unknown; @@ -41,10 +102,23 @@ export interface EventPayload { requestId?: string; /** A `traceparent` header carried verbatim. Core parses nothing — that is the exporter's job. */ 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 `''` 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; method?: 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; } @@ -58,6 +132,22 @@ export interface EventPayload { */ export type Correlation = Pick; +/** + * 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. */ export class Bus { private readonly listeners = new Map void>>(); diff --git a/src/http/body.ts b/src/http/body.ts index 9056233..b761ccd 100644 --- a/src/http/body.ts +++ b/src/http/body.ts @@ -129,7 +129,7 @@ function parseAcquired( return parseRequestBody(acquired.bytes, contentType, duplicates, maxParts).then((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 }, ); } diff --git a/src/http/core.ts b/src/http/core.ts index ad7e732..dd1d9f7 100644 --- a/src/http/core.ts +++ b/src/http/core.ts @@ -144,7 +144,7 @@ function errorOutcome( opts: HttpOptions | undefined, headers: Record = {}, ): HandleResult { - const rendered = renderError(error, req, opts?.onError); + const rendered = renderError(error, req, opts?.onError, opts?.logger); return { injected, outcome: { @@ -192,6 +192,15 @@ async function unmatchedOutcome( 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 = ''; + /** What `dispatch` learned along the way that `handle` needs in order to describe the request afterwards. */ interface Trace { route?: string; @@ -234,6 +243,48 @@ export function handle( 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( routes: RouteDef[], opts: HttpOptions | undefined, @@ -301,9 +352,18 @@ async function dispatch( const matched = resolveRoute(routes, req.method, path); 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')) bus.emit('route:unmatched', { name: `${req.method} ${path}`, + route: UNMATCHED_ROUTE, method: req.method, requestId: req.requestId, traceId: req.traceId, @@ -350,7 +410,7 @@ async function dispatch( traceId: req.traceId, }); } catch (error) { - result = renderError(error, req, opts?.onError); + result = renderError(error, req, opts?.onError, opts?.logger); } if (isStreamResult(result)) { diff --git a/src/http/request-gate.ts b/src/http/request-gate.ts index e6e815c..96ac7ec 100644 --- a/src/http/request-gate.ts +++ b/src/http/request-gate.ts @@ -5,6 +5,16 @@ * handler execution finishes; a returned stream does not hold the slot for the stream's lifetime. */ 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; release(): void; } @@ -12,8 +22,11 @@ export interface RequestGate { /** Creates an unlimited gate when `limit` is undefined or non-positive. */ export function createRequestGate(limit: number | undefined): RequestGate { let active = 0; + const limited = limit !== undefined && limit > 0; return { + limited, + acquire(): boolean { if (limit === undefined || limit <= 0) return true; if (active >= limit) return false; diff --git a/src/http/server.ts b/src/http/server.ts index 7b5202e..a07e50c 100644 --- a/src/http/server.ts +++ b/src/http/server.ts @@ -7,7 +7,15 @@ import { readBody as readBodyBytes, deriveSecure, deriveIp } from './request'; import { pipeStream } from './stream'; import { attachWs } from './ws'; 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 { RouteDef, WsRouteDef, MeshControl, HttpOptions } from './types'; import { nodeRequire } from '../node-require'; @@ -102,23 +110,22 @@ function createRequestHandler(cfg: HandlerConfig) { let result: HandleResult | Preflight; let acquired = false; - const watchingEnd = bus?.hasListeners('request:end') ?? false; - const startedAt = watchingEnd ? performance.now() : 0; + const watching = watchingRequests(bus); + const startedAt = watching ? performance.now() : 0; try { if (!gate.acquire()) { - if (watchingEnd) { - const method = req.method ?? 'GET'; - const url = req.url ?? '/'; - bus!.emit('request:end', { - name: `${method} ${url}`, - method, - status: 503, - durationMs: performance.now() - startedAt, - requestId: correlation.requestId, - traceId: correlation.traceId, - }); - } + if (watching) + emitShedPair( + bus, + { + method: req.method ?? 'GET', + url: req.url ?? '/', + requestId: correlation.requestId, + traceId: correlation.traceId, + }, + startedAt, + ); res.writeHead(503, { 'content-type': 'application/json', @@ -129,12 +136,18 @@ function createRequestHandler(cfg: HandlerConfig) { return; } - acquired = true; - res.once('close', () => { - if (!acquired) return; - acquired = false; - gate.release(); - }); + // Both the flag and the listener are skipped when no budget is configured, which is most + // applications: `maxConcurrentRequests` is opt-in and unlimited by default. A closure and an + // EventEmitter registration per request, on the hot path, for a feature that is off is a cost + // with nothing on the other side of it. + if (gate.limited) { + acquired = true; + res.once('close', () => { + if (!acquired) return; + acquired = false; + gate.release(); + }); + } result = await handle( routes, @@ -191,7 +204,7 @@ function readRequestBytes( return readBodyBytes(req, limit).then( (bytes) => ({ bytes }), (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' } } }; }, ); diff --git a/src/http/web.ts b/src/http/web.ts index 15bfdc5..ab09644 100644 --- a/src/http/web.ts +++ b/src/http/web.ts @@ -1,6 +1,14 @@ import type { StreamEncoder } from '../encoders'; 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 type { BodyFailure, BodyReader, MaybePromise } from './body'; import { HttpError } from '../signals'; @@ -69,7 +77,7 @@ function readFetchBytes( url: url.pathname + url.search, 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) }; @@ -143,21 +151,22 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) { let result: HandleResult | Preflight; let acquired = false; - const watchingEnd = opts?.bus?.hasListeners('request:end') ?? false; - const startedAt = watchingEnd ? performance.now() : 0; + const watching = watchingRequests(opts?.bus); + const startedAt = watching ? performance.now() : 0; try { if (!gate.acquire()) { - if (watchingEnd) { - opts!.bus!.emit('request:end', { - name: `${request.method} ${path}`, - method: request.method, - status: 503, - durationMs: performance.now() - startedAt, - requestId: correlation.requestId, - traceId: correlation.traceId, - }); - } + if (watching) + emitShedPair( + opts!.bus!, + { + method: request.method, + url: path, + requestId: correlation.requestId, + traceId: correlation.traceId, + }, + startedAt, + ); return new Response(JSON.stringify({ error: 'Service Unavailable' }), { status: 503, @@ -171,7 +180,7 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) { }); } - acquired = true; + acquired = gate.limited; result = await handle( routes, diff --git a/src/index.ts b/src/index.ts index bbd0872..cd6c794 100644 --- a/src/index.ts +++ b/src/index.ts @@ -60,7 +60,7 @@ export { // Bus & flow 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 type { StepFn, CompiledFlow } from './flow'; @@ -81,6 +81,7 @@ export type { StreamEncoder } from './encoders'; // HTTP, security & validation export type { RequestLimits } from './http'; +export { UNMATCHED_ROUTE } from './http/core'; export type { TlsOptions, CorsOptions, SecurityOptions } from './security'; export type { UploadedFile, MultipartBody } from './multipart'; export type { StandardSchemaV1 } from './standard-schema'; diff --git a/src/pipeline.ts b/src/pipeline.ts index 2408c57..7356bcf 100644 --- a/src/pipeline.ts +++ b/src/pipeline.ts @@ -3,6 +3,7 @@ import { renderError, type ErrorRenderer } from './transformers'; import { isAsyncIterable } from './channel'; import type { TransformerFn, Transport } from './metadata'; 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. */ export interface PipelineStep { @@ -113,9 +114,10 @@ export async function runPipeline(args: { bus: Bus; transport: Transport; onError?: ErrorRenderer; + logger?: Logger; correlation?: Correlation; }): Promise { - 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 let context: any = { ...seed }; @@ -137,16 +139,33 @@ export async function runPipeline(args: { const transformed = transformer(result); return { status: transformed.status ?? 200, headers: transformed.headers ?? {}, body: transformed.body }; } 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 }; - return renderError( - error, - { method: req.method ?? '', url: req.url ?? '', headers: (context.headers ?? req.headers ?? {}) as never }, - onError, - ); + let status: number | undefined; + + try { + 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 }); + } } } diff --git a/src/plugin.ts b/src/plugin.ts index 92dfa33..abbc596 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -14,7 +14,18 @@ export interface ScopeNode { export interface ScopeApi { 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 { bus: { on: Bus['on'] }; scope: ScopeApi; diff --git a/src/transformers.ts b/src/transformers.ts index eac5c81..7cf7c0e 100644 --- a/src/transformers.ts +++ b/src/transformers.ts @@ -1,6 +1,7 @@ import { isHttpError, ValidationError } from './signals'; import type { TransformerFn } from './metadata'; import { flattenPath } from './standard-schema'; +import type { Logger } from './logger'; /** A ready-to-send HTTP response. */ 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}. */ -export function renderError(error: unknown, req: ErrorRequest, onError?: ErrorRenderer): ErrorResponse { - return onError?.(error, req) ?? errorToResponse(error); +export function renderError( + 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); + } } diff --git a/test/app.test.ts b/test/app.test.ts index 6e0400f..1ab50de 100644 --- a/test/app.test.ts +++ b/test/app.test.ts @@ -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 }); 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' }) class MyRooms { provide() { @@ -618,7 +622,7 @@ describe('rooms auto-provide', () => { } @Module({ mountpoint: '/api', providers: [MyRooms], controllers: [Ctl] }) class M {} - expect(() => createApp({ modules: [M] })).not.toThrow(); + expect(() => createApp({ modules: [M] })).toThrow(/'rooms' is reserved by the framework/); }); }); diff --git a/test/bus-access.test.ts b/test/bus-access.test.ts new file mode 100644 index 0000000..1f3a25c --- /dev/null +++ b/test/bus-access.test.ts @@ -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(); + }); +}); diff --git a/test/errors.test.ts b/test/errors.test.ts index 6245a10..57f279a 100644 --- a/test/errors.test.ts +++ b/test/errors.test.ts @@ -80,3 +80,76 @@ describe('HttpError body', () => { 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 }> = []; + const logger = { + debug() {}, + info() {}, + warn() {}, + error(msg: string, fields?: Record) { + 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(); + }); +}); diff --git a/test/http.test.ts b/test/http.test.ts index ff92d89..ebe1804 100644 --- a/test/http.test.ts +++ b/test/http.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it, test, vi } from 'vitest'; import * as net from 'node:net'; +import { ServerResponse } from 'node:http'; import { once } from 'node:events'; import { Bus } from '../src/bus'; import { matchRoute, parseQuery, createHttpServer } from '../src/http'; @@ -419,4 +420,45 @@ describe('request hardening', () => { 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((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((r) => limited.listen(0, r)); + expect((await fetch(`${getUrl(limited)}/ping`)).status).toBe(200); + expect(closeListeners.length).toBeGreaterThan(0); + limited.close(); + } finally { + spy.mockRestore(); + } + }); + }); diff --git a/test/lifecycle-pairing.test.ts b/test/lifecycle-pairing.test.ts new file mode 100644 index 0000000..f324cb2 --- /dev/null +++ b/test/lifecycle-pairing.test.ts @@ -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[0]; + opts?: Parameters[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((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((r) => (release = r)); + const firstStarted = new Promise((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((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); + }); +}); diff --git a/test/observability.test.ts b/test/observability.test.ts index c4e3a50..e8c99c7 100644 --- a/test/observability.test.ts +++ b/test/observability.test.ts @@ -1,6 +1,7 @@ import { describe, it, expect } from 'vitest'; import { createApp, Provider, Step, Route, Get, Module, needs } from '../src/index'; import type { EventPayload } from '../src/bus'; +import { UNMATCHED_ROUTE } from '../src/index'; @Provider({ provides: 'db' }) class Db { @@ -175,6 +176,100 @@ describe('failure reporting', () => { expect(requestFailures).toHaveLength(1); expect(requestFailures[0].route).toBe('/bad/go'); 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'); + }); }); diff --git a/test/reserved-tokens.test.ts b/test/reserved-tokens.test.ts new file mode 100644 index 0000000..3ce7109 --- /dev/null +++ b/test/reserved-tokens.test.ts @@ -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([]); + }); +}); diff --git a/test/views-html.test.ts b/test/views-html.test.ts index 7eafeb1..2645dc9 100644 --- a/test/views-html.test.ts +++ b/test/views-html.test.ts @@ -19,6 +19,24 @@ class Views { class M {} 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', () => { it('string mode sends the handler return as text/html', async () => { const res = await app.fetch(new Request('http://x/str'));