diff --git a/src/bus.ts b/src/bus.ts index 4bc17a7..9fc069a 100644 --- a/src/bus.ts +++ b/src/bus.ts @@ -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 `''` 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; diff --git a/src/http/core.ts b/src/http/core.ts index 97e2a45..dd1d9f7 100644 --- a/src/http/core.ts +++ b/src/http/core.ts @@ -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; @@ -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, diff --git a/src/index.ts b/src/index.ts index bbd0872..fc38f33 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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/test/observability.test.ts b/test/observability.test.ts index 1ce2b2e..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 { @@ -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.