-
-
Notifications
You must be signed in to change notification settings - Fork 223
/
sentry_navigator_observer.dart
385 lines (335 loc) · 12 KB
/
sentry_navigator_observer.dart
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
// ignore_for_file: invalid_use_of_internal_member
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:meta/meta.dart';
import '../integrations/integrations.dart';
import 'time_to_display_tracker.dart';
import '../../sentry_flutter.dart';
import '../event_processor/flutter_enricher_event_processor.dart';
import '../native/sentry_native.dart';
/// This key must be used so that the web interface displays the events nicely
/// See https://develop.sentry.dev/sdk/event-payloads/breadcrumbs/
const _navigationKey = 'navigation';
typedef RouteNameExtractor = RouteSettings? Function(RouteSettings? settings);
typedef AdditionalInfoExtractor = Map<String, dynamic>? Function(
RouteSettings? from,
RouteSettings? to,
);
/// This is a navigation observer to record navigational breadcrumbs.
/// For now it only records navigation events and no gestures.
///
/// It also records Time to Initial Display (TTID).
///
/// [Route]s can always be null and their [Route.settings] can also always be null.
/// For example, if the application starts, there is no previous route.
/// The [RouteSettings] is null if a developer has not specified any
/// RouteSettings.
///
/// The current route name will also be set to [SentryEvent]
/// `contexts.app.view_names` by [FlutterEnricherEventProcessor].
///
/// [SentryNavigatorObserver] must be added to the [navigation observer](https://api.flutter.dev/flutter/material/MaterialApp/navigatorObservers.html) of
/// your used app. This is an example for [MaterialApp](https://api.flutter.dev/flutter/material/MaterialApp/navigatorObservers.html),
/// but the integration for [CupertinoApp](https://api.flutter.dev/flutter/cupertino/CupertinoApp/navigatorObservers.html)
/// and [WidgetsApp](https://api.flutter.dev/flutter/widgets/WidgetsApp/navigatorObservers.html) is the same.
///
/// ```dart
/// import 'package:flutter/material.dart';
/// import 'package:sentry_flutter/sentry_flutter.dart';
///
/// MaterialApp(
/// navigatorObservers: [
/// SentryNavigatorObserver(),
/// ],
/// // other parameter ...
/// )
/// ```
///
/// The option [enableAutoTransactions] is enabled by default. For every new
/// route a transaction is started. It's automatically finished after
/// [autoFinishAfter] duration or when all child spans are finished,
/// if those happen to take longer. The transaction will be set to [Scope.span]
/// if the latter is empty.
///
/// Enabling the [setRouteNameAsTransaction] option overrides the current
/// [Scope.transaction] which will also override the name of the current
/// [Scope.span]. So be careful when this is used together with performance
/// monitoring.
///
/// See also:
/// - [RouteObserver](https://api.flutter.dev/flutter/widgets/RouteObserver-class.html)
/// - [Navigating with arguments](https://flutter.dev/docs/cookbook/navigation/navigate-with-arguments)
class SentryNavigatorObserver extends RouteObserver<PageRoute<dynamic>> {
SentryNavigatorObserver({
Hub? hub,
bool enableAutoTransactions = true,
Duration autoFinishAfter = const Duration(seconds: 3),
bool setRouteNameAsTransaction = false,
RouteNameExtractor? routeNameExtractor,
AdditionalInfoExtractor? additionalInfoProvider,
@visibleForTesting TimeToDisplayTracker? timeToDisplayTracker,
}) : _hub = hub ?? HubAdapter(),
_enableAutoTransactions = enableAutoTransactions,
_autoFinishAfter = autoFinishAfter,
_setRouteNameAsTransaction = setRouteNameAsTransaction,
_routeNameExtractor = routeNameExtractor,
_additionalInfoProvider = additionalInfoProvider,
_native = SentryFlutter.native,
_timeToDisplayTracker = timeToDisplayTracker ?? TimeToDisplayTracker() {
if (enableAutoTransactions) {
_hub.options.sdk.addIntegration('UINavigationTracing');
}
}
final Hub _hub;
final bool _enableAutoTransactions;
final Duration _autoFinishAfter;
final bool _setRouteNameAsTransaction;
final RouteNameExtractor? _routeNameExtractor;
final AdditionalInfoExtractor? _additionalInfoProvider;
final SentryNative? _native;
final TimeToDisplayTracker? _timeToDisplayTracker;
ISentrySpan? _transaction;
static String? _currentRouteName;
@internal
static String? get currentRouteName => _currentRouteName;
Completer<void>? _completedDisplayTracking;
// Since didPush does not have a future, we can keep track of when the display tracking has finished
@visibleForTesting
Completer<void>? get completedDisplayTracking => _completedDisplayTracking;
@override
void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
super.didPush(route, previousRoute);
_setCurrentRouteName(route);
_setCurrentRouteNameAsTransaction(route);
_addBreadcrumb(
type: 'didPush',
from: previousRoute?.settings,
to: route.settings,
);
_finishTimeToDisplayTracking();
_startTimeToDisplayTracking(route);
}
@override
void didReplace({Route<dynamic>? newRoute, Route<dynamic>? oldRoute}) {
super.didReplace(newRoute: newRoute, oldRoute: oldRoute);
_setCurrentRouteName(newRoute);
_setCurrentRouteNameAsTransaction(newRoute);
_addBreadcrumb(
type: 'didReplace',
from: oldRoute?.settings,
to: newRoute?.settings,
);
}
@override
void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
super.didPop(route, previousRoute);
_setCurrentRouteName(previousRoute);
_setCurrentRouteNameAsTransaction(previousRoute);
_addBreadcrumb(
type: 'didPop',
from: route.settings,
to: previousRoute?.settings,
);
_finishTimeToDisplayTracking();
}
void _addBreadcrumb({
required String type,
RouteSettings? from,
RouteSettings? to,
}) {
_hub.addBreadcrumb(RouteObserverBreadcrumb(
navigationType: type,
from: _routeNameExtractor?.call(from) ?? from,
to: _routeNameExtractor?.call(to) ?? to,
timestamp: _hub.options.clock(),
data: _additionalInfoProvider?.call(from, to),
));
}
String? _getRouteName(Route<dynamic>? route) {
return (_routeNameExtractor?.call(route?.settings) ?? route?.settings)
?.name;
}
Future<void> _setCurrentRouteName(Route<dynamic>? route) async {
_currentRouteName = _getRouteName(route);
}
Future<void> _setCurrentRouteNameAsTransaction(Route<dynamic>? route) async {
final name = _getRouteName(route);
if (name == null) {
return;
}
if (_setRouteNameAsTransaction) {
await _hub.configureScope((scope) {
scope.transaction = name;
});
}
}
Future<void> _startTransaction(
Route<dynamic>? route, DateTime startTimestamp) async {
String? name = _getRouteName(route);
final arguments = route?.settings.arguments;
if (name == null) {
return;
}
if (name == '/') {
name = 'root ("/")';
}
final transactionContext = SentryTransactionContext(
name,
SentrySpanOperations.uiLoad,
transactionNameSource: SentryTransactionNameSource.component,
origin: SentryTraceOrigins.autoNavigationRouteObserver,
);
_transaction = _hub.startTransactionWithContext(
transactionContext,
startTimestamp: startTimestamp,
waitForChildren: true,
autoFinishAfter: _autoFinishAfter,
trimEnd: true,
onFinish: (transaction) async {
_transaction = null;
final nativeFrames = await _native
?.endNativeFramesCollection(transaction.context.traceId);
if (nativeFrames != null) {
final measurements = nativeFrames.toMeasurements();
for (final item in measurements.entries) {
final measurement = item.value;
transaction.setMeasurement(
item.key,
measurement.value,
unit: measurement.unit,
);
}
}
},
);
// if _enableAutoTransactions is enabled but there's no traces sample rate
if (_transaction is NoOpSentrySpan) {
_transaction = null;
return;
}
if (arguments != null) {
_transaction?.setData('route_settings_arguments', arguments);
}
await _hub.configureScope((scope) {
scope.span ??= _transaction;
});
await _native?.beginNativeFramesCollection();
}
Future<void> _finishTimeToDisplayTracking() async {
_timeToDisplayTracker?.clear();
final transaction = _transaction;
_transaction = null;
if (transaction == null || transaction.finished) {
return;
}
transaction.status ??= SpanStatus.ok();
await transaction.finish();
}
Future<void> _startTimeToDisplayTracking(Route<dynamic>? route) async {
if (!_enableAutoTransactions) {
return;
}
_completedDisplayTracking = Completer<void>();
String? routeName = _currentRouteName;
if (routeName == null) return;
DateTime startTimestamp = _hub.options.clock();
DateTime? endTimestamp;
if (routeName == '/') {
final appStartInfo = await NativeAppStartIntegration.getAppStartInfo();
if (appStartInfo == null) {
return;
}
startTimestamp = appStartInfo.start;
endTimestamp = appStartInfo.end;
}
await _startTransaction(route, startTimestamp);
final transaction = _transaction;
if (transaction == null) {
return;
}
if (routeName == '/' && endTimestamp != null) {
await _timeToDisplayTracker?.trackAppStartTTD(transaction,
startTimestamp: startTimestamp, endTimestamp: endTimestamp);
} else {
await _timeToDisplayTracker?.trackRegularRouteTTD(transaction,
startTimestamp: startTimestamp);
}
// Mark the tracking as completed and clear any temporary state.
_completedDisplayTracking?.complete();
_timeToDisplayTracker?.clear();
}
}
/// This class makes it easier to record breadcrumbs for events of Flutters
/// NavigationObserver by accepting
/// [RouteSettings].
///
/// See also:
/// - [Navigating with arguments](https://flutter.dev/docs/cookbook/navigation/navigate-with-arguments)
class RouteObserverBreadcrumb extends Breadcrumb {
factory RouteObserverBreadcrumb({
/// This should correspond to Flutters navigation events.
/// See https://api.flutter.dev/flutter/widgets/RouteObserver-class.html
required String navigationType,
RouteSettings? from,
RouteSettings? to,
SentryLevel? level,
DateTime? timestamp,
Map<String, dynamic>? data,
}) {
final dynamic fromArgs = _formatArgs(from?.arguments);
final dynamic toArgs = _formatArgs(to?.arguments);
return RouteObserverBreadcrumb._(
from: from?.name,
fromArgs: fromArgs,
to: to?.name,
toArgs: toArgs,
navigationType: navigationType,
level: level,
timestamp: timestamp,
data: data,
);
}
RouteObserverBreadcrumb._({
required String navigationType,
String? from,
dynamic fromArgs,
String? to,
dynamic toArgs,
super.level,
super.timestamp,
Map<String, dynamic>? data,
}) : super(
category: _navigationKey,
type: _navigationKey,
data: <String, dynamic>{
'state': navigationType,
if (from != null) 'from': from,
if (fromArgs != null) 'from_arguments': fromArgs,
if (to != null) 'to': to,
if (toArgs != null) 'to_arguments': toArgs,
if (data != null) 'data': data,
});
static dynamic _formatArgs(Object? args) {
if (args == null) {
return null;
}
if (args is Map<String, dynamic>) {
return args.map<String, dynamic>((key, dynamic value) =>
MapEntry<String, String>(key, value.toString()));
}
return args.toString();
}
}
extension NativeFramesMeasurement on NativeFrames {
Map<String, SentryMeasurement> toMeasurements() {
final total = SentryMeasurement.totalFrames(totalFrames);
final slow = SentryMeasurement.slowFrames(slowFrames);
final frozen = SentryMeasurement.frozenFrames(frozenFrames);
return {
total.name: total,
slow.name: slow,
frozen.name: frozen,
};
}
}