RCNConfigSettings.m 19 KB

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