forked from getsentry/sentry-javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
437 lines (377 loc) · 14.8 KB
/
index.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
/* eslint-disable max-lines */
import { Measurements } from '@sentry/types';
import { browserPerformanceTimeOrigin, htmlTreeAsString, logger, WINDOW } from '@sentry/utils';
import { IdleTransaction } from '../../idletransaction';
import { Transaction } from '../../transaction';
import { getActiveTransaction, msToSec } from '../../utils';
import { getCLS, LayoutShift } from '../web-vitals/getCLS';
import { getFID } from '../web-vitals/getFID';
import { getLCP, LargestContentfulPaint } from '../web-vitals/getLCP';
import { getVisibilityWatcher } from '../web-vitals/lib/getVisibilityWatcher';
import { observe, PerformanceEntryHandler } from '../web-vitals/lib/observe';
import { NavigatorDeviceMemory, NavigatorNetworkInformation } from '../web-vitals/types';
import { _startChild, isMeasurementValue } from './utils';
function getBrowserPerformanceAPI(): Performance | undefined {
return WINDOW && WINDOW.addEventListener && WINDOW.performance;
}
let _performanceCursor: number = 0;
let _measurements: Measurements = {};
let _lcpEntry: LargestContentfulPaint | undefined;
let _clsEntry: LayoutShift | undefined;
/**
* Start tracking web vitals
*/
export function startTrackingWebVitals(reportAllChanges: boolean = false): void {
const performance = getBrowserPerformanceAPI();
if (performance && browserPerformanceTimeOrigin) {
if (performance.mark) {
WINDOW.performance.mark('sentry-tracing-init');
}
_trackCLS();
_trackLCP(reportAllChanges);
_trackFID();
}
}
/**
* Start tracking long tasks.
*/
export function startTrackingLongTasks(): void {
const entryHandler: PerformanceEntryHandler = (entry: PerformanceEntry): void => {
const transaction = getActiveTransaction() as IdleTransaction | undefined;
if (!transaction) {
return;
}
const startTime = msToSec((browserPerformanceTimeOrigin as number) + entry.startTime);
const duration = msToSec(entry.duration);
transaction.startChild({
description: 'Main UI thread blocked',
op: 'ui.long-task',
startTimestamp: startTime,
endTimestamp: startTime + duration,
});
};
observe('longtask', entryHandler);
}
/** Starts tracking the Cumulative Layout Shift on the current page. */
function _trackCLS(): void {
// See:
// https://web.dev/evolving-cls/
// https://web.dev/cls-web-tooling/
getCLS(metric => {
const entry = metric.entries.pop();
if (!entry) {
return;
}
__DEBUG_BUILD__ && logger.log('[Measurements] Adding CLS');
_measurements['cls'] = { value: metric.value, unit: '' };
_clsEntry = entry as LayoutShift;
});
}
/** Starts tracking the Largest Contentful Paint on the current page. */
function _trackLCP(reportAllChanges: boolean): void {
getLCP(metric => {
const entry = metric.entries.pop();
if (!entry) {
return;
}
__DEBUG_BUILD__ && logger.log('[Measurements] Adding LCP');
_measurements['lcp'] = { value: metric.value, unit: 'millisecond' };
_lcpEntry = entry as LargestContentfulPaint;
}, reportAllChanges);
}
/** Starts tracking the First Input Delay on the current page. */
function _trackFID(): void {
getFID(metric => {
const entry = metric.entries.pop();
if (!entry) {
return;
}
const timeOrigin = msToSec(browserPerformanceTimeOrigin as number);
const startTime = msToSec(entry.startTime);
__DEBUG_BUILD__ && logger.log('[Measurements] Adding FID');
_measurements['fid'] = { value: metric.value, unit: 'millisecond' };
_measurements['mark.fid'] = { value: timeOrigin + startTime, unit: 'second' };
});
}
/** Add performance related spans to a transaction */
export function addPerformanceEntries(transaction: Transaction): void {
const performance = getBrowserPerformanceAPI();
if (!performance || !WINDOW.performance.getEntries || !browserPerformanceTimeOrigin) {
// Gatekeeper if performance API not available
return;
}
__DEBUG_BUILD__ && logger.log('[Tracing] Adding & adjusting spans using Performance API');
const timeOrigin = msToSec(browserPerformanceTimeOrigin);
const performanceEntries = performance.getEntries();
let responseStartTimestamp: number | undefined;
let requestStartTimestamp: number | undefined;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
performanceEntries.slice(_performanceCursor).forEach((entry: Record<string, any>) => {
const startTime = msToSec(entry.startTime);
const duration = msToSec(entry.duration);
if (transaction.op === 'navigation' && timeOrigin + startTime < transaction.startTimestamp) {
return;
}
switch (entry.entryType) {
case 'navigation': {
_addNavigationSpans(transaction, entry, timeOrigin);
responseStartTimestamp = timeOrigin + msToSec(entry.responseStart);
requestStartTimestamp = timeOrigin + msToSec(entry.requestStart);
break;
}
case 'mark':
case 'paint':
case 'measure': {
_addMeasureSpans(transaction, entry, startTime, duration, timeOrigin);
// capture web vitals
const firstHidden = getVisibilityWatcher();
// Only report if the page wasn't hidden prior to the web vital.
const shouldRecord = entry.startTime < firstHidden.firstHiddenTime;
if (entry.name === 'first-paint' && shouldRecord) {
__DEBUG_BUILD__ && logger.log('[Measurements] Adding FP');
_measurements['fp'] = { value: entry.startTime, unit: 'millisecond' };
}
if (entry.name === 'first-contentful-paint' && shouldRecord) {
__DEBUG_BUILD__ && logger.log('[Measurements] Adding FCP');
_measurements['fcp'] = { value: entry.startTime, unit: 'millisecond' };
}
break;
}
case 'resource': {
const resourceName = (entry.name as string).replace(WINDOW.location.origin, '');
_addResourceSpans(transaction, entry, resourceName, startTime, duration, timeOrigin);
break;
}
default:
// Ignore other entry types.
}
});
_performanceCursor = Math.max(performanceEntries.length - 1, 0);
_trackNavigator(transaction);
// Measurements are only available for pageload transactions
if (transaction.op === 'pageload') {
// Generate TTFB (Time to First Byte), which measured as the time between the beginning of the transaction and the
// start of the response in milliseconds
if (typeof responseStartTimestamp === 'number') {
__DEBUG_BUILD__ && logger.log('[Measurements] Adding TTFB');
_measurements['ttfb'] = {
value: (responseStartTimestamp - transaction.startTimestamp) * 1000,
unit: 'millisecond',
};
if (typeof requestStartTimestamp === 'number' && requestStartTimestamp <= responseStartTimestamp) {
// Capture the time spent making the request and receiving the first byte of the response.
// This is the time between the start of the request and the start of the response in milliseconds.
_measurements['ttfb.requestTime'] = {
value: (responseStartTimestamp - requestStartTimestamp) * 1000,
unit: 'millisecond',
};
}
}
['fcp', 'fp', 'lcp'].forEach(name => {
if (!_measurements[name] || timeOrigin >= transaction.startTimestamp) {
return;
}
// The web vitals, fcp, fp, lcp, and ttfb, all measure relative to timeOrigin.
// Unfortunately, timeOrigin is not captured within the transaction span data, so these web vitals will need
// to be adjusted to be relative to transaction.startTimestamp.
const oldValue = _measurements[name].value;
const measurementTimestamp = timeOrigin + msToSec(oldValue);
// normalizedValue should be in milliseconds
const normalizedValue = Math.abs((measurementTimestamp - transaction.startTimestamp) * 1000);
const delta = normalizedValue - oldValue;
__DEBUG_BUILD__ &&
logger.log(`[Measurements] Normalized ${name} from ${oldValue} to ${normalizedValue} (${delta})`);
_measurements[name].value = normalizedValue;
});
const fidMark = _measurements['mark.fid'];
if (fidMark && _measurements['fid']) {
// create span for FID
_startChild(transaction, {
description: 'first input delay',
endTimestamp: fidMark.value + msToSec(_measurements['fid'].value),
op: 'ui.action',
startTimestamp: fidMark.value,
});
// Delete mark.fid as we don't want it to be part of final payload
delete _measurements['mark.fid'];
}
// If FCP is not recorded we should not record the cls value
// according to the new definition of CLS.
if (!('fcp' in _measurements)) {
delete _measurements.cls;
}
Object.keys(_measurements).forEach(measurementName => {
transaction.setMeasurement(
measurementName,
_measurements[measurementName].value,
_measurements[measurementName].unit,
);
});
_tagMetricInfo(transaction);
}
_lcpEntry = undefined;
_clsEntry = undefined;
_measurements = {};
}
/** Create measure related spans */
export function _addMeasureSpans(
transaction: Transaction,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
entry: Record<string, any>,
startTime: number,
duration: number,
timeOrigin: number,
): number {
const measureStartTimestamp = timeOrigin + startTime;
const measureEndTimestamp = measureStartTimestamp + duration;
_startChild(transaction, {
description: entry.name as string,
endTimestamp: measureEndTimestamp,
op: entry.entryType as string,
startTimestamp: measureStartTimestamp,
});
return measureStartTimestamp;
}
/** Instrument navigation entries */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function _addNavigationSpans(transaction: Transaction, entry: Record<string, any>, timeOrigin: number): void {
['unloadEvent', 'redirect', 'domContentLoadedEvent', 'loadEvent', 'connect'].forEach(event => {
_addPerformanceNavigationTiming(transaction, entry, event, timeOrigin);
});
_addPerformanceNavigationTiming(transaction, entry, 'secureConnection', timeOrigin, 'TLS/SSL', 'connectEnd');
_addPerformanceNavigationTiming(transaction, entry, 'fetch', timeOrigin, 'cache', 'domainLookupStart');
_addPerformanceNavigationTiming(transaction, entry, 'domainLookup', timeOrigin, 'DNS');
_addRequest(transaction, entry, timeOrigin);
}
/** Create performance navigation related spans */
function _addPerformanceNavigationTiming(
transaction: Transaction,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
entry: Record<string, any>,
event: string,
timeOrigin: number,
description?: string,
eventEnd?: string,
): void {
const end = eventEnd ? (entry[eventEnd] as number | undefined) : (entry[`${event}End`] as number | undefined);
const start = entry[`${event}Start`] as number | undefined;
if (!start || !end) {
return;
}
_startChild(transaction, {
op: 'browser',
description: description ?? event,
startTimestamp: timeOrigin + msToSec(start),
endTimestamp: timeOrigin + msToSec(end),
});
}
/** Create request and response related spans */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function _addRequest(transaction: Transaction, entry: Record<string, any>, timeOrigin: number): void {
_startChild(transaction, {
op: 'browser',
description: 'request',
startTimestamp: timeOrigin + msToSec(entry.requestStart as number),
endTimestamp: timeOrigin + msToSec(entry.responseEnd as number),
});
_startChild(transaction, {
op: 'browser',
description: 'response',
startTimestamp: timeOrigin + msToSec(entry.responseStart as number),
endTimestamp: timeOrigin + msToSec(entry.responseEnd as number),
});
}
export interface ResourceEntry extends Record<string, unknown> {
initiatorType?: string;
transferSize?: number;
encodedBodySize?: number;
decodedBodySize?: number;
}
/** Create resource-related spans */
export function _addResourceSpans(
transaction: Transaction,
entry: ResourceEntry,
resourceName: string,
startTime: number,
duration: number,
timeOrigin: number,
): void {
// we already instrument based on fetch and xhr, so we don't need to
// duplicate spans here.
if (entry.initiatorType === 'xmlhttprequest' || entry.initiatorType === 'fetch') {
return;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const data: Record<string, any> = {};
if ('transferSize' in entry) {
data['Transfer Size'] = entry.transferSize;
}
if ('encodedBodySize' in entry) {
data['Encoded Body Size'] = entry.encodedBodySize;
}
if ('decodedBodySize' in entry) {
data['Decoded Body Size'] = entry.decodedBodySize;
}
const startTimestamp = timeOrigin + startTime;
const endTimestamp = startTimestamp + duration;
_startChild(transaction, {
description: resourceName,
endTimestamp,
op: entry.initiatorType ? `resource.${entry.initiatorType}` : 'resource.other',
startTimestamp,
data,
});
}
/**
* Capture the information of the user agent.
*/
function _trackNavigator(transaction: Transaction): void {
const navigator = WINDOW.navigator as null | (Navigator & NavigatorNetworkInformation & NavigatorDeviceMemory);
if (!navigator) {
return;
}
// track network connectivity
const connection = navigator.connection;
if (connection) {
if (connection.effectiveType) {
transaction.setTag('effectiveConnectionType', connection.effectiveType);
}
if (connection.type) {
transaction.setTag('connectionType', connection.type);
}
if (isMeasurementValue(connection.rtt)) {
_measurements['connection.rtt'] = { value: connection.rtt, unit: 'millisecond' };
}
}
if (isMeasurementValue(navigator.deviceMemory)) {
transaction.setTag('deviceMemory', `${navigator.deviceMemory} GB`);
}
if (isMeasurementValue(navigator.hardwareConcurrency)) {
transaction.setTag('hardwareConcurrency', String(navigator.hardwareConcurrency));
}
}
/** Add LCP / CLS data to transaction to allow debugging */
function _tagMetricInfo(transaction: Transaction): void {
if (_lcpEntry) {
__DEBUG_BUILD__ && logger.log('[Measurements] Adding LCP Data');
// Capture Properties of the LCP element that contributes to the LCP.
if (_lcpEntry.element) {
transaction.setTag('lcp.element', htmlTreeAsString(_lcpEntry.element));
}
if (_lcpEntry.id) {
transaction.setTag('lcp.id', _lcpEntry.id);
}
if (_lcpEntry.url) {
// Trim URL to the first 200 characters.
transaction.setTag('lcp.url', _lcpEntry.url.trim().slice(0, 200));
}
transaction.setTag('lcp.size', _lcpEntry.size);
}
// See: https://developer.mozilla.org/en-US/docs/Web/API/LayoutShift
if (_clsEntry && _clsEntry.sources) {
__DEBUG_BUILD__ && logger.log('[Measurements] Adding CLS Data');
_clsEntry.sources.forEach((source, index) =>
transaction.setTag(`cls.source.${index + 1}`, htmlTreeAsString(source.node)),
);
}
}