RCNConfigSettings.m 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  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. if (!fetchSuccess) {
  213. [self updateExponentialBackoffTime];
  214. }
  215. [self updateFetchTimeWithSuccessFetch:fetchSuccess];
  216. _lastFetchStatus =
  217. fetchSuccess ? FIRRemoteConfigFetchStatusSuccess : FIRRemoteConfigFetchStatusFailure;
  218. _lastFetchError = fetchSuccess ? FIRRemoteConfigErrorUnknown : FIRRemoteConfigErrorInternalError;
  219. if (fetchSuccess) {
  220. [self updateLastFetchTimeInterval:[[NSDate date] timeIntervalSince1970]];
  221. // Note: We expect the googleAppID to always be available.
  222. _deviceContext = FIRRemoteConfigDeviceContextWithProjectIdentifier(_googleAppID);
  223. }
  224. [self updateMetadataTable];
  225. }
  226. - (void)updateFetchTimeWithSuccessFetch:(BOOL)isSuccessfulFetch {
  227. NSTimeInterval epochTimeInterval = [[NSDate date] timeIntervalSince1970];
  228. if (isSuccessfulFetch) {
  229. [_successFetchTimes addObject:@(epochTimeInterval)];
  230. } else {
  231. [_failureFetchTimes addObject:@(epochTimeInterval)];
  232. }
  233. }
  234. - (void)updateMetadataTable {
  235. [_DBManager deleteRecordWithBundleIdentifier:_bundleIdentifier
  236. namespace:_FIRNamespace
  237. isInternalDB:NO];
  238. NSError *error;
  239. // Objects to be serialized cannot be invalid.
  240. if (!_bundleIdentifier) {
  241. return;
  242. }
  243. if (![NSJSONSerialization isValidJSONObject:_customVariables]) {
  244. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000028",
  245. @"Invalid custom variables to be serialized.");
  246. return;
  247. }
  248. if (![NSJSONSerialization isValidJSONObject:_deviceContext]) {
  249. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000029",
  250. @"Invalid device context to be serialized.");
  251. return;
  252. }
  253. if (![NSJSONSerialization isValidJSONObject:_successFetchTimes]) {
  254. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000031",
  255. @"Invalid success fetch times to be serialized.");
  256. return;
  257. }
  258. if (![NSJSONSerialization isValidJSONObject:_failureFetchTimes]) {
  259. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000032",
  260. @"Invalid failure fetch times to be serialized.");
  261. return;
  262. }
  263. NSData *serializedAppContext = [NSJSONSerialization dataWithJSONObject:_customVariables
  264. options:NSJSONWritingPrettyPrinted
  265. error:&error];
  266. NSData *serializedDeviceContext =
  267. [NSJSONSerialization dataWithJSONObject:_deviceContext
  268. options:NSJSONWritingPrettyPrinted
  269. error:&error];
  270. // The digestPerNamespace is not used and only meant for backwards DB compatibility.
  271. NSData *serializedDigestPerNamespace =
  272. [NSJSONSerialization dataWithJSONObject:@{} options:NSJSONWritingPrettyPrinted error:&error];
  273. NSData *serializedSuccessTime = [NSJSONSerialization dataWithJSONObject:_successFetchTimes
  274. options:NSJSONWritingPrettyPrinted
  275. error:&error];
  276. NSData *serializedFailureTime = [NSJSONSerialization dataWithJSONObject:_failureFetchTimes
  277. options:NSJSONWritingPrettyPrinted
  278. error:&error];
  279. if (!serializedDigestPerNamespace || !serializedDeviceContext || !serializedAppContext ||
  280. !serializedSuccessTime || !serializedFailureTime) {
  281. return;
  282. }
  283. NSDictionary *columnNameToValue = @{
  284. RCNKeyBundleIdentifier : _bundleIdentifier,
  285. RCNKeyNamespace : _FIRNamespace,
  286. RCNKeyFetchTime : @(self.lastFetchTimeInterval),
  287. RCNKeyDigestPerNamespace : serializedDigestPerNamespace,
  288. RCNKeyDeviceContext : serializedDeviceContext,
  289. RCNKeyAppContext : serializedAppContext,
  290. RCNKeySuccessFetchTime : serializedSuccessTime,
  291. RCNKeyFailureFetchTime : serializedFailureTime,
  292. RCNKeyLastFetchStatus : [NSString stringWithFormat:@"%ld", (long)_lastFetchStatus],
  293. RCNKeyLastFetchError : [NSString stringWithFormat:@"%ld", (long)_lastFetchError],
  294. RCNKeyLastApplyTime : @(_lastApplyTimeInterval),
  295. RCNKeyLastSetDefaultsTime : @(_lastSetDefaultsTimeInterval)
  296. };
  297. [_DBManager insertMetadataTableWithValues:columnNameToValue completionHandler:nil];
  298. }
  299. #pragma mark - fetch request
  300. /// Returns a fetch request with the latest device and config change.
  301. /// Whenever user issues a fetch api call, collect the latest request.
  302. - (NSString *)nextRequestWithUserProperties:(NSDictionary *)userProperties {
  303. // Note: We only set user properties as mentioned in the new REST API Design doc
  304. NSString *ret = [NSString stringWithFormat:@"{"];
  305. ret = [ret stringByAppendingString:[NSString stringWithFormat:@"app_instance_id:'%@'",
  306. _configInstallationsIdentifier]];
  307. ret = [ret stringByAppendingString:[NSString stringWithFormat:@", app_instance_id_token:'%@'",
  308. _configInstallationsToken]];
  309. ret = [ret stringByAppendingString:[NSString stringWithFormat:@", app_id:'%@'", _googleAppID]];
  310. ret = [ret stringByAppendingString:[NSString stringWithFormat:@", country_code:'%@'",
  311. FIRRemoteConfigDeviceCountry()]];
  312. ret = [ret stringByAppendingString:[NSString stringWithFormat:@", language_code:'%@'",
  313. FIRRemoteConfigDeviceLocale()]];
  314. ret = [ret
  315. stringByAppendingString:[NSString stringWithFormat:@", platform_version:'%@'",
  316. [GULAppEnvironmentUtil systemVersion]]];
  317. ret = [ret stringByAppendingString:[NSString stringWithFormat:@", time_zone:'%@'",
  318. FIRRemoteConfigTimezone()]];
  319. ret = [ret stringByAppendingString:[NSString stringWithFormat:@", package_name:'%@'",
  320. _bundleIdentifier]];
  321. ret = [ret stringByAppendingString:[NSString stringWithFormat:@", app_version:'%@'",
  322. FIRRemoteConfigAppVersion()]];
  323. ret = [ret stringByAppendingString:[NSString stringWithFormat:@", app_build:'%@'",
  324. FIRRemoteConfigAppBuildVersion()]];
  325. ret = [ret stringByAppendingString:[NSString stringWithFormat:@", sdk_version:'%@'",
  326. FIRRemoteConfigPodVersion()]];
  327. if (userProperties && userProperties.count > 0) {
  328. NSError *error;
  329. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:userProperties
  330. options:0
  331. error:&error];
  332. if (!error) {
  333. ret = [ret
  334. stringByAppendingString:[NSString
  335. stringWithFormat:@", analytics_user_properties:%@",
  336. [[NSString alloc]
  337. initWithData:jsonData
  338. encoding:NSUTF8StringEncoding]]];
  339. }
  340. }
  341. ret = [ret stringByAppendingString:@"}"];
  342. return ret;
  343. }
  344. #pragma mark - getter/setter
  345. - (void)setLastFetchError:(FIRRemoteConfigError)lastFetchError {
  346. if (_lastFetchError != lastFetchError) {
  347. _lastFetchError = lastFetchError;
  348. [_DBManager updateMetadataWithOption:RCNUpdateOptionFetchStatus
  349. namespace:_FIRNamespace
  350. values:@[ @(_lastFetchStatus), @(_lastFetchError) ]
  351. completionHandler:nil];
  352. }
  353. }
  354. - (NSArray *)successFetchTimes {
  355. return [_successFetchTimes copy];
  356. }
  357. - (NSArray *)failureFetchTimes {
  358. return [_failureFetchTimes copy];
  359. }
  360. - (NSDictionary *)customVariables {
  361. return [_customVariables copy];
  362. }
  363. - (NSDictionary *)internalMetadata {
  364. return [_internalMetadata copy];
  365. }
  366. - (NSDictionary *)deviceContext {
  367. return [_deviceContext copy];
  368. }
  369. - (void)setCustomVariables:(NSDictionary *)customVariables {
  370. _customVariables = [[NSMutableDictionary alloc] initWithDictionary:customVariables];
  371. [self updateMetadataTable];
  372. }
  373. - (void)setMinimumFetchInterval:(NSTimeInterval)minimumFetchInterval {
  374. if (minimumFetchInterval < 0) {
  375. _minimumFetchInterval = 0;
  376. } else {
  377. _minimumFetchInterval = minimumFetchInterval;
  378. }
  379. }
  380. - (void)setFetchTimeout:(NSTimeInterval)fetchTimeout {
  381. if (fetchTimeout <= 0) {
  382. _fetchTimeout = RCNHTTPDefaultConnectionTimeout;
  383. } else {
  384. _fetchTimeout = fetchTimeout;
  385. }
  386. }
  387. - (void)setLastApplyTimeInterval:(NSTimeInterval)lastApplyTimestamp {
  388. _lastApplyTimeInterval = lastApplyTimestamp;
  389. [_DBManager updateMetadataWithOption:RCNUpdateOptionApplyTime
  390. namespace:_FIRNamespace
  391. values:@[ @(lastApplyTimestamp) ]
  392. completionHandler:nil];
  393. }
  394. - (void)setLastSetDefaultsTimeInterval:(NSTimeInterval)lastSetDefaultsTimestamp {
  395. _lastSetDefaultsTimeInterval = lastSetDefaultsTimestamp;
  396. [_DBManager updateMetadataWithOption:RCNUpdateOptionDefaultTime
  397. namespace:_FIRNamespace
  398. values:@[ @(lastSetDefaultsTimestamp) ]
  399. completionHandler:nil];
  400. }
  401. #pragma mark Throttling
  402. - (BOOL)hasMinimumFetchIntervalElapsed:(NSTimeInterval)minimumFetchInterval {
  403. if (self.lastFetchTimeInterval == 0) return YES;
  404. // Check if last config fetch is within minimum fetch interval in seconds.
  405. NSTimeInterval diffInSeconds = [[NSDate date] timeIntervalSince1970] - self.lastFetchTimeInterval;
  406. return diffInSeconds > minimumFetchInterval;
  407. }
  408. - (BOOL)shouldThrottle {
  409. NSTimeInterval now = [[NSDate date] timeIntervalSince1970];
  410. return ((self.lastFetchTimeInterval > 0) &&
  411. (_lastFetchStatus != FIRRemoteConfigFetchStatusSuccess) &&
  412. (_exponentialBackoffThrottleEndTime - now > 0));
  413. }
  414. @end