forked from getsentry/sentry-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSentryClient.java
More file actions
583 lines (504 loc) · 18.7 KB
/
SentryClient.java
File metadata and controls
583 lines (504 loc) · 18.7 KB
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
package io.sentry;
import io.sentry.hints.DiskFlushNotification;
import io.sentry.protocol.SentryId;
import io.sentry.protocol.SentrySpan;
import io.sentry.protocol.SentryTransaction;
import io.sentry.transport.ITransport;
import io.sentry.util.ApplyScopeUtils;
import io.sentry.util.Objects;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
public final class SentryClient implements ISentryClient {
static final String SENTRY_PROTOCOL_VERSION = "7";
private boolean enabled;
private final @NotNull SentryOptions options;
private final @NotNull ITransport transport;
private final @Nullable Random random;
private final @NotNull SortBreadcrumbsByDate sortBreadcrumbsByDate = new SortBreadcrumbsByDate();
@Override
public boolean isEnabled() {
return enabled;
}
SentryClient(final @NotNull SentryOptions options) {
this.options = Objects.requireNonNull(options, "SentryOptions is required.");
this.enabled = true;
ITransportFactory transportFactory = options.getTransportFactory();
if (transportFactory instanceof NoOpTransportFactory) {
transportFactory = new AsyncHttpTransportFactory();
options.setTransportFactory(transportFactory);
}
final RequestDetailsResolver requestDetailsResolver = new RequestDetailsResolver(options);
transport = transportFactory.create(options, requestDetailsResolver.resolve());
this.random = options.getSampleRate() == null ? null : new Random();
}
@Override
public @NotNull SentryId captureEvent(
@NotNull SentryEvent event, final @Nullable Scope scope, final @Nullable Object hint) {
Objects.requireNonNull(event, "SentryEvent is required.");
options.getLogger().log(SentryLevel.DEBUG, "Capturing event: %s", event.getEventId());
if (ApplyScopeUtils.shouldApplyScopeData(hint)) {
// Event has already passed through here before it was cached
// Going through again could be reading data that is no longer relevant
// i.e proguard id, app version, threads
event = applyScope(event, scope, hint);
if (event == null) {
options.getLogger().log(SentryLevel.DEBUG, "Event was dropped by applyScope");
}
} else {
options
.getLogger()
.log(SentryLevel.DEBUG, "Event was cached so not applying scope: %s", event.getEventId());
}
event = processEvent(event, hint, options.getEventProcessors());
Session session = null;
if (event != null) {
session = updateSessionData(event, hint, scope);
if (!sample()) {
options
.getLogger()
.log(
SentryLevel.DEBUG,
"Event %s was dropped due to sampling decision.",
event.getEventId());
// setting event as null to not be sent as its been discarded by sample rate
event = null;
}
}
if (event != null) {
event = executeBeforeSend(event, hint);
if (event == null) {
options.getLogger().log(SentryLevel.DEBUG, "Event was dropped by beforeSend");
}
}
SentryId sentryId = SentryId.EMPTY_ID;
if (event != null) {
sentryId = event.getEventId();
}
try {
final SentryEnvelope envelope = buildEnvelope(event, getAttachmentsFromScope(scope), session);
if (envelope != null) {
transport.send(envelope, hint);
}
} catch (IOException e) {
options.getLogger().log(SentryLevel.WARNING, e, "Capturing event %s failed.", sentryId);
// if there was an error capturing the event, we return an emptyId
sentryId = SentryId.EMPTY_ID;
}
return sentryId;
}
private List<Attachment> getAttachmentsFromScope(@Nullable Scope scope) {
if (scope != null) {
return scope.getAttachments();
} else {
return null;
}
}
private @Nullable SentryEnvelope buildEnvelope(
final @Nullable SentryBaseEvent event, final @Nullable List<Attachment> attachments)
throws IOException {
return this.buildEnvelope(event, attachments, null);
}
private @Nullable SentryEnvelope buildEnvelope(
final @Nullable SentryBaseEvent event,
final @Nullable List<Attachment> attachments,
final @Nullable Session session)
throws IOException {
SentryId sentryId = null;
final List<SentryEnvelopeItem> envelopeItems = new ArrayList<>();
if (event != null) {
final SentryEnvelopeItem eventItem =
SentryEnvelopeItem.fromEvent(options.getSerializer(), event);
envelopeItems.add(eventItem);
sentryId = event.getEventId();
}
if (session != null) {
final SentryEnvelopeItem sessionItem =
SentryEnvelopeItem.fromSession(options.getSerializer(), session);
envelopeItems.add(sessionItem);
}
if (attachments != null) {
for (final Attachment attachment : attachments) {
final SentryEnvelopeItem attachmentItem =
SentryEnvelopeItem.fromAttachment(attachment, options.getMaxAttachmentSize());
envelopeItems.add(attachmentItem);
}
}
if (!envelopeItems.isEmpty()) {
final SentryEnvelopeHeader envelopeHeader =
new SentryEnvelopeHeader(sentryId, options.getSdkVersion());
return new SentryEnvelope(envelopeHeader, envelopeItems);
}
return null;
}
@Nullable
private SentryEvent processEvent(
@NotNull SentryEvent event,
final @Nullable Object hint,
final @NotNull List<EventProcessor> eventProcessors) {
for (EventProcessor processor : eventProcessors) {
try {
event = processor.process(event, hint);
} catch (Exception e) {
options
.getLogger()
.log(
SentryLevel.ERROR,
e,
"An exception occurred while processing event by processor: %s",
processor.getClass().getName());
}
if (event == null) {
options
.getLogger()
.log(
SentryLevel.DEBUG,
"Event was dropped by a processor: %s",
processor.getClass().getName());
break;
}
}
return event;
}
@Override
public void captureUserFeedback(final @NotNull UserFeedback userFeedback) {
Objects.requireNonNull(userFeedback, "SentryEvent is required.");
if (SentryId.EMPTY_ID.equals(userFeedback.getEventId())) {
options.getLogger().log(SentryLevel.WARNING, "Capturing userFeedback without a Sentry Id.");
return;
}
options
.getLogger()
.log(SentryLevel.DEBUG, "Capturing userFeedback: %s", userFeedback.getEventId());
try {
final SentryEnvelope envelope = buildEnvelope(userFeedback);
transport.send(envelope);
} catch (IOException e) {
options
.getLogger()
.log(
SentryLevel.WARNING,
e,
"Capturing user feedback %s failed.",
userFeedback.getEventId());
}
}
private @NotNull SentryEnvelope buildEnvelope(final @NotNull UserFeedback userFeedback) {
final List<SentryEnvelopeItem> envelopeItems = new ArrayList<>();
final SentryEnvelopeItem userFeedbackItem =
SentryEnvelopeItem.fromUserFeedback(options.getSerializer(), userFeedback);
envelopeItems.add(userFeedbackItem);
final SentryEnvelopeHeader envelopeHeader =
new SentryEnvelopeHeader(userFeedback.getEventId(), options.getSdkVersion());
return new SentryEnvelope(envelopeHeader, envelopeItems);
}
/**
* Updates the session data based on the event, hint and scope data
*
* @param event the SentryEvent
* @param hint the hint or null
* @param scope the Scope or null
*/
@TestOnly
@Nullable
Session updateSessionData(
final @NotNull SentryEvent event, final @Nullable Object hint, final @Nullable Scope scope) {
Session clonedSession = null;
if (ApplyScopeUtils.shouldApplyScopeData(hint)) {
if (scope != null) {
clonedSession =
scope.withSession(
session -> {
if (session != null) {
Session.State status = null;
if (event.isCrashed()) {
status = Session.State.Crashed;
}
boolean crashedOrErrored = false;
if (Session.State.Crashed == status || event.isErrored()) {
crashedOrErrored = true;
}
String userAgent = null;
if (event.getRequest() != null && event.getRequest().getHeaders() != null) {
if (event.getRequest().getHeaders().containsKey("user-agent")) {
userAgent = event.getRequest().getHeaders().get("user-agent");
}
}
if (session.update(status, userAgent, crashedOrErrored)) {
// if hint is DiskFlushNotification, it means we have an uncaughtException
// and we can end the session.
if (hint instanceof DiskFlushNotification) {
session.end();
}
}
} else {
options
.getLogger()
.log(SentryLevel.INFO, "Session is null on scope.withSession");
}
});
} else {
options.getLogger().log(SentryLevel.INFO, "Scope is null on client.captureEvent");
}
}
return clonedSession;
}
@ApiStatus.Internal
@Override
public void captureSession(final @NotNull Session session, final @Nullable Object hint) {
Objects.requireNonNull(session, "Session is required.");
if (session.getRelease() == null || session.getRelease().isEmpty()) {
options
.getLogger()
.log(SentryLevel.WARNING, "Sessions can't be captured without setting a release.");
return;
}
SentryEnvelope envelope;
try {
envelope = SentryEnvelope.from(options.getSerializer(), session, options.getSdkVersion());
} catch (IOException e) {
options.getLogger().log(SentryLevel.ERROR, "Failed to capture session.", e);
return;
}
captureEnvelope(envelope, hint);
}
@ApiStatus.Internal
@Override
public @Nullable SentryId captureEnvelope(
final @NotNull SentryEnvelope envelope, final @Nullable Object hint) {
Objects.requireNonNull(envelope, "SentryEnvelope is required.");
try {
transport.send(envelope, hint);
} catch (IOException e) {
options.getLogger().log(SentryLevel.ERROR, "Failed to capture envelope.", e);
return SentryId.EMPTY_ID;
}
return envelope.getHeader().getEventId();
}
@Override
public @NotNull SentryId captureTransaction(
@NotNull SentryTransaction transaction,
final @NotNull Scope scope,
final @Nullable Object hint) {
Objects.requireNonNull(transaction, "Transaction is required.");
options
.getLogger()
.log(SentryLevel.DEBUG, "Capturing transaction: %s", transaction.getEventId());
SentryId sentryId = transaction.getEventId();
if (ApplyScopeUtils.shouldApplyScopeData(hint)) {
transaction = applyScope(transaction, scope);
} else {
options
.getLogger()
.log(
SentryLevel.DEBUG,
"Transaction was cached so not applying scope: %s",
transaction.getEventId());
}
processTransaction(transaction);
try {
final SentryEnvelope envelope =
buildEnvelope(transaction, filterForTransaction(getAttachmentsFromScope(scope)));
if (envelope != null) {
transport.send(envelope, hint);
} else {
sentryId = SentryId.EMPTY_ID;
}
} catch (IOException e) {
options.getLogger().log(SentryLevel.WARNING, e, "Capturing transaction %s failed.", sentryId);
// if there was an error capturing the event, we return an emptyId
sentryId = SentryId.EMPTY_ID;
}
return sentryId;
}
private @Nullable List<Attachment> filterForTransaction(@Nullable List<Attachment> attachments) {
if (attachments == null) {
return null;
}
List<Attachment> attachmentsToSend = new ArrayList<>();
for (Attachment attachment : attachments) {
if (attachment.isAddToTransactions()) {
attachmentsToSend.add(attachment);
}
}
return attachmentsToSend;
}
private @NotNull SentryTransaction processTransaction(
final @NotNull SentryTransaction transaction) {
if (transaction.getRelease() == null) {
transaction.setRelease(options.getRelease());
}
if (transaction.getEnvironment() == null) {
transaction.setEnvironment(options.getEnvironment());
}
if (transaction.getSdk() == null) {
transaction.setSdk(options.getSdkVersion());
}
if (transaction.getTags() == null) {
transaction.setTags(new HashMap<>(options.getTags()));
} else {
for (Map.Entry<String, String> item : options.getTags().entrySet()) {
if (!transaction.getTags().containsKey(item.getKey())) {
transaction.setTag(item.getKey(), item.getValue());
}
}
}
final List<SentrySpan> unfinishedSpans = new ArrayList<>();
for (SentrySpan span : transaction.getSpans()) {
if (!span.isFinished()) {
unfinishedSpans.add(span);
}
}
if (!unfinishedSpans.isEmpty()) {
options
.getLogger()
.log(SentryLevel.WARNING, "Dropping %d unfinished spans", unfinishedSpans.size());
}
transaction.getSpans().removeAll(unfinishedSpans);
return transaction;
}
private @NotNull SentryTransaction applyScope(
@NotNull SentryTransaction transaction, final @Nullable Scope scope) {
if (scope != null) {
if (transaction.getRequest() == null) {
transaction.setRequest(scope.getRequest());
}
}
return transaction;
}
private @Nullable SentryEvent applyScope(
@NotNull SentryEvent event, final @Nullable Scope scope, final @Nullable Object hint) {
if (scope != null) {
if (event.getTransaction() == null) {
event.setTransaction(scope.getTransactionName());
}
if (event.getUser() == null) {
event.setUser(scope.getUser());
}
if (event.getRequest() == null) {
event.setRequest(scope.getRequest());
}
if (event.getFingerprints() == null) {
event.setFingerprints(scope.getFingerprint());
}
if (event.getBreadcrumbs() == null) {
event.setBreadcrumbs(new ArrayList<>(scope.getBreadcrumbs()));
} else {
sortBreadcrumbsByDate(event, scope.getBreadcrumbs());
}
if (event.getTags() == null) {
event.setTags(new HashMap<>(scope.getTags()));
} else {
for (Map.Entry<String, String> item : scope.getTags().entrySet()) {
if (!event.getTags().containsKey(item.getKey())) {
event.getTags().put(item.getKey(), item.getValue());
}
}
}
if (event.getExtras() == null) {
event.setExtras(new HashMap<>(scope.getExtras()));
} else {
for (Map.Entry<String, Object> item : scope.getExtras().entrySet()) {
if (!event.getExtras().containsKey(item.getKey())) {
event.getExtras().put(item.getKey(), item.getValue());
}
}
}
try {
for (Map.Entry<String, Object> entry : scope.getContexts().clone().entrySet()) {
if (!event.getContexts().containsKey(entry.getKey())) {
event.getContexts().put(entry.getKey(), entry.getValue());
}
}
} catch (CloneNotSupportedException e) {
options
.getLogger()
.log(SentryLevel.ERROR, "An error has occurred when cloning Contexts", e);
}
// Level from scope exceptionally take precedence over the event
if (scope.getLevel() != null) {
event.setLevel(scope.getLevel());
}
// Set trace data from active span to connect events with transactions
final ISpan span = scope.getSpan();
if (event.getContexts().getTrace() == null && span != null) {
event.getContexts().setTrace(span.getSpanContext());
}
event = processEvent(event, hint, scope.getEventProcessors());
}
return event;
}
private void sortBreadcrumbsByDate(
final @NotNull SentryEvent event, final @NotNull Collection<Breadcrumb> breadcrumbs) {
final List<Breadcrumb> sortedBreadcrumbs = event.getBreadcrumbs();
if (!breadcrumbs.isEmpty()) {
sortedBreadcrumbs.addAll(breadcrumbs);
Collections.sort(sortedBreadcrumbs, sortBreadcrumbsByDate);
}
}
private @Nullable SentryEvent executeBeforeSend(
@NotNull SentryEvent event, final @Nullable Object hint) {
final SentryOptions.BeforeSendCallback beforeSend = options.getBeforeSend();
if (beforeSend != null) {
try {
event = beforeSend.execute(event, hint);
} catch (Exception e) {
options
.getLogger()
.log(
SentryLevel.ERROR,
"The BeforeSend callback threw an exception. It will be added as breadcrumb and continue.",
e);
final Breadcrumb breadcrumb = new Breadcrumb();
breadcrumb.setMessage("BeforeSend callback failed.");
breadcrumb.setCategory("SentryClient");
breadcrumb.setLevel(SentryLevel.ERROR);
breadcrumb.setData("sentry:message", e.getMessage());
event.addBreadcrumb(breadcrumb);
}
}
return event;
}
@Override
public void close() {
options.getLogger().log(SentryLevel.INFO, "Closing SentryClient.");
try {
flush(options.getShutdownTimeout());
transport.close();
} catch (IOException e) {
options
.getLogger()
.log(SentryLevel.WARNING, "Failed to close the connection to the Sentry Server.", e);
}
enabled = false;
}
@Override
public void flush(final long timeoutMillis) {
transport.flush(timeoutMillis);
}
private boolean sample() {
// https://docs.sentry.io/development/sdk-dev/features/#event-sampling
if (options.getSampleRate() != null && random != null) {
final double sampling = options.getSampleRate();
return !(sampling < random.nextDouble()); // bad luck
}
return true;
}
private static final class SortBreadcrumbsByDate implements Comparator<Breadcrumb> {
@SuppressWarnings("JdkObsolete")
@Override
public int compare(final @NotNull Breadcrumb b1, final @NotNull Breadcrumb b2) {
return b1.getTimestamp().compareTo(b2.getTimestamp());
}
}
}