-
-
Notifications
You must be signed in to change notification settings - Fork 330
/
SentryTracer.m
820 lines (695 loc) · 27.5 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
#import "SentryTracer.h"
#import "NSDictionary+SentrySanitize.h"
#import "PrivateSentrySDKOnly.h"
#import "SentryAppStartMeasurement.h"
#import "SentryClient.h"
#import "SentryCurrentDate.h"
#import "SentryDebugImageProvider.h"
#import "SentryDependencyContainer.h"
#import "SentryEvent+Private.h"
#import "SentryFramesTracker.h"
#import "SentryHub+Private.h"
#import "SentryLog.h"
#import "SentryNSTimerFactory.h"
#import "SentryNoOpSpan.h"
#import "SentryProfiler.h"
#import "SentryProfilesSampler.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 "SentryTime.h"
#import "SentryTraceContext.h"
#import "SentryTraceOrigins.h"
#import "SentryTracerConcurrency.h"
#import "SentryTransaction.h"
#import "SentryTransactionContext.h"
#import "SentryUIViewControllerPerformanceTracker.h"
#import <NSMutableDictionary+Sentry.h>
#import <SentryDispatchQueueWrapper.h>
#import <SentryMeasurementValue.h>
#import <SentryScreenFrames.h>
#import <SentrySpanOperations.h>
NS_ASSUME_NONNULL_BEGIN
static const void *spanTimestampObserver = &spanTimestampObserver;
/**
* 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;
static const NSTimeInterval SENTRY_AUTO_TRANSACTION_MAX_DURATION = 500.0;
static const NSTimeInterval SENTRY_AUTO_TRANSACTION_DEADLINE = 30.0;
@interface
SentryTracer ()
@property (nonatomic, strong) SentryHub *hub;
@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;
#if SENTRY_TARGET_PROFILING_SUPPORTED
@property (nonatomic) BOOL isProfiling;
@property (nonatomic) uint64_t startSystemTime;
#endif // SENTRY_TARGET_PROFILING_SUPPORTED
@end
@implementation SentryTracer {
/** Wether the tracer should wait for child spans to finish before finishing itself. */
SentryTraceContext *_traceContext;
SentryAppStartMeasurement *appStartMeasurement;
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;
#endif
}
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])) {
return nil;
}
_configuration = configuration;
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];
}
appStartMeasurement = [self getAppStartMeasurement];
_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) {
_isProfiling = YES;
_startSystemTime = SentryCurrentDate.systemTime;
[SentryProfiler startWithHub:hub];
trackTracerWithID(self.traceId);
}
#endif // SENTRY_TARGET_PROFILING_SUPPORTED
return self;
}
- (nullable SentryTracer *)tracer
{
return self;
}
- (void)dispatchIdleTimeout
{
@synchronized(_idleTimeoutLock) {
if (_idleTimeoutBlock != NULL) {
[_configuration.dispatchQueueWrapper dispatchCancel:_idleTimeoutBlock];
}
__weak SentryTracer *weakSelf = self;
_idleTimeoutBlock = [_configuration.dispatchQueueWrapper 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 {
[_configuration.dispatchQueueWrapper dispatchAfter:_configuration.idleTimeout
block:_idleTimeoutBlock];
}
}
}
- (BOOL)hasIdleTimeout
{
return _configuration.idleTimeout > 0 && _configuration.dispatchQueueWrapper != nil;
}
- (BOOL)isAutoGeneratedTransaction
{
return _configuration.waitForChildren || [self hasIdleTimeout];
}
- (void)cancelIdleTimeout
{
@synchronized(_idleTimeoutLock) {
if ([self hasIdleTimeout]) {
[_configuration.dispatchQueueWrapper dispatchCancel:_idleTimeoutBlock];
}
}
}
- (void)startDeadlineTimer
{
__weak SentryTracer *weakSelf = self;
self.deadlineTimer =
[_configuration.timerFactory scheduledTimerWithTimeInterval:SENTRY_AUTO_TRANSACTION_DEADLINE
repeats:NO
block:^(NSTimer *_Nonnull timer) {
if (weakSelf == nil) {
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
{
[self.deadlineTimer invalidate];
self.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];
child.startTimestamp = [SentryCurrentDate 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.traceId.sentryIdString,
nameForSentrySpanStatus(status));
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];
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 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 (![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];
}
[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 (appStartMeasurement != nil) {
[self updateStartTime:appStartMeasurement.appStartTimestamp];
}
// 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;
}
stopTrackingTracerWithID(self.traceId, ^{ [SentryProfiler stop]; });
SENTRY_LOG_DEBUG(@"Capturing transaction with profiling data attached.");
[_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
{
NSArray<id<SentrySpan>> *appStartSpans = [self buildAppStartSpans];
NSMutableArray<id<SentrySpan>> *spans =
[[NSMutableArray alloc] initWithCapacity:_children.count + appStartSpans.count];
@synchronized(_children) {
[spans addObjectsFromArray:_children];
}
[spans addObjectsFromArray:appStartSpans];
SentryTransaction *transaction = [[SentryTransaction alloc] initWithTrace:self children:spans];
transaction.transaction = self.transactionContext.name;
#if SENTRY_TARGET_PROFILING_SUPPORTED
transaction.startSystemTime = self.startSystemTime;
transaction.endSystemTime = SentryCurrentDate.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];
}
[self addMeasurements:transaction];
return transaction;
}
- (nullable SentryAppStartMeasurement *)getAppStartMeasurement
{
// Only send app start measurement for transactions generated by auto performance
// instrumentation.
if (![self.operation isEqualToString:SentrySpanOperationUILoad]) {
return nil;
}
// Hybrid SDKs send the app start measurement themselves.
if (PrivateSentrySDKOnly.appStartMeasurementHybridSDKMode) {
return nil;
}
// Double-Checked Locking to avoid acquiring unnecessary locks.
if (appStartMeasurementRead == YES) {
return nil;
}
SentryAppStartMeasurement *measurement = nil;
@synchronized(appStartMeasurementLock) {
if (appStartMeasurementRead == YES) {
return nil;
}
measurement = [SentrySDK getAppStartMeasurement];
if (measurement == nil) {
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) {
return nil;
}
return measurement;
}
- (NSArray<SentrySpan *> *)buildAppStartSpans
{
if (appStartMeasurement == nil) {
return @[];
}
NSString *operation;
NSString *type;
switch (appStartMeasurement.type) {
case SentryAppStartTypeCold:
operation = @"app.start.cold";
type = @"Cold Start";
break;
case SentryAppStartTypeWarm:
operation = @"app.start.warm";
type = @"Warm Start";
break;
default:
return @[];
}
NSMutableArray<SentrySpan *> *appStartSpans = [NSMutableArray array];
NSDate *appStartEndTimestamp = [appStartMeasurement.appStartTimestamp
dateByAddingTimeInterval:appStartMeasurement.duration];
SentrySpan *appStartSpan = [self buildSpan:self.spanId operation:operation description:type];
[appStartSpan setStartTimestamp:appStartMeasurement.appStartTimestamp];
[appStartSpan setTimestamp:appStartEndTimestamp];
[appStartSpans addObject:appStartSpan];
if (!appStartMeasurement.isPreWarmed) {
SentrySpan *premainSpan = [self buildSpan:appStartSpan.spanId
operation:operation
description:@"Pre Runtime Init"];
[premainSpan setStartTimestamp:appStartMeasurement.appStartTimestamp];
[premainSpan setTimestamp:appStartMeasurement.runtimeInitTimestamp];
[appStartSpans addObject:premainSpan];
SentrySpan *runtimeInitSpan = [self buildSpan:appStartSpan.spanId
operation:operation
description:@"Runtime Init to Pre Main Initializers"];
[runtimeInitSpan setStartTimestamp:appStartMeasurement.runtimeInitTimestamp];
[runtimeInitSpan setTimestamp:appStartMeasurement.moduleInitializationTimestamp];
[appStartSpans addObject:runtimeInitSpan];
}
SentrySpan *appInitSpan = [self buildSpan:appStartSpan.spanId
operation:operation
description:@"UIKit and Application Init"];
[appInitSpan setStartTimestamp:appStartMeasurement.moduleInitializationTimestamp];
[appInitSpan setTimestamp:appStartMeasurement.didFinishLaunchingTimestamp];
[appStartSpans addObject:appInitSpan];
SentrySpan *frameRenderSpan = [self buildSpan:appStartSpan.spanId
operation:operation
description:@"Initial Frame Render"];
[frameRenderSpan setStartTimestamp:appStartMeasurement.didFinishLaunchingTimestamp];
[frameRenderSpan setTimestamp:appStartEndTimestamp];
[appStartSpans addObject:frameRenderSpan];
return appStartSpans;
}
- (void)addMeasurements:(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];
}
}
#if SENTRY_HAS_UIKIT
// Frames
SentryFramesTracker *framesTracker = SentryDependencyContainer.sharedInstance.framesTracker;
if (framesTracker.isRunning && !_startTimeChanged) {
SentryScreenFrames *currentFrames = framesTracker.currentFrames;
NSInteger totalFrames = currentFrames.total - initTotalFrames;
NSInteger slowFrames = currentFrames.slow - initSlowFrames;
NSInteger frozenFrames = currentFrames.frozen - initFrozenFrames;
BOOL allBiggerThanZero = totalFrames >= 0 && slowFrames >= 0 && frozenFrames >= 0;
BOOL oneBiggerThanZero = totalFrames > 0 || slowFrames > 0 || frozenFrames > 0;
if (allBiggerThanZero && oneBiggerThanZero) {
[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
}
- (id<SentrySpan>)buildSpan:(SentrySpanId *)parentId
operation:(NSString *)operation
description:(NSString *)description
{
SentrySpanContext *context =
[[SentrySpanContext alloc] initWithTraceId:self.traceId
spanId:[[SentrySpanId alloc] init]
parentId:parentId
operation:operation
spanDescription:description
origin:SentryTraceOriginAutoAppStart
sampled:self.sampled];
return [[SentrySpan alloc] initWithTracer:self context:context];
}
/**
* 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;
}
#if SENTRY_TARGET_PROFILING_SUPPORTED && (defined(TEST) || defined(TESTCI))
// this just calls through to SentryTracerConcurrency.resetConcurrencyTracking(). we have to do this
// through SentryTracer because SentryTracerConcurrency cannot be included in test targets via ObjC
// bridging headers because it contains C++.
+ (void)resetConcurrencyTracking
{
resetConcurrencyTracking();
}
#endif // SENTRY_TARGET_PROFILING_SUPPORTED && (defined(TEST) || defined(TESTCI))
@end
NS_ASSUME_NONNULL_END