feat(observability): request-level events, and request logging that reads them

Tasks 5 and 6, in that order rather than the plan's: request logging is a
subscriber, so the events it subscribes to had to exist first.

handle() now emits request:start, request:end, route:matched and
route:unmatched. request:end fires when the handler returns, not when a stream
it produced finishes — a streaming route is done here in milliseconds while its
connection may live for hours, and ending the span at close would put hour-long
SSE connections and 2ms buffered replies in one latency distribution. The
stream events already describe the connection and now share the requestId.

route:unmatched covers 404 and 405 both. Naming it after one outcome, as the
report's route.not_found does, would misreport the other.

logRequests(bus, logger) is the consumer: info per completed request, error per
failed one, and it returns an unsubscribe so it is removable rather than merely
optional. createApp({ logRequests: true }) turns it on and is off by default,
because a framework that writes to stdout uninvited is one you have to
configure before you can use it. withConsoleFallback wraps it, since Bus.emit
isolates listener failures by design and a user logger that throws would
otherwise stop writing with nothing to say so. A test proves both halves: the
request still succeeds, and the failure still surfaces.

The bus reaches handle() through HttpOptions so the Node and Fetch adapters
share one channel instead of growing separate ones.

Cost, measured: nothing. First attempt wrapped dispatch in a second async frame
and that alone cost 0.43us per request — a promise and two microtask ticks,
an order of magnitude more than the four Map lookups it was there to arrange.
handle() is no longer async and hands back dispatch's own promise when nothing
subscribes; 4.716-4.791us against 4.736-4.793 before, which is the same number.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-08-16 14:57:42 -05:00
1 parent df460f01dd
commit e052d5ba8f
7 files changed
+303 -6

No files matched your search

