diff --git a/History.md b/History.md index 554fd4a701c..02ed3474c68 100644 --- a/History.md +++ b/History.md @@ -3,6 +3,7 @@ Unreleased (fork) ## ✨ Additions +* `diagnostics_channel` events (PR #6959, #7041, issue #6353), for APMs and tracers. Every middleware, route handler, error handler and `app.param()` callback the router runs is traced through the `express.router.request` `TracingChannel`, ported from router 2.3.0 (pillarjs/router#196, #207 and #223 by Abdelrahman Awad (logaretm), and #215 by Sebastian Beltran (bjohansebas)): `start` and `end` around the call, `asyncStart` and `asyncEnd` when a returned promise settles, and `error` once per error, where it starts (`next(err)`, a throw or a rejection). The context has `req`, `res`, `handler`, `layer`, `route` (the pattern that matched, such as `'/users/:id'` or a mount path), and `param`, `errorHandler`, `incomingError`, `error` and `result` where they apply, the same channel and payload as router 2.3.0, so subscribers written for it work unchanged; stores bound on `start` follow the request into async handlers. `express()` publishes `{ app }` on `express.initialization` (from PR #7041 by DemianParkhomenko, Fastify's `fastify.initialization`). With no subscribers nothing is published, no context is built and no error is recorded: each router and each route checks `hasSubscribers` once per request, where router 2.3.0 checks before every handler and stores the matched pattern on every request (instruction count -0.02% to +0.18% per request; router 2.3.0's way measured up to +1.05%). Subscriber errors don't reach the request (Node rethrows them on the next tick). PR #6959's `express.request.*`, `express.middleware.*` and `express.route.match` channels are not taken: they wrapped every handler at registration (changing `layer.handle` and adding work to every call), and Node's `http.server.request.start` and `http.server.response.finish` already mark a request's start and end. Documented in docs/api/diagnostics.md, typed as `RouterTraceContext` and `InitializationMessage`. * Warn, on the `express:router` debug namespace, about routes that can't work as written, when they are registered: a path no request can match (#2511), because its literal text has a space, a control or non-ASCII character, a `?` or a `#` (none of which is ever in a request's still-encoded path), or doesn't start with `/`, with the character's encoded form; and the same method and path registered twice on the same router, naming both by stack index and handler name. Only what the path string proves is flagged. Nothing is printed without `DEBUG=express:router` (or `express:*`), and the checks only run while it is enabled, so they cost nothing per request. * Add `req.originalRoute` (#2501): the full path pattern of the route that matched, the path of every router and sub-app it is mounted under followed by its own, so `router.get('/users/:id')` under `app.use('/api', router)` gives `'/api/users/:id'` for `GET /api/users/7`. Mount paths are joined as `req.baseUrl` joins them, a path array gives the entry that matched, and a RegExp route or mount gives `undefined`, since it has no path form. It is set and kept exactly as long as `req.route` is, so error handlers see the route that failed, and a 404 handler sees `undefined` unless a route matched and passed the request on. The router records the mounts and the route as it goes, and the string is built only when read; the request prototype's enumerable keys are unchanged. Upstream's proposals (pillarjs/router#34 and #86, `req.matchedRoutes`) built an array of every matched path on every request and were never finished. * The `ERR_HTTP_HEADERS_SENT` error thrown when a response method is called after the headers were sent names the method (expressjs/express#7560): `Cannot set headers after they are sent to the client: res.json() was called after the response headers were sent`, where Express 5.3.0 gave Node's message alone. It covers `res.send`, `res.json`, `res.jsonp`, `res.sendStatus`, `res.redirect`, `res.render` (passed to `next(err)` without a callback), `res.set`, `res.append`, `res.cookie`, `res.clearCookie`, `res.location`, `res.type`, `res.attachment`, `res.links`, `res.vary` and `res.format`, and names the method the app called (`res.json()`, not the `res.set()` inside it). Only the message changes: it is the same error object, with the same class, `code` and stack frames, thrown or forwarded from the same place, and Node's text is still its start. Each method names it in a `catch` block, so nothing runs unless the error is thrown. diff --git a/ROADMAP.md b/ROADMAP.md index c4a2f684e31..a57a221e611 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -279,7 +279,7 @@ These are opt-in, and nothing existing changes. | Status | Item | Upstream | Line | Size | Proof | PR | |---|---|---|---|---|---|---| | [x] | `req.signal`, which aborts when the client disconnects | | master | Small | Express's own lazy, non-enumerable accessor on the request prototype, the same on Node 22, 24 and 26: Node 22 has no `IncomingMessage#signal`, and 24.16 to 24.19 and 26.1 to 26.6 abort theirs after every response (nodejs/node#64390, fixed in 24.20 and 26.7). The reason is the default `AbortError` `DOMException`, as for Node and Fastify. 18 new tests (abort on disconnect, `res.destroy()`, a pipelined request, a POST after its body; no abort after a finish, keep-alive or `Connection: close`; read late; sub-apps; no leak over 200 keep-alive requests), passing on Node 22 and 24. 10 planted breaks each fail 1 to 6 of them. Assigning `req.signal` still sets an own property, as on Node 22 with Express 5.3.0. Instruction count within noise | [#75](https://github.com/abedmurrar/express/pull/75) | -| [ ] | `diagnostics_channel` events | PR #6959 | master | Medium | new tests | | +| [x] | `diagnostics_channel` events | PR #6959 | master | Medium | router 2.3.0's `express.router.request` TracingChannel (pillarjs/router#196, #207, #215, #223) ported into the vendored router with the same name, events and context, so subscribers written for it work unchanged; `express()` publishes `{ app }` on `express.initialization` (PR #7041). PR #6959's own channels not taken (it wraps every handler at registration; Node's `http.server.request.start`/`response.finish` already mark the request). Without subscribers: no publish, no context, no error recording (a spy on all six channels sees zero calls); one subscriber check per router and per route, which picks each layer's untraced method (byte for byte router 2.2.0's) or traced one. Same responses and call order with subscribers, and with subscribers that throw (child process). 174 new tests (router 2.3.0's 151, 23 through Express apps); 26 planted breaks each fail 1 to 71. Instruction count -0.02% to +0.18% (2.3.0's per-handler check measured up to +1.05%) | [#84](https://github.com/abedmurrar/express/pull/84) | | [ ] | `app.listRoutes()` | PR #7531, router#174 | master | Medium | new tests; router part arrives with the 2.3.0 re-sync | | | [x] | Explicit error-handler API (`app.error`, `router.error`); counting arguments still works | #2896, #3367, router#59 | master | Medium | `app.error([path], ...fns)` and `router.error([path], ...fns)` take `use()`'s arguments and mount the same way, but the layer is marked `errorOnly` (`false` on the prototype), so it runs only for an error, whatever its `length`; length 4 through `use()` or inline in a route is unchanged. A router or an app given to `error()` throws `EXPRESS_ERR_ERROR_HANDLER_IS_ROUTER`. `app.error` is mixed into each app, so `express.application` keeps 5.3.0's own properties; typed on the global `Express.Application`, and `router.error` on what `express.Router()` returns (`RouterWithErrorHandlers`), so `@types` apps and routers stay assignable both ways. No `route.error()`: a required member on `IRoute` breaks that interop. 46 new tests (wrapped, bound, default and rest parameters, async; paths; sub-apps; nested routers; `next(err)` and `next()`; order with `use()`); 9 planted breaks each fail 1 to 41. Instruction count (valgrind, local): -0.02% to +0.20% | [#85](https://github.com/abedmurrar/express/pull/85) | | [x] | Clearer error when a response is sent twice | #7560 | master | Small | Node's `ERR_HTTP_HEADERS_SENT` message gets `: res.json() was called after the response headers were sent`, naming the Express method the app called (the outermost of `res.send`, `json`, `jsonp`, `sendStatus`, `redirect`, `render`, `set`, `append`, `cookie`, `clearCookie`, `location`, `type`, `attachment`, `links`, `vary` and `format`). Same object, class, `code` and stack frames, thrown or forwarded from the same place, and Node's text is still the start. It is named in `catch` blocks only, so instruction count is within ±0.09%. 30 new tests compare each case with Express 5.3.0; 8 planted breaks each fail 1 to 27 of them. `res.sendFile`/`res.download` keep `send`'s own 500 message | [#76](https://github.com/abedmurrar/express/pull/76) | diff --git a/VENDORED.md b/VENDORED.md index 816ce38e9ad..cec2590c266 100644 --- a/VENDORED.md +++ b/VENDORED.md @@ -22,7 +22,7 @@ All seven copies are the same versions Express 5.3.0 installs here, and match th `serve-static`'s source is our fork, https://github.com/abedmurrar/serve-static, created from expressjs/serve-static with only its default branch. Nothing is pushed to it yet: its `master` is upstream's, and the vendored code is upstream's tag `v2.2.1` (commit `76312e12c2754c226a685201ff43d785455d0590`, which the fork's `master` contains; the fork has no tags). Upstream's `master` has one later change to `index.js`, a comment typo fix (`fall-though` to `fall-through`, expressjs/serve-static#246), which is not released and not in our copy. -`router` 2.3.0 (published 2026-11-17) is not vendored yet. This machine's npm config only accepts releases at least 7 days old, so it waits until 2026-11-24 and goes in as a re-sync. It fixes a rewritten `req.url` losing a slash in a mounted router (upstream issue #4059, pillarjs/router#206), but none of the three routing fixes below (`//` mounts, router cycles, `#` fragments), and adds `router.listRoutes()` (pillarjs/router#174) and request tracing channels (pillarjs/router#196). +`router` 2.3.0 (published 2026-11-17) is not vendored yet. This machine's npm config only accepts releases at least 7 days old, so it waits until 2026-11-24 and goes in as a re-sync. It fixes a rewritten `req.url` losing a slash in a mounted router (upstream issue #4059, pillarjs/router#206), but none of the three routing fixes below (`//` mounts, router cycles, `#` fragments), and adds `router.listRoutes()` (pillarjs/router#174) and request tracing channels (pillarjs/router#196), whose tracing is already ported (see the tracing edit below). `express.static` is our `lib/serve-static`, which loads our `lib/send`, so `express.static`, `res.sendFile` and `res.download` all use the same `send`. The `serve-static` package (and the npm `send` it brings) is no longer a dependency; npm still installs both for the development-only `express-baseline` (Express 5.3.0, the differential harness's baseline). @@ -54,11 +54,18 @@ All seven copies are the same versions Express 5.3.0 installs here, and match th - `router.error()` (expressjs/express#2896): `use()` for error handlers, which run only for an error whatever their `length`. Not in router 2.2.0 or 2.3.0 (pillarjs/router#59, open since 2017, proposed it along with deprecating the length check, which we keep). `src/router/lib/layer.ts`: the `Layer` interface has `errorOnly: boolean`, set to `false` on the prototype after `const proto = Layer.prototype as Layer` (so layers that don't use it get no own property); `handleError` now passes the error on when `fn.length !== 4 && !this.errorOnly` (was `fn.length !== 4`), and `handleRequest` passes the request on when `fn.length > 3 || this.errorOnly` (was `fn.length > 3`). `src/router/index.ts`: the `Router` interface has `error()`, and `proto.error` (after `proto.use`) calls `this.use(...)`, then sets `errorOnly` on the layers it added, or removes them all and throws `EXPRESS_ERR_ERROR_HANDLER_IS_ROUTER` when one of them is a router or an app (a function with a `handle` method). When re-syncing, keep the two conditions and `proto.error`; `route.ts` is untouched. - Error codes (expressjs/express#6951): every error the router creates gets a stable `code` from Express's `withCode` helper (`src/error-code.ts`, required as `../error-code` from `index.ts` and `../../error-code` from `lib/layer.ts` and `lib/route.ts`), which defines `code` as a writable, configurable, non-enumerable own property on the error the call site just created, so messages, classes and stack frames stay upstream's. Not in router 2.2.0 or 2.3.0. `index.ts`: the four `param()` checks (`EXPRESS_ERR_PARAM_NAME_REQUIRED`, `EXPRESS_ERR_PARAM_NAME_NOT_STRING`, `EXPRESS_ERR_PARAM_CALLBACK_REQUIRED`, `EXPRESS_ERR_PARAM_CALLBACK_NOT_FUNCTION`), `handle()` without a callback (`EXPRESS_ERR_ROUTER_CALLBACK_REQUIRED`), `use()` without a handler or with one that isn't a function (`EXPRESS_ERR_HANDLER_REQUIRED`, `EXPRESS_ERR_HANDLER_NOT_FUNCTION`), our mount-on-itself check (`EXPRESS_ERR_ROUTER_MOUNTS_ITSELF`), our `error()` given a router or an app (`EXPRESS_ERR_ERROR_HANDLER_IS_ROUTER`) and the `Rejected promise` error of a param callback (`EXPRESS_ERR_REJECTED_PROMISE`). `lib/route.ts`: the same two handler checks in `all()` and in each method. `lib/layer.ts`: the two `Rejected promise` errors (`handleRequest`, `handleError`), and `decodeParam`'s 400 `URIError` (`EXPRESS_ERR_PARAM_DECODE_FAILED`, set after its `status`). When re-syncing, wrap any new `new Error`/`new TypeError` the same way and add its code to docs/api/errors.md (the `fork-error-codes` tests check the list). +- Tracing (`diagnostics_channel`), ported from router 2.3.0 before the re-sync: the `express.router.request` TracingChannel of pillarjs/router#196, with the matched pattern of #207, the parameter callbacks and error attribution of #215 and the terminal-event rules of #223. Same channel name, events and context, so the re-sync keeps this code. `src/router/lib/tracing.ts` (new) is 2.3.0's `lib/tracing.js` typed, plus its `lib/param.js` (`callParam`) as a private helper that only the traced path uses; it exports the `TraceContext` type, and requires `node:diagnostics_channel` without 2.3.0's `dc.tracingChannel &&` guard (Node 22 has it). `src/router/lib/symbols.ts`: 2.3.0's `matchedRoute` symbol. `src/router/lib/layer.ts`: `handleError` and `handleRequest` are unchanged; two new methods after them, `traceError` and `traceRequest`, do the same with 2.3.0's traced path (the not-a-handler checks, then 2.3.0's `invokeWithTrace` call with its context), and `invokeWithTrace` (2.3.0's) follows them. Their callbacks are named `invokeErrorHandler` and `invokeHandler` (anonymous upstream; lcov rejects their duplicate inferred names). `src/router/index.ts`: `handle()` checks `requestChannel.hasSubscribers` once (`var traced`, after the `restore` line: a `var`, so `next()` and `trimPrefix` read it without a temporal-dead-zone check), and when traced wraps `done` in a second `restore` for `req[matchedRoute]`; when traced, `trimPrefix` sets `req[matchedRoute]` with the new `setMatchedRoute` helper (placed before `mergeParams`) and calls `traceError`/`traceRequest` instead of `handleError`/`handleRequest`; a route's own layer always gets `handleRequest` (`route.dispatch` traces its handlers); when traced, `next()` calls `setMatchedRoute` for a matched route, in the block that sets `req.route` (not in the `processParams` callback, which would make `noSlash` a context variable that the matching loop reads for every layer); `next()` records `err`, and the loop records a matching error, with `recordError`; and `paramCallback` calls `setMatchedRoute` and `traceParam` when there are subscribers. `src/router/lib/route.ts`: `dispatch()` checks once (`var traced`, requiring `requestChannel` from `./tracing`), and its `next()` calls `traceError`/`traceRequest` when traced. How this copy differs from 2.3.0: + - The subscriber check is made once per router and once per route as they start on a request, and picks each layer's traced or untraced method, where 2.3.0 checks inside `handleError` and `handleRequest` before every handler (with the traced call's closure in them) and sets `req[matchedRoute]` in `next()` for every matched layer, and restores it, on every request. Here it is set only while traced, right before the parameter callbacks or the handler run. 2.3.0's way counted 0.5% to 1% more instructions per request with no subscribers (hello +0.48%, mw10 +1.05%), over the 0.3% budget; with the check moved out but the traced path still inside the two methods, mw10 was still +0.43%. A subscriber that attaches during a request is seen from the next router or route the request enters. Keep this when re-syncing. + - The untraced paths are 2.2.0's, unchanged: 2.3.0 rewrote them around a `handlePromise` helper and `callParam`, passing a no-op instead of `null` to a returned promise's `then`, so a broken thenable that calls `then`'s first callback without checking it no longer gets a `TypeError` to `next()`. Here that change only applies while traced (`invokeWithTrace` and `callParam` pass functions, as 2.3.0 does); the re-sync brings it to the untraced path. + - Errors are recorded only while the channel has subscribers (`requestChannel.hasSubscribers` before both `recordError` calls in `index.ts`), so an untraced request gets no `Symbol.for('router.tracing.publishedErrors')` set. 2.3.0 records every error, so a subscriber that attaches while an error is already on its way can't blame a forwarder; here that's covered when the error passes a router or reaches an error handler after the subscriber attached (2.3.0's tests for it pass), and missed only if it did both before. Keep the guards when re-syncing. + - The pattern comes from `layer.rawPath` (`matchedPattern` from `./original-route` for a path array, run only while traced), since `match()` still returns `true` here: 2.3.0's `match()` returns it as `match.pattern` (pillarjs/router#216). After the re-sync, `req[matchedRoute] = match.pattern` replaces it. + ### router tests - `require('..')` changed to `require('../../lib/router')`. - Removed the first-line `const { it, describe } = require('mocha')` from the 7 router test files, so they use the test runner's globals (Vitest). - Added `require('node:buffer')` in `support/utils.js`, `router.js` and `route.js`, for the same lint rule. +- `tracing.js` (from router 2.3.0, with the tracing edit above), with the same two changes, and the copy-loading helper's `require.resolve('..')` changed to `require.resolve('../../lib/router')`. These tests differ: the one that calls an error handler's layer directly calls `traceError` instead of `handleError` (see the tracing edit above); the URL-decoding tests answer with `err.status`, since 2.3.0's `statusCode` on that error (pillarjs/router#171) isn't here yet; and the test that a broken thenable gets no `TypeError` without subscribers now checks that it still does (router 2.2.0's untraced path, see above), while the traced case keeps 2.3.0's test. ### send diff --git a/docs/api/diagnostics.md b/docs/api/diagnostics.md new file mode 100644 index 00000000000..c4ce87d8001 --- /dev/null +++ b/docs/api/diagnostics.md @@ -0,0 +1,170 @@ +--- +title: Diagnostics channels +description: The diagnostics_channel events Express publishes, when each fires, and what it carries. +--- + +# Diagnostics channels + +Express publishes events on Node.js [`diagnostics_channel`](https://nodejs.org/api/diagnostics_channel.html), +so APMs, tracers and loggers can observe an app without patching it. This is a fork addition, not in +Express 5.3.0. + +| Channel | Kind | Fires | Payload | +|---|---|---|---| +| `express.router.request` | [`TracingChannel`](https://nodejs.org/api/diagnostics_channel.html#class-tracingchannel) | for every middleware, route handler, error handler and `app.param()` callback the router runs | [the trace context](#the-trace-context) | +| `express.initialization` | channel | once per `express()` call, sub-apps included, after the app is set up and before it is returned | `{ app }` | + +Nothing is published, and no payload is built, unless the channel has subscribers: with none, each +router and each route checks `hasSubscribers` once as it starts on a request. A subscriber that throws doesn't break the request: +`diagnostics_channel` calls each subscriber in a `try`/`catch` and rethrows its error on the next tick, +as an uncaught exception, while the app answers as it would without it. + +The start and end of the whole request are Node's own channels, `http.server.request.start` and +`http.server.response.finish` (with `request`, `response`, `socket` and `server`), so Express doesn't +publish them again. + +## express.router.request + +The same `TracingChannel`, with the same context, as router 2.3.0 (pillarjs/router#196 and the +releases after it), so a subscriber written for Express 5 with router 2.3.0 works unchanged. Subscribe +with `tracingChannel('express.router.request')`; the channel names are +`tracing:express.router.request:start`, `:end`, `:asyncStart`, `:asyncEnd` and `:error`. + +::: code-group + +```js [index.cjs] +const dc = require('node:diagnostics_channel'); + +dc.tracingChannel('express.router.request').subscribe({ + start(ctx) { + ctx.startTime = process.hrtime.bigint(); + }, + end(ctx) {}, + asyncStart(ctx) {}, + asyncEnd(ctx) {}, + error(ctx) { + console.error('%s failed in %s:', ctx.req.originalUrl, ctx.handler.name || '', ctx.error); + } +}); +``` + +```ts [index.ts] +import dc from 'node:diagnostics_channel'; +import type { RouterTraceContext } from 'express'; + +dc.tracingChannel('express.router.request').subscribe({ + start(ctx) {}, + end(ctx) {}, + asyncStart(ctx) {}, + asyncEnd(ctx) { + console.log('%s %s -> %d', ctx.req.method, ctx.req.originalRoute ?? ctx.req.originalUrl, ctx.res.statusCode); + }, + error(ctx) {} +}); +``` + +::: + +### The events + +Each handler the router runs is one trace, and each trace publishes, on the same context object: + +| Event | When | +|---|---| +| `start` | right before the handler is called. Stores bound with `start.bindStore()` are active while it runs, and in everything it calls, `next()` included. | +| `end` | when the handler returns or throws. For a handler that doesn't return a promise, this is the last event (`result` or `error` is set). | +| `asyncStart` | when the promise the handler returned settles. `result` is set if it resolved. | +| `asyncEnd` | right after `asyncStart`, with the stores bound with `asyncStart.bindStore()` active. | +| `error` | when the handler reports an error: it calls `next(err)`, throws, or its promise rejects. Published as soon as it happens, so `next(err)` publishes it before `end`, and before the error handler it leads to runs. | + +`next()` usually runs the next handler before the current one returns, so traces nest: for +`app.use(logger)` and `app.get('/', show)`, a request publishes `start logger`, `start show`, +`end show`, `end logger`. A promise-returning handler publishes `start`, `end`, then `asyncStart` and +`asyncEnd` once its promise settles. + +What runs is traced: + +- middleware (`app.use(fn)`, `router.use(fn)`), with `route` the path it was mounted with (`'/'` by default); +- each handler of a route (`app.get('/users/:id', a, b)` is two traces), with `route` the route's path; +- error handlers (four arguments), with `errorHandler: true` and the error they received in `incomingError`; +- `app.param()` and `router.param()` callbacks, with `param` the parameter's name and `route` the path of the + route or middleware whose parameter it is. A parameter whose callbacks already ran for the same value is + not traced again; +- a mounted router or sub-app is middleware: its mount is one trace (`layer.name` is `'router'` for a + router and `'mounted_app'` for an app, `route` the mount path), and the handlers inside it are traced + inside it. + +Each router and each route checks for subscribers when it starts on a request, so a subscriber that +attaches while a request is already being routed sees its handlers from the next router or route it +enters. + +What doesn't run isn't traced: a layer whose path doesn't match, a route whose method doesn't, a normal +handler while an error is pending, or an error handler while none is. A request no handler matches (a +404 from an app with no middleware) publishes nothing. + +### The trace context + +| Property | Value | +|---|---| +| `req` | the request, as the handler gets it (`req.baseUrl`, `req.params` and `req.route` are the handler's). | +| `res` | the response. | +| `handler` | the function called: the middleware, route handler, error handler, or the `app.param()` callback. | +| `layer` | the router's layer for it (`layer.name` is the handler's name, or `''`). For a parameter callback, the layer of the route or middleware whose parameter it is. The layer is internal: its other properties may change between releases, so read them defensively. | +| `route` | the path pattern that matched: `'/users/:id'` for a route handler, the mount path for middleware, a router or a sub-app. For a path array, the entry that matched; for a RegExp path, the RegExp. Each pattern is relative to the router it was registered on; `req.originalRoute` (a fork addition) is the whole pattern, mount paths included, such as `'/api/users/:id'`, for an OpenTelemetry `http.route`. | +| `param` | the parameter's name (`'id'`), for `app.param()` callbacks only. | +| `errorHandler` | `true` for error handlers, absent otherwise. | +| `incomingError` | the error an error handler received, for error handlers only. | +| `error` | the error the handler reported: set before the `error` event, and present at the trace's last event (`end`, or `asyncEnd` for a promise) when it failed. A throw or a rejection always sets it, even for an error already reported upstream. | +| `result` | what the handler returned (before `end`), or what its promise resolved to (before `asyncStart`). Not set when it threw or rejected. | + +Subscribers may add their own properties (a span, a start time): every event of one trace gets the +same object. + +### Errors + +The `error` event is published once per error, by the handler where it starts: a handler that calls +`next(err)`, throws, or rejects. An error passed on by routers, sub-apps and error handlers that +forward it (`next(err)` with the error they got, or rethrowing it) isn't published again, but a throw or +rejection still sets `error` on that handler's own context. An error handler that passes on a +different error starts a new one, which is published. An error raised while matching, such as a +parameter that can't be decoded (`/users/%ZZ`), is not blamed on the handlers that forward it: it +reaches the error handlers' `incomingError` only. + +`next('route')` and `next('router')` (or throwing those strings) are not errors. + +| Request | Events | +|---|---| +| `boom` throws, `recover(err, req, res, next)` answers | `start boom`, `error boom`, `start recover`, `end recover`, `end boom` | +| `fail` calls `next(err)`, `recover` answers | `start fail`, `error fail`, `start recover`, `end recover`, `end fail` | +| async `reject` rejects, `recover` answers | `start reject`, `end reject`, `error reject`, `start recover`, `end recover`, `asyncStart reject`, `asyncEnd reject` | +| a route in a nested router calls `next(err)`, nothing handles it | `error` once, for that handler; Express's final handler answers 500 | + +## express.initialization + +Published with `{ app }` by every `express()` call, sub-apps included, once the app's settings and +router are set up and before `express()` returns, so instrumentation can reach an app before any +request does. The counterpart of Fastify's `fastify.initialization`. + +::: code-group + +```js [index.cjs] +const dc = require('node:diagnostics_channel'); + +dc.subscribe('express.initialization', ({ app }) => { + app.disable('x-powered-by'); +}); +``` + +```ts [index.ts] +import dc from 'node:diagnostics_channel'; +import type { InitializationMessage } from 'express'; + +dc.subscribe('express.initialization', (message) => { + const { app } = message as InitializationMessage; + app.disable('x-powered-by'); +}); +``` + +::: + +Subscribe before the app is created: an app created earlier isn't published again. diff --git a/docs/api/index.md b/docs/api/index.md index 1e41830b450..71af406f44a 100644 --- a/docs/api/index.md +++ b/docs/api/index.md @@ -60,3 +60,4 @@ With express v5.x, you can define routes, configure middleware, and start handli - [Response object](/api/response): the properties and methods of the Express 5.x response object. - [Router](/api/router): the properties and methods of the Express 5.x router. - [Error codes](/api/errors): the `code` on every error Express creates, and when each one is raised (a fork addition). +- [Diagnostics channels](/api/diagnostics): the `diagnostics_channel` events Express publishes for tracing and monitoring tools, and what each one carries (a fork addition). diff --git a/docs/fork/differences.md b/docs/fork/differences.md index 081a52f3947..c32ddf06d64 100644 --- a/docs/fork/differences.md +++ b/docs/fork/differences.md @@ -58,6 +58,7 @@ Opt-in: an app that doesn't use them behaves as on Express 5.3.0. - **`req.signal`.** An `AbortSignal` that aborts when the client goes away before the response has finished, for `fetch`, database drivers and timers. It is made on first read, never aborts after a finished response, and behaves the same on Node.js 22, 24 and 26, where Node's own `IncomingMessage#signal` is missing (22) or, before 24.20 and 26.7, also aborts after a finished response. See [req.signal](/api/request#reqsignal). - **`app.error()` and `router.error()`.** Add error handlers, with an optional path as `app.use()` takes, that run only for an error, whatever the number of parameters the function declares. A handler without `next`, or one that a wrapper, `bind`, a default or rest parameter, a compiler or a minifier gave a `length` other than 4, no longer turns into a normal middleware. Error handlers of four parameters added with `app.use()` work as before. In TypeScript, `router.error()` is on what `express.Router()` returns (`RouterWithErrorHandlers`), not on the `Router` type, which stays as it was. See [app.error()](/api/application#apperror). - **Error codes.** Every error Express creates has a stable `code`, such as `EXPRESS_ERR_VIEW_NOT_FOUND`, so error handlers can branch on it instead of on the message. The property isn't enumerable, so serialised and logged errors look as on Express 5.3.0, and errors that already had a code (`ENOENT`, `ERR_HTTP_HEADERS_SENT`) keep it. See [Error codes](/api/errors). +- **Diagnostics channels.** Every middleware, route handler, error handler and `app.param()` callback is traced through the `express.router.request` `TracingChannel` (start, end, asyncStart, asyncEnd and error, with `req`, `res`, the handler, the matched pattern and the error), the same channel and payload as router 2.3.0, so APM subscribers written for it work unchanged; `express()` publishes `{ app }` on `express.initialization`. Nothing runs without subscribers. See [Diagnostics channels](/api/diagnostics). ## Tests that guard the drop-in promise diff --git a/src/express.ts b/src/express.ts index ead791dfcae..ee4206beda3 100644 --- a/src/express.ts +++ b/src/express.ts @@ -29,6 +29,17 @@ const Router = require('./router') as RouterConstructor const req = require('./request') as Request const res = require('./response') as ExpressResponse const { originalRoute } = require('./router/lib/original-route') as typeof import('./router/lib/original-route') +const dc = require('node:diagnostics_channel') as typeof import('node:diagnostics_channel') + +/** + * Published with `{ app }` by every `express()` call, once the app is set up + * and before it is returned, so instrumentation can reach an app before any + * request does. Not in Express 5.3.0: ported from expressjs/express#7041 by + * DemianParkhomenko (open), the counterpart of Fastify's + * `fastify.initialization`. + */ + +const initializationChannel = dc.channel('express.initialization') /** * Not in Express 5.3.0: the methods the fork adds to every app. They are kept @@ -82,6 +93,11 @@ function createApplication(): Application { }) app.init() + + if (initializationChannel.hasSubscribers) { + initializationChannel.publish({ app }) + } + return app } diff --git a/src/router/index.ts b/src/router/index.ts index 26c0e746df8..b25c163d092 100644 --- a/src/router/index.ts +++ b/src/router/index.ts @@ -23,9 +23,12 @@ const parseUrl = require('parseurl') as typeof import('parseurl') const Route = require('./lib/route') as RouteConstructor const symbols = require('./lib/symbols') as typeof import('./lib/symbols') const { checkPath, trackRoute } = require('./lib/warnings') as typeof import('./lib/warnings') +const { recordError, requestChannel, traceParam } = require('./lib/tracing') as typeof import('./lib/tracing') +const { matchedPattern } = require('./lib/original-route') as typeof import('./lib/original-route') const { withCode } = require('../error-code') as typeof import('../error-code') const mountMatch: typeof symbols.mountMatch = symbols.mountMatch const routeMatch: typeof symbols.routeMatch = symbols.routeMatch +const matchedRoute: typeof symbols.matchedRoute = symbols.matchedRoute const debug = (require('debug') as typeof import('debug'))('router') const deprecate = (require('depd') as typeof import('depd'))('router') @@ -292,6 +295,14 @@ proto.handle = function handleRequest(req, res, callback) { const parentUrl = req.baseUrl || '' let done = restore(callback, req, 'baseUrl', 'next', 'params') + // Not in router 2.2.0 or 2.3.0: whether the tracing channel (lib/tracing) + // has subscribers, checked once here rather than for every layer. Only a + // traced router keeps the matched pattern, so only it restores it (2.3.0 + // always restores it, with baseUrl, next and params). + // `var`, so the closures below read it without a temporal-dead-zone check + var traced = requestChannel.hasSubscribers + if (traced) done = restore(done, req as RouterRequest & MatchedRequest, matchedRoute) + // setup next layer req.next = next @@ -310,6 +321,12 @@ proto.handle = function handleRequest(req, res, callback) { function next(err?: unknown): void | NodeJS.Immediate { let layerError = err === 'route' ? null : err + // Router 2.3.0 (tracing): the error has already left its originating + // callback. Remember it even when that callback was not traced, so + // enclosing routers cannot claim it. Not in 2.3.0: only while the channel + // has subscribers, so an untraced request gets nothing new. + if (err && requestChannel.hasSubscribers) recordError(req, err) + // remove added slash if (slashAdded) { req.url = req.url.slice(1) @@ -373,6 +390,11 @@ proto.handle = function handleRequest(req, res, callback) { route = layer.route if (typeof match !== 'boolean') { + // Router 2.3.0 (tracing): matching can fail before a handler runs (for + // example, URI decoding). Forwarding that error must not attribute it + // to a later handler. Only while traced, as above. + if (requestChannel.hasSubscribers) recordError(req, match) + // hold on to layerError layerError = layerError || match } @@ -424,6 +446,12 @@ proto.handle = function handleRequest(req, res, callback) { noSlash, parent: (req as RouterRequest & MatchedRequest)[mountMatch] } + + // Router 2.3.0 (tracing): the route's pattern, for its parameter + // callbacks and handlers (see setMatchedRoute). Here, not in the + // callback below, which would make noSlash a context variable that the + // matching loop reads on every layer. + if (traced) setMatchedRoute(req, layer, path, noSlash) } // Capture one-time layer values @@ -435,6 +463,7 @@ proto.handle = function handleRequest(req, res, callback) { if (err) { next(layerError || err) } else if (route) { + // a route's own layer: route.dispatch traces its handlers layer.handleRequest(req, res, next) } else { trimPrefix(layer, layerError, layerPath, path) @@ -492,7 +521,13 @@ proto.handle = function handleRequest(req, res, callback) { debug('%s %s : %s', layer.name, layerPath, req.originalUrl) - if (layerError) { + // Not in router 2.2.0 or 2.3.0: traced, the layer's tracing methods run + // it, with its pattern (see setMatchedRoute) + if (traced) { + setMatchedRoute(req, layer, path, false) + if (layerError) layer.traceError(layerError, req, res, next) + else layer.traceRequest(req, res, next) + } else if (layerError) { layer.handleError(layerError, req, res, next) } else { layer.handleRequest(req, res, next) @@ -737,6 +772,23 @@ function matchLayer(layer: LayerInstance, path: string): unknown { } } +/** + * Router 2.3.0's `req[matchedRoute] = match.pattern` (tracing): the pattern + * the layer matched with, which the tracing context reports as `route`. Not + * in 2.3.0: set only while traced, right before the layer's parameter + * callbacks or handler run (2.3.0 sets it in next() for every matched layer), + * and taken from `rawPath`, since match() returns true here, not a match + * object (pillarjs/router#216). + * + * @private + */ + +function setMatchedRoute(req: RouterRequest, layer: LayerInstance, path: string, noSlash: boolean | undefined) { + ;(req as RouterRequest & MatchedRequest)[matchedRoute] = Array.isArray(layer.rawPath) + ? matchedPattern(layer, path, noSlash) + : layer.rawPath +} + /** * Merge params with parent params * @@ -896,6 +948,29 @@ function processParams( if (!fn) return nextParam() + // Not in router 2.2.0: router 2.3.0's tracing (lib/tracing), only while + // the channel has subscribers + if (requestChannel.hasSubscribers) { + // the pattern of the layer whose parameter it is (the path of a route's + // "" entry has no parameters, so noSlash can't apply) + setMatchedRoute(req, layer, getPathname(req) as string, false) + traceParam( + fn, + { + req, + res, + layer, + handler: fn, + route: (req as RouterRequest & MatchedRequest)[matchedRoute], + param: key + }, + paramCallback, + paramVal, + key + ) + return + } + try { const ret = fn(req, res, paramCallback, paramVal, key) if (isPromise(ret)) { diff --git a/src/router/lib/layer.ts b/src/router/lib/layer.ts index 5a95fe7a313..08f45f84a23 100644 --- a/src/router/lib/layer.ts +++ b/src/router/lib/layer.ts @@ -20,11 +20,17 @@ const pathRegexp = require('path-to-regexp') as typeof import('path-to-regexp') const debug = (require('debug') as typeof import('debug'))('router:layer') const deprecate = (require('depd') as typeof import('depd'))('router') const { withCode } = require('../../error-code') as typeof import('../../error-code') +const symbols = require('./symbols') as typeof import('./symbols') +const { publishEnd, recordThrown, requestChannel, traceAsyncEnd, wrapNext } = + require('./tracing') as typeof import('./tracing') +const matchedRoute: typeof symbols.matchedRoute = symbols.matchedRoute import type { MatchFunction, MatchOptions, ParamData } from 'path-to-regexp' import type { Request } from '../../request' import type { ExpressResponse } from '../../response' import type { Route } from './route' +import type { MatchedRequest } from './symbols' +import type { TraceContext } from './tracing' /** Call it to pass control on, or with an error (or `'route'`, `'router'`) to skip ahead. */ export type NextFunction = (err?: unknown) => void @@ -66,6 +72,8 @@ export interface Layer { errorOnly: boolean // registered with error(): an error handler whatever its length (false on the prototype) handleError(error: unknown, req: RouterRequest, res: RouterResponse, next: NextFunction): void handleRequest(req: RouterRequest, res: RouterResponse, next: NextFunction): void + traceError(error: unknown, req: RouterRequest, res: RouterResponse, next: NextFunction): void + traceRequest(req: RouterRequest, res: RouterResponse, next: NextFunction): void match(path: string | null | undefined): boolean } @@ -257,6 +265,139 @@ proto.handleRequest = function handleRequest(req, res, next) { } } +/** + * Not in router 2.2.0: handleError and handleRequest traced through router + * 2.3.0's request TracingChannel (lib/tracing). The router and the route call + * these instead when the channel has subscribers, which they check once as + * they start on a request. Router 2.3.0 has the traced path inside + * handleError and handleRequest, behind a subscriber check before every + * handler; here those two stay as in 2.2.0. A route's own layer only calls + * route.dispatch, which traces the route's handlers one by one, so the router + * always calls its handleRequest, never traceRequest. + * + * @api private + */ + +proto.traceError = function traceError(error, req, res, next) { + const fn = this.handle as ErrorRequestHandler + + if (fn.length !== 4 && !this.errorOnly) { + // not a standard error handler + return next(error) + } + + invokeWithTrace( + function invokeErrorHandler(wrappedNext) { + return fn(error, req, res, wrappedNext) + }, + { + req, + res, + incomingError: error, + layer: this, + handler: fn, + route: (req as RouterRequest & MatchedRequest)[matchedRoute], + errorHandler: true + }, + next + ) +} + +proto.traceRequest = function traceRequest(req, res, next) { + const fn = this.handle as RequestHandler + + if (fn.length > 3 || this.errorOnly) { + // not a standard request handler + return next() + } + + invokeWithTrace( + function invokeHandler(wrappedNext) { + return fn(req, res, wrappedNext) + }, + { + req, + res, + layer: this, + handler: fn, + route: (req as RouterRequest & MatchedRequest)[matchedRoute] + }, + next + ) +} + +/** + * Invoke a handler wrapped in the request TracingChannel. Only called when the + * channel has subscribers, so ctx is always present. Router 2.3.0's, with the + * promise check written out as in the untraced path above (2.3.0 moved it to + * a `handlePromise` helper that both paths share). + * @private + */ + +function invokeWithTrace(exec: (next: NextFunction) => unknown, ctx: TraceContext, next: NextFunction): void { + const wrappedNext = wrapNext(ctx, next) + let settled = false + + // runStores fires `start` and sets the async context. Synchronous layers + // emit only start/end. All outcomes flow through wrappedNext to keep signal + // filtering and dedup in one place. + requestChannel.start.runStores(ctx, function () { + let out: PromiseLike | undefined + try { + const ret = exec(wrappedNext) + if (isPromise(ret)) { + if (!(ret instanceof Promise)) { + deprecate('handlers that are Promise-like are deprecated, use a native Promise instead') + } + out = ret + } else { + // Same as tracePromise, a promise only gets its result once it resolves + ctx.result = ret + } + } catch (err) { + // A sync throw is forwarded verbatim, so a falsy value keeps routing + // exactly as the untraced path does. + wrappedNext(err) + recordThrown(ctx, err, true) + publishEnd(ctx, false) + return + } + + publishEnd(ctx, out !== undefined) + if (out === undefined) return + + try { + out.then( + function (value) { + // Same as tracePromise, only the first outcome settles the trace + if (settled) return + settled = true + ctx.result = value + traceAsyncEnd(ctx) + }, + function (err: unknown) { + // A rejected promise is an error even when the reason is falsy; + // normalize it to the error the router forwards to next(). + rejected(err || withCode(new Error('Rejected promise'), 'EXPRESS_ERR_REJECTED_PROMISE')) + } + ) + } catch (err) { + // Same as tracePromise, a `then` that throws is a rejection, forwarded + // verbatim as the untraced path does + rejected(err) + } + }) + + function rejected(err: unknown) { + // Routing still gets every outcome, as the untraced path does + wrappedNext(err) + if (settled) return + settled = true + recordThrown(ctx, err, false) + traceAsyncEnd(ctx) + } +} + /** * Check if this route matches `path`, if so * populate `.params`. diff --git a/src/router/lib/original-route.ts b/src/router/lib/original-route.ts index ae620ca0c3c..f4fed31425b 100644 --- a/src/router/lib/original-route.ts +++ b/src/router/lib/original-route.ts @@ -16,7 +16,7 @@ */ import type { MatchFunction } from 'path-to-regexp' -import type { Params, RouterRequest } from './layer' +import type { Layer, Params, RouterRequest } from './layer' import type { MatchedRequest, MatchRecord } from './symbols' const symbols = require('./symbols') as typeof import('./symbols') @@ -40,7 +40,7 @@ export function originalRoute(req: RouterRequest): string | undefined { let path = '' for (let m: MatchRecord | undefined = route; m !== undefined; m = m.parent) { - const pattern = matchedPattern(m) + const pattern = matchedPattern(m.layer, m.path, m.noSlash) if (typeof pattern !== 'string') { return undefined @@ -54,20 +54,21 @@ export function originalRoute(req: RouterRequest): string | undefined { } /** - * The pattern the record's layer matched with: its path, or for a path array - * the first entry that matches what the layer matched, tried in the order the - * router tried them ("" first for a strict router's route, see `noSlash`). + * The pattern a layer matched `path` with: its path, or for a path array the + * first entry that matches, tried in the order the router tried them ("" + * first for a strict router's route, see `noSlash`). The tracing context's + * `route` uses it too. */ -function matchedPattern(m: MatchRecord): string | RegExp | undefined { - const rawPath = m.layer.rawPath +export function matchedPattern(layer: Layer, path: string, noSlash: boolean | undefined): string | RegExp | undefined { + const rawPath = layer.rawPath if (!Array.isArray(rawPath)) { return rawPath } - const matchers = m.layer.rawMatchers + const matchers = layer.rawMatchers - return (m.noSlash ? firstMatch(rawPath, matchers, '') : undefined) ?? firstMatch(rawPath, matchers, m.path) + return (noSlash ? firstMatch(rawPath, matchers, '') : undefined) ?? firstMatch(rawPath, matchers, path) } function firstMatch( diff --git a/src/router/lib/route.ts b/src/router/lib/route.ts index c3780e29304..1ab2c35147c 100644 --- a/src/router/lib/route.ts +++ b/src/router/lib/route.ts @@ -20,6 +20,7 @@ const Layer = require('./layer') as LayerConstructor const { METHODS } = require('node:http') as typeof import('node:http') const { methodAdded } = require('./warnings') as typeof import('./warnings') const { withCode } = require('../../error-code') as typeof import('../../error-code') +const { requestChannel } = require('./tracing') as typeof import('./tracing') import type { Layer as LayerInstance, @@ -194,6 +195,12 @@ proto.dispatch = function dispatch(req, res, done) { req.route = this + // Not in router 2.2.0 or 2.3.0: whether the tracing channel (./tracing) has + // subscribers, checked once per dispatch, which picks each layer's traced + // or untraced method + // `var`, so the closures below read it without a temporal-dead-zone check + var traced = requestChannel.hasSubscribers + next() function next(err?: unknown): void | NodeJS.Immediate { @@ -232,7 +239,10 @@ proto.dispatch = function dispatch(req, res, done) { } if (err) { - layer.handleError(err, req, res, next) + if (traced) layer.traceError(err, req, res, next) + else layer.handleError(err, req, res, next) + } else if (traced) { + layer.traceRequest(req, res, next) } else { layer.handleRequest(req, res, next) } diff --git a/src/router/lib/symbols.ts b/src/router/lib/symbols.ts index 7f084d8f133..e6a13d62a3b 100644 --- a/src/router/lib/symbols.ts +++ b/src/router/lib/symbols.ts @@ -9,9 +9,10 @@ /** * Not in router 2.2.0. Router 2.3.0 adds a file of this name for its own - * request symbol (`matchedRoute`); the re-sync adds it here. These two are - * ours: what the routers record on the request so `req.originalRoute` - * (`./original-route`) can be built when it is read, never while routing. + * request symbol, `matchedRoute`, which is ported here with its tracing + * (`./tracing`). The other two are ours: what the routers record on the + * request so `req.originalRoute` (`./original-route`) can be built when it is + * read, never while routing. * @private */ @@ -34,8 +35,15 @@ export const mountMatch: unique symbol = Symbol('router.mountMatch') /** The route layer that set `req.route`, kept as long as `req.route` is. */ export const routeMatch: unique symbol = Symbol('router.routeMatch') -/** The request, with the two records. */ +/** + * Router 2.3.0's symbol (pillarjs/router#207): the pattern the layer being run + * matched with, which the tracing context (`./tracing`) reports as `route`. + */ +export const matchedRoute: unique symbol = Symbol('router.tracing.matchedRoute') + +/** The request, with the two records and the matched pattern. */ export interface MatchedRequest { [mountMatch]?: MatchRecord | undefined [routeMatch]?: MatchRecord | undefined + [matchedRoute]?: string | RegExp | undefined } diff --git a/src/router/lib/tracing.ts b/src/router/lib/tracing.ts new file mode 100644 index 00000000000..ee06f9521e2 --- /dev/null +++ b/src/router/lib/tracing.ts @@ -0,0 +1,270 @@ +/*! + * router + * MIT Licensed + */ + +'use strict' + +/** + * Not in router 2.2.0: router 2.3.0's `diagnostics_channel` tracing + * (pillarjs/router#196, #207 and #223 by logaretm, #215 by bjohansebas), from + * its lib/tracing.js and lib/param.js. Every middleware, route handler, error + * handler and `router.param()` callback the router runs is traced through the + * `express.router.request` TracingChannel, the same channel and context as + * router 2.3.0, so a subscriber written for Express with router 2.3.0 works + * here unchanged. Nothing here runs unless the channel has subscribers. + * @private + */ + +import type { ErrorRequestHandler, Layer, NextFunction, RequestHandler, RouterRequest, RouterResponse } from './layer' + +/** + * Module dependencies. + * + * Loaded with `require` and typed with `typeof import(...)`, so the compiled + * output calls them directly, with no interop helpers in between. + * @private + */ + +const dc = require('node:diagnostics_channel') as typeof import('node:diagnostics_channel') +const isPromise = require('is-promise') as typeof import('is-promise').default +const deprecate = (require('depd') as typeof import('depd'))('router') +const { withCode } = require('../../error-code') as typeof import('../../error-code') + +/** A `router.param()` callback, as `index` declares it (`ParamCallback`). */ +export type ParamHandler = ( + req: RouterRequest, + res: RouterResponse, + next: NextFunction, + value: string | string[], + name: string +) => unknown + +/** What every event of the `express.router.request` TracingChannel publishes. */ +export interface TraceContext { + req: RouterRequest + res: RouterResponse + /** The router's layer (internal: its shape may change between releases). */ + layer: Layer + /** The function invoked: the handler, or the `router.param()` callback. */ + handler: RequestHandler | ErrorRequestHandler | ParamHandler + /** The pattern that matched: the route's path, or the path a middleware or router was mounted with. */ + route: string | RegExp | undefined + /** The parameter's name, for `router.param()` callbacks only. */ + param?: string + /** The error the invocation reported (`next(err)`, a throw or a rejection). */ + error?: unknown + /** The error an error handler received. */ + incomingError?: unknown + /** `true` for error handlers (four arguments). */ + errorHandler?: true + /** What the invocation returned, or what its promise resolved to. */ + result?: unknown +} + +/** The request, with the errors already published for it. */ +interface TracedRequest { + [seenErrors]?: Set +} + +/** + * Module variables. + * @private + */ + +export const requestChannel = dc.tracingChannel('express.router.request') + +// Share error identity tracking across callbacks and router boundaries. Keep +// the registered symbol compatible with separately installed copies of router. +const seenErrors: unique symbol = Symbol.for('router.tracing.publishedErrors') as never + +// Remember errors already observed, including those from untraced code or +// route matching. Only the first report from a traced invocation is published. +export function recordError(req: RouterRequest, err: unknown): boolean { + if (!err || isRoutingSignal(err)) return false + + let seen = (req as RouterRequest & TracedRequest)[seenErrors] + if (!seen) { + seen = (req as RouterRequest & TracedRequest)[seenErrors] = new Set() + } else if (seen.has(err)) { + return false + } + seen.add(err) + return true +} + +/** + * `'route'` and `'router'` are routing signals, not errors. + */ +function isRoutingSignal(err: unknown): boolean { + return err === 'route' || err === 'router' +} + +/** + * Record a throw or rejection on the context. A rethrown error isn't published + * again, but the terminal event still needs it. A routing signal isn't an + * error, so a sync one finishes like calling next('route') and returning. + */ +export function recordThrown(ctx: TraceContext, err: unknown, sync: boolean): void { + if (isRoutingSignal(err)) { + if (sync) ctx.result = undefined + + return + } + if (!('error' in ctx)) ctx.error = err +} + +/** + * Forget an error an error handler has dealt with, so a later report of the + * same object is published again. + */ +function forgetError(req: RouterRequest, err: unknown): void { + const seen = (req as RouterRequest & TracedRequest)[seenErrors] + if (seen) seen.delete(err) +} + +export function wrapNext(ctx: TraceContext, next: NextFunction): NextFunction { + // An error received by an error handler did not originate there, even if + // tracing was disabled at its origin. A replacement error is still reported. + if (ctx.errorHandler) recordError(ctx.req, ctx.incomingError) + + return function wrappedNext(err) { + // An error handler that recovers or replaces the error has handled it, so + // the same object reported later in the request is a new failure. + if (ctx.errorHandler && err !== ctx.incomingError) forgetError(ctx.req, ctx.incomingError) + // Routing signals aren't errors. Report a real error once, at its origin, + // before forwarding it to another callback, layer or enclosing router. + if (err && recordError(ctx.req, err)) { + ctx.error = err + requestChannel.error.publish(ctx) + } + next(err) + } +} + +// An error reported before a promise is returned is published before `end`, so +// it's hidden during `end` to keep `result` or `error` there meaning done. +export function publishEnd(ctx: TraceContext, async: boolean): void { + if (!async || !('error' in ctx)) return requestChannel.end.publish(ctx) + + const error = ctx.error + delete ctx.error + requestChannel.end.publish(ctx) + ctx.error = error +} + +export function traceAsyncEnd(ctx: TraceContext): void { + // Scope completion to asyncStart's bound stores without scheduling more work. + requestChannel.asyncStart.runStores(ctx, publishAsyncEnd, null, ctx) +} + +function publishAsyncEnd(ctx: TraceContext): void { + requestChannel.asyncEnd.publish(ctx) +} + +// Wrap the shared parameter invocation with its tracing context and lifecycle. +export function traceParam( + fn: ParamHandler, + ctx: TraceContext, + next: NextFunction, + value: string | string[], + name: string +): void { + const wrappedNext = wrapNext(ctx, next) + let async = false + let ended = false + let settled = false + let early: (() => void) | undefined + + requestChannel.start.runStores(ctx, function () { + try { + callParam(invoke, ctx.req, ctx.res, wrappedNext, value, name, settle) + } finally { + publishEnd(ctx, async) + ended = true + if (early) early() + } + }) + + // Same as layers, a throw skips the assignment so no result is set + function invoke( + req: RouterRequest, + res: RouterResponse, + next: NextFunction, + value: string | string[], + name: string + ): unknown { + let ret: unknown + try { + ret = fn(req, res, next, value, name) + } catch (err) { + recordThrown(ctx, err, true) + throw err + } + async = isPromise(ret) + if (!async) ctx.result = ret + + return ret + } + + function settle(value: unknown, rejected?: boolean): void { + // Same as tracePromise, only the first outcome settles the trace + if (settled) return + settled = true + // Same as layers, a thenable that settles synchronously still settles after `end` + if (!ended) { + early = function () { + finish(value, rejected) + } + + return + } + finish(value, rejected) + } + + function finish(value: unknown, rejected: boolean | undefined): void { + if (!rejected) ctx.result = value + else recordThrown(ctx, value, false) + traceAsyncEnd(ctx) + } +} + +// router 2.3.0's lib/param.js, which the untraced path shares there. Here +// only the traced path uses it, so the untraced path in index stays as in +// router 2.2.0. A resolved promise may notify tracing, but does not call +// next(). onSettle gets the resolved value, or (reason, true) if the promise +// rejected. +function callParam( + fn: ParamHandler, + req: RouterRequest, + res: RouterResponse, + next: NextFunction, + value: string | string[], + name: string, + onSettle: (value: unknown, rejected?: boolean) => void +): void { + try { + const ret = fn(req, res, next, value, name) + if (isPromise(ret)) { + if (!(ret instanceof Promise)) { + deprecate('parameters that are Promise-like are deprecated, use a native Promise instead') + } + + try { + ret.then(onSettle, function (err: unknown) { + rejected(err || withCode(new Error('Rejected promise'), 'EXPRESS_ERR_REJECTED_PROMISE')) + }) + } catch (err) { + // A `then` that throws is a rejection, forwarded verbatim as before + rejected(err) + } + } + } catch (err) { + next(err) + } + + function rejected(err: unknown): void { + next(err) + onSettle(err, true) + } +} diff --git a/test/fixtures/diagnostics-throwing.js b/test/fixtures/diagnostics-throwing.js new file mode 100644 index 00000000000..6b82cf1880a --- /dev/null +++ b/test/fixtures/diagnostics-throwing.js @@ -0,0 +1,101 @@ +'use strict' + +// Run by test/fork-diagnostics-channel.js: `node diagnostics-throwing.js none` +// or `... throwing`. With `throwing`, every diagnostics_channel subscriber +// Express can reach throws, and so does a store bound on `start`. Prints the +// handlers that ran, the responses and the uncaught exceptions as JSON. + +var { AsyncLocalStorage } = require('node:async_hooks') +var dc = require('node:diagnostics_channel') +var http = require('node:http') +var express = require('../../') + +var uncaught = [] +var calls = [] + +process.on('uncaughtException', function (err) { + uncaught.push(err.message) +}) + +if (process.argv[2] === 'throwing') { + var channel = dc.tracingChannel('express.router.request') + var handlers = {} + ;['start', 'end', 'asyncStart', 'asyncEnd', 'error'].forEach(function (phase) { + handlers[phase] = function () { + throw new Error('subscriber ' + phase) + } + }) + channel.subscribe(handlers) + channel.start.bindStore(new AsyncLocalStorage(), function () { + throw new Error('subscriber store') + }) + dc.subscribe('express.initialization', function () { + throw new Error('subscriber initialization') + }) +} + +var app = express() +var api = express.Router() + +app.param('id', function loadId(req, res, next) { + calls.push('param') + next() +}) +app.use(function first(req, res, next) { + calls.push('first') + next() +}) +api.get('/:id', async function item(req, res, next) { + calls.push('item') + await null + next(new Error('item failed')) +}) +api.use(function apiRecover(err, req, res, next) { + calls.push('apiRecover') + res.status(503).send(err.message) +}) +app.use('/api', api) +app.get('/ok', async function ok(req, res) { + calls.push('ok') + await null + res.send('fine') +}) +app.get('/throw', function thrower() { + calls.push('thrower') + throw new Error('thrown') +}) +// Express's final handler would print the stack, whose frames differ when +// traced (the tracing calls sit between the router and the handler) +app.use(function last(err, req, res, next) { + calls.push('last') + res.status(500).send(err.message) +}) + +var server = app.listen(0, '127.0.0.1', async function () { + var results = [] + for (var url of ['/api/9', '/ok', '/throw', '/missing']) { + results.push(await get(url)) + } + server.close() + // let the last rethrown subscriber errors arrive + setImmediate(function () { + process.stdout.write(JSON.stringify({ calls: calls, results: results, uncaught: uncaught })) + }) +}) + +function get(url) { + return new Promise(function (resolve, reject) { + http + .get({ host: '127.0.0.1', port: server.address().port, path: url, agent: false }, function (res) { + var body = '' + res.setEncoding('utf8') + res.on('data', function (chunk) { + body += chunk + }) + res.on('end', function () { + resolve([url, res.statusCode, res.headers['content-type'], body]) + }) + }) + .on('error', reject) + }) +} diff --git a/test/fork-diagnostics-channel.js b/test/fork-diagnostics-channel.js new file mode 100644 index 00000000000..9a3a10e5cc3 --- /dev/null +++ b/test/fork-diagnostics-channel.js @@ -0,0 +1,699 @@ +'use strict' + +// Not in Express 5.3.0: the `diagnostics_channel` events (ROADMAP.md, +// "Additions on the compatible line"). Every handler the router runs is +// traced through the `express.router.request` TracingChannel, ported from +// router 2.3.0 (pillarjs/router#196, #207, #215, #223; the router's own tests +// are in test/router/tracing.js), and `express()` publishes `{ app }` on +// `express.initialization` (expressjs/express#7041). These tests drive them +// through Express apps, and check that nothing runs or changes without +// subscribers, or with subscribers that throw. + +var assert = require('node:assert') +var { AsyncLocalStorage } = require('node:async_hooks') +var { execFileSync } = require('node:child_process') +var dc = require('node:diagnostics_channel') +var path = require('node:path') +var express = require('../') +var request = require('supertest') + +var CHANNEL = 'express.router.request' +var PHASES = ['start', 'end', 'asyncStart', 'asyncEnd', 'error'] + +describe('fork: diagnostics_channel', function () { + var events + var handlers + + // Subscribes to every phase, recording what each event carried when it was + // published (the context is one object that later events change). + function subscribe() { + events = [] + handlers = {} + PHASES.forEach(function (phase) { + handlers[phase] = function (ctx) { + events.push({ + phase: phase, + name: ctx.handler.name, + layer: ctx.layer.name, + route: ctx.route, + baseUrl: ctx.req.baseUrl, + reqRoute: ctx.req.route && ctx.req.route.path, + param: ctx.param, + errorHandler: ctx.errorHandler, + error: 'error' in ctx ? message(ctx.error) : undefined, + incomingError: 'incomingError' in ctx ? message(ctx.incomingError) : undefined, + result: ctx.result, + ctx: ctx + }) + } + }) + dc.tracingChannel(CHANNEL).subscribe(handlers) + } + + function message(err) { + return err instanceof Error ? err.message : err + } + + // "phase name" for each event, for checking the order. + function sequence() { + return events.map(function (e) { + return e.phase + ' ' + e.name + }) + } + + afterEach(function () { + if (handlers) dc.tracingChannel(CHANNEL).unsubscribe(handlers) + handlers = undefined + }) + + describe('express.router.request', function () { + it('should trace sync middleware and route handlers in order, with req, res and the pattern', async function () { + var app = express() + var seen + + app.use(function logger(req, res, next) { + seen = req + next() + }) + app.get('/users/:id', function show(req, res) { + res.send('user ' + req.params.id) + }) + + subscribe() + await request(app).get('/users/42').expect(200, 'user 42') + + assert.deepStrictEqual(sequence(), ['start logger', 'start show', 'end show', 'end logger']) + var logger = events[0] + var show = events[1] + assert.strictEqual(logger.ctx.req, seen) + assert.strictEqual(logger.ctx.req.app, app) + assert.strictEqual(logger.ctx.res, seen.res) + assert.strictEqual(logger.route, '/') + assert.strictEqual(logger.layer, 'logger') + assert.strictEqual(logger.reqRoute, undefined) + assert.strictEqual(show.route, '/users/:id') + assert.strictEqual(show.reqRoute, '/users/:id') + assert.strictEqual(show.ctx.handler, app.router.stack[1].route.stack[0].handle) + assert.strictEqual(events[2].result, undefined) + assert.ok('result' in events[2].ctx) + assert.strictEqual(logger.ctx.errorHandler, undefined) + assert.ok(!('error' in show.ctx)) + }) + + it('should trace a promise-returning handler through asyncStart and asyncEnd', async function () { + var app = express() + + app.get('/', async function show(req, res) { + await null + res.send('ok') + return 'done' + }) + + subscribe() + await request(app).get('/').expect(200, 'ok') + + assert.deepStrictEqual(sequence(), ['start show', 'end show', 'asyncStart show', 'asyncEnd show']) + assert.strictEqual(events[1].result, undefined) + assert.strictEqual(events[3].result, 'done') + }) + + it('should keep a store bound on start through an async handler', async function () { + var app = express() + var store = new AsyncLocalStorage() + var channel = dc.tracingChannel(CHANNEL) + var inside + + function transform(ctx) { + return ctx.handler.name + } + + app.get('/', async function show(req, res) { + await null + inside = store.getStore() + res.send('ok') + }) + + channel.start.bindStore(store, transform) + try { + subscribe() + await request(app).get('/').expect(200, 'ok') + } finally { + channel.start.unbindStore(store) + } + + assert.strictEqual(inside, 'show') + }) + + it('should report a thrown error at its origin, then trace the error handler', async function () { + var app = express() + + app.get('/', function boom() { + throw new Error('boom') + }) + app.use(function recover(err, req, res, next) { + res.status(500).send('recovered ' + err.message) + }) + + subscribe() + await request(app).get('/').expect(500, 'recovered boom') + + assert.deepStrictEqual(sequence(), ['start boom', 'error boom', 'start recover', 'end recover', 'end boom']) + assert.strictEqual(events[1].error, 'boom') + assert.strictEqual(events[2].errorHandler, true) + assert.strictEqual(events[2].incomingError, 'boom') + assert.strictEqual(events[2].route, '/') + assert.strictEqual(events[4].error, 'boom') + }) + + it('should trace app.error() handlers whatever their length, and only for errors', async function () { + var app = express() + + app.get('/fail', function fail(req, res, next) { + next(new Error('failed')) + }) + app.get('/ok', function ok(req, res, next) { + next() + }) + app.error(function recover(err, req, res) { + res.status(500).send(err.message) + }) + app.use(function notFound(req, res) { + res.status(404).send('none') + }) + + subscribe() + await request(app).get('/fail').expect(500, 'failed') + await request(app).get('/ok').expect(404, 'none') + + assert.deepStrictEqual(sequence(), [ + 'start fail', + 'error fail', + 'start recover', + 'end recover', + 'end fail', + 'start ok', + 'start notFound', + 'end notFound', + 'end ok' + ]) + assert.strictEqual(events[2].errorHandler, true) + assert.strictEqual(events[2].incomingError, 'failed') + }) + + it('should report an error passed to next() at its origin', async function () { + var app = express() + var error = new Error('nope') + + app.use(function fail(req, res, next) { + next(error) + }) + app.use(function recover(err, req, res, next) { + res.status(418).send(err.message) + }) + + subscribe() + await request(app).get('/').expect(418, 'nope') + + assert.deepStrictEqual(sequence(), ['start fail', 'error fail', 'start recover', 'end recover', 'end fail']) + assert.strictEqual(events[1].ctx.error, error) + assert.strictEqual(events[2].ctx.incomingError, error) + assert.ok(!('error' in events[3].ctx)) + }) + + it('should report a rejected promise at its origin, before asyncStart', async function () { + var app = express() + + app.get('/', async function reject() { + await null + throw new Error('async boom') + }) + app.use(function recover(err, req, res, next) { + res.status(500).send(err.message) + }) + + subscribe() + await request(app).get('/').expect(500, 'async boom') + + assert.deepStrictEqual(sequence(), [ + 'start reject', + 'end reject', + 'error reject', + 'start recover', + 'end recover', + 'asyncStart reject', + 'asyncEnd reject' + ]) + assert.strictEqual(events[6].error, 'async boom') + assert.ok(!('result' in events[6].ctx)) + }) + + it('should report an unhandled error once, and Express still answers 500', async function () { + var app = express() + var outer = express.Router() + var inner = express.Router() + + inner.get('/x', function boom(req, res, next) { + next(new Error('unhandled')) + }) + outer.use('/inner', inner) + app.use('/outer', outer) + app.set('env', 'test') + + subscribe() + await request(app) + .get('/outer/inner/x') + .expect(500, /unhandled/) + + var errors = events.filter(function (e) { + return e.phase === 'error' + }) + assert.strictEqual(errors.length, 1) + assert.strictEqual(errors[0].name, 'boom') + }) + + it('should not treat next("route") and next("router") as errors', async function () { + var app = express() + var router = express.Router() + + router.use(function leave(req, res, next) { + next('router') + }) + app.use(router) + app.get( + '/', + function skip(req, res, next) { + next('route') + }, + function never(req, res) { + res.send('never') + } + ) + app.get('/', function show(req, res) { + res.send('ok') + }) + + subscribe() + await request(app).get('/').expect(200, 'ok') + + assert.ok(!events.some((e) => e.phase === 'error')) + assert.ok(!events.some((e) => e.name === 'never')) + assert.ok(events.some((e) => e.name === 'show')) + }) + + it('should trace a sub-app: its mount, then its handlers, with the request as the sub-app sees it', async function () { + var app = express() + var sub = express() + + sub.use(function subLogger(req, res, next) { + next() + }) + sub.get('/x/:id', function subShow(req, res) { + res.send(req.originalRoute) + }) + app.use('/sub', sub) + + subscribe() + await request(app).get('/sub/x/1').expect(200, '/sub/x/:id') + + assert.deepStrictEqual(sequence(), [ + 'start mounted_app', + 'start subLogger', + 'start subShow', + 'end subShow', + 'end subLogger', + 'end mounted_app' + ]) + assert.strictEqual(events[0].route, '/sub') + assert.strictEqual(events[0].baseUrl, '/sub') + assert.strictEqual(events[0].ctx.req.app, sub, 'req.app is the sub-app once it handles the request') + assert.strictEqual(events[1].route, '/') + assert.strictEqual(events[1].baseUrl, '/sub') + assert.strictEqual(events[2].route, '/x/:id') + assert.strictEqual(events[2].baseUrl, '/sub') + assert.strictEqual(events[2].ctx.req.originalRoute, '/sub/x/:id') + }) + + it('should trace nested routers with their mount patterns', async function () { + var app = express() + var api = express.Router({ mergeParams: true }) + var users = express.Router({ mergeParams: true }) + + users.get('/:id', function user(req, res) { + res.json(req.params) + }) + api.use('/users', users) + app.use('/api/:version', api) + + subscribe() + await request(app).get('/api/v2/users/7').expect(200, { version: 'v2', id: '7' }) + + assert.deepStrictEqual(sequence(), [ + 'start router', + 'start router', + 'start user', + 'end user', + 'end router', + 'end router' + ]) + assert.deepStrictEqual( + events.map((e) => e.route), + ['/api/:version', '/users', '/:id', '/:id', '/users', '/api/:version'] + ) + assert.deepStrictEqual( + events.filter((e) => e.phase === 'start').map((e) => e.baseUrl), + ['/api/v2', '/api/v2/users', '/api/v2/users'] + ) + }) + + it('should report the pattern that matched for a path array', async function () { + var app = express() + + app.get(['/a', '/b/:id'], function show(req, res) { + res.send('ok') + }) + + subscribe() + await request(app).get('/b/1').expect(200, 'ok') + + assert.strictEqual(events[0].route, '/b/:id') + }) + + it("should report the '' entry of a path array for a strict router's mount path", async function () { + var app = express() + var router = express.Router({ strict: true }) + + router.get(['', '/x'], function show(req, res) { + res.send('dir') + }) + app.use('/dir', router) + + subscribe() + await request(app).get('/dir').expect(200, 'dir') + await request(app).get('/dir/x').expect(200, 'dir') + + assert.deepStrictEqual( + events.filter((e) => e.phase === 'start' && e.name === 'show').map((e) => e.route), + ['', '/x'] + ) + }) + + for (const misuse of ['rejects and then resolves', 'resolves twice']) { + it('should settle a thenable once when it ' + misuse, async function () { + var app = express() + var rejects = misuse === 'rejects and then resolves' + + app.use(function subject(req, res) { + if (!rejects) res.send('resolved') + return { + then: function (resolve, reject) { + if (rejects) reject(new Error('first')) + else resolve('first') + resolve('late') + } + } + }) + app.use(function recover(err, req, res, next) { + res.status(500).send(err.message) + }) + + subscribe() + await request(app) + .get('/') + .expect(rejects ? 500 : 200, rejects ? 'first' : 'resolved') + + var subject = events.filter((e) => e.name === 'subject') + assert.deepStrictEqual( + subject.map((e) => e.phase), + rejects ? ['start', 'end', 'error', 'asyncStart', 'asyncEnd'] : ['start', 'end', 'asyncStart', 'asyncEnd'] + ) + assert.strictEqual(subject[subject.length - 1].result, rejects ? undefined : 'first') + }) + } + + it('should trace only the middleware that ran for a 404', async function () { + var app = express() + + app.use(function logger(req, res, next) { + next() + }) + app.get('/x', function show(req, res) { + res.send('x') + }) + + subscribe() + await request(app).get('/nope').expect(404) + + assert.deepStrictEqual(sequence(), ['start logger', 'end logger']) + }) + + it('should publish nothing for a 404 from an app with no handlers', async function () { + var app = express() + + subscribe() + await request(app).get('/nope').expect(404) + + assert.deepStrictEqual(events, []) + }) + + it('should trace app.param() callbacks with the parameter name', async function () { + var app = express() + + app.param('id', function loadId(req, res, next, id) { + req.loaded = 'item ' + id + next() + }) + app.get('/items/:id', function show(req, res) { + res.send(req.loaded) + }) + + subscribe() + await request(app).get('/items/3').expect(200, 'item 3') + + assert.deepStrictEqual(sequence(), ['start loadId', 'start show', 'end show', 'end loadId']) + assert.strictEqual(events[0].param, 'id') + assert.strictEqual(events[0].route, '/items/:id') + assert.strictEqual(events[0].layer, 'handle') + assert.strictEqual(events[1].param, undefined) + }) + + it('should run every handler in the same order and answer the same with and without subscribers', async function () { + var calls = [] + + function build() { + var app = express() + var sub = express() + var api = express.Router() + + app.param('id', function loadId(req, res, next) { + calls.push('param') + next() + }) + app.use(function first(req, res, next) { + calls.push('first') + next() + }) + api.get('/:id', async function item(req, res, next) { + calls.push('item') + await null + next(new Error('item failed')) + }) + api.use(function apiRecover(err, req, res, next) { + calls.push('apiRecover') + res.status(503).json({ error: err.message, route: req.originalRoute }) + }) + sub.get('/hello', function hello(req, res) { + calls.push('hello') + res.send('hi') + }) + app.use('/api', api) + app.use('/sub', sub) + app.get('/throw', function thrower() { + calls.push('thrower') + throw new Error('thrown') + }) + // Express's final handler would print the stack, whose frames differ + // when traced (the tracing calls sit between the router and handler) + app.use(function last(err, req, res, next) { + calls.push('last') + res.status(500).send(err.message) + }) + return app + } + + async function run(app) { + calls = [] + var results = [] + for (var url of ['/api/9', '/sub/hello', '/throw', '/missing']) { + var res = await request(app).get(url) + results.push([url, res.status, res.headers['content-type'], res.text]) + } + return { calls: calls, results: results } + } + + var without = await run(build()) + subscribe() + var withSubscribers = await run(build()) + + assert.deepStrictEqual(withSubscribers, without) + assert.ok(events.length > 0) + }) + }) + + describe('express.initialization', function () { + it('should publish { app } for every app, sub-apps included, once it is set up', function () { + var messages = [] + + function onInit(message) { + messages.push(message) + // set up before it is published: settings and router are there + assert.strictEqual(message.app.get('env'), process.env.NODE_ENV || 'development') + assert.strictEqual(typeof message.app.handle, 'function') + } + + dc.subscribe('express.initialization', onInit) + try { + var app = express() + var sub = express() + app.use('/sub', sub) + } finally { + dc.unsubscribe('express.initialization', onInit) + } + + assert.strictEqual(messages.length, 2) + assert.strictEqual(messages[0].app, app) + assert.strictEqual(messages[1].app, sub) + assert.deepStrictEqual(Object.keys(messages[0]), ['app']) + }) + }) + + describe('without subscribers', function () { + // Every channel and the methods that publish on it. A publish without a + // hasSubscribers check (or a context built for nobody) calls one of these. + var channels = PHASES.map(function (phase) { + return dc.channel('tracing:' + CHANNEL + ':' + phase) + }).concat(dc.channel('express.initialization')) + var calls + + beforeEach(function () { + calls = [] + channels.forEach(function (channel) { + ;['publish', 'runStores'].forEach(function (method) { + channel[method] = function () { + calls.push(channel.name + ' ' + method) + return Object.getPrototypeOf(channel)[method].apply(channel, arguments) + } + }) + }) + }) + + afterEach(function () { + channels.forEach(function (channel) { + delete channel.publish + delete channel.runStores + }) + }) + + it('should not publish, run stores or record errors for any kind of handler', async function () { + var requests = [] + var app = express() + var sub = express() + var api = express.Router() + + channels.forEach(function (channel) { + assert.strictEqual(channel.hasSubscribers, false, channel.name) + }) + + app.use(function collect(req, res, next) { + requests.push(req) + next() + }) + app.param('id', async function loadId(req, res, next) { + await null + next() + }) + api.get( + ['/a', '/:id'], + async function item(req, res) { + await null + throw new Error('item failed') + }, + function itemRecover(err, req, res, next) { + next(err) + } + ) + api.use(function apiRecover(err, req, res, next) { + next(err) + }) + sub.get('/x', function show(req, res, next) { + next(new Error('sub failed')) + }) + app.use('/api', api) + app.use('/sub', sub) + app.get('/items/:id', function showItem(req, res) { + res.send('item ' + req.params.id) + }) + app.use(function recover(err, req, res, next) { + res.status(err.status || 500).send(err.message) + }) + + await request(app).get('/items/5').expect(200, 'item 5') + await request(app).get('/api/1').expect(500, 'item failed') + await request(app).get('/sub/x').expect(500, 'sub failed') + // an error from matching (decoding the parameter) + await request(app).get('/api/%ZZ').expect(400, "Failed to decode param '%ZZ'") + await request(app).get('/nope').expect(404) + + assert.deepStrictEqual(calls, []) + requests.forEach(function (req) { + assert.strictEqual(req[Symbol.for('router.tracing.publishedErrors')], undefined) + }) + }) + + it('should see a publish when something does publish (the spies work)', async function () { + var app = express() + + app.get('/', function show(req, res) { + res.send('ok') + }) + + subscribe() + await request(app).get('/').expect(200, 'ok') + express() + + assert.deepStrictEqual(calls, [ + 'tracing:express.router.request:start runStores', + 'tracing:express.router.request:start publish', + 'tracing:express.router.request:end publish' + ]) + }) + }) + + describe('with subscribers that throw', function () { + // diagnostics_channel calls each subscriber in a try/catch and rethrows + // its error on the next tick, as an uncaught exception, so the request + // goes on unchanged. Run in a child process, which handles those. + function run(mode) { + var output = execFileSync(process.execPath, [path.join(__dirname, 'fixtures', 'diagnostics-throwing.js'), mode], { + encoding: 'utf8' + }) + return JSON.parse(output) + } + + it('should answer and call handlers as without subscribers', function () { + var without = run('none') + var throwing = run('throwing') + + assert.deepStrictEqual(throwing.calls, without.calls) + assert.deepStrictEqual(throwing.results, without.results) + assert.deepStrictEqual(without.uncaught, []) + // every subscriber and the store transform threw, and each was reported + assert.ok(throwing.uncaught.length > 0) + assert.deepStrictEqual( + Array.from(new Set(throwing.uncaught)).sort(), + ['asyncEnd', 'asyncStart', 'end', 'error', 'initialization', 'start', 'store'].map(function (n) { + return 'subscriber ' + n + }) + ) + }) + }) +}) diff --git a/test/router/tracing.js b/test/router/tracing.js new file mode 100644 index 00000000000..2818aeb6e65 --- /dev/null +++ b/test/router/tracing.js @@ -0,0 +1,2680 @@ +const { AsyncLocalStorage } = require('node:async_hooks') +const path = require('node:path') +const Router = require('../../lib/router') +const utils = require('./support/utils') + +const assert = utils.assert +const createServer = utils.createServer +const request = utils.request + +const CHANNEL = 'express.router.request' + +let dc +let tracingChannel + +try { + dc = require('node:diagnostics_channel') + if (dc.tracingChannel) { + tracingChannel = dc.tracingChannel + } +} catch {} + +// Node 19 drops a channel once its last subscriber leaves, orphaning the +// router's cached channel. A permanent no-op subscriber keeps it alive. +if (tracingChannel && process.version.startsWith('v19')) { + const noop = function () {} + tracingChannel(CHANNEL).subscribe({ + start: noop, + end: noop, + asyncStart: noop, + asyncEnd: noop, + error: noop + }) +} + +const describeTracing = tracingChannel ? describe : describe.skip + +describeTracing('TracingChannel', function () { + let handlers + let events + + beforeEach(function () { + events = [] + handlers = { + start(ctx) { + events.push({ phase: 'start', ctx }) + }, + end(ctx) { + events.push({ phase: 'end', ctx }) + }, + asyncStart(ctx) { + events.push({ phase: 'asyncStart', ctx }) + }, + asyncEnd(ctx) { + events.push({ phase: 'asyncEnd', ctx }) + }, + error(ctx) { + events.push({ phase: 'error', ctx }) + } + } + }) + + afterEach(function () { + dc.tracingChannel(CHANNEL).unsubscribe(handlers) + }) + + // Build a router and server with the tracing handlers subscribed. + function traced() { + const router = new Router() + const server = createServer(router) + dc.tracingChannel(CHANNEL).subscribe(handlers) + return { router, server } + } + + describe('when no subscribers', function () { + it('should not affect normal behavior', function (done) { + const router = new Router() + const server = createServer(router) + + router.get('/foo', function (req, res) { + res.statusCode = 200 + res.end('hello') + }) + + request(server).get('/foo').expect(200, 'hello', done) + }) + }) + + describe('context shape', function () { + it('should provide req, res, and layer in context', function (done) { + const { router, server } = traced() + + router.use(function myMiddleware(req, res, next) { + next() + }) + + router.get('/foo', function (req, res) { + res.statusCode = 200 + res.end('hello') + }) + + request(server) + .get('/foo') + .expect(200, function (err) { + if (err) return done(err) + + const startEvents = events.filter(byPhase('start')) + const middlewareStart = startEvents.find(function (e) { + return e.ctx.layer && e.ctx.layer.name === 'myMiddleware' + }) + + assert.ok(middlewareStart, 'should have start event for myMiddleware') + assert.ok(middlewareStart.ctx.req, 'should have req') + assert.ok(middlewareStart.ctx.res, 'should have res') + assert.ok(middlewareStart.ctx.layer, 'should have layer') + assert.equal(middlewareStart.ctx.layer.name, 'myMiddleware') + + done() + }) + }) + + it('should have layer.name as for unnamed middleware', function (done) { + const { router, server } = traced() + + router.use(function (req, res, next) { + next() + }) + + router.get('/foo', function (req, res) { + res.statusCode = 200 + res.end('hello') + }) + + request(server) + .get('/foo') + .expect(200, function (err) { + if (err) return done(err) + + const startEvents = events.filter(byPhase('start')) + const anonMiddleware = startEvents.find(function (e) { + return e.ctx.layer && e.ctx.layer.name === '' + }) + + assert.ok(anonMiddleware, 'should have anonymous middleware event') + + done() + }) + }) + }) + + describe('route handler tracing', function () { + it('should have req.route set for route handlers', function (done) { + const { router, server } = traced() + + router.get('/users/:id', function getUser(req, res) { + res.statusCode = 200 + res.end('user') + }) + + request(server) + .get('/users/123') + .expect(200, function (err) { + if (err) return done(err) + + const startEvents = events.filter(byPhase('start')) + const handlerStart = startEvents.find(function (e) { + return e.ctx.layer && e.ctx.layer.name === 'getUser' + }) + + assert.ok(handlerStart, 'should have start event for getUser') + assert.ok(handlerStart.ctx.req.route, 'should have req.route') + assert.equal(handlerStart.ctx.req.route.path, '/users/:id') + + done() + }) + }) + + it('should not trace the route dispatch wrapper', function (done) { + const { router, server } = traced() + + router.get('/foo', function myHandler(req, res) { + res.statusCode = 200 + res.end('ok') + }) + + request(server) + .get('/foo') + .expect(200, function (err) { + if (err) return done(err) + + const startEvents = events.filter(byPhase('start')) + const dispatchWrapper = startEvents.find(function (e) { + return e.ctx.layer && e.ctx.layer.name === 'handle' + }) + + assert.ok(!dispatchWrapper, 'should not have dispatch wrapper event') + + done() + }) + }) + }) + + describe('error handler tracing', function () { + it('should trace error handlers (fn.length === 4) and flag their ctx as errorHandler', function (done) { + const { router, server } = traced() + + router.get('/fail', function failingHandler(req, res, next) { + next(new Error('boom')) + }) + + router.use(function myErrorHandler(err, req, res, next) { + res.statusCode = 500 + res.end(err.message) + }) + + request(server) + .get('/fail') + .expect(500, 'boom', function (err) { + if (err) return done(err) + + const failingEvents = events.filter(byLayer('failingHandler')) + const errorHandlerEvents = events.filter(byLayer('myErrorHandler')) + + const errorHandlerStart = errorHandlerEvents.find(byPhase('start')) + assert.ok(errorHandlerStart, 'should have start event for error handler') + assert.equal(errorHandlerStart.ctx.layer.handle.length, 4) + assert.equal( + errorHandlerStart.ctx.errorHandler, + true, + 'error handler ctx should be flagged errorHandler so APMs can dedup the origin error' + ) + assert.equal( + errorHandlerStart.ctx.incomingError.message, + 'boom', + 'error handler ctx should expose the error it received' + ) + assert.ok(!('error' in errorHandlerStart.ctx), 'error is only set when the error handler itself fails') + + assert.ok( + !errorHandlerEvents.some(byPhase('error')), + 'error handler itself did not throw, so it should not emit error' + ) + + const failingError = failingEvents.find(byPhase('error')) + assert.ok(failingError, 'origin layer should emit error for next(err)') + assert.equal(failingError.ctx.error.message, 'boom') + assert.ok( + !failingError.ctx.errorHandler, + 'origin layer is not an error handler, so it should not be flagged errorHandler' + ) + + done() + }) + }) + + it('should emit error on originating layer when next(err) is recovered downstream', function (done) { + const { router, server } = traced() + + router.get('/fail', function failingHandler(req, res, next) { + next(new Error('boom')) + }) + + router.use(function myErrorHandler(err, req, res, next) { + res.statusCode = 500 + res.end(err.message) + }) + + request(server) + .get('/fail') + .expect(500, 'boom', function (err) { + if (err) return done(err) + + const failingEvents = events.filter(byLayer('failingHandler')) + const errorHandlerEvents = events.filter(byLayer('myErrorHandler')) + + const failingError = failingEvents.find(byPhase('error')) + assert.ok(failingError, 'originating layer should emit error, since unhandled-at-origin is always observable') + assert.equal(failingError.ctx.error.message, 'boom') + + assert.ok( + !errorHandlerEvents.some(byPhase('error')), + 'recovering error handler itself did not throw, so it should not emit error' + ) + + const errorHandlerStart = errorHandlerEvents.find(byPhase('start')) + assert.equal( + errorHandlerStart.ctx.errorHandler, + true, + 'error handler ctx is flagged errorHandler so APMs can dedup against the origin error' + ) + + const errorEvents = events.filter(byPhase('error')) + assert.equal( + errorEvents.length, + 1, + 'exactly one error event fires, on the origin layer that called next(err)' + ) + + done() + }) + }) + + it('should nest the error handler span inside the originating layer span', function (done) { + const { router, server } = traced() + + router.use(function firstMiddleware(req, res, next) { + next() + }) + + router.get('/fail', function failingHandler(req, res, next) { + next(new Error('boom')) + }) + + router.use(function myErrorHandler(err, req, res, next) { + res.statusCode = 500 + res.end(err.message) + }) + + request(server) + .get('/fail') + .expect(500, 'boom', function (err) { + if (err) return done(err) + + const syncEvents = events + .filter(function (e) { + return e.phase === 'start' || e.phase === 'end' + }) + .map(function (e) { + return e.phase + ':' + (e.ctx.layer && e.ctx.layer.name) + }) + + const failingStart = syncEvents.indexOf('start:failingHandler') + const failingEnd = syncEvents.indexOf('end:failingHandler') + const errorHandlerStart = syncEvents.indexOf('start:myErrorHandler') + const errorHandlerEnd = syncEvents.indexOf('end:myErrorHandler') + + assert.notEqual(failingStart, -1, 'failingHandler should have start') + assert.notEqual(errorHandlerStart, -1, 'myErrorHandler should have start') + + assert.ok(failingStart < errorHandlerStart, 'failing layer start should come before error handler start') + assert.ok(errorHandlerStart < errorHandlerEnd, 'error handler start should come before its own end') + assert.ok( + errorHandlerEnd < failingEnd, + 'error handler end should come before failing layer end. Nesting contract: the error handler that runs via next(err) is nested inside the layer that triggered it, letting APMs attribute the error to the correct parent span' + ) + + done() + }) + }) + + it('should not emit error for next("route") routing signal', function (done) { + const { router, server } = traced() + + router.get('/skip', function skipToNextRoute(req, res, next) { + next('route') + }) + + router.get('/skip', function nextRouteHandler(req, res) { + res.statusCode = 200 + res.end('skipped') + }) + + request(server) + .get('/skip') + .expect(200, 'skipped', function (err) { + if (err) return done(err) + + const errorEvents = events.filter(byPhase('error')) + assert.equal( + errorEvents.length, + 0, + 'next("route") is a routing signal, not an error, so nothing should publish' + ) + + done() + }) + }) + + it('should not emit error for next("router") routing signal', function (done) { + const { router, server } = traced() + + router.use(function ejectFromRouter(req, res, next) { + next('router') + }) + + router.get('/foo', function shouldNotRun(req, res) { + res.statusCode = 200 + res.end('should not reach') + }) + + request(server) + .get('/foo') + .expect(404, function (err) { + if (err) return done(err) + + const errorEvents = events.filter(byPhase('error')) + assert.equal( + errorEvents.length, + 0, + 'next("router") is a routing signal, not an error, so nothing should publish' + ) + + done() + }) + }) + + it('should not emit error when a handler throws the "route" routing signal', function (done) { + const { router, server } = traced() + + router.get('/skip', function throwRoute(req, res) { + throw 'route' // eslint-disable-line no-throw-literal + }) + + router.get('/skip', function nextRouteHandler(req, res) { + res.statusCode = 200 + res.end('skipped') + }) + + request(server) + .get('/skip') + .expect(200, 'skipped', function (err) { + if (err) return done(err) + + const errorEvents = events.filter(byPhase('error')) + assert.equal( + errorEvents.length, + 0, + 'a thrown "route" routing signal is not an error, so nothing should publish' + ) + + done() + }) + }) + + it('should not emit error when a handler throws the "router" routing signal', function (done) { + const { router, server } = traced() + + router.use(function throwRouter(req, res) { + throw 'router' // eslint-disable-line no-throw-literal + }) + + router.get('/foo', function shouldNotRun(req, res) { + res.statusCode = 200 + res.end('should not reach') + }) + + request(server) + .get('/foo') + .expect(404, function (err) { + if (err) return done(err) + + const errorEvents = events.filter(byPhase('error')) + assert.equal( + errorEvents.length, + 0, + 'a thrown "router" routing signal is not an error, so nothing should publish' + ) + + done() + }) + }) + + it('should emit error on originating layer when next(err) is unhandled', function (done) { + const { router, server } = traced() + + router.get('/fail', function failingHandler(req, res, next) { + next(new Error('unhandled boom')) + }) + + request(server) + .get('/fail') + .expect(500, function (err) { + if (err) return done(err) + + const failingEvents = events.filter(function (e) { + return e.ctx.layer && e.ctx.layer.name === 'failingHandler' + }) + + const failingError = failingEvents.find(byPhase('error')) + assert.ok(failingError, 'unhandled next(err) must be observable on the origin layer') + assert.equal(failingError.ctx.error.message, 'unhandled boom') + + const errorEvents = events.filter(byPhase('error')) + assert.equal( + errorEvents.length, + 1, + 'exactly one error event fires, on the origin layer that called next(err)' + ) + + done() + }) + }) + }) + + describe('error channel', function () { + it('should emit error when handler throws synchronously', function (done) { + const { router, server } = traced() + + router.get('/throw', function (req, res) { + throw new Error('sync boom') + }) + + request(server) + .get('/throw') + .expect(500, function (err) { + if (err) return done(err) + + const errorEvents = events.filter(byPhase('error')) + assert.ok(errorEvents.length > 0, 'should have error events') + + const errorEvent = errorEvents.find(function (e) { + return e.ctx.error && e.ctx.error.message === 'sync boom' + }) + assert.ok(errorEvent, 'should have error event with the thrown error') + + done() + }) + }) + + it('should emit error when async handler rejects', function (done) { + const { router, server } = traced() + + router.get('/reject', async function (req, res) { + throw new Error('async boom') + }) + + request(server) + .get('/reject') + .expect(500, function (err) { + if (err) return done(err) + + const errorEvents = events.filter(byPhase('error')) + assert.ok(errorEvents.length > 0, 'should have error events') + + const errorEvent = errorEvents.find(function (e) { + return e.ctx.error && e.ctx.error.message === 'async boom' + }) + assert.ok(errorEvent, 'should have error event with the rejected error') + + done() + }) + }) + + it('should normalize a falsy rejection to the error the router forwards', function (done) { + const { router, server } = traced() + + router.get('/reject', async function rejectFalsy(req, res) { + return Promise.reject() // eslint-disable-line prefer-promise-reject-errors + }) + + request(server) + .get('/reject') + .expect(500, function (err) { + if (err) return done(err) + + const errorEvents = events.filter(byPhase('error')) + assert.equal(errorEvents.length, 1, 'should report the rejection once') + + const reported = errorEvents[0].ctx.error + assert.ok( + reported instanceof Error, + 'a falsy rejection is reported as the Error the router forwards to next(), not the raw value' + ) + assert.equal(reported.message, 'Rejected promise') + + done() + }) + }) + + it('should keep routing after a sync falsy throw, same as the untraced path', function (done) { + const { router, server } = traced() + + router.get('/falsy', function throwsFalsy(req, res) { + throw undefined // eslint-disable-line no-throw-literal + }) + + router.get('/falsy', function continues(req, res) { + res.statusCode = 200 + res.end('continued') + }) + + request(server) + .get('/falsy') + .expect(200, 'continued', function (err) { + if (err) return done(err) + + const errorEvents = events.filter(byPhase('error')) + assert.equal( + errorEvents.length, + 0, + 'the untraced router treats a sync falsy throw as next(), so subscribing must not divert it to error handling' + ) + + done() + }) + }) + + it('should emit error on route only when sync throw is recovered by a clean error handler', function (done) { + const { router, server } = traced() + + router.get('/throw', function throwingHandler(req, res) { + throw new Error('sync boom') + }) + + router.use(function cleanErrorHandler(err, req, res, next) { + res.statusCode = 500 + res.end(err.message) + }) + + request(server) + .get('/throw') + .expect(500, 'sync boom', function (err) { + if (err) return done(err) + + const errorEvents = events.filter(byPhase('error')) + assert.equal(errorEvents.length, 1, 'exactly one error event should fire') + assert.equal( + errorEvents[0].ctx.layer.name, + 'throwingHandler', + 'error event should belong to the throwing route layer' + ) + + done() + }) + }) + + it('should emit error on route only when async reject is recovered by a clean error handler', function (done) { + const { router, server } = traced() + + router.get('/reject', async function rejectingHandler(req, res) { + throw new Error('async boom') + }) + + router.use(function cleanErrorHandler(err, req, res, next) { + res.statusCode = 500 + res.end(err.message) + }) + + request(server) + .get('/reject') + .expect(500, 'async boom', function (err) { + if (err) return done(err) + + const errorEvents = events.filter(byPhase('error')) + assert.equal(errorEvents.length, 1, 'exactly one error event should fire') + assert.equal( + errorEvents[0].ctx.layer.name, + 'rejectingHandler', + 'error event should belong to the rejecting route layer' + ) + + done() + }) + }) + + it('should emit error on both layers when sync throw is followed by a throwing error handler', function (done) { + const { router, server } = traced() + + router.get('/throw', function throwingHandler(req, res) { + throw new Error('sync boom') + }) + + // eslint-disable-next-line n/handle-callback-err + router.use(function throwingErrorHandler(err, req, res, next) { + throw new Error('handler boom') + }) + + request(server) + .get('/throw') + .expect(500, function (err) { + if (err) return done(err) + + const errorEvents = events.filter(byPhase('error')) + + assert.equal(errorEvents.length, 2, 'error should fire on both layers') + + const routeError = errorEvents.find(byLayer('throwingHandler')) + assert.ok(routeError, 'route layer should emit error') + assert.ok( + !routeError.ctx.errorHandler, + 'route layer is not an error handler, so errorHandler flag must be absent' + ) + + const handlerError = errorEvents.find(byLayer('throwingErrorHandler')) + assert.ok(handlerError, 'error handler should emit its own error') + assert.equal( + handlerError.ctx.errorHandler, + true, + "error handler's own error event must carry errorHandler:true so APMs can classify the span correctly" + ) + + done() + }) + }) + + it('should emit error on both layers when async reject is followed by a throwing error handler', function (done) { + const { router, server } = traced() + + router.get('/reject', async function rejectingHandler(req, res) { + throw new Error('async boom') + }) + + // eslint-disable-next-line n/handle-callback-err + router.use(function throwingErrorHandler(err, req, res, next) { + throw new Error('handler boom') + }) + + request(server) + .get('/reject') + .expect(500, function (err) { + if (err) return done(err) + + const errorEvents = events.filter(byPhase('error')) + + assert.equal(errorEvents.length, 2, 'error should fire on both layers') + + const routeError = errorEvents.find(byLayer('rejectingHandler')) + assert.ok(routeError, 'route layer should emit error') + assert.ok( + !routeError.ctx.errorHandler, + 'route layer is not an error handler, so errorHandler flag must be absent' + ) + + const handlerError = errorEvents.find(byLayer('throwingErrorHandler')) + assert.ok(handlerError, 'error handler should emit its own error') + assert.equal( + handlerError.ctx.errorHandler, + true, + "error handler's own error event must carry errorHandler:true so APMs can classify the span correctly" + ) + + done() + }) + }) + }) + + describe('async handlers', function () { + it('should trace async handlers that return promises', function (done) { + const { router, server } = traced() + + router.get('/async', function asyncHandler(req, res) { + return new Promise(function (resolve) { + setTimeout(function () { + res.statusCode = 200 + res.end('async hello') + resolve() + }, 10) + }) + }) + + request(server) + .get('/async') + .expect(200, 'async hello', function (err) { + if (err) return done(err) + + const startEvents = events.filter(byPhase('start')) + const asyncEndEvents = events.filter(byPhase('asyncEnd')) + + assert.ok(startEvents.length > 0, 'should have start events') + assert.ok(asyncEndEvents.length > 0, 'should have asyncEnd events') + + done() + }) + }) + }) + + describe('nested routers', function () { + it('should trace middleware in nested routers', function (done) { + const { router, server } = traced() + const nested = new Router() + + nested.get('/bar', function nestedHandler(req, res) { + res.statusCode = 200 + res.end('nested') + }) + + router.use('/foo', nested) + + request(server) + .get('/foo/bar') + .expect(200, 'nested', function (err) { + if (err) return done(err) + + const startEvents = events.filter(byPhase('start')) + const handlerEvent = startEvents.find(function (e) { + return e.ctx.layer && e.ctx.layer.name === 'nestedHandler' + }) + assert.ok(handlerEvent, 'should have event from nested route handler') + assert.ok(handlerEvent.ctx.req.route, 'should have req.route') + + done() + }) + }) + }) + + describe('parameter callbacks', function () { + it('should report the parameter callback with only an error subscriber', async function () { + const router = new Router() + const server = createServer(router) + dc.tracingChannel(CHANNEL).error.subscribe(handlers.error) + + function validateId(req, res, next) { + next(new Error('Invalid ID')) + } + + router.param('id', validateId) + router.get('/users/:id', function unexpected(req, res) { + res.end('unexpected') + }) + router.use(function forwarding(err, req, res, next) { + next(err) + }) + router.use(recover) + + await request(server).get('/users/123').expect(500, 'Invalid ID') + + assert.strictEqual(events.length, 1) + assert.strictEqual(events[0].phase, 'error') + assert.strictEqual(events[0].ctx.handler, validateId) + assert.strictEqual(events[0].ctx.param, 'id') + }) + + it('should run asynchronous parameter callbacks in the bound tracing store', async function () { + const { router, server } = traced() + const store = new AsyncLocalStorage() + const channel = dc.tracingChannel(CHANNEL).start + channel.bindStore(store, function (ctx) { + return ctx + }) + let observed + + async function load(req, res, next) { + observed = store.getStore() + await new Promise(function (resolve) { + setImmediate(resolve) + }) + assert.strictEqual(store.getStore(), observed) + next() + } + + router.param('id', load) + router.get('/users/:id', function user(req, res) { + assert.notStrictEqual(store.getStore(), observed) + res.end('ok') + }) + + try { + await request(server).get('/users/123').expect(200, 'ok') + assert.strictEqual(observed.handler, load) + assert.strictEqual(observed.param, 'id') + assert.strictEqual(observed.route, '/users/:id') + } finally { + channel.unbindStore(store) + store.disable() + } + }) + + for (const failure of ['next', 'throw', 'reject', 'async next']) { + for (const forward of [false, true]) { + it( + 'should report a parameter ' + failure + ' at its origin when ' + (forward ? 'forwarded' : 'recovered'), + async function () { + const { router, server } = traced() + const error = new Error('Invalid ID') + + function validateId(req, res, next) { + if (failure === 'throw') throw error + if (failure === 'reject') return Promise.reject(error) + if (failure === 'async next') return setImmediate(next, error) + next(error) + } + + router.param('id', validateId) + router.get('/users/:id', function unexpected(req, res) { + res.end('unexpected') + }) + + if (forward) { + router.use(function forwarding(err, req, res, next) { + next(err) + }) + } + router.use(recover) + + await request(server).get('/users/123').expect(500, 'Invalid ID') + + const errors = events.filter(byPhase('error')) + assert.strictEqual(errors.length, 1) + const ctx = errors[0].ctx + assert.strictEqual(ctx.error, error) + assert.strictEqual(ctx.handler, validateId) + assert.strictEqual(ctx.param, 'id') + assert.strictEqual(ctx.route, '/users/:id') + assert.strictEqual(ctx.layer, router.stack[0]) + assert.strictEqual(ctx.errorHandler, undefined) + + const ownEvents = events.filter(function (e) { + return e.ctx === ctx + }) + assert.deepStrictEqual( + ownEvents.map(function (e) { + return e.phase + }), + failure === 'reject' + ? ['start', 'end', 'error', 'asyncStart', 'asyncEnd'] + : failure === 'async next' + ? ['start', 'end', 'error'] + : ['start', 'error', 'end'] + ) + } + ) + } + } + + it('should retain callback identity and arguments when parameters are chained and cached', async function () { + const { router, server } = traced() + + function normalizeId(req, res, next, value, name) { + assert.strictEqual(value, '123') + assert.strictEqual(name, 'id') + req.params.id = Number(value) + next() + } + + function loadUser(req, res, next, value, name) { + assert.strictEqual(value, '123') + assert.strictEqual(name, 'id') + assert.strictEqual(req.params.id, 123) + next() + return Promise.resolve() + } + + function validateSlug(req, res, next, value, name) { + assert.strictEqual(value, 'profile') + assert.strictEqual(name, 'slug') + next() + } + + router.param('id', normalizeId) + router.param('id', loadUser) + router.param('slug', validateSlug) + router.use('/users/:id/:slug', function middleware(req, res, next) { + next() + }) + router.get('/users/:id/:slug', function user(req, res) { + assert.strictEqual(req.params.id, 123) + res.end('ok') + }) + + await request(server).get('/users/123/profile').expect(200, 'ok') + + const starts = events.filter(byPhase('start')).filter(function (e) { + return e.ctx.param !== undefined + }) + assert.deepStrictEqual( + starts.map(function (e) { + return [e.ctx.handler, e.ctx.param] + }), + [ + [normalizeId, 'id'], + [loadUser, 'id'], + [validateSlug, 'slug'] + ] + ) + for (const event of starts) { + assert.strictEqual(event.ctx.layer, router.stack[0]) + assert.strictEqual(event.ctx.route, '/users/:id/:slug') + assert.strictEqual(event.ctx.req.originalUrl, '/users/123/profile') + assert.ok(event.ctx.res) + } + assert.deepStrictEqual( + events + .filter(function (e) { + return e.ctx.handler === loadUser + }) + .map(function (e) { + return e.phase + }), + ['start', 'end', 'asyncStart', 'asyncEnd'] + ) + assert.strictEqual(router.stack[0].name, 'middleware') + }) + + it('should wait for next even when a parameter promise resolves', async function () { + const { router } = traced() + let resume + let reached = false + + function load(req, res, next) { + resume = next + return Promise.resolve() + } + + router.param('id', load) + router.get('/users/:id', function user(req, res, next) { + reached = true + next() + }) + + const completed = new Promise(function (resolve, reject) { + router({ method: 'GET', url: '/users/123' }, {}, function (err) { + if (err) return reject(err) + resolve() + }) + }) + + await new Promise(function (resolve) { + setImmediate(resolve) + }) + assert.strictEqual(reached, false) + assert.deepStrictEqual( + events + .filter(function (e) { + return e.ctx.handler === load + }) + .map(function (e) { + return e.phase + }), + ['start', 'end', 'asyncStart', 'asyncEnd'] + ) + resume() + await completed + assert.strictEqual(reached, true) + }) + + for (const signal of ['route', 'router']) { + for (const kind of ['next', 'throw', 'reject']) { + it('should preserve a parameter ' + kind + ' with the ' + signal + ' signal', async function () { + const { router, server } = traced() + const nested = new Router() + + function skip(req, res, next) { + if (kind === 'throw') throw signal + if (kind === 'reject') return Promise.reject(signal) + next(signal) + } + + nested.param('id', skip) + nested.get('/users/:id', function unexpected(req, res) { + res.end('unexpected') + }) + nested.get('/users/123', function fallback(req, res) { + res.end('route') + }) + router.use(nested) + router.get('/users/123', function outer(req, res) { + res.end('router') + }) + + await request(server).get('/users/123').expect(200, signal) + + assert.strictEqual(events.filter(byPhase('error')).length, 0) + const ownEvents = events.filter(function (e) { + return e.ctx.handler === skip + }) + assert.deepStrictEqual( + ownEvents.map(function (e) { + return e.phase + }), + kind === 'reject' ? ['start', 'end', 'asyncStart', 'asyncEnd'] : ['start', 'end'] + ) + assert.strictEqual(ownEvents[0].ctx.param, 'id') + }) + } + } + + for (const kind of ['throw', 'reject']) { + it('should preserve a falsy parameter ' + kind, async function () { + const { router, server } = traced() + + function falsy(req, res, next) { + if (kind === 'throw') throw undefined // eslint-disable-line no-throw-literal + return Promise.reject() // eslint-disable-line prefer-promise-reject-errors + } + + router.param('id', falsy) + router.get('/users/:id', function user(req, res) { + res.end('ok') + }) + router.use(recover) + + await request(server) + .get('/users/123') + .expect(kind === 'reject' ? 500 : 200, kind === 'reject' ? 'Rejected promise' : 'ok') + + const errors = events.filter(byPhase('error')) + assert.strictEqual(errors.length, kind === 'reject' ? 1 : 0) + if (kind === 'reject') { + assert.strictEqual(errors[0].ctx.handler, falsy) + assert.strictEqual(errors[0].ctx.error.message, 'Rejected promise') + } + }) + } + + it('should report a parameter error once across separately loaded routers', async function () { + const { router, server } = traced() + const RouterCopy = loadRouterCopy() + const nested = new RouterCopy() + + function validateId(req, res, next) { + next(new Error('Invalid ID')) + } + + nested.param('id', validateId) + nested.get('/users/:id', function unexpected(req, res) { + res.end('unexpected') + }) + nested.use(function forwarding(err, req, res, next) { + next(err) + }) + router.use('/api', nested) + router.use(function rethrowing(err, req, res, next) { + throw err + }) + router.use(recover) + + await request(server).get('/api/users/123').expect(500, 'Invalid ID') + + assert.notStrictEqual(RouterCopy, Router) + const errors = events.filter(byPhase('error')) + assert.strictEqual(errors.length, 1) + assert.strictEqual(errors[0].ctx.handler, validateId) + assert.strictEqual(errors[0].ctx.layer, nested.stack[0]) + assert.strictEqual(errors[0].ctx.route, '/users/:id') + assert.strictEqual(errors[0].ctx.param, 'id') + }) + + it('should attribute downstream errors to the handler instead of the parameter callback', async function () { + const { router, server } = traced() + + function load(req, res, next) { + next() + } + function fail(req, res) { + throw new Error('route failed') + } + + router.param('id', load) + router.get('/users/:id', fail) + router.use(recover) + + await request(server).get('/users/123').expect(500, 'route failed') + + const errors = events.filter(byPhase('error')) + assert.strictEqual(errors.length, 1) + assert.strictEqual(errors[0].ctx.handler, fail) + assert.strictEqual(errors[0].ctx.param, undefined) + }) + + for (const fail of [false, true]) { + it( + 'should preserve the parameter context across concurrent requests that ' + (fail ? 'fail' : 'succeed'), + async function () { + const { router, server } = traced() + let resume + let entered + const waiting = new Promise(function (resolve) { + entered = resolve + }) + + function load(req, res, next, id) { + if (id !== '1') { + next() + return Promise.resolve() + } + return new Promise(function (resolve, reject) { + resume = function () { + if (fail) { + reject(new Error('first failed')) + } else { + next() + resolve() + } + } + entered() + }) + } + + router.param('id', load) + router.get(['/users/:id', '/posts/:id'], function item(req, res) { + res.end(req.params.id) + }) + router.use(recover) + + const first = request(server) + .get('/users/1') + .expect(fail ? 500 : 200, fail ? 'first failed' : '1') + .then(function () {}) + await waiting + try { + await request(server).get('/posts/2').expect(200, '2') + } finally { + resume() + await first + } + + const ownEvents = events.filter(function (e) { + return e.ctx.handler === load + }) + for (const url of ['/users/1', '/posts/2']) { + const requestEvents = ownEvents.filter(function (e) { + return e.ctx.req.originalUrl === url + }) + assert.deepStrictEqual( + requestEvents.map(function (e) { + return e.phase + }), + fail && url === '/users/1' + ? ['start', 'end', 'error', 'asyncStart', 'asyncEnd'] + : ['start', 'end', 'asyncStart', 'asyncEnd'] + ) + for (const event of requestEvents) { + assert.strictEqual(event.ctx.route, url === '/users/1' ? '/users/:id' : '/posts/:id') + assert.strictEqual(event.ctx.param, 'id') + } + } + } + ) + } + }) + + describe('asynchronous tracing stores', function () { + for (const kind of ['parameter', 'middleware', 'route', 'error handler']) { + for (const outcome of ['resolve', 'reject']) { + it( + 'should bind the asyncStart store through asyncEnd when a ' + kind + ' promise will ' + outcome, + async function () { + const { router, server } = traced() + const channel = dc.tracingChannel(CHANNEL) + const store = new AsyncLocalStorage() + const observed = [] + + function result(next) { + if (outcome === 'reject') return Promise.reject(new Error('failed')) + next() + return Promise.resolve() + } + + const handler = + kind === 'error handler' + ? function subject(err, req, res, next) { + assert.strictEqual(err.message, 'original') + return result(next) + } + : function subject(req, res, next) { + return result(next) + } + + function onEnd(ctx) { + if (ctx.handler === handler) observed.push([ctx, store.getStore()]) + } + + if (kind === 'parameter') { + router.param('id', handler) + } else if (kind === 'route') { + router.get('/users/:id', handler) + } else { + if (kind === 'error handler') { + router.use(function fail(req, res, next) { + next(new Error('original')) + }) + } + router.use(handler) + } + router.get('/users/:id', function user(req, res) { + res.end('ok') + }) + router.use(recover) + + channel.asyncStart.bindStore(store, function (ctx) { + return ctx + }) + channel.asyncEnd.subscribe(onEnd) + try { + await request(server) + .get('/users/123') + .expect(outcome === 'reject' ? 500 : 200, outcome === 'reject' ? 'failed' : 'ok') + + assert.strictEqual(observed.length, 1) + assert.strictEqual(observed[0][1], observed[0][0]) + assert.strictEqual(store.getStore(), undefined) + } finally { + channel.asyncStart.unbindStore(store) + channel.asyncEnd.unsubscribe(onEnd) + store.disable() + } + } + ) + } + } + }) + + describe('untraced error origins', function () { + for (const source of ['parameter callback', 'parameter promise', 'middleware', 'route']) { + for (const forwarding of ['next', 'throw', 'reject']) { + it('should not blame a ' + forwarding + ' forwarder after subscribing during a ' + source, async function () { + const router = new Router() + const error = new Error('before subscription') + let resume + + function pending(req, res, next) { + if (source === 'parameter promise') { + return new Promise(function (resolve, reject) { + resume = reject + }) + } + resume = next + } + + if (source.startsWith('parameter')) { + router.param('id', pending) + } else if (source === 'middleware') { + router.use(pending) + } else { + router.get('/users/:id', pending) + } + router.get('/users/:id', function unexpected(req, res) { + throw new Error('unexpected') + }) + router.use(function forward(err, req, res, next) { + if (forwarding === 'throw') throw err + if (forwarding === 'reject') return Promise.reject(err) + next(err) + }) + + const completed = new Promise(function (resolve) { + router({ method: 'GET', url: '/users/123' }, {}, resolve) + }) + dc.tracingChannel(CHANNEL).subscribe(handlers) + resume(error) + + assert.strictEqual(await completed, error) + // Node 19 keeps no-op subscribers for its cached-channel workaround, + // so it may have traced the origin before our observers subscribed. + for (const event of events.filter(byPhase('error'))) { + assert.strictEqual(event.ctx.handler, pending) + } + }) + } + } + + it('should not blame a traced mount for an error raised while tracing was disabled', async function () { + const { router } = traced() + const channel = dc.tracingChannel(CHANNEL) + const nested = new Router() + const error = new Error('untraced parameter') + let resume + + function pending(req, res, next) { + resume = next + } + + nested.use(function disableTracing(req, res, next) { + channel.unsubscribe(handlers) + next() + }) + nested.param('id', pending) + nested.get('/users/:id', function unexpected(req, res) { + throw new Error('unexpected') + }) + router.use(nested) + + const completed = new Promise(function (resolve) { + router({ method: 'GET', url: '/users/123' }, {}, resolve) + }) + channel.subscribe(handlers) + resume(error) + + assert.strictEqual(await completed, error) + for (const event of events.filter(byPhase('error'))) { + assert.strictEqual(event.ctx.handler, pending) + } + }) + + for (const mounted of [false, true]) { + for (const forwarding of ['next', 'throw', 'reject', 'replace']) { + it( + 'should not blame a ' + + forwarding + + ' forwarder for ' + + (mounted ? 'mounted' : 'direct') + + ' URL decoding errors', + async function () { + const { router, server } = traced() + const target = mounted ? new Router() : router + const replacement = new Error('replacement') + + function forward(err, req, res, next) { + if (forwarding === 'throw') throw err + if (forwarding === 'reject') return Promise.reject(err) + next(forwarding === 'replace' ? replacement : err) + } + + target.get('/users/:id', function unexpected(req, res) { + res.end('unexpected') + }) + if (mounted) router.use('/api', target) + router.use(forward) + router.use(function respond(err, req, res, next) { + // err.status: router 2.3.0 also sets statusCode on the decoding + // error (pillarjs/router#171), which this copy doesn't have yet + res.statusCode = err.status || 500 + res.end(err.message) + }) + + await request(server) + .get((mounted ? '/api' : '') + '/users/%ZZ') + .expect( + forwarding === 'replace' ? 500 : 400, + forwarding === 'replace' ? 'replacement' : "Failed to decode param '%ZZ'" + ) + + const errors = events.filter(byPhase('error')) + assert.strictEqual(errors.length, forwarding === 'replace' ? 1 : 0) + if (forwarding === 'replace') { + assert.strictEqual(errors[0].ctx.handler, forward) + assert.strictEqual(errors[0].ctx.error, replacement) + } + } + ) + } + } + + for (const forwarding of ['next', 'throw', 'reject', 'replace']) { + it('should distinguish an incoming error from a ' + forwarding + ' error handler result', async function () { + const { router } = traced() + const error = new Error('external') + const replacement = new Error('replacement') + + function forward(err, req, res, next) { + if (forwarding === 'throw') throw err + if (forwarding === 'reject') return Promise.reject(err) + next(forwarding === 'replace' ? replacement : err) + } + + router.use(forward) + const received = await new Promise(function (resolve) { + // Exercise an error handler directly, without a router boundary that + // could already have recorded the incoming error. (traceError: in + // this copy the router calls it instead of handleError when traced.) + router.stack[0].traceError(error, {}, {}, resolve) + }) + + assert.strictEqual(received, forwarding === 'replace' ? replacement : error) + const errors = events.filter(byPhase('error')) + assert.strictEqual(errors.length, forwarding === 'replace' ? 1 : 0) + if (forwarding === 'replace') { + assert.strictEqual(errors[0].ctx.error, replacement) + assert.strictEqual(errors[0].ctx.incomingError, error) + } + }) + } + }) + + describe('route pattern', function () { + function startFor(predicate) { + return events.filter(byPhase('start')).find(function (e) { + return predicate(e.ctx.layer) + }) + } + + it('should provide the matched path for middleware', function (done) { + const { router, server } = traced() + + router.use('/api/:version', function apiMiddleware(req, res, next) { + next() + }) + + router.get('/api/:version/users', function (req, res) { + res.statusCode = 200 + res.end('users') + }) + + request(server) + .get('/api/v1/users') + .expect(200, 'users', function (err) { + if (err) return done(err) + + const startEvent = startFor(function (layer) { + return layer.name === 'apiMiddleware' + }) + assert.ok(startEvent, 'should have start event for apiMiddleware') + assert.equal(startEvent.ctx.route, '/api/:version') + + done() + }) + }) + + it('should provide the route path for route handlers', function (done) { + const { router, server } = traced() + + router.get('/users/:id', function getUser(req, res) { + res.statusCode = 200 + res.end('user') + }) + + request(server) + .get('/users/42') + .expect(200, 'user', function (err) { + if (err) return done(err) + + const startEvent = startFor(function (layer) { + return layer.name === 'getUser' + }) + assert.ok(startEvent, 'should have start event for getUser') + assert.equal(startEvent.ctx.route, '/users/:id') + + done() + }) + }) + + it('should provide the path that matched for array paths', function (done) { + const { router, server } = traced() + + router.get(['/foo', ['/bar', '/baz/:id']], function multi(req, res) { + res.statusCode = 200 + res.end('multi') + }) + + request(server) + .get('/baz/1') + .expect(200, 'multi', function (err) { + if (err) return done(err) + + const startEvent = startFor(function (layer) { + return layer.name === 'multi' + }) + assert.ok(startEvent, 'should have start event for multi') + assert.equal(startEvent.ctx.route, '/baz/:id') + + done() + }) + }) + + for (const kind of ['route handlers', 'middleware', 'error middleware']) { + for (const otherPath of ['/posts/2', '/missing']) { + it('should preserve the matched path for ' + kind + ' during a request to ' + otherPath, async function () { + const { router, server } = traced() + let resume + let entered + const waiting = new Promise(function (resolve) { + entered = resolve + }) + + router.param('id', function (req, res, next, id) { + if (id === '1') { + resume = next + entered() + } else { + next() + } + }) + + const handler = + kind === 'error middleware' + ? function onError(err, req, res, next) { + assert.equal(err.message, 'boom') + res.statusCode = 500 + res.end(req.params.id) + } + : function onRequest(req, res) { + res.end(req.params.id) + } + + if (kind === 'error middleware') { + router.use(function (req, res, next) { + next(new Error('boom')) + }) + } + + router[kind === 'route handlers' ? 'get' : 'use'](['/users/:id', '/posts/:id'], handler) + + // Handle unmatched requests with a pending error without finalhandler logging it. + router.use(function (err, req, res, next) { + res.statusCode = 404 + res.end(err.message) + }) + + const status = kind === 'error middleware' ? 500 : 200 + const first = request(server) + .get('/users/1') + .expect(status, '1') + .then(function () {}) + + await waiting + try { + await request(server) + .get(otherPath) + .expect(otherPath === '/missing' ? 404 : status) + } finally { + resume() + await first + } + + const paths = events + .filter(byPhase('start')) + .filter(function (e) { + return e.ctx.handler === handler + }) + .map(function (e) { + return [e.ctx.req.originalUrl, e.ctx.route] + }) + + assert.deepStrictEqual( + paths, + otherPath === '/missing' + ? [['/users/1', '/users/:id']] + : [ + ['/posts/2', '/posts/:id'], + ['/users/1', '/users/:id'] + ] + ) + }) + } + } + + it('should preserve an empty matched pattern', async function () { + const { router, server } = traced() + + router.get('', function root(req, res) { + res.end('root') + }) + + await request(server).get('/').expect(200, 'root') + + const event = startFor(function (layer) { + return layer.name === 'root' + }) + assert.ok(event) + assert.strictEqual(event.ctx.route, '') + }) + + for (const signal of ['next', 'error', 'router']) { + it('should restore the outer route pattern after a nested router calls ' + signal, async function () { + const { router, server } = traced() + const nested = new Router() + const fail = signal === 'error' + + nested.get('/users/*rest', function inner(req, res, next) { + setImmediate(next, fail ? new Error('boom') : signal === 'router' ? 'router' : undefined) + }) + + router.get( + '/users/:id', + nested, + function outer(req, res) { + res.end('outer') + }, + function outerError(err, req, res, next) { + res.statusCode = 500 + res.end(err.message) + } + ) + + await request(server) + .get('/users/1') + .expect(fail ? 500 : 200, fail ? 'boom' : 'outer') + + const innerEvent = startFor(function (layer) { + return layer.name === 'inner' + }) + const outerEvent = startFor(function (layer) { + return layer.name === (fail ? 'outerError' : 'outer') + }) + assert.ok(innerEvent) + assert.ok(outerEvent) + assert.strictEqual(innerEvent.ctx.route, '/users/*rest') + assert.strictEqual(outerEvent.ctx.route, '/users/:id') + }) + } + + it('should preserve the route pattern while a parameter callback invokes a router', async function () { + const { router, server } = traced() + const nested = new Router() + + nested.use(function middleware(req, res, next) { + setImmediate(next) + }) + router.param('id', function (req, res, next) { + nested(req, res, next) + }) + router.get('/users/:id', function user(req, res) { + res.end(req.params.id) + }) + + await request(server).get('/users/1').expect(200, '1') + + const middlewareEvent = startFor(function (layer) { + return layer.name === 'middleware' + }) + const userEvent = startFor(function (layer) { + return layer.name === 'user' + }) + assert.ok(middlewareEvent) + assert.ok(userEvent) + assert.strictEqual(middlewareEvent.ctx.route, '/') + assert.strictEqual(userEvent.ctx.route, '/users/:id') + }) + + it('should provide the route path for error handlers inside a route', function (done) { + const { router, server } = traced() + + router.get( + '/fail/:id', + function fail(req, res, next) { + next(new Error('boom')) + }, + function routeErrorHandler(err, req, res, next) { + res.statusCode = 500 + res.end(err.message) + } + ) + + request(server) + .get('/fail/1') + .expect(500, 'boom', function (err) { + if (err) return done(err) + + const startEvent = startFor(function (layer) { + return layer.name === 'routeErrorHandler' + }) + assert.ok(startEvent, 'should have start event for routeErrorHandler') + assert.equal(startEvent.ctx.route, '/fail/:id') + + done() + }) + }) + + it('should provide the mount path for mounted routers', function (done) { + const { router, server } = traced() + const nested = new Router() + + nested.get('/:id', function getItem(req, res) { + res.statusCode = 200 + res.end('item') + }) + + router.use('/items', nested) + + request(server) + .get('/items/7') + .expect(200, 'item', function (err) { + if (err) return done(err) + + const mountEvent = startFor(function (layer) { + return layer.handle === nested + }) + const itemEvent = startFor(function (layer) { + return layer.name === 'getItem' + }) + assert.ok(mountEvent, 'should have start event for the mounted router') + assert.ok(itemEvent, 'should have start event for getItem') + assert.equal(mountEvent.ctx.route, '/items') + assert.equal(itemEvent.ctx.route, '/:id') + + done() + }) + }) + }) + + describe('error deduplication', function () { + it('should report a next(err) error once, on the origin layer, across mounted routers', function (done) { + const { router: outer, server } = traced() + const nested = new Router() + + nested.get('/bar', function innerHandler(req, res, next) { + next(new Error('boom')) + }) + outer.use('/foo', nested) + outer.use(recover) + + request(server) + .get('/foo/bar') + .expect(500, 'boom', function (err) { + if (err) return done(err) + + const errorEvents = events.filter(byPhase('error')) + assert.equal( + errorEvents.length, + 1, + 'the same error bubbling through the mounted router must be reported once' + ) + assert.equal( + errorEvents[0].ctx.layer.name, + 'innerHandler', + 'the single error event belongs to the origin layer' + ) + + done() + }) + }) + + it('should report a next(err) error once across separate copies of the router', function (done) { + const { router: outer, server } = traced() + const RouterCopy = loadRouterCopy() + const nested = new RouterCopy() + + assert.notStrictEqual(RouterCopy, Router) + + nested.get('/bar', function innerHandler(req, res, next) { + next(new Error('boom')) + }) + outer.use('/foo', nested) + outer.use(recover) + + request(server) + .get('/foo/bar') + .expect(500, 'boom', function (err) { + if (err) return done(err) + + const errorEvents = events.filter(byPhase('error')) + assert.equal( + errorEvents.length, + 1, + 'an app can end up with multiple copies of router, so dedup must not be scoped to one copy' + ) + assert.equal(errorEvents[0].ctx.layer.name, 'innerHandler') + + done() + }) + }) + + it('should report a next(err) error once across two mount levels', function (done) { + const { router: outer, server } = traced() + const mid = new Router() + const deep = new Router() + + deep.get('/baz', function deepHandler(req, res, next) { + next(new Error('boom')) + }) + mid.use('/bar', deep) + outer.use('/foo', mid) + outer.use(recover) + + request(server) + .get('/foo/bar/baz') + .expect(500, 'boom', function (err) { + if (err) return done(err) + + const errorEvents = events.filter(byPhase('error')) + assert.equal(errorEvents.length, 1, 'the error must not be re-reported at each ancestor router') + assert.equal(errorEvents[0].ctx.layer.name, 'deepHandler') + + done() + }) + }) + + it('should report a thrown error once across mounted routers', function (done) { + const { router: outer, server } = traced() + const nested = new Router() + + nested.get('/bar', function innerThrow(req, res) { + throw new Error('boom') + }) + outer.use('/foo', nested) + outer.use(recover) + + request(server) + .get('/foo/bar') + .expect(500, 'boom', function (err) { + if (err) return done(err) + + const errorEvents = events.filter(byPhase('error')) + assert.equal(errorEvents.length, 1, 'a thrown error must be reported once, at its origin') + assert.equal(errorEvents[0].ctx.layer.name, 'innerThrow') + + done() + }) + }) + + it('should report a rejected error once across mounted routers', function (done) { + const { router: outer, server } = traced() + const nested = new Router() + + nested.get('/bar', async function innerReject(req, res) { + throw new Error('boom') + }) + outer.use('/foo', nested) + outer.use(recover) + + request(server) + .get('/foo/bar') + .expect(500, 'boom', function (err) { + if (err) return done(err) + + const errorEvents = events.filter(byPhase('error')) + assert.equal(errorEvents.length, 1, 'a rejected error must be reported once, at its origin') + assert.equal(errorEvents[0].ctx.layer.name, 'innerReject') + + done() + }) + }) + + it('should report next(err) once when an error handler forwards it', function (done) { + const { router, server } = traced() + + router.get('/fail', function origin(req, res, next) { + next(new Error('boom')) + }) + router.use(function forwarding(err, req, res, next) { + next(err) + }) + router.use(recover) + + request(server) + .get('/fail') + .expect(500, 'boom', function (err) { + if (err) return done(err) + + const errorEvents = events.filter(byPhase('error')) + assert.equal(errorEvents.length, 1, 'forwarding the same error with next(err) must not re-report it') + assert.equal(errorEvents[0].ctx.layer.name, 'origin') + + done() + }) + }) + + it('should report next(err) once when an error handler rethrows it', function (done) { + const { router, server } = traced() + + router.get('/fail', function origin(req, res, next) { + next(new Error('boom')) + }) + router.use(function rethrowing(err, req, res, next) { + throw err + }) + router.use(recover) + + request(server) + .get('/fail') + .expect(500, 'boom', function (err) { + if (err) return done(err) + + const errorEvents = events.filter(byPhase('error')) + assert.equal( + errorEvents.length, + 1, + 'throw err and next(err) are equivalent to the router, so rethrowing the same error must not re-report it' + ) + assert.equal(errorEvents[0].ctx.layer.name, 'origin') + + done() + }) + }) + }) + + describe('event ordering', function () { + it('should emit only start and end for a synchronous handler', function (done) { + const { router, server } = traced() + + router.get('/order', function syncHandler(req, res) { + res.statusCode = 200 + res.end('ok') + }) + + request(server) + .get('/order') + .expect(200, function (err) { + if (err) return done(err) + + const phases = events.filter(byLayer('syncHandler')).map(function (e) { + return e.phase + }) + assert.equal(phases.length, 2, 'a synchronous handler has no async phase') + assert.equal(phases[0], 'start') + assert.equal(phases[1], 'end') + assert.ok( + phases.indexOf('asyncStart') < 0 && phases.indexOf('asyncEnd') < 0, + 'a synchronous handler should not emit asyncStart/asyncEnd' + ) + + done() + }) + }) + + it('should emit start before asyncEnd for an asynchronous handler', function (done) { + const { router, server } = traced() + + router.get('/order', async function asyncHandler(req, res) { + res.statusCode = 200 + res.end('ok') + }) + + request(server) + .get('/order') + .expect(200, function (err) { + if (err) return done(err) + + const phases = events.filter(byLayer('asyncHandler')).map(function (e) { + return e.phase + }) + assert.ok(phases.indexOf('start') >= 0, 'should have start') + assert.ok(phases.indexOf('asyncEnd') >= 0, 'should have asyncEnd') + assert.ok(phases.indexOf('start') < phases.indexOf('asyncEnd'), 'start should come before asyncEnd') + + done() + }) + }) + }) + + describe('return value', function () { + // It's the same context object on every event, so copy what we need each time + function snapshots() { + const seen = [] + for (const phase of ['end', 'error', 'asyncStart', 'asyncEnd']) { + handlers[phase] = function (ctx) { + events.push({ phase, ctx }) + seen.push({ + phase, + name: ctx.handler.name, + has: 'result' in ctx, + result: ctx.result, + done: 'result' in ctx || 'error' in ctx + }) + } + } + function at(name, phase) { + return seen.find(function (s) { + return s.name === name && s.phase === phase + }) + } + at.phases = function (name) { + return seen + .filter(function (s) { + return s.name === name + }) + .map(function (s) { + return s.phase + }) + } + return at + } + + it('should set a synchronous return value as the result at end', async function () { + const at = snapshots() + const { router, server } = traced() + + router.use(function callbackMiddleware(req, res, next) { + setImmediate(next) + }) + router.get('/users/:id', function syncHandler(req, res) { + res.end('ok') + return 'done' + }) + + await request(server).get('/users/1').expect(200, 'ok') + + assert.deepStrictEqual(at('callbackMiddleware', 'end'), { + phase: 'end', + name: 'callbackMiddleware', + has: true, + result: undefined, + done: true + }) + assert.deepStrictEqual(at('syncHandler', 'end'), { + phase: 'end', + name: 'syncHandler', + has: true, + result: 'done', + done: true + }) + assert.strictEqual(at('syncHandler', 'asyncStart'), undefined) + }) + + for (const kind of ['handler', 'error handler', 'parameter callback']) { + for (const native of [true, false]) { + const label = native ? 'promise' : 'non-native thenable' + + it( + 'should set the resolved value of ' + + (kind === 'error handler' ? 'an ' : 'a ') + + kind + + ' ' + + label + + ' as the result at asyncStart', + async function () { + const at = snapshots() + const { router, server } = traced() + + // Resolves to 'done' after running work + function settle(work) { + if (native) + return Promise.resolve().then(function () { + work() + return 'done' + }) + return { + then(resolve) { + setImmediate(function () { + work() + resolve('done') + }) + } + } + } + const subjects = { + handler: function subject(req, res) { + return settle(function () { + res.end('ok') + }) + }, + 'error handler': function subject(err, req, res, next) { + assert.strictEqual(err.message, 'boom') + return settle(next) + }, + 'parameter callback': function subject(req, res, next) { + return settle(next) + } + } + const subject = subjects[kind] + + if (kind === 'parameter callback') router.param('id', subject) + if (kind === 'error handler') { + router.use(function fail(req, res, next) { + next(new Error('boom')) + }) + router.use(subject) + } + router.get( + '/users/:id', + kind === 'handler' + ? subject + : function user(req, res) { + res.end('ok') + } + ) + + await request(server).get('/users/1').expect(200, 'ok') + + assert.strictEqual(at('subject', 'end').done, false, 'neither result nor error before it settles') + assert.strictEqual(at('subject', 'asyncStart').result, 'done') + assert.strictEqual(at('subject', 'asyncEnd').result, 'done') + } + ) + } + } + + for (const kind of ['handler', 'parameter callback']) { + for (const outcome of ['resolves', 'rejects']) { + it( + 'should publish asyncStart and asyncEnd after end when a ' + kind + ' thenable ' + outcome + ' synchronously', + async function () { + const at = snapshots() + const { router, server } = traced() + + function subject(req, res, next) { + if (kind === 'parameter callback' && outcome === 'resolves') next() + if (kind === 'handler' && outcome === 'resolves') res.end('ok') + return { + then(resolve, reject) { + if (outcome === 'resolves') resolve('val') + else reject(new Error('boom')) + } + } + } + + if (kind === 'parameter callback') router.param('id', subject) + router.get( + '/users/:id', + kind === 'handler' + ? subject + : function user(req, res) { + res.end('ok') + } + ) + router.use(recover) + + await request(server) + .get('/users/1') + .expect(outcome === 'resolves' ? 200 : 500) + + const phases = at.phases('subject').filter(function (phase) { + return phase !== 'error' + }) + assert.deepStrictEqual(phases, ['end', 'asyncStart', 'asyncEnd']) + assert.strictEqual(at('subject', 'end').done, false) + assert.strictEqual(at('subject', 'asyncEnd').done, true) + if (outcome === 'resolves') assert.strictEqual(at('subject', 'asyncEnd').result, 'val') + } + ) + } + } + + for (const kind of ['middleware', 'route handler', 'parameter callback']) { + it('should treat a ' + kind + ' thenable whose then throws as a rejection', async function () { + const at = snapshots() + const { router, server } = traced() + + function subject() { + return { + then() { + throw new Error('bad then') + } + } + } + + if (kind === 'middleware') router.use(subject) + if (kind === 'parameter callback') router.param('id', subject) + router.get( + '/users/:id', + kind === 'route handler' + ? subject + : function user(req, res) { + res.end('ok') + } + ) + router.use(recover) + + await request(server).get('/users/1').expect(500, 'bad then') + + // A parameter callback forwards the error before returning, like next(err) then a promise + assert.deepStrictEqual( + at.phases('subject'), + kind === 'parameter callback' + ? ['error', 'end', 'asyncStart', 'asyncEnd'] + : ['end', 'error', 'asyncStart', 'asyncEnd'] + ) + assert.strictEqual(at('subject', 'end').done, false) + assert.strictEqual(at('subject', 'asyncEnd').done, true) + }) + } + + for (const kind of ['middleware', 'parameter callback']) { + for (const misuse of ['throws', 'rejects']) { + it('should settle a ' + kind + ' thenable once when it resolves and then ' + misuse, async function () { + const at = snapshots() + const { router, server } = traced() + + function subject(req, res, next) { + return { + then(resolve, reject) { + resolve('val') + if (misuse === 'throws') throw new Error('late') + reject(new Error('late')) + } + } + } + + if (kind === 'middleware') router.use(subject) + if (kind === 'parameter callback') router.param('id', subject) + router.get('/users/:id', function user(req, res) { + res.end('ok') + }) + router.use(recover) + + // Routing still gets the late error, as it does untraced + await request(server).get('/users/1').expect(500, 'late') + + const phases = at.phases('subject').filter(function (phase) { + return phase !== 'error' + }) + assert.deepStrictEqual(phases, ['end', 'asyncStart', 'asyncEnd']) + assert.strictEqual(at('subject', 'asyncEnd').result, 'val') + }) + } + } + + it('should accept a thenable that calls its callbacks without checking them with subscribers', async function () { + const { router, server } = traced() + const failures = [] + + router.use(function loose(req, res) { + res.end('ok') + return { + then(resolve) { + resolve('val') + } + } + }) + router.use(function failed(err, req, res, next) { + failures.push(err) + }) + + await request(server).get('/').expect(200, 'ok') + + assert.deepStrictEqual(failures, []) + }) + + // Not in router 2.3.0, which passes a no-op to then() on the untraced path + // too. Without subscribers this copy keeps router 2.2.0's untraced path, + // which passes null, so such a thenable's TypeError reaches next() as + // before (the re-sync to 2.3.0 changes it). + it('should keep router 2.2.0 for a thenable that calls its callbacks without checking them without subscribers', async function () { + const router = new Router() + const server = createServer(router) + const failures = [] + + router.use(function loose(req, res) { + res.end('ok') + return { + then(resolve) { + resolve('val') + } + } + }) + router.use(function failed(err, req, res, next) { + failures.push(err) + }) + + await request(server).get('/').expect(200, 'ok') + + assert.strictEqual(failures.length, 1) + assert.ok(failures[0] instanceof TypeError) + }) + + it('should publish an error again when it is reported after an error handler recovered from it', async function () { + const { router, server } = traced() + const single = new Error('single') + + function first(req, res, next) { + next(single) + } + function second(req, res, next) { + next(single) + } + + router.use(first) + router.use(function recovered(err, req, res, next) { + next(err === single ? undefined : err) + }) + router.use(second) + router.use(recover) + + await request(server).get('/').expect(500, 'single') + + const errors = events.filter(byPhase('error')) + assert.deepStrictEqual( + errors.map(function (e) { + return e.ctx.handler + }), + [first, second] + ) + assert.strictEqual( + events.find(function (e) { + return e.phase === 'end' && e.ctx.handler === second + }).ctx.error, + single + ) + }) + + for (const kind of ['handler', 'parameter callback']) { + for (const signal of ['route', 'router']) { + for (const async of [false, true]) { + it( + 'should not treat ' + + (async ? 'rejecting' : 'throwing') + + " '" + + signal + + "' from a " + + kind + + ' as an error', + async function () { + const at = snapshots() + const { router, server } = traced() + const inner = new Router() + + const subject = async + ? function subject() { + return Promise.reject(signal) + } + : function subject() { + throw signal + } + + if (kind === 'parameter callback') inner.param('id', subject) + inner.get( + '/users/:id', + kind === 'handler' + ? subject + : function user(req, res) { + res.end('unexpected') + } + ) + router.use(inner) + router.use(function after(req, res) { + res.end('after') + }) + + await request(server).get('/users/1').expect(200, 'after') + + assert.strictEqual(events.filter(byPhase('error')).length, 0) + const last = at.phases('subject').slice(-1)[0] + assert.deepStrictEqual(at.phases('subject'), async ? ['end', 'asyncStart', 'asyncEnd'] : ['end']) + assert.strictEqual(at('subject', 'end').done, !async) + assert.strictEqual(at('subject', last).done, !async, 'no error at the terminal event') + } + ) + } + } + } + + for (const kind of ['handler', 'parameter callback']) { + for (const failure of ['throw', 'reject']) { + it( + 'should not set a result when a ' + kind + ' ' + (failure === 'throw' ? 'throws' : 'rejects'), + async function () { + const at = snapshots() + const { router, server } = traced() + + function subject() { + if (failure === 'throw') throw new Error('boom') + return Promise.reject(new Error('boom')) + } + + if (kind === 'parameter callback') router.param('id', subject) + router.get( + '/users/:id', + kind === 'handler' + ? subject + : function user(req, res) { + res.end('ok') + } + ) + router.use(recover) + + await request(server).get('/users/1').expect(500, 'boom') + + assert.strictEqual(at('subject', 'end').has, false) + if (failure === 'throw') { + assert.deepStrictEqual(at.phases('subject'), ['error', 'end']) + assert.strictEqual(at('subject', 'end').done, true) + } else { + assert.deepStrictEqual(at.phases('subject'), ['end', 'error', 'asyncStart', 'asyncEnd']) + assert.strictEqual(at('subject', 'end').done, false) + assert.strictEqual(at('subject', 'asyncEnd').has, false) + } + } + ) + } + } + + for (const kind of ['handler', 'error handler', 'parameter callback']) { + for (const async of [false, true]) { + it( + 'should set the error at ' + + (async ? 'asyncEnd' : 'end') + + ' when ' + + (async ? 'an async ' : 'a sync ') + + kind + + ' rethrows an error already published', + async function () { + const at = snapshots() + const { router, server } = traced() + + function fail(req, res, next) { + req.failure = new Error('boom') + next(req.failure) + } + + router.use(fail) + if (kind === 'error handler') { + router.use( + async + ? async function subject(err, req, res, next) { + throw err + } + : function subject(err, req, res, next) { + throw err + } + ) + } else { + const subject = async + ? async function subject(req, res, next) { + throw req.failure + } + : function subject(req, res, next) { + throw req.failure + } + + // Recover from the error so the request reaches the subject + router.use(function swallow(err, req, res, next) { + next(err.message === 'boom' ? undefined : err) + }) + if (kind === 'parameter callback') router.param('id', subject) + router.get( + '/users/:id', + kind === 'handler' + ? subject + : function user(req, res) { + res.end('ok') + } + ) + } + router.use(recover) + + await request(server).get('/users/1').expect(500, 'boom') + + // Only an error handler still holds it; after swallow recovered, it's a new failure + const errors = events.filter(byPhase('error')) + assert.deepStrictEqual( + errors.map(function (e) { + return e.ctx.handler.name + }), + kind === 'error handler' ? ['fail'] : ['fail', 'subject'] + ) + if (kind === 'error handler') { + assert.deepStrictEqual(at.phases('subject'), async ? ['end', 'asyncStart', 'asyncEnd'] : ['end']) + } + assert.strictEqual(at('subject', 'end').done, !async) + if (async) assert.strictEqual(at('subject', 'asyncEnd').done, true) + } + ) + } + } + + for (const kind of ['handler', 'parameter callback']) { + for (const async of [false, true]) { + it( + 'should publish next(err) from ' + (async ? 'an async ' : 'a sync ') + kind + ' before end', + async function () { + const at = snapshots() + const { router, server } = traced() + + // Calls next(err) before returning, so the router can't know yet if a promise follows + const subject = async + ? async function subject(req, res, next) { + next(new Error('boom')) + } + : function subject(req, res, next) { + next(new Error('boom')) + } + + if (kind === 'parameter callback') router.param('id', subject) + router.get( + '/users/:id', + kind === 'handler' + ? subject + : function user(req, res) { + res.end('ok') + } + ) + router.use(recover) + + await request(server).get('/users/1').expect(500, 'boom') + + assert.deepStrictEqual( + at.phases('subject'), + async ? ['error', 'end', 'asyncStart', 'asyncEnd'] : ['error', 'end'] + ) + // A promise follows, so `end` must not look done + assert.strictEqual(at('subject', 'end').done, !async) + if (async) assert.strictEqual(at('subject', 'asyncEnd').done, true) + } + ) + } + } + + it('should publish every error a handler reports', async function () { + const { router, server } = traced() + const first = new Error('first') + const second = new Error('second') + + function twice(req, res, next) { + next(first) + throw second + } + + router.get('/users/:id', twice) + router.use(recover) + + await request(server).get('/users/1').expect(500, 'first') + + const errors = events.filter(byPhase('error')) + assert.deepStrictEqual( + errors.map(function (e) { + return e.ctx.handler + }), + [twice, twice] + ) + const end = events.find(function (e) { + return e.phase === 'end' && e.ctx.handler === twice + }) + assert.strictEqual(end.ctx.error, second) + }) + + it('should publish next(err) before the error handler it calls runs', async function () { + const { router, server } = traced() + + function boom(req, res, next) { + next(new Error('boom')) + } + + router.get('/users/:id', boom) + router.use(recover) + + await request(server).get('/users/1').expect(500, 'boom') + + const order = events + .filter(function (e) { + return e.phase === 'start' || e.phase === 'error' + }) + .map(function (e) { + return e.phase + ' ' + e.ctx.handler.name + }) + assert.deepStrictEqual(order, ['start boom', 'error boom', 'start recover']) + }) + }) + + describe('multiple middleware', function () { + it('should emit events for each middleware in the chain', function (done) { + const { router, server } = traced() + + router.use(function first(req, res, next) { + next() + }) + + router.use(function second(req, res, next) { + next() + }) + + router.get('/multi', function handler(req, res) { + res.statusCode = 200 + res.end('multi') + }) + + request(server) + .get('/multi') + .expect(200, function (err) { + if (err) return done(err) + + const startEvents = events.filter(byPhase('start')) + const names = startEvents.map(function (e) { + return e.ctx.layer.name + }) + + assert.ok(names.indexOf('first') >= 0, 'should trace first middleware') + assert.ok(names.indexOf('second') >= 0, 'should trace second middleware') + + done() + }) + }) + }) +}) + +// Load a separate instance of the router module, as when an app installs more +// than one copy (e.g. a direct dependency alongside the one bundled by express). +function loadRouterCopy() { + const root = path.dirname(require.resolve('../../lib/router')) + const isRouterModule = function (key) { + return key === path.join(root, 'index.js') || key.startsWith(path.join(root, 'lib') + path.sep) + } + + const original = {} + Object.keys(require.cache) + .filter(isRouterModule) + .forEach(function (key) { + original[key] = require.cache[key] + delete require.cache[key] + }) + + try { + return require('../../lib/router') + } finally { + Object.keys(require.cache) + .filter(isRouterModule) + .forEach(function (key) { + delete require.cache[key] + }) + Object.assign(require.cache, original) + } +} + +// Predicate matching a captured event by its layer name. +function byLayer(name) { + return function (e) { + return e.ctx.layer && e.ctx.layer.name === name + } +} + +// Predicate matching a captured event by its lifecycle phase. +function byPhase(name) { + return function (e) { + return e.phase === name + } +} + +// Error handler that recovers by ending the response with the error message. +function recover(err, req, res, next) { + res.statusCode = 500 + res.end(err.message) +} diff --git a/test/types/diagnostics.ts b/test/types/diagnostics.ts new file mode 100644 index 00000000000..9e518b9e7ce --- /dev/null +++ b/test/types/diagnostics.ts @@ -0,0 +1,57 @@ +// The diagnostics_channel payloads (a fork addition): subscribers typed with +// express.RouterTraceContext and express.InitializationMessage, the way +// docs/api/diagnostics.md uses them. + +import dc from 'node:diagnostics_channel' +import express, { type Express, type Request, type Response } from 'express' + +const channel = dc.tracingChannel('express.router.request') + +channel.subscribe({ + start(ctx) { + const req: Request = ctx.req + const res: Response = ctx.res + const name: string = ctx.layer.name + const route: string | RegExp | undefined = ctx.route + const param: string | undefined = ctx.param + const handlerName: string = ctx.handler.name + const errorHandler: true | undefined = ctx.errorHandler + const incoming: unknown = ctx.incomingError + void [req, res, name, route, param, handlerName, errorHandler, incoming] + }, + end(ctx) { + const result: unknown = ctx.result + void result + }, + asyncStart() {}, + asyncEnd(ctx) { + const status: number = ctx.res.statusCode + const pattern: string | undefined = ctx.req.originalRoute + void [status, pattern] + }, + error(ctx) { + const error: unknown = ctx.error + void error + } +}) + +dc.subscribe('express.initialization', (message) => { + const { app } = message as express.InitializationMessage + const typed: Express = app + typed.disable('x-powered-by') +}) + +function onStart(ctx: express.RouterTraceContext): void { + // @ts-expect-error the context's request is read, not replaced with something else + ctx.req = 42 + // @ts-expect-error errorHandler is only ever true + ctx.errorHandler = false + // @ts-expect-error route is a pattern, not a number + const route: number = ctx.route + void route +} +void onStart + +// @ts-expect-error an initialization message carries the app +const empty: express.InitializationMessage = {} +void empty diff --git a/typings/index.d.mts b/typings/index.d.mts index 5b8edcb6e0f..2cbfd27687d 100644 --- a/typings/index.d.mts +++ b/typings/index.d.mts @@ -34,6 +34,7 @@ export import ErrorRequestHandler = express.ErrorRequestHandler export import Express = express.Express export import Handler = express.Handler export import IRoute = express.IRoute +export import InitializationMessage = express.InitializationMessage export import IRouter = express.IRouter export import IRouterHandler = express.IRouterHandler export import IRouterMatcher = express.IRouterMatcher @@ -54,6 +55,7 @@ export import RequestHandlerParams = express.RequestHandlerParams export import RequestParamHandler = express.RequestParamHandler export import Response = express.Response export import RouteParameters = express.RouteParameters +export import RouterTraceContext = express.RouterTraceContext export import RouterOptions = express.RouterOptions export import RouterWithErrorHandlers = express.RouterWithErrorHandlers export import Send = express.Send diff --git a/typings/index.d.ts b/typings/index.d.ts index 083952e3062..580d1a32e8a 100644 --- a/typings/index.d.ts +++ b/typings/index.d.ts @@ -21,6 +21,8 @@ * (`ParamsDictionary`, `Query`, `RouteParameters` and the rest) are also * exported here, so they can come from `express`. * - `ErrorCode`, the codes on the errors Express creates (a fork addition). + * - `RouterTraceContext` and `InitializationMessage`, what Express's + * `diagnostics_channel` channels publish (a fork addition). * * MIT License * @@ -409,6 +411,42 @@ declare namespace e { | 'EXPRESS_ERR_STATIC_ROOT_REQUIRED' | 'EXPRESS_ERR_STATIC_ROOT_NOT_STRING' | 'EXPRESS_ERR_STATIC_SET_HEADERS_NOT_FUNCTION' + + /** + * What every event of the `express.router.request` TracingChannel publishes, for each middleware, + * route handler, error handler and `app.param()` callback the router runs (a fork addition, not + * in Express 5.3.0; the channel and context are router 2.3.0's). docs/api/diagnostics.md says + * when each event fires. Subscribe with `diagnostics_channel.tracingChannel('express.router.request')`. + */ + interface RouterTraceContext { + req: Request + res: Response + /** The router's layer. Internal: its shape may change between releases, so read it defensively. */ + layer: core.ILayer + /** The function invoked: the handler, or the `app.param()` callback. */ + handler: RequestHandler | ErrorRequestHandler | RequestParamHandler + /** The pattern that matched: the route's path, or the path a middleware, router or app was mounted with. */ + route: string | RegExp | undefined + /** The parameter's name, for `app.param()` callbacks only. */ + param?: string + /** The error the invocation reported: `next(err)`, a throw or a rejection. */ + error?: unknown + /** The error an error handler received. */ + incomingError?: unknown + /** `true` for error handlers (four arguments). */ + errorHandler?: true + /** What the invocation returned, or what its promise resolved to. */ + result?: unknown + } + + /** + * What `express()` publishes on the `express.initialization` channel, once the app is set up + * (a fork addition, not in Express 5.3.0). + */ + interface InitializationMessage { + app: Express + } } export = e