/
request.ts
241 lines (210 loc) · 6.57 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
import { addInstrumentationHandler, isInstanceOf, isMatchingPattern } from '@sentry/utils';
import { Span } from '../span';
import { getActiveTransaction } from './utils';
export const DEFAULT_TRACING_ORIGINS = ['localhost', /^\//];
/** Options for Request Instrumentation */
export interface RequestInstrumentationOptions {
/**
* List of strings / regex where the integration should create Spans out of. Additionally this will be used
* to define which outgoing requests the `sentry-trace` header will be attached to.
*
* Default: ['localhost', /^\//] {@see DEFAULT_TRACING_ORIGINS}
*/
tracingOrigins: 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;
/**
* 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.
*
* By default it uses the `tracingOrigins` options as a url match.
*/
shouldCreateSpanForRequest?(url: string): boolean;
}
/** Data returned from fetch callback */
export interface FetchData {
args: any[];
fetchData?: {
method: string;
url: string;
// span_id
__span?: string;
};
startTimestamp: number;
endTimestamp?: number;
}
/** Data returned from XHR request */
interface XHRData {
xhr?: {
__sentry_xhr__?: {
method: string;
url: string;
status_code: number;
data: Record<string, any>;
};
__sentry_xhr_span_id__?: string;
__sentry_own_request__: boolean;
setRequestHeader?: Function;
};
startTimestamp: number;
endTimestamp?: number;
}
export const defaultRequestInstrumentionOptions: RequestInstrumentationOptions = {
traceFetch: true,
traceXHR: true,
tracingOrigins: DEFAULT_TRACING_ORIGINS,
};
/** Registers span creators for xhr and fetch requests */
export function registerRequestInstrumentation(_options?: Partial<RequestInstrumentationOptions>): void {
const { traceFetch, traceXHR, tracingOrigins, shouldCreateSpanForRequest } = {
...defaultRequestInstrumentionOptions,
..._options,
};
// We should cache url -> decision so that we don't have to compute
// regexp everytime we create a request.
const urlMap: Record<string, boolean> = {};
const defaultShouldCreateSpan = (url: string): boolean => {
if (urlMap[url]) {
return urlMap[url];
}
const origins = tracingOrigins;
urlMap[url] =
origins.some((origin: string | RegExp) => isMatchingPattern(url, origin)) &&
!isMatchingPattern(url, 'sentry_key');
return urlMap[url];
};
const shouldCreateSpan = shouldCreateSpanForRequest || defaultShouldCreateSpan;
const spans: Record<string, Span> = {};
if (traceFetch) {
addInstrumentationHandler({
callback: (handlerData: FetchData) => {
_fetchCallback(handlerData, shouldCreateSpan, spans);
},
type: 'fetch',
});
}
if (traceXHR) {
addInstrumentationHandler({
callback: (handlerData: XHRData) => {
xhrCallback(handlerData, shouldCreateSpan, spans);
},
type: 'xhr',
});
}
}
/**
* Create and track fetch request spans
*/
export function _fetchCallback(
handlerData: FetchData,
shouldCreateSpan: (url: string) => boolean,
spans: Record<string, Span>,
): void {
if (!handlerData.fetchData || !shouldCreateSpan(handlerData.fetchData.url)) {
return;
}
if (handlerData.endTimestamp && handlerData.fetchData.__span) {
const span = spans[handlerData.fetchData.__span];
if (span) {
span.finish();
// tslint:disable-next-line: no-dynamic-delete
delete spans[handlerData.fetchData.__span];
}
return;
}
const activeTransaction = getActiveTransaction();
if (activeTransaction) {
const span = activeTransaction.startChild({
data: {
...handlerData.fetchData,
type: 'fetch',
},
description: `${handlerData.fetchData.method} ${handlerData.fetchData.url}`,
op: 'http',
});
handlerData.fetchData.__span = span.spanId;
spans[span.spanId] = span;
const request = (handlerData.args[0] = handlerData.args[0] as string | Request);
const options = (handlerData.args[1] = (handlerData.args[1] as { [key: string]: any }) || {});
let headers = options.headers;
if (isInstanceOf(request, Request)) {
headers = (request as Request).headers;
}
if (headers) {
// tslint:disable-next-line: no-unsafe-any
if (typeof headers.append === 'function') {
// tslint:disable-next-line: no-unsafe-any
headers.append('sentry-trace', span.toTraceparent());
} else if (Array.isArray(headers)) {
headers = [...headers, ['sentry-trace', span.toTraceparent()]];
} else {
headers = { ...headers, 'sentry-trace': span.toTraceparent() };
}
} else {
headers = { 'sentry-trace': span.toTraceparent() };
}
options.headers = headers;
}
}
/**
* Create and track xhr request spans
*/
function xhrCallback(
handlerData: XHRData,
shouldCreateSpan: (url: string) => boolean,
spans: Record<string, Span>,
): void {
if (!handlerData || !handlerData.xhr || !handlerData.xhr.__sentry_xhr__) {
return;
}
const xhr = handlerData.xhr.__sentry_xhr__;
if (!shouldCreateSpan(xhr.url)) {
return;
}
// We only capture complete, non-sentry requests
if (handlerData.xhr.__sentry_own_request__) {
return;
}
if (handlerData.endTimestamp && handlerData.xhr.__sentry_xhr_span_id__) {
const span = spans[handlerData.xhr.__sentry_xhr_span_id__];
if (span) {
span.setData('url', xhr.url);
span.setData('method', xhr.method);
span.setHttpStatus(xhr.status_code);
span.finish();
// tslint:disable-next-line: no-dynamic-delete
delete spans[handlerData.xhr.__sentry_xhr_span_id__];
}
return;
}
const activeTransaction = getActiveTransaction();
if (activeTransaction) {
const span = activeTransaction.startChild({
data: {
...xhr.data,
type: 'xhr',
},
description: `${xhr.method} ${xhr.url}`,
op: 'http',
});
handlerData.xhr.__sentry_xhr_span_id__ = span.spanId;
spans[handlerData.xhr.__sentry_xhr_span_id__] = span;
if (handlerData.xhr.setRequestHeader) {
try {
handlerData.xhr.setRequestHeader('sentry-trace', span.toTraceparent());
} catch (_) {
// Error: InvalidStateError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED.
}
}
}
}