-
-
Notifications
You must be signed in to change notification settings - Fork 220
/
sentry_client.dart
398 lines (345 loc) · 11.4 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
import 'dart:async';
import 'dart:math';
import 'package:meta/meta.dart';
import 'event_processor.dart';
import 'sentry_user_feedback.dart';
import 'transport/rate_limiter.dart';
import 'protocol.dart';
import 'scope.dart';
import 'sentry_exception_factory.dart';
import 'sentry_options.dart';
import 'sentry_stack_trace_factory.dart';
import 'transport/http_transport.dart';
import 'transport/noop_transport.dart';
import 'utils/isolate_utils.dart';
import 'version.dart';
import 'sentry_envelope.dart';
import 'client_reports/client_report_recorder.dart';
import 'client_reports/discard_reason.dart';
import 'transport/data_category.dart';
/// Default value for [User.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;
final Random? _random;
static final _sentryId = 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);
}
return SentryClient._(options);
}
/// Instantiates a client using [SentryOptions]
SentryClient._(this._options)
: _random = _options.sampleRate == null ? null : Random();
/// Reports an [event] to Sentry.io.
Future<SentryId> captureEvent(
SentryEvent event, {
Scope? scope,
dynamic stackTrace,
dynamic hint,
}) async {
if (_sampleRate()) {
_recordLostEvent(event, DiscardReason.sampleRate);
_options.logger(
SentryLevel.debug,
'Event ${event.eventId.toString()} was dropped due to sampling decision.',
);
return _sentryId;
}
SentryEvent? preparedEvent = _prepareEvent(event, stackTrace: stackTrace);
if (scope != null) {
preparedEvent = await scope.applyToEvent(preparedEvent, hint: hint);
} else {
_options.logger(
SentryLevel.debug, 'No scope to apply on event was provided');
}
// dropped by scope event processors
if (preparedEvent == null) {
return _sentryId;
}
preparedEvent = await _processEvent(
preparedEvent,
eventProcessors: _options.eventProcessors,
hint: hint,
);
// dropped by event processors
if (preparedEvent == null) {
return _sentryId;
}
final beforeSend = _options.beforeSend;
if (beforeSend != null) {
final beforeSendEvent = preparedEvent;
try {
preparedEvent = await beforeSend(preparedEvent, hint: hint);
} catch (exception, stackTrace) {
_options.logger(
SentryLevel.error,
'The BeforeSend callback threw an exception',
exception: exception,
stackTrace: stackTrace,
);
}
if (preparedEvent == null) {
_recordLostEvent(beforeSendEvent, DiscardReason.beforeSend);
_options.logger(
SentryLevel.debug,
'Event was dropped by BeforeSend callback',
);
return _sentryId;
}
}
if (_options.platformChecker.platform.isAndroid &&
_options.enableScopeSync) {
/*
We do this to avoid duplicate breadcrumbs on Android as sentry-android applies the breadcrumbs
from the native scope onto every envelope sent through it. This scope will contain the breadcrumbs
sent through the scope sync feature. This causes duplicate breadcrumbs.
We then remove the breadcrumbs in all cases but if it is handled == false,
this is a signal that the app would crash and android would lose the breadcrumbs by the time the app is restarted to read
the envelope.
*/
preparedEvent = _eventWithRemovedBreadcrumbsIfHandled(preparedEvent);
}
final envelope = SentryEnvelope.fromEvent(
preparedEvent,
_options.sdk,
attachments: scope?.attachments,
);
final id = await captureEnvelope(envelope);
return id ?? SentryId.empty();
}
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),
);
event = _applyDefaultPii(event);
if (event is SentryTransaction) {
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) {
var sentryException = _exceptionFactory.getSentryException(
event.throwableMechanism,
stackTrace: stackTrace,
);
if (_options.platformChecker.isWeb) {
return event.copyWith(
exceptions: [
...?event.exceptions,
sentryException,
],
);
}
SentryThread? thread;
if (isolateName != null && _options.attachThreads) {
sentryException = sentryException.copyWith(threadId: isolateId);
thread = SentryThread(
id: isolateId,
name: isolateName,
crashed: true,
current: true,
);
}
return event.copyWith(
exceptions: [...?event.exceptions, sentryException],
threads: [
...?event.threads,
if (thread != null) thread,
],
);
}
// 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 ??= StackTrace.current;
final frames = _stackTraceFactory.getStackFrames(stackTrace);
if (frames.isNotEmpty) {
event = event.copyWith(threads: [
...?event.threads,
SentryThread(
name: isolateName,
id: isolateId,
crashed: false,
current: true,
stacktrace: SentryStackTrace(frames: frames),
),
]);
}
}
return event;
}
/// This modifies the users IP address according
/// to [SentryOptions.sendDefaultPii].
SentryEvent _applyDefaultPii(SentryEvent event) {
if (!_options.sendDefaultPii) {
return event;
}
var user = event.user;
if (user == null) {
user = SentryUser(ipAddress: _defaultIpAddress);
return event.copyWith(user: user);
} 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,
dynamic 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,
dynamic 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,
}) async {
SentryTransaction? preparedTransaction =
_prepareEvent(transaction) as SentryTransaction;
if (scope != null) {
preparedTransaction =
await scope.applyToEvent(preparedTransaction) as SentryTransaction?;
} else {
_options.logger(
SentryLevel.debug, 'No scope to apply on transaction was provided');
}
// dropped by scope event processors
if (preparedTransaction == null) {
return _sentryId;
}
preparedTransaction = await _processEvent(
preparedTransaction,
eventProcessors: _options.eventProcessors,
) as SentryTransaction?;
// dropped by event processors
if (preparedTransaction == null) {
return _sentryId;
}
final id = await captureEnvelope(
SentryEnvelope.fromTransaction(preparedTransaction, _options.sdk,
attachments: scope?.attachments
.where((element) => element.addToTransactions)
.toList()),
);
return id ?? SentryId.empty();
}
/// Reports the [envelope] to Sentry.io.
Future<SentryId?> captureEnvelope(SentryEnvelope envelope) {
return _attachClientReportsAndSend(envelope);
}
/// Reports the [userFeedback] to Sentry.io.
Future<void> captureUserFeedback(SentryUserFeedback userFeedback) {
final envelope = SentryEnvelope.fromUserFeedback(
userFeedback,
_options.sdk,
);
return _attachClientReportsAndSend(envelope);
}
void close() => _options.httpClient.close();
Future<SentryEvent?> _processEvent(
SentryEvent event, {
dynamic hint,
required List<EventProcessor> eventProcessors,
}) async {
SentryEvent? processedEvent = event;
for (final processor in eventProcessors) {
try {
processedEvent = await processor.apply(processedEvent!, hint: hint);
} catch (exception, stackTrace) {
_options.logger(
SentryLevel.error,
'An exception occurred while processing event by a processor',
exception: exception,
stackTrace: stackTrace,
);
}
if (processedEvent == null) {
_recordLostEvent(event, DiscardReason.eventProcessor);
_options.logger(SentryLevel.debug, 'Event was dropped by a processor');
break;
}
}
return processedEvent;
}
bool _sampleRate() {
if (_options.sampleRate != null && _random != null) {
return (_options.sampleRate! < _random!.nextDouble());
}
return false;
}
void _recordLostEvent(SentryEvent event, DiscardReason reason) {
DataCategory category;
if (event is SentryTransaction) {
category = DataCategory.transaction;
} else {
category = DataCategory.error;
}
_options.recorder.recordLostEvent(reason, category);
}
SentryEvent _eventWithRemovedBreadcrumbsIfHandled(SentryEvent event) {
final exceptions = event.exceptions ?? [];
final handled = exceptions.isNotEmpty
? exceptions.first.mechanism?.handled == true
: false;
if (handled) {
return event.copyWith(breadcrumbs: []);
} else {
return event;
}
}
Future<SentryId?> _attachClientReportsAndSend(SentryEnvelope envelope) {
final clientReport = _options.recorder.flush();
envelope.addClientReport(clientReport);
return _options.transport.send(envelope);
}
}