-
Notifications
You must be signed in to change notification settings - Fork 756
/
fetch.ts
493 lines (460 loc) · 15 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
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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as api from '@opentelemetry/api';
import {
isWrapped,
InstrumentationBase,
InstrumentationConfig,
safeExecuteInTheMiddle,
} from '@opentelemetry/instrumentation';
import * as core from '@opentelemetry/core';
import * as web from '@opentelemetry/sdk-trace-web';
import { AttributeNames } from './enums/AttributeNames';
import {
SEMATTRS_HTTP_STATUS_CODE,
SEMATTRS_HTTP_HOST,
SEMATTRS_HTTP_USER_AGENT,
SEMATTRS_HTTP_SCHEME,
SEMATTRS_HTTP_URL,
SEMATTRS_HTTP_METHOD,
} from '@opentelemetry/semantic-conventions';
import { FetchError, FetchResponse, SpanData } from './types';
import { VERSION } from './version';
import { _globalThis } from '@opentelemetry/core';
// how long to wait for observer to collect information about resources
// this is needed as event "load" is called before observer
// hard to say how long it should really wait, seems like 300ms is
// safe enough
const OBSERVER_WAIT_TIME_MS = 300;
const isNode = typeof process === 'object' && process.release?.name === 'node';
export interface FetchCustomAttributeFunction {
(
span: api.Span,
request: Request | RequestInit,
result: Response | FetchError
): void;
}
/**
* FetchPlugin Config
*/
export interface FetchInstrumentationConfig extends InstrumentationConfig {
// the number of timing resources is limited, after the limit
// (chrome 250, safari 150) the information is not collected anymore
// the only way to prevent that is to regularly clean the resources
// whenever it is possible, this is needed only when PerformanceObserver
// is not available
clearTimingResources?: boolean;
// urls which should include trace headers when origin doesn't match
propagateTraceHeaderCorsUrls?: web.PropagateTraceHeaderCorsUrls;
/**
* URLs that partially match any regex in ignoreUrls will not be traced.
* In addition, URLs that are _exact matches_ of strings in ignoreUrls will
* also not be traced.
*/
ignoreUrls?: Array<string | RegExp>;
/** Function for adding custom attributes on the span */
applyCustomAttributesOnSpan?: FetchCustomAttributeFunction;
// Ignore adding network events as span events
ignoreNetworkEvents?: boolean;
}
/**
* This class represents a fetch plugin for auto instrumentation
*/
export class FetchInstrumentation extends InstrumentationBase<FetchInstrumentationConfig> {
readonly component: string = 'fetch';
readonly version: string = VERSION;
moduleName = this.component;
private _usedResources = new WeakSet<PerformanceResourceTiming>();
private _tasksCount = 0;
constructor(config: FetchInstrumentationConfig = {}) {
super('@opentelemetry/instrumentation-fetch', VERSION, config);
}
init(): void {}
/**
* Add cors pre flight child span
* @param span
* @param corsPreFlightRequest
*/
private _addChildSpan(
span: api.Span,
corsPreFlightRequest: PerformanceResourceTiming
): void {
const childSpan = this.tracer.startSpan(
'CORS Preflight',
{
startTime: corsPreFlightRequest[web.PerformanceTimingNames.FETCH_START],
},
api.trace.setSpan(api.context.active(), span)
);
if (!this.getConfig().ignoreNetworkEvents) {
web.addSpanNetworkEvents(childSpan, corsPreFlightRequest);
}
childSpan.end(
corsPreFlightRequest[web.PerformanceTimingNames.RESPONSE_END]
);
}
/**
* Adds more attributes to span just before ending it
* @param span
* @param response
*/
private _addFinalSpanAttributes(
span: api.Span,
response: FetchResponse
): void {
const parsedUrl = web.parseUrl(response.url);
span.setAttribute(SEMATTRS_HTTP_STATUS_CODE, response.status);
if (response.statusText != null) {
span.setAttribute(AttributeNames.HTTP_STATUS_TEXT, response.statusText);
}
span.setAttribute(SEMATTRS_HTTP_HOST, parsedUrl.host);
span.setAttribute(
SEMATTRS_HTTP_SCHEME,
parsedUrl.protocol.replace(':', '')
);
if (typeof navigator !== 'undefined') {
span.setAttribute(SEMATTRS_HTTP_USER_AGENT, navigator.userAgent);
}
}
/**
* Add headers
* @param options
* @param spanUrl
*/
private _addHeaders(options: Request | RequestInit, spanUrl: string): void {
if (
!web.shouldPropagateTraceHeaders(
spanUrl,
this.getConfig().propagateTraceHeaderCorsUrls
)
) {
const headers: Partial<Record<string, unknown>> = {};
api.propagation.inject(api.context.active(), headers);
if (Object.keys(headers).length > 0) {
this._diag.debug('headers inject skipped due to CORS policy');
}
return;
}
if (options instanceof Request) {
api.propagation.inject(api.context.active(), options.headers, {
set: (h, k, v) => h.set(k, typeof v === 'string' ? v : String(v)),
});
} else if (options.headers instanceof Headers) {
api.propagation.inject(api.context.active(), options.headers, {
set: (h, k, v) => h.set(k, typeof v === 'string' ? v : String(v)),
});
} else if (options.headers instanceof Map) {
api.propagation.inject(api.context.active(), options.headers, {
set: (h, k, v) => h.set(k, typeof v === 'string' ? v : String(v)),
});
} else {
const headers: Partial<Record<string, unknown>> = {};
api.propagation.inject(api.context.active(), headers);
options.headers = Object.assign({}, headers, options.headers || {});
}
}
/**
* Clears the resource timings and all resources assigned with spans
* when {@link FetchPluginConfig.clearTimingResources} is
* set to true (default false)
* @private
*/
private _clearResources() {
if (this._tasksCount === 0 && this.getConfig().clearTimingResources) {
performance.clearResourceTimings();
this._usedResources = new WeakSet<PerformanceResourceTiming>();
}
}
/**
* Creates a new span
* @param url
* @param options
*/
private _createSpan(
url: string,
options: Partial<Request | RequestInit> = {}
): api.Span | undefined {
if (core.isUrlIgnored(url, this.getConfig().ignoreUrls)) {
this._diag.debug('ignoring span as url matches ignored url');
return;
}
const method = (options.method || 'GET').toUpperCase();
const spanName = `HTTP ${method}`;
return this.tracer.startSpan(spanName, {
kind: api.SpanKind.CLIENT,
attributes: {
[AttributeNames.COMPONENT]: this.moduleName,
[SEMATTRS_HTTP_METHOD]: method,
[SEMATTRS_HTTP_URL]: url,
},
});
}
/**
* Finds appropriate resource and add network events to the span
* @param span
* @param resourcesObserver
* @param endTime
*/
private _findResourceAndAddNetworkEvents(
span: api.Span,
resourcesObserver: SpanData,
endTime: api.HrTime
): void {
let resources: PerformanceResourceTiming[] = resourcesObserver.entries;
if (!resources.length) {
if (!performance.getEntriesByType) {
return;
}
// fallback - either Observer is not available or it took longer
// then OBSERVER_WAIT_TIME_MS and observer didn't collect enough
// information
resources = performance.getEntriesByType(
'resource'
) as PerformanceResourceTiming[];
}
const resource = web.getResource(
resourcesObserver.spanUrl,
resourcesObserver.startTime,
endTime,
resources,
this._usedResources,
'fetch'
);
if (resource.mainRequest) {
const mainRequest = resource.mainRequest;
this._markResourceAsUsed(mainRequest);
const corsPreFlightRequest = resource.corsPreFlightRequest;
if (corsPreFlightRequest) {
this._addChildSpan(span, corsPreFlightRequest);
this._markResourceAsUsed(corsPreFlightRequest);
}
if (!this.getConfig().ignoreNetworkEvents) {
web.addSpanNetworkEvents(span, mainRequest);
}
}
}
/**
* Marks certain [resource]{@link PerformanceResourceTiming} when information
* from this is used to add events to span.
* This is done to avoid reusing the same resource again for next span
* @param resource
*/
private _markResourceAsUsed(resource: PerformanceResourceTiming): void {
this._usedResources.add(resource);
}
/**
* Finish span, add attributes, network events etc.
* @param span
* @param spanData
* @param response
*/
private _endSpan(
span: api.Span,
spanData: SpanData,
response: FetchResponse
) {
const endTime = core.millisToHrTime(Date.now());
const performanceEndTime = core.hrTime();
this._addFinalSpanAttributes(span, response);
setTimeout(() => {
spanData.observer?.disconnect();
this._findResourceAndAddNetworkEvents(span, spanData, performanceEndTime);
this._tasksCount--;
this._clearResources();
span.end(endTime);
}, OBSERVER_WAIT_TIME_MS);
}
/**
* Patches the constructor of fetch
*/
private _patchConstructor(): (original: typeof fetch) => typeof fetch {
return original => {
const plugin = this;
return function patchConstructor(
this: typeof globalThis,
...args: Parameters<typeof fetch>
): Promise<Response> {
const self = this;
const url = web.parseUrl(
args[0] instanceof Request ? args[0].url : String(args[0])
).href;
const options = args[0] instanceof Request ? args[0] : args[1] || {};
const createdSpan = plugin._createSpan(url, options);
if (!createdSpan) {
return original.apply(this, args);
}
const spanData = plugin._prepareSpanData(url);
function endSpanOnError(span: api.Span, error: FetchError) {
plugin._applyAttributesAfterFetch(span, options, error);
plugin._endSpan(span, spanData, {
status: error.status || 0,
statusText: error.message,
url,
});
}
function endSpanOnSuccess(span: api.Span, response: Response) {
plugin._applyAttributesAfterFetch(span, options, response);
if (response.status >= 200 && response.status < 400) {
plugin._endSpan(span, spanData, response);
} else {
plugin._endSpan(span, spanData, {
status: response.status,
statusText: response.statusText,
url,
});
}
}
function onSuccess(
span: api.Span,
resolve: (value: Response | PromiseLike<Response>) => void,
response: Response
): void {
try {
const resClone = response.clone();
const resClone4Hook = response.clone();
const body = resClone.body;
if (body) {
const reader = body.getReader();
const read = (): void => {
reader.read().then(
({ done }) => {
if (done) {
endSpanOnSuccess(span, resClone4Hook);
} else {
read();
}
},
error => {
endSpanOnError(span, error);
}
);
};
read();
} else {
// some older browsers don't have .body implemented
endSpanOnSuccess(span, response);
}
} finally {
resolve(response);
}
}
function onError(
span: api.Span,
reject: (reason?: unknown) => void,
error: FetchError
) {
try {
endSpanOnError(span, error);
} finally {
reject(error);
}
}
return new Promise((resolve, reject) => {
return api.context.with(
api.trace.setSpan(api.context.active(), createdSpan),
() => {
plugin._addHeaders(options, url);
plugin._tasksCount++;
// TypeScript complains about arrow function captured a this typed as globalThis
// ts(7041)
return original
.apply(
self,
options instanceof Request ? [options] : [url, options]
)
.then(
onSuccess.bind(self, createdSpan, resolve),
onError.bind(self, createdSpan, reject)
);
}
);
});
};
};
}
private _applyAttributesAfterFetch(
span: api.Span,
request: Request | RequestInit,
result: Response | FetchError
) {
const applyCustomAttributesOnSpan =
this.getConfig().applyCustomAttributesOnSpan;
if (applyCustomAttributesOnSpan) {
safeExecuteInTheMiddle(
() => applyCustomAttributesOnSpan(span, request, result),
error => {
if (!error) {
return;
}
this._diag.error('applyCustomAttributesOnSpan', error);
},
true
);
}
}
/**
* Prepares a span data - needed later for matching appropriate network
* resources
* @param spanUrl
*/
private _prepareSpanData(spanUrl: string): SpanData {
const startTime = core.hrTime();
const entries: PerformanceResourceTiming[] = [];
if (typeof PerformanceObserver !== 'function') {
return { entries, startTime, spanUrl };
}
const observer = new PerformanceObserver(list => {
const perfObsEntries = list.getEntries() as PerformanceResourceTiming[];
perfObsEntries.forEach(entry => {
if (entry.initiatorType === 'fetch' && entry.name === spanUrl) {
entries.push(entry);
}
});
});
observer.observe({
entryTypes: ['resource'],
});
return { entries, observer, startTime, spanUrl };
}
/**
* implements enable function
*/
override enable(): void {
if (isNode) {
// Node.js v18+ *does* have a global `fetch()`, but this package does not
// support instrumenting it.
this._diag.warn(
"this instrumentation is intended for web usage only, it does not instrument Node.js's fetch()"
);
return;
}
if (isWrapped(fetch)) {
this._unwrap(_globalThis, 'fetch');
this._diag.debug('removing previous patch for constructor');
}
this._wrap(_globalThis, 'fetch', this._patchConstructor());
}
/**
* implements unpatch function
*/
override disable(): void {
if (isNode) {
return;
}
this._unwrap(_globalThis, 'fetch');
this._usedResources = new WeakSet<PerformanceResourceTiming>();
}
}