-
Notifications
You must be signed in to change notification settings - Fork 469
/
instrumentation.ts
661 lines (626 loc) · 19.2 KB
/
instrumentation.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
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
/*
* 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 {
isWrapped,
InstrumentationBase,
InstrumentationConfig,
} from '@opentelemetry/instrumentation';
import * as api from '@opentelemetry/api';
import { hrTime } from '@opentelemetry/core';
import { getElementXPath } from '@opentelemetry/sdk-trace-web';
import { AttributeNames } from './enums/AttributeNames';
import {
AsyncTask,
RunTaskFunction,
SpanData,
WindowWithZone,
ZoneTypeWithPrototype,
} from './types';
import { VERSION } from './version';
const ZONE_CONTEXT_KEY = 'OT_ZONE_CONTEXT';
const EVENT_NAVIGATION_NAME = 'Navigation:';
/**
* This class represents a UserInteraction plugin for auto instrumentation.
* If zone.js is available then it patches the zone otherwise it patches
* addEventListener of HTMLElement
*/
export class UserInteractionInstrumentation extends InstrumentationBase<unknown> {
readonly component: string = 'user-interaction';
readonly version = VERSION;
moduleName = this.component;
private _spansData = new WeakMap<api.Span, SpanData>();
private _zonePatched?: boolean;
// for addEventListener/removeEventListener state
private _wrappedListeners = new WeakMap<
Function | EventListenerObject,
Map<string, Map<HTMLElement, Function>>
>();
// for event bubbling
private _eventsSpanMap: WeakMap<Event, api.Span> = new WeakMap<
Event,
api.Span
>();
constructor(config?: InstrumentationConfig) {
super('@opentelemetry/instrumentation-user-interaction', VERSION, config);
}
init() {}
/**
* This will check if last task was timeout and will save the time to
* fix the user interaction when nothing happens
* This timeout comes from xhr plugin which is needed to collect information
* about last xhr main request from observer
* @param task
* @param span
*/
private _checkForTimeout(task: AsyncTask, span: api.Span) {
const spanData = this._spansData.get(span);
if (spanData) {
if (task.source === 'setTimeout') {
spanData.hrTimeLastTimeout = hrTime();
} else if (
task.source !== 'Promise.then' &&
task.source !== 'setTimeout'
) {
spanData.hrTimeLastTimeout = undefined;
}
}
}
/**
* Controls whether or not to create a span, based on the event type.
*/
protected _allowEventType(eventType: string): boolean {
return eventType === 'click';
}
/**
* Creates a new span
* @param element
* @param eventName
*/
private _createSpan(
element: EventTarget | null | undefined,
eventName: string,
parentSpan?: api.Span | undefined
): api.Span | undefined {
if (!(element instanceof HTMLElement)) {
return undefined;
}
if (!element.getAttribute) {
return undefined;
}
if (element.hasAttribute('disabled')) {
return undefined;
}
if (!this._allowEventType(eventName)) {
return undefined;
}
const xpath = getElementXPath(element, true);
try {
const span = this.tracer.startSpan(
eventName,
{
attributes: {
[AttributeNames.COMPONENT]: this.component,
[AttributeNames.EVENT_TYPE]: eventName,
[AttributeNames.TARGET_ELEMENT]: element.tagName,
[AttributeNames.TARGET_XPATH]: xpath,
[AttributeNames.HTTP_URL]: window.location.href,
[AttributeNames.HTTP_USER_AGENT]: navigator.userAgent,
},
},
parentSpan
? api.trace.setSpan(api.context.active(), parentSpan)
: undefined
);
this._spansData.set(span, {
taskCount: 0,
});
return span;
} catch (e) {
api.diag.error(this.component, e);
}
return undefined;
}
/**
* Decrement number of tasks that left in zone,
* This is needed to be able to end span when no more tasks left
* @param span
*/
private _decrementTask(span: api.Span) {
const spanData = this._spansData.get(span);
if (spanData) {
spanData.taskCount--;
if (spanData.taskCount === 0) {
this._tryToEndSpan(span, spanData.hrTimeLastTimeout);
}
}
}
/**
* Return the current span
* @param zone
* @private
*/
private _getCurrentSpan(zone: Zone): api.Span | undefined {
const context: api.Context | undefined = zone.get(ZONE_CONTEXT_KEY);
if (context) {
return api.trace.getSpan(context);
}
return context;
}
/**
* Increment number of tasks that are run within the same zone.
* This is needed to be able to end span when no more tasks left
* @param span
*/
private _incrementTask(span: api.Span) {
const spanData = this._spansData.get(span);
if (spanData) {
spanData.taskCount++;
}
}
/**
* Returns true iff we should use the patched callback; false if it's already been patched
*/
private addPatchedListener(
on: HTMLElement,
type: string,
listener: Function | EventListenerObject,
wrappedListener: Function
): boolean {
let listener2Type = this._wrappedListeners.get(listener);
if (!listener2Type) {
listener2Type = new Map();
this._wrappedListeners.set(listener, listener2Type);
}
let element2patched = listener2Type.get(type);
if (!element2patched) {
element2patched = new Map();
listener2Type.set(type, element2patched);
}
if (element2patched.has(on)) {
return false;
}
element2patched.set(on, wrappedListener);
return true;
}
/**
* Returns the patched version of the callback (or undefined)
*/
private removePatchedListener(
on: HTMLElement,
type: string,
listener: Function | EventListenerObject
): Function | undefined {
const listener2Type = this._wrappedListeners.get(listener);
if (!listener2Type) {
return undefined;
}
const element2patched = listener2Type.get(type);
if (!element2patched) {
return undefined;
}
const patched = element2patched.get(on);
if (patched) {
element2patched.delete(on);
if (element2patched.size === 0) {
listener2Type.delete(type);
if (listener2Type.size === 0) {
this._wrappedListeners.delete(listener);
}
}
}
return patched;
}
// utility method to deal with the Function|EventListener nature of addEventListener
private _invokeListener(
listener: Function | EventListenerObject,
target: any,
args: any[]
): any {
if (typeof listener === 'function') {
return listener.apply(target, args);
} else {
return listener.handleEvent(args[0]);
}
}
/**
* This patches the addEventListener of HTMLElement to be able to
* auto instrument the click events
* This is done when zone is not available
*/
private _patchAddEventListener() {
const plugin = this;
return (original: Function) => {
return function addEventListenerPatched(
this: HTMLElement,
type: any,
listener: any,
useCapture: any
) {
const once = useCapture && useCapture.once;
const patchedListener = function (this: HTMLElement, ...args: any[]) {
let parentSpan: api.Span | undefined;
const event: Event | undefined = args[0];
const target = event?.target;
if (event) {
parentSpan = plugin._eventsSpanMap.get(event);
}
if (once) {
plugin.removePatchedListener(this, type, listener);
}
const span = plugin._createSpan(target, type, parentSpan);
if (span) {
if (event) {
plugin._eventsSpanMap.set(event, span);
}
return api.context.with(
api.trace.setSpan(api.context.active(), span),
() => {
const result = plugin._invokeListener(listener, this, args);
// no zone so end span immediately
span.end();
return result;
}
);
} else {
return plugin._invokeListener(listener, this, args);
}
};
if (plugin.addPatchedListener(this, type, listener, patchedListener)) {
return original.call(this, type, patchedListener, useCapture);
}
};
};
}
/**
* This patches the removeEventListener of HTMLElement to handle the fact that
* we patched the original callbacks
* This is done when zone is not available
*/
private _patchRemoveEventListener() {
const plugin = this;
return (original: Function) => {
return function removeEventListenerPatched(
this: HTMLElement,
type: any,
listener: any,
useCapture: any
) {
const wrappedListener = plugin.removePatchedListener(
this,
type,
listener
);
if (wrappedListener) {
return original.call(this, type, wrappedListener, useCapture);
} else {
return original.call(this, type, listener, useCapture);
}
};
};
}
/**
* Most browser provide event listener api via EventTarget in prototype chain.
* Exception to this is IE 11 which has it on the prototypes closest to EventTarget:
*
* * - has addEventListener in IE
* ** - has addEventListener in all other browsers
* ! - missing in IE
*
* HTMLElement -> Element -> Node * -> EventTarget **! -> Object
* Document -> Node * -> EventTarget **! -> Object
* Window * -> WindowProperties ! -> EventTarget **! -> Object
*/
private _getPatchableEventTargets(): EventTarget[] {
return window.EventTarget
? [EventTarget.prototype]
: [Node.prototype, Window.prototype];
}
/**
* Patches the history api
*/
_patchHistoryApi() {
this._unpatchHistoryApi();
this._wrap(history, 'replaceState', this._patchHistoryMethod());
this._wrap(history, 'pushState', this._patchHistoryMethod());
this._wrap(history, 'back', this._patchHistoryMethod());
this._wrap(history, 'forward', this._patchHistoryMethod());
this._wrap(history, 'go', this._patchHistoryMethod());
}
/**
* Patches the certain history api method
*/
_patchHistoryMethod() {
const plugin = this;
return (original: any) => {
return function patchHistoryMethod(this: History, ...args: unknown[]) {
const url = `${location.pathname}${location.hash}${location.search}`;
const result = original.apply(this, args);
const urlAfter = `${location.pathname}${location.hash}${location.search}`;
if (url !== urlAfter) {
plugin._updateInteractionName(urlAfter);
}
return result;
};
};
}
/**
* unpatch the history api methods
*/
_unpatchHistoryApi() {
if (isWrapped(history.replaceState)) this._unwrap(history, 'replaceState');
if (isWrapped(history.pushState)) this._unwrap(history, 'pushState');
if (isWrapped(history.back)) this._unwrap(history, 'back');
if (isWrapped(history.forward)) this._unwrap(history, 'forward');
if (isWrapped(history.go)) this._unwrap(history, 'go');
}
/**
* Updates interaction span name
* @param url
*/
_updateInteractionName(url: string) {
const span: api.Span | undefined = api.trace.getSpan(api.context.active());
if (span && typeof span.updateName === 'function') {
span.updateName(`${EVENT_NAVIGATION_NAME} ${url}`);
}
}
/**
* Patches zone cancel task - this is done to be able to correctly
* decrement the number of remaining tasks
*/
private _patchZoneCancelTask() {
const plugin = this;
return (original: any) => {
return function patchCancelTask<T extends Task>(
this: Zone,
task: AsyncTask
) {
const currentZone = Zone.current;
const currentSpan = plugin._getCurrentSpan(currentZone);
if (currentSpan && plugin._shouldCountTask(task, currentZone)) {
plugin._decrementTask(currentSpan);
}
return original.call(this, task) as T;
};
};
}
/**
* Patches zone schedule task - this is done to be able to correctly
* increment the number of tasks running within current zone but also to
* save time in case of timeout running from xhr plugin when waiting for
* main request from PerformanceResourceTiming
*/
private _patchZoneScheduleTask() {
const plugin = this;
return (original: any) => {
return function patchScheduleTask<T extends Task>(
this: Zone,
task: AsyncTask
) {
const currentZone = Zone.current;
const currentSpan = plugin._getCurrentSpan(currentZone);
if (currentSpan && plugin._shouldCountTask(task, currentZone)) {
plugin._incrementTask(currentSpan);
plugin._checkForTimeout(task, currentSpan);
}
return original.call(this, task) as T;
};
};
}
/**
* Patches zone run task - this is done to be able to create a span when
* user interaction starts
* @private
*/
private _patchZoneRunTask() {
const plugin = this;
return (original: RunTaskFunction): RunTaskFunction => {
return function patchRunTask(
this: Zone,
task: AsyncTask,
applyThis?: any,
applyArgs?: any
): Zone {
const event =
Array.isArray(applyArgs) && applyArgs[0] instanceof Event
? applyArgs[0]
: undefined;
const target = event?.target;
let span: api.Span | undefined;
const activeZone = this;
if (target) {
span = plugin._createSpan(target, task.eventName);
if (span) {
plugin._incrementTask(span);
return activeZone.run(() => {
try {
return api.context.with(
api.trace.setSpan(api.context.active(), span!),
() => {
const currentZone = Zone.current;
task._zone = currentZone;
return original.call(
currentZone,
task,
applyThis,
applyArgs
);
}
);
} finally {
plugin._decrementTask(span as api.Span);
}
});
}
} else {
span = plugin._getCurrentSpan(activeZone);
}
try {
return original.call(activeZone, task, applyThis, applyArgs);
} finally {
if (span && plugin._shouldCountTask(task, activeZone)) {
plugin._decrementTask(span);
}
}
};
};
}
/**
* Decides if task should be counted.
* @param task
* @param currentZone
* @private
*/
private _shouldCountTask(task: AsyncTask, currentZone: Zone): boolean {
if (task._zone) {
currentZone = task._zone;
}
if (!currentZone || !task.data || task.data.isPeriodic) {
return false;
}
const currentSpan = this._getCurrentSpan(currentZone);
if (!currentSpan) {
return false;
}
if (!this._spansData.get(currentSpan)) {
return false;
}
return task.type === 'macroTask' || task.type === 'microTask';
}
/**
* Will try to end span when such span still exists.
* @param span
* @param endTime
* @private
*/
private _tryToEndSpan(span: api.Span, endTime?: api.HrTime) {
if (span) {
const spanData = this._spansData.get(span);
if (spanData) {
span.end(endTime);
this._spansData.delete(span);
}
}
}
/**
* implements enable function
*/
override enable() {
const ZoneWithPrototype = this.getZoneWithPrototype();
api.diag.debug(
'applying patch to',
this.moduleName,
this.version,
'zone:',
!!ZoneWithPrototype
);
if (ZoneWithPrototype) {
if (isWrapped(ZoneWithPrototype.prototype.runTask)) {
this._unwrap(ZoneWithPrototype.prototype, 'runTask');
api.diag.debug('removing previous patch from method runTask');
}
if (isWrapped(ZoneWithPrototype.prototype.scheduleTask)) {
this._unwrap(ZoneWithPrototype.prototype, 'scheduleTask');
api.diag.debug('removing previous patch from method scheduleTask');
}
if (isWrapped(ZoneWithPrototype.prototype.cancelTask)) {
this._unwrap(ZoneWithPrototype.prototype, 'cancelTask');
api.diag.debug('removing previous patch from method cancelTask');
}
this._zonePatched = true;
this._wrap(
ZoneWithPrototype.prototype,
'runTask',
this._patchZoneRunTask()
);
this._wrap(
ZoneWithPrototype.prototype,
'scheduleTask',
this._patchZoneScheduleTask()
);
this._wrap(
ZoneWithPrototype.prototype,
'cancelTask',
this._patchZoneCancelTask()
);
} else {
this._zonePatched = false;
const targets = this._getPatchableEventTargets();
targets.forEach(target => {
if (isWrapped(target.addEventListener)) {
this._unwrap(target, 'addEventListener');
api.diag.debug(
'removing previous patch from method addEventListener'
);
}
if (isWrapped(target.removeEventListener)) {
this._unwrap(target, 'removeEventListener');
api.diag.debug(
'removing previous patch from method removeEventListener'
);
}
this._wrap(target, 'addEventListener', this._patchAddEventListener());
this._wrap(
target,
'removeEventListener',
this._patchRemoveEventListener()
);
});
}
this._patchHistoryApi();
}
/**
* implements unpatch function
*/
override disable() {
const ZoneWithPrototype = this.getZoneWithPrototype();
api.diag.debug(
'removing patch from',
this.moduleName,
this.version,
'zone:',
!!ZoneWithPrototype
);
if (ZoneWithPrototype && this._zonePatched) {
if (isWrapped(ZoneWithPrototype.prototype.runTask)) {
this._unwrap(ZoneWithPrototype.prototype, 'runTask');
}
if (isWrapped(ZoneWithPrototype.prototype.scheduleTask)) {
this._unwrap(ZoneWithPrototype.prototype, 'scheduleTask');
}
if (isWrapped(ZoneWithPrototype.prototype.cancelTask)) {
this._unwrap(ZoneWithPrototype.prototype, 'cancelTask');
}
} else {
const targets = this._getPatchableEventTargets();
targets.forEach(target => {
if (isWrapped(target.addEventListener)) {
this._unwrap(target, 'addEventListener');
}
if (isWrapped(target.removeEventListener)) {
this._unwrap(target, 'removeEventListener');
}
});
}
this._unpatchHistoryApi();
}
/**
* returns Zone
*/
getZoneWithPrototype(): ZoneTypeWithPrototype | undefined {
const _window: WindowWithZone = window as unknown as WindowWithZone;
return _window.Zone;
}
}