Repository navigation
Add diagnostics_channel events (router 2.3.0's express.router.request tracing, express.initialization) - #84
Merged
Merged
Conversation
… 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.
Coverage Report for CI Build 45243374660Coverage remained the same at 100.0%Details
Uncovered ChangesNo uncovered changes found. Coverage RegressionsNo coverage regressions found. Coverage Stats
💛 - 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
added a commit
that referenced
this pull request
Nov 23, 2026
ROADMAP: router re-sync keeps the tracing from #84
This was referenced Nov 23, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Express now publishes
diagnostics_channelevents, so APMs, tracers and loggers can observe an app without monkey-patching it:express.router.request, aTracingChannel: every middleware, route handler, error handler andapp.param()callback the router runs publishesstart/end,asyncStart/asyncEndwhen a returned promise settles, anderroronce per error, where it starts. The context carriesreq,res,handler,layer,route(the pattern that matched), andparam,errorHandler,incomingError,error,resultwhere they apply.express.initialization, a plain channel: everyexpress()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:PR expressjs#6959's channels (
express.request.start/end/error,express.middleware.start/end/error,express.route.match) are not taken:app.use,app.METHOD,app.paramonly, notrouter.use), solayer.handleis no longer the app's function, and every call goes through the wrapper and its threehasSubscriberschecks even with no subscribers; it also registers anon-finishedlistener and callsprocess.hrtime()on every request unconditionally;TracingChanneldoes (start.bindStore()follows the handler into its promise, as the tests show);http.server.request.startandhttp.server.response.finish, which every Node HTTP server already publishes.express.initializationis PR expressjs#7041 (DemianParkhomenko) as written:{ app }afterapp.init(), beforeexpress()returns, Fastify'sfastify.initializationcounterpart.Changes
src/router/lib/tracing.ts(new): router 2.3.0'slib/tracing.jstyped, plus itslib/param.jsas a private helper of the traced param path. Exports theTraceContexttype.src/router/lib/layer.ts:handleRequest/handleErrorare unchanged. NewtraceRequest/traceErrordo the same through 2.3.0'sinvokeWithTrace, followingerrorOnlyfrom 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 inhandle(), and calls each layer'straceRequest/traceErrorinstead when traced (a route's own layer is never traced;route.dispatchtraces its handlers); while traced, records the matched pattern (req[matchedRoute], restored on router exit likebaseUrl/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'smatchedRoutesymbol.src/router/lib/original-route.ts:matchedPatternexported, for the path-array case.src/express.ts: theexpress.initializationchannel.typings/:express.RouterTraceContextandexpress.InitializationMessage(also inindex.d.mts);test/types/diagnostics.ts.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/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
requestChannel.hasSubscribersonce as it starts on a request, and calls each layer's untracedhandleRequest/handleError, which are byte for byte the old ones. No pattern stored on the request, no context object, norunStores, nopublish, noSetof seen errors. A test replacespublishandrunStoreson 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.diagnostics_channelcalls each subscriber (and each bound store's transform) in atry/catchand rethrows on the next tick as an uncaught exception. Checked in a child process where every phase's subscriber, astart.bindStore()transform and the initialization subscriber all throw: same calls and responses as without subscribers, and all seven errors arrive asuncaughtException.app.use(logger)+app.get('/', show)givesstart logger, start show, end show, end logger; an async handlerstart, end, asyncStart, asyncEnd; a throw recovered by an error handlerstart boom, error boom, start recover, end recover, end boom; a rejectionstart, end, error, start recover, end recover, asyncStart, asyncEnd; an unhandlednext(err)two routers deep publisheserroronce. A sub-app is traced as itsmounted_applayer (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.helloand +1.05% onmw10here), 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 tothen); the pattern comes fromlayer.rawPathbecause ourmatch()still returnstrue(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-cion Node 24.17.0, after merging master (PR Add app.error() and router.error(): error handlers whatever their length #85'sapp.error()): 172 files, 9,496 passed, 8 skipped (174 new: 151 intest/router/tracing.js, 23 intest/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 newallowedentry.src/in a separate worktree, rebuilt, and the two new test files run (174 tests), then restored. All 26 are caught:tracedflaghasSubscribersguardnext()records errors without the guardexpress.initializationpublished without the guardexpress.initializationnot publishednext()traceErrorignoresapp.error()'serrorOnlytraceRequestignoreserrorOnlyEvery unguarded or always-on path is caught by the spy test (zero
publish/runStorescalls without subscribers), and the unguardedrecordErrorby the check that no request gets the error-tracking symbol.errorHandler?: booleaninstead oftruefails 2 checks intest/types/diagnostics.ts;route: anyfails 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%: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):
hasSubscriberscheck and the traced call's closure insidehandleRequest/handleError,req[matchedRoute]set for every matched layer and restored on every router exithandleRequest/handleErrorleft as they were;traceRequest/traceErrorpicked at the call sitevarflag (no TDZ check)next(), not in theprocessParamscallback (readingnoSlashthere made it a context variable the matching loop loads for every layer)What is left per request without subscribers: one
TracingChannel#hasSubscribersread per router and per route, one boolean test per middleware layer, and one falsy test oferrpernext()call.Risks / follow-ups
invokeHandler,runStores,invokeWithTraceandtraceRequestframes between the router and the handler, so a stack printed by Express's final handler in development differs. Without subscribers the stack is unchanged.ctx.layeris internal (as upstream documents): its shape may change;layer.name,routeandreq.routeare the stable parts.req[matchedRoute] = match.patternreplaces therawPathlookup oncematch()returns objects; keep the once-per-routertracedflag and the twohasSubscribersguards onrecordError. The 2.3.0 untraced-path change (no-opthencallback) 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).npm run test:ecosystem-suites) were not run locally; CI runs them.