FPRRemoteConfigFlags.m 14 KB

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