FPRRemoteConfigFlags.m 14 KB

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