-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
index.ts
348 lines (296 loc) · 9.75 KB
/
index.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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
import type { SentrySpan } from '@sentry/core';
import {
SPAN_STATUS_ERROR,
addBreadcrumb,
defineIntegration,
getActiveSpan,
getClient,
getCurrentScope,
getDynamicSamplingContextFromClient,
getDynamicSamplingContextFromSpan,
getIsolationScope,
hasTracingEnabled,
isSentryRequestUrl,
setHttpStatus,
spanToTraceHeader,
} from '@sentry/core';
import type { EventProcessor, Integration, IntegrationFn, IntegrationFnResult, Span } from '@sentry/types';
import {
LRUMap,
dynamicSamplingContextToSentryBaggageHeader,
generateSentryTraceHeader,
getSanitizedUrlString,
parseUrl,
stringMatchesSomePattern,
} from '@sentry/utils';
import type { NodeClient } from '../../client';
import { NODE_VERSION } from '../../nodeVersion';
import type {
DiagnosticsChannel,
RequestCreateMessage,
RequestEndMessage,
RequestErrorMessage,
RequestWithSentry,
} from './types';
export enum ChannelName {
// https://github.com/nodejs/undici/blob/e6fc80f809d1217814c044f52ed40ef13f21e43c/docs/api/DiagnosticsChannel.md#undicirequestcreate
RequestCreate = 'undici:request:create',
RequestEnd = 'undici:request:headers',
RequestError = 'undici:request:error',
}
export interface UndiciOptions {
/**
* Whether breadcrumbs should be recorded for requests
* Defaults to true
*/
breadcrumbs: boolean;
/**
* Whether tracing spans should be created for requests
* If not set, this will be enabled/disabled based on if tracing is enabled.
*/
tracing?: boolean;
/**
* Function determining whether or not to create spans to track outgoing requests to the given URL.
* By default, spans will be created for all outgoing requests.
*/
shouldCreateSpanForRequest?: (url: string) => boolean;
}
// Please note that you cannot use `console.log` to debug the callbacks registered to the `diagnostics_channel` API.
// To debug, you can use `writeFileSync` to write to a file:
// https://nodejs.org/api/async_hooks.html#printing-in-asynchook-callbacks
//
// import { writeFileSync } from 'fs';
// import { format } from 'util';
//
// function debug(...args: any): void {
// // Use a function like this one when debugging inside an AsyncHook callback
// // @ts-expect-error any
// writeFileSync('log.out', `${format(...args)}\n`, { flag: 'a' });
// }
const _nativeNodeFetchintegration = ((options?: Partial<UndiciOptions>) => {
// eslint-disable-next-line deprecation/deprecation
return new Undici(options) as unknown as IntegrationFnResult;
}) satisfies IntegrationFn;
export const nativeNodeFetchintegration = defineIntegration(_nativeNodeFetchintegration);
/**
* Instruments outgoing HTTP requests made with the `undici` package via
* Node's `diagnostics_channel` API.
*
* Supports Undici 4.7.0 or higher.
*
* Requires Node 16.17.0 or higher.
*
* @deprecated Use `nativeNodeFetchintegration()` instead.
*/
export class Undici implements Integration {
/**
* @inheritDoc
*/
public static id: string = 'Undici';
/**
* @inheritDoc
*/
// eslint-disable-next-line deprecation/deprecation
public name: string = Undici.id;
private readonly _options: UndiciOptions;
private readonly _createSpanUrlMap: LRUMap<string, boolean> = new LRUMap(100);
private readonly _headersUrlMap: LRUMap<string, boolean> = new LRUMap(100);
public constructor(_options: Partial<UndiciOptions> = {}) {
this._options = {
breadcrumbs: _options.breadcrumbs === undefined ? true : _options.breadcrumbs,
tracing: _options.tracing,
shouldCreateSpanForRequest: _options.shouldCreateSpanForRequest,
};
}
/**
* @inheritDoc
*/
public setupOnce(_addGlobalEventProcessor: (callback: EventProcessor) => void): void {
// Requires Node 16+ to use the diagnostics_channel API.
if (NODE_VERSION.major < 16) {
return;
}
let ds: DiagnosticsChannel | undefined;
try {
// eslint-disable-next-line @typescript-eslint/no-var-requires
ds = require('diagnostics_channel') as DiagnosticsChannel;
} catch (e) {
// no-op
}
if (!ds || !ds.subscribe) {
return;
}
// https://github.com/nodejs/undici/blob/e6fc80f809d1217814c044f52ed40ef13f21e43c/docs/api/DiagnosticsChannel.md
ds.subscribe(ChannelName.RequestCreate, this._onRequestCreate);
ds.subscribe(ChannelName.RequestEnd, this._onRequestEnd);
ds.subscribe(ChannelName.RequestError, this._onRequestError);
}
/** Helper that wraps shouldCreateSpanForRequest option */
private _shouldCreateSpan(url: string): boolean {
if (this._options.tracing === false || (this._options.tracing === undefined && !hasTracingEnabled())) {
return false;
}
if (this._options.shouldCreateSpanForRequest === undefined) {
return true;
}
const cachedDecision = this._createSpanUrlMap.get(url);
if (cachedDecision !== undefined) {
return cachedDecision;
}
const decision = this._options.shouldCreateSpanForRequest(url);
this._createSpanUrlMap.set(url, decision);
return decision;
}
private _onRequestCreate = (message: unknown): void => {
// eslint-disable-next-line deprecation/deprecation
if (!getClient()?.getIntegration(Undici)) {
return;
}
const { request } = message as RequestCreateMessage;
const stringUrl = request.origin ? request.origin.toString() + request.path : request.path;
const client = getClient<NodeClient>();
if (!client) {
return;
}
if (isSentryRequestUrl(stringUrl, client) || request.__sentry_span__ !== undefined) {
return;
}
const clientOptions = client.getOptions();
const scope = getCurrentScope();
const isolationScope = getIsolationScope();
const parentSpan = getActiveSpan() as SentrySpan;
const span = this._shouldCreateSpan(stringUrl) ? createRequestSpan(parentSpan, request, stringUrl) : undefined;
if (span) {
request.__sentry_span__ = span;
}
const shouldAttachTraceData = (url: string): boolean => {
if (clientOptions.tracePropagationTargets === undefined) {
return true;
}
const cachedDecision = this._headersUrlMap.get(url);
if (cachedDecision !== undefined) {
return cachedDecision;
}
const decision = stringMatchesSomePattern(url, clientOptions.tracePropagationTargets);
this._headersUrlMap.set(url, decision);
return decision;
};
if (shouldAttachTraceData(stringUrl)) {
const { traceId, spanId, sampled, dsc } = {
...isolationScope.getPropagationContext(),
...scope.getPropagationContext(),
};
const sentryTraceHeader = span ? spanToTraceHeader(span) : generateSentryTraceHeader(traceId, spanId, sampled);
const sentryBaggageHeader = dynamicSamplingContextToSentryBaggageHeader(
dsc || (span ? getDynamicSamplingContextFromSpan(span) : getDynamicSamplingContextFromClient(traceId, client)),
);
setHeadersOnRequest(request, sentryTraceHeader, sentryBaggageHeader);
}
};
private _onRequestEnd = (message: unknown): void => {
// eslint-disable-next-line deprecation/deprecation
if (!getClient()?.getIntegration(Undici)) {
return;
}
const { request, response } = message as RequestEndMessage;
const stringUrl = request.origin ? request.origin.toString() + request.path : request.path;
if (isSentryRequestUrl(stringUrl, getClient())) {
return;
}
const span = request.__sentry_span__;
if (span) {
setHttpStatus(span, response.statusCode);
span.end();
}
if (this._options.breadcrumbs) {
addBreadcrumb(
{
category: 'http',
data: {
method: request.method,
status_code: response.statusCode,
url: stringUrl,
},
type: 'http',
},
{
event: 'response',
request,
response,
},
);
}
};
private _onRequestError = (message: unknown): void => {
// eslint-disable-next-line deprecation/deprecation
if (!getClient()?.getIntegration(Undici)) {
return;
}
const { request } = message as RequestErrorMessage;
const stringUrl = request.origin ? request.origin.toString() + request.path : request.path;
if (isSentryRequestUrl(stringUrl, getClient())) {
return;
}
const span = request.__sentry_span__;
if (span) {
span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });
span.end();
}
if (this._options.breadcrumbs) {
addBreadcrumb(
{
category: 'http',
data: {
method: request.method,
url: stringUrl,
},
level: 'error',
type: 'http',
},
{
event: 'error',
request,
},
);
}
};
}
function setHeadersOnRequest(
request: RequestWithSentry,
sentryTrace: string,
sentryBaggageHeader: string | undefined,
): void {
const headerLines = request.headers.split('\r\n');
const hasSentryHeaders = headerLines.some(headerLine => headerLine.startsWith('sentry-trace:'));
if (hasSentryHeaders) {
return;
}
request.addHeader('sentry-trace', sentryTrace);
if (sentryBaggageHeader) {
request.addHeader('baggage', sentryBaggageHeader);
}
}
function createRequestSpan(
activeSpan: SentrySpan | undefined,
request: RequestWithSentry,
stringUrl: string,
): Span | undefined {
const url = parseUrl(stringUrl);
const method = request.method || 'GET';
const data: Record<string, unknown> = {
'http.method': method,
};
if (url.search) {
data['http.query'] = url.search;
}
if (url.hash) {
data['http.fragment'] = url.hash;
}
// eslint-disable-next-line deprecation/deprecation
return activeSpan?.startChild({
op: 'http.client',
origin: 'auto.http.node.undici',
name: `${method} ${getSanitizedUrlString(url)}`,
data,
});
}