-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathfetch.ts
266 lines (231 loc) · 8.59 KB
/
fetch.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
/* eslint-disable @typescript-eslint/no-explicit-any */
import { Scope } from '../../scope';
import type { HandlerDataFetch } from '../../types-hoist';
import { addScopeDataToError } from '../../utils/prepareEvent';
import { isError } from '../is';
import { addNonEnumerableProperty, fill } from '../object';
import { supportsNativeFetch } from '../supports';
import { timestampInSeconds } from '../time';
import { GLOBAL_OBJ } from '../worldwide';
import { addHandler, maybeInstrument, triggerHandlers } from './handlers';
type FetchResource = string | { toString(): string } | { url: string };
/**
* Add an instrumentation handler for when a fetch request happens.
* The handler function is called once when the request starts and once when it ends,
* which can be identified by checking if it has an `endTimestamp`.
*
* Use at your own risk, this might break without changelog notice, only used internally.
* @hidden
*/
export function addFetchInstrumentationHandler(
handler: (data: HandlerDataFetch) => void,
skipNativeFetchCheck?: boolean,
): void {
const type = 'fetch';
addHandler(type, handler);
maybeInstrument(type, () => instrumentFetch(undefined, skipNativeFetchCheck));
}
/**
* Add an instrumentation handler for long-lived fetch requests, like consuming server-sent events (SSE) via fetch.
* The handler will resolve the request body and emit the actual `endTimestamp`, so that the
* span can be updated accordingly.
*
* Only used internally
* @hidden
*/
export function addFetchEndInstrumentationHandler(handler: (data: HandlerDataFetch) => void): void {
const type = 'fetch-body-resolved';
addHandler(type, handler);
maybeInstrument(type, () => instrumentFetch(streamHandler));
}
function instrumentFetch(onFetchResolved?: (response: Response) => void, skipNativeFetchCheck: boolean = false): void {
if (skipNativeFetchCheck && !supportsNativeFetch()) {
return;
}
fill(GLOBAL_OBJ, 'fetch', function (originalFetch: () => void): () => void {
return function (...args: any[]): void {
// We capture the error right here and not in the Promise error callback because Safari (and probably other
// browsers too) will wipe the stack trace up to this point, only leaving us with this file which is useless.
// NOTE: If you are a Sentry user, and you are seeing this stack frame,
// it means the error, that was caused by your fetch call did not
// have a stack trace, so the SDK backfilled the stack trace so
// you can see which fetch call failed.
const virtualError = new Error();
const { method, url } = parseFetchArgs(args);
const handlerData: HandlerDataFetch = {
args,
fetchData: {
method,
url,
},
startTimestamp: timestampInSeconds() * 1000,
// // Adding the error to be able to fingerprint the failed fetch event in HttpClient instrumentation
virtualError,
};
// if there is no callback, fetch is instrumented directly
if (!onFetchResolved) {
triggerHandlers('fetch', {
...handlerData,
});
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
return originalFetch.apply(GLOBAL_OBJ, args).then(
async (response: Response) => {
if (onFetchResolved) {
onFetchResolved(response);
} else {
triggerHandlers('fetch', {
...handlerData,
endTimestamp: timestampInSeconds() * 1000,
response,
});
}
return response;
},
(error: Error) => {
triggerHandlers('fetch', {
...handlerData,
endTimestamp: timestampInSeconds() * 1000,
error,
});
if (isError(error) && error.stack === undefined) {
// NOTE: If you are a Sentry user, and you are seeing this stack frame,
// it means the error, that was caused by your fetch call did not
// have a stack trace, so the SDK backfilled the stack trace so
// you can see which fetch call failed.
error.stack = virtualError.stack;
addNonEnumerableProperty(error, 'framesToPop', 1);
}
// We enhance the not-so-helpful "Failed to fetch" error messages with the host
// Possible messages we handle here:
// * "Failed to fetch" (chromium)
// * "Load failed" (webkit)
// * "NetworkError when attempting to fetch resource." (firefox)
if (
error instanceof TypeError &&
(error.message === 'Failed to fetch' ||
error.message === 'Load failed' ||
error.message === 'NetworkError when attempting to fetch resource.')
) {
try {
const url = new URL(handlerData.fetchData.url);
error.message = `${error.message} (${url.host})`;
} catch {
// ignore it if errors happen here
}
}
// We attach an additional scope to the error, which contains the outgoing request data
// If this error bubbles up and is captured by Sentry, the scope will be added to the event
const scope = new Scope();
scope.setContext('outgoingRequest', {
method,
url,
});
addScopeDataToError(error, scope);
// NOTE: If you are a Sentry user, and you are seeing this stack frame,
// it means the sentry.javascript SDK caught an error invoking your application code.
// This is expected behavior and NOT indicative of a bug with sentry.javascript.
throw error;
},
);
};
});
}
async function resolveResponse(res: Response | undefined, onFinishedResolving: () => void): Promise<void> {
if (res?.body) {
const body = res.body;
const responseReader = body.getReader();
// Define a maximum duration after which we just cancel
const maxFetchDurationTimeout = setTimeout(
() => {
body.cancel().then(null, () => {
// noop
});
},
90 * 1000, // 90s
);
let readingActive = true;
while (readingActive) {
let chunkTimeout;
try {
// abort reading if read op takes more than 5s
chunkTimeout = setTimeout(() => {
body.cancel().then(null, () => {
// noop on error
});
}, 5000);
// This .read() call will reject/throw when we abort due to timeouts through `body.cancel()`
const { done } = await responseReader.read();
clearTimeout(chunkTimeout);
if (done) {
onFinishedResolving();
readingActive = false;
}
} catch (error) {
readingActive = false;
} finally {
clearTimeout(chunkTimeout);
}
}
clearTimeout(maxFetchDurationTimeout);
responseReader.releaseLock();
body.cancel().then(null, () => {
// noop on error
});
}
}
function streamHandler(response: Response): void {
// clone response for awaiting stream
let clonedResponseForResolving: Response;
try {
clonedResponseForResolving = response.clone();
} catch {
return;
}
// eslint-disable-next-line @typescript-eslint/no-floating-promises
resolveResponse(clonedResponseForResolving, () => {
triggerHandlers('fetch-body-resolved', {
endTimestamp: timestampInSeconds() * 1000,
response,
});
});
}
function hasProp<T extends string>(obj: unknown, prop: T): obj is Record<string, string> {
return !!obj && typeof obj === 'object' && !!(obj as Record<string, string>)[prop];
}
function getUrlFromResource(resource: FetchResource): string {
if (typeof resource === 'string') {
return resource;
}
if (!resource) {
return '';
}
if (hasProp(resource, 'url')) {
return resource.url;
}
if (resource.toString) {
return resource.toString();
}
return '';
}
/**
* Parses the fetch arguments to find the used Http method and the url of the request.
* Exported for tests only.
*/
export function parseFetchArgs(fetchArgs: unknown[]): { method: string; url: string } {
if (fetchArgs.length === 0) {
return { method: 'GET', url: '' };
}
if (fetchArgs.length === 2) {
const [url, options] = fetchArgs as [FetchResource, object];
return {
url: getUrlFromResource(url),
method: hasProp(options, 'method') ? String(options.method).toUpperCase() : 'GET',
};
}
const arg = fetchArgs[0];
return {
url: getUrlFromResource(arg as FetchResource),
method: hasProp(arg, 'method') ? String(arg.method).toUpperCase() : 'GET',
};
}