RCNConfigSettings.m 23 KB

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