-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathfetch.ts
More file actions
396 lines (341 loc) · 13.9 KB
/
fetch.ts
File metadata and controls
396 lines (341 loc) · 13.9 KB
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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
import { getClient } from './currentScopes';
import { SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN } from './semanticAttributes';
import { setHttpStatus, SPAN_STATUS_ERROR, startInactiveSpan } from './tracing';
import { SentryNonRecordingSpan } from './tracing/sentryNonRecordingSpan';
import type { FetchBreadcrumbHint } from './types-hoist/breadcrumb';
import type { HandlerDataFetch } from './types-hoist/instrument';
import type { ResponseHookInfo } from './types-hoist/request';
import type { Span, SpanAttributes, SpanOrigin } from './types-hoist/span';
import { SENTRY_BAGGAGE_KEY_PREFIX } from './utils/baggage';
import { hasSpansEnabled } from './utils/hasSpansEnabled';
import { isInstanceOf, isRequest } from './utils/is';
import { getActiveSpan } from './utils/spanUtils';
import { getTraceData } from './utils/traceData';
import {
getSanitizedUrlStringFromUrlObject,
isURLObjectRelative,
parseStringToURLObject,
stripDataUrlContent,
} from './utils/url';
type PolymorphicRequestHeaders =
| Record<string, unknown>
| Array<[string, unknown]>
| Iterable<Iterable<unknown>>
// the below is not precisely the Header type used in Request, but it'll pass duck-typing
| {
append: (key: string, value: string) => void;
get: (key: string) => string | null | undefined;
};
interface InstrumentFetchRequestOptions {
spanOrigin?: SpanOrigin;
propagateTraceparent?: boolean;
onRequestSpanEnd?: (span: Span, responseInformation: ResponseHookInfo) => void;
}
/**
* Create and track fetch request spans for usage in combination with `addFetchInstrumentationHandler`.
*
* @deprecated pass an options object instead of the spanOrigin parameter
*
* @returns Span if a span was created, otherwise void.
*/
export function instrumentFetchRequest(
handlerData: HandlerDataFetch,
shouldCreateSpan: (url: string) => boolean,
shouldAttachHeaders: (url: string) => boolean,
spans: Record<string, Span>,
spanOrigin: SpanOrigin,
): Span | undefined;
/**
* Create and track fetch request spans for usage in combination with `addFetchInstrumentationHandler`.
*
* @returns Span if a span was created, otherwise void.
*/
export function instrumentFetchRequest(
handlerData: HandlerDataFetch,
shouldCreateSpan: (url: string) => boolean,
shouldAttachHeaders: (url: string) => boolean,
spans: Record<string, Span>,
// eslint-disable-next-line @typescript-eslint/unified-signatures -- needed because the other overload is deprecated
instrumentFetchRequestOptions: InstrumentFetchRequestOptions,
): Span | undefined;
/**
* Create and track fetch request spans for usage in combination with `addFetchInstrumentationHandler`.
*
* @returns Span if a span was created, otherwise void.
*/
export function instrumentFetchRequest(
handlerData: HandlerDataFetch,
shouldCreateSpan: (url: string) => boolean,
shouldAttachHeaders: (url: string) => boolean,
spans: Record<string, Span>,
spanOriginOrOptions?: SpanOrigin | InstrumentFetchRequestOptions,
): Span | undefined {
if (!handlerData.fetchData) {
return undefined;
}
const { method, url } = handlerData.fetchData;
const shouldCreateSpanResult = hasSpansEnabled() && shouldCreateSpan(url);
if (handlerData.endTimestamp) {
const spanId = handlerData.fetchData.__span;
if (!spanId) return;
const span = spans[spanId];
if (span) {
// Only end the span and call hooks if we're actually recording
if (shouldCreateSpanResult) {
endSpan(span, handlerData);
_callOnRequestSpanEnd(span, handlerData, spanOriginOrOptions);
}
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete
delete spans[spanId];
}
return undefined;
}
// Backwards-compatible with the old signature. Needed to introduce the combined optional parameter
// to avoid API breakage for anyone calling this function with the optional spanOrigin parameter
// TODO (v11): remove this backwards-compatible code and only accept the options parameter
const { spanOrigin = 'auto.http.browser', propagateTraceparent = false } =
typeof spanOriginOrOptions === 'object' ? spanOriginOrOptions : { spanOrigin: spanOriginOrOptions };
const hasParent = !!getActiveSpan();
const span =
shouldCreateSpanResult && hasParent
? startInactiveSpan(getSpanStartOptions(url, method, spanOrigin))
: new SentryNonRecordingSpan();
handlerData.fetchData.__span = span.spanContext().spanId;
spans[span.spanContext().spanId] = span;
if (shouldAttachHeaders(handlerData.fetchData.url)) {
const request: string | Request = handlerData.args[0];
// Shallow clone the options object to avoid mutating the original user-provided object
// Examples: users re-using same options object for multiple fetch calls, frozen objects
const options: { [key: string]: unknown } = { ...(handlerData.args[1] || {}) };
const headers = _INTERNAL_getTracingHeadersForFetchRequest(
request,
options,
// If performance is disabled (TWP) or there's no active root span (pageload/navigation/interaction),
// we do not want to use the span as base for the trace headers,
// which means that the headers will be generated from the scope and the sampling decision is deferred
hasSpansEnabled() && hasParent ? span : undefined,
propagateTraceparent,
);
if (headers) {
// Ensure this is actually set, if no options have been passed previously
handlerData.args[1] = options;
options.headers = headers;
}
}
const client = getClient();
if (client) {
const fetchHint = {
input: handlerData.args,
response: handlerData.response,
startTimestamp: handlerData.startTimestamp,
endTimestamp: handlerData.endTimestamp,
} satisfies FetchBreadcrumbHint;
client.emit('beforeOutgoingRequestSpan', span, fetchHint);
}
return span;
}
/**
* Calls the onRequestSpanEnd callback if it is defined.
*/
export function _callOnRequestSpanEnd(
span: Span,
handlerData: HandlerDataFetch,
spanOriginOrOptions?: SpanOrigin | InstrumentFetchRequestOptions,
): void {
const onRequestSpanEnd =
typeof spanOriginOrOptions === 'object' && spanOriginOrOptions !== null
? spanOriginOrOptions.onRequestSpanEnd
: undefined;
onRequestSpanEnd?.(span, {
headers: handlerData.response?.headers,
error: handlerData.error,
});
}
/**
* Builds merged fetch headers that include `sentry-trace` and `baggage` (and optionally `traceparent`)
* for the given request and init, without mutating the original request or options.
* Returns `undefined` when there is no `sentry-trace` value to attach.
*
* @internal Exported for cross-package instrumentation (for example Cloudflare Workers fetcher bindings)
* and unit tests
*
* Baggage handling:
* 1. No previous baggage header → include Sentry baggage
* 2. Previous baggage has no Sentry entries → merge Sentry baggage in
* 3. Previous baggage already has Sentry entries → leave as-is (may be user-defined)
*/
// eslint-disable-next-line complexity -- yup it's this complicated :(
export function _INTERNAL_getTracingHeadersForFetchRequest(
request: string | URL | Request,
fetchOptionsObj: {
headers?:
| {
[key: string]: string[] | string | undefined;
}
| PolymorphicRequestHeaders;
},
span?: Span,
propagateTraceparent?: boolean,
): PolymorphicRequestHeaders | undefined {
const traceHeaders = getTraceData({ span, propagateTraceparent });
const sentryTrace = traceHeaders['sentry-trace'];
const baggage = traceHeaders.baggage;
const traceparent = traceHeaders.traceparent;
// Nothing to do, when we return undefined here, the original headers will be used
if (!sentryTrace) {
return undefined;
}
const originalHeaders = fetchOptionsObj.headers || (isRequest(request) ? request.headers : undefined);
if (!originalHeaders) {
return { ...traceHeaders };
} else if (isHeaders(originalHeaders)) {
const newHeaders = new Headers(originalHeaders);
// We don't want to override manually added sentry headers
if (!newHeaders.get('sentry-trace')) {
newHeaders.set('sentry-trace', sentryTrace);
}
if (propagateTraceparent && traceparent && !newHeaders.get('traceparent')) {
newHeaders.set('traceparent', traceparent);
}
if (baggage) {
const prevBaggageHeader = newHeaders.get('baggage');
if (!prevBaggageHeader) {
newHeaders.set('baggage', baggage);
} else if (!baggageHeaderHasSentryBaggageValues(prevBaggageHeader)) {
newHeaders.set('baggage', `${prevBaggageHeader},${baggage}`);
}
}
return newHeaders;
} else if (isHeadersInitTupleArray(originalHeaders)) {
const newHeaders = [...originalHeaders];
if (!newHeaders.find(header => header[0] === 'sentry-trace')) {
newHeaders.push(['sentry-trace', sentryTrace]);
}
if (propagateTraceparent && traceparent && !newHeaders.find(header => header[0] === 'traceparent')) {
newHeaders.push(['traceparent', traceparent]);
}
const prevBaggageHeaderWithSentryValues = originalHeaders.find(
header =>
header[0] === 'baggage' && typeof header[1] === 'string' && baggageHeaderHasSentryBaggageValues(header[1]),
);
if (baggage && !prevBaggageHeaderWithSentryValues) {
// If there are multiple entries with the same key, the browser will merge the values into a single request header.
// Its therefore safe to simply push a "baggage" entry, even though there might already be another baggage header.
newHeaders.push(['baggage', baggage]);
}
return newHeaders;
} else {
const existingSentryTraceHeader = 'sentry-trace' in originalHeaders ? originalHeaders['sentry-trace'] : undefined;
const existingTraceparentHeader = 'traceparent' in originalHeaders ? originalHeaders.traceparent : undefined;
const existingBaggageHeader = 'baggage' in originalHeaders ? originalHeaders.baggage : undefined;
const newBaggageHeaders: string[] = existingBaggageHeader
? Array.isArray(existingBaggageHeader)
? [...existingBaggageHeader]
: [existingBaggageHeader]
: [];
const prevBaggageHeaderWithSentryValues =
existingBaggageHeader &&
(Array.isArray(existingBaggageHeader)
? existingBaggageHeader.find(headerItem => baggageHeaderHasSentryBaggageValues(headerItem))
: baggageHeaderHasSentryBaggageValues(existingBaggageHeader));
if (baggage && !prevBaggageHeaderWithSentryValues) {
newBaggageHeaders.push(baggage);
}
const newHeaders: {
'sentry-trace': string;
baggage: string | undefined;
traceparent?: string;
} = {
...originalHeaders,
'sentry-trace': (existingSentryTraceHeader as string | undefined) ?? sentryTrace,
baggage: newBaggageHeaders.length > 0 ? newBaggageHeaders.join(',') : undefined,
};
if (propagateTraceparent && traceparent && !existingTraceparentHeader) {
newHeaders.traceparent = traceparent;
}
return newHeaders;
}
}
function endSpan(span: Span, handlerData: HandlerDataFetch): void {
if (handlerData.response) {
setHttpStatus(span, handlerData.response.status);
const contentLength = handlerData.response?.headers?.get('content-length');
if (contentLength) {
const contentLengthNum = parseInt(contentLength);
if (contentLengthNum > 0) {
span.setAttribute('http.response_content_length', contentLengthNum);
}
}
} else if (handlerData.error) {
span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });
}
span.end();
}
function baggageHeaderHasSentryBaggageValues(baggageHeader: unknown): boolean {
if (typeof baggageHeader !== 'string') {
return false;
}
return baggageHeader.split(',').some(baggageEntry => baggageEntry.trim().startsWith(SENTRY_BAGGAGE_KEY_PREFIX));
}
function isHeaders(headers: unknown): headers is Headers {
return typeof Headers !== 'undefined' && isInstanceOf(headers, Headers);
}
/** `HeadersInit` array form: each entry is a [name, value] pair of strings. */
function isHeadersInitTupleArray(headers: unknown): headers is [string, unknown][] {
if (!Array.isArray(headers)) {
return false;
}
return headers.every(
(item): item is [string, unknown] => Array.isArray(item) && item.length === 2 && typeof item[0] === 'string',
);
}
function getSpanStartOptions(
url: string,
method: string,
spanOrigin: SpanOrigin,
): Parameters<typeof startInactiveSpan>[0] {
// Data URLs need special handling because parseStringToURLObject treats them as "relative"
// (no "://"), causing getSanitizedUrlStringFromUrlObject to return just the pathname
// without the "data:" prefix, making later stripDataUrlContent calls ineffective.
// So for data URLs, we strip the content first and use that directly.
if (url.startsWith('data:')) {
const sanitizedUrl = stripDataUrlContent(url);
return {
name: `${method} ${sanitizedUrl}`,
attributes: getFetchSpanAttributes(url, undefined, method, spanOrigin),
};
}
const parsedUrl = parseStringToURLObject(url);
const sanitizedUrl = parsedUrl ? getSanitizedUrlStringFromUrlObject(parsedUrl) : url;
return {
name: `${method} ${sanitizedUrl}`,
attributes: getFetchSpanAttributes(url, parsedUrl, method, spanOrigin),
};
}
function getFetchSpanAttributes(
url: string,
parsedUrl: ReturnType<typeof parseStringToURLObject>,
method: string,
spanOrigin: SpanOrigin,
): SpanAttributes {
const attributes: SpanAttributes = {
url: stripDataUrlContent(url),
type: 'fetch',
'http.method': method,
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: spanOrigin,
[SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'http.client',
};
if (parsedUrl) {
if (!isURLObjectRelative(parsedUrl)) {
attributes['http.url'] = stripDataUrlContent(parsedUrl.href);
attributes['server.address'] = parsedUrl.host;
}
if (parsedUrl.search) {
attributes['http.query'] = parsedUrl.search;
}
if (parsedUrl.hash) {
attributes['http.fragment'] = parsedUrl.hash;
}
}
return attributes;
}