-
-
Notifications
You must be signed in to change notification settings - Fork 385
Expand file tree
/
Copy pathSentryClient.m
More file actions
1155 lines (983 loc) · 45.4 KB
/
SentryClient.m
File metadata and controls
1155 lines (983 loc) · 45.4 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
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
#import "SentryClient.h"
#import "SentryAttachment.h"
#import "SentryClient+Private.h"
#import "SentryCrashDefaultMachineContextWrapper.h"
#import "SentryCrashStackEntryMapper.h"
#import "SentryDefaultTelemetryProcessorTransport.h"
#import "SentryDefaultThreadInspector.h"
#import "SentryDeviceContextKeys.h"
#import "SentryEvent+Private.h"
#import "SentryException.h"
#import "SentryInternalDefines.h"
#import "SentryLogC.h"
#import "SentryMechanism.h"
#import "SentryMechanismContext.h"
#import "SentryMessage.h"
#import "SentryMeta.h"
#import "SentryMsgPackSerializer.h"
#import "SentryNSDictionarySanitize.h"
#import "SentryNSError.h"
#import "SentrySDK+Private.h"
#import "SentryScope+Private.h"
#import "SentryScope+PrivateSwift.h"
#import "SentrySerialization.h"
#import "SentryStacktraceBuilder.h"
#import "SentrySwift.h"
#import "SentryTraceContext+Private.h"
#import "SentryTraceContext.h"
#import "SentryTracer.h"
#import "SentryTransaction.h"
#import "SentryTransport.h"
#import "SentryTransportAdapter.h"
#import "SentryTransportFactory.h"
#import "SentryUseNSExceptionCallstackWrapper.h"
#import "SentryUser.h"
#if SENTRY_HAS_UIKIT
# import <UIKit/UIKit.h>
#endif
NS_ASSUME_NONNULL_BEGIN
@protocol SentryEventContextEnricher;
@interface SentryClientInternal ()
@property (nonatomic, strong) SentryTransportAdapter *transportAdapter;
@property (nonatomic, strong) SentryDebugImageProvider *debugImageProvider;
@property (nonatomic, strong) id<SentryRandomProtocol> random;
@property (nonatomic, strong) NSLocale *locale;
@property (nonatomic, strong) NSTimeZone *timezone;
@property (nonatomic, strong) id<SentryLogScopeApplier> logScopeApplier;
@property (nonatomic, strong) id<SentryTelemetryProcessor> telemetryProcessor;
@property (nonatomic, strong) id<SentryEventContextEnricher> eventContextEnricher;
@end
NSString *const DropSessionLogMessage = @"Session has no release name. Won't send it.";
@implementation SentryClientInternal
- (_Nullable instancetype)initWithOptions:(SentryOptions *)options
{
NSError *error;
SentryFileManager *fileManager = [[SentryFileManager alloc]
initWithOptions:options
dateProvider:SentryDependencyContainer.sharedInstance.dateProvider
dispatchQueueWrapper:SentryDependencyContainer.sharedInstance.dispatchQueueWrapper
error:&error];
if (error != nil) {
SENTRY_LOG_FATAL(@"Failed to initialize file system: %@", error.localizedDescription);
return nil;
}
NSArray<id<SentryTransport>> *transports = [SentryTransportFactory
initTransports:options
dateProvider:SentryDependencyContainer.sharedInstance.dateProvider
sentryFileManager:fileManager
rateLimits:SentryDependencyContainer.sharedInstance.rateLimits
reachability:SentryDependencyContainer.sharedInstance.reachability];
SentryTransportAdapter *transportAdapter =
[[SentryTransportAdapter alloc] initWithTransports:transports options:options];
SentryDefaultThreadInspector *threadInspector =
[[SentryDefaultThreadInspector alloc] initWithOptions:options];
id<SentryEventContextEnricher> eventContextEnricher
= SentryDependencyContainer.sharedInstance.eventContextEnricher;
return [self initWithOptions:options
dateProvider:SentryDependencyContainer.sharedInstance.dateProvider
transportAdapter:transportAdapter
fileManager:fileManager
threadInspector:threadInspector
debugImageProvider:[SentryDependencyContainer sharedInstance].debugImageProvider
random:[SentryDependencyContainer sharedInstance].random
locale:[NSLocale autoupdatingCurrentLocale]
timezone:[NSCalendar autoupdatingCurrentCalendar].timeZone
eventContextEnricher:eventContextEnricher];
}
- (instancetype)initWithOptions:(SentryOptions *)options
dateProvider:(id<SentryCurrentDateProvider>)dateProvider
transportAdapter:(SentryTransportAdapter *)transportAdapter
fileManager:(SentryFileManager *)fileManager
threadInspector:(SentryDefaultThreadInspector *)threadInspector
debugImageProvider:(SentryDebugImageProvider *)debugImageProvider
random:(id<SentryRandomProtocol>)random
locale:(NSLocale *)locale
timezone:(NSTimeZone *)timezone
eventContextEnricher:(id<SentryEventContextEnricher>)eventContextEnricher
{
if (self = [super init]) {
_isEnabled = YES;
self.options = options;
self.transportAdapter = transportAdapter;
self.fileManager = fileManager;
self.threadInspector = threadInspector;
self.random = random;
self.debugImageProvider = debugImageProvider;
self.locale = locale;
self.timezone = timezone;
self.attachmentProcessors = [[NSMutableArray alloc] init];
self.eventContextEnricher = eventContextEnricher;
self.telemetryProcessor = [SentryTelemetryProcessorFactory
getProcessorWithTransport:[[SentryDefaultTelemetryProcessorTransport alloc]
initWithTransportAdapter:transportAdapter]
dependencies:SentryDependencyContainer.sharedInstance];
self.logScopeApplier =
[[SentryDefaultLogScopeApplier alloc] initWithEnvironment:options.environment
releaseName:options.releaseName
cacheDirectoryPath:options.cacheDirectoryPath
sendDefaultPii:options.sendDefaultPii];
// The SDK stores the installationID in a file. The first call requires file IO. To avoid
// executing this on the main thread, we cache the installationID async here.
[SentryInstallation cacheIDAsyncWithCacheDirectoryPath:options.cacheDirectoryPath];
[fileManager deleteOldEnvelopeItems];
}
return self;
}
- (void)setOptionsInternal:(SentryOptions *)optionsInternal
{
self.options = optionsInternal;
}
- (NSObject *)getOptions
{
return self.options;
}
- (SentryId *)captureMessage:(NSString *)message
{
return [self captureMessage:message withScope:[[SentryScope alloc] init]];
}
- (SentryId *)captureMessage:(NSString *)message withScope:(SentryScope *)scope
{
SentryEvent *event = [[SentryEvent alloc] initWithLevel:kSentryLevelInfo];
event.message = [[SentryMessage alloc] initWithFormatted:message];
return [self sendEvent:event withScope:scope alwaysAttachStacktrace:NO];
}
- (SentryId *)captureException:(NSException *)exception
{
return [self captureException:exception withScope:[[SentryScope alloc] init]];
}
- (SentryId *)captureException:(NSException *)exception withScope:(SentryScope *)scope
{
SentryEvent *event = [self buildExceptionEvent:exception];
return [self captureEventIncrementingSessionErrorCount:event withScope:scope];
}
- (SentryEvent *)buildExceptionEvent:(NSException *)exception
{
SentryEvent *event = [[SentryEvent alloc] initWithLevel:kSentryLevelError];
SentryException *sentryException = [[SentryException alloc] initWithValue:exception.reason
type:exception.name];
event.exceptions = @[ sentryException ];
#if TARGET_OS_OSX
// When a exception class is SentryUseNSExceptionCallstackWrapper, we should use the thread from
// it
if ([exception isKindOfClass:[SentryUseNSExceptionCallstackWrapper class]]) {
event.threads = [(SentryUseNSExceptionCallstackWrapper *)exception buildThreads];
}
#endif
[self setUserInfo:exception.userInfo withEvent:event];
return event;
}
- (SentryId *)captureError:(NSError *)error
{
return [self captureError:error withScope:[[SentryScope alloc] init]];
}
- (SentryId *)captureError:(NSError *)error withScope:(SentryScope *)scope
{
SentryEvent *event = [self buildErrorEvent:error];
return [self captureEventIncrementingSessionErrorCount:event withScope:scope];
}
- (SentryEvent *)buildErrorEvent:(NSError *)error
{
SentryEvent *event = [[SentryEvent alloc] initWithError:error];
// flatten any recursive description of underlying errors into a list, to ultimately report them
// as a list of exceptions with error mechanisms, sorted oldest to newest (so, the leaf node
// underlying error as oldest, with the root as the newest)
NSMutableArray<NSError *> *errors = [NSMutableArray<NSError *> arrayWithObject:error];
NSError *underlyingError;
if ([error.userInfo[NSUnderlyingErrorKey] isKindOfClass:[NSError class]]) {
underlyingError = error.userInfo[NSUnderlyingErrorKey];
} else if (error.userInfo[NSUnderlyingErrorKey] != nil) {
SENTRY_LOG_WARN(@"Invalid value for NSUnderlyingErrorKey in user info. Data at key: %@. "
@"Class type: %@.",
error.userInfo[NSUnderlyingErrorKey], [error.userInfo[NSUnderlyingErrorKey] class]);
}
while (underlyingError != nil) {
[errors addObject:underlyingError];
if ([underlyingError.userInfo[NSUnderlyingErrorKey] isKindOfClass:[NSError class]]) {
underlyingError = underlyingError.userInfo[NSUnderlyingErrorKey];
} else {
if (underlyingError.userInfo[NSUnderlyingErrorKey] != nil) {
SENTRY_LOG_WARN(@"Invalid value for NSUnderlyingErrorKey in user info. Data at "
@"key: %@. Class type: %@.",
underlyingError.userInfo[NSUnderlyingErrorKey],
[underlyingError.userInfo[NSUnderlyingErrorKey] class]);
}
underlyingError = nil;
}
}
NSMutableArray<SentryException *> *exceptions = [NSMutableArray<SentryException *> array];
[errors enumerateObjectsWithOptions:NSEnumerationReverse
usingBlock:^(NSError *_Nonnull nextError, NSUInteger __unused idx,
BOOL *_Nonnull __unused stop) {
[exceptions addObject:[self exceptionForError:nextError]];
}];
event.exceptions = exceptions;
// Once the UI displays the mechanism data we can the userInfo from the event.context using only
// the root error's userInfo.
[self setUserInfo:sentry_sanitize(error.userInfo) withEvent:event];
return event;
}
- (SentryException *)exceptionForError:(NSError *)error
{
NSString *exceptionValue;
// If the error has a debug description, use that.
NSString *customExceptionValue = [[error userInfo] valueForKey:NSDebugDescriptionErrorKey];
NSString *swiftErrorDescription = nil;
// SwiftNativeNSError is the subclass of NSError used to represent bridged native Swift errors,
// see
// https://github.com/apple/swift/blob/067e4ec50147728f2cb990dbc7617d66692c1554/stdlib/public/runtime/ErrorObject.mm#L63-L73
NSString *errorClass = NSStringFromClass(error.class);
if ([errorClass containsString:@"SwiftNativeNSError"]) {
swiftErrorDescription = [SwiftDescriptor getSwiftErrorDescription:error];
}
if (customExceptionValue != nil) {
exceptionValue =
[NSString stringWithFormat:@"%@ (Code: %ld)", customExceptionValue, (long)error.code];
} else if (swiftErrorDescription != nil) {
exceptionValue =
[NSString stringWithFormat:@"%@ (Code: %ld)", swiftErrorDescription, (long)error.code];
} else {
exceptionValue = [NSString stringWithFormat:@"Code: %ld", (long)error.code];
}
SentryException *exception = [[SentryException alloc] initWithValue:exceptionValue
type:error.domain];
// Sentry uses the error domain and code on the mechanism for gouping
SentryMechanism *mechanism = [[SentryMechanism alloc] initWithType:@"NSError"];
SentryMechanismContext *mechanismMeta = [[SentryMechanismContext alloc] init];
mechanismMeta.error = [[SentryNSError alloc] initWithDomain:error.domain code:error.code];
mechanism.meta = mechanismMeta;
// The description of the error can be especially useful for error from swift that
// use a simple enum.
mechanism.desc = error.description;
NSDictionary<NSString *, id> *userInfo = sentry_sanitize(error.userInfo);
mechanism.data = userInfo;
exception.mechanism = mechanism;
return exception;
}
- (SentryId *)captureFatalEvent:(SentryEvent *)event withScope:(SentryScope *)scope
{
return [self sendEvent:event withScope:scope alwaysAttachStacktrace:NO isFatalEvent:YES];
}
- (SentryId *)captureFatalEvent:(SentryEvent *)event
withSession:(SentrySession *)session
withScope:(SentryScope *)scope
{
SentryEvent *preparedEvent = [self prepareEvent:event
withScope:scope
alwaysAttachStacktrace:NO
isFatalEvent:YES];
return [self sendEvent:preparedEvent withSession:session withScope:scope];
}
- (void)saveCrashTransaction:(SentryTransaction *)transaction withScope:(SentryScope *)scope
{
SentryEvent *preparedEvent = [self prepareEvent:transaction
withScope:scope
alwaysAttachStacktrace:NO
isFatalEvent:NO];
if (preparedEvent == nil) {
return;
}
SentryTraceContext *traceContext = [self getTraceStateWithEvent:transaction withScope:scope];
[self.transportAdapter storeEvent:preparedEvent traceContext:traceContext];
}
- (SentryId *)captureEvent:(SentryEvent *)event
{
return [self captureEvent:event withScope:[[SentryScope alloc] init]];
}
- (SentryId *)captureEvent:(SentryEvent *)event withScope:(SentryScope *)scope
{
return [self sendEvent:event withScope:scope alwaysAttachStacktrace:NO];
}
- (SentryId *)captureEvent:(SentryEvent *)event
withScope:(SentryScope *)scope
additionalEnvelopeItems:(NSArray<SentryEnvelopeItem *> *)additionalEnvelopeItems
{
return [self sendEvent:event
withScope:scope
alwaysAttachStacktrace:NO
isFatalEvent:NO
additionalEnvelopeItems:additionalEnvelopeItems];
}
- (SentryId *)captureEventIncrementingSessionErrorCount:(SentryEvent *)event
withScope:(SentryScope *)scope
{
SentryEvent *preparedEvent = [self prepareEvent:event
withScope:scope
alwaysAttachStacktrace:YES];
if (preparedEvent != nil) {
SentrySession *session = nil;
id<SentrySessionDelegate> delegate = self.sessionDelegate;
if (delegate != nil) {
session = [delegate incrementSessionErrors];
}
return [self sendEvent:preparedEvent withSession:session withScope:scope];
}
return SentryId.empty;
}
- (SentryId *)sendEvent:(SentryEvent *)event
withScope:(SentryScope *)scope
alwaysAttachStacktrace:(BOOL)alwaysAttachStacktrace
{
return [self sendEvent:event
withScope:scope
alwaysAttachStacktrace:alwaysAttachStacktrace
isFatalEvent:NO];
}
- (nullable SentryTraceContext *)getTraceStateWithEvent:(SentryEvent *)event
withScope:(SentryScope *)scope
{
id<SentrySpan> span;
if ([event isKindOfClass:[SentryTransaction class]]) {
span = [(SentryTransaction *)event trace];
} else {
// Even envelopes without transactions can contain the trace state, allowing Sentry to
// eventually sample attachments belonging to a transaction.
span = scope.span;
}
SentryTracer *tracer = [SentryTracer getTracer:span];
if (tracer != nil) {
return [[SentryTraceContext alloc] initWithTracer:tracer scope:scope options:_options];
}
if (event.error || event.exceptions.count > 0) {
return [[SentryTraceContext alloc] initWithTraceId:scope.propagationContext.traceId
options:self.options
replayId:scope.replayId];
}
return nil;
}
- (SentryId *)sendEvent:(SentryEvent *)event
withScope:(SentryScope *)scope
alwaysAttachStacktrace:(BOOL)alwaysAttachStacktrace
isFatalEvent:(BOOL)isFatalEvent
{
return [self sendEvent:event
withScope:scope
alwaysAttachStacktrace:alwaysAttachStacktrace
isFatalEvent:isFatalEvent
additionalEnvelopeItems:@[]];
}
- (SentryId *)sendEvent:(SentryEvent *)event
withScope:(SentryScope *)scope
alwaysAttachStacktrace:(BOOL)alwaysAttachStacktrace
isFatalEvent:(BOOL)isFatalEvent
additionalEnvelopeItems:(NSArray<SentryEnvelopeItem *> *)additionalEnvelopeItems
{
SentryEvent *preparedEvent = [self prepareEvent:event
withScope:scope
alwaysAttachStacktrace:alwaysAttachStacktrace
isFatalEvent:isFatalEvent];
if (preparedEvent == nil) {
return SentryId.empty;
}
SentryTraceContext *traceContext = [self getTraceStateWithEvent:event withScope:scope];
NSArray<SentryAttachment *> *attachments = [self processAttachmentsForEvent:preparedEvent
attachments:scope.attachments];
[self.transportAdapter sendEvent:preparedEvent
traceContext:traceContext
attachments:attachments
additionalEnvelopeItems:additionalEnvelopeItems];
return preparedEvent.eventId;
}
- (SentryId *)sendEvent:(SentryEvent *)event
withSession:(nullable SentrySession *)session
withScope:(SentryScope *)scope
{
if (event == nil) {
return SentryId.empty;
}
NSArray<SentryAttachment *> *attachments = [self processAttachmentsForEvent:event
attachments:scope.attachments];
if (event.isFatalEvent && event.context[@"replay"] &&
[event.context[@"replay"] isKindOfClass:NSDictionary.class]) {
NSDictionary *replay = event.context[@"replay"];
scope.replayId = replay[@"replay_id"];
}
SentryTraceContext *traceContext = [self getTraceStateWithEvent:event withScope:scope];
if (session == nil) {
[self.transportAdapter sendEvent:event traceContext:traceContext attachments:attachments];
return event.eventId;
}
SentrySession *nonnullSession = SENTRY_UNWRAP_NULLABLE(SentrySession, session);
if (nonnullSession.releaseName == nil || [nonnullSession.releaseName length] == 0) {
SENTRY_LOG_DEBUG(DropSessionLogMessage);
[self.transportAdapter sendEvent:event traceContext:traceContext attachments:attachments];
return event.eventId;
}
[self.transportAdapter sendEvent:event
withSession:nonnullSession
traceContext:traceContext
attachments:attachments];
return event.eventId;
}
- (void)captureSession:(SentrySession *)session
{
if (nil == session.releaseName || [session.releaseName length] == 0) {
SENTRY_LOG_DEBUG(DropSessionLogMessage);
return;
}
SentryEnvelopeItem *item = [[SentryEnvelopeItem alloc] initWithSession:session];
SentryEnvelope *envelope = [[SentryEnvelope alloc] initWithHeader:[SentryEnvelopeHeader empty]
singleItem:item];
[self captureEnvelope:envelope];
}
- (void)captureReplayEvent:(SentryReplayEvent *)replayEvent
replayRecording:(SentryReplayRecording *)replayRecording
video:(NSURL *)videoURL
withScope:(SentryScope *)scope
{
replayEvent = (SentryReplayEvent *)[self prepareEvent:replayEvent
withScope:scope
alwaysAttachStacktrace:NO];
if (replayEvent == nil) {
SENTRY_LOG_DEBUG(@"The replay event was filtered out in prepare event. "
@"The replay was discarded.");
return;
}
// Only check the type of the returned event, as the instance could be changed in the event
// preprocessor and before-send handlers.
if (![replayEvent isKindOfClass:SentryReplayEvent.class]) {
SENTRY_LOG_ERROR(@"The event preprocessor didn't update the replay event in place. The "
@"replay was discarded.");
return;
}
SentryEnvelopeItem *videoEnvelopeItem =
[[SentryEnvelopeItem alloc] initWithReplayEvent:replayEvent
replayRecording:replayRecording
video:videoURL];
if (videoEnvelopeItem == nil) {
SENTRY_LOG_ERROR(@"The Session Replay segment will not be sent to Sentry because an "
@"Envelope Item could not be created.");
// Record a counted lost event in case preparing the event (e.g. encoding the event) failed.
// This is used to determine if replay events are missing due to an error in the SDK.
[self recordLostEvent:kSentryDataCategoryReplay
reason:kSentryDiscardReasonInsufficientData
quantity:1];
return;
}
// Hybrid SDKs may override the sdk info for a replay Event,
// the same SDK should be used for the envelope header.
SentryEnvelopeHeader *envelopeHeader =
[[SentryEnvelopeHeader alloc] initWithId:replayEvent.eventId sdkInfo:replayEvent.sdk];
SentryEnvelope *envelope = [[SentryEnvelope alloc] initWithHeader:envelopeHeader
items:@[ videoEnvelopeItem ]];
[self captureEnvelope:envelope];
}
- (void)captureEnvelope:(SentryEnvelope *)envelope
{
if ([self isDisabled]) {
[self logDisabledMessage];
return;
}
[self.transportAdapter sendEnvelope:envelope];
}
- (void)captureFeedback:(SentryFeedback *)feedback withScope:(SentryScope *)scope
{
[self captureSerializedFeedback:[feedback serialize]
withEventId:feedback.eventId.sentryIdString
attachments:[feedback attachmentsForEnvelope]
scope:scope];
}
- (void)captureSerializedFeedback:(NSDictionary *)serializedFeedback
withEventId:(NSString *)feedbackEventId
attachments:(NSArray<SentryAttachment *> *)feedbackAttachments
scope:(SentryScope *)scope
{
if ([self isDisabled]) {
[self logDisabledMessage];
return;
}
SentryEvent *feedbackEvent = [[SentryEvent alloc] init];
feedbackEvent.eventId = [[SentryId alloc] initWithUUIDString:feedbackEventId];
feedbackEvent.type = SentryEnvelopeItemTypes.feedback;
NSUInteger optionalItems = (scope.span == nil ? 0 : 1) + (scope.replayId == nil ? 0 : 1);
NSMutableDictionary *context = [NSMutableDictionary dictionaryWithCapacity:1 + optionalItems];
context[@"feedback"] = serializedFeedback;
if (scope.replayId != nil) {
NSMutableDictionary *replayContext = [NSMutableDictionary dictionaryWithCapacity:1];
replayContext[@"replay_id"] = scope.replayId;
context[@"replay"] = replayContext;
}
feedbackEvent.context = context;
SentryEvent *preparedEvent = [self prepareEvent:feedbackEvent
withScope:scope
alwaysAttachStacktrace:NO];
SentryTraceContext *traceContext = [self getTraceStateWithEvent:preparedEvent withScope:scope];
NSArray<SentryAttachment *> *attachments = [[self processAttachmentsForEvent:preparedEvent
attachments:scope.attachments]
arrayByAddingObjectsFromArray:feedbackAttachments];
[self.transportAdapter sendEvent:preparedEvent
traceContext:traceContext
attachments:attachments
additionalEnvelopeItems:@[]];
}
- (void)storeEnvelope:(SentryEnvelope *)envelope
{
[self.fileManager storeEnvelope:envelope];
}
- (void)recordLostEvent:(SentryDataCategory)category reason:(SentryDiscardReason)reason
{
[self.transportAdapter recordLostEvent:category reason:reason];
}
- (void)recordLostEvent:(SentryDataCategory)category
reason:(SentryDiscardReason)reason
quantity:(NSUInteger)quantity
{
[self.transportAdapter recordLostEvent:category reason:reason quantity:quantity];
}
- (SentryEvent *_Nullable)prepareEvent:(SentryEvent *)event
withScope:(SentryScope *)scope
alwaysAttachStacktrace:(BOOL)alwaysAttachStacktrace
{
return [self prepareEvent:event
withScope:scope
alwaysAttachStacktrace:alwaysAttachStacktrace
isFatalEvent:NO];
}
- (void)flush:(NSTimeInterval)timeout
{
NSTimeInterval forwardingTelemetryDataDuration = [self.telemetryProcessor forwardTelemetryData];
// Calculate remaining timeout for transport flush.
// We subtract the time already spent capturing logs to respect the overall timeout.
// If log capture took longer than the timeout, we use 0.0 which will still trigger
// sending events but won't block waiting for completion.
NSTimeInterval remainingTimeout = fmax(0.0, timeout - forwardingTelemetryDataDuration);
[self.transportAdapter flush:remainingTimeout];
}
- (void)close
{
_isEnabled = NO;
[self flush:self.options.shutdownTimeInterval];
SENTRY_LOG_DEBUG(@"Closed the Client.");
}
- (SentryEvent *_Nullable)prepareEvent:(SentryEvent *_Nullable)event
withScope:(SentryScope *)scope
alwaysAttachStacktrace:(BOOL)alwaysAttachStacktrace
isFatalEvent:(BOOL)isFatalEvent
{
NSParameterAssert(event);
if (event == nil) {
return nil;
}
if ([self isDisabled]) {
[self logDisabledMessage];
return nil;
}
BOOL eventIsNotATransaction
= event.type == nil || ![event.type isEqualToString:SentryEnvelopeItemTypes.transaction];
BOOL eventIsNotReplay
= event.type == nil || ![event.type isEqualToString:SentryEnvelopeItemTypes.replayVideo];
BOOL eventIsNotUserFeedback
= event.type == nil || ![event.type isEqualToString:SentryEnvelopeItemTypes.feedback];
// Transactions and replays have their own sampleRate
if (eventIsNotATransaction && eventIsNotReplay && eventIsNotUserFeedback &&
[self isSampled:self.options.sampleRate]) {
SENTRY_LOG_DEBUG(@"Event got sampled, will not send the event");
[self recordLostEvent:kSentryDataCategoryError reason:kSentryDiscardReasonSampleRate];
return nil;
}
NSDictionary *infoDict = [[NSBundle mainBundle] infoDictionary];
if (nil != infoDict && nil == event.dist) {
event.dist = infoDict[@"CFBundleVersion"];
}
// Use the values from SentryOptions as a fallback,
// in case not yet set directly in the event nor in the scope:
NSString *releaseName = self.options.releaseName;
if (nil == event.releaseName && nil != releaseName) {
// If no release was already set (i.e: crashed on an older version) use
// current release name
event.releaseName = releaseName;
}
NSString *dist = self.options.dist;
if (nil != dist) {
event.dist = dist;
}
[self setSdk:SENTRY_UNWRAP_NULLABLE(SentryEvent, event)];
// We don't want to attach debug meta and stacktraces for transactions, replays or user
// feedback.
if (eventIsNotATransaction && eventIsNotReplay && eventIsNotUserFeedback) {
BOOL shouldAttachStacktrace = alwaysAttachStacktrace || self.options.attachStacktrace
|| (nil != event.exceptions && [event.exceptions count] > 0);
BOOL threadsNotAttached = !(nil != event.threads && event.threads.count > 0);
if (!isFatalEvent && shouldAttachStacktrace && threadsNotAttached) {
event.threads = [self.threadInspector getCurrentThreads];
}
BOOL debugMetaNotAttached = !(nil != event.debugMeta && event.debugMeta.count > 0);
if (!isFatalEvent && shouldAttachStacktrace && debugMetaNotAttached
&& event.threads != nil) {
event.debugMeta = [self.debugImageProvider
getDebugImagesFromCacheForThreads:SENTRY_UNWRAP_NULLABLE(
NSArray<SentryThread *>, event.threads)];
}
}
#if SENTRY_HAS_UIKIT
if (!isFatalEvent && eventIsNotReplay) {
NSDictionary *currentContext = event.context ?: @{ };
event.context = [self.eventContextEnricher enrichWithAppState:currentContext];
}
#endif
// Crash events are from a previous run. Applying the current scope would potentially apply
// current data.
if (!isFatalEvent) {
// Unwrapping the event because we assume that the event will be returned
event = SENTRY_UNWRAP_NULLABLE(
SentryEvent, [scope applyToEvent:event maxBreadcrumb:self.options.maxBreadcrumbs]);
}
if (!eventIsNotReplay) {
event.breadcrumbs = nil;
}
if ([self isWatchdogTermination:SENTRY_UNWRAP_NULLABLE(SentryEvent, event)
isFatalEvent:isFatalEvent]) {
// Remove some mutable properties from the device/app contexts which are no longer
// applicable
[self removeExtraDeviceContextFromEvent:SENTRY_UNWRAP_NULLABLE(SentryEvent, event)];
} else if (!isFatalEvent) {
// Store the current free memory battery level and more mutable properties,
// at the time of this event, but not for crashes as the current data isn't guaranteed to be
// the same as when the app crashed.
[self applyExtraDeviceContextToEvent:SENTRY_UNWRAP_NULLABLE(SentryEvent, event)];
[self applyCultureContextToEvent:SENTRY_UNWRAP_NULLABLE(SentryEvent, event)];
#if SENTRY_HAS_UIKIT
[self applyCurrentViewNamesToEventContext:SENTRY_UNWRAP_NULLABLE(SentryEvent, event)
withScope:scope];
#endif // SENTRY_HAS_UIKIT
}
// With scope applied, before running callbacks run:
if (event.environment == nil) {
// We default to environment 'production' if nothing was set
event.environment = self.options.environment;
}
// Need to do this after the scope is applied cause this sets the user if there is any
[self setUserIdIfNoUserSet:SENTRY_UNWRAP_NULLABLE(SentryEvent, event)];
BOOL eventIsATransaction
= event.type != nil && [event.type isEqualToString:SentryEnvelopeItemTypes.transaction];
BOOL eventIsATransactionClass
= eventIsATransaction && [event isKindOfClass:[SentryTransaction class]];
NSUInteger currentSpanCount;
if (eventIsATransactionClass) {
SentryTransaction *transaction = (SentryTransaction *)event;
currentSpanCount = transaction.spans.count;
} else {
currentSpanCount = 0;
}
if (event != nil && eventIsATransaction && self.options.beforeSendSpan != nil) {
SentryTransaction *transaction = (SentryTransaction *)event;
NSMutableArray<id<SentrySpan>> *processedSpans = [NSMutableArray array];
for (id<SentrySpan> span in transaction.spans) {
id<SentrySpan> processedSpan = self.options.beforeSendSpan(span);
if (processedSpan) {
[processedSpans addObject:processedSpan];
}
}
transaction.spans = processedSpans;
if (eventIsATransactionClass) {
[self recordPartiallyDroppedSpans:transaction
withReason:kSentryDiscardReasonBeforeSend
withCurrentSpanCount:¤tSpanCount];
}
}
if (eventIsNotUserFeedback && event != nil && nil != self.options.beforeSend) {
event = self.options.beforeSend(SENTRY_UNWRAP_NULLABLE(SentryEvent, event));
if (event == nil) {
[self recordLost:eventIsNotATransaction reason:kSentryDiscardReasonBeforeSend];
if (eventIsATransaction) {
// We dropped the whole transaction, the dropped count includes all child spans + 1
// root span
[self recordLostSpanWithReason:kSentryDiscardReasonBeforeSend
quantity:currentSpanCount + 1];
}
} else {
if (eventIsATransactionClass) {
[self recordPartiallyDroppedSpans:(SentryTransaction *)event
withReason:kSentryDiscardReasonBeforeSend
withCurrentSpanCount:¤tSpanCount];
}
}
}
if (event != nil) {
// if the event is dropped by beforeSend we should not execute event processors as they
// might trigger e.g. unnecessary replay capture
event = [self callEventProcessors:SENTRY_UNWRAP_NULLABLE(SentryEvent, event)];
if (event == nil) {
[self recordLost:eventIsNotATransaction reason:kSentryDiscardReasonEventProcessor];
if (eventIsATransaction) {
// We dropped the whole transaction, the dropped count includes all child spans + 1
// root span
[self recordLostSpanWithReason:kSentryDiscardReasonEventProcessor
quantity:currentSpanCount + 1];
}
} else {
if (eventIsATransactionClass) {
[self recordPartiallyDroppedSpans:(SentryTransaction *)event
withReason:kSentryDiscardReasonEventProcessor
withCurrentSpanCount:¤tSpanCount];
}
}
}
if (event != nil && isFatalEvent && nil != self.options.onCrashedLastRun
&& !SentrySDKInternal.crashedLastRunCalled) {
// We only want to call the callback once. It can occur that multiple crash events are
// about to be sent.
SentrySDKInternal.crashedLastRunCalled = YES;
self.options.onCrashedLastRun(SENTRY_UNWRAP_NULLABLE(SentryEvent, event));
}
return event;
}
- (void)recordPartiallyDroppedSpans:(SentryTransaction *)transaction
withReason:(SentryDiscardReason)reason
withCurrentSpanCount:(NSUInteger *)currentSpanCount
{
// If some spans got removed we still report them as dropped
NSUInteger spanCountAfter = transaction.spans.count;
NSUInteger droppedSpanCount = *currentSpanCount - spanCountAfter;
if (droppedSpanCount > 0) {
[self recordLostSpanWithReason:reason quantity:droppedSpanCount];
}
*currentSpanCount = spanCountAfter;
}
- (BOOL)isSampled:(NSNumber *_Nullable)sampleRate
{
if (sampleRate == nil) {
return NO;
}
return [self.random nextNumber] <= sampleRate.doubleValue ? NO : YES;
}
- (BOOL)isDisabled
{
return !_isEnabled || !self.options.enabled || nil == self.options.parsedDsn;
}
- (void)logDisabledMessage
{
SENTRY_LOG_DEBUG(@"SDK disabled or no DSN set. Won't do anyting.");
}
- (SentryEvent *_Nullable)callEventProcessors:(SentryEvent *)event
{
SentryGlobalEventProcessor *globalEventProcessor
= SentryDependencyContainer.sharedInstance.globalEventProcessor;
SentryEvent *newEvent = [globalEventProcessor reportAll:event];
if (newEvent == nil) {
SENTRY_LOG_DEBUG(@"SentryScope callEventProcessors: An event processor decided to "
@"remove this event.");
}
return newEvent;
}
- (void)setSdk:(SentryEvent *)event
{
if (event.sdk) {
return;
}
event.sdk = [SentrySdkInfoObjC optionsToDict:self.options];
}
- (void)setUserInfo:(NSDictionary *_Nullable)userInfo withEvent:(SentryEvent *_Nullable)event
{
if (nil != event && nil != userInfo && userInfo.count > 0) {
NSMutableDictionary *context;
if (event.context == nil) {
context = [[NSMutableDictionary alloc] init];
event.context = context;
} else {
context = [event.context mutableCopy];
}
[context setValue:sentry_sanitize(userInfo) forKey:@"user info"];
}
}
- (void)setUserIdIfNoUserSet:(SentryEvent *)event
{
// We only want to set the id if the customer didn't set a user so we at least set something to
// identify the user.
if (event.user == nil) {
SentryUser *user = [[SentryUser alloc] init];
user.userId = [SentryInstallation idWithCacheDirectoryPath:self.options.cacheDirectoryPath];
event.user = user;
}
}
- (BOOL)isWatchdogTermination:(SentryEvent *)event isFatalEvent:(BOOL)isFatalEvent
{
if (!isFatalEvent) {
return NO;
}
if (event.exceptions == nil || event.exceptions.count != 1) {
return NO;
}
SentryException *exception = event.exceptions[0];
return exception.mechanism != nil &&
[exception.mechanism.type isEqualToString:SentryWatchdogTerminationConstants.MechanismType];
}
- (void)applyCultureContextToEvent:(SentryEvent *)event
{
[self modifyContext:event
key:@"culture"
block:^(NSMutableDictionary *culture) {
culture[@"calendar"] = [self.locale
localizedStringForCalendarIdentifier:self.locale.calendarIdentifier];
culture[@"display_name"] = [self.locale
localizedStringForLocaleIdentifier:self.locale.localeIdentifier];
culture[@"locale"] = self.locale.localeIdentifier;
culture[@"is_24_hour_format"] = @([SentryLocale timeIs24HourFormat]);
culture[@"timezone"] = self.timezone.name;
}];
}
- (void)applyExtraDeviceContextToEvent:(SentryEvent *)event
{
NSDictionary *extraContext =
[SentryDependencyContainer.sharedInstance.extraContextProvider getExtraContext];
[self modifyContext:event
key:SENTRY_CONTEXT_DEVICE_KEY
block:^(NSMutableDictionary *device) {
if (extraContext[SENTRY_CONTEXT_DEVICE_KEY] != nil &&
[extraContext[SENTRY_CONTEXT_DEVICE_KEY]
isKindOfClass:NSDictionary.class]) {
[device addEntriesFromDictionary:extraContext[SENTRY_CONTEXT_DEVICE_KEY]
?: @ { }];
}
}];
[self modifyContext:event
key:SENTRY_CONTEXT_APP_KEY
block:^(NSMutableDictionary *app) {
if (extraContext[SENTRY_CONTEXT_APP_KEY] != nil &&
[extraContext[SENTRY_CONTEXT_APP_KEY] isKindOfClass:NSDictionary.class]) {
[app addEntriesFromDictionary:extraContext[SENTRY_CONTEXT_APP_KEY]
?: @ { }];
}
}];
}
#if SENTRY_HAS_UIKIT
- (void)applyCurrentViewNamesToEventContext:(SentryEvent *)event withScope:(SentryScope *)scope
{
[self modifyContext:event
key:@"app"
block:^(NSMutableDictionary *app) {
if ([event isKindOfClass:[SentryTransaction class]]) {
SentryTransaction *transaction = (SentryTransaction *)event;