-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
tracing.ts
323 lines (286 loc) · 11.2 KB
/
tracing.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
/* eslint-disable max-lines */
import { AfterViewInit, Directive, Injectable, Input, NgModule, OnDestroy, OnInit } from '@angular/core';
import { ActivatedRouteSnapshot, Event, NavigationEnd, NavigationStart, ResolveEnd, Router } from '@angular/router';
import { getCurrentHub } from '@sentry/browser';
import { Span, Transaction, TransactionContext } from '@sentry/types';
import { getGlobalObject, logger, stripUrlQueryAndFragment, timestampWithMs } from '@sentry/utils';
import { Observable, Subscription } from 'rxjs';
import { filter, tap } from 'rxjs/operators';
import { ANGULAR_INIT_OP, ANGULAR_OP, ANGULAR_ROUTING_OP } from './constants';
import { IS_DEBUG_BUILD } from './flags';
import { runOutsideAngular } from './zone';
type ParamMap = { [key: string]: string[] };
let instrumentationInitialized: boolean;
let stashedStartTransaction: (context: TransactionContext) => Transaction | undefined;
let stashedStartTransactionOnLocationChange: boolean;
const global = getGlobalObject<Window>();
/**
* Creates routing instrumentation for Angular Router.
*/
export function routingInstrumentation(
customStartTransaction: (context: TransactionContext) => Transaction | undefined,
startTransactionOnPageLoad: boolean = true,
startTransactionOnLocationChange: boolean = true,
): void {
instrumentationInitialized = true;
stashedStartTransaction = customStartTransaction;
stashedStartTransactionOnLocationChange = startTransactionOnLocationChange;
if (startTransactionOnPageLoad && global && global.location) {
customStartTransaction({
name: global.location.pathname,
op: 'pageload',
metadata: { source: 'url' },
});
}
}
export const instrumentAngularRouting = routingInstrumentation;
/**
* Grabs active transaction off scope
*/
export function getActiveTransaction(): Transaction | undefined {
const currentHub = getCurrentHub();
if (currentHub) {
const scope = currentHub.getScope();
if (scope) {
return scope.getTransaction();
}
}
return undefined;
}
/**
* Angular's Service responsible for hooking into Angular Router and tracking current navigation process.
* Creates a new transaction for every route change and measures a duration of routing process.
*/
@Injectable({ providedIn: 'root' })
export class TraceService implements OnDestroy {
public navStart$: Observable<Event> = this._router.events.pipe(
filter(event => event instanceof NavigationStart),
tap(event => {
if (!instrumentationInitialized) {
IS_DEBUG_BUILD &&
logger.error('Angular integration has tracing enabled, but Tracing integration is not configured');
return;
}
const navigationEvent = event as NavigationStart;
const strippedUrl = stripUrlQueryAndFragment(navigationEvent.url);
let activeTransaction = getActiveTransaction();
if (!activeTransaction && stashedStartTransactionOnLocationChange) {
activeTransaction = stashedStartTransaction({
name: strippedUrl,
op: 'navigation',
metadata: { source: 'url' },
});
}
if (activeTransaction) {
if (this._routingSpan) {
this._routingSpan.finish();
}
this._routingSpan = activeTransaction.startChild({
description: `${navigationEvent.url}`,
op: ANGULAR_ROUTING_OP,
tags: {
'routing.instrumentation': '@sentry/angular',
url: strippedUrl,
...(navigationEvent.navigationTrigger && {
navigationTrigger: navigationEvent.navigationTrigger,
}),
},
});
}
}),
);
// The ResolveEnd event is fired when the Angular router has resolved the URL
// and activated the route. It holds the new resolved router state and the
// new URL.
// Only After this event, the route is activated, meaning that the transaction
// can be updated with the parameterized route name before e.g. the route's root
// component is initialized. This should be early enough before outgoing requests
// are made from the new route.
// In any case, this is the earliest stage where we can reliably get a resolved
//
public resEnd$: Observable<Event> = this._router.events.pipe(
filter(event => event instanceof ResolveEnd),
tap(event => {
const ev = event as ResolveEnd;
const params = getParamsOfRoute(ev.state.root);
// ev.urlAfterRedirects is the one we prefer because it should hold the most recent
// one that holds information about a redirect to another route if this was specified
// in the Angular router config. In case this doesn't exist (for whatever reason),
// we fall back to ev.url which holds the primarily resolved URL before a potential
// redirect.
const url = ev.urlAfterRedirects || ev.url;
const route = getParameterizedRouteFromUrlAndParams(url, params);
const transaction = getActiveTransaction();
// TODO (v8 / #5416): revisit the source condition. Do we want to make the parameterized route the default?
if (transaction && transaction.metadata.source === 'url') {
transaction.setName(route);
transaction.setMetadata({ source: 'route' });
}
}),
);
public navEnd$: Observable<Event> = this._router.events.pipe(
filter(event => event instanceof NavigationEnd),
tap(() => {
if (this._routingSpan) {
runOutsideAngular(() => {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
this._routingSpan!.finish();
});
this._routingSpan = null;
}
}),
);
private _routingSpan: Span | null = null;
private _subscription: Subscription = new Subscription();
public constructor(private readonly _router: Router) {
this._subscription.add(this.navStart$.subscribe());
this._subscription.add(this.resEnd$.subscribe());
this._subscription.add(this.navEnd$.subscribe());
}
/**
* This is used to prevent memory leaks when the root view is created and destroyed multiple times,
* since `subscribe` callbacks capture `this` and prevent many resources from being GC'd.
*/
public ngOnDestroy(): void {
this._subscription.unsubscribe();
}
}
const UNKNOWN_COMPONENT = 'unknown';
/**
* A directive that can be used to capture initialization lifecycle of the whole component.
*/
@Directive({ selector: '[trace]' })
export class TraceDirective implements OnInit, AfterViewInit {
@Input('trace') public componentName: string = UNKNOWN_COMPONENT;
private _tracingSpan?: Span;
/**
* Implementation of OnInit lifecycle method
* @inheritdoc
*/
public ngOnInit(): void {
const activeTransaction = getActiveTransaction();
if (activeTransaction) {
this._tracingSpan = activeTransaction.startChild({
description: `<${this.componentName}>`,
op: ANGULAR_INIT_OP,
});
}
}
/**
* Implementation of AfterViewInit lifecycle method
* @inheritdoc
*/
public ngAfterViewInit(): void {
if (this._tracingSpan) {
this._tracingSpan.finish();
}
}
}
/**
* A module serves as a single compilation unit for the `TraceDirective` and can be re-used by any other module.
*/
@NgModule({
declarations: [TraceDirective],
exports: [TraceDirective],
})
export class TraceModule {}
/**
* Decorator function that can be used to capture initialization lifecycle of the whole component.
*/
export function TraceClassDecorator(): ClassDecorator {
let tracingSpan: Span;
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
return target => {
const originalOnInit = target.prototype.ngOnInit;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
target.prototype.ngOnInit = function (...args: any[]): ReturnType<typeof originalOnInit> {
const activeTransaction = getActiveTransaction();
if (activeTransaction) {
tracingSpan = activeTransaction.startChild({
description: `<${target.name}>`,
op: ANGULAR_INIT_OP,
});
}
if (originalOnInit) {
return originalOnInit.apply(this, args);
}
};
const originalAfterViewInit = target.prototype.ngAfterViewInit;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
target.prototype.ngAfterViewInit = function (...args: any[]): ReturnType<typeof originalAfterViewInit> {
if (tracingSpan) {
tracingSpan.finish();
}
if (originalAfterViewInit) {
return originalAfterViewInit.apply(this, args);
}
};
};
/* eslint-enable @typescript-eslint/no-unsafe-member-access */
}
/**
* Decorator function that can be used to capture a single lifecycle methods of the component.
*/
export function TraceMethodDecorator(): MethodDecorator {
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type, @typescript-eslint/ban-types
return (target: Object, propertyKey: string | symbol, descriptor: PropertyDescriptor) => {
const originalMethod = descriptor.value;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
descriptor.value = function (...args: any[]): ReturnType<typeof originalMethod> {
const now = timestampWithMs();
const activeTransaction = getActiveTransaction();
if (activeTransaction) {
activeTransaction.startChild({
description: `<${target.constructor.name}>`,
endTimestamp: now,
op: `${ANGULAR_OP}.${String(propertyKey)}`,
startTimestamp: now,
});
}
if (originalMethod) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
return originalMethod.apply(this, args);
}
};
return descriptor;
};
}
/**
* Recursively traverses the routerstate and its children to collect a map of parameters on the entire route.
*
* Because Angular supports child routes (e.g. when creating nested routes or lazy loaded routes), we have
* to not only visit the root router snapshot but also its children to get all parameters of the entire route.
*
* @param activatedRouteSnapshot the root router snapshot
* @returns a map of params, mapping from a key to an array of values
*/
export function getParamsOfRoute(activatedRouteSnapshot: ActivatedRouteSnapshot): ParamMap {
function getParamsOfRouteH(routeSnapshot: ActivatedRouteSnapshot, accParams: ParamMap): ParamMap {
Object.keys(routeSnapshot.params).forEach(key => {
accParams[key] = [...(accParams[key] || []), routeSnapshot.params[key]];
});
routeSnapshot.children.forEach(child => getParamsOfRouteH(child, accParams));
return accParams;
}
return getParamsOfRouteH(activatedRouteSnapshot, {});
}
/**
* Takes a raw URl and a map of params and replaces each values occuring in the raw URL with
* the name of the parameter.
*
* @param url raw URL (e.g. /user/1234/details)
* @param params a map of type ParamMap
* @returns the parameterized URL (e.g. /user/:userId/details)
*/
export function getParameterizedRouteFromUrlAndParams(url: string, params: ParamMap): string {
if (params) {
return Object.keys(params).reduce((prevUrl: string, paramName: string) => {
return prevUrl
.split('/')
.map(segment => (params[paramName].find(p => p === segment) ? `:${paramName}` : segment))
.join('/');
}, url);
}
return url;
}