RCNConfigSettings.m 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. /*
  2. * Copyright 2019 Google
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #import "FirebaseRemoteConfig/Sources/Private/RCNConfigSettings.h"
  17. #import "FirebaseRemoteConfig/Sources/RCNConfigConstants.h"
  18. #import "FirebaseRemoteConfig/Sources/RCNConfigDBManager.h"
  19. #import "FirebaseRemoteConfig/Sources/RCNConfigValue_Internal.h"
  20. #import "FirebaseRemoteConfig/Sources/RCNDevice.h"
  21. #import "FirebaseRemoteConfig/Sources/RCNUserDefaultsManager.h"
  22. #import <GoogleUtilities/GULAppEnvironmentUtil.h>
  23. #import "FirebaseCore/Sources/Private/FirebaseCoreInternal.h"
  24. static NSString *const kRCNGroupPrefix = @"frc.group.";
  25. static NSString *const kRCNUserDefaultsKeyNamelastETag = @"lastETag";
  26. static NSString *const kRCNUserDefaultsKeyNameLastSuccessfulFetchTime = @"lastSuccessfulFetchTime";
  27. static const int kRCNExponentialBackoffMinimumInterval = 60 * 2; // 2 mins.
  28. static const int kRCNExponentialBackoffMaximumInterval = 60 * 60 * 4; // 4 hours.
  29. @interface RCNConfigSettings () {
  30. /// A list of successful fetch timestamps in seconds.
  31. NSMutableArray *_successFetchTimes;
  32. /// A list of failed fetch timestamps in seconds.
  33. NSMutableArray *_failureFetchTimes;
  34. /// Device conditions since last successful fetch from the backend. Device conditions including
  35. /// app
  36. /// version, iOS version, device localte, language, GMP project ID and Game project ID. Used for
  37. /// determing whether to throttle.
  38. NSMutableDictionary *_deviceContext;
  39. /// Custom variables (aka App context digest). This is the pending custom variables request before
  40. /// fetching.
  41. NSMutableDictionary *_customVariables;
  42. /// Cached internal metadata from internal metadata table. It contains customized information such
  43. /// as HTTP connection timeout, HTTP read timeout, success/failure throttling rate and time
  44. /// interval. Client has the default value of each parameters, they are only saved in
  45. /// internalMetadata if they have been customize by developers.
  46. NSMutableDictionary *_internalMetadata;
  47. /// Last fetch status.
  48. FIRRemoteConfigFetchStatus _lastFetchStatus;
  49. /// Last fetch Error.
  50. FIRRemoteConfigError _lastFetchError;
  51. /// The time of last apply timestamp.
  52. NSTimeInterval _lastApplyTimeInterval;
  53. /// The time of last setDefaults timestamp.
  54. NSTimeInterval _lastSetDefaultsTimeInterval;
  55. /// The database manager.
  56. RCNConfigDBManager *_DBManager;
  57. // The namespace for this instance.
  58. NSString *_FIRNamespace;
  59. // The Google App ID of the configured FIRApp.
  60. NSString *_googleAppID;
  61. /// The user defaults manager scoped to this RC instance of FIRApp and namespace.
  62. RCNUserDefaultsManager *_userDefaultsManager;
  63. /// The timestamp of last eTag update.
  64. NSTimeInterval _lastETagUpdateTime;
  65. }
  66. @end
  67. @implementation RCNConfigSettings
  68. - (instancetype)initWithDatabaseManager:(RCNConfigDBManager *)manager
  69. namespace:(NSString *)FIRNamespace
  70. firebaseAppName:(NSString *)appName
  71. googleAppID:(NSString *)googleAppID {
  72. self = [super init];
  73. if (self) {
  74. _FIRNamespace = FIRNamespace;
  75. _googleAppID = googleAppID;
  76. _bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];
  77. if (!_bundleIdentifier) {
  78. FIRLogNotice(kFIRLoggerRemoteConfig, @"I-RCN000038",
  79. @"Main bundle identifier is missing. Remote Config might not work properly.");
  80. _bundleIdentifier = @"";
  81. }
  82. _minimumFetchInterval = RCNDefaultMinimumFetchInterval;
  83. _deviceContext = [[NSMutableDictionary alloc] init];
  84. _customVariables = [[NSMutableDictionary alloc] init];
  85. _successFetchTimes = [[NSMutableArray alloc] init];
  86. _failureFetchTimes = [[NSMutableArray alloc] init];
  87. _DBManager = manager;
  88. _internalMetadata = [[_DBManager loadInternalMetadataTable] mutableCopy];
  89. if (!_internalMetadata) {
  90. _internalMetadata = [[NSMutableDictionary alloc] init];
  91. }
  92. _userDefaultsManager = [[RCNUserDefaultsManager alloc] initWithAppName:appName
  93. bundleID:_bundleIdentifier
  94. namespace:_FIRNamespace];
  95. // Check if the config database is new. If so, clear the configs saved in userDefaults.
  96. if ([_DBManager isNewDatabase]) {
  97. FIRLogNotice(kFIRLoggerRemoteConfig, @"I-RCN000072",
  98. @"New config database created. Resetting user defaults.");
  99. [_userDefaultsManager resetUserDefaults];
  100. }
  101. _isFetchInProgress = NO;
  102. }
  103. return self;
  104. }
  105. #pragma mark - read from / update userDefaults
  106. - (NSString *)lastETag {
  107. return [_userDefaultsManager lastETag];
  108. }
  109. - (void)setLastETag:(NSString *)lastETag {
  110. [self setLastETagUpdateTime:[[NSDate date] timeIntervalSince1970]];
  111. [_userDefaultsManager setLastETag:lastETag];
  112. }
  113. - (void)setLastETagUpdateTime:(NSTimeInterval)lastETagUpdateTime {
  114. [_userDefaultsManager setLastETagUpdateTime:lastETagUpdateTime];
  115. }
  116. - (NSTimeInterval)lastFetchTimeInterval {
  117. return _userDefaultsManager.lastFetchTime;
  118. }
  119. - (NSTimeInterval)lastETagUpdateTime {
  120. return _userDefaultsManager.lastETagUpdateTime;
  121. }
  122. // TODO: Update logic for app extensions as required.
  123. - (void)updateLastFetchTimeInterval:(NSTimeInterval)lastFetchTimeInterval {
  124. _userDefaultsManager.lastFetchTime = lastFetchTimeInterval;
  125. }
  126. #pragma mark - load from DB
  127. - (NSDictionary *)loadConfigFromMetadataTable {
  128. NSDictionary *metadata = [[_DBManager loadMetadataWithBundleIdentifier:_bundleIdentifier
  129. namespace:_FIRNamespace] copy];
  130. if (metadata) {
  131. // TODO: Remove (all metadata in general) once ready to
  132. // migrate to user defaults completely.
  133. if (metadata[RCNKeyDeviceContext]) {
  134. self->_deviceContext = [metadata[RCNKeyDeviceContext] mutableCopy];
  135. }
  136. if (metadata[RCNKeyAppContext]) {
  137. self->_customVariables = [metadata[RCNKeyAppContext] mutableCopy];
  138. }
  139. if (metadata[RCNKeySuccessFetchTime]) {
  140. self->_successFetchTimes = [metadata[RCNKeySuccessFetchTime] mutableCopy];
  141. }
  142. if (metadata[RCNKeyFailureFetchTime]) {
  143. self->_failureFetchTimes = [metadata[RCNKeyFailureFetchTime] mutableCopy];
  144. }
  145. if (metadata[RCNKeyLastFetchStatus]) {
  146. self->_lastFetchStatus =
  147. (FIRRemoteConfigFetchStatus)[metadata[RCNKeyLastFetchStatus] intValue];
  148. }
  149. if (metadata[RCNKeyLastFetchError]) {
  150. self->_lastFetchError = (FIRRemoteConfigError)[metadata[RCNKeyLastFetchError] intValue];
  151. }
  152. if (metadata[RCNKeyLastApplyTime]) {
  153. self->_lastApplyTimeInterval = [metadata[RCNKeyLastApplyTime] doubleValue];
  154. }
  155. if (metadata[RCNKeyLastFetchStatus]) {
  156. self->_lastSetDefaultsTimeInterval = [metadata[RCNKeyLastSetDefaultsTime] doubleValue];
  157. }
  158. }
  159. return metadata;
  160. }
  161. #pragma mark - update DB/cached
  162. // Update internal metadata content to cache and DB.
  163. - (void)updateInternalContentWithResponse:(NSDictionary *)response {
  164. // Remove all the keys with current pakcage name.
  165. [_DBManager deleteRecordWithBundleIdentifier:_bundleIdentifier
  166. namespace:_FIRNamespace
  167. isInternalDB:YES];
  168. for (NSString *key in _internalMetadata.allKeys) {
  169. if ([key hasPrefix:_bundleIdentifier]) {
  170. [_internalMetadata removeObjectForKey:key];
  171. }
  172. }
  173. for (NSString *entry in response) {
  174. NSData *val = [response[entry] dataUsingEncoding:NSUTF8StringEncoding];
  175. NSArray *values = @[ entry, val ];
  176. _internalMetadata[entry] = response[entry];
  177. [self updateInternalMetadataTableWithValues:values];
  178. }
  179. }
  180. - (void)updateInternalMetadataTableWithValues:(NSArray *)values {
  181. [_DBManager insertInternalMetadataTableWithValues:values completionHandler:nil];
  182. }
  183. /// If the last fetch was not successful, update the (exponential backoff) period that we wait until
  184. /// fetching again. Any subsequent fetch requests will be checked and allowed only if past this
  185. /// throttle end time.
  186. - (void)updateExponentialBackoffTime {
  187. // If not in exponential backoff mode, reset the retry interval.
  188. if (_lastFetchStatus == FIRRemoteConfigFetchStatusSuccess) {
  189. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000057",
  190. @"Throttling: Entering exponential backoff mode.");
  191. _exponentialBackoffRetryInterval = kRCNExponentialBackoffMinimumInterval;
  192. } else {
  193. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000057",
  194. @"Throttling: Updating throttling interval.");
  195. // Double the retry interval until we hit the truncated exponential backoff. More info here:
  196. // https://cloud.google.com/storage/docs/exponential-backoff
  197. _exponentialBackoffRetryInterval =
  198. ((_exponentialBackoffRetryInterval * 2) < kRCNExponentialBackoffMaximumInterval)
  199. ? _exponentialBackoffRetryInterval * 2
  200. : _exponentialBackoffRetryInterval;
  201. }
  202. // Randomize the next retry interval.
  203. int randomPlusMinusInterval = ((arc4random() % 2) == 0) ? -1 : 1;
  204. NSTimeInterval randomizedRetryInterval =
  205. _exponentialBackoffRetryInterval +
  206. (0.5 * _exponentialBackoffRetryInterval * randomPlusMinusInterval);
  207. _exponentialBackoffThrottleEndTime =
  208. [[NSDate date] timeIntervalSince1970] + randomizedRetryInterval;
  209. }
  210. - (void)updateMetadataWithFetchSuccessStatus:(BOOL)fetchSuccess {
  211. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000056", @"Updating metadata with fetch result.");
  212. [self updateFetchTimeWithSuccessFetch:fetchSuccess];
  213. _lastFetchStatus =
  214. fetchSuccess ? FIRRemoteConfigFetchStatusSuccess : FIRRemoteConfigFetchStatusFailure;
  215. _lastFetchError = fetchSuccess ? FIRRemoteConfigErrorUnknown : FIRRemoteConfigErrorInternalError;
  216. if (fetchSuccess) {
  217. [self updateLastFetchTimeInterval:[[NSDate date] timeIntervalSince1970]];
  218. // Note: We expect the googleAppID to always be available.
  219. _deviceContext = FIRRemoteConfigDeviceContextWithProjectIdentifier(_googleAppID);
  220. }
  221. [self updateMetadataTable];
  222. }
  223. - (void)updateFetchTimeWithSuccessFetch:(BOOL)isSuccessfulFetch {
  224. NSTimeInterval epochTimeInterval = [[NSDate date] timeIntervalSince1970];
  225. if (isSuccessfulFetch) {
  226. [_successFetchTimes addObject:@(epochTimeInterval)];
  227. } else {
  228. [_failureFetchTimes addObject:@(epochTimeInterval)];
  229. }
  230. }
  231. - (void)updateMetadataTable {
  232. [_DBManager deleteRecordWithBundleIdentifier:_bundleIdentifier
  233. namespace:_FIRNamespace
  234. isInternalDB:NO];
  235. NSError *error;
  236. // Objects to be serialized cannot be invalid.
  237. if (!_bundleIdentifier) {
  238. return;
  239. }
  240. if (![NSJSONSerialization isValidJSONObject:_customVariables]) {
  241. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000028",
  242. @"Invalid custom variables to be serialized.");
  243. return;
  244. }
  245. if (![NSJSONSerialization isValidJSONObject:_deviceContext]) {
  246. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000029",
  247. @"Invalid device context to be serialized.");
  248. return;
  249. }
  250. if (![NSJSONSerialization isValidJSONObject:_successFetchTimes]) {
  251. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000031",
  252. @"Invalid success fetch times to be serialized.");
  253. return;
  254. }
  255. if (![NSJSONSerialization isValidJSONObject:_failureFetchTimes]) {
  256. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000032",
  257. @"Invalid failure fetch times to be serialized.");
  258. return;
  259. }
  260. NSData *serializedAppContext = [NSJSONSerialization dataWithJSONObject:_customVariables
  261. options:NSJSONWritingPrettyPrinted
  262. error:&error];
  263. NSData *serializedDeviceContext =
  264. [NSJSONSerialization dataWithJSONObject:_deviceContext
  265. options:NSJSONWritingPrettyPrinted
  266. error:&error];
  267. // The digestPerNamespace is not used and only meant for backwards DB compatibility.
  268. NSData *serializedDigestPerNamespace =
  269. [NSJSONSerialization dataWithJSONObject:@{} options:NSJSONWritingPrettyPrinted error:&error];
  270. NSData *serializedSuccessTime = [NSJSONSerialization dataWithJSONObject:_successFetchTimes
  271. options:NSJSONWritingPrettyPrinted
  272. error:&error];
  273. NSData *serializedFailureTime = [NSJSONSerialization dataWithJSONObject:_failureFetchTimes
  274. options:NSJSONWritingPrettyPrinted
  275. error:&error];
  276. if (!serializedDigestPerNamespace || !serializedDeviceContext || !serializedAppContext ||
  277. !serializedSuccessTime || !serializedFailureTime) {
  278. return;
  279. }
  280. NSDictionary *columnNameToValue = @{
  281. RCNKeyBundleIdentifier : _bundleIdentifier,
  282. RCNKeyNamespace : _FIRNamespace,
  283. RCNKeyFetchTime : @(self.lastFetchTimeInterval),
  284. RCNKeyDigestPerNamespace : serializedDigestPerNamespace,
  285. RCNKeyDeviceContext : serializedDeviceContext,
  286. RCNKeyAppContext : serializedAppContext,
  287. RCNKeySuccessFetchTime : serializedSuccessTime,
  288. RCNKeyFailureFetchTime : serializedFailureTime,
  289. RCNKeyLastFetchStatus : [NSString stringWithFormat:@"%ld", (long)_lastFetchStatus],
  290. RCNKeyLastFetchError : [NSString stringWithFormat:@"%ld", (long)_lastFetchError],
  291. RCNKeyLastApplyTime : @(_lastApplyTimeInterval),
  292. RCNKeyLastSetDefaultsTime : @(_lastSetDefaultsTimeInterval)
  293. };
  294. [_DBManager insertMetadataTableWithValues:columnNameToValue completionHandler:nil];
  295. }
  296. #pragma mark - fetch request
  297. /// Returns a fetch request with the latest device and config change.
  298. /// Whenever user issues a fetch api call, collect the latest request.
  299. - (NSString *)nextRequestWithUserProperties:(NSDictionary *)userProperties {
  300. // Note: We only set user properties as mentioned in the new REST API Design doc
  301. NSString *ret = [NSString stringWithFormat:@"{"];
  302. ret = [ret stringByAppendingString:[NSString stringWithFormat:@"app_instance_id:'%@'",
  303. _configInstallationsIdentifier]];
  304. ret = [ret stringByAppendingString:[NSString stringWithFormat:@", app_instance_id_token:'%@'",
  305. _configInstallationsToken]];
  306. ret = [ret stringByAppendingString:[NSString stringWithFormat:@", app_id:'%@'", _googleAppID]];
  307. ret = [ret stringByAppendingString:[NSString stringWithFormat:@", country_code:'%@'",
  308. FIRRemoteConfigDeviceCountry()]];
  309. ret = [ret stringByAppendingString:[NSString stringWithFormat:@", language_code:'%@'",
  310. FIRRemoteConfigDeviceLocale()]];
  311. ret = [ret
  312. stringByAppendingString:[NSString stringWithFormat:@", platform_version:'%@'",
  313. [GULAppEnvironmentUtil systemVersion]]];
  314. ret = [ret stringByAppendingString:[NSString stringWithFormat:@", time_zone:'%@'",
  315. FIRRemoteConfigTimezone()]];
  316. ret = [ret stringByAppendingString:[NSString stringWithFormat:@", package_name:'%@'",
  317. _bundleIdentifier]];
  318. ret = [ret stringByAppendingString:[NSString stringWithFormat:@", app_version:'%@'",
  319. FIRRemoteConfigAppVersion()]];
  320. ret = [ret stringByAppendingString:[NSString stringWithFormat:@", app_build:'%@'",
  321. FIRRemoteConfigAppBuildVersion()]];
  322. ret = [ret stringByAppendingString:[NSString stringWithFormat:@", sdk_version:'%@'",
  323. FIRRemoteConfigPodVersion()]];
  324. if (userProperties && userProperties.count > 0) {
  325. NSError *error;
  326. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:userProperties
  327. options:0
  328. error:&error];
  329. if (!error) {
  330. ret = [ret
  331. stringByAppendingString:[NSString
  332. stringWithFormat:@", analytics_user_properties:%@",
  333. [[NSString alloc]
  334. initWithData:jsonData
  335. encoding:NSUTF8StringEncoding]]];
  336. }
  337. }
  338. ret = [ret stringByAppendingString:@"}"];
  339. return ret;
  340. }
  341. #pragma mark - getter/setter
  342. - (void)setLastFetchError:(FIRRemoteConfigError)lastFetchError {
  343. if (_lastFetchError != lastFetchError) {
  344. _lastFetchError = lastFetchError;
  345. [_DBManager updateMetadataWithOption:RCNUpdateOptionFetchStatus
  346. namespace:_FIRNamespace
  347. values:@[ @(_lastFetchStatus), @(_lastFetchError) ]
  348. completionHandler:nil];
  349. }
  350. }
  351. - (NSArray *)successFetchTimes {
  352. return [_successFetchTimes copy];
  353. }
  354. - (NSArray *)failureFetchTimes {
  355. return [_failureFetchTimes copy];
  356. }
  357. - (NSDictionary *)customVariables {
  358. return [_customVariables copy];
  359. }
  360. - (NSDictionary *)internalMetadata {
  361. return [_internalMetadata copy];
  362. }
  363. - (NSDictionary *)deviceContext {
  364. return [_deviceContext copy];
  365. }
  366. - (void)setCustomVariables:(NSDictionary *)customVariables {
  367. _customVariables = [[NSMutableDictionary alloc] initWithDictionary:customVariables];
  368. [self updateMetadataTable];
  369. }
  370. - (void)setMinimumFetchInterval:(NSTimeInterval)minimumFetchInterval {
  371. if (minimumFetchInterval < 0) {
  372. _minimumFetchInterval = 0;
  373. } else {
  374. _minimumFetchInterval = minimumFetchInterval;
  375. }
  376. }
  377. - (void)setFetchTimeout:(NSTimeInterval)fetchTimeout {
  378. if (fetchTimeout <= 0) {
  379. _fetchTimeout = RCNHTTPDefaultConnectionTimeout;
  380. } else {
  381. _fetchTimeout = fetchTimeout;
  382. }
  383. }
  384. - (void)setLastApplyTimeInterval:(NSTimeInterval)lastApplyTimestamp {
  385. _lastApplyTimeInterval = lastApplyTimestamp;
  386. [_DBManager updateMetadataWithOption:RCNUpdateOptionApplyTime
  387. namespace:_FIRNamespace
  388. values:@[ @(lastApplyTimestamp) ]
  389. completionHandler:nil];
  390. }
  391. - (void)setLastSetDefaultsTimeInterval:(NSTimeInterval)lastSetDefaultsTimestamp {
  392. _lastSetDefaultsTimeInterval = lastSetDefaultsTimestamp;
  393. [_DBManager updateMetadataWithOption:RCNUpdateOptionDefaultTime
  394. namespace:_FIRNamespace
  395. values:@[ @(lastSetDefaultsTimestamp) ]
  396. completionHandler:nil];
  397. }
  398. #pragma mark Throttling
  399. - (BOOL)hasMinimumFetchIntervalElapsed:(NSTimeInterval)minimumFetchInterval {
  400. if (self.lastFetchTimeInterval == 0) return YES;
  401. // Check if last config fetch is within minimum fetch interval in seconds.
  402. NSTimeInterval diffInSeconds = [[NSDate date] timeIntervalSince1970] - self.lastFetchTimeInterval;
  403. return diffInSeconds > minimumFetchInterval;
  404. }
  405. - (BOOL)shouldThrottle {
  406. NSTimeInterval now = [[NSDate date] timeIntervalSince1970];
  407. return ((self.lastFetchTimeInterval > 0) &&
  408. (_lastFetchStatus != FIRRemoteConfigFetchStatusSuccess) &&
  409. (_exponentialBackoffThrottleEndTime - now > 0));
  410. }
  411. @end