feat(bus): give an unmatched request a bounded route to be labelled by
`route:unmatched` was the one terminal request event carrying no `route`, so the only
subject a consumer could reach was `name` — and on that event `name` is the concrete,
caller-controlled path.
The cardinality doctrine is already written into the codebase and it is right: a metrics
consumer that labels a counter with a concrete path gets one label per distinct URL, and
unbounded label cardinality takes down the metrics backend rather than the application.
That reasoning applies hardest to exactly this event. A matched route's path is bounded by
the route table; an unmatched one is bounded by nothing at all, and a scanner walking
/aaa, /aab, /aac is a memory leak with a metrics backend attached.
The framework did not create the trap knowingly. It just left the one field that avoids
it empty, precisely where it mattered most.
`route:unmatched` and the `request:end` that follows it now both carry
`route: '<unmatched>'`, exported as `UNMATCHED_ROUTE` so nobody has to hardcode the
string to compare against it. A single series for every path that was never a route,
rather than a fallback each consumer invents and some get wrong. It cannot collide with a
pattern a user can declare, since those start with `/`.
Written down alongside it, because a field alone does not teach the rule: `name` is
caller-controlled and must not be a metric label — true of `request:start` too, which is
not terminal and so was never the one anyone counted. And `route:unmatched` is not a
synonym for failure: a static file served by `createApp({ static })` matched no route
either and answers 200, so the status comes from `request:end`, like everything else.
Closes #65.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
4 files changed
+76
-2
No files matched your search
+22
-2
@@ -50,7 +50,9 @@ export type LifecycleEvent =
|
||||
| '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';
|
||||
|
||||
/**
|
||||
@@ -82,6 +84,16 @@ export type LifecycleEvent =
|
||||
* 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;
|
||||
@@ -90,7 +102,15 @@ 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 `'<unmatched>'` rather than absent, on `route:unmatched` and on the `request:end`
|
||||
* that follows it: a single series for every path that was never a route, instead of a fallback
|
||||
* each consumer invents and some get wrong. It cannot collide with a real pattern, which always
|
||||
* starts with `/`.
|
||||
*/
|
||||
route?: string;
|
||||
method?: string;
|
||||
transport?: string;
|
||||
|
||||
@@ -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 = '<unmatched>';
|
||||
|
||||
/** What `dispatch` learned along the way that `handle` needs in order to describe the request afterwards. */
|
||||
interface Trace {
|
||||
route?: string;
|
||||
@@ -343,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,
|
||||
|
||||
@@ -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';
|
||||
|
||||
@@ -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 {
|
||||
@@ -180,6 +181,40 @@ describe('failure reporting', () => {
|
||||
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.
|
||||
|
||||
Reference in new issue
Block a user