FPRRemoteConfigFlags.m 13 KB

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