+13 -1
View File
@@ -1,6 +1,6 @@
import type http from 'http';
import { Bus } from '../bus';
import { createDefaultLogger, type Logger } from '../logger';
import { createDefaultLogger, logRequests, type Logger } from '../logger';
import { Container } from '../container';
import { topoSort, subgraphFor, GraphNode, nearest } from '../graph';
import { toMermaid, toDOT, graphHtml, type GraphView } from '../graph-viz';
@@ -121,6 +121,15 @@ export function createApp(opts: {
* `@needs('logger')` — one object, two access paths.
*/
logger?: Logger;
/**
* Log one line per completed request, and one per failed one (default: off).
*
* Off by default because a framework that writes to stdout without being asked is a framework
* you have to configure before you can use it. On, it is a subscriber to the lifecycle stream
* like any other consumer — `logRequests(app.bus, app.logger)` does the same thing by hand and
* hands back an unsubscribe, so nothing here is reachable only through this flag.
*/
logRequests?: boolean;
/** Opt in to alpha features whose API may still change. Currently gates `mesh`. */
experimental?: boolean;
/**
@@ -139,6 +148,7 @@ export function createApp(opts: {
const bus = new Bus();
const logger = opts.logger ?? createDefaultLogger();
if (opts.logRequests) logRequests(bus, logger);
const container = new Container();
let server: http.Server | undefined;
const streams = new Set<() => void>();
@@ -234,6 +244,7 @@ export function createApp(opts: {
const staticResolver = opts.static ? buildStaticResolver(opts.static) : undefined;
const fetchOpts: HttpOptions = {
bus,
limits: opts.limits,
tls: opts.tls,
trustProxy: opts.trustProxy,
@@ -264,6 +275,7 @@ export function createApp(opts: {
const wsRoutes = buildWsRoutes(routePlans, deps);
server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl, {
bus,
limits: opts.limits,
streams,
tls: opts.tls,
+7 -1
View File
@@ -13,7 +13,13 @@ export type LifecycleEvent =
| 'mesh:disconnect'
| 'mesh:rpc:error'
| 'plugin:mounted'
| 'request:failed';
| 'request:start'
| 'request:end'
| '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.
| 'route:unmatched';
/**
* Data carried by a lifecycle event: the subject's name plus optional scope, error, timing and
+101 -2
View File
@@ -7,6 +7,7 @@ import { resolveRoute, allowedMethods, normalizeRequestPath, parseQuery } from '
import { pickEncoder } from './stream';
import type { RouteDef, HttpOptions } from './types';
import type { StreamEncoder } from '../encoders';
import type { Bus } from '../bus';
// 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
@@ -153,15 +154,91 @@ async function unmatchedOutcome(
return errorOutcome(error, req, injected, opts, allow.length ? { allow: allow.join(', ') } : {});
}
/** What `dispatch` learned along the way that `handle` needs in order to describe the request afterwards. */
interface Trace {
route?: string;
}
/**
* Runtime-neutral request handler: security/CORS headers, preflight short-circuit, route match / 404 / 405,
* route-handler invocation with error rendering, and the buffered-vs-stream decision. Does no I/O — the
* caller (a Node adapter, a fetch adapter, …) reads/writes the actual request/response.
*
* Wraps {@link dispatch} with the request-level lifecycle events. `request:end` fires when the handler
* returns, **not** when a stream it produced finishes: a route that returns an `AsyncIterable` is done
* here in milliseconds while its connection may live for hours, and ending the span at close would put
* hour-long SSE connections and 2 ms buffered replies in one latency distribution, ruining both.
* `stream:open`/`stream:close` already describe the connection, and now carry the same `requestId`.
*/
export async function handle(
export function handle(
routes: RouteDef[],
opts: HttpOptions | undefined,
req: NeutralRequest,
): Promise<HandleResult | Preflight> {
const bus = opts?.bus;
// Deliberately not `async`. Wrapping `dispatch` in a second async frame costs a promise and two
// microtask ticks per request — measured at 0.43 us, an order of magnitude more than the four
// Map lookups this branch avoids. An unobserved app returns dispatch's own promise untouched.
if (
bus === undefined ||
!(
bus.hasListeners('request:start') ||
bus.hasListeners('request:end') ||
bus.hasListeners('route:matched') ||
bus.hasListeners('route:unmatched')
)
) {
return dispatch(routes, opts, req, undefined, undefined);
}
return observedDispatch(routes, opts, req, bus);
}
async function observedDispatch(
routes: RouteDef[],
opts: HttpOptions | undefined,
req: NeutralRequest,
bus: Bus,
): Promise<HandleResult | Preflight> {
const watchingEnd = bus.hasListeners('request:end');
const startedAt = watchingEnd ? performance.now() : 0;
const trace: Trace = {};
if (bus.hasListeners('request:start'))
bus.emit('request:start', {
name: `${req.method} ${req.url}`,
method: req.method,
requestId: req.requestId,
traceId: req.traceId,
});
const result = await dispatch(routes, opts, req, bus, trace);
if (watchingEnd) {
// A preflight is a 204 the router never routed; a stream has no status of its own and is a 200
// by the time anything is piped.
const status = 'preflight' in result ? 204 : result.outcome.kind === 'buffered' ? result.outcome.status : 200;
bus.emit('request:end', {
name: trace.route ?? `${req.method} ${req.url}`,
method: req.method,
route: trace.route,
status,
durationMs: performance.now() - startedAt,
requestId: req.requestId,
traceId: req.traceId,
});
}
return result;
}
async function dispatch(
routes: RouteDef[],
opts: HttpOptions | undefined,
req: NeutralRequest,
bus: Bus | undefined,
trace: Trace | undefined,
): Promise<HandleResult | Preflight> {
const injected = computeInjected(opts, req);
let path: string;
@@ -178,7 +255,29 @@ export async function handle(
const matched = resolveRoute(routes, req.method, path);
if (!matched) return unmatchedOutcome(routes, opts, req, path, injected);
if (!matched) {
if (bus?.hasListeners('route:unmatched'))
bus.emit('route:unmatched', {
name: `${req.method} ${path}`,
method: req.method,
requestId: req.requestId,
traceId: req.traceId,
});
return unmatchedOutcome(routes, opts, req, path, injected);
}
if (trace) trace.route = matched.def.pattern;
if (bus?.hasListeners('route:matched'))
bus.emit('route:matched', {
name: matched.def.pattern,
route: matched.def.pattern,
method: req.method,
transport: matched.def.transport,
requestId: req.requestId,
traceId: req.traceId,
});
let result: PipelineResult;
+7
View File
@@ -4,6 +4,7 @@ import type { ErrorRenderer } from '../transformers';
import type { TlsOptions, SecurityOptions, CorsOptions } from '../security';
import type { WsRequest, WsSocket } from './ws-core';
import type { StaticResolver } from '../views';
import type { Bus } from '../bus';
/** Per-request and per-server resource ceilings applied by the server. */
export interface RequestLimits {
@@ -17,6 +18,12 @@ export interface RequestLimits {
/** Options controlling server construction: limits, TLS, proxy trust, security headers, CORS, and body parsing. */
export interface HttpOptions {
/**
* Lifecycle events go here. Carried on the options rather than as a parameter so `handle()` —
* the one place both the Node and Fetch adapters meet — can emit without either adapter growing
* a separate channel for it.
*/
bus?: Bus;
limits?: RequestLimits;
streams?: Set<() => void>;
tls?: TlsOptions;
+1 -1
View File
@@ -67,7 +67,7 @@ export { needs, ctx, param, query, body, headers, header, inbound, abort } from
export type { Query, Headers, Context, ArgSpec, ArgDecorator } from './params';
// Observability
export { createDefaultLogger } from './logger';
export { createDefaultLogger, logRequests, withConsoleFallback } from './logger';
export type { Logger, LogLevel, LogFields } from './logger';
// Streaming
+74
View File
@@ -1,3 +1,5 @@
import type { EventPayload } from './bus';
/**
* The logging contract. Four levels, because four have callers: core diagnostics are all `warn`
* today, request logging adds `info` and `error`, and the graph diagnostics add `debug`. No
@@ -59,6 +61,78 @@ function renderJson(level: LogLevel, message: string, fields?: LogFields): strin
return JSON.stringify({ level, time: new Date().toISOString(), name: 'green-tea', msg: message, ...fields });
}
/**
* Wraps a logger so a throwing one cannot go silent.
*
* `Bus.emit` isolates listener failures on purpose — an observer must never be able to break a
* request — but that guarantee has a cost when the observer is the logger itself: a user logger
* that throws would simply stop writing, with nothing to say so. Falling back to `console` keeps
* the Bus's promise without paying for it in silence.
*
* Exported because request logging is not the only thing that should survive a broken logger.
*/
export function withConsoleFallback(logger: Logger): Logger {
const guard =
(level: LogLevel) =>
(message: string, fields?: LogFields): void => {
try {
logger[level](message, fields);
} catch (error) {
console.error(
renderJson('error', 'the configured logger threw; falling back to console', {
level,
originalMessage: message,
error: error instanceof Error ? error.message : String(error),
...fields,
}),
);
}
};
return { debug: guard('debug'), info: guard('info'), warn: guard('warn'), error: guard('error') };
}
/**
* Subscribes request logging to the lifecycle stream: `info` per completed request, `error` per
* failed one. Returns an unsubscribe function, so it is as removable as it is composable — which
* is what "a composable step, not a global middleware" has to mean in practice.
*
* Reads the stream rather than being called from the request path, so there is exactly one account
* of what happened to a request. A second path would eventually disagree with the first.
*/
export function logRequests(bus: BusLike, logger: Logger): () => void {
const safe = withConsoleFallback(logger);
const offEnd = bus.on('request:end', (event) => {
safe.info(`${event.method ?? ''} ${event.route ?? event.name} ${event.status ?? ''}`.trim(), {
requestId: event.requestId,
traceId: event.traceId,
route: event.route,
method: event.method,
status: event.status,
durationMs: event.durationMs,
});
});
const offFailed = bus.on('request:failed', (event) => {
safe.error(`${event.method ?? ''} ${event.route ?? event.name} failed`.trim(), {
requestId: event.requestId,
traceId: event.traceId,
route: event.route,
method: event.method,
error: event.error instanceof Error ? event.error.message : event.error,
});
});
return () => {
offEnd();
offFailed();
};
}
/** The slice of {@link Bus} request logging needs — `on` only, matching what a plugin is handed. */
interface BusLike {
on(event: 'request:end' | 'request:failed', listener: (payload: EventPayload) => void): () => void;
}
/**
* The logger used when `createApp` is given none: structured JSON, or human-readable on a TTY.
*