-
-
Notifications
You must be signed in to change notification settings - Fork 244
/
Copy pathdefault_integrations.dart
518 lines (449 loc) · 17.1 KB
/
default_integrations.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
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
513
514
515
516
517
518
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:sentry/sentry.dart';
import 'binding_utils.dart';
import 'sentry_flutter_options.dart';
import 'widgets_binding_observer.dart';
/// It is necessary to initialize Flutter method channels so that our plugin can
/// call into the native code.
class WidgetsFlutterBindingIntegration
extends Integration<SentryFlutterOptions> {
WidgetsFlutterBindingIntegration(
[WidgetsBinding Function()? ensureInitialized])
: _ensureInitialized =
ensureInitialized ?? WidgetsFlutterBinding.ensureInitialized;
final WidgetsBinding Function() _ensureInitialized;
@override
FutureOr<void> call(Hub hub, SentryFlutterOptions options) {
_ensureInitialized();
options.sdk.addIntegration('widgetsFlutterBindingIntegration');
}
}
/// Integration that capture errors on the [FlutterError.onError] handler.
///
/// Remarks:
/// - Most UI and layout related errors (such as
/// [these](https://flutter.dev/docs/testing/common-errors)) are AssertionErrors
/// and are stripped in release mode. See [Flutter build modes](https://flutter.dev/docs/testing/build-modes).
/// So they only get caught in debug mode.
class FlutterErrorIntegration extends Integration<SentryFlutterOptions> {
/// Reference to the original handler.
FlutterExceptionHandler? _defaultOnError;
/// The error handler set by this integration.
FlutterExceptionHandler? _integrationOnError;
@override
void call(Hub hub, SentryFlutterOptions options) {
_defaultOnError = FlutterError.onError;
_integrationOnError = (FlutterErrorDetails errorDetails) async {
final exception = errorDetails.exception;
options.logger(
SentryLevel.debug,
'Capture from onError $exception',
);
if (errorDetails.silent != true || options.reportSilentFlutterErrors) {
final context = errorDetails.context?.toDescription();
final collector = errorDetails.informationCollector?.call() ?? [];
final information =
(StringBuffer()..writeAll(collector, '\n')).toString();
// errorDetails.library defaults to 'Flutter framework' even though it
// is nullable. We do null checks anyway, just to be sure.
final library = errorDetails.library;
final flutterErrorDetails = <String, String>{
// This is a message which should make sense if written after the
// word `thrown`:
// https://api.flutter.dev/flutter/foundation/FlutterErrorDetails/context.html
if (context != null) 'context': 'thrown $context',
if (collector.isNotEmpty) 'information': information,
if (library != null) 'library': library,
};
options.logger(
SentryLevel.error,
errorDetails.toStringShort(),
logger: 'sentry.flutterError',
exception: exception,
stackTrace: errorDetails.stack,
);
// FlutterError doesn't crash the App.
final mechanism = Mechanism(
type: 'FlutterError',
handled: true,
data: {
if (flutterErrorDetails.isNotEmpty)
'hint':
'See "flutter_error_details" down below for more information'
},
);
final throwableMechanism = ThrowableMechanism(mechanism, exception);
var event = SentryEvent(
throwable: throwableMechanism,
level: SentryLevel.fatal,
contexts: flutterErrorDetails.isNotEmpty
? (Contexts()..['flutter_error_details'] = flutterErrorDetails)
: null,
);
await hub.captureEvent(event, stackTrace: errorDetails.stack);
// we don't call Zone.current.handleUncaughtError because we'd like
// to set a specific mechanism for FlutterError.onError.
} else {
options.logger(
SentryLevel.debug,
'Error not captured due to [FlutterErrorDetails.silent], '
'Enable [SentryFlutterOptions.reportSilentFlutterErrors] '
'if you wish to capture silent errors',
);
}
// Call original handler, regardless of `errorDetails.silent` or
// `reportSilentFlutterErrors`. This ensures, that we don't swallow
// messages.
if (_defaultOnError != null) {
_defaultOnError!(errorDetails);
}
};
FlutterError.onError = _integrationOnError;
options.sdk.addIntegration('flutterErrorIntegration');
}
@override
FutureOr<void> close() async {
/// Restore default if the integration error is still set.
if (FlutterError.onError == _integrationOnError) {
FlutterError.onError = _defaultOnError;
_defaultOnError = null;
_integrationOnError = null;
}
}
}
/// Load Device's Contexts from the iOS SDK.
///
/// This integration calls the iOS SDK via Message channel to load the
/// Device's contexts before sending the event back to the iOS SDK via
/// Message channel (already enriched with all the information).
///
/// The Device's contexts are:
/// App, Device and OS.
///
/// ps. This integration won't be run on Android because the Device's Contexts
/// is set on Android when the event is sent to the Android SDK via
/// the Message channel.
/// We intend to unify this behaviour in the future.
///
/// This integration is only executed on iOS & MacOS Apps.
class LoadContextsIntegration extends Integration<SentryFlutterOptions> {
final MethodChannel _channel;
LoadContextsIntegration(this._channel);
@override
FutureOr<void> call(Hub hub, SentryFlutterOptions options) async {
options.addEventProcessor(
_LoadContextsIntegrationEventProcessor(_channel, options),
);
options.sdk.addIntegration('loadContextsIntegration');
}
}
class _LoadContextsIntegrationEventProcessor extends EventProcessor {
_LoadContextsIntegrationEventProcessor(this._channel, this._options);
final MethodChannel _channel;
final SentryFlutterOptions _options;
@override
FutureOr<SentryEvent?> apply(SentryEvent event, {hint}) async {
try {
final infos = Map<String, dynamic>.from(
await (_channel.invokeMethod('loadContexts')),
);
if (infos['contexts'] != null) {
final contexts = Contexts.fromJson(
Map<String, dynamic>.from(infos['contexts'] as Map),
);
final eventContexts = event.contexts.clone();
contexts.forEach(
(key, dynamic value) {
if (value != null) {
if (key == SentryRuntime.listType) {
contexts.runtimes.forEach(eventContexts.addRuntime);
} else if (eventContexts[key] == null) {
eventContexts[key] = value;
}
}
},
);
event = event.copyWith(contexts: eventContexts);
}
final userMap = infos['user'];
if (event.user == null && userMap != null) {
final user = Map<String, dynamic>.from(userMap as Map);
event = event.copyWith(user: SentryUser.fromJson(user));
}
if (infos['integrations'] != null) {
final integrations = List<String>.from(infos['integrations'] as List);
final sdk = event.sdk ?? _options.sdk;
for (final integration in integrations) {
if (!sdk.integrations.contains(integration)) {
sdk.addIntegration(integration);
}
}
event = event.copyWith(sdk: sdk);
}
if (infos['package'] != null) {
final package = Map<String, String>.from(infos['package'] as Map);
final sdk = event.sdk ?? _options.sdk;
final name = package['sdk_name'];
final version = package['version'];
if (name != null &&
version != null &&
!sdk.packages.any((element) =>
element.name == name && element.version == version)) {
sdk.addPackage(name, version);
}
event = event.copyWith(sdk: sdk);
}
// on iOS, captureEnvelope does not call the beforeSend callback,
// hence we need to add these tags here.
if (event.sdk?.name == 'sentry.dart.flutter') {
final tags = event.tags ?? {};
tags['event.origin'] = 'flutter';
tags['event.environment'] = 'dart';
event = event.copyWith(tags: tags);
}
} catch (exception, stackTrace) {
_options.logger(
SentryLevel.error,
'loadContextsIntegration failed',
exception: exception,
stackTrace: stackTrace,
);
}
return event;
}
}
/// Enables Sentry's native SDKs (Android and iOS)
class NativeSdkIntegration extends Integration<SentryFlutterOptions> {
NativeSdkIntegration(this._channel);
final MethodChannel _channel;
SentryFlutterOptions? _options;
@override
FutureOr<void> call(Hub hub, SentryFlutterOptions options) async {
_options = options;
try {
await _channel.invokeMethod<void>('initNativeSdk', <String, dynamic>{
'dsn': options.dsn,
'debug': options.debug,
'environment': options.environment,
'release': options.release,
'enableAutoSessionTracking': options.enableAutoSessionTracking,
'enableNativeCrashHandling': options.enableNativeCrashHandling,
'attachStacktrace': options.attachStacktrace,
'attachThreads': options.attachThreads,
'autoSessionTrackingIntervalMillis':
options.autoSessionTrackingInterval.inMilliseconds,
'dist': options.dist,
'integrations': options.sdk.integrations,
'packages':
options.sdk.packages.map((e) => e.toJson()).toList(growable: false),
'diagnosticLevel': options.diagnosticLevel.name,
'maxBreadcrumbs': options.maxBreadcrumbs,
'anrEnabled': options.anrEnabled,
'anrTimeoutIntervalMillis': options.anrTimeoutInterval.inMilliseconds,
'enableAutoNativeBreadcrumbs': options.enableAutoNativeBreadcrumbs,
'maxCacheItems': options.maxCacheItems,
'sendDefaultPii': options.sendDefaultPii,
'enableOutOfMemoryTracking': options.enableOutOfMemoryTracking,
'enableNdkScopeSync': options.enableNdkScopeSync,
'enableAutoPerformanceTracking': options.enableAutoPerformanceTracking,
});
options.sdk.addIntegration('nativeSdkIntegration');
} catch (exception, stackTrace) {
options.logger(
SentryLevel.fatal,
'nativeSdkIntegration failed to be installed',
exception: exception,
stackTrace: stackTrace,
);
}
}
@override
FutureOr<void> close() async {
try {
await _channel.invokeMethod<void>('closeNativeSdk');
} catch (exception, stackTrace) {
_options?.logger(
SentryLevel.fatal,
'nativeSdkIntegration failed to be closed',
exception: exception,
stackTrace: stackTrace,
);
}
}
}
/// Integration that captures certain window and device events.
/// See also:
/// - [SentryWidgetsBindingObserver]
/// - [WidgetsBindingObserver](https://api.flutter.dev/flutter/widgets/WidgetsBindingObserver-class.html)
class WidgetsBindingIntegration extends Integration<SentryFlutterOptions> {
SentryWidgetsBindingObserver? _observer;
@override
FutureOr<void> call(Hub hub, SentryFlutterOptions options) {
_observer = SentryWidgetsBindingObserver(
hub: hub,
options: options,
);
// We don't need to call `WidgetsFlutterBinding.ensureInitialized()`
// because `WidgetsFlutterBindingIntegration` already calls it.
// If the instance is not created, we skip it to keep going.
final instance = BindingUtils.getWidgetsBindingInstance();
if (instance != null) {
instance.addObserver(_observer!);
options.sdk.addIntegration('widgetsBindingIntegration');
} else {
options.logger(
SentryLevel.error,
'widgetsBindingIntegration failed to be installed',
);
}
}
@override
FutureOr<void> close() {
final instance = BindingUtils.getWidgetsBindingInstance();
if (instance != null && _observer != null) {
instance.removeObserver(_observer!);
}
}
}
/// Loads the Android Image list for stack trace symbolication
class LoadAndroidImageListIntegration
extends Integration<SentryFlutterOptions> {
final MethodChannel _channel;
LoadAndroidImageListIntegration(this._channel);
@override
FutureOr<void> call(Hub hub, SentryFlutterOptions options) {
options.addEventProcessor(
_LoadAndroidImageListIntegrationEventProcessor(_channel, options),
);
options.sdk.addIntegration('loadAndroidImageListIntegration');
}
}
class _LoadAndroidImageListIntegrationEventProcessor extends EventProcessor {
_LoadAndroidImageListIntegrationEventProcessor(this._channel, this._options);
final MethodChannel _channel;
final SentryFlutterOptions _options;
@override
FutureOr<SentryEvent?> apply(SentryEvent event, {hint}) async {
if (event is SentryTransaction) {
return event;
}
try {
final exceptions = event.exceptions;
if (exceptions != null && exceptions.first.stackTrace != null) {
final needsSymbolication = exceptions.first.stackTrace?.frames
.any((element) => 'native' == element.platform) ??
false;
// if there are no frames that require symbolication, we don't
// load the debug image list.
if (!needsSymbolication) {
return event;
}
} else {
return event;
}
// we call on every event because the loaded image list is cached
// and it could be changed on the Native side.
final imageList = List<Map<dynamic, dynamic>>.from(
await _channel.invokeMethod('loadImageList'),
);
if (imageList.isEmpty) {
return event;
}
final newDebugImages = <DebugImage>[];
for (final item in imageList) {
final codeFile = item['code_file'] as String?;
final codeId = item['code_id'] as String?;
final imageAddr = item['image_addr'] as String?;
final imageSize = item['image_size'] as int?;
final type = item['type'] as String;
final debugId = item['debug_id'] as String?;
final debugFile = item['debug_file'] as String?;
final image = DebugImage(
type: type,
imageAddr: imageAddr,
imageSize: imageSize,
codeFile: codeFile,
debugId: debugId,
codeId: codeId,
debugFile: debugFile,
);
newDebugImages.add(image);
}
final debugMeta = DebugMeta(images: newDebugImages);
event = event.copyWith(debugMeta: debugMeta);
} catch (exception, stackTrace) {
_options.logger(
SentryLevel.error,
'loadImageList failed',
exception: exception,
stackTrace: stackTrace,
);
}
return event;
}
}
/// a PackageInfo wrapper to make it testable
typedef PackageLoader = Future<PackageInfo> Function();
/// An [Integration] that loads the release version from native apps
class LoadReleaseIntegration extends Integration<SentryFlutterOptions> {
final PackageLoader _packageLoader;
LoadReleaseIntegration(this._packageLoader);
@override
FutureOr<void> call(Hub hub, SentryFlutterOptions options) async {
try {
if (options.release == null || options.dist == null) {
final packageInfo = await _packageLoader();
var name = _cleanString(packageInfo.packageName);
if (name.isEmpty) {
// Not all platforms have a packageName.
// If no packageName is available, use the appName instead.
name = _cleanString(packageInfo.appName);
}
final version = _cleanString(packageInfo.version);
final buildNumber = _cleanString(packageInfo.buildNumber);
var release = name;
if (version.isNotEmpty) {
release = '$release@$version';
}
// At least windows sometimes does not have a buildNumber
if (buildNumber.isNotEmpty) {
release = '$release+$buildNumber';
}
options.logger(SentryLevel.debug, 'release: $release');
options.release = options.release ?? release;
if (buildNumber.isNotEmpty) {
options.dist = options.dist ?? buildNumber;
}
}
} catch (exception, stackTrace) {
options.logger(
SentryLevel.error,
'Failed to load release and dist',
exception: exception,
stackTrace: stackTrace,
);
}
options.sdk.addIntegration('loadReleaseIntegration');
}
/// This method cleans the given string from characters which should not be
/// used.
/// For example https://docs.sentry.io/platforms/flutter/configuration/releases/#bind-the-version
/// imposes some requirements. Also Windows uses some characters which
/// should not be used.
String _cleanString(String appName) {
// Replace disallowed chars with an underscore '_'
return appName
.replaceAll('/', '_')
.replaceAll('\\', '_')
.replaceAll('\t', '_')
.replaceAll('\r\n', '_')
.replaceAll('\r', '_')
.replaceAll('\n', '_')
// replace Unicode NULL character with an empty string
.replaceAll('\u{0000}', '');
}
}