feat: add diagnostics_channel support for request lifecycle, middleware, and route events #6959
+295
−5
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.
I have successfully implemented support for Node.js Diagnostic Channels in Express.js. This allows for fine-grained observability of the request lifecycle, middleware execution, and route matching without the need for monkey-patching.
Changes Made
Core Infrastructure
Created diagnostics.js to centralize diagnostic channel definitions using node:diagnostics_channel.
Defined the following channels:
Request Lifecycle Events
Modified application.js to publish events at the start and end of each request in app.handle.
Used on-finished to reliably detect request completion and errors for diagnostic publishing.
Middleware and Route Match Events
Implemented a wrapMiddleware helper in application.js to intercept middleware execution.
Added support for wrapping middleware in app.use, app.param, and all HTTP verb methods (e.g., app.get, app.post).
Ensured transparency by preserving function length and maintaining req.next consistency to avoid breaking existing Express logic and tests.
Implemented express.route.match publishing when a route is first encountered during middleware execution.
Verification Results
Automated Tests
Created test/diagnostics.js to specifically verify all new diagnostic events.
Ran the full Express test suite (npm test) to ensure no regressions were introduced.
Result: All 1243 existing tests and the 5 new diagnostic tests PASSED.
Performance Consideration
All diagnostic publishing is guarded by channel.hasSubscribers checks, ensuring zero to minimal overhead when no subscribers are active.