-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathsentry-nest-instrumentation.ts
304 lines (263 loc) · 11.5 KB
/
sentry-nest-instrumentation.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
import type { InstrumentationConfig } from '@opentelemetry/instrumentation';
import {
InstrumentationBase,
InstrumentationNodeModuleDefinition,
InstrumentationNodeModuleFile,
isWrapped,
} from '@opentelemetry/instrumentation';
import type { Span } from '@sentry/core';
import {
SDK_VERSION,
getActiveSpan,
isThenable,
startInactiveSpan,
startSpan,
startSpanManual,
withActiveSpan,
} from '@sentry/core';
import { getMiddlewareSpanOptions, getNextProxy, instrumentObservable, isPatched } from './helpers';
import type { CallHandler, CatchTarget, InjectableTarget, MinimalNestJsExecutionContext, Observable } from './types';
const supportedVersions = ['>=8.0.0 <12'];
const COMPONENT = '@nestjs/common';
/**
* Custom instrumentation for nestjs.
*
* This hooks into
* 1. @Injectable decorator, which is applied on class middleware, interceptors and guards.
* 2. @Catch decorator, which is applied on exception filters.
*/
export class SentryNestInstrumentation extends InstrumentationBase {
public constructor(config: InstrumentationConfig = {}) {
super('sentry-nestjs', SDK_VERSION, config);
}
/**
* Initializes the instrumentation by defining the modules to be patched.
*/
public init(): InstrumentationNodeModuleDefinition {
const moduleDef = new InstrumentationNodeModuleDefinition(COMPONENT, supportedVersions);
moduleDef.files.push(
this._getInjectableFileInstrumentation(supportedVersions),
this._getCatchFileInstrumentation(supportedVersions),
);
return moduleDef;
}
/**
* Wraps the @Injectable decorator.
*/
private _getInjectableFileInstrumentation(versions: string[]): InstrumentationNodeModuleFile {
return new InstrumentationNodeModuleFile(
'@nestjs/common/decorators/core/injectable.decorator.js',
versions,
(moduleExports: { Injectable: InjectableTarget }) => {
if (isWrapped(moduleExports.Injectable)) {
this._unwrap(moduleExports, 'Injectable');
}
this._wrap(moduleExports, 'Injectable', this._createWrapInjectable());
return moduleExports;
},
(moduleExports: { Injectable: InjectableTarget }) => {
this._unwrap(moduleExports, 'Injectable');
},
);
}
/**
* Wraps the @Catch decorator.
*/
private _getCatchFileInstrumentation(versions: string[]): InstrumentationNodeModuleFile {
return new InstrumentationNodeModuleFile(
'@nestjs/common/decorators/core/catch.decorator.js',
versions,
(moduleExports: { Catch: CatchTarget }) => {
if (isWrapped(moduleExports.Catch)) {
this._unwrap(moduleExports, 'Catch');
}
this._wrap(moduleExports, 'Catch', this._createWrapCatch());
return moduleExports;
},
(moduleExports: { Catch: CatchTarget }) => {
this._unwrap(moduleExports, 'Catch');
},
);
}
/**
* Creates a wrapper function for the @Injectable decorator.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private _createWrapInjectable(): (original: any) => (options?: unknown) => (target: InjectableTarget) => any {
const SeenNestjsContextSet = new WeakSet<MinimalNestJsExecutionContext>();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return function wrapInjectable(original: any) {
return function wrappedInjectable(options?: unknown) {
return function (target: InjectableTarget) {
// patch middleware
if (typeof target.prototype.use === 'function' && !target.__SENTRY_INTERNAL__) {
// patch only once
if (isPatched(target)) {
return original(options)(target);
}
target.prototype.use = new Proxy(target.prototype.use, {
apply: (originalUse, thisArgUse, argsUse) => {
const [req, res, next, ...args] = argsUse;
// Check that we can reasonably assume that the target is a middleware.
// Without these guards, instrumentation will fail if a function named 'use' on a service, which is
// decorated with @Injectable, is called.
if (!req || !res || !next || typeof next !== 'function') {
return originalUse.apply(thisArgUse, argsUse);
}
const prevSpan = getActiveSpan();
return startSpanManual(getMiddlewareSpanOptions(target), (span: Span) => {
// proxy next to end span on call
const nextProxy = getNextProxy(next, span, prevSpan);
return originalUse.apply(thisArgUse, [req, res, nextProxy, args]);
});
},
});
}
// patch guards
if (typeof target.prototype.canActivate === 'function' && !target.__SENTRY_INTERNAL__) {
// patch only once
if (isPatched(target)) {
return original(options)(target);
}
target.prototype.canActivate = new Proxy(target.prototype.canActivate, {
apply: (originalCanActivate, thisArgCanActivate, argsCanActivate) => {
const context = argsCanActivate[0];
if (!context) {
return originalCanActivate.apply(thisArgCanActivate, argsCanActivate);
}
return startSpan(getMiddlewareSpanOptions(target), () => {
return originalCanActivate.apply(thisArgCanActivate, argsCanActivate);
});
},
});
}
// patch pipes
if (typeof target.prototype.transform === 'function' && !target.__SENTRY_INTERNAL__) {
if (isPatched(target)) {
return original(options)(target);
}
target.prototype.transform = new Proxy(target.prototype.transform, {
apply: (originalTransform, thisArgTransform, argsTransform) => {
const value = argsTransform[0];
const metadata = argsTransform[1];
if (!value || !metadata) {
return originalTransform.apply(thisArgTransform, argsTransform);
}
return startSpan(getMiddlewareSpanOptions(target), () => {
return originalTransform.apply(thisArgTransform, argsTransform);
});
},
});
}
// patch interceptors
if (typeof target.prototype.intercept === 'function' && !target.__SENTRY_INTERNAL__) {
if (isPatched(target)) {
return original(options)(target);
}
target.prototype.intercept = new Proxy(target.prototype.intercept, {
apply: (originalIntercept, thisArgIntercept, argsIntercept) => {
const context = argsIntercept[0] as MinimalNestJsExecutionContext | undefined;
const next = argsIntercept[1] as CallHandler | undefined;
const parentSpan = getActiveSpan();
let afterSpan: Span | undefined;
// Check that we can reasonably assume that the target is an interceptor.
if (!context || !next || typeof next.handle !== 'function') {
return originalIntercept.apply(thisArgIntercept, argsIntercept);
}
return startSpanManual(getMiddlewareSpanOptions(target), (beforeSpan: Span) => {
// eslint-disable-next-line @typescript-eslint/unbound-method
next.handle = new Proxy(next.handle, {
apply: (originalHandle, thisArgHandle, argsHandle) => {
beforeSpan.end();
if (parentSpan) {
return withActiveSpan(parentSpan, () => {
const handleReturnObservable = Reflect.apply(originalHandle, thisArgHandle, argsHandle);
if (!SeenNestjsContextSet.has(context)) {
SeenNestjsContextSet.add(context);
afterSpan = startInactiveSpan(
getMiddlewareSpanOptions(target, 'Interceptors - After Route'),
);
}
return handleReturnObservable;
});
} else {
const handleReturnObservable = Reflect.apply(originalHandle, thisArgHandle, argsHandle);
if (!SeenNestjsContextSet.has(context)) {
SeenNestjsContextSet.add(context);
afterSpan = startInactiveSpan(getMiddlewareSpanOptions(target, 'Interceptors - After Route'));
}
return handleReturnObservable;
}
},
});
let returnedObservableInterceptMaybePromise: Observable<unknown> | Promise<Observable<unknown>>;
try {
returnedObservableInterceptMaybePromise = originalIntercept.apply(thisArgIntercept, argsIntercept);
} catch (e) {
beforeSpan.end();
afterSpan?.end();
throw e;
}
if (!afterSpan) {
return returnedObservableInterceptMaybePromise;
}
// handle async interceptor
if (isThenable(returnedObservableInterceptMaybePromise)) {
return returnedObservableInterceptMaybePromise.then(
observable => {
instrumentObservable(observable, afterSpan ?? parentSpan);
return observable;
},
e => {
beforeSpan.end();
afterSpan?.end();
throw e;
},
);
}
// handle sync interceptor
if (typeof returnedObservableInterceptMaybePromise.subscribe === 'function') {
instrumentObservable(returnedObservableInterceptMaybePromise, afterSpan);
}
return returnedObservableInterceptMaybePromise;
});
},
});
}
return original(options)(target);
};
};
};
}
/**
* Creates a wrapper function for the @Catch decorator. Used to instrument exception filters.
*/
private _createWrapCatch() {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return function wrapCatch(original: any) {
return function wrappedCatch(...exceptions: unknown[]) {
return function (target: CatchTarget) {
if (typeof target.prototype.catch === 'function' && !target.__SENTRY_INTERNAL__) {
// patch only once
if (isPatched(target)) {
return original(...exceptions)(target);
}
target.prototype.catch = new Proxy(target.prototype.catch, {
apply: (originalCatch, thisArgCatch, argsCatch) => {
const exception = argsCatch[0];
const host = argsCatch[1];
if (!exception || !host) {
return originalCatch.apply(thisArgCatch, argsCatch);
}
return startSpan(getMiddlewareSpanOptions(target), () => {
return originalCatch.apply(thisArgCatch, argsCatch);
});
},
});
}
return original(...exceptions)(target);
};
};
};
}
}