FPRAppActivityTracker.m 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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 <Network/Network.h>
  17. #import <UIKit/UIKit.h>
  18. #import "FirebasePerformance/Sources/AppActivity/FPRSessionManager.h"
  19. #import "FirebasePerformance/Sources/Configurations/FPRConfigurations.h"
  20. #import "FirebasePerformance/Sources/Gauges/CPU/FPRCPUGaugeCollector+Private.h"
  21. #import "FirebasePerformance/Sources/Gauges/FPRGaugeManager.h"
  22. #import "FirebasePerformance/Sources/Gauges/Memory/FPRMemoryGaugeCollector+Private.h"
  23. #import "FirebasePerformance/Sources/Timer/FIRTrace+Internal.h"
  24. #import "FirebasePerformance/Sources/Timer/FIRTrace+Private.h"
  25. static NSDate *appStartTime = nil;
  26. static NSDate *doubleDispatchTime = nil;
  27. static NSDate *applicationDidFinishLaunchTime = nil;
  28. static NSTimeInterval gAppStartMaxValidDuration = 60 * 60; // 60 minutes.
  29. static FPRCPUGaugeData *gAppStartCPUGaugeData = nil;
  30. static FPRMemoryGaugeData *gAppStartMemoryGaugeData = nil;
  31. static BOOL isActivePrewarm = NO;
  32. NSString *const kFPRAppStartTraceName = @"_as";
  33. NSString *const kFPRAppStartStageNameTimeToUI = @"_astui";
  34. NSString *const kFPRAppStartStageNameTimeToFirstDraw = @"_astfd";
  35. NSString *const kFPRAppStartStageNameTimeToUserInteraction = @"_asti";
  36. NSString *const kFPRAppTraceNameForegroundSession = @"_fs";
  37. NSString *const kFPRAppTraceNameBackgroundSession = @"_bs";
  38. NSString *const kFPRAppCounterNameTraceEventsRateLimited = @"_fstec";
  39. NSString *const kFPRAppCounterNameNetworkTraceEventsRateLimited = @"_fsntc";
  40. NSString *const kFPRAppCounterNameTraceNotStopped = @"_tsns";
  41. NSString *const kFPRAppCounterNameActivePrewarm = @"_fsapc";
  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. /** Current network connection type of the application. */
  50. @property(nonatomic, readwrite) firebase_perf_v1_NetworkConnectionInfo_NetworkType networkType;
  51. /** Network monitor object to track network movements. */
  52. @property(nonatomic, readwrite) nw_path_monitor_t monitor;
  53. /** Queue used to track the network monitoring changes. */
  54. @property(nonatomic, readwrite) dispatch_queue_t monitorQueue;
  55. /** Trace to measure the app start performance. */
  56. @property(nonatomic) FIRTrace *appStartTrace;
  57. /** Tracks if the gauge metrics are dispatched. */
  58. @property(nonatomic) BOOL appStartGaugeMetricDispatched;
  59. /** Firebase Performance Configuration object */
  60. @property(nonatomic) FPRConfigurations *configurations;
  61. /** Starts tracking app active sessions. */
  62. - (void)startAppActivityTracking;
  63. @end
  64. @implementation FPRAppActivityTracker
  65. + (void)load {
  66. // This is an approximation of the app start time.
  67. appStartTime = [NSDate date];
  68. // When an app is prewarmed, Apple sets env variable ActivePrewarm to 1, then the env variable is
  69. // deleted after didFinishLaunching
  70. isActivePrewarm = [NSProcessInfo.processInfo.environment[@"ActivePrewarm"] isEqualToString:@"1"];
  71. gAppStartCPUGaugeData = fprCollectCPUMetric();
  72. gAppStartMemoryGaugeData = fprCollectMemoryMetric();
  73. [[NSNotificationCenter defaultCenter] addObserver:self
  74. selector:@selector(windowDidBecomeVisible:)
  75. name:UIWindowDidBecomeVisibleNotification
  76. object:nil];
  77. [[NSNotificationCenter defaultCenter] addObserver:self
  78. selector:@selector(applicationDidFinishLaunching:)
  79. name:UIApplicationDidFinishLaunchingNotification
  80. object:nil];
  81. }
  82. + (void)windowDidBecomeVisible:(NSNotification *)notification {
  83. FPRAppActivityTracker *activityTracker = [self sharedInstance];
  84. [activityTracker startAppActivityTracking];
  85. [[NSNotificationCenter defaultCenter] removeObserver:self
  86. name:UIWindowDidBecomeVisibleNotification
  87. object:nil];
  88. }
  89. + (void)applicationDidFinishLaunching:(NSNotification *)notification {
  90. applicationDidFinishLaunchTime = [NSDate date];
  91. [[NSNotificationCenter defaultCenter] removeObserver:self
  92. name:UIApplicationDidFinishLaunchingNotification
  93. object:nil];
  94. }
  95. + (instancetype)sharedInstance {
  96. static FPRAppActivityTracker *instance;
  97. static dispatch_once_t onceToken;
  98. dispatch_once(&onceToken, ^{
  99. instance = [[self alloc] initAppActivityTracker];
  100. });
  101. return instance;
  102. }
  103. /**
  104. * Custom initializer to create an app activity tracker.
  105. */
  106. - (instancetype)initAppActivityTracker {
  107. self = [super init];
  108. if (self != nil) {
  109. _applicationState = FPRApplicationStateUnknown;
  110. _appStartGaugeMetricDispatched = NO;
  111. _configurations = [FPRConfigurations sharedInstance];
  112. [self startTrackingNetwork];
  113. }
  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. - (void)startTrackingNetwork {
  133. self.networkType = firebase_perf_v1_NetworkConnectionInfo_NetworkType_NONE;
  134. dispatch_queue_attr_t attrs = dispatch_queue_attr_make_with_qos_class(
  135. DISPATCH_QUEUE_SERIAL, QOS_CLASS_UTILITY, DISPATCH_QUEUE_PRIORITY_DEFAULT);
  136. self.monitorQueue = dispatch_queue_create("com.google.firebase.perf.network.monitor", attrs);
  137. self.monitor = nw_path_monitor_create();
  138. nw_path_monitor_set_queue(self.monitor, self.monitorQueue);
  139. __weak FPRAppActivityTracker *weakSelf = self;
  140. nw_path_monitor_set_update_handler(self.monitor, ^(nw_path_t _Nonnull path) {
  141. BOOL isWiFi = nw_path_uses_interface_type(path, nw_interface_type_wifi);
  142. BOOL isCellular = nw_path_uses_interface_type(path, nw_interface_type_cellular);
  143. BOOL isEthernet = nw_path_uses_interface_type(path, nw_interface_type_wired);
  144. if (isWiFi) {
  145. weakSelf.networkType = firebase_perf_v1_NetworkConnectionInfo_NetworkType_WIFI;
  146. } else if (isCellular) {
  147. weakSelf.networkType = firebase_perf_v1_NetworkConnectionInfo_NetworkType_MOBILE;
  148. } else if (isEthernet) {
  149. weakSelf.networkType = firebase_perf_v1_NetworkConnectionInfo_NetworkType_ETHERNET;
  150. }
  151. });
  152. nw_path_monitor_start(self.monitor);
  153. }
  154. /**
  155. * Checks if the prewarming feature is available on the current device.
  156. *
  157. * @return true if the OS could prewarm apps on the current device
  158. */
  159. - (BOOL)isPrewarmAvailable {
  160. return YES;
  161. }
  162. /**
  163. RC flag for dropping all app start events
  164. */
  165. - (BOOL)isAppStartEnabled {
  166. return [self.configurations prewarmDetectionMode] != PrewarmDetectionModeKeepNone;
  167. }
  168. /**
  169. RC flag for enabling prewarm-detection using ActivePrewarm environment variable
  170. */
  171. - (BOOL)isActivePrewarmEnabled {
  172. PrewarmDetectionMode mode = [self.configurations prewarmDetectionMode];
  173. return (mode == PrewarmDetectionModeActivePrewarm);
  174. }
  175. /**
  176. Checks if the current app start is a prewarmed app start
  177. */
  178. - (BOOL)isApplicationPreWarmed {
  179. if (![self isPrewarmAvailable]) {
  180. return NO;
  181. }
  182. BOOL isPrewarmed = NO;
  183. if (isActivePrewarm == YES) {
  184. isPrewarmed = isPrewarmed || [self isActivePrewarmEnabled];
  185. [self.activeTrace incrementMetric:kFPRAppCounterNameActivePrewarm byInt:1];
  186. } else {
  187. [self.activeTrace incrementMetric:kFPRAppCounterNameActivePrewarm byInt:0];
  188. }
  189. return isPrewarmed;
  190. }
  191. /**
  192. * This gets called whenever the app becomes active. A new trace will be created to track the active
  193. * foreground session. Any background session trace that was running in the past will be stopped.
  194. *
  195. * @param notification Notification received during app launch.
  196. */
  197. - (void)appDidBecomeActiveNotification:(NSNotification *)notification {
  198. self.applicationState = FPRApplicationStateForeground;
  199. static dispatch_once_t onceToken;
  200. dispatch_once(&onceToken, ^{
  201. self.appStartTrace = [[FIRTrace alloc] initInternalTraceWithName:kFPRAppStartTraceName];
  202. [self.appStartTrace startWithStartTime:appStartTime];
  203. [self.appStartTrace startStageNamed:kFPRAppStartStageNameTimeToUI startTime:appStartTime];
  204. // Start measuring time to first draw on the App start trace.
  205. [self.appStartTrace startStageNamed:kFPRAppStartStageNameTimeToFirstDraw];
  206. });
  207. // If ever the app start trace had it life in background stage, do not send the trace.
  208. if (self.appStartTrace.backgroundTraceState != FPRTraceStateForegroundOnly) {
  209. self.appStartTrace = nil;
  210. }
  211. // Stop the active background session trace.
  212. [self.backgroundSessionTrace stop];
  213. self.backgroundSessionTrace = nil;
  214. // Start foreground session trace.
  215. FIRTrace *appTrace =
  216. [[FIRTrace alloc] initInternalTraceWithName:kFPRAppTraceNameForegroundSession];
  217. [appTrace start];
  218. self.foregroundSessionTrace = appTrace;
  219. // Start measuring time to make the app interactive on the App start trace.
  220. static BOOL TTIStageStarted = NO;
  221. if (!TTIStageStarted) {
  222. [self.appStartTrace startStageNamed:kFPRAppStartStageNameTimeToUserInteraction];
  223. TTIStageStarted = YES;
  224. // Assumption here is that - the app becomes interactive in the next runloop cycle.
  225. // It is possible that the app does more things later, but for now we are not measuring that.
  226. dispatch_async(dispatch_get_main_queue(), ^{
  227. NSTimeInterval startTimeSinceEpoch = [self.appStartTrace startTimeSinceEpoch];
  228. NSTimeInterval currentTimeSinceEpoch = [[NSDate date] timeIntervalSince1970];
  229. // The below check is to account for 2 scenarios.
  230. // 1. The app gets started in the background and might come to foreground a lot later.
  231. // 2. The app is launched, but immediately backgrounded for some reason and the actual launch
  232. // happens a lot later.
  233. // Dropping the app start trace in such situations where the launch time is taking more than
  234. // 60 minutes. This is an approximation, but a more agreeable timelimit for app start.
  235. if ((currentTimeSinceEpoch - startTimeSinceEpoch < gAppStartMaxValidDuration) &&
  236. [self isAppStartEnabled] && ![self isApplicationPreWarmed]) {
  237. [self.appStartTrace stop];
  238. } else {
  239. [self.appStartTrace cancel];
  240. }
  241. });
  242. }
  243. }
  244. /**
  245. * This gets called whenever the app resigns its active status. The currently active foreground
  246. * session trace will be stopped and a background session trace will be started.
  247. *
  248. * @param notification Notification received during app resigning active status.
  249. */
  250. - (void)appWillResignActiveNotification:(NSNotification *)notification {
  251. // Dispatch the collected gauge metrics.
  252. if (!self.appStartGaugeMetricDispatched) {
  253. [[FPRGaugeManager sharedInstance] dispatchMetric:gAppStartCPUGaugeData];
  254. [[FPRGaugeManager sharedInstance] dispatchMetric:gAppStartMemoryGaugeData];
  255. self.appStartGaugeMetricDispatched = YES;
  256. }
  257. self.applicationState = FPRApplicationStateBackground;
  258. // Stop foreground session trace.
  259. [self.foregroundSessionTrace stop];
  260. self.foregroundSessionTrace = nil;
  261. // Start background session trace.
  262. self.backgroundSessionTrace =
  263. [[FIRTrace alloc] initInternalTraceWithName:kFPRAppTraceNameBackgroundSession];
  264. [self.backgroundSessionTrace start];
  265. }
  266. - (void)dealloc {
  267. nw_path_monitor_cancel(self.monitor);
  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