-
-
Notifications
You must be signed in to change notification settings - Fork 440
/
SentryClient.java
1015 lines (878 loc) · 33.4 KB
/
SentryClient.java
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
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package io.sentry;
import io.sentry.clientreport.DiscardReason;
import io.sentry.exception.SentryEnvelopeException;
import io.sentry.hints.AbnormalExit;
import io.sentry.hints.Backfillable;
import io.sentry.hints.DiskFlushNotification;
import io.sentry.hints.TransactionEnd;
import io.sentry.metrics.EncodedMetrics;
import io.sentry.metrics.IMetricsClient;
import io.sentry.metrics.NoopMetricsAggregator;
import io.sentry.protocol.Contexts;
import io.sentry.protocol.SentryId;
import io.sentry.protocol.SentryTransaction;
import io.sentry.transport.ITransport;
import io.sentry.transport.RateLimiter;
import io.sentry.util.CheckInUtils;
import io.sentry.util.HintUtils;
import io.sentry.util.Objects;
import io.sentry.util.TracingUtils;
import java.io.Closeable;
import java.io.IOException;
import java.security.SecureRandom;
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 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, IMetricsClient {
static final String SENTRY_PROTOCOL_VERSION = "7";
private boolean enabled;
private final @NotNull SentryOptions options;
private final @NotNull ITransport transport;
private final @Nullable SecureRandom random;
private final @NotNull SortBreadcrumbsByDate sortBreadcrumbsByDate = new SortBreadcrumbsByDate();
private final @NotNull IMetricsAggregator metricsAggregator;
@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());
metricsAggregator =
options.isEnableMetrics()
? new MetricsAggregator(options, this)
: NoopMetricsAggregator.getInstance();
this.random = options.getSampleRate() == null ? null : new SecureRandom();
}
private boolean shouldApplyScopeData(
final @NotNull SentryBaseEvent event, final @NotNull Hint hint) {
if (HintUtils.shouldApplyScopeData(hint)) {
return true;
} else {
options
.getLogger()
.log(SentryLevel.DEBUG, "Event was cached so not applying scope: %s", event.getEventId());
return false;
}
}
private boolean shouldApplyScopeData(final @NotNull CheckIn event, final @NotNull Hint hint) {
if (HintUtils.shouldApplyScopeData(hint)) {
return true;
} else {
options
.getLogger()
.log(
SentryLevel.DEBUG,
"Check-in was cached so not applying scope: %s",
event.getCheckInId());
return false;
}
}
@Override
public @NotNull SentryId captureEvent(
@NotNull SentryEvent event, final @Nullable IScope scope, @Nullable Hint hint) {
Objects.requireNonNull(event, "SentryEvent is required.");
if (hint == null) {
hint = new Hint();
}
if (shouldApplyScopeData(event, hint)) {
addScopeAttachmentsToHint(scope, hint);
}
options.getLogger().log(SentryLevel.DEBUG, "Capturing event: %s", event.getEventId());
if (event != null) {
final Throwable eventThrowable = event.getThrowable();
if (eventThrowable != null && options.containsIgnoredExceptionForType(eventThrowable)) {
options
.getLogger()
.log(
SentryLevel.DEBUG,
"Event was dropped as the exception %s is ignored",
eventThrowable.getClass());
options
.getClientReportRecorder()
.recordLostEvent(DiscardReason.EVENT_PROCESSOR, DataCategory.Error);
return SentryId.EMPTY_ID;
}
}
if (shouldApplyScopeData(event, 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");
return SentryId.EMPTY_ID;
}
}
event = processEvent(event, hint, options.getEventProcessors());
if (event != null) {
event = executeBeforeSend(event, hint);
if (event == null) {
options.getLogger().log(SentryLevel.DEBUG, "Event was dropped by beforeSend");
options
.getClientReportRecorder()
.recordLostEvent(DiscardReason.BEFORE_SEND, DataCategory.Error);
}
}
if (event == null) {
return SentryId.EMPTY_ID;
}
@Nullable
Session sessionBeforeUpdate =
scope != null ? scope.withSession((@Nullable Session session) -> {}) : null;
@Nullable Session session = null;
if (event != null) {
// https://develop.sentry.dev/sdk/sessions/#terminal-session-states
if (sessionBeforeUpdate == null || !sessionBeforeUpdate.isTerminated()) {
session = updateSessionData(event, hint, scope);
}
if (!sample()) {
options
.getLogger()
.log(
SentryLevel.DEBUG,
"Event %s was dropped due to sampling decision.",
event.getEventId());
options
.getClientReportRecorder()
.recordLostEvent(DiscardReason.SAMPLE_RATE, DataCategory.Error);
// setting event as null to not be sent as its been discarded by sample rate
event = null;
}
}
final boolean shouldSendSessionUpdate =
shouldSendSessionUpdateForDroppedEvent(sessionBeforeUpdate, session);
if (event == null && !shouldSendSessionUpdate) {
options
.getLogger()
.log(
SentryLevel.DEBUG,
"Not sending session update for dropped event as it did not cause the session health to change.");
return SentryId.EMPTY_ID;
}
SentryId sentryId = SentryId.EMPTY_ID;
if (event != null && event.getEventId() != null) {
sentryId = event.getEventId();
}
try {
@Nullable TraceContext traceContext = null;
if (HintUtils.hasType(hint, Backfillable.class)) {
// for backfillable hint we synthesize Baggage from event values
if (event != null) {
final Baggage baggage = Baggage.fromEvent(event, options);
traceContext = baggage.toTraceContext();
}
} else if (scope != null) {
final @Nullable ITransaction transaction = scope.getTransaction();
if (transaction != null) {
traceContext = transaction.traceContext();
} else {
final @NotNull PropagationContext propagationContext =
TracingUtils.maybeUpdateBaggage(scope, options);
traceContext = propagationContext.traceContext();
}
}
final boolean shouldSendAttachments = event != null;
List<Attachment> attachments = shouldSendAttachments ? getAttachments(hint) : null;
final @Nullable SentryEnvelope envelope =
buildEnvelope(event, attachments, session, traceContext, null);
hint.clear();
if (envelope != null) {
sentryId = sendEnvelope(envelope, hint);
}
} catch (IOException | SentryEnvelopeException 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;
}
// if we encountered a crash/abnormal exit finish tracing in order to persist and send
// any running transaction / profiling data
if (scope != null) {
final @Nullable ITransaction transaction = scope.getTransaction();
if (transaction != null) {
if (HintUtils.hasType(hint, TransactionEnd.class)) {
final Object sentrySdkHint = HintUtils.getSentrySdkHint(hint);
if (sentrySdkHint instanceof DiskFlushNotification) {
((DiskFlushNotification) sentrySdkHint).setFlushable(transaction.getEventId());
transaction.forceFinish(SpanStatus.ABORTED, false, hint);
} else {
transaction.forceFinish(SpanStatus.ABORTED, false, null);
}
}
}
}
return sentryId;
}
private void addScopeAttachmentsToHint(@Nullable IScope scope, @NotNull Hint hint) {
if (scope != null) {
hint.addAttachments(scope.getAttachments());
}
}
private boolean shouldSendSessionUpdateForDroppedEvent(
@Nullable Session sessionBeforeUpdate, @Nullable Session sessionAfterUpdate) {
if (sessionAfterUpdate == null) {
return false;
}
if (sessionBeforeUpdate == null) {
return true;
}
final boolean didSessionMoveToCrashedState =
sessionAfterUpdate.getStatus() == Session.State.Crashed
&& sessionBeforeUpdate.getStatus() != Session.State.Crashed;
if (didSessionMoveToCrashedState) {
return true;
}
final boolean didSessionMoveToErroredState =
sessionAfterUpdate.errorCount() > 0 && sessionBeforeUpdate.errorCount() <= 0;
if (didSessionMoveToErroredState) {
return true;
}
return false;
}
private @Nullable List<Attachment> getAttachments(final @NotNull Hint hint) {
@NotNull final List<Attachment> attachments = hint.getAttachments();
@Nullable final Attachment screenshot = hint.getScreenshot();
if (screenshot != null) {
attachments.add(screenshot);
}
@Nullable final Attachment viewHierarchy = hint.getViewHierarchy();
if (viewHierarchy != null) {
attachments.add(viewHierarchy);
}
@Nullable final Attachment threadDump = hint.getThreadDump();
if (threadDump != null) {
attachments.add(threadDump);
}
return attachments;
}
private @Nullable SentryEnvelope buildEnvelope(
final @Nullable SentryBaseEvent event,
final @Nullable List<Attachment> attachments,
final @Nullable Session session,
final @Nullable TraceContext traceContext,
final @Nullable ProfilingTraceData profilingTraceData)
throws IOException, SentryEnvelopeException {
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 (profilingTraceData != null) {
final SentryEnvelopeItem profilingTraceItem =
SentryEnvelopeItem.fromProfilingTrace(
profilingTraceData, options.getMaxTraceFileSize(), options.getSerializer());
envelopeItems.add(profilingTraceItem);
if (sentryId == null) {
sentryId = new SentryId(profilingTraceData.getProfileId());
}
}
if (attachments != null) {
for (final Attachment attachment : attachments) {
final SentryEnvelopeItem attachmentItem =
SentryEnvelopeItem.fromAttachment(
options.getSerializer(),
options.getLogger(),
attachment,
options.getMaxAttachmentSize());
envelopeItems.add(attachmentItem);
}
}
if (!envelopeItems.isEmpty()) {
final SentryEnvelopeHeader envelopeHeader =
new SentryEnvelopeHeader(sentryId, options.getSdkVersion(), traceContext);
return new SentryEnvelope(envelopeHeader, envelopeItems);
}
return null;
}
@Nullable
private SentryEvent processEvent(
@NotNull SentryEvent event,
final @NotNull Hint hint,
final @NotNull List<EventProcessor> eventProcessors) {
for (final EventProcessor processor : eventProcessors) {
try {
// only wire backfillable events through the backfilling processors, skip from others, and
// the other way around
final boolean isBackfillingProcessor = processor instanceof BackfillingEventProcessor;
final boolean isBackfillable = HintUtils.hasType(hint, Backfillable.class);
if (isBackfillable && isBackfillingProcessor) {
event = processor.process(event, hint);
} else if (!isBackfillable && !isBackfillingProcessor) {
event = processor.process(event, hint);
}
} catch (Throwable 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());
options
.getClientReportRecorder()
.recordLostEvent(DiscardReason.EVENT_PROCESSOR, DataCategory.Error);
break;
}
}
return event;
}
@Nullable
private SentryTransaction processTransaction(
@NotNull SentryTransaction transaction,
final @NotNull Hint hint,
final @NotNull List<EventProcessor> eventProcessors) {
for (final EventProcessor processor : eventProcessors) {
try {
transaction = processor.process(transaction, hint);
} catch (Throwable e) {
options
.getLogger()
.log(
SentryLevel.ERROR,
e,
"An exception occurred while processing transaction by processor: %s",
processor.getClass().getName());
}
if (transaction == null) {
options
.getLogger()
.log(
SentryLevel.DEBUG,
"Transaction was dropped by a processor: %s",
processor.getClass().getName());
options
.getClientReportRecorder()
.recordLostEvent(DiscardReason.EVENT_PROCESSOR, DataCategory.Transaction);
break;
}
}
return transaction;
}
@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 @NotNull SentryEnvelope envelope = buildEnvelope(userFeedback);
sendEnvelope(envelope, null);
} 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);
}
private @NotNull SentryEnvelope buildEnvelope(
final @NotNull CheckIn checkIn, final @Nullable TraceContext traceContext) {
final List<SentryEnvelopeItem> envelopeItems = new ArrayList<>();
final SentryEnvelopeItem checkInItem =
SentryEnvelopeItem.fromCheckIn(options.getSerializer(), checkIn);
envelopeItems.add(checkInItem);
final SentryEnvelopeHeader envelopeHeader =
new SentryEnvelopeHeader(checkIn.getCheckInId(), options.getSdkVersion(), traceContext);
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 @NotNull Hint hint, final @Nullable IScope scope) {
Session clonedSession = null;
if (HintUtils.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");
}
}
final Object sentrySdkHint = HintUtils.getSentrySdkHint(hint);
@Nullable String abnormalMechanism = null;
if (sentrySdkHint instanceof AbnormalExit) {
abnormalMechanism = ((AbnormalExit) sentrySdkHint).mechanism();
status = Session.State.Abnormal;
}
if (session.update(status, userAgent, crashedOrErrored, abnormalMechanism)) {
// if session terminated we can end it.
if (session.isTerminated()) {
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 Hint 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 @NotNull SentryId captureEnvelope(
final @NotNull SentryEnvelope envelope, @Nullable Hint hint) {
Objects.requireNonNull(envelope, "SentryEnvelope is required.");
if (hint == null) {
hint = new Hint();
}
try {
hint.clear();
return sendEnvelope(envelope, hint);
} catch (IOException e) {
options.getLogger().log(SentryLevel.ERROR, "Failed to capture envelope.", e);
}
return SentryId.EMPTY_ID;
}
private @NotNull SentryId sendEnvelope(
@NotNull final SentryEnvelope envelope, @Nullable final Hint hint) throws IOException {
final @Nullable SentryOptions.BeforeEnvelopeCallback beforeEnvelopeCallback =
options.getBeforeEnvelopeCallback();
if (beforeEnvelopeCallback != null) {
try {
beforeEnvelopeCallback.execute(envelope, hint);
} catch (Throwable e) {
options
.getLogger()
.log(SentryLevel.ERROR, "The BeforeEnvelope callback threw an exception.", e);
}
}
if (hint == null) {
transport.send(envelope);
} else {
transport.send(envelope, hint);
}
final @Nullable SentryId id = envelope.getHeader().getEventId();
return id != null ? id : SentryId.EMPTY_ID;
}
@Override
public @NotNull SentryId captureTransaction(
@NotNull SentryTransaction transaction,
@Nullable TraceContext traceContext,
final @Nullable IScope scope,
@Nullable Hint hint,
final @Nullable ProfilingTraceData profilingTraceData) {
Objects.requireNonNull(transaction, "Transaction is required.");
if (hint == null) {
hint = new Hint();
}
if (shouldApplyScopeData(transaction, hint)) {
addScopeAttachmentsToHint(scope, hint);
}
options
.getLogger()
.log(SentryLevel.DEBUG, "Capturing transaction: %s", transaction.getEventId());
SentryId sentryId = SentryId.EMPTY_ID;
if (transaction.getEventId() != null) {
sentryId = transaction.getEventId();
}
if (shouldApplyScopeData(transaction, hint)) {
transaction = applyScope(transaction, scope);
if (transaction != null && scope != null) {
transaction = processTransaction(transaction, hint, scope.getEventProcessors());
}
if (transaction == null) {
options.getLogger().log(SentryLevel.DEBUG, "Transaction was dropped by applyScope");
}
}
if (transaction != null) {
transaction = processTransaction(transaction, hint, options.getEventProcessors());
}
if (transaction == null) {
options.getLogger().log(SentryLevel.DEBUG, "Transaction was dropped by Event processors.");
return SentryId.EMPTY_ID;
}
transaction = executeBeforeSendTransaction(transaction, hint);
if (transaction == null) {
options
.getLogger()
.log(SentryLevel.DEBUG, "Transaction was dropped by beforeSendTransaction.");
options
.getClientReportRecorder()
.recordLostEvent(DiscardReason.BEFORE_SEND, DataCategory.Transaction);
return SentryId.EMPTY_ID;
}
try {
final SentryEnvelope envelope =
buildEnvelope(
transaction,
filterForTransaction(getAttachments(hint)),
null,
traceContext,
profilingTraceData);
hint.clear();
if (envelope != null) {
sentryId = sendEnvelope(envelope, hint);
}
} catch (IOException | SentryEnvelopeException 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;
}
@Override
@ApiStatus.Experimental
public @NotNull SentryId captureCheckIn(
@NotNull CheckIn checkIn, final @Nullable IScope scope, @Nullable Hint hint) {
if (hint == null) {
hint = new Hint();
}
if (checkIn.getEnvironment() == null) {
checkIn.setEnvironment(options.getEnvironment());
}
if (checkIn.getRelease() == null) {
checkIn.setRelease(options.getRelease());
}
if (shouldApplyScopeData(checkIn, hint)) {
checkIn = applyScope(checkIn, scope);
}
if (CheckInUtils.isIgnored(options.getIgnoredCheckIns(), checkIn.getMonitorSlug())) {
options
.getLogger()
.log(
SentryLevel.DEBUG,
"Check-in was dropped as slug %s is ignored",
checkIn.getMonitorSlug());
// TODO in a follow up PR with DataCategory.Monitor
// options
// .getClientReportRecorder()
// .recordLostEvent(DiscardReason.EVENT_PROCESSOR, DataCategory.Error);
return SentryId.EMPTY_ID;
}
options.getLogger().log(SentryLevel.DEBUG, "Capturing check-in: %s", checkIn.getCheckInId());
SentryId sentryId = checkIn.getCheckInId();
try {
@Nullable TraceContext traceContext = null;
if (scope != null) {
final @Nullable ITransaction transaction = scope.getTransaction();
if (transaction != null) {
traceContext = transaction.traceContext();
} else {
final @NotNull PropagationContext propagationContext =
TracingUtils.maybeUpdateBaggage(scope, options);
traceContext = propagationContext.traceContext();
}
}
final @NotNull SentryEnvelope envelope = buildEnvelope(checkIn, traceContext);
hint.clear();
sentryId = sendEnvelope(envelope, hint);
} catch (IOException e) {
options.getLogger().log(SentryLevel.WARNING, e, "Capturing check-in %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 @Nullable SentryEvent applyScope(
@NotNull SentryEvent event, final @Nullable IScope scope, final @NotNull Hint hint) {
if (scope != null) {
applyScope(event, scope);
if (event.getTransaction() == null) {
event.setTransaction(scope.getTransactionName());
}
if (event.getFingerprints() == null) {
event.setFingerprints(scope.getFingerprint());
}
// 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) {
if (span == null) {
event
.getContexts()
.setTrace(TransactionContext.fromPropagationContext(scope.getPropagationContext()));
} else {
event.getContexts().setTrace(span.getSpanContext());
}
}
event = processEvent(event, hint, scope.getEventProcessors());
}
return event;
}
private @NotNull CheckIn applyScope(@NotNull CheckIn checkIn, final @Nullable IScope scope) {
if (scope != null) {
// Set trace data from active span to connect events with transactions
final ISpan span = scope.getSpan();
if (checkIn.getContexts().getTrace() == null) {
if (span == null) {
checkIn
.getContexts()
.setTrace(TransactionContext.fromPropagationContext(scope.getPropagationContext()));
} else {
checkIn.getContexts().setTrace(span.getSpanContext());
}
}
}
return checkIn;
}
private <T extends SentryBaseEvent> @NotNull T applyScope(
final @NotNull T sentryBaseEvent, final @Nullable IScope scope) {
if (scope != null) {
if (sentryBaseEvent.getRequest() == null) {
sentryBaseEvent.setRequest(scope.getRequest());
}
if (sentryBaseEvent.getUser() == null) {
sentryBaseEvent.setUser(scope.getUser());
}
if (sentryBaseEvent.getTags() == null) {
sentryBaseEvent.setTags(new HashMap<>(scope.getTags()));
} else {
for (Map.Entry<String, String> item : scope.getTags().entrySet()) {
if (!sentryBaseEvent.getTags().containsKey(item.getKey())) {
sentryBaseEvent.getTags().put(item.getKey(), item.getValue());
}
}
}
if (sentryBaseEvent.getBreadcrumbs() == null) {
sentryBaseEvent.setBreadcrumbs(new ArrayList<>(scope.getBreadcrumbs()));
} else {
sortBreadcrumbsByDate(sentryBaseEvent, scope.getBreadcrumbs());
}
if (sentryBaseEvent.getExtras() == null) {
sentryBaseEvent.setExtras(new HashMap<>(scope.getExtras()));
} else {
for (Map.Entry<String, Object> item : scope.getExtras().entrySet()) {
if (!sentryBaseEvent.getExtras().containsKey(item.getKey())) {
sentryBaseEvent.getExtras().put(item.getKey(), item.getValue());
}
}
}
final Contexts contexts = sentryBaseEvent.getContexts();
for (Map.Entry<String, Object> entry : new Contexts(scope.getContexts()).entrySet()) {
if (!contexts.containsKey(entry.getKey())) {
contexts.put(entry.getKey(), entry.getValue());
}
}
}
return sentryBaseEvent;
}
private void sortBreadcrumbsByDate(
final @NotNull SentryBaseEvent event, final @NotNull Collection<Breadcrumb> breadcrumbs) {
final List<Breadcrumb> sortedBreadcrumbs = event.getBreadcrumbs();
if (sortedBreadcrumbs != null && !breadcrumbs.isEmpty()) {
sortedBreadcrumbs.addAll(breadcrumbs);
Collections.sort(sortedBreadcrumbs, sortBreadcrumbsByDate);
}
}
private @Nullable SentryEvent executeBeforeSend(
@NotNull SentryEvent event, final @NotNull Hint hint) {
final SentryOptions.BeforeSendCallback beforeSend = options.getBeforeSend();
if (beforeSend != null) {
try {
event = beforeSend.execute(event, hint);
} catch (Throwable e) {
options
.getLogger()
.log(
SentryLevel.ERROR,
"The BeforeSend callback threw an exception. It will be added as breadcrumb and continue.",
e);
// drop event in case of an error in beforeSend due to PII concerns
event = null;
}
}
return event;
}
private @Nullable SentryTransaction executeBeforeSendTransaction(
@NotNull SentryTransaction transaction, final @NotNull Hint hint) {
final SentryOptions.BeforeSendTransactionCallback beforeSendTransaction =
options.getBeforeSendTransaction();
if (beforeSendTransaction != null) {
try {
transaction = beforeSendTransaction.execute(transaction, hint);
} catch (Throwable e) {
options
.getLogger()
.log(
SentryLevel.ERROR,
"The BeforeSendTransaction callback threw an exception. It will be added as breadcrumb and continue.",
e);
// drop transaction in case of an error in beforeSend due to PII concerns
transaction = null;
}
}
return transaction;
}
@Override
public void close() {
close(false);
}
@Override
public void close(final boolean isRestarting) {
options.getLogger().log(SentryLevel.INFO, "Closing SentryClient.");
try {
metricsAggregator.close();
} catch (IOException e) {
options.getLogger().log(SentryLevel.WARNING, "Failed to close the metrics aggregator.", e);
}
try {
flush(isRestarting ? 0 : options.getShutdownTimeoutMillis());
transport.close(isRestarting);
} catch (IOException e) {
options
.getLogger()
.log(SentryLevel.WARNING, "Failed to close the connection to the Sentry Server.", e);
}
for (EventProcessor eventProcessor : options.getEventProcessors()) {
if (eventProcessor instanceof Closeable) {
try {
((Closeable) eventProcessor).close();
} catch (IOException e) {
options
.getLogger()
.log(
SentryLevel.WARNING,
"Failed to close the event processor {}.",
eventProcessor,
e);
}
}
}
enabled = false;
}
@Override
public void flush(final long timeoutMillis) {
transport.flush(timeoutMillis);
}
@Override
public @Nullable RateLimiter getRateLimiter() {
return transport.getRateLimiter();
}
@Override
public boolean isHealthy() {
return transport.isHealthy();
}
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;
}
@Override
public @NotNull IMetricsAggregator getMetricsAggregator() {
return metricsAggregator;
}
@Override
public @NotNull SentryId captureMetrics(final @NotNull EncodedMetrics metrics) {
final @NotNull SentryEnvelopeItem envelopeItem = SentryEnvelopeItem.fromMetrics(metrics);
final @NotNull SentryEnvelopeHeader envelopeHeader =
new SentryEnvelopeHeader(new SentryId(), options.getSdkVersion(), null);