-
Notifications
You must be signed in to change notification settings - Fork 821
/
utils.ts
390 lines (360 loc) · 10.6 KB
/
utils.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
/*
* 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 {
PerformanceEntries,
PerformanceResourceTimingInfo,
PropagateTraceHeaderCorsUrls,
} from './types';
import { PerformanceTimingNames as PTN } from './enums/PerformanceTimingNames';
import * as api from '@opentelemetry/api';
import {
hrTimeToNanoseconds,
timeInputToHrTime,
urlMatches,
} from '@opentelemetry/core';
import { HttpAttribute } from '@opentelemetry/semantic-conventions';
// Used to normalize relative URLs
const urlNormalizingA = document.createElement('a');
/**
* Helper function to be able to use enum as typed key in type and in interface when using forEach
* @param obj
* @param key
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function hasKey<O>(obj: O, key: keyof any): key is keyof O {
return key in obj;
}
/**
* Helper function for starting an event on span based on {@link PerformanceEntries}
* @param span
* @param performanceName name of performance entry for time start
* @param entries
*/
export function addSpanNetworkEvent(
span: api.Span,
performanceName: string,
entries: PerformanceEntries
): api.Span | undefined {
if (
hasKey(entries, performanceName) &&
typeof entries[performanceName] === 'number'
) {
// some metrics are available but have value 0 which means they are invalid
// for example "secureConnectionStart" is 0 which makes the events to be wrongly interpreted
if (entries[performanceName] === 0) {
return undefined;
}
span.addEvent(performanceName, entries[performanceName]);
return span;
}
return undefined;
}
/**
* Helper function for adding network events
* @param span
* @param resource
*/
export function addSpanNetworkEvents(
span: api.Span,
resource: PerformanceEntries
): void {
addSpanNetworkEvent(span, PTN.FETCH_START, resource);
addSpanNetworkEvent(span, PTN.DOMAIN_LOOKUP_START, resource);
addSpanNetworkEvent(span, PTN.DOMAIN_LOOKUP_END, resource);
addSpanNetworkEvent(span, PTN.CONNECT_START, resource);
addSpanNetworkEvent(span, PTN.SECURE_CONNECTION_START, resource);
addSpanNetworkEvent(span, PTN.CONNECT_END, resource);
addSpanNetworkEvent(span, PTN.REQUEST_START, resource);
addSpanNetworkEvent(span, PTN.RESPONSE_START, resource);
addSpanNetworkEvent(span, PTN.RESPONSE_END, resource);
if (resource[PTN.ENCODED_BODY_SIZE]) {
span.setAttribute(
HttpAttribute.HTTP_RESPONSE_CONTENT_LENGTH,
resource[PTN.ENCODED_BODY_SIZE]
);
}
}
/**
* sort resources by startTime
* @param filteredResources
*/
export function sortResources(filteredResources: PerformanceResourceTiming[]) {
return filteredResources.slice().sort((a, b) => {
const valueA = a[PTN.FETCH_START];
const valueB = b[PTN.FETCH_START];
if (valueA > valueB) {
return 1;
} else if (valueA < valueB) {
return -1;
}
return 0;
});
}
/**
* Get closest performance resource ignoring the resources that have been
* already used.
* @param spanUrl
* @param startTimeHR
* @param endTimeHR
* @param resources
* @param ignoredResources
* @param initiatorType
*/
export function getResource(
spanUrl: string,
startTimeHR: api.HrTime,
endTimeHR: api.HrTime,
resources: PerformanceResourceTiming[],
ignoredResources: WeakSet<PerformanceResourceTiming> = new WeakSet<
PerformanceResourceTiming
>(),
initiatorType?: string
): PerformanceResourceTimingInfo {
// de-relativize the URL before usage (does no harm to absolute URLs)
urlNormalizingA.href = spanUrl;
spanUrl = urlNormalizingA.href;
const filteredResources = filterResourcesForSpan(
spanUrl,
startTimeHR,
endTimeHR,
resources,
ignoredResources,
initiatorType
);
if (filteredResources.length === 0) {
return {
mainRequest: undefined,
};
}
if (filteredResources.length === 1) {
return {
mainRequest: filteredResources[0],
};
}
const sorted = sortResources(filteredResources.slice());
const parsedSpanUrl = parseUrl(spanUrl);
if (parsedSpanUrl.origin !== window.location.origin && sorted.length > 1) {
let corsPreFlightRequest: PerformanceResourceTiming | undefined = sorted[0];
let mainRequest: PerformanceResourceTiming = findMainRequest(
sorted,
corsPreFlightRequest[PTN.RESPONSE_END],
endTimeHR
);
const responseEnd = corsPreFlightRequest[PTN.RESPONSE_END];
const fetchStart = mainRequest[PTN.FETCH_START];
// no corsPreFlightRequest
if (fetchStart < responseEnd) {
mainRequest = corsPreFlightRequest;
corsPreFlightRequest = undefined;
}
return {
corsPreFlightRequest,
mainRequest,
};
} else {
return {
mainRequest: filteredResources[0],
};
}
}
/**
* Will find the main request skipping the cors pre flight requests
* @param resources
* @param corsPreFlightRequestEndTime
* @param spanEndTimeHR
*/
function findMainRequest(
resources: PerformanceResourceTiming[],
corsPreFlightRequestEndTime: number,
spanEndTimeHR: api.HrTime
): PerformanceResourceTiming {
const spanEndTime = hrTimeToNanoseconds(spanEndTimeHR);
const minTime = hrTimeToNanoseconds(
timeInputToHrTime(corsPreFlightRequestEndTime)
);
let mainRequest: PerformanceResourceTiming = resources[1];
let bestGap;
const length = resources.length;
for (let i = 1; i < length; i++) {
const resource = resources[i];
const resourceStartTime = hrTimeToNanoseconds(
timeInputToHrTime(resource[PTN.FETCH_START])
);
const resourceEndTime = hrTimeToNanoseconds(
timeInputToHrTime(resource[PTN.RESPONSE_END])
);
const currentGap = spanEndTime - resourceEndTime;
if (resourceStartTime >= minTime && (!bestGap || currentGap < bestGap)) {
bestGap = currentGap;
mainRequest = resource;
}
}
return mainRequest;
}
/**
* Filter all resources that has started and finished according to span start time and end time.
* It will return the closest resource to a start time
* @param spanUrl
* @param startTimeHR
* @param endTimeHR
* @param resources
* @param ignoredResources
*/
function filterResourcesForSpan(
spanUrl: string,
startTimeHR: api.HrTime,
endTimeHR: api.HrTime,
resources: PerformanceResourceTiming[],
ignoredResources: WeakSet<PerformanceResourceTiming>,
initiatorType?: string
) {
const startTime = hrTimeToNanoseconds(startTimeHR);
const endTime = hrTimeToNanoseconds(endTimeHR);
let filteredResources = resources.filter(resource => {
const resourceStartTime = hrTimeToNanoseconds(
timeInputToHrTime(resource[PTN.FETCH_START])
);
const resourceEndTime = hrTimeToNanoseconds(
timeInputToHrTime(resource[PTN.RESPONSE_END])
);
return (
resource.initiatorType.toLowerCase() ===
(initiatorType || 'xmlhttprequest') &&
resource.name === spanUrl &&
resourceStartTime >= startTime &&
resourceEndTime <= endTime
);
});
if (filteredResources.length > 0) {
filteredResources = filteredResources.filter(resource => {
return !ignoredResources.has(resource);
});
}
return filteredResources;
}
/**
* Parses url using anchor element
* @param url
*/
export function parseUrl(url: string): HTMLAnchorElement {
const a = document.createElement('a');
a.href = url;
return a;
}
/**
* Get element XPath
* @param target - target element
* @param optimised - when id attribute of element is present the xpath can be
* simplified to contain id
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function getElementXPath(target: any, optimised?: boolean) {
if (target.nodeType === Node.DOCUMENT_NODE) {
return '/';
}
const targetValue = getNodeValue(target, optimised);
if (optimised && targetValue.indexOf('@id') > 0) {
return targetValue;
}
let xpath = '';
if (target.parentNode) {
xpath += getElementXPath(target.parentNode, false);
}
xpath += targetValue;
return xpath;
}
/**
* get node index within the siblings
* @param target
*/
function getNodeIndex(target: HTMLElement): number {
if (!target.parentNode) {
return 0;
}
const allowedTypes = [target.nodeType];
if (target.nodeType === Node.CDATA_SECTION_NODE) {
allowedTypes.push(Node.TEXT_NODE);
}
let elements = Array.from(target.parentNode.childNodes);
elements = elements.filter((element: Node) => {
const localName = (element as HTMLElement).localName;
return (
allowedTypes.indexOf(element.nodeType) >= 0 &&
localName === target.localName
);
});
if (elements.length >= 1) {
return elements.indexOf(target) + 1; // xpath starts from 1
}
// if there are no other similar child xpath doesn't need index
return 0;
}
/**
* get node value for xpath
* @param target
* @param optimised
*/
function getNodeValue(target: HTMLElement, optimised?: boolean): string {
const nodeType = target.nodeType;
const index = getNodeIndex(target);
let nodeValue = '';
if (nodeType === Node.ELEMENT_NODE) {
const id = target.getAttribute('id');
if (optimised && id) {
return `//*[@id="${id}"]`;
}
nodeValue = target.localName;
} else if (
nodeType === Node.TEXT_NODE ||
nodeType === Node.CDATA_SECTION_NODE
) {
nodeValue = 'text()';
} else if (nodeType === Node.COMMENT_NODE) {
nodeValue = 'comment()';
} else {
return '';
}
// if index is 1 it can be omitted in xpath
if (nodeValue && index > 1) {
return `/${nodeValue}[${index}]`;
}
return `/${nodeValue}`;
}
/**
* Checks if trace headers should be propagated
* @param spanUrl
* @private
*/
export function shouldPropagateTraceHeaders(
spanUrl: string,
propagateTraceHeaderCorsUrls?: PropagateTraceHeaderCorsUrls
) {
let propagateTraceHeaderUrls = propagateTraceHeaderCorsUrls || [];
if (
typeof propagateTraceHeaderUrls === 'string' ||
propagateTraceHeaderUrls instanceof RegExp
) {
propagateTraceHeaderUrls = [propagateTraceHeaderUrls];
}
const parsedSpanUrl = parseUrl(spanUrl);
if (parsedSpanUrl.origin === window.location.origin) {
return true;
} else {
return propagateTraceHeaderUrls.some(propagateTraceHeaderUrl =>
urlMatches(spanUrl, propagateTraceHeaderUrl)
);
}
}