diff --git a/src/bus.ts b/src/bus.ts index 58c17b3..4bc17a7 100644 --- a/src/bus.ts +++ b/src/bus.ts @@ -59,6 +59,27 @@ 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 { name: string; @@ -73,6 +94,11 @@ export interface EventPayload { 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; } diff --git a/src/pipeline.ts b/src/pipeline.ts index 2408c57..d1311a1 100644 --- a/src/pipeline.ts +++ b/src/pipeline.ts @@ -137,16 +137,29 @@ 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, + ); + 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 from `finally`, after the render rather than before it, for two reasons. The status + // is only decided by the render — `onError` may turn any throw into any status, so deriving + // it from the error would be a guess that a custom renderer makes wrong. And a renderer that + // *throws* must not swallow the event: `finally` still fires, with `status` left undefined, + // which is the one case where this event has none. + if (bus.hasListeners('request:failed')) + bus.emit('request:failed', { name: correlation.route ?? 'pipeline', error, status, ...correlation }); + } } } diff --git a/test/observability.test.ts b/test/observability.test.ts index c4e3a50..e532b5e 100644 --- a/test/observability.test.ts +++ b/test/observability.test.ts @@ -175,6 +175,62 @@ 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 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. + it('still reports the failure when onError itself throws, with no status to give', async () => { + const app = createApp({ + modules: [BadModule], + onError: () => { + throw new Error('renderer exploded'); + }, + }); + const failures: EventPayload[] = []; + app.bus.on('request:failed', (p) => failures.push(p)); + + await app.fetch(new Request('http://x/bad/go')).catch(() => undefined); + + expect(failures).toHaveLength(1); + expect(failures[0].status).toBeUndefined(); + expect((failures[0].error as Error).message).toBe('step exploded'); + }); });