|
| 1 | +/* eslint-disable max-lines */ |
1 | 2 | import { Integration, Transaction } from '@sentry/types';
|
2 |
| -import { logger } from '@sentry/utils'; |
| 3 | +import { CrossPlatformRequest, extractPathForTransaction, logger } from '@sentry/utils'; |
3 | 4 |
|
4 | 5 | type Method =
|
5 | 6 | | 'all'
|
@@ -32,6 +33,32 @@ type Router = {
|
32 | 33 | [method in Method]: (...args: any) => any; // eslint-disable-line @typescript-eslint/no-explicit-any
|
33 | 34 | };
|
34 | 35 |
|
| 36 | +/* Extend the CrossPlatformRequest type with a patched parameter to build a reconstructed route */ |
| 37 | +type PatchedRequest = CrossPlatformRequest & { _reconstructedRoute?: string }; |
| 38 | + |
| 39 | +/* Type used for pathing the express router prototype */ |
| 40 | +type ExpressRouter = Router & { |
| 41 | + _router?: ExpressRouter; |
| 42 | + stack?: Layer[]; |
| 43 | + lazyrouter?: () => void; |
| 44 | + settings?: unknown; |
| 45 | + process_params: ( |
| 46 | + layer: Layer, |
| 47 | + called: unknown, |
| 48 | + req: PatchedRequest, |
| 49 | + res: ExpressResponse, |
| 50 | + done: () => void, |
| 51 | + ) => unknown; |
| 52 | +}; |
| 53 | + |
| 54 | +/* Type used for pathing the express router prototype */ |
| 55 | +type Layer = { |
| 56 | + match: (path: string) => boolean; |
| 57 | + handle_request: (req: PatchedRequest, res: ExpressResponse, next: () => void) => void; |
| 58 | + route?: { path: string }; |
| 59 | + path?: string; |
| 60 | +}; |
| 61 | + |
35 | 62 | interface ExpressResponse {
|
36 | 63 | once(name: string, callback: () => void): void;
|
37 | 64 | }
|
@@ -83,6 +110,7 @@ export class Express implements Integration {
|
83 | 110 | return;
|
84 | 111 | }
|
85 | 112 | instrumentMiddlewares(this._router, this._methods);
|
| 113 | + instrumentRouter(this._router as ExpressRouter); |
86 | 114 | }
|
87 | 115 | }
|
88 | 116 |
|
@@ -211,3 +239,75 @@ function patchMiddleware(router: Router, method: Method): Router {
|
211 | 239 | function instrumentMiddlewares(router: Router, methods: Method[] = []): void {
|
212 | 240 | methods.forEach((method: Method) => patchMiddleware(router, method));
|
213 | 241 | }
|
| 242 | + |
| 243 | +/** |
| 244 | + * Patches the prototype of Express.Router to accumulate the resolved route |
| 245 | + * if a layer instance's `match` function was called and it returned a successful match. |
| 246 | + * |
| 247 | + * @see https://github.com/expressjs/express/blob/master/lib/router/index.js |
| 248 | + * |
| 249 | + * @param appOrRouter the router instance which can either be an app (i.e. top-level) or a (nested) router. |
| 250 | + */ |
| 251 | +function instrumentRouter(appOrRouter: ExpressRouter): void { |
| 252 | + // This is how we can distinguish between app and routers |
| 253 | + const isApp = 'settings' in appOrRouter; |
| 254 | + |
| 255 | + // In case the app's top-level router hasn't been initialized yet, we have to do it now |
| 256 | + if (isApp && appOrRouter._router === undefined && appOrRouter.lazyrouter) { |
| 257 | + appOrRouter.lazyrouter(); |
| 258 | + } |
| 259 | + |
| 260 | + const router = isApp ? appOrRouter._router : appOrRouter; |
| 261 | + const routerProto = Object.getPrototypeOf(router) as ExpressRouter; |
| 262 | + |
| 263 | + const originalProcessParams = routerProto.process_params; |
| 264 | + routerProto.process_params = function process_params( |
| 265 | + layer: Layer, |
| 266 | + called: unknown, |
| 267 | + req: PatchedRequest, |
| 268 | + res: ExpressResponse & SentryTracingResponse, |
| 269 | + done: () => unknown, |
| 270 | + ) { |
| 271 | + // Base case: We're in the first part of the URL (thus we start with the root '/') |
| 272 | + if (!req._reconstructedRoute) { |
| 273 | + req._reconstructedRoute = ''; |
| 274 | + } |
| 275 | + |
| 276 | + // If the layer's partial route has params, the route is stored in layer.route. Otherwise, the hardcoded path |
| 277 | + // (i.e. a partial route without params) is stored in layer.path |
| 278 | + const partialRoute = layer.route?.path || layer.path || ''; |
| 279 | + |
| 280 | + // Normalize the partial route so that it doesn't contain leading or trailing slashes |
| 281 | + // and exclude empty or '*' wildcard routes. |
| 282 | + // The exclusion of '*' routes is our best effort to not "pollute" the transaction name |
| 283 | + // with interim handlers (e.g. ones that check authentication or do other middleware stuff). |
| 284 | + // We want to end up with the parameterized URL of the incoming request without any extraneous path segments. |
| 285 | + const finalPartialRoute = partialRoute |
| 286 | + .split('/') |
| 287 | + .filter(segment => segment.length > 0 && !segment.includes('*')) |
| 288 | + .join('/'); |
| 289 | + |
| 290 | + // If we found a valid partial URL, we append it to the reconstructed route |
| 291 | + if (finalPartialRoute.length > 0) { |
| 292 | + req._reconstructedRoute += `/${finalPartialRoute}`; |
| 293 | + } |
| 294 | + |
| 295 | + // Now we check if we are in the "last" part of the route. We determine this by comparing the |
| 296 | + // number of URL segments from the original URL to that of our reconstructed parameterized URL. |
| 297 | + // If we've reached our final destination, we update the transaction name. |
| 298 | + const urlLength = req.originalUrl?.split('/').filter(s => s.length > 0).length; |
| 299 | + const routeLength = req._reconstructedRoute.split('/').filter(s => s.length > 0).length; |
| 300 | + if (urlLength === routeLength) { |
| 301 | + const transaction = res.__sentry_transaction; |
| 302 | + if (transaction && transaction.metadata.source !== 'custom') { |
| 303 | + // If the request URL is '/' or empty, the reconstructed route will be empty. |
| 304 | + // Therefore, we fall back to setting the final route to '/' in this case. |
| 305 | + const finalRoute = req._reconstructedRoute || '/'; |
| 306 | + |
| 307 | + transaction.setName(...extractPathForTransaction(req, { path: true, method: true, customRoute: finalRoute })); |
| 308 | + } |
| 309 | + } |
| 310 | + |
| 311 | + return originalProcessParams.call(this, layer, called, req, res, done); |
| 312 | + }; |
| 313 | +} |
0 commit comments