Skip to content

Add diagnostics_channel events (router 2.3.0's express.router.request tracing, express.initialization) - #84

Merged
abedmurrar merged 12 commits into
masterfrom
add/diagnostics-channel
Nov 23, 2026
Merged

abedmurrar merged 12 commits into
masterfrom
add/diagnostics-channel

Conversation

@abedmurrar

@abedmurrar abedmurrar commented Nov 23, 2026 •

Copy link
Copy Markdown
Owner

Summary

Express now publishes diagnostics_channel events, so APMs, tracers and loggers can observe an app without monkey-patching it:

  • express.router.request, a TracingChannel: every middleware, route handler, error handler and app.param() callback the router runs publishes start/end, asyncStart/asyncEnd when a returned promise settles, and error once per error, where it starts. The context carries req, res, handler, layer, route (the pattern that matched), and param, errorHandler, incomingError, error, result where they apply.
  • express.initialization, a plain channel: every express() call publishes { app } once the app is set up.

With no subscribers nothing is published, no context object is built and no error is recorded.

Upstream: expressjs#6353, expressjs#6959 (the ROADMAP row's PR), expressjs#7041. ROADMAP.md, "Additions on the compatible line".

Design: why router 2.3.0's channel, not PR expressjs#6959's names

Router 2.3.0 (published 2026-11-17, not vendored yet) already ships request tracing: pillarjs/router#196 by logaretm, with pillarjs/router#207 (the matched pattern), pillarjs/router#215 by bjohansebas (param callbacks, error attribution) and pillarjs/router#223 (terminal events). It was reviewed by Node's diagnostics_channel maintainer (Qard) and APM authors (Flarna), it closes expressjs#6353, and it is what Express 5 users get from npm update router. This PR ports it into our vendored router with the same channel name, events and context, so:

  • a subscriber written for Express + router 2.3.0 (Sentry's, OpenTelemetry's once they adopt it) works on the fork unchanged;
  • the coming 2.3.0 re-sync keeps this code instead of replacing it (VENDORED.md lists every line that differs).

PR expressjs#6959's channels (express.request.start/end/error, express.middleware.start/end/error, express.route.match) are not taken:

  • it wraps every handler at registration (app.use, app.METHOD, app.param only, not router.use), so layer.handle is no longer the app's function, and every call goes through the wrapper and its three hasSubscribers checks even with no subscribers; it also registers an on-finished listener and calls process.hrtime() on every request unconditionally;
  • plain start/end channels give no async-context propagation; a TracingChannel does (start.bindStore() follows the handler into its promise, as the tests show);
  • the request's own start and end are Node's http.server.request.start and http.server.response.finish, which every Node HTTP server already publishes.

express.initialization is PR expressjs#7041 (DemianParkhomenko) as written: { app } after app.init(), before express() returns, Fastify's fastify.initialization counterpart.

Changes

  • src/router/lib/tracing.ts (new): router 2.3.0's lib/tracing.js typed, plus its lib/param.js as a private helper of the traced param path. Exports the TraceContext type.
  • src/router/lib/layer.ts: handleRequest/handleError are unchanged. New traceRequest/traceError do the same through 2.3.0's invokeWithTrace, following errorOnly from PR Add app.error() and router.error(): error handlers whatever their length #85 (app.error() handlers are traced as error handlers whatever their length).
  • src/router/index.ts: checks for subscribers once in handle(), and calls each layer's traceRequest/traceError instead when traced (a route's own layer is never traced; route.dispatch traces its handlers); while traced, records the matched pattern (req[matchedRoute], restored on router exit like baseUrl/params); records errors for attribution (only while subscribed); traces param callbacks.
  • src/router/lib/route.ts: dispatch() checks once and picks each handler's traced or untraced method.
  • src/router/lib/symbols.ts: 2.3.0's matchedRoute symbol. src/router/lib/original-route.ts: matchedPattern exported, for the path-array case.
  • src/express.ts: the express.initialization channel.
  • typings/: express.RouterTraceContext and express.InitializationMessage (also in index.d.mts); test/types/diagnostics.ts.
  • Tests: test/router/tracing.js (router 2.3.0's 2,171-line suite, 151 tests, three adapted, see VENDORED.md), test/fork-diagnostics-channel.js (23 tests through Express apps), test/fixtures/diagnostics-throwing.js.
  • Docs: docs/api/diagnostics.md (new: each channel, each event and when it fires, every context property, error rules, examples), the API index, docs/fork/differences.md, History.md (Additions), VENDORED.md, the ROADMAP row.

Behaviour

  • No subscribers: nothing new happens. Each router and each route checks requestChannel.hasSubscribers once as it starts on a request, and calls each layer's untraced handleRequest/handleError, which are byte for byte the old ones. No pattern stored on the request, no context object, no runStores, no publish, no Set of seen errors. A test replaces publish and runStores on all six channel objects and drives middleware, routes, a path array, async param callbacks, sync and async errors, error handlers, a sub-app, a nested router, a URL-decoding error and a 404: zero calls, and no error-tracking symbol on any request.
  • Same responses and call order with subscribers. A test runs the same app (param callback, middleware, nested router with an async handler that fails, a sub-app, a thrown error, a 404) with and without subscribers: identical handler call order, statuses, content types and bodies.
  • Subscriber exceptions don't break a request. Node's diagnostics_channel calls each subscriber (and each bound store's transform) in a try/catch and rethrows on the next tick as an uncaught exception. Checked in a child process where every phase's subscriber, a start.bindStore() transform and the initialization subscriber all throw: same calls and responses as without subscribers, and all seven errors arrive as uncaughtException.
  • Events (from the tests): app.use(logger) + app.get('/', show) gives start logger, start show, end show, end logger; an async handler start, end, asyncStart, asyncEnd; a throw recovered by an error handler start boom, error boom, start recover, end recover, end boom; a rejection start, end, error, start recover, end recover, asyncStart, asyncEnd; an unhandled next(err) two routers deep publishes error once. A sub-app is traced as its mounted_app layer (route /sub) with its handlers inside; nested routers report their mount patterns (/api/:version, /users, /:id); a path array reports the entry that matched; a 404 traces only middleware that ran.
  • Differences from router 2.3.0 (VENDORED.md): the subscriber check is once per router and per route instead of before every handler, and the pattern is only stored while traced (2.3.0's way measured +0.48% on hello and +1.05% on mw10 here), so a subscriber that attaches mid-request sees handlers from the next router or route the request enters; errors are only recorded while subscribed (2.3.0 records every error, which sets a symbol on every failing request); the untraced paths stay 2.2.0's (2.3.0 also changed them to pass a no-op to then); the pattern comes from layer.rawPath because our match() still returns true (2.3.0's Profile expressjs/express#216).

Proof

  • npm run lint, npm run typecheck, npm run test:types (declarations 71,175 bytes of the 75,000 budget): clean.
  • npm run test-ci on Node 24.17.0, after merging master (PR Add app.error() and router.error(): error handlers whatever their length #85's app.error()): 172 files, 9,496 passed, 8 skipped (174 new: 151 in test/router/tracing.js, 23 in test/fork-diagnostics-channel.js), 100% statements, branches, functions and lines; coverage-files check passed (35 source files). The differential harness and every existing test pass unchanged, with no new allowed entry.
  • Planted breaks, each applied to src/ in a separate worktree, rebuilt, and the two new test files run (174 tests), then restored. All 26 are caught:
Planted break Fails
middleware and error handlers traced without the router's traced flag 2
route handlers traced without the route's flag 1
route error handlers traced without the flag 1
param callbacks traced without the hasSubscribers guard 1
router flag always on 2
route flag always on 1
next() records errors without the guard 1
matching errors recorded without the guard 1
express.initialization published without the guard 2
middleware and error handlers never traced (the core line) 45
route handlers never traced 70
router flag always off 54
route flag always off 71
router error handlers run untraced while traced 25
route error handlers never traced 2
param callbacks never traced 42
route pattern not stored 13
middleware pattern not stored 6
param callback pattern not stored (middleware parameters) 1
path-array entry not resolved 11
matched pattern not restored on router exit 4
express.initialization not published 2
matching errors not recorded 4
errors not recorded in next() 1
traceError ignores app.error()'s errorOnly 1
traceRequest ignores errorOnly 1

Every unguarded or always-on path is caught by the spy test (zero publish/runStores calls without subscribers), and the unguarded recordError by the check that no request gets the error-tracking symbol.

  • Type tests: errorHandler?: boolean instead of true fails 2 checks in test/types/diagnostics.ts; route: any fails 1.

Benchmark

Local instruction count, run on this machine (not CI): valgrind 3.19.0, Node 24.17.0, node benchmarks/count/run.ts --counter valgrind --runs 1 --jobs 2 --against origin/master --max-change 0.3 --report-only, merge-base 1d579ee -> 9f7c7b7 (the later commits are docs only). Every scenario is within 0.3%:

scenario baseline head change
hello 78.44k 78.51k +0.09%
json 86.79k 86.85k +0.07%
params 81.72k 81.70k -0.02%
mw10 94.83k 95.00k +0.18%
routes100 122.60k 122.69k +0.07%
post-json 125.37k 125.34k -0.02%
not-found 99.28k 99.30k +0.01%
query 103.25k 103.32k +0.07%
format 140.27k 140.30k +0.02%

How it got there (same harness; the first three rows against merge-base b9e0e3d, before PR #85 merged, the rest against 1d579ee; runs whose result was already over budget were stopped early):

Layout hello mw10 routes100
Router 2.3.0's: a hasSubscribers check and the traced call's closure inside handleRequest/handleError, req[matchedRoute] set for every matched layer and restored on every router exit +0.48% +1.05% (stopped early)
Checked once per router and per route, passed to the layer methods; pattern only while traced +0.19% +0.63% (stopped early)
Traced calls moved out of the layer methods (the closure made every call allocate a context) +0.10% +0.43% (stopped early)
handleRequest/handleError left as they were; traceRequest/traceError picked at the call site +0.10% +0.40% +0.07%
One check per layer (pattern set only on traced paths), var flag (no TDZ check) +0.00% +0.25% +0.43%
Final: the route's pattern set in next(), not in the processParams callback (reading noSlash there made it a context variable the matching loop loads for every layer) +0.09% +0.18% +0.07%

What is left per request without subscribers: one TracingChannel#hasSubscribers read per router and per route, one boolean test per middleware layer, and one falsy test of err per next() call.

Risks / follow-ups

  • Stack traces differ while traced. With subscribers, an error thrown by a handler has invokeHandler, runStores, invokeWithTrace and traceRequest frames between the router and the handler, so a stack printed by Express's final handler in development differs. Without subscribers the stack is unchanged.
  • Late subscribers: a subscriber that attaches while a request is being routed sees its handlers from the next router or route that request enters, not the rest of the current one. An error that was raised and forwarded through a router entirely before the first subscriber attached isn't recorded, so a traced forwarder could report it later (2.3.0 records every error to avoid that, at a cost to every failing request). 2.3.0's tests for subscribing mid-request pass.
  • ctx.layer is internal (as upstream documents): its shape may change; layer.name, route and req.route are the stable parts.
  • Re-sync to router 2.3.0 (from 2026-11-24): req[matchedRoute] = match.pattern replaces the rawPath lookup once match() returns objects; keep the once-per-router traced flag and the two hasSubscribers guards on recordError. The 2.3.0 untraced-path change (no-op then callback) is a behaviour change to judge in that PR.
  • test/fork-res-render.js "passes the send error to the error handler, once" timed out once in a full run under load average 10 (it waits 20 ms on a timer); it passed alone three times and in the next full run. Unrelated code path (no subscribers).
  • The middleware suites (npm run test:ecosystem-suites) were not run locally; CI runs them.

… tracing and express.initialization

Port router 2.3.0's TracingChannel (pillarjs/router#196, expressjs#207, expressjs#215, expressjs#223)
into the vendored router, and publish { app } on express.initialization
from express() (expressjs#7041). Nothing is built or published
without subscribers.
docs/api/diagnostics.md (new) lists both channels, when each event fires
and what it carries; History, differences, the API index and VENDORED.md
describe the router 2.3.0 tracing port and how this copy differs.
@coveralls

coveralls commented Nov 23, 2026 •

Copy link
Copy Markdown

Coverage Report for CI Build 45243374660

Coverage remained the same at 100.0%

Details

  • Coverage remained the same as the base build.
  • Patch coverage: 536 of 536 lines across 7 files are fully covered (100%).
  • No coverage regressions found.

Uncovered Changes

No uncovered changes found.

Coverage Regressions

No coverage regressions found.


Coverage Stats

Coverage Status
Relevant Lines: 12352
Covered Lines: 12352
Line Coverage: 100.0%
Coverage Strength: 62409.38 hits per line

💛 - Coveralls

Router 2.3.0 checks the channel before every handler and stores the
matched pattern on every request. The router and the route now check once
as they start and pass the result to each layer, and only a traced router
stores and restores the pattern, so an untraced request adds one check per
router and per route.
A closure inside Layer#handleRequest made every call allocate a context,
traced or not, and the restore for the matched pattern pushed
Router#handle past V8's inlining size. Move the traced calls into helpers
and wrap done for the pattern only when traced.
The router and the route call new traceRequest and traceError methods
when traced, chosen at the call site from their once-per-request check,
so the untraced layer methods are byte for byte the old ones.
traceRequest and traceError follow errorOnly as handleRequest and
handleError do since the merge of PR #85.
The pattern is set where a traced handler or parameter callback is about
to run, so next() no longer checks for every matched layer, and the
once-per-request flag is a var, which closures read without a TDZ check.
Read from that callback, noSlash became a context variable, which the
matching loop then loads for every layer (routes100 counted +0.43%).
@abedmurrar
abedmurrar merged commit f3add0d into master Nov 23, 2026
12 checks passed
@abedmurrar
abedmurrar deleted the add/diagnostics-channel branch November 23, 2026 19:01
abedmurrar added a commit that referenced this pull request Nov 23, 2026
ROADMAP: router re-sync keeps the tracing from #84
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Support diagnostic channels

2 participants