-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathexpress.ts
313 lines (282 loc) · 9.64 KB
/
express.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
/* eslint-disable max-lines */
import { Integration, Transaction } from '@sentry/types';
import { CrossPlatformRequest, extractPathForTransaction, logger } from '@sentry/utils';
type Method =
| 'all'
| 'get'
| 'post'
| 'put'
| 'delete'
| 'patch'
| 'options'
| 'head'
| 'checkout'
| 'copy'
| 'lock'
| 'merge'
| 'mkactivity'
| 'mkcol'
| 'move'
| 'm-search'
| 'notify'
| 'purge'
| 'report'
| 'search'
| 'subscribe'
| 'trace'
| 'unlock'
| 'unsubscribe'
| 'use';
type Router = {
[method in Method]: (...args: any) => any; // eslint-disable-line @typescript-eslint/no-explicit-any
};
/* Extend the CrossPlatformRequest type with a patched parameter to build a reconstructed route */
type PatchedRequest = CrossPlatformRequest & { _reconstructedRoute?: string };
/* Type used for pathing the express router prototype */
type ExpressRouter = Router & {
_router?: ExpressRouter;
stack?: Layer[];
lazyrouter?: () => void;
settings?: unknown;
process_params: (
layer: Layer,
called: unknown,
req: PatchedRequest,
res: ExpressResponse,
done: () => void,
) => unknown;
};
/* Type used for pathing the express router prototype */
type Layer = {
match: (path: string) => boolean;
handle_request: (req: PatchedRequest, res: ExpressResponse, next: () => void) => void;
route?: { path: string };
path?: string;
};
interface ExpressResponse {
once(name: string, callback: () => void): void;
}
/**
* Internal helper for `__sentry_transaction`
* @hidden
*/
interface SentryTracingResponse {
__sentry_transaction?: Transaction;
}
/**
* Express integration
*
* Provides an request and error handler for Express framework as well as tracing capabilities
*/
export class Express implements Integration {
/**
* @inheritDoc
*/
public static id: string = 'Express';
/**
* @inheritDoc
*/
public name: string = Express.id;
/**
* Express App instance
*/
private readonly _router?: Router;
private readonly _methods?: Method[];
/**
* @inheritDoc
*/
public constructor(options: { app?: Router; router?: Router; methods?: Method[] } = {}) {
this._router = options.router || options.app;
this._methods = (Array.isArray(options.methods) ? options.methods : []).concat('use');
}
/**
* @inheritDoc
*/
public setupOnce(): void {
if (!this._router) {
__DEBUG_BUILD__ && logger.error('ExpressIntegration is missing an Express instance');
return;
}
instrumentMiddlewares(this._router, this._methods);
instrumentRouter(this._router as ExpressRouter);
}
}
/**
* Wraps original middleware function in a tracing call, which stores the info about the call as a span,
* and finishes it once the middleware is done invoking.
*
* Express middlewares have 3 various forms, thus we have to take care of all of them:
* // sync
* app.use(function (req, res) { ... })
* // async
* app.use(function (req, res, next) { ... })
* // error handler
* app.use(function (err, req, res, next) { ... })
*
* They all internally delegate to the `router[method]` of the given application instance.
*/
// eslint-disable-next-line @typescript-eslint/ban-types, @typescript-eslint/no-explicit-any
function wrap(fn: Function, method: Method): (...args: any[]) => void {
const arity = fn.length;
switch (arity) {
case 2: {
return function (this: NodeJS.Global, req: unknown, res: ExpressResponse & SentryTracingResponse): void {
const transaction = res.__sentry_transaction;
if (transaction) {
const span = transaction.startChild({
description: fn.name,
op: `express.middleware.${method}`,
});
res.once('finish', () => {
span.finish();
});
}
return fn.call(this, req, res);
};
}
case 3: {
return function (
this: NodeJS.Global,
req: unknown,
res: ExpressResponse & SentryTracingResponse,
next: () => void,
): void {
const transaction = res.__sentry_transaction;
const span = transaction?.startChild({
description: fn.name,
op: `express.middleware.${method}`,
});
fn.call(this, req, res, function (this: NodeJS.Global, ...args: unknown[]): void {
span?.finish();
next.call(this, ...args);
});
};
}
case 4: {
return function (
this: NodeJS.Global,
err: Error,
req: Request,
res: Response & SentryTracingResponse,
next: () => void,
): void {
const transaction = res.__sentry_transaction;
const span = transaction?.startChild({
description: fn.name,
op: `express.middleware.${method}`,
});
fn.call(this, err, req, res, function (this: NodeJS.Global, ...args: unknown[]): void {
span?.finish();
next.call(this, ...args);
});
};
}
default: {
throw new Error(`Express middleware takes 2-4 arguments. Got: ${arity}`);
}
}
}
/**
* Takes all the function arguments passed to the original `app` or `router` method, eg. `app.use` or `router.use`
* and wraps every function, as well as array of functions with a call to our `wrap` method.
* We have to take care of the arrays as well as iterate over all of the arguments,
* as `app.use` can accept middlewares in few various forms.
*
* app.use([<path>], <fn>)
* app.use([<path>], <fn>, ...<fn>)
* app.use([<path>], ...<fn>[])
*/
function wrapMiddlewareArgs(args: unknown[], method: Method): unknown[] {
return args.map((arg: unknown) => {
if (typeof arg === 'function') {
return wrap(arg, method);
}
if (Array.isArray(arg)) {
return arg.map((a: unknown) => {
if (typeof a === 'function') {
return wrap(a, method);
}
return a;
});
}
return arg;
});
}
/**
* Patches original router to utilize our tracing functionality
*/
function patchMiddleware(router: Router, method: Method): Router {
const originalCallback = router[method];
router[method] = function (...args: unknown[]): void {
return originalCallback.call(this, ...wrapMiddlewareArgs(args, method));
};
return router;
}
/**
* Patches original router methods
*/
function instrumentMiddlewares(router: Router, methods: Method[] = []): void {
methods.forEach((method: Method) => patchMiddleware(router, method));
}
/**
* Patches the prototype of Express.Router to accumulate the resolved route
* if a layer instance's `match` function was called and it returned a successful match.
*
* @see https://github.com/expressjs/express/blob/master/lib/router/index.js
*
* @param appOrRouter the router instance which can either be an app (i.e. top-level) or a (nested) router.
*/
function instrumentRouter(appOrRouter: ExpressRouter): void {
// This is how we can distinguish between app and routers
const isApp = 'settings' in appOrRouter;
// In case the app's top-level router hasn't been initialized yet, we have to do it now
if (isApp && appOrRouter._router === undefined && appOrRouter.lazyrouter) {
appOrRouter.lazyrouter();
}
const router = isApp ? appOrRouter._router : appOrRouter;
const routerProto = Object.getPrototypeOf(router) as ExpressRouter;
const originalProcessParams = routerProto.process_params;
routerProto.process_params = function process_params(
layer: Layer,
called: unknown,
req: PatchedRequest,
res: ExpressResponse & SentryTracingResponse,
done: () => unknown,
) {
// Base case: We're in the first part of the URL (thus we start with the root '/')
if (!req._reconstructedRoute) {
req._reconstructedRoute = '';
}
// If the layer's partial route has params, the route is stored in layer.route. Otherwise, the hardcoded path
// (i.e. a partial route without params) is stored in layer.path
const partialRoute = layer.route?.path || layer.path || '';
// Normalize the partial route so that it doesn't contain leading or trailing slashes
// and exclude empty or '*' wildcard routes.
// The exclusion of '*' routes is our best effort to not "pollute" the transaction name
// with interim handlers (e.g. ones that check authentication or do other middleware stuff).
// We want to end up with the parameterized URL of the incoming request without any extraneous path segments.
const finalPartialRoute = partialRoute
.split('/')
.filter(segment => segment.length > 0 && !segment.includes('*'))
.join('/');
// If we found a valid partial URL, we append it to the reconstructed route
if (finalPartialRoute.length > 0) {
req._reconstructedRoute += `/${finalPartialRoute}`;
}
// Now we check if we are in the "last" part of the route. We determine this by comparing the
// number of URL segments from the original URL to that of our reconstructed parameterized URL.
// If we've reached our final destination, we update the transaction name.
const urlLength = req.originalUrl?.split('/').filter(s => s.length > 0).length;
const routeLength = req._reconstructedRoute.split('/').filter(s => s.length > 0).length;
if (urlLength === routeLength) {
const transaction = res.__sentry_transaction;
if (transaction && transaction.metadata.source !== 'custom') {
// If the request URL is '/' or empty, the reconstructed route will be empty.
// Therefore, we fall back to setting the final route to '/' in this case.
const finalRoute = req._reconstructedRoute || '/';
transaction.setName(...extractPathForTransaction(req, { path: true, method: true, customRoute: finalRoute }));
}
}
return originalProcessParams.call(this, layer, called, req, res, done);
};
}