forked from getsentry/sentry-javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsentry-performance.ts
412 lines (352 loc) · 11.9 KB
/
sentry-performance.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
import ApplicationInstance from '@ember/application/instance';
import Ember from 'ember';
import { run, _backburner, scheduleOnce } from '@ember/runloop';
import * as Sentry from '@sentry/browser';
import { ExtendedBackburner } from '@sentry/ember/runloop';
import { Span, Transaction, Integration } from '@sentry/types';
import { EmberRunQueues } from '@ember/runloop/-private/types';
import { getActiveTransaction } from '..';
import { browserPerformanceTimeOrigin, GLOBAL_OBJ, timestampWithMs } from '@sentry/utils';
import { macroCondition, isTesting, getOwnConfig } from '@embroider/macros';
import { EmberSentryConfig, GlobalConfig, OwnConfig } from '../types';
function getSentryConfig() {
const _global = GLOBAL_OBJ as typeof GLOBAL_OBJ & GlobalConfig;
_global.__sentryEmberConfig = _global.__sentryEmberConfig ?? {};
const environmentConfig = getOwnConfig<OwnConfig>().sentryConfig;
if (!environmentConfig.sentry) {
environmentConfig.sentry = {
browserTracingOptions: {},
};
}
Object.assign(environmentConfig.sentry, _global.__sentryEmberConfig);
return environmentConfig;
}
export function initialize(appInstance: ApplicationInstance): void {
const config = getSentryConfig();
if (config['disablePerformance']) {
return;
}
const performancePromise = instrumentForPerformance(appInstance);
if (macroCondition(isTesting())) {
(<any>window)._sentryPerformanceLoad = performancePromise;
}
}
function getBackburner(): Pick<ExtendedBackburner, 'on' | 'off'> {
if (_backburner) {
return _backburner;
}
if (run.backburner) {
return run.backburner;
}
return {
on() {},
off() {},
};
}
function getTransitionInformation(transition: any, router: any) {
const fromRoute = transition?.from?.name;
const toRoute = transition && transition.to ? transition.to.name : router.currentRouteName;
return {
fromRoute,
toRoute,
};
}
function getLocationURL(location: any) {
if (!location || !location.getURL || !location.formatURL) {
return '';
}
const url = location.formatURL(location.getURL());
if (location.implementation === 'hash') {
return `${location.rootURL}${url}`;
}
return url;
}
export function _instrumentEmberRouter(
routerService: any,
routerMain: any,
config: EmberSentryConfig,
startTransaction: Function,
startTransactionOnPageLoad?: boolean,
) {
const { disableRunloopPerformance } = config;
const location = routerMain.location;
let activeTransaction: Transaction;
let transitionSpan: Span;
const url = getLocationURL(location);
if (macroCondition(isTesting())) {
routerService._sentryInstrumented = true;
routerService._startTransaction = startTransaction;
}
if (startTransactionOnPageLoad && url) {
const routeInfo = routerService.recognize(url);
activeTransaction = startTransaction({
name: `route:${routeInfo.name}`,
op: 'pageload',
tags: {
url,
toRoute: routeInfo.name,
'routing.instrumentation': '@sentry/ember',
},
});
}
const finishActiveTransaction = function (_: any, nextInstance: any) {
if (nextInstance) {
return;
}
activeTransaction.finish();
getBackburner().off('end', finishActiveTransaction);
};
routerService.on('routeWillChange', (transition: any) => {
const { fromRoute, toRoute } = getTransitionInformation(transition, routerService);
activeTransaction?.finish();
activeTransaction = startTransaction({
name: `route:${toRoute}`,
op: 'navigation',
tags: {
fromRoute,
toRoute,
'routing.instrumentation': '@sentry/ember',
},
});
transitionSpan = activeTransaction.startChild({
op: 'ui.ember.transition',
description: `route:${fromRoute} -> route:${toRoute}`,
});
});
routerService.on('routeDidChange', () => {
if (!transitionSpan || !activeTransaction) {
return;
}
transitionSpan.finish();
if (disableRunloopPerformance) {
activeTransaction.finish();
return;
}
getBackburner().on('end', finishActiveTransaction);
});
return {
startTransaction,
};
}
function _instrumentEmberRunloop(config: EmberSentryConfig) {
const { disableRunloopPerformance, minimumRunloopQueueDuration } = config;
if (disableRunloopPerformance) {
return;
}
let currentQueueStart: number | undefined;
let currentQueueSpan: Span | undefined;
const instrumentedEmberQueues = [
'actions',
'routerTransitions',
'render',
'afterRender',
'destroy',
] as EmberRunQueues[];
getBackburner().on('begin', (_: any, previousInstance: any) => {
if (previousInstance) {
return;
}
const activeTransaction = getActiveTransaction();
if (!activeTransaction) {
return;
}
if (currentQueueSpan) {
currentQueueSpan.finish();
}
currentQueueStart = timestampWithMs();
instrumentedEmberQueues.forEach(queue => {
scheduleOnce(queue, null, () => {
scheduleOnce(queue, null, () => {
// Process this queue using the end of the previous queue.
if (currentQueueStart) {
const now = timestampWithMs();
const minQueueDuration = minimumRunloopQueueDuration ?? 5;
if ((now - currentQueueStart) * 1000 >= minQueueDuration) {
activeTransaction
?.startChild({
op: `ui.ember.runloop.${queue}`,
startTimestamp: currentQueueStart,
endTimestamp: now,
})
.finish();
}
currentQueueStart = undefined;
}
// Setup for next queue
const stillActiveTransaction = getActiveTransaction();
if (!stillActiveTransaction) {
return;
}
currentQueueStart = timestampWithMs();
});
});
});
});
getBackburner().on('end', (_: any, nextInstance: any) => {
if (nextInstance) {
return;
}
if (currentQueueSpan) {
currentQueueSpan.finish();
currentQueueSpan = undefined;
}
});
}
type Payload = {
containerKey: string;
initialRender: true;
object: string;
};
type RenderEntry = {
payload: Payload;
now: number;
};
interface RenderEntries {
[name: string]: RenderEntry;
}
function processComponentRenderBefore(payload: Payload, beforeEntries: RenderEntries) {
const info = {
payload,
now: timestampWithMs(),
};
beforeEntries[payload.object] = info;
}
function processComponentRenderAfter(
payload: Payload,
beforeEntries: RenderEntries,
op: string,
minComponentDuration: number,
) {
const begin = beforeEntries[payload.object];
if (!begin) {
return;
}
const now = timestampWithMs();
const componentRenderDuration = now - begin.now;
if (componentRenderDuration * 1000 >= minComponentDuration) {
const activeTransaction = getActiveTransaction();
activeTransaction?.startChild({
op,
description: payload.containerKey || payload.object,
startTimestamp: begin.now,
endTimestamp: now,
});
}
}
function _instrumentComponents(config: EmberSentryConfig) {
const { disableInstrumentComponents, minimumComponentRenderDuration, enableComponentDefinitions } = config;
if (disableInstrumentComponents) {
return;
}
const minComponentDuration = minimumComponentRenderDuration ?? 2;
const beforeEntries = {} as RenderEntries;
const beforeComponentDefinitionEntries = {} as RenderEntries;
const subscribe = Ember.subscribe;
function _subscribeToRenderEvents() {
subscribe('render.component', {
before(_name: string, _timestamp: number, payload: Payload) {
processComponentRenderBefore(payload, beforeEntries);
},
after(_name: string, _timestamp: number, payload: any, _beganIndex: number) {
processComponentRenderAfter(payload, beforeEntries, 'ui.ember.component.render', minComponentDuration);
},
});
if (enableComponentDefinitions) {
subscribe('render.getComponentDefinition', {
before(_name: string, _timestamp: number, payload: Payload) {
processComponentRenderBefore(payload, beforeComponentDefinitionEntries);
},
after(_name: string, _timestamp: number, payload: any, _beganIndex: number) {
processComponentRenderAfter(payload, beforeComponentDefinitionEntries, 'ui.ember.component.definition', 0);
},
});
}
}
_subscribeToRenderEvents();
}
function _instrumentInitialLoad(config: EmberSentryConfig) {
const startName = '@sentry/ember:initial-load-start';
const endName = '@sentry/ember:initial-load-end';
const { performance } = window;
const HAS_PERFORMANCE = performance && performance.clearMarks && performance.clearMeasures;
if (!HAS_PERFORMANCE) {
return;
}
if (config.disableInitialLoadInstrumentation) {
performance.clearMarks(startName);
performance.clearMarks(endName);
return;
}
// Split performance check in two so clearMarks still happens even if timeOrigin isn't available.
const HAS_PERFORMANCE_TIMING =
performance.measure && performance.getEntriesByName && browserPerformanceTimeOrigin !== undefined;
if (!HAS_PERFORMANCE_TIMING) {
return;
}
const measureName = '@sentry/ember:initial-load';
const startMarkExists = performance.getEntriesByName(startName).length > 0;
const endMarkExists = performance.getEntriesByName(endName).length > 0;
if (!startMarkExists || !endMarkExists) {
return;
}
performance.measure(measureName, startName, endName);
const measures = performance.getEntriesByName(measureName);
const measure = measures[0];
const startTimestamp = (measure.startTime + browserPerformanceTimeOrigin!) / 1000;
const endTimestamp = startTimestamp + measure.duration / 1000;
const transaction = getActiveTransaction();
const span = transaction?.startChild({
op: 'ui.ember.init',
startTimestamp,
});
span?.finish(endTimestamp);
performance.clearMarks(startName);
performance.clearMarks(endName);
performance.clearMeasures(measureName);
}
export async function instrumentForPerformance(appInstance: ApplicationInstance) {
const config = getSentryConfig();
const sentryConfig = config.sentry;
// Maintaining backwards compatibility with config.browserTracingOptions, but passing it with Sentry options is preferred.
const browserTracingOptions = config.browserTracingOptions || config.sentry.browserTracingOptions || {};
const tracing = await import('@sentry/tracing');
const idleTimeout = config.transitionTimeout || 5000;
const existingIntegrations = (sentryConfig['integrations'] || []) as Integration[];
sentryConfig['integrations'] = [
...existingIntegrations,
new tracing.Integrations.BrowserTracing({
routingInstrumentation: (customStartTransaction, startTransactionOnPageLoad) => {
const routerMain = appInstance.lookup('router:main');
const routerService = appInstance.lookup('service:router');
_instrumentEmberRouter(routerService, routerMain, config, customStartTransaction, startTransactionOnPageLoad);
},
idleTimeout,
...browserTracingOptions,
}),
];
class FakeBrowserTracingClass {
static id = tracing.BROWSER_TRACING_INTEGRATION_ID;
public name = FakeBrowserTracingClass.id;
setupOnce() {
// noop - We're just faking this class for a lookup
}
}
if (
isTesting() &&
Sentry.getCurrentHub()?.getIntegration(
// This is a temporary hack because the BrowserTracing integration cannot have a static `id` field for tree
// shaking reasons. However, `getIntegration` needs that field.
FakeBrowserTracingClass,
)
) {
// Initializers are called more than once in tests, causing the integrations to not be setup correctly.
return;
}
Sentry.init(sentryConfig); // Call init again to rebind client with new integration list in addition to the defaults
_instrumentEmberRunloop(config);
_instrumentComponents(config);
_instrumentInitialLoad(config);
}
export default {
initialize,
};