FPRAppActivityTracker.m 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  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. NSString *const kFPRAppCounterNameDoubleDispatch = @"_fsddc";
  42. @interface FPRAppActivityTracker ()
  43. /** The foreground session trace. Will be set only when the app is in the foreground. */
  44. @property(nonatomic, readwrite) FIRTrace *foregroundSessionTrace;
  45. /** The background session trace. Will be set only when the app is in the background. */
  46. @property(nonatomic, readwrite) FIRTrace *backgroundSessionTrace;
  47. /** Current running state of the application. */
  48. @property(nonatomic, readwrite) FPRApplicationState applicationState;
  49. /** Trace to measure the app start performance. */
  50. @property(nonatomic) FIRTrace *appStartTrace;
  51. /** Tracks if the gauge metrics are dispatched. */
  52. @property(nonatomic) BOOL appStartGaugeMetricDispatched;
  53. /** Firebase Performance Configuration object */
  54. @property(nonatomic) FPRConfigurations *configurations;
  55. /** Starts tracking app active sessions. */
  56. - (void)startAppActivityTracking;
  57. @end
  58. @implementation FPRAppActivityTracker
  59. + (void)load {
  60. // This is an approximation of the app start time.
  61. appStartTime = [NSDate date];
  62. // Double dispatch is used to detect prewarming, but if it causes hang or crash in the future
  63. // developers can disable it by setting a plist flag "fireperf_disable_dd" to true
  64. if ([[[NSBundle mainBundle] objectForInfoDictionaryKey:@"fireperf_disable_dd"] boolValue] == NO) {
  65. dispatch_async(dispatch_get_main_queue(), ^{
  66. dispatch_async(dispatch_get_main_queue(), ^{
  67. doubleDispatchTime = [NSDate date];
  68. });
  69. });
  70. }
  71. // When an app is prewarmed, Apple sets env variable ActivePrewarm to 1, then the env variable is
  72. // deleted after didFinishLaunching
  73. isActivePrewarm = [NSProcessInfo.processInfo.environment[@"ActivePrewarm"] isEqualToString:@"1"];
  74. gAppStartCPUGaugeData = fprCollectCPUMetric();
  75. gAppStartMemoryGaugeData = fprCollectMemoryMetric();
  76. [[NSNotificationCenter defaultCenter] addObserver:self
  77. selector:@selector(windowDidBecomeVisible:)
  78. name:UIWindowDidBecomeVisibleNotification
  79. object:nil];
  80. [[NSNotificationCenter defaultCenter] addObserver:self
  81. selector:@selector(applicationDidFinishLaunching:)
  82. name:UIApplicationDidFinishLaunchingNotification
  83. object:nil];
  84. }
  85. + (void)windowDidBecomeVisible:(NSNotification *)notification {
  86. FPRAppActivityTracker *activityTracker = [self sharedInstance];
  87. [activityTracker startAppActivityTracking];
  88. [[NSNotificationCenter defaultCenter] removeObserver:self
  89. name:UIWindowDidBecomeVisibleNotification
  90. object:nil];
  91. }
  92. + (void)applicationDidFinishLaunching:(NSNotification *)notification {
  93. applicationDidFinishLaunchTime = [NSDate date];
  94. [[NSNotificationCenter defaultCenter] removeObserver:self
  95. name:UIApplicationDidFinishLaunchingNotification
  96. object:nil];
  97. }
  98. + (instancetype)sharedInstance {
  99. static FPRAppActivityTracker *instance;
  100. static dispatch_once_t onceToken;
  101. dispatch_once(&onceToken, ^{
  102. instance = [[self alloc] initAppActivityTracker];
  103. });
  104. return instance;
  105. }
  106. /**
  107. * Custom initializer to create an app activity tracker.
  108. */
  109. - (instancetype)initAppActivityTracker {
  110. self = [super init];
  111. _applicationState = FPRApplicationStateUnknown;
  112. _appStartGaugeMetricDispatched = NO;
  113. _configurations = [FPRConfigurations sharedInstance];
  114. return self;
  115. }
  116. - (void)startAppActivityTracking {
  117. [[NSNotificationCenter defaultCenter] addObserver:self
  118. selector:@selector(appDidBecomeActiveNotification:)
  119. name:UIApplicationDidBecomeActiveNotification
  120. object:[UIApplication sharedApplication]];
  121. [[NSNotificationCenter defaultCenter] addObserver:self
  122. selector:@selector(appWillResignActiveNotification:)
  123. name:UIApplicationWillResignActiveNotification
  124. object:[UIApplication sharedApplication]];
  125. }
  126. - (FIRTrace *)activeTrace {
  127. if (self.foregroundSessionTrace) {
  128. return self.foregroundSessionTrace;
  129. }
  130. return self.backgroundSessionTrace;
  131. }
  132. /**
  133. * Checks if the prewarming feature is available on the current device.
  134. *
  135. * @return true if the OS could prewarm apps on the current device
  136. */
  137. - (BOOL)isPrewarmAvailable {
  138. BOOL canPrewarm = NO;
  139. // Guarding for double dispatch which does not work below iOS 13, and 0.1% of app start also show
  140. // signs of prewarming on iOS 14 go/paste/5533761933410304
  141. if (@available(iOS 13, *)) {
  142. canPrewarm = YES;
  143. }
  144. return canPrewarm;
  145. }
  146. /**
  147. RC flag for dropping all app start events
  148. */
  149. - (BOOL)isAppStartEnabled {
  150. return [self.configurations prewarmDetectionMode] != PrewarmDetectionModeKeepNone;
  151. }
  152. /**
  153. RC flag for enabling prewarm-detection using ActivePrewarm environment variable
  154. */
  155. - (BOOL)isActivePrewarmEnabled {
  156. PrewarmDetectionMode mode = [self.configurations prewarmDetectionMode];
  157. return (mode == PrewarmDetectionModeActivePrewarm ||
  158. mode == PrewarmDetectionModeActivePrewarmOrDoubleDispatch);
  159. }
  160. /**
  161. RC flag for enabling prewarm-detection using double dispatch method
  162. */
  163. - (BOOL)isDoubleDispatchEnabled {
  164. PrewarmDetectionMode mode = [self.configurations prewarmDetectionMode];
  165. return (mode == PrewarmDetectionModeDoubleDispatch ||
  166. mode == PrewarmDetectionModeActivePrewarmOrDoubleDispatch);
  167. }
  168. /**
  169. Checks if the current app start is a prewarmed app start
  170. */
  171. - (BOOL)isApplicationPreWarmed {
  172. if (![self isPrewarmAvailable]) {
  173. return NO;
  174. }
  175. BOOL isPrewarmed = NO;
  176. if (isActivePrewarm == YES) {
  177. isPrewarmed = isPrewarmed || [self isActivePrewarmEnabled];
  178. [self.activeTrace incrementMetric:kFPRAppCounterNameActivePrewarm byInt:1];
  179. } else {
  180. [self.activeTrace incrementMetric:kFPRAppCounterNameActivePrewarm byInt:0];
  181. }
  182. if ([doubleDispatchTime compare:applicationDidFinishLaunchTime] == NSOrderedAscending) {
  183. isPrewarmed = isPrewarmed || [self isDoubleDispatchEnabled];
  184. [self.activeTrace incrementMetric:kFPRAppCounterNameDoubleDispatch byInt:1];
  185. } else if (doubleDispatchTime) {
  186. [self.activeTrace incrementMetric:kFPRAppCounterNameDoubleDispatch byInt:0];
  187. }
  188. return isPrewarmed;
  189. }
  190. /**
  191. * This gets called whenever the app becomes active. A new trace will be created to track the active
  192. * foreground session. Any background session trace that was running in the past will be stopped.
  193. *
  194. * @param notification Notification received during app launch.
  195. */
  196. - (void)appDidBecomeActiveNotification:(NSNotification *)notification {
  197. self.applicationState = FPRApplicationStateForeground;
  198. static dispatch_once_t onceToken;
  199. dispatch_once(&onceToken, ^{
  200. self.appStartTrace = [[FIRTrace alloc] initInternalTraceWithName:kFPRAppStartTraceName];
  201. [self.appStartTrace startWithStartTime:appStartTime];
  202. [self.appStartTrace startStageNamed:kFPRAppStartStageNameTimeToUI startTime:appStartTime];
  203. // Start measuring time to first draw on the App start trace.
  204. [self.appStartTrace startStageNamed:kFPRAppStartStageNameTimeToFirstDraw];
  205. });
  206. // If ever the app start trace had it life in background stage, do not send the trace.
  207. if (self.appStartTrace.backgroundTraceState != FPRTraceStateForegroundOnly) {
  208. self.appStartTrace = nil;
  209. }
  210. // Stop the active background session trace.
  211. [self.backgroundSessionTrace stop];
  212. self.backgroundSessionTrace = nil;
  213. // Start foreground session trace.
  214. FIRTrace *appTrace =
  215. [[FIRTrace alloc] initInternalTraceWithName:kFPRAppTraceNameForegroundSession];
  216. [appTrace start];
  217. self.foregroundSessionTrace = appTrace;
  218. // Start measuring time to make the app interactive on the App start trace.
  219. static BOOL TTIStageStarted = NO;
  220. if (!TTIStageStarted) {
  221. [self.appStartTrace startStageNamed:kFPRAppStartStageNameTimeToUserInteraction];
  222. TTIStageStarted = YES;
  223. // Assumption here is that - the app becomes interactive in the next runloop cycle.
  224. // It is possible that the app does more things later, but for now we are not measuring that.
  225. dispatch_async(dispatch_get_main_queue(), ^{
  226. NSTimeInterval startTimeSinceEpoch = [self.appStartTrace startTimeSinceEpoch];
  227. NSTimeInterval currentTimeSinceEpoch = [[NSDate date] timeIntervalSince1970];
  228. // The below check is to account for 2 scenarios.
  229. // 1. The app gets started in the background and might come to foreground a lot later.
  230. // 2. The app is launched, but immediately backgrounded for some reason and the actual launch
  231. // happens a lot later.
  232. // Dropping the app start trace in such situations where the launch time is taking more than
  233. // 60 minutes. This is an approximation, but a more agreeable timelimit for app start.
  234. if ((currentTimeSinceEpoch - startTimeSinceEpoch < gAppStartMaxValidDuration) &&
  235. [self isAppStartEnabled] && ![self isApplicationPreWarmed]) {
  236. [self.appStartTrace stop];
  237. } else {
  238. [self.appStartTrace cancel];
  239. }
  240. });
  241. }
  242. // Let the session manager to start tracking app activity changes.
  243. [[FPRSessionManager sharedInstance] startTrackingAppStateChanges];
  244. }
  245. /**
  246. * This gets called whenever the app resigns its active status. The currently active foreground
  247. * session trace will be stopped and a background session trace will be started.
  248. *
  249. * @param notification Notification received during app resigning active status.
  250. */
  251. - (void)appWillResignActiveNotification:(NSNotification *)notification {
  252. // Dispatch the collected gauge metrics.
  253. if (!self.appStartGaugeMetricDispatched) {
  254. [[FPRGaugeManager sharedInstance] dispatchMetric:gAppStartCPUGaugeData];
  255. [[FPRGaugeManager sharedInstance] dispatchMetric:gAppStartMemoryGaugeData];
  256. self.appStartGaugeMetricDispatched = YES;
  257. }
  258. self.applicationState = FPRApplicationStateBackground;
  259. // Stop foreground session trace.
  260. [self.foregroundSessionTrace stop];
  261. self.foregroundSessionTrace = nil;
  262. // Start background session trace.
  263. self.backgroundSessionTrace =
  264. [[FIRTrace alloc] initInternalTraceWithName:kFPRAppTraceNameBackgroundSession];
  265. [self.backgroundSessionTrace start];
  266. }
  267. - (void)dealloc {
  268. [[NSNotificationCenter defaultCenter] removeObserver:self
  269. name:UIApplicationDidBecomeActiveNotification
  270. object:[UIApplication sharedApplication]];
  271. [[NSNotificationCenter defaultCenter] removeObserver:self
  272. name:UIApplicationWillResignActiveNotification
  273. object:[UIApplication sharedApplication]];
  274. }
  275. @end