FPRAppActivityTracker.m 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. // Copyright 2020 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #import "FirebasePerformance/Sources/AppActivity/FPRAppActivityTracker.h"
  15. #import <Foundation/Foundation.h>
  16. #import <UIKit/UIKit.h>
  17. #import "FirebasePerformance/Sources/AppActivity/FPRSessionManager.h"
  18. #import "FirebasePerformance/Sources/Configurations/FPRConfigurations.h"
  19. #import "FirebasePerformance/Sources/Gauges/CPU/FPRCPUGaugeCollector+Private.h"
  20. #import "FirebasePerformance/Sources/Gauges/FPRGaugeManager.h"
  21. #import "FirebasePerformance/Sources/Gauges/Memory/FPRMemoryGaugeCollector+Private.h"
  22. #import "FirebasePerformance/Sources/Timer/FIRTrace+Internal.h"
  23. #import "FirebasePerformance/Sources/Timer/FIRTrace+Private.h"
  24. static NSDate *appStartTime = nil;
  25. static NSDate *doubleDispatchTime = nil;
  26. static NSDate *applicationDidFinishLaunchTime = nil;
  27. static NSTimeInterval gAppStartMaxValidDuration = 60 * 60; // 60 minutes.
  28. static FPRCPUGaugeData *gAppStartCPUGaugeData = nil;
  29. static FPRMemoryGaugeData *gAppStartMemoryGaugeData = nil;
  30. static BOOL isActivePrewarm = NO;
  31. NSString *const kFPRAppStartTraceName = @"_as";
  32. NSString *const kFPRAppStartStageNameTimeToUI = @"_astui";
  33. NSString *const kFPRAppStartStageNameTimeToFirstDraw = @"_astfd";
  34. NSString *const kFPRAppStartStageNameTimeToUserInteraction = @"_asti";
  35. NSString *const kFPRAppTraceNameForegroundSession = @"_fs";
  36. NSString *const kFPRAppTraceNameBackgroundSession = @"_bs";
  37. NSString *const kFPRAppCounterNameTraceEventsRateLimited = @"_fstec";
  38. NSString *const kFPRAppCounterNameNetworkTraceEventsRateLimited = @"_fsntc";
  39. NSString *const kFPRAppCounterNameTraceNotStopped = @"_tsns";
  40. NSString *const kFPRAppCounterNameActivePrewarm = @"_fsapc";
  41. @interface FPRAppActivityTracker ()
  42. /** The foreground session trace. Will be set only when the app is in the foreground. */
  43. @property(nonatomic, readwrite) FIRTrace *foregroundSessionTrace;
  44. /** The background session trace. Will be set only when the app is in the background. */
  45. @property(nonatomic, readwrite) FIRTrace *backgroundSessionTrace;
  46. /** Current running state of the application. */
  47. @property(nonatomic, readwrite) FPRApplicationState applicationState;
  48. /** Trace to measure the app start performance. */
  49. @property(nonatomic) FIRTrace *appStartTrace;
  50. /** Tracks if the gauge metrics are dispatched. */
  51. @property(nonatomic) BOOL appStartGaugeMetricDispatched;
  52. /** Firebase Performance Configuration object */
  53. @property(nonatomic) FPRConfigurations *configurations;
  54. /** Starts tracking app active sessions. */
  55. - (void)startAppActivityTracking;
  56. @end
  57. @implementation FPRAppActivityTracker
  58. + (void)load {
  59. // This is an approximation of the app start time.
  60. appStartTime = [NSDate date];
  61. // When an app is prewarmed, Apple sets env variable ActivePrewarm to 1, then the env variable is
  62. // deleted after didFinishLaunching
  63. isActivePrewarm = [NSProcessInfo.processInfo.environment[@"ActivePrewarm"] isEqualToString:@"1"];
  64. gAppStartCPUGaugeData = fprCollectCPUMetric();
  65. gAppStartMemoryGaugeData = fprCollectMemoryMetric();
  66. [[NSNotificationCenter defaultCenter] addObserver:self
  67. selector:@selector(windowDidBecomeVisible:)
  68. name:UIWindowDidBecomeVisibleNotification
  69. object:nil];
  70. [[NSNotificationCenter defaultCenter] addObserver:self
  71. selector:@selector(applicationDidFinishLaunching:)
  72. name:UIApplicationDidFinishLaunchingNotification
  73. object:nil];
  74. }
  75. + (void)windowDidBecomeVisible:(NSNotification *)notification {
  76. FPRAppActivityTracker *activityTracker = [self sharedInstance];
  77. [activityTracker startAppActivityTracking];
  78. [[NSNotificationCenter defaultCenter] removeObserver:self
  79. name:UIWindowDidBecomeVisibleNotification
  80. object:nil];
  81. }
  82. + (void)applicationDidFinishLaunching:(NSNotification *)notification {
  83. applicationDidFinishLaunchTime = [NSDate date];
  84. [[NSNotificationCenter defaultCenter] removeObserver:self
  85. name:UIApplicationDidFinishLaunchingNotification
  86. object:nil];
  87. }
  88. + (instancetype)sharedInstance {
  89. static FPRAppActivityTracker *instance;
  90. static dispatch_once_t onceToken;
  91. dispatch_once(&onceToken, ^{
  92. instance = [[self alloc] initAppActivityTracker];
  93. });
  94. return instance;
  95. }
  96. /**
  97. * Custom initializer to create an app activity tracker.
  98. */
  99. - (instancetype)initAppActivityTracker {
  100. self = [super init];
  101. _applicationState = FPRApplicationStateUnknown;
  102. _appStartGaugeMetricDispatched = NO;
  103. _configurations = [FPRConfigurations sharedInstance];
  104. return self;
  105. }
  106. - (void)startAppActivityTracking {
  107. [[NSNotificationCenter defaultCenter] addObserver:self
  108. selector:@selector(appDidBecomeActiveNotification:)
  109. name:UIApplicationDidBecomeActiveNotification
  110. object:[UIApplication sharedApplication]];
  111. [[NSNotificationCenter defaultCenter] addObserver:self
  112. selector:@selector(appWillResignActiveNotification:)
  113. name:UIApplicationWillResignActiveNotification
  114. object:[UIApplication sharedApplication]];
  115. }
  116. - (FIRTrace *)activeTrace {
  117. if (self.foregroundSessionTrace) {
  118. return self.foregroundSessionTrace;
  119. }
  120. return self.backgroundSessionTrace;
  121. }
  122. /**
  123. * Checks if the prewarming feature is available on the current device.
  124. *
  125. * @return true if the OS could prewarm apps on the current device
  126. */
  127. - (BOOL)isPrewarmAvailable {
  128. BOOL canPrewarm = NO;
  129. // Guarding for double dispatch which does not work below iOS 13, and 0.1% of app start also show
  130. // signs of prewarming on iOS 14 go/paste/5533761933410304
  131. if (@available(iOS 13, *)) {
  132. canPrewarm = YES;
  133. }
  134. return canPrewarm;
  135. }
  136. /**
  137. RC flag for dropping all app start events
  138. */
  139. - (BOOL)isAppStartEnabled {
  140. return [self.configurations prewarmDetectionMode] != PrewarmDetectionModeKeepNone;
  141. }
  142. /**
  143. RC flag for enabling prewarm-detection using ActivePrewarm environment variable
  144. */
  145. - (BOOL)isActivePrewarmEnabled {
  146. PrewarmDetectionMode mode = [self.configurations prewarmDetectionMode];
  147. return (mode == PrewarmDetectionModeActivePrewarm);
  148. }
  149. /**
  150. Checks if the current app start is a prewarmed app start
  151. */
  152. - (BOOL)isApplicationPreWarmed {
  153. if (![self isPrewarmAvailable]) {
  154. return NO;
  155. }
  156. BOOL isPrewarmed = NO;
  157. if (isActivePrewarm == YES) {
  158. isPrewarmed = isPrewarmed || [self isActivePrewarmEnabled];
  159. [self.activeTrace incrementMetric:kFPRAppCounterNameActivePrewarm byInt:1];
  160. } else {
  161. [self.activeTrace incrementMetric:kFPRAppCounterNameActivePrewarm byInt:0];
  162. }
  163. return isPrewarmed;
  164. }
  165. /**
  166. * This gets called whenever the app becomes active. A new trace will be created to track the active
  167. * foreground session. Any background session trace that was running in the past will be stopped.
  168. *
  169. * @param notification Notification received during app launch.
  170. */
  171. - (void)appDidBecomeActiveNotification:(NSNotification *)notification {
  172. self.applicationState = FPRApplicationStateForeground;
  173. static dispatch_once_t onceToken;
  174. dispatch_once(&onceToken, ^{
  175. self.appStartTrace = [[FIRTrace alloc] initInternalTraceWithName:kFPRAppStartTraceName];
  176. [self.appStartTrace startWithStartTime:appStartTime];
  177. [self.appStartTrace startStageNamed:kFPRAppStartStageNameTimeToUI startTime:appStartTime];
  178. // Start measuring time to first draw on the App start trace.
  179. [self.appStartTrace startStageNamed:kFPRAppStartStageNameTimeToFirstDraw];
  180. });
  181. // If ever the app start trace had it life in background stage, do not send the trace.
  182. if (self.appStartTrace.backgroundTraceState != FPRTraceStateForegroundOnly) {
  183. self.appStartTrace = nil;
  184. }
  185. // Stop the active background session trace.
  186. [self.backgroundSessionTrace stop];
  187. self.backgroundSessionTrace = nil;
  188. // Start foreground session trace.
  189. FIRTrace *appTrace =
  190. [[FIRTrace alloc] initInternalTraceWithName:kFPRAppTraceNameForegroundSession];
  191. [appTrace start];
  192. self.foregroundSessionTrace = appTrace;
  193. // Start measuring time to make the app interactive on the App start trace.
  194. static BOOL TTIStageStarted = NO;
  195. if (!TTIStageStarted) {
  196. [self.appStartTrace startStageNamed:kFPRAppStartStageNameTimeToUserInteraction];
  197. TTIStageStarted = YES;
  198. // Assumption here is that - the app becomes interactive in the next runloop cycle.
  199. // It is possible that the app does more things later, but for now we are not measuring that.
  200. dispatch_async(dispatch_get_main_queue(), ^{
  201. NSTimeInterval startTimeSinceEpoch = [self.appStartTrace startTimeSinceEpoch];
  202. NSTimeInterval currentTimeSinceEpoch = [[NSDate date] timeIntervalSince1970];
  203. // The below check is to account for 2 scenarios.
  204. // 1. The app gets started in the background and might come to foreground a lot later.
  205. // 2. The app is launched, but immediately backgrounded for some reason and the actual launch
  206. // happens a lot later.
  207. // Dropping the app start trace in such situations where the launch time is taking more than
  208. // 60 minutes. This is an approximation, but a more agreeable timelimit for app start.
  209. if ((currentTimeSinceEpoch - startTimeSinceEpoch < gAppStartMaxValidDuration) &&
  210. [self isAppStartEnabled] && ![self isApplicationPreWarmed]) {
  211. [self.appStartTrace stop];
  212. } else {
  213. [self.appStartTrace cancel];
  214. }
  215. });
  216. }
  217. }
  218. /**
  219. * This gets called whenever the app resigns its active status. The currently active foreground
  220. * session trace will be stopped and a background session trace will be started.
  221. *
  222. * @param notification Notification received during app resigning active status.
  223. */
  224. - (void)appWillResignActiveNotification:(NSNotification *)notification {
  225. // Dispatch the collected gauge metrics.
  226. if (!self.appStartGaugeMetricDispatched) {
  227. [[FPRGaugeManager sharedInstance] dispatchMetric:gAppStartCPUGaugeData];
  228. [[FPRGaugeManager sharedInstance] dispatchMetric:gAppStartMemoryGaugeData];
  229. self.appStartGaugeMetricDispatched = YES;
  230. }
  231. self.applicationState = FPRApplicationStateBackground;
  232. // Stop foreground session trace.
  233. [self.foregroundSessionTrace stop];
  234. self.foregroundSessionTrace = nil;
  235. // Start background session trace.
  236. self.backgroundSessionTrace =
  237. [[FIRTrace alloc] initInternalTraceWithName:kFPRAppTraceNameBackgroundSession];
  238. [self.backgroundSessionTrace start];
  239. }
  240. - (void)dealloc {
  241. [[NSNotificationCenter defaultCenter] removeObserver:self
  242. name:UIApplicationDidBecomeActiveNotification
  243. object:[UIApplication sharedApplication]];
  244. [[NSNotificationCenter defaultCenter] removeObserver:self
  245. name:UIApplicationWillResignActiveNotification
  246. object:[UIApplication sharedApplication]];
  247. }
  248. @end