FPRRemoteConfigFlags.m 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  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. self.configKeys = [keysToCache copy];
  90. [self update];
  91. }
  92. return self;
  93. }
  94. - (void)update {
  95. // If a fetch is already happening, do not attempt a fetch.
  96. if (self.fetchInProgress) {
  97. return;
  98. }
  99. NSTimeInterval timeIntervalSinceLastFetch =
  100. [self.fprRemoteConfig.lastFetchTime timeIntervalSinceNow];
  101. NSTimeInterval timeSinceAppStart = [self.applicationStartTime timeIntervalSinceNow];
  102. if ((ABS(timeSinceAppStart) > self.appStartConfigFetchDelayInSeconds) &&
  103. (!self.fprRemoteConfig.lastFetchTime ||
  104. ABS(timeIntervalSinceLastFetch) > kFPRConfigFetchIntervalInSeconds)) {
  105. self.fetchInProgress = YES;
  106. [self.fprRemoteConfig
  107. fetchAndActivateWithCompletionHandler:^(FIRRemoteConfigFetchAndActivateStatus status,
  108. NSError *_Nullable error) {
  109. self.lastFetchStatus = self.fprRemoteConfig.lastFetchStatus;
  110. if (status == FIRRemoteConfigFetchAndActivateStatusError) {
  111. FPRLogError(kFPRConfigurationFetchFailure, @"Unable to fetch configurations.");
  112. } else {
  113. self.lastFetchedTime = self.fprRemoteConfig.lastFetchTime;
  114. // If a fetch was successful,
  115. // 1. Clear the old cache
  116. [self resetCache];
  117. // 2. Cache the new config values
  118. [self cacheConfigValues];
  119. }
  120. self.fetchInProgress = NO;
  121. }];
  122. } else if (self.fprRemoteConfig.lastFetchTime) {
  123. // Update the last fetched time to know that remote config fetch has happened in the past.
  124. self.lastFetchedTime = self.fprRemoteConfig.lastFetchTime;
  125. }
  126. }
  127. #pragma mark - Util methods.
  128. - (void)resetCache {
  129. [self.configKeys
  130. enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSNumber *valueType, BOOL *stop) {
  131. NSString *cacheKey = [NSString stringWithFormat:@"%@.%@", kFPRConfigPrefix, key];
  132. [self.userDefaults removeObjectForKey:cacheKey];
  133. }];
  134. }
  135. - (void)cacheConfigValues {
  136. [self.configKeys
  137. enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSNumber *valueType, BOOL *stop) {
  138. FIRRemoteConfigValue *rcValue = [self.fprRemoteConfig configValueForKey:key];
  139. // Cache only values that comes from remote.
  140. if (rcValue != nil && rcValue.source == FIRRemoteConfigSourceRemote) {
  141. FPRConfigValueType configValueType = [valueType integerValue];
  142. NSString *cacheKey = [NSString stringWithFormat:@"%@.%@", kFPRConfigPrefix, key];
  143. if (configValueType == FPRConfigValueTypeInteger) {
  144. NSInteger integerValue = [[rcValue numberValue] integerValue];
  145. [self.userDefaults setInteger:integerValue forKey:cacheKey];
  146. } else if (configValueType == FPRConfigValueTypeFloat) {
  147. float floatValue = [[rcValue numberValue] floatValue];
  148. [self.userDefaults setFloat:floatValue forKey:cacheKey];
  149. } else if (configValueType == FPRConfigValueTypeBool) {
  150. BOOL boolValue = [rcValue boolValue];
  151. [self.userDefaults setBool:boolValue forKey:cacheKey];
  152. } else if (configValueType == FPRConfigValueTypeString) {
  153. NSString *stringValue = [rcValue stringValue];
  154. [self.userDefaults setObject:stringValue forKey:cacheKey];
  155. }
  156. self.lastCachedTime = [NSDate date];
  157. }
  158. }];
  159. }
  160. - (id)cachedValueForConfigFlag:(NSString *)configFlag {
  161. // If the cached value is too old, return nil.
  162. if (ABS([self.lastFetchedTime timeIntervalSinceNow]) > 7 * ONE_DAY_SECONDS) {
  163. return nil;
  164. }
  165. NSString *cacheKey = [NSString stringWithFormat:@"%@.%@", kFPRConfigPrefix, configFlag];
  166. id cachedValueObject = [self.userDefaults objectForKey:cacheKey];
  167. return cachedValueObject;
  168. }
  169. #pragma mark - Config value fetch methods.
  170. - (NSString *)getStringValueForFlag:(NSString *)flagName defaultValue:(NSString *)defaultValue {
  171. id cachedValueObject = [self cachedValueForConfigFlag:flagName];
  172. if ([cachedValueObject isKindOfClass:[NSString class]]) {
  173. return (NSString *)cachedValueObject;
  174. }
  175. return defaultValue;
  176. }
  177. - (int)getIntValueForFlag:(NSString *)flagName defaultValue:(int)defaultValue {
  178. id cachedValueObject = [self cachedValueForConfigFlag:flagName];
  179. if (cachedValueObject) {
  180. return [cachedValueObject intValue];
  181. }
  182. return defaultValue;
  183. }
  184. - (float)getFloatValueForFlag:(NSString *)flagName defaultValue:(float)defaultValue {
  185. id cachedValueObject = [self cachedValueForConfigFlag:flagName];
  186. if (cachedValueObject) {
  187. return [cachedValueObject floatValue];
  188. }
  189. return defaultValue;
  190. }
  191. - (BOOL)getBoolValueForFlag:(NSString *)flagName defaultValue:(BOOL)defaultValue {
  192. id cachedValueObject = [self cachedValueForConfigFlag:flagName];
  193. if (cachedValueObject) {
  194. return [cachedValueObject boolValue];
  195. }
  196. return defaultValue;
  197. }
  198. #pragma mark - Configuration methods.
  199. - (int)logSourceWithDefaultValue:(int)logSource {
  200. return [self getIntValueForFlag:@"fpr_log_source" defaultValue:logSource];
  201. }
  202. - (BOOL)performanceSDKEnabledWithDefaultValue:(BOOL)sdkEnabled {
  203. /* Order of preference:
  204. * 1. If remote config fetch was a failure, return NO.
  205. * 2. If the fetch was successful, but RC does not have the value (not a remote value),
  206. * return YES.
  207. * 3. Else, use the value from RC.
  208. */
  209. if (self.lastFetchStatus == FIRRemoteConfigFetchStatusFailure) {
  210. return NO;
  211. }
  212. return [self getBoolValueForFlag:@"fpr_enabled" defaultValue:sdkEnabled];
  213. }
  214. - (NSSet<NSString *> *)sdkDisabledVersionsWithDefaultValue:(NSSet<NSString *> *)sdkVersions {
  215. NSMutableSet<NSString *> *disabledVersions = [[NSMutableSet<NSString *> alloc] init];
  216. NSString *sdkVersionsString = [[self getStringValueForFlag:@"fpr_disabled_ios_versions"
  217. defaultValue:@""]
  218. stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
  219. if (sdkVersionsString.length > 0) {
  220. NSArray<NSString *> *sdkVersionStrings = [sdkVersionsString componentsSeparatedByString:@";"];
  221. for (NSString *sdkVersionString in sdkVersionStrings) {
  222. NSString *trimmedString = [sdkVersionString
  223. stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
  224. if (trimmedString.length > 0) {
  225. [disabledVersions addObject:trimmedString];
  226. }
  227. }
  228. } else {
  229. return sdkVersions;
  230. }
  231. return [disabledVersions copy];
  232. }
  233. #pragma mark - Rate limiting flags
  234. - (int)rateLimitTimeDurationWithDefaultValue:(int)durationInSeconds {
  235. return [self getIntValueForFlag:@"fpr_rl_time_limit_sec" defaultValue:durationInSeconds];
  236. }
  237. - (int)rateLimitTraceCountInForegroundWithDefaultValue:(int)eventCount {
  238. return [self getIntValueForFlag:@"fpr_rl_trace_event_count_fg" defaultValue:eventCount];
  239. }
  240. - (int)rateLimitTraceCountInBackgroundWithDefaultValue:(int)eventCount {
  241. return [self getIntValueForFlag:@"fpr_rl_trace_event_count_bg" defaultValue:eventCount];
  242. }
  243. - (int)rateLimitNetworkRequestCountInForegroundWithDefaultValue:(int)eventCount {
  244. return [self getIntValueForFlag:@"fpr_rl_network_request_event_count_fg" defaultValue:eventCount];
  245. }
  246. - (int)rateLimitNetworkRequestCountInBackgroundWithDefaultValue:(int)eventCount {
  247. return [self getIntValueForFlag:@"fpr_rl_network_request_event_count_bg" defaultValue:eventCount];
  248. }
  249. #pragma mark - Sampling flags
  250. - (float)traceSamplingRateWithDefaultValue:(float)samplingRate {
  251. return [self getFloatValueForFlag:@"fpr_vc_trace_sampling_rate" defaultValue:samplingRate];
  252. }
  253. - (float)networkRequestSamplingRateWithDefaultValue:(float)samplingRate {
  254. return [self getFloatValueForFlag:@"fpr_vc_network_request_sampling_rate"
  255. defaultValue:samplingRate];
  256. }
  257. #pragma mark - Session flags
  258. - (float)sessionSamplingRateWithDefaultValue:(float)samplingRate {
  259. return [self getFloatValueForFlag:@"fpr_vc_session_sampling_rate" defaultValue:samplingRate];
  260. }
  261. - (int)sessionGaugeCPUCaptureFrequencyInForegroundWithDefaultValue:(int)defaultFrequency {
  262. return [self getIntValueForFlag:@"fpr_session_gauge_cpu_capture_frequency_fg_ms"
  263. defaultValue:defaultFrequency];
  264. }
  265. - (int)sessionGaugeCPUCaptureFrequencyInBackgroundWithDefaultValue:(int)defaultFrequency {
  266. return [self getIntValueForFlag:@"fpr_session_gauge_cpu_capture_frequency_bg_ms"
  267. defaultValue:defaultFrequency];
  268. }
  269. - (int)sessionGaugeMemoryCaptureFrequencyInForegroundWithDefaultValue:(int)defaultFrequency {
  270. return [self getIntValueForFlag:@"fpr_session_gauge_memory_capture_frequency_fg_ms"
  271. defaultValue:defaultFrequency];
  272. }
  273. - (int)sessionGaugeMemoryCaptureFrequencyInBackgroundWithDefaultValue:(int)defaultFrequency {
  274. return [self getIntValueForFlag:@"fpr_session_gauge_memory_capture_frequency_bg_ms"
  275. defaultValue:defaultFrequency];
  276. }
  277. - (int)sessionMaxDurationWithDefaultValue:(int)maxDurationInMinutes {
  278. return [self getIntValueForFlag:@"fpr_session_max_duration_min"
  279. defaultValue:maxDurationInMinutes];
  280. }
  281. @end