-
-
Notifications
You must be signed in to change notification settings - Fork 239
/
sentry_client.dart
638 lines (555 loc) · 19.2 KB
/
sentry_client.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
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
import 'dart:async';
import 'dart:math';
import 'package:meta/meta.dart';
import 'client_reports/client_report_recorder.dart';
import 'client_reports/discard_reason.dart';
import 'event_processor.dart';
import 'hint.dart';
import 'metrics/metric.dart';
import 'metrics/metrics_aggregator.dart';
import 'protocol.dart';
import 'protocol/sentry_feedback.dart';
import 'scope.dart';
import 'sentry_attachment/sentry_attachment.dart';
import 'sentry_baggage.dart';
import 'sentry_envelope.dart';
import 'sentry_exception_factory.dart';
import 'sentry_options.dart';
import 'sentry_stack_trace_factory.dart';
import 'sentry_trace_context_header.dart';
import 'sentry_user_feedback.dart';
import 'transport/data_category.dart';
import 'transport/http_transport.dart';
import 'transport/noop_transport.dart';
import 'transport/rate_limiter.dart';
import 'transport/spotlight_http_transport.dart';
import 'transport/task_queue.dart';
import 'utils/isolate_utils.dart';
import 'utils/regex_utils.dart';
import 'utils/stacktrace_utils.dart';
import 'version.dart';
/// Default value for [SentryUser.ipAddress]. It gets set when an event does not have
/// a user and IP address. Only applies if [SentryOptions.sendDefaultPii] is set
/// to true.
const _defaultIpAddress = '{{auto}}';
/// Logs crash reports and events to the Sentry.io service.
class SentryClient {
final SentryOptions _options;
late final _taskQueue = TaskQueue<SentryId?>(
_options.maxQueueSize,
_options.logger,
);
final Random? _random;
late final MetricsAggregator? _metricsAggregator;
static final _emptySentryId = Future.value(SentryId.empty());
SentryExceptionFactory get _exceptionFactory => _options.exceptionFactory;
SentryStackTraceFactory get _stackTraceFactory => _options.stackTraceFactory;
/// Instantiates a client using [SentryOptions]
factory SentryClient(SentryOptions options) {
if (options.sendClientReports) {
options.recorder = ClientReportRecorder(options.clock);
}
if (options.transport is NoOpTransport) {
final rateLimiter = RateLimiter(options);
options.transport = HttpTransport(options, rateLimiter);
}
// TODO: Web might change soon to use the JS SDK so we can remove it here later on
final enableFlutterSpotlight = (options.spotlight.enabled &&
(options.platformChecker.isWeb ||
options.platformChecker.platform.isLinux ||
options.platformChecker.platform.isWindows));
// Spotlight in the Flutter layer is only enabled for Web, Linux and Windows
// Other platforms use spotlight through their native SDKs
if (enableFlutterSpotlight) {
options.transport = SpotlightHttpTransport(options, options.transport);
}
return SentryClient._(options);
}
/// Instantiates a client using [SentryOptions]
SentryClient._(this._options)
: _random = _options.sampleRate == null ? null : Random(),
_metricsAggregator = _options.enableMetrics
? MetricsAggregator(options: _options)
: null;
@internal
MetricsAggregator? get metricsAggregator => _metricsAggregator;
/// Reports an [event] to Sentry.io.
Future<SentryId> captureEvent(
SentryEvent event, {
Scope? scope,
dynamic stackTrace,
Hint? hint,
}) async {
if (_isIgnoredError(event)) {
_options.logger(
SentryLevel.debug,
'Error was ignored as specified in the ignoredErrors options.',
);
_options.recorder
.recordLostEvent(DiscardReason.ignored, _getCategory(event));
return _emptySentryId;
}
if (_options.containsIgnoredExceptionForType(event.throwable)) {
_options.logger(
SentryLevel.debug,
'Event was dropped as the exception ${event.throwable.runtimeType.toString()} is ignored.',
);
_options.recorder
.recordLostEvent(DiscardReason.eventProcessor, _getCategory(event));
return _emptySentryId;
}
if (_sampleRate() && event.type != 'feedback') {
_options.recorder
.recordLostEvent(DiscardReason.sampleRate, _getCategory(event));
_options.logger(
SentryLevel.debug,
'Event ${event.eventId.toString()} was dropped due to sampling decision.',
);
return _emptySentryId;
}
SentryEvent? preparedEvent = _prepareEvent(event, stackTrace: stackTrace);
hint ??= Hint();
if (scope != null) {
preparedEvent = await scope.applyToEvent(preparedEvent, hint);
} else {
_options.logger(
SentryLevel.debug, 'No scope to apply on event was provided');
}
// dropped by scope event processors
if (preparedEvent == null) {
return _emptySentryId;
}
preparedEvent = await _runEventProcessors(
preparedEvent,
hint,
eventProcessors: _options.eventProcessors,
);
// dropped by event processors
if (preparedEvent == null) {
return _emptySentryId;
}
preparedEvent = _createUserOrSetDefaultIpAddress(preparedEvent);
preparedEvent = await _runBeforeSend(
preparedEvent,
hint,
);
// dropped by beforeSend
if (preparedEvent == null) {
return _emptySentryId;
}
var attachments = List<SentryAttachment>.from(scope?.attachments ?? []);
attachments.addAll(hint.attachments);
var screenshot = hint.screenshot;
if (screenshot != null) {
attachments.add(screenshot);
}
var viewHierarchy = hint.viewHierarchy;
if (viewHierarchy != null && event.type != 'feedback') {
attachments.add(viewHierarchy);
}
var traceContext = scope?.span?.traceContext();
if (traceContext == null) {
if (scope != null) {
scope.propagationContext.baggage ??=
SentryBaggage({}, logger: _options.logger)
..setValuesFromScope(scope, _options);
traceContext = SentryTraceContextHeader.fromBaggage(
scope.propagationContext.baggage!);
}
} else {
traceContext.replayId = scope?.replayId;
}
final envelope = SentryEnvelope.fromEvent(
preparedEvent,
_options.sdk,
dsn: _options.dsn,
traceContext: traceContext,
attachments: attachments.isNotEmpty ? attachments : null,
);
final id = await captureEnvelope(envelope);
return id ?? SentryId.empty();
}
bool _isIgnoredError(SentryEvent event) {
if (event.message == null || _options.ignoreErrors.isEmpty) {
return false;
}
var message = event.message!.formatted;
return isMatchingRegexPattern(message, _options.ignoreErrors);
}
SentryEvent _prepareEvent(SentryEvent event, {dynamic stackTrace}) {
event = event.copyWith(
serverName: event.serverName ?? _options.serverName,
dist: event.dist ?? _options.dist,
environment: event.environment ?? _options.environment,
release: event.release ?? _options.release,
sdk: event.sdk ?? _options.sdk,
platform: event.platform ?? sdkPlatform(_options.platformChecker.isWeb),
);
if (event is SentryTransaction) {
return event;
}
if (event.type == 'feedback') {
return event;
}
if (event.exceptions?.isNotEmpty ?? false) {
return event;
}
final isolateName = getIsolateName();
// Isolates have no id, so the hashCode of the name will be used as id
final isolateId = isolateName?.hashCode;
if (event.throwableMechanism != null) {
final extractedExceptions = _exceptionFactory.extractor
.flatten(event.throwableMechanism, stackTrace);
final sentryExceptions = <SentryException>[];
final sentryThreads = <SentryThread>[];
for (final extractedException in extractedExceptions) {
var sentryException = _exceptionFactory.getSentryException(
extractedException.exception,
stackTrace: extractedException.stackTrace,
);
SentryThread? sentryThread;
if (!_options.platformChecker.isWeb &&
isolateName != null &&
_options.attachThreads) {
sentryException = sentryException.copyWith(threadId: isolateId);
sentryThread = SentryThread(
id: isolateId,
name: isolateName,
crashed: true,
current: true,
);
}
sentryExceptions.add(sentryException);
if (sentryThread != null) {
sentryThreads.add(sentryThread);
}
}
return event.copyWith(
exceptions: [...?event.exceptions, ...sentryExceptions],
threads: [
...?event.threads,
...sentryThreads,
],
);
}
// The stacktrace is not part of an exception,
// therefore add it to the threads.
// https://develop.sentry.dev/sdk/event-payloads/stacktrace/
if (stackTrace != null || _options.attachStacktrace) {
stackTrace ??= getCurrentStackTrace();
final sentryStackTrace = _stackTraceFactory.parse(stackTrace);
if (sentryStackTrace.frames.isNotEmpty) {
event = event.copyWith(threads: [
...?event.threads,
SentryThread(
name: isolateName,
id: isolateId,
crashed: false,
current: true,
stacktrace: sentryStackTrace,
),
]);
}
}
return event;
}
SentryEvent _createUserOrSetDefaultIpAddress(SentryEvent event) {
var user = event.user;
if (user == null) {
return event.copyWith(user: SentryUser(ipAddress: _defaultIpAddress));
} else if (event.user?.ipAddress == null) {
return event.copyWith(user: user.copyWith(ipAddress: _defaultIpAddress));
}
return event;
}
/// Reports the [throwable] and optionally its [stackTrace] to Sentry.io.
Future<SentryId> captureException(
dynamic throwable, {
dynamic stackTrace,
Scope? scope,
Hint? hint,
}) {
final event = SentryEvent(
throwable: throwable,
timestamp: _options.clock(),
);
return captureEvent(
event,
stackTrace: stackTrace,
scope: scope,
hint: hint,
);
}
/// Reports the [template]
Future<SentryId> captureMessage(
String formatted, {
SentryLevel? level,
String? template,
List<dynamic>? params,
Scope? scope,
Hint? hint,
}) {
final event = SentryEvent(
message: SentryMessage(formatted, template: template, params: params),
level: level ?? SentryLevel.info,
timestamp: _options.clock(),
);
return captureEvent(event, scope: scope, hint: hint);
}
@internal
Future<SentryId> captureTransaction(
SentryTransaction transaction, {
Scope? scope,
SentryTraceContextHeader? traceContext,
}) async {
SentryTransaction? preparedTransaction =
_prepareEvent(transaction) as SentryTransaction;
final hint = Hint();
if (scope != null) {
preparedTransaction = await scope.applyToEvent(preparedTransaction, hint)
as SentryTransaction?;
} else {
_options.logger(
SentryLevel.debug, 'No scope to apply on transaction was provided');
}
// dropped by scope event processors
if (preparedTransaction == null) {
return _emptySentryId;
}
preparedTransaction = await _runEventProcessors(
preparedTransaction,
hint,
eventProcessors: _options.eventProcessors,
) as SentryTransaction?;
// dropped by event processors
if (preparedTransaction == null) {
return _emptySentryId;
}
if (_isIgnoredTransaction(preparedTransaction)) {
_options.logger(
SentryLevel.debug,
'Transaction was ignored as specified in the ignoredTransactions options.',
);
_options.recorder.recordLostEvent(
DiscardReason.ignored, _getCategory(preparedTransaction));
return _emptySentryId;
}
preparedTransaction =
await _runBeforeSend(preparedTransaction, hint) as SentryTransaction?;
// dropped by beforeSendTransaction
if (preparedTransaction == null) {
return _emptySentryId;
}
final attachments = scope?.attachments
.where((element) => element.addToTransactions)
.toList();
final envelope = SentryEnvelope.fromTransaction(
preparedTransaction,
_options.sdk,
dsn: _options.dsn,
traceContext: traceContext,
attachments: attachments,
);
final profileInfo = preparedTransaction.tracer.profileInfo;
if (profileInfo != null) {
envelope.items.add(profileInfo.asEnvelopeItem());
}
final id = await captureEnvelope(envelope);
return id ?? SentryId.empty();
}
bool _isIgnoredTransaction(SentryTransaction transaction) {
if (_options.ignoreTransactions.isEmpty) {
return false;
}
var name = transaction.tracer.name;
return isMatchingRegexPattern(name, _options.ignoreTransactions);
}
/// Reports the [envelope] to Sentry.io.
Future<SentryId?> captureEnvelope(SentryEnvelope envelope) {
return _attachClientReportsAndSend(envelope);
}
/// Reports the [userFeedback] to Sentry.io.
@Deprecated(
'Will be removed in a future version. Use [captureFeedback] instead')
Future<void> captureUserFeedback(SentryUserFeedback userFeedback) {
final envelope = SentryEnvelope.fromUserFeedback(
userFeedback,
_options.sdk,
dsn: _options.dsn,
);
return _attachClientReportsAndSend(envelope);
}
/// Reports the [feedback] to Sentry.io.
Future<SentryId> captureFeedback(
SentryFeedback feedback, {
Scope? scope,
Hint? hint,
}) {
final feedbackEvent = SentryEvent(
type: 'feedback',
contexts: Contexts(feedback: feedback),
level: SentryLevel.info,
);
return captureEvent(
feedbackEvent,
scope: scope,
hint: hint,
);
}
/// Reports the [metricsBuckets] to Sentry.io.
Future<SentryId> captureMetrics(
Map<int, Iterable<Metric>> metricsBuckets) async {
final envelope = SentryEnvelope.fromMetrics(
metricsBuckets,
_options.sdk,
dsn: _options.dsn,
);
final id = await _attachClientReportsAndSend(envelope);
return id ?? SentryId.empty();
}
void close() {
_metricsAggregator?.close();
_options.httpClient.close();
}
Future<SentryEvent?> _runBeforeSend(
SentryEvent event,
Hint hint,
) async {
SentryEvent? processedEvent = event;
final spanCountBeforeCallback =
event is SentryTransaction ? event.spans.length : 0;
final beforeSend = _options.beforeSend;
final beforeSendTransaction = _options.beforeSendTransaction;
final beforeSendFeedback = _options.beforeSendFeedback;
String beforeSendName = 'beforeSend';
try {
if (event is SentryTransaction && beforeSendTransaction != null) {
beforeSendName = 'beforeSendTransaction';
final callbackResult = beforeSendTransaction(event);
if (callbackResult is Future<SentryTransaction?>) {
processedEvent = await callbackResult;
} else {
processedEvent = callbackResult;
}
} else if (event.type == 'feedback' && beforeSendFeedback != null) {
final callbackResult = beforeSendFeedback(event, hint);
if (callbackResult is Future<SentryEvent?>) {
processedEvent = await callbackResult;
} else {
processedEvent = callbackResult;
}
} else if (beforeSend != null) {
final callbackResult = beforeSend(event, hint);
if (callbackResult is Future<SentryEvent?>) {
processedEvent = await callbackResult;
} else {
processedEvent = callbackResult;
}
}
} catch (exception, stackTrace) {
_options.logger(
SentryLevel.error,
'The $beforeSendName callback threw an exception',
exception: exception,
stackTrace: stackTrace,
);
if (_options.automatedTestMode) {
rethrow;
}
}
final discardReason = DiscardReason.beforeSend;
if (processedEvent == null) {
_options.recorder.recordLostEvent(discardReason, _getCategory(event));
if (event is SentryTransaction) {
// We dropped the whole transaction, the dropped count includes all child spans + 1 root span
_options.recorder.recordLostEvent(discardReason, DataCategory.span,
count: spanCountBeforeCallback + 1);
}
_options.logger(
SentryLevel.debug,
'${event.runtimeType} was dropped by $beforeSendName callback',
);
} else if (event is SentryTransaction &&
processedEvent is SentryTransaction) {
// If beforeSend removed only some spans we still report them as dropped
final spanCountAfterCallback = processedEvent.spans.length;
final droppedSpanCount = spanCountBeforeCallback - spanCountAfterCallback;
if (droppedSpanCount > 0) {
_options.recorder.recordLostEvent(discardReason, DataCategory.span,
count: droppedSpanCount);
}
}
return processedEvent;
}
Future<SentryEvent?> _runEventProcessors(
SentryEvent event,
Hint hint, {
required List<EventProcessor> eventProcessors,
}) async {
SentryEvent? processedEvent = event;
int spanCountBeforeEventProcessors =
event is SentryTransaction ? event.spans.length : 0;
for (final processor in eventProcessors) {
try {
final e = processor.apply(processedEvent!, hint);
if (e is Future<SentryEvent?>) {
processedEvent = await e;
} else {
processedEvent = e;
}
} catch (exception, stackTrace) {
_options.logger(
SentryLevel.error,
'An exception occurred while processing event by a processor',
exception: exception,
stackTrace: stackTrace,
);
if (_options.automatedTestMode) {
rethrow;
}
}
final discardReason = DiscardReason.eventProcessor;
if (processedEvent == null) {
_options.recorder.recordLostEvent(discardReason, _getCategory(event));
if (event is SentryTransaction) {
// We dropped the whole transaction, the dropped count includes all child spans + 1 root span
_options.recorder.recordLostEvent(discardReason, DataCategory.span,
count: spanCountBeforeEventProcessors + 1);
}
_options.logger(SentryLevel.debug, 'Event was dropped by a processor');
break;
} else if (event is SentryTransaction &&
processedEvent is SentryTransaction) {
// If event processor removed only some spans we still report them as dropped
final spanCountAfterEventProcessors = processedEvent.spans.length;
final droppedSpanCount =
spanCountBeforeEventProcessors - spanCountAfterEventProcessors;
if (droppedSpanCount > 0) {
_options.recorder.recordLostEvent(discardReason, DataCategory.span,
count: droppedSpanCount);
}
}
}
return processedEvent;
}
bool _sampleRate() {
if (_options.sampleRate != null && _random != null) {
return (_options.sampleRate! < _random!.nextDouble());
}
return false;
}
DataCategory _getCategory(SentryEvent event) {
if (event is SentryTransaction) {
return DataCategory.transaction;
}
return DataCategory.error;
}
Future<SentryId?> _attachClientReportsAndSend(SentryEnvelope envelope) {
final clientReport = _options.recorder.flush();
envelope.addClientReport(clientReport);
return _taskQueue.enqueue(
() => _options.transport.send(envelope),
SentryId.empty(),
);
}
}