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>
This commit is contained in:
3 files changed
+105
-10
No files matched your search
+26
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
+23
-10
@@ -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<string, unknown> };
|
||||
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 });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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');
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user