-
-
Notifications
You must be signed in to change notification settings - Fork 318
/
SentryTracer.m
849 lines (722 loc) · 27.9 KB
/
SentryTracer.m
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
#import "NSDictionary+SentrySanitize.h"
#import "PrivateSentrySDKOnly.h"
#import "SentryClient.h"
#import "SentryCurrentDateProvider.h"
#import "SentryDebugImageProvider.h"
#import "SentryDependencyContainer.h"
#import "SentryEvent+Private.h"
#import "SentryHub+Private.h"
#import "SentryLog.h"
#import "SentryNSTimerFactory.h"
#import "SentryNoOpSpan.h"
#import "SentryProfilingConditionals.h"
#import "SentrySDK+Private.h"
#import "SentryScope.h"
#import "SentrySpan.h"
#import "SentrySpanContext+Private.h"
#import "SentrySpanContext.h"
#import "SentrySpanId.h"
#import "SentryThreadWrapper.h"
#import "SentryTime.h"
#import "SentryTraceContext.h"
#import "SentryTraceOrigins.h"
#import "SentryTracer+Private.h"
#import "SentryTransaction.h"
#import "SentryTransactionContext.h"
#import "SentryUIApplication.h"
#import <NSMutableDictionary+Sentry.h>
#import <SentryDispatchQueueWrapper.h>
#import <SentryMeasurementValue.h>
#import <SentrySpanOperations.h>
@import SentryPrivate;
#if SENTRY_TARGET_PROFILING_SUPPORTED
# import "SentryProfiledTracerConcurrency.h"
# import "SentryProfiler.h"
# import "SentryProfilesSampler.h"
#endif // SENTRY_TARGET_PROFILING_SUPPORTED
#if SENTRY_HAS_UIKIT
# import "SentryAppStartMeasurement.h"
# import "SentryBuildAppStartSpans.h"
# import "SentryFramesTracker.h"
# import "SentryUIViewControllerPerformanceTracker.h"
# import <SentryScreenFrames.h>
#endif // SENTRY_HAS_UIKIT
NS_ASSUME_NONNULL_BEGIN
static const void *spanTimestampObserver = &spanTimestampObserver;
#if SENTRY_HAS_UIKIT
/**
* The maximum amount of seconds the app start measurement end time and the start time of the
* transaction are allowed to be apart.
*/
static const NSTimeInterval SENTRY_APP_START_MEASUREMENT_DIFFERENCE = 5.0;
#endif // SENTRY_HAS_UIKIT
static const NSTimeInterval SENTRY_AUTO_TRANSACTION_DEADLINE = 30.0;
@interface
SentryTracer ()
@property (nonatomic) uint64_t startSystemTime;
@property (nonatomic) SentrySpanStatus finishStatus;
/** This property is different from @c isFinished. While @c isFinished states if the tracer is
* actually finished, this property tells you if finish was called on the tracer. Calling
* @c -[finish] doesn't necessarily lead to finishing the tracer, because it could still wait for
* child spans to finish if @c waitForChildren is @c YES . */
@property (nonatomic) BOOL wasFinishCalled;
@property (nonatomic, nullable, strong) NSTimer *deadlineTimer;
@property (nonnull, strong) SentryTracerConfiguration *configuration;
@property (nonatomic, strong) SentryDispatchQueueWrapper *dispatchQueue;
@property (nonatomic, strong) SentryDebugImageProvider *debugImageProvider;
#if SENTRY_TARGET_PROFILING_SUPPORTED
@property (nonatomic) BOOL isProfiling;
#endif // SENTRY_TARGET_PROFILING_SUPPORTED
@end
@implementation SentryTracer {
/** Wether the tracer should wait for child spans to finish before finishing itself. */
SentryTraceContext *_traceContext;
#if SENTRY_HAS_UIKIT
SentryAppStartMeasurement *appStartMeasurement;
#endif // SENTRY_HAS_UIKIT
NSMutableDictionary<NSString *, SentryMeasurementValue *> *_measurements;
dispatch_block_t _idleTimeoutBlock;
NSMutableArray<id<SentrySpan>> *_children;
BOOL _startTimeChanged;
NSDate *_originalStartTimestamp;
NSObject *_idleTimeoutLock;
#if SENTRY_HAS_UIKIT
NSUInteger initTotalFrames;
NSUInteger initSlowFrames;
NSUInteger initFrozenFrames;
NSArray<NSString *> *viewNames;
#endif // SENTRY_HAS_UIKIT
}
static NSObject *appStartMeasurementLock;
static BOOL appStartMeasurementRead;
+ (void)initialize
{
if (self == [SentryTracer class]) {
appStartMeasurementLock = [[NSObject alloc] init];
appStartMeasurementRead = NO;
}
}
- (instancetype)initWithTransactionContext:(SentryTransactionContext *)transactionContext
hub:(nullable SentryHub *)hub
{
return [self initWithTransactionContext:transactionContext
hub:hub
configuration:SentryTracerConfiguration.defaultConfiguration];
}
- (instancetype)initWithTransactionContext:(SentryTransactionContext *)transactionContext
hub:(nullable SentryHub *)hub
configuration:(SentryTracerConfiguration *)configuration;
{
if (!(self = [super initWithContext:transactionContext
#if SENTRY_HAS_UIKIT
framesTracker:SentryDependencyContainer.sharedInstance.framesTracker
#endif // SENTRY_HAS_UIKIT
])) {
return nil;
}
_startSystemTime = SentryDependencyContainer.sharedInstance.dateProvider.systemTime;
_configuration = configuration;
_dispatchQueue = SentryDependencyContainer.sharedInstance.dispatchQueueWrapper;
_debugImageProvider = SentryDependencyContainer.sharedInstance.debugImageProvider;
self.transactionContext = transactionContext;
_children = [[NSMutableArray alloc] init];
self.hub = hub;
self.wasFinishCalled = NO;
_measurements = [[NSMutableDictionary alloc] init];
self.finishStatus = kSentrySpanStatusUndefined;
if (_configuration.timerFactory == nil) {
_configuration.timerFactory = [[SentryNSTimerFactory alloc] init];
}
#if SENTRY_HAS_UIKIT
viewNames = [SentryDependencyContainer.sharedInstance.application relevantViewControllersNames];
#endif // SENTRY_HAS_UIKIT
_idleTimeoutLock = [[NSObject alloc] init];
if ([self hasIdleTimeout]) {
[self dispatchIdleTimeout];
}
if ([self isAutoGeneratedTransaction]) {
[self startDeadlineTimer];
}
#if SENTRY_HAS_UIKIT
// Store current amount of frames at the beginning to be able to calculate the amount of
// frames at the end of the transaction.
SentryFramesTracker *framesTracker = SentryDependencyContainer.sharedInstance.framesTracker;
if (framesTracker.isRunning) {
SentryScreenFrames *currentFrames = framesTracker.currentFrames;
initTotalFrames = currentFrames.total;
initSlowFrames = currentFrames.slow;
initFrozenFrames = currentFrames.frozen;
}
#endif // SENTRY_HAS_UIKIT
#if SENTRY_TARGET_PROFILING_SUPPORTED
if (_configuration.profilesSamplerDecision.decision == kSentrySampleDecisionYes) {
_internalID = [[SentryId alloc] init];
_isProfiling = [SentryProfiler startWithTracer:_internalID];
}
#endif // SENTRY_TARGET_PROFILING_SUPPORTED
return self;
}
- (void)dealloc
{
#if SENTRY_TARGET_PROFILING_SUPPORTED
if (self.isProfiling) {
discardProfilerForTracer(self.internalID);
}
#endif // SENTRY_TARGET_PROFILING_SUPPORTED
}
- (nullable SentryTracer *)tracer
{
return self;
}
- (void)dispatchIdleTimeout
{
@synchronized(_idleTimeoutLock) {
if (_idleTimeoutBlock != NULL) {
[_dispatchQueue dispatchCancel:_idleTimeoutBlock];
}
__weak SentryTracer *weakSelf = self;
_idleTimeoutBlock = [_dispatchQueue createDispatchBlock:^{
if (weakSelf == nil) {
SENTRY_LOG_DEBUG(@"WeakSelf is nil. Not doing anything.");
return;
}
[weakSelf finishInternal];
}];
if (_idleTimeoutBlock == NULL) {
SENTRY_LOG_WARN(@"Couldn't create idle time out block. Can't schedule idle timeout. "
@"Finishing transaction");
// If the transaction has no children, the SDK will discard it.
[self finishInternal];
} else {
[_dispatchQueue dispatchAfter:_configuration.idleTimeout block:_idleTimeoutBlock];
}
}
}
- (BOOL)hasIdleTimeout
{
return _configuration.idleTimeout > 0;
}
- (BOOL)isAutoGeneratedTransaction
{
return _configuration.waitForChildren || [self hasIdleTimeout];
}
- (void)cancelIdleTimeout
{
@synchronized(_idleTimeoutLock) {
if ([self hasIdleTimeout]) {
[SentryDependencyContainer.sharedInstance.dispatchQueueWrapper
dispatchCancel:_idleTimeoutBlock];
}
}
}
- (void)startDeadlineTimer
{
__weak SentryTracer *weakSelf = self;
[_dispatchQueue dispatchOnMainQueue:^{
weakSelf.deadlineTimer = [weakSelf.configuration.timerFactory
scheduledTimerWithTimeInterval:SENTRY_AUTO_TRANSACTION_DEADLINE
repeats:NO
block:^(NSTimer *_Nonnull timer) {
if (weakSelf == nil) {
SENTRY_LOG_DEBUG(@"WeakSelf is nil. Not calling "
@"deadlineTimerFired.");
return;
}
[weakSelf deadlineTimerFired];
}];
}];
}
- (void)deadlineTimerFired
{
SENTRY_LOG_DEBUG(@"Sentry tracer deadline fired");
@synchronized(self) {
// This try to minimize a race condition with a proper call to `finishInternal`.
if (self.isFinished) {
return;
}
}
@synchronized(_children) {
for (id<SentrySpan> span in _children) {
if (![span isFinished])
[span finishWithStatus:kSentrySpanStatusDeadlineExceeded];
}
}
[self finishWithStatus:kSentrySpanStatusDeadlineExceeded];
}
- (void)cancelDeadlineTimer
{
// If the main thread is busy the tracer could be deallocated in between.
__weak SentryTracer *weakSelf = self;
// The timer must be invalidated from the thread on which the timer was installed, see
// https://developer.apple.com/documentation/foundation/nstimer/1415405-invalidate#1770468
[_dispatchQueue dispatchOnMainQueue:^{
if (weakSelf == nil) {
SENTRY_LOG_DEBUG(@"WeakSelf is nil. Not invalidating deadlineTimer.");
return;
}
[weakSelf.deadlineTimer invalidate];
weakSelf.deadlineTimer = nil;
}];
}
- (id<SentrySpan>)getActiveSpan
{
id<SentrySpan> span;
if (self.delegate) {
@synchronized(_children) {
span = [self.delegate activeSpanForTracer:self];
if (span == nil || ![_children containsObject:span]) {
span = self;
}
}
} else {
span = self;
}
return span;
}
- (id<SentrySpan>)startChildWithOperation:(NSString *)operation
{
id<SentrySpan> activeSpan = [self getActiveSpan];
if (activeSpan == self) {
return [self startChildWithParentId:self.spanId operation:operation description:nil];
}
return [activeSpan startChildWithOperation:operation];
}
- (id<SentrySpan>)startChildWithOperation:(NSString *)operation
description:(nullable NSString *)description
{
id<SentrySpan> activeSpan = [self getActiveSpan];
if (activeSpan == self) {
return [self startChildWithParentId:self.spanId
operation:operation
description:description];
}
return [activeSpan startChildWithOperation:operation description:description];
}
- (id<SentrySpan>)startChildWithParentId:(SentrySpanId *)parentId
operation:(NSString *)operation
description:(nullable NSString *)description
{
[self cancelIdleTimeout];
if (self.isFinished) {
SENTRY_LOG_WARN(
@"Starting a child on a finished span is not supported; it won't be sent to Sentry.");
return [SentryNoOpSpan shared];
}
SentrySpanContext *context =
[[SentrySpanContext alloc] initWithTraceId:self.traceId
spanId:[[SentrySpanId alloc] init]
parentId:parentId
operation:operation
spanDescription:description
sampled:self.sampled];
SentrySpan *child =
[[SentrySpan alloc] initWithTracer:self
context:context
#if SENTRY_HAS_UIKIT
framesTracker:SentryDependencyContainer.sharedInstance.framesTracker
#endif // SENTRY_HAS_UIKIT
];
child.startTimestamp = [SentryDependencyContainer.sharedInstance.dateProvider date];
SENTRY_LOG_DEBUG(@"Started child span %@ under %@", child.spanId.sentrySpanIdString,
parentId.sentrySpanIdString);
@synchronized(_children) {
[_children addObject:child];
}
return child;
}
- (void)spanFinished:(id<SentrySpan>)finishedSpan
{
SENTRY_LOG_DEBUG(@"Finished span %@", finishedSpan.spanId.sentrySpanIdString);
// Calling canBeFinished on self would end up in an endless loop because canBeFinished
// calls finish again.
if (finishedSpan == self) {
SENTRY_LOG_DEBUG(
@"Cannot call finish on span with id %@", finishedSpan.spanId.sentrySpanIdString);
return;
}
[self canBeFinished];
}
- (SentryTraceContext *)traceContext
{
if (_traceContext == nil) {
@synchronized(self) {
if (_traceContext == nil) {
_traceContext = [[SentryTraceContext alloc] initWithTracer:self
scope:_hub.scope
options:SentrySDK.options];
}
}
}
return _traceContext;
}
- (NSArray<id<SentrySpan>> *)children
{
return [_children copy];
}
- (void)setMeasurement:(NSString *)name value:(NSNumber *)value
{
SentryMeasurementValue *measurement = [[SentryMeasurementValue alloc] initWithValue:value];
_measurements[name] = measurement;
}
- (void)setMeasurement:(NSString *)name value:(NSNumber *)value unit:(SentryMeasurementUnit *)unit
{
SentryMeasurementValue *measurement = [[SentryMeasurementValue alloc] initWithValue:value
unit:unit];
_measurements[name] = measurement;
}
- (void)finish
{
[self finishWithStatus:kSentrySpanStatusOk];
}
- (void)finishWithStatus:(SentrySpanStatus)status
{
SENTRY_LOG_DEBUG(@"Finished trace with traceID: %@ and status: %@",
self.internalID.sentryIdString, nameForSentrySpanStatus(status));
@synchronized(self) {
self.wasFinishCalled = YES;
}
_finishStatus = status;
[self canBeFinished];
}
- (void)canBeFinished
{
// Transaction already finished and captured.
// Sending another transaction and spans with
// the same SentryId would be an error.
if (self.isFinished) {
SENTRY_LOG_DEBUG(@"Span with id %@ is already finished", self.spanId.sentrySpanIdString);
return;
}
BOOL hasUnfinishedChildSpansToWaitFor = [self hasUnfinishedChildSpansToWaitFor];
@synchronized(self) {
if (!self.wasFinishCalled && !hasUnfinishedChildSpansToWaitFor && [self hasIdleTimeout]) {
SENTRY_LOG_DEBUG(
@"Span with id %@ isn't waiting on children and needs idle timeout dispatched.",
self.spanId.sentrySpanIdString);
[self dispatchIdleTimeout];
return;
}
if (!self.wasFinishCalled || hasUnfinishedChildSpansToWaitFor) {
SENTRY_LOG_DEBUG(
@"Span with id %@ has children but hasn't finished yet so isn't waiting "
@"for them right now.",
self.spanId.sentrySpanIdString);
return;
}
}
[self finishInternal];
}
- (BOOL)hasUnfinishedChildSpansToWaitFor
{
if (!self.configuration.waitForChildren) {
return NO;
}
@synchronized(_children) {
for (id<SentrySpan> span in _children) {
if (self.shouldIgnoreWaitForChildrenCallback != nil
&& self.shouldIgnoreWaitForChildrenCallback(span)) {
continue;
}
if (![span isFinished])
return YES;
}
return NO;
}
}
- (void)finishInternal
{
[self cancelDeadlineTimer];
if (self.isFinished) {
return;
}
@synchronized(self) {
if (self.isFinished) {
return;
}
// Keep existing status of auto generated transactions if set by the user.
if ([self isAutoGeneratedTransaction] && !self.wasFinishCalled
&& self.status != kSentrySpanStatusUndefined) {
_finishStatus = self.status;
}
[super finishWithStatus:_finishStatus];
}
#if SENTRY_HAS_UIKIT
appStartMeasurement = [self getAppStartMeasurement];
if (appStartMeasurement != nil) {
[self updateStartTime:appStartMeasurement.appStartTimestamp];
}
#endif // SENTRY_HAS_UIKIT
[self.delegate tracerDidFinish:self];
if (self.finishCallback) {
self.finishCallback(self);
// The callback will only be executed once. No need to keep the reference and we avoid
// potential retain cycles.
self.finishCallback = nil;
}
if (self.shouldIgnoreWaitForChildrenCallback) {
self.shouldIgnoreWaitForChildrenCallback = nil;
}
// Prewarming can execute code up to viewDidLoad of a UIViewController, and keep the app in the
// background. This can lead to auto-generated transactions lasting for minutes or even hours.
// Therefore, we drop transactions lasting longer than SENTRY_AUTO_TRANSACTION_MAX_DURATION.
NSTimeInterval transactionDuration = [self.timestamp timeIntervalSinceDate:self.startTimestamp];
if ([self isAutoGeneratedTransaction]
&& transactionDuration >= SENTRY_AUTO_TRANSACTION_MAX_DURATION) {
SENTRY_LOG_INFO(@"Auto generated transaction exceeded the max duration of %f seconds. Not "
@"capturing transaction.",
SENTRY_AUTO_TRANSACTION_MAX_DURATION);
return;
}
if (_hub == nil) {
return;
}
[_hub.scope useSpan:^(id<SentrySpan> _Nullable span) {
if (span == self) {
[self->_hub.scope setSpan:nil];
}
}];
@synchronized(_children) {
if (_configuration.idleTimeout > 0.0 && _children.count == 0) {
SENTRY_LOG_DEBUG(@"Was waiting for timeout for UI event trace but it had no children, "
@"will not keep transaction.");
return;
}
for (id<SentrySpan> span in _children) {
if (!span.isFinished) {
[span finishWithStatus:kSentrySpanStatusDeadlineExceeded];
// Unfinished children should have the same
// end timestamp as their parent transaction
span.timestamp = self.timestamp;
}
}
if ([self isAutoGeneratedTransaction]) {
[self trimEndTimestamp];
}
}
SentryTransaction *transaction = [self toTransaction];
#if SENTRY_TARGET_PROFILING_SUPPORTED
if (self.isProfiling) {
[self captureTransactionWithProfile:transaction];
return;
}
#endif // SENTRY_TARGET_PROFILING_SUPPORTED
[_hub captureTransaction:transaction withScope:_hub.scope];
}
#if SENTRY_TARGET_PROFILING_SUPPORTED
- (void)captureTransactionWithProfile:(SentryTransaction *)transaction
{
SentryEnvelopeItem *profileEnvelopeItem =
[SentryProfiler createProfilingEnvelopeItemForTransaction:transaction];
if (!profileEnvelopeItem) {
[_hub captureTransaction:transaction withScope:_hub.scope];
return;
}
SENTRY_LOG_DEBUG(@"Capturing transaction with profiling data attached for tracer id %@.",
self.internalID.sentryIdString);
[_hub captureTransaction:transaction
withScope:_hub.scope
additionalEnvelopeItems:@[ profileEnvelopeItem ]];
}
#endif // SENTRY_TARGET_PROFILING_SUPPORTED
- (void)trimEndTimestamp
{
NSDate *oldest = self.startTimestamp;
@synchronized(_children) {
for (id<SentrySpan> childSpan in _children) {
if ([oldest compare:childSpan.timestamp] == NSOrderedAscending) {
oldest = childSpan.timestamp;
}
}
}
if (oldest) {
self.timestamp = oldest;
}
}
- (void)updateStartTime:(NSDate *)startTime
{
_originalStartTimestamp = self.startTimestamp;
super.startTimestamp = startTime;
_startTimeChanged = YES;
}
- (SentryTransaction *)toTransaction
{
NSUInteger capacity;
#if SENTRY_HAS_UIKIT
[self addFrameStatistics];
NSArray<id<SentrySpan>> *appStartSpans = sentryBuildAppStartSpans(self, appStartMeasurement);
capacity = _children.count + appStartSpans.count;
#else
capacity = _children.count;
#endif // SENTRY_HAS_UIKIT
NSMutableArray<id<SentrySpan>> *spans = [[NSMutableArray alloc] initWithCapacity:capacity];
@synchronized(_children) {
[spans addObjectsFromArray:_children];
}
#if SENTRY_HAS_UIKIT
[spans addObjectsFromArray:appStartSpans];
#endif // SENTRY_HAS_UIKIT
SentryTransaction *transaction = [[SentryTransaction alloc] initWithTrace:self children:spans];
transaction.transaction = self.transactionContext.name;
#if SENTRY_TARGET_PROFILING_SUPPORTED
transaction.startSystemTime = self.startSystemTime;
if (self.isProfiling) {
[SentryProfiler recordMetrics];
}
transaction.endSystemTime = SentryDependencyContainer.sharedInstance.dateProvider.systemTime;
#endif // SENTRY_TARGET_PROFILING_SUPPORTED
NSMutableArray *framesOfAllSpans = [NSMutableArray array];
if ([(SentrySpan *)self frames]) {
[framesOfAllSpans addObjectsFromArray:[(SentrySpan *)self frames]];
}
for (SentrySpan *span in spans) {
if (span.frames) {
[framesOfAllSpans addObjectsFromArray:span.frames];
}
}
if (framesOfAllSpans.count > 0) {
SentryDebugImageProvider *debugImageProvider
= SentryDependencyContainer.sharedInstance.debugImageProvider;
transaction.debugMeta = [debugImageProvider getDebugImagesForFrames:framesOfAllSpans
isCrash:NO];
}
#if SENTRY_HAS_UIKIT
[self addAppStartMeasurements:transaction];
if ([viewNames count] > 0) {
transaction.viewNames = viewNames;
}
#endif // SENTRY_HAS_UIKIT
return transaction;
}
#if SENTRY_HAS_UIKIT
- (nullable SentryAppStartMeasurement *)getAppStartMeasurement
{
// Only send app start measurement for transactions generated by auto performance
// instrumentation.
if (![self.operation isEqualToString:SentrySpanOperationUILoad]) {
SENTRY_LOG_DEBUG(
@"Not returning app start measurements because it's not a ui.load operation.");
return nil;
}
// Hybrid SDKs send the app start measurement themselves.
if (PrivateSentrySDKOnly.appStartMeasurementHybridSDKMode) {
SENTRY_LOG_DEBUG(@"Not returning app start measurements because hybrid SDK will do it in "
@"its own routine.");
return nil;
}
// Double-Checked Locking to avoid acquiring unnecessary locks.
if (appStartMeasurementRead == YES) {
SENTRY_LOG_DEBUG(@"Not returning app start measurements because it was already reported.");
return nil;
}
SentryAppStartMeasurement *measurement = nil;
@synchronized(appStartMeasurementLock) {
if (appStartMeasurementRead == YES) {
SENTRY_LOG_DEBUG(@"Not returning app start measurements because it was already "
@"reported concurrently.");
return nil;
}
measurement = [SentrySDK getAppStartMeasurement];
if (measurement == nil) {
SENTRY_LOG_DEBUG(@"No app start measurement available.");
return nil;
}
appStartMeasurementRead = YES;
}
NSDate *appStartTimestamp = measurement.appStartTimestamp;
NSDate *appStartEndTimestamp =
[appStartTimestamp dateByAddingTimeInterval:measurement.duration];
NSTimeInterval difference = [appStartEndTimestamp timeIntervalSinceDate:self.startTimestamp];
// Don't attach app start measurements if too much time elapsed between the end of the app start
// sequence and the start of the transaction. This makes transactions too long.
if (difference > SENTRY_APP_START_MEASUREMENT_DIFFERENCE
|| difference < -SENTRY_APP_START_MEASUREMENT_DIFFERENCE) {
SENTRY_LOG_DEBUG(@"Not returning app start measurements because too much time elapsed.");
return nil;
}
SENTRY_LOG_DEBUG(
@"Returning app start measurements for trace id %@", self.internalID.sentryIdString);
return measurement;
}
- (void)addAppStartMeasurements:(SentryTransaction *)transaction
{
if (appStartMeasurement != nil && appStartMeasurement.type != SentryAppStartTypeUnknown) {
NSString *type = nil;
NSString *appContextType = nil;
if (appStartMeasurement.type == SentryAppStartTypeCold) {
type = @"app_start_cold";
appContextType = @"cold";
} else if (appStartMeasurement.type == SentryAppStartTypeWarm) {
type = @"app_start_warm";
appContextType = @"warm";
}
if (type != nil && appContextType != nil) {
[self setMeasurement:type value:@(appStartMeasurement.duration * 1000)];
NSString *appStartType = appStartMeasurement.isPreWarmed
? [NSString stringWithFormat:@"%@.prewarmed", appContextType]
: appContextType;
NSMutableDictionary *context =
[[NSMutableDictionary alloc] initWithDictionary:[transaction context]];
NSDictionary *appContext = @{ @"app" : @ { @"start_type" : appStartType } };
[context mergeEntriesFromDictionary:appContext];
[transaction setContext:context];
// The backend calculates statistics on the number and size of debug images for app
// start transactions. Therefore, we add all debug images here.
transaction.debugMeta = [self.debugImageProvider getDebugImagesCrashed:NO];
}
}
}
- (void)addFrameStatistics
{
SentryFramesTracker *framesTracker = SentryDependencyContainer.sharedInstance.framesTracker;
if (framesTracker.isRunning) {
CFTimeInterval framesDelay = [framesTracker
getFramesDelay:self.startSystemTime
endSystemTimestamp:SentryDependencyContainer.sharedInstance.dateProvider.systemTime];
if (framesDelay >= 0) {
[self setDataValue:@(framesDelay) forKey:@"frames.delay"];
SENTRY_LOG_DEBUG(@"Frames Delay:%f ms", framesDelay * 1000);
}
if (!_startTimeChanged) {
SentryScreenFrames *currentFrames = framesTracker.currentFrames;
NSInteger totalFrames = currentFrames.total - initTotalFrames;
NSInteger slowFrames = currentFrames.slow - initSlowFrames;
NSInteger frozenFrames = currentFrames.frozen - initFrozenFrames;
if (sentryShouldAddSlowFrozenFramesData(totalFrames, slowFrames, frozenFrames)) {
[self setMeasurement:@"frames_total" value:@(totalFrames)];
[self setMeasurement:@"frames_slow" value:@(slowFrames)];
[self setMeasurement:@"frames_frozen" value:@(frozenFrames)];
SENTRY_LOG_DEBUG(@"Frames for transaction \"%@\" Total:%ld Slow:%ld "
@"Frozen:%ld",
self.operation, (long)totalFrames, (long)slowFrames, (long)frozenFrames);
}
}
}
}
#endif // SENTRY_HAS_UIKIT
/**
* Internal. Only needed for testing.
*/
+ (void)resetAppStartMeasurementRead
{
@synchronized(appStartMeasurementLock) {
appStartMeasurementRead = NO;
}
}
+ (nullable SentryTracer *)getTracer:(id<SentrySpan>)span
{
if (span == nil) {
return nil;
}
if ([span isKindOfClass:[SentryTracer class]]) {
return span;
} else if ([span isKindOfClass:[SentrySpan class]]) {
return [(SentrySpan *)span tracer];
}
return nil;
}
- (NSDate *)originalStartTimestamp
{
return _startTimeChanged ? _originalStartTimestamp : self.startTimestamp;
}
@end
NS_ASSUME_NONNULL_END