FPRRemoteConfigFlags.m 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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/Configurations/FPRRemoteConfigFlags.h"
  15. #import "FirebasePerformance/Sources/Configurations/FPRConfigurations+Private.h"
  16. #import "FirebasePerformance/Sources/Configurations/FPRConfigurations.h"
  17. #import "FirebasePerformance/Sources/Configurations/FPRRemoteConfigFlags+Private.h"
  18. #import "FirebasePerformance/Sources/FPRConsoleLogger.h"
  19. #import "FirebaseCore/Sources/Private/FirebaseCoreInternal.h"
  20. #define ONE_DAY_SECONDS 24 * 60 * 60
  21. static NSDate *FPRAppStartTime = nil;
  22. typedef NS_ENUM(NSInteger, FPRConfigValueType) {
  23. // Config value type String.
  24. FPRConfigValueTypeString,
  25. // Config value type Bool.
  26. FPRConfigValueTypeBool,
  27. // Config value type Integer.
  28. FPRConfigValueTypeInteger,
  29. // Config value type Float.
  30. FPRConfigValueTypeFloat,
  31. };
  32. @interface FPRRemoteConfigFlags ()
  33. /** @brief Represents if a fetch is currently in progress. */
  34. @property(atomic) BOOL fetchInProgress;
  35. /** @brief Dictionary of different config keys and value types. */
  36. @property(nonatomic) NSDictionary<NSString *, NSNumber *> *configKeys;
  37. /** @brief Last time the configs were cached. */
  38. @property(nonatomic) NSDate *lastCachedTime;
  39. @end
  40. @implementation FPRRemoteConfigFlags
  41. + (void)load {
  42. FPRAppStartTime = [NSDate date];
  43. }
  44. + (nullable instancetype)sharedInstance {
  45. static FPRRemoteConfigFlags *instance = nil;
  46. static dispatch_once_t onceToken;
  47. dispatch_once(&onceToken, ^{
  48. FIRRemoteConfig *rc = [FIRRemoteConfig remoteConfigWithFIRNamespace:@"fireperf"
  49. app:[FIRApp defaultApp]];
  50. instance = [[FPRRemoteConfigFlags alloc] initWithRemoteConfig:rc];
  51. });
  52. return instance;
  53. }
  54. - (instancetype)initWithRemoteConfig:(FIRRemoteConfig *)config {
  55. self = [super init];
  56. if (self) {
  57. _fprRemoteConfig = config;
  58. _userDefaults = [FPRConfigurations sharedInstance].userDefaults;
  59. self.fetchInProgress = NO;
  60. // Set the overall delay to 5+random(25) making the config fetch delay at a max of 30 seconds
  61. self.applicationStartTime = FPRAppStartTime;
  62. self.appStartConfigFetchDelayInSeconds =
  63. kFPRMinAppStartConfigFetchDelayInSeconds + arc4random_uniform(25);
  64. NSMutableDictionary<NSString *, NSNumber *> *keysToCache =
  65. [[NSMutableDictionary<NSString *, NSNumber *> alloc] init];
  66. [keysToCache setObject:@(FPRConfigValueTypeInteger) forKey:@"fpr_log_source"];
  67. [keysToCache setObject:@(FPRConfigValueTypeBool) forKey:@"fpr_enabled"];
  68. [keysToCache setObject:@(FPRConfigValueTypeString) forKey:@"fpr_disabled_ios_versions"];
  69. [keysToCache setObject:@(FPRConfigValueTypeInteger) forKey:@"fpr_rl_time_limit_sec"];
  70. [keysToCache setObject:@(FPRConfigValueTypeInteger) forKey:@"fpr_rl_trace_event_count_fg"];
  71. [keysToCache setObject:@(FPRConfigValueTypeInteger) forKey:@"fpr_rl_trace_event_count_bg"];
  72. [keysToCache setObject:@(FPRConfigValueTypeInteger)
  73. forKey:@"fpr_rl_network_request_event_count_fg"];
  74. [keysToCache setObject:@(FPRConfigValueTypeInteger)
  75. forKey:@"fpr_rl_network_request_event_count_bg"];
  76. [keysToCache setObject:@(FPRConfigValueTypeFloat) forKey:@"fpr_vc_trace_sampling_rate"];
  77. [keysToCache setObject:@(FPRConfigValueTypeFloat)
  78. forKey:@"fpr_vc_network_request_sampling_rate"];
  79. [keysToCache setObject:@(FPRConfigValueTypeFloat) forKey:@"fpr_vc_session_sampling_rate"];
  80. [keysToCache setObject:@(FPRConfigValueTypeInteger)
  81. forKey:@"fpr_session_gauge_cpu_capture_frequency_fg_ms"];
  82. [keysToCache setObject:@(FPRConfigValueTypeInteger)
  83. forKey:@"fpr_session_gauge_cpu_capture_frequency_bg_ms"];
  84. [keysToCache setObject:@(FPRConfigValueTypeInteger)
  85. forKey:@"fpr_session_gauge_memory_capture_frequency_fg_ms"];
  86. [keysToCache setObject:@(FPRConfigValueTypeInteger)
  87. forKey:@"fpr_session_gauge_memory_capture_frequency_bg_ms"];
  88. [keysToCache setObject:@(FPRConfigValueTypeInteger) forKey:@"fpr_session_max_duration_min"];
  89. [keysToCache setObject:@(FPRConfigValueTypeInteger) forKey:@"fpr_prewarm_detection"];
  90. self.configKeys = [keysToCache copy];
  91. [self update];
  92. }
  93. return self;
  94. }
  95. - (void)update {
  96. // If a fetch is already happening, do not attempt a fetch.
  97. if (self.fetchInProgress) {
  98. return;
  99. }
  100. NSTimeInterval timeIntervalSinceLastFetch =
  101. [self.fprRemoteConfig.lastFetchTime timeIntervalSinceNow];
  102. NSTimeInterval timeSinceAppStart = [self.applicationStartTime timeIntervalSinceNow];
  103. if ((ABS(timeSinceAppStart) > self.appStartConfigFetchDelayInSeconds) &&
  104. (!self.fprRemoteConfig.lastFetchTime ||
  105. ABS(timeIntervalSinceLastFetch) > kFPRConfigFetchIntervalInSeconds)) {
  106. self.fetchInProgress = YES;
  107. [self.fprRemoteConfig
  108. fetchAndActivateWithCompletionHandler:^(FIRRemoteConfigFetchAndActivateStatus status,
  109. NSError *_Nullable error) {
  110. self.lastFetchStatus = self.fprRemoteConfig.lastFetchStatus;
  111. if (status == FIRRemoteConfigFetchAndActivateStatusError) {
  112. FPRLogError(kFPRConfigurationFetchFailure, @"Unable to fetch configurations.");
  113. } else {
  114. self.lastFetchedTime = self.fprRemoteConfig.lastFetchTime;
  115. // If a fetch was successful,
  116. // 1. Clear the old cache
  117. [self resetCache];
  118. // 2. Cache the new config values
  119. [self cacheConfigValues];
  120. }
  121. self.fetchInProgress = NO;
  122. }];
  123. } else if (self.fprRemoteConfig.lastFetchTime) {
  124. // Update the last fetched time to know that remote config fetch has happened in the past.
  125. self.lastFetchedTime = self.fprRemoteConfig.lastFetchTime;
  126. }
  127. }
  128. #pragma mark - Util methods.
  129. - (void)resetCache {
  130. [self.configKeys
  131. enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSNumber *valueType, BOOL *stop) {
  132. NSString *cacheKey = [NSString stringWithFormat:@"%@.%@", kFPRConfigPrefix, key];
  133. [self.userDefaults removeObjectForKey:cacheKey];
  134. }];
  135. }
  136. - (void)cacheConfigValues {
  137. [self.configKeys
  138. enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSNumber *valueType, BOOL *stop) {
  139. FIRRemoteConfigValue *rcValue = [self.fprRemoteConfig configValueForKey:key];
  140. // Cache only values that comes from remote.
  141. if (rcValue != nil && rcValue.source == FIRRemoteConfigSourceRemote) {
  142. FPRConfigValueType configValueType = [valueType integerValue];
  143. NSString *cacheKey = [NSString stringWithFormat:@"%@.%@", kFPRConfigPrefix, key];
  144. if (configValueType == FPRConfigValueTypeInteger) {
  145. NSInteger integerValue = [[rcValue numberValue] integerValue];
  146. [self.userDefaults setInteger:integerValue forKey:cacheKey];
  147. } else if (configValueType == FPRConfigValueTypeFloat) {
  148. float floatValue = [[rcValue numberValue] floatValue];
  149. [self.userDefaults setFloat:floatValue forKey:cacheKey];
  150. } else if (configValueType == FPRConfigValueTypeBool) {
  151. BOOL boolValue = [rcValue boolValue];
  152. [self.userDefaults setBool:boolValue forKey:cacheKey];
  153. } else if (configValueType == FPRConfigValueTypeString) {
  154. NSString *stringValue = [rcValue stringValue];
  155. [self.userDefaults setObject:stringValue forKey:cacheKey];
  156. }
  157. self.lastCachedTime = [NSDate date];
  158. }
  159. }];
  160. }
  161. - (id)cachedValueForConfigFlag:(NSString *)configFlag {
  162. // If the cached value is too old, return nil.
  163. if (ABS([self.lastFetchedTime timeIntervalSinceNow]) > 7 * ONE_DAY_SECONDS) {
  164. return nil;
  165. }
  166. NSString *cacheKey = [NSString stringWithFormat:@"%@.%@", kFPRConfigPrefix, configFlag];
  167. id cachedValueObject = [self.userDefaults objectForKey:cacheKey];
  168. return cachedValueObject;
  169. }
  170. #pragma mark - Config value fetch methods.
  171. - (NSString *)getStringValueForFlag:(NSString *)flagName defaultValue:(NSString *)defaultValue {
  172. id cachedValueObject = [self cachedValueForConfigFlag:flagName];
  173. if ([cachedValueObject isKindOfClass:[NSString class]]) {
  174. return (NSString *)cachedValueObject;
  175. }
  176. return defaultValue;
  177. }
  178. - (int)getIntValueForFlag:(NSString *)flagName defaultValue:(int)defaultValue {
  179. id cachedValueObject = [self cachedValueForConfigFlag:flagName];
  180. if (cachedValueObject) {
  181. return [cachedValueObject intValue];
  182. }
  183. return defaultValue;
  184. }
  185. - (float)getFloatValueForFlag:(NSString *)flagName defaultValue:(float)defaultValue {
  186. id cachedValueObject = [self cachedValueForConfigFlag:flagName];
  187. if (cachedValueObject) {
  188. return [cachedValueObject floatValue];
  189. }
  190. return defaultValue;
  191. }
  192. - (BOOL)getBoolValueForFlag:(NSString *)flagName defaultValue:(BOOL)defaultValue {
  193. id cachedValueObject = [self cachedValueForConfigFlag:flagName];
  194. if (cachedValueObject) {
  195. return [cachedValueObject boolValue];
  196. }
  197. return defaultValue;
  198. }
  199. #pragma mark - Configuration methods.
  200. - (int)logSourceWithDefaultValue:(int)logSource {
  201. return [self getIntValueForFlag:@"fpr_log_source" defaultValue:logSource];
  202. }
  203. - (BOOL)performanceSDKEnabledWithDefaultValue:(BOOL)sdkEnabled {
  204. /* Order of preference:
  205. * 1. If remote config fetch was a failure, return NO.
  206. * 2. If the fetch was successful, but RC does not have the value (not a remote value),
  207. * return YES.
  208. * 3. Else, use the value from RC.
  209. */
  210. if (self.lastFetchStatus == FIRRemoteConfigFetchStatusFailure) {
  211. return NO;
  212. }
  213. return [self getBoolValueForFlag:@"fpr_enabled" defaultValue:sdkEnabled];
  214. }
  215. - (NSSet<NSString *> *)sdkDisabledVersionsWithDefaultValue:(NSSet<NSString *> *)sdkVersions {
  216. NSMutableSet<NSString *> *disabledVersions = [[NSMutableSet<NSString *> alloc] init];
  217. NSString *sdkVersionsString = [[self getStringValueForFlag:@"fpr_disabled_ios_versions"
  218. defaultValue:@""]
  219. stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
  220. if (sdkVersionsString.length > 0) {
  221. NSArray<NSString *> *sdkVersionStrings = [sdkVersionsString componentsSeparatedByString:@";"];
  222. for (NSString *sdkVersionString in sdkVersionStrings) {
  223. NSString *trimmedString = [sdkVersionString
  224. stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
  225. if (trimmedString.length > 0) {
  226. [disabledVersions addObject:trimmedString];
  227. }
  228. }
  229. } else {
  230. return sdkVersions;
  231. }
  232. return [disabledVersions copy];
  233. }
  234. #pragma mark - Rate limiting flags
  235. - (int)rateLimitTimeDurationWithDefaultValue:(int)durationInSeconds {
  236. return [self getIntValueForFlag:@"fpr_rl_time_limit_sec" defaultValue:durationInSeconds];
  237. }
  238. - (int)rateLimitTraceCountInForegroundWithDefaultValue:(int)eventCount {
  239. return [self getIntValueForFlag:@"fpr_rl_trace_event_count_fg" defaultValue:eventCount];
  240. }
  241. - (int)rateLimitTraceCountInBackgroundWithDefaultValue:(int)eventCount {
  242. return [self getIntValueForFlag:@"fpr_rl_trace_event_count_bg" defaultValue:eventCount];
  243. }
  244. - (int)rateLimitNetworkRequestCountInForegroundWithDefaultValue:(int)eventCount {
  245. return [self getIntValueForFlag:@"fpr_rl_network_request_event_count_fg" defaultValue:eventCount];
  246. }
  247. - (int)rateLimitNetworkRequestCountInBackgroundWithDefaultValue:(int)eventCount {
  248. return [self getIntValueForFlag:@"fpr_rl_network_request_event_count_bg" defaultValue:eventCount];
  249. }
  250. #pragma mark - Sampling flags
  251. - (float)traceSamplingRateWithDefaultValue:(float)samplingRate {
  252. return [self getFloatValueForFlag:@"fpr_vc_trace_sampling_rate" defaultValue:samplingRate];
  253. }
  254. - (float)networkRequestSamplingRateWithDefaultValue:(float)samplingRate {
  255. return [self getFloatValueForFlag:@"fpr_vc_network_request_sampling_rate"
  256. defaultValue:samplingRate];
  257. }
  258. #pragma mark - Session flags
  259. - (float)sessionSamplingRateWithDefaultValue:(float)samplingRate {
  260. return [self getFloatValueForFlag:@"fpr_vc_session_sampling_rate" defaultValue:samplingRate];
  261. }
  262. - (int)sessionGaugeCPUCaptureFrequencyInForegroundWithDefaultValue:(int)defaultFrequency {
  263. return [self getIntValueForFlag:@"fpr_session_gauge_cpu_capture_frequency_fg_ms"
  264. defaultValue:defaultFrequency];
  265. }
  266. - (int)sessionGaugeCPUCaptureFrequencyInBackgroundWithDefaultValue:(int)defaultFrequency {
  267. return [self getIntValueForFlag:@"fpr_session_gauge_cpu_capture_frequency_bg_ms"
  268. defaultValue:defaultFrequency];
  269. }
  270. - (int)sessionGaugeMemoryCaptureFrequencyInForegroundWithDefaultValue:(int)defaultFrequency {
  271. return [self getIntValueForFlag:@"fpr_session_gauge_memory_capture_frequency_fg_ms"
  272. defaultValue:defaultFrequency];
  273. }
  274. - (int)sessionGaugeMemoryCaptureFrequencyInBackgroundWithDefaultValue:(int)defaultFrequency {
  275. return [self getIntValueForFlag:@"fpr_session_gauge_memory_capture_frequency_bg_ms"
  276. defaultValue:defaultFrequency];
  277. }
  278. - (int)sessionMaxDurationWithDefaultValue:(int)maxDurationInMinutes {
  279. return [self getIntValueForFlag:@"fpr_session_max_duration_min"
  280. defaultValue:maxDurationInMinutes];
  281. }
  282. @end