-
Notifications
You must be signed in to change notification settings - Fork 837
/
Copy pathxhr.ts
546 lines (488 loc) · 15.8 KB
/
xhr.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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
/*
* 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 { hrTime, isUrlIgnored, otperformance } from '@opentelemetry/core';
import { SemanticAttributes } from '@opentelemetry/semantic-conventions';
import {
addSpanNetworkEvents,
getResource,
PerformanceTimingNames as PTN,
shouldPropagateTraceHeaders,
parseUrl,
} from '@opentelemetry/sdk-trace-web';
import { EventNames } from './enums/EventNames';
import {
OpenFunction,
PropagateTraceHeaderCorsUrls,
SendFunction,
XhrMem,
} from './types';
import { VERSION } from './version';
import { AttributeNames } from './enums/AttributeNames';
// 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;
export type XHRCustomAttributeFunction = (
span: api.Span,
xhr: XMLHttpRequest
) => void;
/**
* XMLHttpRequest config
*/
export interface XMLHttpRequestInstrumentationConfig
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?: 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?: XHRCustomAttributeFunction;
}
/**
* This class represents a XMLHttpRequest plugin for auto instrumentation
*/
export class XMLHttpRequestInstrumentation extends InstrumentationBase<XMLHttpRequest> {
readonly component: string = 'xml-http-request';
readonly version: string = VERSION;
moduleName = this.component;
private _tasksCount = 0;
private _xhrMem = new WeakMap<XMLHttpRequest, XhrMem>();
private _usedResources = new WeakSet<PerformanceResourceTiming>();
constructor(config?: XMLHttpRequestInstrumentationConfig) {
super(
'@opentelemetry/instrumentation-xml-http-request',
VERSION,
config
);
}
init() {}
private _getConfig(): XMLHttpRequestInstrumentationConfig {
return this._config;
}
/**
* Adds custom headers to XMLHttpRequest
* @param xhr
* @param spanUrl
* @private
*/
private _addHeaders(xhr: XMLHttpRequest, spanUrl: string) {
const url = parseUrl(spanUrl).href;
if (
!shouldPropagateTraceHeaders(
url,
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;
}
const headers: { [key: string]: unknown } = {};
api.propagation.inject(api.context.active(), headers);
Object.keys(headers).forEach(key => {
xhr.setRequestHeader(key, String(headers[key]));
});
}
/**
* Add cors pre flight child span
* @param span
* @param corsPreFlightRequest
* @private
*/
private _addChildSpan(
span: api.Span,
corsPreFlightRequest: PerformanceResourceTiming
): void {
api.context.with(api.trace.setSpan(api.context.active(), span), () => {
const childSpan = this.tracer.startSpan('CORS Preflight', {
startTime: corsPreFlightRequest[PTN.FETCH_START],
});
addSpanNetworkEvents(childSpan, corsPreFlightRequest);
childSpan.end(corsPreFlightRequest[PTN.RESPONSE_END]);
});
}
/**
* Add attributes when span is going to end
* @param span
* @param xhr
* @param spanUrl
* @private
*/
_addFinalSpanAttributes(span: api.Span, xhrMem: XhrMem, spanUrl?: string) {
if (typeof spanUrl === 'string') {
const parsedUrl = parseUrl(spanUrl);
if (xhrMem.status !== undefined) {
span.setAttribute(SemanticAttributes.HTTP_STATUS_CODE, xhrMem.status);
}
if (xhrMem.statusText !== undefined) {
span.setAttribute(AttributeNames.HTTP_STATUS_TEXT, xhrMem.statusText);
}
span.setAttribute(SemanticAttributes.HTTP_HOST, parsedUrl.host);
span.setAttribute(
SemanticAttributes.HTTP_SCHEME,
parsedUrl.protocol.replace(':', '')
);
// @TODO do we want to collect this or it will be collected earlier once only or
// maybe when parent span is not available ?
span.setAttribute(
SemanticAttributes.HTTP_USER_AGENT,
navigator.userAgent
);
}
}
private _applyAttributesAfterXHR(span: api.Span, xhr: XMLHttpRequest) {
const applyCustomAttributesOnSpan = this._getConfig()
.applyCustomAttributesOnSpan;
if (typeof applyCustomAttributesOnSpan === 'function') {
safeExecuteInTheMiddle(
() => applyCustomAttributesOnSpan(span, xhr),
error => {
if (!error) {
return;
}
this._diag.error('applyCustomAttributesOnSpan', error);
},
true
);
}
}
/**
* will collect information about all resources created
* between "send" and "end" with additional waiting for main resource
* @param xhr
* @param spanUrl
* @private
*/
private _addResourceObserver(xhr: XMLHttpRequest, spanUrl: string) {
const xhrMem = this._xhrMem.get(xhr);
if (
!xhrMem ||
typeof PerformanceObserver !== 'function' ||
typeof PerformanceResourceTiming !== 'function'
) {
return;
}
xhrMem.createdResources = {
observer: new PerformanceObserver(list => {
const entries = list.getEntries() as PerformanceResourceTiming[];
const parsedUrl = parseUrl(spanUrl);
entries.forEach(entry => {
if (
entry.initiatorType === 'xmlhttprequest' &&
entry.name === parsedUrl.href
) {
if (xhrMem.createdResources) {
xhrMem.createdResources.entries.push(entry);
}
}
});
}),
entries: [],
};
xhrMem.createdResources.observer.observe({
entryTypes: ['resource'],
});
}
/**
* Clears the resource timings and all resources assigned with spans
* when {@link XMLHttpRequestInstrumentationConfig.clearTimingResources} is
* set to true (default false)
* @private
*/
private _clearResources() {
if (this._tasksCount === 0 && this._getConfig().clearTimingResources) {
((otperformance as unknown) as Performance).clearResourceTimings();
this._xhrMem = new WeakMap<XMLHttpRequest, XhrMem>();
this._usedResources = new WeakSet<PerformanceResourceTiming>();
}
}
/**
* Finds appropriate resource and add network events to the span
* @param span
*/
private _findResourceAndAddNetworkEvents(
xhrMem: XhrMem,
span: api.Span,
spanUrl?: string,
startTime?: api.HrTime,
endTime?: api.HrTime
): void {
if (!spanUrl || !startTime || !endTime || !xhrMem.createdResources) {
return;
}
let resources: PerformanceResourceTiming[] =
xhrMem.createdResources.entries;
if (!resources || !resources.length) {
// fallback - either Observer is not available or it took longer
// then OBSERVER_WAIT_TIME_MS and observer didn't collect enough
// information
// ts thinks this is the perf_hooks module, but it is the browser performance api
resources = ((otperformance as unknown) as Performance).getEntriesByType(
'resource'
) as PerformanceResourceTiming[];
}
const resource = getResource(
parseUrl(spanUrl).href,
startTime,
endTime,
resources,
this._usedResources
);
if (resource.mainRequest) {
const mainRequest = resource.mainRequest;
this._markResourceAsUsed(mainRequest);
const corsPreFlightRequest = resource.corsPreFlightRequest;
if (corsPreFlightRequest) {
this._addChildSpan(span, corsPreFlightRequest);
this._markResourceAsUsed(corsPreFlightRequest);
}
addSpanNetworkEvents(span, mainRequest);
}
}
/**
* Removes the previous information about span.
* This might happened when the same xhr is used again.
* @param xhr
* @private
*/
private _cleanPreviousSpanInformation(xhr: XMLHttpRequest) {
const xhrMem = this._xhrMem.get(xhr);
if (xhrMem) {
const callbackToRemoveEvents = xhrMem.callbackToRemoveEvents;
if (callbackToRemoveEvents) {
callbackToRemoveEvents();
}
this._xhrMem.delete(xhr);
}
}
/**
* Creates a new span when method "open" is called
* @param xhr
* @param url
* @param method
* @private
*/
private _createSpan(
xhr: XMLHttpRequest,
url: string,
method: string
): api.Span | undefined {
if (isUrlIgnored(url, this._getConfig().ignoreUrls)) {
this._diag.debug('ignoring span as url matches ignored url');
return;
}
const spanName = `HTTP ${method.toUpperCase()}`;
const currentSpan = this.tracer.startSpan(spanName, {
kind: api.SpanKind.CLIENT,
attributes: {
[SemanticAttributes.HTTP_METHOD]: method,
[SemanticAttributes.HTTP_URL]: url,
},
});
currentSpan.addEvent(EventNames.METHOD_OPEN);
this._cleanPreviousSpanInformation(xhr);
this._xhrMem.set(xhr, {
span: currentSpan,
spanUrl: url,
});
return currentSpan;
}
/**
* 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
*/
private _markResourceAsUsed(resource: PerformanceResourceTiming) {
this._usedResources.add(resource);
}
/**
* Patches the method open
* @private
*/
protected _patchOpen() {
return (original: OpenFunction): OpenFunction => {
const plugin = this;
return function patchOpen(this: XMLHttpRequest, ...args): void {
const method: string = args[0];
const url: string = args[1];
plugin._createSpan(this, url, method);
return original.apply(this, args);
};
};
}
/**
* Patches the method send
* @private
*/
protected _patchSend() {
const plugin = this;
function endSpanTimeout(
eventName: string,
xhrMem: XhrMem,
endTime: api.HrTime
) {
const callbackToRemoveEvents = xhrMem.callbackToRemoveEvents;
if (typeof callbackToRemoveEvents === 'function') {
callbackToRemoveEvents();
}
const { span, spanUrl, sendStartTime } = xhrMem;
if (span) {
plugin._findResourceAndAddNetworkEvents(
xhrMem,
span,
spanUrl,
sendStartTime,
endTime
);
span.addEvent(eventName, endTime);
plugin._addFinalSpanAttributes(span, xhrMem, spanUrl);
span.end(endTime);
plugin._tasksCount--;
}
plugin._clearResources();
}
function endSpan(eventName: string, xhr: XMLHttpRequest) {
const xhrMem = plugin._xhrMem.get(xhr);
if (!xhrMem) {
return;
}
xhrMem.status = xhr.status;
xhrMem.statusText = xhr.statusText;
plugin._xhrMem.delete(xhr);
if (xhrMem.span) {
plugin._applyAttributesAfterXHR(xhrMem.span, xhr);
}
const endTime = hrTime();
// the timeout is needed as observer doesn't have yet information
// when event "load" is called. Also the time may differ depends on
// browser and speed of computer
setTimeout(() => {
endSpanTimeout(eventName, xhrMem, endTime);
}, OBSERVER_WAIT_TIME_MS);
}
function onError(this: XMLHttpRequest) {
endSpan(EventNames.EVENT_ERROR, this);
}
function onAbort(this: XMLHttpRequest) {
endSpan(EventNames.EVENT_ABORT, this);
}
function onTimeout(this: XMLHttpRequest) {
endSpan(EventNames.EVENT_TIMEOUT, this);
}
function onLoad(this: XMLHttpRequest) {
if (this.status < 299) {
endSpan(EventNames.EVENT_LOAD, this);
} else {
endSpan(EventNames.EVENT_ERROR, this);
}
}
function unregister(xhr: XMLHttpRequest) {
xhr.removeEventListener('abort', onAbort);
xhr.removeEventListener('error', onError);
xhr.removeEventListener('load', onLoad);
xhr.removeEventListener('timeout', onTimeout);
const xhrMem = plugin._xhrMem.get(xhr);
if (xhrMem) {
xhrMem.callbackToRemoveEvents = undefined;
}
}
return (original: SendFunction): SendFunction => {
return function patchSend(this: XMLHttpRequest, ...args): void {
const xhrMem = plugin._xhrMem.get(this);
if (!xhrMem) {
return original.apply(this, args);
}
const currentSpan = xhrMem.span;
const spanUrl = xhrMem.spanUrl;
if (currentSpan && spanUrl) {
api.context.with(
api.trace.setSpan(api.context.active(), currentSpan),
() => {
plugin._tasksCount++;
xhrMem.sendStartTime = hrTime();
currentSpan.addEvent(EventNames.METHOD_SEND);
this.addEventListener('abort', onAbort);
this.addEventListener('error', onError);
this.addEventListener('load', onLoad);
this.addEventListener('timeout', onTimeout);
xhrMem.callbackToRemoveEvents = () => {
unregister(this);
if (xhrMem.createdResources) {
xhrMem.createdResources.observer.disconnect();
}
};
plugin._addHeaders(this, spanUrl);
plugin._addResourceObserver(this, spanUrl);
}
);
}
return original.apply(this, args);
};
};
}
/**
* implements enable function
*/
override enable() {
this._diag.debug('applying patch to', this.moduleName, this.version);
if (isWrapped(XMLHttpRequest.prototype.open)) {
this._unwrap(XMLHttpRequest.prototype, 'open');
this._diag.debug('removing previous patch from method open');
}
if (isWrapped(XMLHttpRequest.prototype.send)) {
this._unwrap(XMLHttpRequest.prototype, 'send');
this._diag.debug('removing previous patch from method send');
}
this._wrap(XMLHttpRequest.prototype, 'open', this._patchOpen());
this._wrap(XMLHttpRequest.prototype, 'send', this._patchSend());
}
/**
* implements disable function
*/
override disable() {
this._diag.debug('removing patch from', this.moduleName, this.version);
this._unwrap(XMLHttpRequest.prototype, 'open');
this._unwrap(XMLHttpRequest.prototype, 'send');
this._tasksCount = 0;
this._xhrMem = new WeakMap<XMLHttpRequest, XhrMem>();
this._usedResources = new WeakSet<PerformanceResourceTiming>();
}
}