-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathbrowsertracing.ts
More file actions
268 lines (228 loc) · 9.36 KB
/
browsertracing.ts
File metadata and controls
268 lines (228 loc) · 9.36 KB
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
import { Hub } from '@sentry/hub';
import { EventProcessor, Integration, Transaction, TransactionContext } from '@sentry/types';
import { getGlobalObject, logger } from '@sentry/utils';
import { startIdleTransaction } from '../hubextensions';
import { DEFAULT_IDLE_TIMEOUT, IdleTransaction } from '../idletransaction';
import { SpanStatus } from '../spanstatus';
import { extractSentrytraceData, extractTracestateData, secToMs } from '../utils';
import { registerBackgroundTabDetection } from './backgroundtab';
import { MetricsInstrumentation } from './metrics';
import {
defaultRequestInstrumentationOptions,
registerRequestInstrumentation,
RequestInstrumentationOptions,
} from './request';
import { defaultRoutingInstrumentation } from './router';
export const DEFAULT_MAX_TRANSACTION_DURATION_SECONDS = 600;
/** Options for Browser Tracing integration */
export interface BrowserTracingOptions extends RequestInstrumentationOptions {
/**
* The time to wait in ms until the transaction will be finished. The transaction will use the end timestamp of
* the last finished span as the endtime for the transaction.
* Time is in ms.
*
* Default: 1000
*/
idleTimeout: number;
/**
* Flag to enable/disable creation of `navigation` transaction on history changes.
*
* Default: true
*/
startTransactionOnLocationChange: boolean;
/**
* Flag to enable/disable creation of `pageload` transaction on first pageload.
*
* Default: true
*/
startTransactionOnPageLoad: boolean;
/**
* The maximum duration of a transaction before it will be marked as "deadline_exceeded".
* If you never want to mark a transaction set it to 0.
* Time is in seconds.
*
* Default: 600
*/
maxTransactionDuration: number;
/**
* Flag Transactions 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
*/
markBackgroundTransactions: boolean;
/**
* beforeNavigate is called before a pageload/navigation transaction is created and allows users to modify transaction
* context data, or drop the transaction entirely (by setting `sampled = false` in the context).
*
* Note: For legacy reasons, transactions can also be dropped by returning `undefined`.
*
* @param context: The context data which will be passed to `startTransaction` by default
*
* @returns A (potentially) modified context object, with `sampled = false` if the transaction should be dropped.
*/
beforeNavigate?(context: TransactionContext): TransactionContext | undefined;
/**
* Instrumentation that creates routing change transactions. By default creates
* pageload and navigation transactions.
*/
routingInstrumentation<T extends Transaction>(
startTransaction: (context: TransactionContext) => T | undefined,
startTransactionOnPageLoad?: boolean,
startTransactionOnLocationChange?: boolean,
): void;
}
const DEFAULT_BROWSER_TRACING_OPTIONS = {
idleTimeout: DEFAULT_IDLE_TIMEOUT,
markBackgroundTransactions: true,
maxTransactionDuration: DEFAULT_MAX_TRANSACTION_DURATION_SECONDS,
routingInstrumentation: defaultRoutingInstrumentation,
startTransactionOnLocationChange: true,
startTransactionOnPageLoad: true,
...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. This integration uses {@see IdleTransaction} to create transactions.
*/
export class BrowserTracing implements Integration {
/**
* @inheritDoc
*/
public static id: string = 'BrowserTracing';
/** Browser Tracing integration options */
public options: BrowserTracingOptions;
/**
* @inheritDoc
*/
public name: string = BrowserTracing.id;
private _getCurrentHub?: () => Hub;
private readonly _metrics: MetricsInstrumentation = new MetricsInstrumentation();
private readonly _emitOptionsWarning: boolean = false;
public constructor(_options?: Partial<BrowserTracingOptions>) {
let tracingOrigins = defaultRequestInstrumentationOptions.tracingOrigins;
// NOTE: Logger doesn't work in constructors, as it's initialized after integrations instances
if (
_options &&
_options.tracingOrigins &&
Array.isArray(_options.tracingOrigins) &&
_options.tracingOrigins.length !== 0
) {
tracingOrigins = _options.tracingOrigins;
} else {
this._emitOptionsWarning = true;
}
this.options = {
...DEFAULT_BROWSER_TRACING_OPTIONS,
..._options,
tracingOrigins,
};
}
/**
* @inheritDoc
*/
public setupOnce(_: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {
this._getCurrentHub = getCurrentHub;
if (this._emitOptionsWarning) {
logger.warn(
'[Tracing] You need to define `tracingOrigins` in the options. Set an array of urls or patterns to trace.',
);
logger.warn(
`[Tracing] We added a reasonable default for you: ${defaultRequestInstrumentationOptions.tracingOrigins}`,
);
}
// eslint-disable-next-line @typescript-eslint/unbound-method
const {
routingInstrumentation,
startTransactionOnLocationChange,
startTransactionOnPageLoad,
markBackgroundTransactions,
traceFetch,
traceXHR,
tracingOrigins,
shouldCreateSpanForRequest,
} = this.options;
routingInstrumentation(
(context: TransactionContext) => this._createRouteTransaction(context),
startTransactionOnPageLoad,
startTransactionOnLocationChange,
);
if (markBackgroundTransactions) {
registerBackgroundTabDetection();
}
registerRequestInstrumentation({ traceFetch, traceXHR, tracingOrigins, shouldCreateSpanForRequest });
}
/** Create routing idle transaction. */
private _createRouteTransaction(context: TransactionContext): Transaction | undefined {
if (!this._getCurrentHub) {
logger.warn(`[Tracing] Did not create ${context.op} transaction because _getCurrentHub is invalid.`);
return undefined;
}
// eslint-disable-next-line @typescript-eslint/unbound-method
const { beforeNavigate, idleTimeout, maxTransactionDuration } = this.options;
const parentContextFromHeader = context.op === 'pageload' ? extractTraceDataFromMetaTags() : undefined;
const expandedContext = {
...context,
...parentContextFromHeader,
trimEnd: true,
};
const modifiedContext = typeof beforeNavigate === 'function' ? beforeNavigate(expandedContext) : expandedContext;
// For backwards compatibility reasons, beforeNavigate can return undefined to "drop" the transaction (prevent it
// from being sent to Sentry).
const finalContext = modifiedContext === undefined ? { ...expandedContext, sampled: false } : modifiedContext;
if (finalContext.sampled === false) {
logger.log(`[Tracing] Will not send ${finalContext.op} transaction because of beforeNavigate.`);
}
logger.log(`[Tracing] Starting ${finalContext.op} transaction on scope`);
const hub = this._getCurrentHub();
const { location } = getGlobalObject() as WindowOrWorkerGlobalScope & { location: Location };
const idleTransaction = startIdleTransaction(
hub,
finalContext,
idleTimeout,
true,
{ location }, // for use in the tracesSampler
);
idleTransaction.registerBeforeFinishCallback((transaction, endTimestamp) => {
this._metrics.addPerformanceEntries(transaction);
adjustTransactionDuration(secToMs(maxTransactionDuration), transaction, endTimestamp);
});
return idleTransaction as Transaction;
}
}
/**
* Gets transaction context data from `sentry-trace` and `tracestate` <meta> tags.
*
* @returns Transaction context data or undefined neither tag exists or has valid data
*/
export function extractTraceDataFromMetaTags(): Partial<TransactionContext> | undefined {
const sentrytraceValue = getMetaContent('sentry-trace');
const tracestateValue = getMetaContent('tracestate');
const sentrytraceData = sentrytraceValue ? extractSentrytraceData(sentrytraceValue) : undefined;
const tracestateData = tracestateValue ? extractTracestateData(tracestateValue) : undefined;
if (sentrytraceData || tracestateData?.sentry || tracestateData?.thirdparty) {
return {
...sentrytraceData,
...(tracestateData && { metadata: { tracestate: tracestateData } }),
};
}
return undefined;
}
/** Returns the value of a meta tag */
export function getMetaContent(metaName: string): string | null {
const el = document.querySelector(`meta[name=${metaName}]`);
return el ? el.getAttribute('content') : null;
}
/** Adjusts transaction value based on max transaction duration */
function adjustTransactionDuration(maxDuration: number, transaction: IdleTransaction, endTimestamp: number): void {
const diff = endTimestamp - transaction.startTimestamp;
const isOutdatedTransaction = endTimestamp && (diff > maxDuration || diff < 0);
if (isOutdatedTransaction) {
transaction.setStatus(SpanStatus.DeadlineExceeded);
transaction.setTag('maxTransactionDurationExceeded', 'true');
}
}