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

+100 -1
View File
@@ -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();