-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathSentryHttpInstrumentation.ts
318 lines (273 loc) · 12.3 KB
/
SentryHttpInstrumentation.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
314
315
316
317
318
import type * as http from 'node:http';
import type { RequestOptions } from 'node:http';
import type * as https from 'node:https';
import { VERSION } from '@opentelemetry/core';
import type { InstrumentationConfig } from '@opentelemetry/instrumentation';
import { InstrumentationBase, InstrumentationNodeModuleDefinition } from '@opentelemetry/instrumentation';
import { getRequestInfo } from '@opentelemetry/instrumentation-http';
import { addBreadcrumb, getClient, getIsolationScope, withIsolationScope } from '@sentry/core';
import type { SanitizedRequestData } from '@sentry/types';
import {
getBreadcrumbLogLevelFromHttpStatusCode,
getSanitizedUrlString,
parseUrl,
stripUrlQueryAndFragment,
} from '@sentry/utils';
import type { NodeClient } from '../../sdk/client';
import { getRequestUrl } from '../../utils/getRequestUrl';
type Http = typeof http;
type Https = typeof https;
type SentryHttpInstrumentationOptions = InstrumentationConfig & {
/**
* Whether breadcrumbs should be recorded for requests.
*
* @default `true`
*/
breadcrumbs?: boolean;
/**
* Do not capture breadcrumbs for outgoing HTTP requests to URLs where the given callback returns `true`.
* For the scope of this instrumentation, this callback only controls breadcrumb creation.
* The same option can be passed to the top-level httpIntegration where it controls both, breadcrumb and
* span creation.
*
* @param url Contains the entire URL, including query string (if any), protocol, host, etc. of the outgoing request.
* @param request Contains the {@type RequestOptions} object used to make the outgoing request.
*/
ignoreOutgoingRequests?: (url: string, request: RequestOptions) => boolean;
};
/**
* This custom HTTP instrumentation is used to isolate incoming requests and annotate them with additional information.
* It does not emit any spans.
*
* The reason this is isolated from the OpenTelemetry instrumentation is that users may overwrite this,
* which would lead to Sentry not working as expected.
*
* Important note: Contrary to other OTEL instrumentation, this one cannot be unwrapped.
* It only does minimal things though and does not emit any spans.
*
* This is heavily inspired & adapted from:
* https://github.com/open-telemetry/opentelemetry-js/blob/f8ab5592ddea5cba0a3b33bf8d74f27872c0367f/experimental/packages/opentelemetry-instrumentation-http/src/http.ts
*/
export class SentryHttpInstrumentation extends InstrumentationBase<SentryHttpInstrumentationOptions> {
public constructor(config: SentryHttpInstrumentationOptions = {}) {
super('@sentry/instrumentation-http', VERSION, config);
}
/** @inheritdoc */
public init(): [InstrumentationNodeModuleDefinition, InstrumentationNodeModuleDefinition] {
return [this._getHttpsInstrumentation(), this._getHttpInstrumentation()];
}
/** Get the instrumentation for the http module. */
private _getHttpInstrumentation(): InstrumentationNodeModuleDefinition {
return new InstrumentationNodeModuleDefinition(
'http',
['*'],
(moduleExports: Http): Http => {
// Patch incoming requests for request isolation
stealthWrap(moduleExports.Server.prototype, 'emit', this._getPatchIncomingRequestFunction());
// Patch outgoing requests for breadcrumbs
const patchedRequest = stealthWrap(moduleExports, 'request', this._getPatchOutgoingRequestFunction());
stealthWrap(moduleExports, 'get', this._getPatchOutgoingGetFunction(patchedRequest));
return moduleExports;
},
() => {
// no unwrap here
},
);
}
/** Get the instrumentation for the https module. */
private _getHttpsInstrumentation(): InstrumentationNodeModuleDefinition {
return new InstrumentationNodeModuleDefinition(
'https',
['*'],
(moduleExports: Https): Https => {
// Patch incoming requests for request isolation
stealthWrap(moduleExports.Server.prototype, 'emit', this._getPatchIncomingRequestFunction());
// Patch outgoing requests for breadcrumbs
const patchedRequest = stealthWrap(moduleExports, 'request', this._getPatchOutgoingRequestFunction());
stealthWrap(moduleExports, 'get', this._getPatchOutgoingGetFunction(patchedRequest));
return moduleExports;
},
() => {
// no unwrap here
},
);
}
/**
* Patch the incoming request function for request isolation.
*/
private _getPatchIncomingRequestFunction(): (
original: (event: string, ...args: unknown[]) => boolean,
) => (this: unknown, event: string, ...args: unknown[]) => boolean {
// eslint-disable-next-line @typescript-eslint/no-this-alias
const instrumentation = this;
return (
original: (event: string, ...args: unknown[]) => boolean,
): ((this: unknown, event: string, ...args: unknown[]) => boolean) => {
return function incomingRequest(this: unknown, event: string, ...args: unknown[]): boolean {
// Only traces request events
if (event !== 'request') {
return original.apply(this, [event, ...args]);
}
instrumentation._diag.debug('http instrumentation for incoming request');
const request = args[0] as http.IncomingMessage;
const isolationScope = getIsolationScope().clone();
// Update the isolation scope, isolate this request
isolationScope.setSDKProcessingMetadata({ request });
const client = getClient<NodeClient>();
if (client && client.getOptions().autoSessionTracking) {
isolationScope.setRequestSession({ status: 'ok' });
}
// attempt to update the scope's `transactionName` based on the request URL
// Ideally, framework instrumentations coming after the HttpInstrumentation
// update the transactionName once we get a parameterized route.
const httpMethod = (request.method || 'GET').toUpperCase();
const httpTarget = stripUrlQueryAndFragment(request.url || '/');
const bestEffortTransactionName = `${httpMethod} ${httpTarget}`;
isolationScope.setTransactionName(bestEffortTransactionName);
return withIsolationScope(isolationScope, () => {
return original.apply(this, [event, ...args]);
});
};
};
}
/**
* Patch the outgoing request function for breadcrumbs.
*/
private _getPatchOutgoingRequestFunction(): (
// eslint-disable-next-line @typescript-eslint/no-explicit-any
original: (...args: any[]) => http.ClientRequest,
) => (options: URL | http.RequestOptions | string, ...args: unknown[]) => http.ClientRequest {
// eslint-disable-next-line @typescript-eslint/no-this-alias
const instrumentation = this;
return (original: (...args: unknown[]) => http.ClientRequest): ((...args: unknown[]) => http.ClientRequest) => {
return function outgoingRequest(this: unknown, ...args: unknown[]): http.ClientRequest {
instrumentation._diag.debug('http instrumentation for outgoing requests');
// Making a copy to avoid mutating the original args array
// We need to access and reconstruct the request options object passed to `ignoreOutgoingRequests`
// so that it matches what Otel instrumentation passes to `ignoreOutgoingRequestHook`.
// @see https://github.com/open-telemetry/opentelemetry-js/blob/7293e69c1e55ca62e15d0724d22605e61bd58952/experimental/packages/opentelemetry-instrumentation-http/src/http.ts#L756-L789
const argsCopy = [...args];
const options = argsCopy.shift() as URL | http.RequestOptions | string;
const extraOptions =
typeof argsCopy[0] === 'object' && (typeof options === 'string' || options instanceof URL)
? (argsCopy.shift() as http.RequestOptions)
: undefined;
const { optionsParsed } = getRequestInfo(options, extraOptions);
const request = original.apply(this, args) as ReturnType<typeof http.request>;
request.prependListener('response', (response: http.IncomingMessage) => {
const _breadcrumbs = instrumentation.getConfig().breadcrumbs;
const breadCrumbsEnabled = typeof _breadcrumbs === 'undefined' ? true : _breadcrumbs;
const _ignoreOutgoingRequests = instrumentation.getConfig().ignoreOutgoingRequests;
const shouldCreateBreadcrumb =
typeof _ignoreOutgoingRequests === 'function'
? !_ignoreOutgoingRequests(getRequestUrl(request), optionsParsed)
: true;
if (breadCrumbsEnabled && shouldCreateBreadcrumb) {
addRequestBreadcrumb(request, response);
}
});
return request;
};
};
}
/** Path the outgoing get function for breadcrumbs. */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private _getPatchOutgoingGetFunction(clientRequest: (...args: any[]) => http.ClientRequest) {
return (_original: unknown): ((...args: unknown[]) => http.ClientRequest) => {
// Re-implement http.get. This needs to be done (instead of using
// getPatchOutgoingRequestFunction to patch it) because we need to
// set the trace context header before the returned http.ClientRequest is
// ended. The Node.js docs state that the only differences between
// request and get are that (1) get defaults to the HTTP GET method and
// (2) the returned request object is ended immediately. The former is
// already true (at least in supported Node versions up to v10), so we
// simply follow the latter. Ref:
// https://nodejs.org/dist/latest/docs/api/http.html#http_http_get_options_callback
// https://github.com/googleapis/cloud-trace-nodejs/blob/master/src/instrumentations/instrumentation-http.ts#L198
return function outgoingGetRequest(...args: unknown[]): http.ClientRequest {
const req = clientRequest(...args);
req.end();
return req;
};
};
}
}
/**
* This is a minimal version of `wrap` from shimmer:
* https://github.com/othiym23/shimmer/blob/master/index.js
*
* In contrast to the original implementation, this version does not allow to unwrap,
* and does not make it clear that the method is wrapped.
* This is necessary because we want to wrap the http module with our own code,
* while still allowing to use the HttpInstrumentation from OTEL.
*
* Without this, if we'd just use `wrap` from shimmer, the OTEL instrumentation would remove our wrapping,
* because it only allows any module to be wrapped a single time.
*/
function stealthWrap<Nodule extends object, FieldName extends keyof Nodule>(
nodule: Nodule,
name: FieldName,
wrapper: (original: Nodule[FieldName]) => Nodule[FieldName],
): Nodule[FieldName] {
const original = nodule[name];
const wrapped = wrapper(original);
defineProperty(nodule, name, wrapped);
return wrapped;
}
// Sets a property on an object, preserving its enumerability.
function defineProperty<Nodule extends object, FieldName extends keyof Nodule>(
obj: Nodule,
name: FieldName,
value: Nodule[FieldName],
): void {
const enumerable = !!obj[name] && Object.prototype.propertyIsEnumerable.call(obj, name);
Object.defineProperty(obj, name, {
configurable: true,
enumerable: enumerable,
writable: true,
value: value,
});
}
/** Add a breadcrumb for outgoing requests. */
function addRequestBreadcrumb(request: http.ClientRequest, response: http.IncomingMessage): void {
const data = getBreadcrumbData(request);
const statusCode = response.statusCode;
const level = getBreadcrumbLogLevelFromHttpStatusCode(statusCode);
addBreadcrumb(
{
category: 'http',
data: {
status_code: statusCode,
...data,
},
type: 'http',
level,
},
{
event: 'response',
request,
response,
},
);
}
function getBreadcrumbData(request: http.ClientRequest): Partial<SanitizedRequestData> {
try {
// `request.host` does not contain the port, but the host header does
const host = request.getHeader('host') || request.host;
const url = new URL(request.path, `${request.protocol}//${host}`);
const parsedUrl = parseUrl(url.toString());
const data: Partial<SanitizedRequestData> = {
url: getSanitizedUrlString(parsedUrl),
'http.method': request.method || 'GET',
};
if (parsedUrl.search) {
data['http.query'] = parsedUrl.search;
}
if (parsedUrl.hash) {
data['http.fragment'] = parsedUrl.hash;
}
return data;
} catch {
return {};
}
}