-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathrequest.ts
370 lines (325 loc) · 12.5 KB
/
request.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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
/* eslint-disable max-lines */
import {
SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,
getClient,
getCurrentScope,
getDynamicSamplingContextFromClient,
getDynamicSamplingContextFromSpan,
getIsolationScope,
hasTracingEnabled,
setHttpStatus,
spanToJSON,
spanToTraceHeader,
startInactiveSpan,
} from '@sentry/core';
import type { HandlerDataXhr, SentryWrappedXMLHttpRequest, Span } from '@sentry/types';
import {
BAGGAGE_HEADER_NAME,
SENTRY_XHR_DATA_KEY,
addFetchInstrumentationHandler,
addXhrInstrumentationHandler,
browserPerformanceTimeOrigin,
dynamicSamplingContextToSentryBaggageHeader,
generateSentryTraceHeader,
parseUrl,
stringMatchesSomePattern,
} from '@sentry/utils';
import { instrumentFetchRequest } from '../common/fetch';
import { addPerformanceInstrumentationHandler } from './instrument';
import { WINDOW } from './types';
export const DEFAULT_TRACE_PROPAGATION_TARGETS = ['localhost', /^\/(?!\/)/];
/** Options for Request Instrumentation */
export interface RequestInstrumentationOptions {
/**
* @deprecated Will be removed in v8.
* Use `shouldCreateSpanForRequest` to control span creation and `tracePropagationTargets` to control
* trace header attachment.
*/
tracingOrigins: Array<string | RegExp>;
/**
* List of strings and/or regexes used to determine which outgoing requests will have `sentry-trace` and `baggage`
* headers attached.
*
* @deprecated Use the top-level `tracePropagationTargets` option in `Sentry.init` instead.
* This option will be removed in v8.
*
* Default: ['localhost', /^\//] @see {DEFAULT_TRACE_PROPAGATION_TARGETS}
*/
tracePropagationTargets: Array<string | RegExp>;
/**
* Flag to disable patching all together for fetch requests.
*
* Default: true
*/
traceFetch: boolean;
/**
* Flag to disable patching all together for xhr requests.
*
* Default: true
*/
traceXHR: boolean;
/**
* If true, Sentry will capture http timings and add them to the corresponding http spans.
*
* Default: true
*/
enableHTTPTimings: boolean;
/**
* This function will be called before creating a span for a request with the given url.
* Return false if you don't want a span for the given url.
*
* Default: (url: string) => true
*/
shouldCreateSpanForRequest?(this: void, url: string): boolean;
}
export const defaultRequestInstrumentationOptions: RequestInstrumentationOptions = {
traceFetch: true,
traceXHR: true,
enableHTTPTimings: true,
// TODO (v8): Remove this property
tracingOrigins: DEFAULT_TRACE_PROPAGATION_TARGETS,
tracePropagationTargets: DEFAULT_TRACE_PROPAGATION_TARGETS,
};
/** Registers span creators for xhr and fetch requests */
export function instrumentOutgoingRequests(_options?: Partial<RequestInstrumentationOptions>): void {
const {
traceFetch,
traceXHR,
// eslint-disable-next-line deprecation/deprecation
tracePropagationTargets,
// eslint-disable-next-line deprecation/deprecation
tracingOrigins,
shouldCreateSpanForRequest,
enableHTTPTimings,
} = {
traceFetch: defaultRequestInstrumentationOptions.traceFetch,
traceXHR: defaultRequestInstrumentationOptions.traceXHR,
..._options,
};
const shouldCreateSpan =
typeof shouldCreateSpanForRequest === 'function' ? shouldCreateSpanForRequest : (_: string) => true;
// TODO(v8) Remove tracingOrigins here
// The only reason we're passing it in here is because this instrumentOutgoingRequests function is publicly exported
// and we don't want to break the API. We can remove it in v8.
const shouldAttachHeadersWithTargets = (url: string): boolean =>
shouldAttachHeaders(url, tracePropagationTargets || tracingOrigins);
const spans: Record<string, Span> = {};
if (traceFetch) {
addFetchInstrumentationHandler(handlerData => {
const createdSpan = instrumentFetchRequest(handlerData, shouldCreateSpan, shouldAttachHeadersWithTargets, spans);
// We cannot use `window.location` in the generic fetch instrumentation,
// but we need it for reliable `server.address` attribute.
// so we extend this in here
if (createdSpan) {
const fullUrl = getFullURL(handlerData.fetchData.url);
const host = fullUrl ? parseUrl(fullUrl).host : undefined;
createdSpan.setAttributes({
'http.url': fullUrl,
'server.address': host,
});
}
if (enableHTTPTimings && createdSpan) {
addHTTPTimings(createdSpan);
}
});
}
if (traceXHR) {
addXhrInstrumentationHandler(handlerData => {
const createdSpan = xhrCallback(handlerData, shouldCreateSpan, shouldAttachHeadersWithTargets, spans);
if (enableHTTPTimings && createdSpan) {
addHTTPTimings(createdSpan);
}
});
}
}
function isPerformanceResourceTiming(entry: PerformanceEntry): entry is PerformanceResourceTiming {
return (
entry.entryType === 'resource' &&
'initiatorType' in entry &&
typeof (entry as PerformanceResourceTiming).nextHopProtocol === 'string' &&
(entry.initiatorType === 'fetch' || entry.initiatorType === 'xmlhttprequest')
);
}
/**
* Creates a temporary observer to listen to the next fetch/xhr resourcing timings,
* so that when timings hit their per-browser limit they don't need to be removed.
*
* @param span A span that has yet to be finished, must contain `url` on data.
*/
function addHTTPTimings(span: Span): void {
const { url } = spanToJSON(span).data || {};
if (!url || typeof url !== 'string') {
return;
}
const cleanup = addPerformanceInstrumentationHandler('resource', ({ entries }) => {
entries.forEach(entry => {
if (isPerformanceResourceTiming(entry) && entry.name.endsWith(url)) {
const spanData = resourceTimingEntryToSpanData(entry);
spanData.forEach(data => span.setAttribute(...data));
// In the next tick, clean this handler up
// We have to wait here because otherwise this cleans itself up before it is fully done
setTimeout(cleanup);
}
});
});
}
/**
* Converts ALPN protocol ids to name and version.
*
* (https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids)
* @param nextHopProtocol PerformanceResourceTiming.nextHopProtocol
*/
export function extractNetworkProtocol(nextHopProtocol: string): { name: string; version: string } {
let name = 'unknown';
let version = 'unknown';
let _name = '';
for (const char of nextHopProtocol) {
// http/1.1 etc.
if (char === '/') {
[name, version] = nextHopProtocol.split('/');
break;
}
// h2, h3 etc.
if (!isNaN(Number(char))) {
name = _name === 'h' ? 'http' : _name;
version = nextHopProtocol.split(_name)[1];
break;
}
_name += char;
}
if (_name === nextHopProtocol) {
// webrtc, ftp, etc.
name = _name;
}
return { name, version };
}
function getAbsoluteTime(time: number = 0): number {
return ((browserPerformanceTimeOrigin || performance.timeOrigin) + time) / 1000;
}
function resourceTimingEntryToSpanData(resourceTiming: PerformanceResourceTiming): [string, string | number][] {
const { name, version } = extractNetworkProtocol(resourceTiming.nextHopProtocol);
const timingSpanData: [string, string | number][] = [];
timingSpanData.push(['network.protocol.version', version], ['network.protocol.name', name]);
if (!browserPerformanceTimeOrigin) {
return timingSpanData;
}
return [
...timingSpanData,
['http.request.redirect_start', getAbsoluteTime(resourceTiming.redirectStart)],
['http.request.fetch_start', getAbsoluteTime(resourceTiming.fetchStart)],
['http.request.domain_lookup_start', getAbsoluteTime(resourceTiming.domainLookupStart)],
['http.request.domain_lookup_end', getAbsoluteTime(resourceTiming.domainLookupEnd)],
['http.request.connect_start', getAbsoluteTime(resourceTiming.connectStart)],
['http.request.secure_connection_start', getAbsoluteTime(resourceTiming.secureConnectionStart)],
['http.request.connection_end', getAbsoluteTime(resourceTiming.connectEnd)],
['http.request.request_start', getAbsoluteTime(resourceTiming.requestStart)],
['http.request.response_start', getAbsoluteTime(resourceTiming.responseStart)],
['http.request.response_end', getAbsoluteTime(resourceTiming.responseEnd)],
];
}
/**
* A function that determines whether to attach tracing headers to a request.
* This was extracted from `instrumentOutgoingRequests` to make it easier to test shouldAttachHeaders.
* We only export this fuction for testing purposes.
*/
export function shouldAttachHeaders(url: string, tracePropagationTargets: (string | RegExp)[] | undefined): boolean {
return stringMatchesSomePattern(url, tracePropagationTargets || DEFAULT_TRACE_PROPAGATION_TARGETS);
}
/**
* Create and track xhr request spans
*
* @returns Span if a span was created, otherwise void.
*/
// eslint-disable-next-line complexity
export function xhrCallback(
handlerData: HandlerDataXhr,
shouldCreateSpan: (url: string) => boolean,
shouldAttachHeaders: (url: string) => boolean,
spans: Record<string, Span>,
): Span | undefined {
const xhr = handlerData.xhr;
const sentryXhrData = xhr && xhr[SENTRY_XHR_DATA_KEY];
if (!hasTracingEnabled() || !xhr || xhr.__sentry_own_request__ || !sentryXhrData) {
return undefined;
}
const shouldCreateSpanResult = shouldCreateSpan(sentryXhrData.url);
// check first if the request has finished and is tracked by an existing span which should now end
if (handlerData.endTimestamp && shouldCreateSpanResult) {
const spanId = xhr.__sentry_xhr_span_id__;
if (!spanId) return;
const span = spans[spanId];
if (span && sentryXhrData.status_code !== undefined) {
setHttpStatus(span, sentryXhrData.status_code);
span.end();
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete
delete spans[spanId];
}
return undefined;
}
const scope = getCurrentScope();
const isolationScope = getIsolationScope();
const fullUrl = getFullURL(sentryXhrData.url);
const host = fullUrl ? parseUrl(fullUrl).host : undefined;
const span = shouldCreateSpanResult
? startInactiveSpan({
name: `${sentryXhrData.method} ${sentryXhrData.url}`,
onlyIfParent: true,
attributes: {
type: 'xhr',
'http.method': sentryXhrData.method,
'http.url': fullUrl,
url: sentryXhrData.url,
'server.address': host,
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.browser',
},
op: 'http.client',
})
: undefined;
if (span) {
xhr.__sentry_xhr_span_id__ = span.spanContext().spanId;
spans[xhr.__sentry_xhr_span_id__] = span;
}
const client = getClient();
if (xhr.setRequestHeader && shouldAttachHeaders(sentryXhrData.url) && client) {
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, scope)),
);
setHeaderOnXhr(xhr, sentryTraceHeader, sentryBaggageHeader);
}
return span;
}
function setHeaderOnXhr(
xhr: SentryWrappedXMLHttpRequest,
sentryTraceHeader: string,
sentryBaggageHeader: string | undefined,
): void {
try {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
xhr.setRequestHeader!('sentry-trace', sentryTraceHeader);
if (sentryBaggageHeader) {
// From MDN: "If this method is called several times with the same header, the values are merged into one single request header."
// We can therefore simply set a baggage header without checking what was there before
// https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
xhr.setRequestHeader!(BAGGAGE_HEADER_NAME, sentryBaggageHeader);
}
} catch (_) {
// Error: InvalidStateError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED.
}
}
function getFullURL(url: string): string | undefined {
try {
// By adding a base URL to new URL(), this will also work for relative urls
// If `url` is a full URL, the base URL is ignored anyhow
const parsed = new URL(url, WINDOW.location.origin);
return parsed.href;
} catch {
return undefined;
}
}