feat(observability): correlate and time the lifecycle event stream
Tasks 1-3 of the observability plan. The Bus already had 19 emission points; what it lacked was any way to tell which request an event belonged to, which made the whole stream unusable under concurrency. Every per-request event now carries requestId, traceId, route, method and transport, and request:step:leave carries durationMs — a field that has been declared in EventPayload since the beginning with nothing ever writing it. Identity is derived in the adapters rather than in handle(), because both read and size-check the body first: a 413 is answered without handle() ever seeing the request, so generating there would leave exactly the failures an operator most wants to correlate with nothing to correlate them by. An incoming x-request-id is adopted rather than replaced, and traceparent is carried verbatim — core implements no propagation spec. Timing takes N+1 readings for N steps, since one step's end is the next one's start. Measured at 25.2ns per step against a ~10.19us request. request:step:error now names the step that actually failed. It reported name: 'pipeline' before, discarding the one fact it exists to carry, because it was emitted from the outer catch where that is all that is known. The outer catch emits request:failed instead: one marks the span, the other the trace. route carries the matched pattern and never the concrete path. Labelling a metric on raw URLs gives unbounded cardinality and takes down the metrics backend rather than the app, so it is a contract, with a test. Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
8 files changed
+305
-13
No files matched your search
@@ -8,6 +8,13 @@ import { pickEncoder } from './stream';
|
||||
import type { RouteDef, HttpOptions } from './types';
|
||||
import type { StreamEncoder } from '../encoders';
|
||||
|
||||
// The project tsconfig's `lib` is `es2020` with no `DOM`, so the Web Crypto global is undeclared
|
||||
// even though all four supported runtimes provide it. Ambient-declare only what is called — the
|
||||
// same approach `src/deno.ts` takes for the Deno globals. Deliberately *not* `node:crypto`: this
|
||||
// file is the runtime-neutral core, and the web-standard global is what Deno, Bun and workerd all
|
||||
// have without a compatibility flag.
|
||||
declare const crypto: { randomUUID(): string };
|
||||
|
||||
/** A runtime-neutral inbound request: body already parsed by the caller's ingress (Node stream, fetch Request, …). */
|
||||
export interface NeutralRequest {
|
||||
method: string;
|
||||
@@ -16,6 +23,31 @@ export interface NeutralRequest {
|
||||
body: unknown; // already-parsed body
|
||||
secure: boolean;
|
||||
ip: string;
|
||||
requestId: string;
|
||||
traceId?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Derives a request's identity from its headers, for the adapters to stamp on a `NeutralRequest`.
|
||||
*
|
||||
* **Called by the adapters, not by {@link handle}**, and the placement is the point. Both adapters
|
||||
* read and size-check the body before they reach `handle()` (`server.ts`, `web.ts`), so a `413` is
|
||||
* answered without `handle()` ever seeing the request. Generating identity in here would leave
|
||||
* precisely the failures an operator most wants to correlate with nothing to correlate them by.
|
||||
*
|
||||
* An `x-request-id` from a gateway is adopted rather than replaced — a service behind a proxy must
|
||||
* not open a second identity for a request that already has one. `traceparent` is carried through
|
||||
* untouched: core implements no propagation spec, and W3C Trace Context belongs to the exporter.
|
||||
*/
|
||||
export function correlateRequest(headers: Record<string, string | string[] | undefined>): {
|
||||
requestId: string;
|
||||
traceId?: string;
|
||||
} {
|
||||
const first = (value: string | string[] | undefined): string | undefined => (Array.isArray(value) ? value[0] : value);
|
||||
const incoming = first(headers['x-request-id'])?.trim();
|
||||
const traceId = first(headers.traceparent)?.trim();
|
||||
|
||||
return { requestId: incoming || crypto.randomUUID(), traceId: traceId || undefined };
|
||||
}
|
||||
|
||||
/** The neutral shape of a response: a fully buffered body, or a stream to pipe frame-by-frame. */
|
||||
@@ -143,6 +175,8 @@ export async function handle(
|
||||
body: req.body,
|
||||
protocol: req.secure ? 'https' : 'http',
|
||||
ip: req.ip,
|
||||
requestId: req.requestId,
|
||||
traceId: req.traceId,
|
||||
});
|
||||
} catch (error) {
|
||||
result = renderError(error, { method: req.method, url: req.url, headers: req.headers }, opts?.onError);
|
||||
|
||||
+4
-1
@@ -10,7 +10,7 @@ import { readBody, deriveSecure, deriveIp } from './request';
|
||||
import { pipeStream } from './stream';
|
||||
import { attachWs } from './ws';
|
||||
import { mergeInjectedHeaders } from './headers';
|
||||
import { handle } from './core';
|
||||
import { handle, correlateRequest } from './core';
|
||||
import type { RouteDef, WsRouteDef, MatchedRoute, MeshControl, HttpOptions } from './types';
|
||||
|
||||
interface HandlerConfig {
|
||||
@@ -85,6 +85,8 @@ function createRequestHandler(cfg: HandlerConfig) {
|
||||
// Install the security-header patch BEFORE any routing/response so every path
|
||||
// (200, 404, error, stream) writes headers through the same patched writeHead.
|
||||
const secure = deriveSecure(req, trustProxy);
|
||||
// Derived before the body is read, so a 413 rejected below still carries an identity.
|
||||
const correlation = correlateRequest(req.headers);
|
||||
const injected: Record<string, string> = { ...buildSecurityHeaders(opts?.security ?? true, secure) };
|
||||
patchResponseHeaders(res, injected);
|
||||
|
||||
@@ -118,6 +120,7 @@ function createRequestHandler(cfg: HandlerConfig) {
|
||||
}
|
||||
|
||||
const result = await handle(routes, opts, {
|
||||
...correlation,
|
||||
method,
|
||||
url,
|
||||
headers: req.headers,
|
||||
|
||||
@@ -38,6 +38,10 @@ export type RouteHandler = (req: {
|
||||
body: unknown;
|
||||
protocol: 'http' | 'https';
|
||||
ip: string;
|
||||
/** Correlates every lifecycle event this request emits; see `correlateRequest` in `./core`. */
|
||||
requestId: string;
|
||||
/** An incoming `traceparent`, carried verbatim for an exporter to interpret. */
|
||||
traceId?: string;
|
||||
}) => Promise<PipelineResult>;
|
||||
|
||||
/** A registered HTTP route: method, path pattern, streaming transport, and handler. */
|
||||
|
||||
+4
-1
@@ -1,5 +1,5 @@
|
||||
import type { StreamEncoder } from '../encoders';
|
||||
import { handle, computeInjected, type HandleResult } from './core';
|
||||
import { handle, computeInjected, correlateRequest, type HandleResult } from './core';
|
||||
import { mergeInjectedHeaders } from './headers';
|
||||
import { parseRequestBody } from './server';
|
||||
import { normalizeRequestPath, resolveRoute } from './router';
|
||||
@@ -154,6 +154,8 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
|
||||
const url = new URL(request.url);
|
||||
const path = url.pathname + url.search;
|
||||
const headers = headersToRecord(request.headers);
|
||||
// Derived before the body is read, so a 413 rejected below still carries an identity.
|
||||
const correlation = correlateRequest(headers);
|
||||
let matched: ReturnType<typeof resolveRoute>;
|
||||
|
||||
try {
|
||||
@@ -176,6 +178,7 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
|
||||
}
|
||||
|
||||
const result = await handle(routes, opts, {
|
||||
...correlation,
|
||||
method: request.method,
|
||||
url: path,
|
||||
headers,
|
||||
|
||||
Reference in new issue
Block a user