diff --git a/src/app/index.ts b/src/app/index.ts index 6d5c6ff..281f8be 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -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, diff --git a/src/bus.ts b/src/bus.ts index 5a3d229..f293bec 100644 --- a/src/bus.ts +++ b/src/bus.ts @@ -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 diff --git a/src/http/core.ts b/src/http/core.ts index cace5ff..fa99e72 100644 --- a/src/http/core.ts +++ b/src/http/core.ts @@ -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 { + 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 { + 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 { 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; diff --git a/src/http/types.ts b/src/http/types.ts index 6b1af32..4e9d61f 100644 --- a/src/http/types.ts +++ b/src/http/types.ts @@ -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; diff --git a/src/index.ts b/src/index.ts index 22d1f79..031a099 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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 diff --git a/src/logger.ts b/src/logger.ts index 5cd9beb..81e2344 100644 --- a/src/logger.ts +++ b/src/logger.ts @@ -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. * diff --git a/test/logger.test.ts b/test/logger.test.ts index 1fb52c8..665bcbc 100644 --- a/test/logger.test.ts +++ b/test/logger.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect, vi, afterEach } from 'vitest'; -import { createApp, createDefaultLogger, Route, Get, Step, Module, Provider, needs } from '../src/index'; +import { createApp, createDefaultLogger, logRequests, Route, Get, Step, Module, Provider, needs } from '../src/index'; import type { Logger, LogFields } from '../src/index'; /** Captures every call so a test can assert on what core wrote rather than on console output. */ @@ -121,6 +121,105 @@ describe('createApp({ logger })', () => { }); }); +describe('request logging', () => { + @Route('/api') + class Ctl { + @Get('/ok') + ok() { + return { ok: true }; + } + @Get('/boom') + boom(): never { + throw new Error('handler exploded'); + } + } + @Module({ mountpoint: '/', controllers: [Ctl] }) + class M {} + + it('is off unless asked for', async () => { + const logger = recordingLogger(); + const app = createApp({ modules: [M], logger }); + + await app.fetch(new Request('http://x/api/ok')); + + // A framework that writes to stdout uninvited is one you must configure before using. + expect(logger.records).toHaveLength(0); + }); + + it('logs one info per completed request, with the pattern and a duration', async () => { + const logger = recordingLogger(); + const app = createApp({ modules: [M], logger, logRequests: true }); + + await app.fetch(new Request('http://x/api/ok')); + + expect(logger.records).toHaveLength(1); + const [record] = logger.records; + expect(record.level).toBe('info'); + expect(record.fields).toMatchObject({ route: '/api/ok', method: 'GET', status: 200 }); + expect(typeof record.fields!.requestId).toBe('string'); + expect(record.fields!.durationMs).toBeGreaterThanOrEqual(0); + }); + + it('logs an error for a failed request, correlated with it', async () => { + const logger = recordingLogger(); + const app = createApp({ modules: [M], logger, logRequests: true }); + + await app.fetch(new Request('http://x/api/boom')); + + const failed = logger.records.find((r) => r.level === 'error'); + expect(failed).toBeDefined(); + expect(failed!.fields).toMatchObject({ route: '/api/boom', error: 'handler exploded' }); + + // Same request, so the failure and the completion carry one identity between them. + const completed = logger.records.find((r) => r.level === 'info'); + expect(completed!.fields!.requestId).toBe(failed!.fields!.requestId); + }); + + it('unsubscribes, so it is removable and not just optional', async () => { + const logger = recordingLogger(); + const app = createApp({ modules: [M], logger }); + const stop = logRequests(app.bus, logger); + + await app.fetch(new Request('http://x/api/ok')); + expect(logger.records).toHaveLength(1); + + stop(); + await app.fetch(new Request('http://x/api/ok')); + expect(logger.records).toHaveLength(1); + }); + + it('keeps writing, and keeps serving, when the logger throws on every call', async () => { + const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {}); + const exploding: Logger = { + debug: () => { + throw new Error('logger is broken'); + }, + info: () => { + throw new Error('logger is broken'); + }, + warn: () => { + throw new Error('logger is broken'); + }, + error: () => { + throw new Error('logger is broken'); + }, + }; + const app = createApp({ modules: [M], logger: exploding, logRequests: true }); + + const res = await app.fetch(new Request('http://x/api/ok')); + + // The request is unharmed: Bus.emit isolates listener failures by design. + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ ok: true }); + + // And the failure is not silent, which is what the wrapper buys on top of that guarantee. + expect(consoleError).toHaveBeenCalled(); + const written = JSON.parse(consoleError.mock.calls[0][0] as string); + expect(written.msg).toContain('the configured logger threw'); + expect(written.error).toBe('logger is broken'); + }); +}); + describe('logger as a dependency', () => { it('is injectable with @needs("logger") and is the same instance', async () => { const logger = recordingLogger();