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>
This commit is contained in:
chrnx committed 2026-09-01 10:21:34 -05:00
1 parent 0f2f62d8c1
commit 5d8363d225
5 files changed
+300 -29

No files matched your search

+29 -1
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 =
| 'boot:provider:start'
| 'boot:provider:ok'
@@ -17,8 +41,12 @@ 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
+42
View File
@@ -234,6 +234,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,
+22 -15
View File
@@ -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',
+22 -13
View File
@@ -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';
@@ -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,
+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);
});
});