-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathnest.ts
295 lines (256 loc) · 8.89 KB
/
nest.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
import { isWrapped } from '@opentelemetry/core';
import type { InstrumentationConfig } from '@opentelemetry/instrumentation';
import {
InstrumentationBase,
InstrumentationNodeModuleDefinition,
InstrumentationNodeModuleFile,
} from '@opentelemetry/instrumentation';
import { NestInstrumentation } from '@opentelemetry/instrumentation-nestjs-core';
import {
SDK_VERSION,
SEMANTIC_ATTRIBUTE_SENTRY_OP,
SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,
captureException,
defineIntegration,
getActiveSpan,
getClient,
getDefaultIsolationScope,
getIsolationScope,
spanToJSON,
startSpanManual,
withActiveSpan,
} from '@sentry/core';
import type { IntegrationFn, Span } from '@sentry/types';
import { addNonEnumerableProperty, logger } from '@sentry/utils';
import { generateInstrumentOnce } from '../../otel/instrument';
interface MinimalNestJsExecutionContext {
getType: () => string;
switchToHttp: () => {
// minimal request object
// according to official types, all properties are required but
// let's play it safe and assume they're optional
getRequest: () => {
route?: {
path?: string;
};
method?: string;
};
};
}
interface NestJsErrorFilter {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
catch(exception: any, host: any): void;
}
interface MinimalNestJsApp {
useGlobalFilters: (arg0: NestJsErrorFilter) => void;
useGlobalInterceptors: (interceptor: {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
intercept: (context: MinimalNestJsExecutionContext, next: { handle: () => any }) => any;
}) => void;
}
const INTEGRATION_NAME = 'Nest';
const supportedVersions = ['>=8.0.0 <11'];
const sentryPatched = 'sentryPatched';
/**
* Represents an injectable target class in NestJS.
*/
export interface InjectableTarget {
name: string;
sentryPatched?: boolean;
prototype: {
use?: (req: unknown, res: unknown, next: () => void) => void;
};
}
/**
* Helper checking if a concrete target class is already patched.
*
* We already guard duplicate patching with isWrapped. However, isWrapped checks whether a file has been patched, whereas we use this check for concrete target classes.
* This check might not be necessary, but better to play it safe.
*/
export function isPatched(target: InjectableTarget): boolean {
if (target.sentryPatched) {
return true;
}
addNonEnumerableProperty(target, sentryPatched, true);
return false;
}
/**
* Custom instrumentation for nestjs.
*
* This hooks into the @Injectable decorator, which is applied on class middleware, interceptors and guards.
*/
export class SentryNestInstrumentation extends InstrumentationBase {
public static readonly COMPONENT = '@nestjs/common';
public static readonly COMMON_ATTRIBUTES = {
component: SentryNestInstrumentation.COMPONENT,
};
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(SentryNestInstrumentation.COMPONENT, supportedVersions);
moduleDef.files.push(this._getInjectableFileInstrumentation(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');
},
);
}
/**
* Creates a wrapper function for the @Injectable decorator.
*
* Wraps the use method to instrument nest class middleware.
*/
private _createWrapInjectable() {
// 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') {
// 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;
const prevSpan = getActiveSpan();
startSpanManual(
{
name: target.name,
attributes: {
[SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'middleware.nestjs',
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.middleware.nestjs',
},
},
(span: Span) => {
const nextProxy = new Proxy(next, {
apply: (originalNext, thisArgNext, argsNext) => {
span.end();
if (prevSpan) {
withActiveSpan(prevSpan, () => {
Reflect.apply(originalNext, thisArgNext, argsNext);
});
} else {
Reflect.apply(originalNext, thisArgNext, argsNext);
}
},
});
originalUse.apply(thisArgUse, [req, res, nextProxy, args]);
},
);
},
});
}
return original(options)(target);
};
};
};
}
}
const instrumentNestCore = generateInstrumentOnce('Nest-Core', () => {
return new NestInstrumentation();
});
const instrumentNestCommon = generateInstrumentOnce('Nest-Common', () => {
return new SentryNestInstrumentation();
});
export const instrumentNest = Object.assign(
(): void => {
instrumentNestCore();
instrumentNestCommon();
},
{ id: INTEGRATION_NAME },
);
const _nestIntegration = (() => {
return {
name: INTEGRATION_NAME,
setupOnce() {
instrumentNest();
},
};
}) satisfies IntegrationFn;
/**
* Nest framework integration
*
* Capture tracing data for nest.
*/
export const nestIntegration = defineIntegration(_nestIntegration);
/**
* Setup an error handler for Nest.
*/
export function setupNestErrorHandler(app: MinimalNestJsApp, baseFilter: NestJsErrorFilter): void {
// Sadly, NestInstrumentation has no requestHook, so we need to add the attributes here
// We register this hook in this method, because if we register it in the integration `setup`,
// it would always run even for users that are not even using Nest.js
const client = getClient();
if (client) {
client.on('spanStart', span => {
addNestSpanAttributes(span);
});
}
app.useGlobalInterceptors({
intercept(context, next) {
if (getIsolationScope() === getDefaultIsolationScope()) {
logger.warn('Isolation scope is still the default isolation scope, skipping setting transactionName.');
return next.handle();
}
if (context.getType() === 'http') {
const req = context.switchToHttp().getRequest();
if (req.route) {
getIsolationScope().setTransactionName(`${req.method?.toUpperCase() || 'GET'} ${req.route.path}`);
}
}
return next.handle();
},
});
const wrappedFilter = new Proxy(baseFilter, {
get(target, prop, receiver) {
if (prop === 'catch') {
const originalCatch = Reflect.get(target, prop, receiver);
return (exception: unknown, host: unknown) => {
const status_code = (exception as { status?: number }).status;
// don't report expected errors
if (status_code !== undefined) {
return originalCatch.apply(target, [exception, host]);
}
captureException(exception);
return originalCatch.apply(target, [exception, host]);
};
}
return Reflect.get(target, prop, receiver);
},
});
app.useGlobalFilters(wrappedFilter);
}
function addNestSpanAttributes(span: Span): void {
const attributes = spanToJSON(span).data || {};
// this is one of: app_creation, request_context, handler
const type = attributes['nestjs.type'];
// If this is already set, or we have no nest.js span, no need to process again...
if (attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP] || !type) {
return;
}
span.setAttributes({
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.otel.nestjs',
[SEMANTIC_ATTRIBUTE_SENTRY_OP]: `${type}.nestjs`,
});
}