/
express.ts
213 lines (195 loc) · 5.42 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
import { Integration, Transaction } from '@sentry/types';
import { 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
};
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) {
logger.error('ExpressIntegration is missing an Express instance');
return;
}
instrumentMiddlewares(this._router, this._methods);
}
}
/**
* 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: `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: `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: `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));
}