-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathbrowserTracingIntegration.ts
512 lines (444 loc) · 16.2 KB
/
browserTracingIntegration.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
/* eslint-disable max-lines */
import {
addHistoryInstrumentationHandler,
addPerformanceEntries,
registerInpInteractionListener,
startTrackingINP,
startTrackingInteractions,
startTrackingLongAnimationFrames,
startTrackingLongTasks,
startTrackingWebVitals,
} from '@sentry-internal/browser-utils';
import {
SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON,
SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,
SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,
TRACING_DEFAULTS,
getActiveSpan,
getClient,
getCurrentScope,
getDynamicSamplingContextFromSpan,
getIsolationScope,
getRootSpan,
registerSpanErrorInstrumentation,
spanIsSampled,
spanToJSON,
startIdleSpan,
} from '@sentry/core';
import type { Client, IntegrationFn, StartSpanOptions, TransactionSource } from '@sentry/types';
import type { Span } from '@sentry/types';
import {
browserPerformanceTimeOrigin,
generatePropagationContext,
getDomElement,
logger,
propagationContextFromHeaders,
} from '@sentry/utils';
import { DEBUG_BUILD } from '../debug-build';
import { WINDOW } from '../helpers';
import { registerBackgroundTabDetection } from './backgroundtab';
import { defaultRequestInstrumentationOptions, instrumentOutgoingRequests } from './request';
export const BROWSER_TRACING_INTEGRATION_ID = 'BrowserTracing';
interface RouteInfo {
name: string | undefined;
source: TransactionSource | undefined;
}
/** Options for Browser Tracing integration */
export interface BrowserTracingOptions {
/**
* The time that has to pass without any span being created.
* If this time is exceeded, the idle span will finish.
*
* Default: 1000 (ms)
*/
idleTimeout: number;
/**
* The max. time an idle span may run.
* If this time is exceeded, the idle span will finish no matter what.
*
* Default: 30000 (ms)
*/
finalTimeout: number;
/**
The max. time an idle span may run.
* If this time is exceeded, the idle span will finish no matter what.
*
* Default: 15000 (ms)
*/
childSpanTimeout: number;
/**
* If a span should be created on page load.
* If this is set to `false`, this integration will not start the default page load span.
* Default: true
*/
instrumentPageLoad: boolean;
/**
* If a span should be created on navigation (history change).
* If this is set to `false`, this integration will not start the default navigation spans.
* Default: true
*/
instrumentNavigation: boolean;
/**
* Flag spans where tabs moved to background with "cancelled". Browser background tab timing is
* not suited towards doing precise measurements of operations. By default, we recommend that this option
* be enabled as background transactions can mess up your statistics in nondeterministic ways.
*
* Default: true
*/
markBackgroundSpan: boolean;
/**
* If true, Sentry will capture long tasks and add them to the corresponding transaction.
*
* Default: true
*/
enableLongTask: boolean;
/**
* If true, Sentry will capture long animation frames and add them to the corresponding transaction.
*
* Default: false
*/
enableLongAnimationFrame: boolean;
/**
* If true, Sentry will capture first input delay and add it to the corresponding transaction.
*
* Default: true
*/
enableInp: boolean;
/**
* Flag to disable patching all together for fetch requests.
*
* Default: true
*/
traceFetch: boolean;
/**
* Flag to disable patching all together for xhr requests.
*
* Default: true
*/
traceXHR: boolean;
/**
* If true, Sentry will capture http timings and add them to the corresponding http spans.
*
* Default: true
*/
enableHTTPTimings: boolean;
/**
* _experiments allows the user to send options to define how this integration works.
*
* Default: undefined
*/
_experiments: Partial<{
enableInteractions: boolean;
}>;
/**
* A callback which is called before a span for a pageload or navigation is started.
* It receives the options passed to `startSpan`, and expects to return an updated options object.
*/
beforeStartSpan?: (options: StartSpanOptions) => StartSpanOptions;
/**
* This function will be called before creating a span for a request with the given url.
* Return false if you don't want a span for the given url.
*
* Default: (url: string) => true
*/
shouldCreateSpanForRequest?(this: void, url: string): boolean;
}
const DEFAULT_BROWSER_TRACING_OPTIONS: BrowserTracingOptions = {
...TRACING_DEFAULTS,
instrumentNavigation: true,
instrumentPageLoad: true,
markBackgroundSpan: true,
enableLongTask: true,
enableLongAnimationFrame: false,
enableInp: true,
_experiments: {},
...defaultRequestInstrumentationOptions,
};
/**
* The Browser Tracing integration automatically instruments browser pageload/navigation
* actions as transactions, and captures requests, metrics and errors as spans.
*
* The integration can be configured with a variety of options, and can be extended to use
* any routing library.
*
* We explicitly export the proper type here, as this has to be extended in some cases.
*/
export const browserTracingIntegration = ((_options: Partial<BrowserTracingOptions> = {}) => {
registerSpanErrorInstrumentation();
const {
enableInp,
enableLongTask,
enableLongAnimationFrame,
_experiments: { enableInteractions },
beforeStartSpan,
idleTimeout,
finalTimeout,
childSpanTimeout,
markBackgroundSpan,
traceFetch,
traceXHR,
shouldCreateSpanForRequest,
enableHTTPTimings,
instrumentPageLoad,
instrumentNavigation,
} = {
...DEFAULT_BROWSER_TRACING_OPTIONS,
..._options,
};
const _collectWebVitals = startTrackingWebVitals();
if (enableInp) {
startTrackingINP();
}
if (enableLongAnimationFrame && PerformanceObserver.supportedEntryTypes.includes('long-animation-frame')) {
startTrackingLongAnimationFrames();
} else if (enableLongTask) {
startTrackingLongTasks();
}
if (enableInteractions) {
startTrackingInteractions();
}
const latestRoute: RouteInfo = {
name: undefined,
source: undefined,
};
/** Create routing idle transaction. */
function _createRouteSpan(client: Client, startSpanOptions: StartSpanOptions): Span {
const isPageloadTransaction = startSpanOptions.op === 'pageload';
const finalStartSpanOptions: StartSpanOptions = beforeStartSpan
? beforeStartSpan(startSpanOptions)
: startSpanOptions;
const attributes = finalStartSpanOptions.attributes || {};
// If `finalStartSpanOptions.name` is different than `startSpanOptions.name`
// it is because `beforeStartSpan` set a custom name. Therefore we set the source to 'custom'.
if (startSpanOptions.name !== finalStartSpanOptions.name) {
attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] = 'custom';
finalStartSpanOptions.attributes = attributes;
}
latestRoute.name = finalStartSpanOptions.name;
latestRoute.source = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];
const idleSpan = startIdleSpan(finalStartSpanOptions, {
idleTimeout,
finalTimeout,
childSpanTimeout,
// should wait for finish signal if it's a pageload transaction
disableAutoFinish: isPageloadTransaction,
beforeSpanEnd: span => {
_collectWebVitals();
addPerformanceEntries(span);
},
});
function emitFinish(): void {
if (['interactive', 'complete'].includes(WINDOW.document.readyState)) {
client.emit('idleSpanEnableAutoFinish', idleSpan);
}
}
if (isPageloadTransaction && WINDOW.document) {
WINDOW.document.addEventListener('readystatechange', () => {
emitFinish();
});
emitFinish();
}
return idleSpan;
}
return {
name: BROWSER_TRACING_INTEGRATION_ID,
afterAllSetup(client) {
let activeSpan: Span | undefined;
let startingUrl: string | undefined = WINDOW.location && WINDOW.location.href;
client.on('startNavigationSpan', startSpanOptions => {
if (getClient() !== client) {
return;
}
if (activeSpan) {
DEBUG_BUILD && logger.log(`[Tracing] Finishing current root span with op: ${spanToJSON(activeSpan).op}`);
// If there's an open transaction on the scope, we need to finish it before creating an new one.
activeSpan.end();
}
activeSpan = _createRouteSpan(client, {
op: 'navigation',
...startSpanOptions,
});
});
client.on('startPageLoadSpan', (startSpanOptions, traceOptions = {}) => {
if (getClient() !== client) {
return;
}
if (activeSpan) {
DEBUG_BUILD && logger.log(`[Tracing] Finishing current root span with op: ${spanToJSON(activeSpan).op}`);
// If there's an open transaction on the scope, we need to finish it before creating an new one.
activeSpan.end();
}
const sentryTrace = traceOptions.sentryTrace || getMetaContent('sentry-trace');
const baggage = traceOptions.baggage || getMetaContent('baggage');
const propagationContext = propagationContextFromHeaders(sentryTrace, baggage);
getCurrentScope().setPropagationContext(propagationContext);
activeSpan = _createRouteSpan(client, {
op: 'pageload',
...startSpanOptions,
});
});
// A trace should to stay the consistent over the entire time span of one route.
// Therefore, when the initial pageload or navigation root span ends, we update the
// scope's propagation context to keep span-specific attributes like the `sampled` decision and
// the dynamic sampling context valid, even after the root span has ended.
// This ensures that the trace data is consistent for the entire duration of the route.
client.on('spanEnd', span => {
const op = spanToJSON(span).op;
if (span !== getRootSpan(span) || (op !== 'navigation' && op !== 'pageload')) {
return;
}
const scope = getCurrentScope();
const oldPropagationContext = scope.getPropagationContext();
scope.setPropagationContext({
...oldPropagationContext,
sampled: oldPropagationContext.sampled !== undefined ? oldPropagationContext.sampled : spanIsSampled(span),
dsc: oldPropagationContext.dsc || getDynamicSamplingContextFromSpan(span),
});
});
if (WINDOW.location) {
if (instrumentPageLoad) {
startBrowserTracingPageLoadSpan(client, {
name: WINDOW.location.pathname,
// pageload should always start at timeOrigin (and needs to be in s, not ms)
startTime: browserPerformanceTimeOrigin ? browserPerformanceTimeOrigin / 1000 : undefined,
attributes: {
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'url',
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.pageload.browser',
},
});
}
if (instrumentNavigation) {
addHistoryInstrumentationHandler(({ to, from }) => {
/**
* This early return is there to account for some cases where a navigation transaction starts right after
* long-running pageload. We make sure that if `from` is undefined and a valid `startingURL` exists, we don't
* create an uneccessary navigation transaction.
*
* This was hard to duplicate, but this behavior stopped as soon as this fix was applied. This issue might also
* only be caused in certain development environments where the usage of a hot module reloader is causing
* errors.
*/
if (from === undefined && startingUrl && startingUrl.indexOf(to) !== -1) {
startingUrl = undefined;
return;
}
if (from !== to) {
startingUrl = undefined;
startBrowserTracingNavigationSpan(client, {
name: WINDOW.location.pathname,
attributes: {
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'url',
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.navigation.browser',
},
});
}
});
}
}
if (markBackgroundSpan) {
registerBackgroundTabDetection();
}
if (enableInteractions) {
registerInteractionListener(idleTimeout, finalTimeout, childSpanTimeout, latestRoute);
}
if (enableInp) {
registerInpInteractionListener(latestRoute);
}
instrumentOutgoingRequests({
traceFetch,
traceXHR,
tracePropagationTargets: client.getOptions().tracePropagationTargets,
shouldCreateSpanForRequest,
enableHTTPTimings,
});
},
};
}) satisfies IntegrationFn;
/**
* Manually start a page load span.
* This will only do something if a browser tracing integration integration has been setup.
*
* If you provide a custom `traceOptions` object, it will be used to continue the trace
* instead of the default behavior, which is to look it up on the <meta> tags.
*/
export function startBrowserTracingPageLoadSpan(
client: Client,
spanOptions: StartSpanOptions,
traceOptions?: { sentryTrace?: string | undefined; baggage?: string | undefined },
): Span | undefined {
client.emit('startPageLoadSpan', spanOptions, traceOptions);
getCurrentScope().setTransactionName(spanOptions.name);
const span = getActiveSpan();
const op = span && spanToJSON(span).op;
return op === 'pageload' ? span : undefined;
}
/**
* Manually start a navigation span.
* This will only do something if a browser tracing integration has been setup.
*/
export function startBrowserTracingNavigationSpan(client: Client, spanOptions: StartSpanOptions): Span | undefined {
getIsolationScope().setPropagationContext(generatePropagationContext());
getCurrentScope().setPropagationContext(generatePropagationContext());
client.emit('startNavigationSpan', spanOptions);
getCurrentScope().setTransactionName(spanOptions.name);
const span = getActiveSpan();
const op = span && spanToJSON(span).op;
return op === 'navigation' ? span : undefined;
}
/** Returns the value of a meta tag */
export function getMetaContent(metaName: string): string | undefined {
// Can't specify generic to `getDomElement` because tracing can be used
// in a variety of environments, have to disable `no-unsafe-member-access`
// as a result.
const metaTag = getDomElement(`meta[name=${metaName}]`);
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
return metaTag ? metaTag.getAttribute('content') : undefined;
}
/** Start listener for interaction transactions */
function registerInteractionListener(
idleTimeout: BrowserTracingOptions['idleTimeout'],
finalTimeout: BrowserTracingOptions['finalTimeout'],
childSpanTimeout: BrowserTracingOptions['childSpanTimeout'],
latestRoute: RouteInfo,
): void {
let inflightInteractionSpan: Span | undefined;
const registerInteractionTransaction = (): void => {
const op = 'ui.action.click';
const activeSpan = getActiveSpan();
const rootSpan = activeSpan && getRootSpan(activeSpan);
if (rootSpan) {
const currentRootSpanOp = spanToJSON(rootSpan).op;
if (['navigation', 'pageload'].includes(currentRootSpanOp as string)) {
DEBUG_BUILD &&
logger.warn(`[Tracing] Did not create ${op} span because a pageload or navigation span is in progress.`);
return undefined;
}
}
if (inflightInteractionSpan) {
inflightInteractionSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON, 'interactionInterrupted');
inflightInteractionSpan.end();
inflightInteractionSpan = undefined;
}
if (!latestRoute.name) {
DEBUG_BUILD && logger.warn(`[Tracing] Did not create ${op} transaction because _latestRouteName is missing.`);
return undefined;
}
inflightInteractionSpan = startIdleSpan(
{
name: latestRoute.name,
op,
attributes: {
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: latestRoute.source || 'url',
},
},
{
idleTimeout,
finalTimeout,
childSpanTimeout,
},
);
};
if (WINDOW.document) {
addEventListener('click', registerInteractionTransaction, { once: false, capture: true });
}
}