RCNConfigSettings.m 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  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] copy];
  129. if (metadata) {
  130. // TODO: Remove (all metadata in general) once ready to
  131. // migrate to user defaults completely.
  132. if (metadata[RCNKeyDeviceContext]) {
  133. self->_deviceContext = [metadata[RCNKeyDeviceContext] mutableCopy];
  134. }
  135. if (metadata[RCNKeyAppContext]) {
  136. self->_customVariables = [metadata[RCNKeyAppContext] mutableCopy];
  137. }
  138. if (metadata[RCNKeySuccessFetchTime]) {
  139. self->_successFetchTimes = [metadata[RCNKeySuccessFetchTime] mutableCopy];
  140. }
  141. if (metadata[RCNKeyFailureFetchTime]) {
  142. self->_failureFetchTimes = [metadata[RCNKeyFailureFetchTime] mutableCopy];
  143. }
  144. if (metadata[RCNKeyLastFetchStatus]) {
  145. self->_lastFetchStatus =
  146. (FIRRemoteConfigFetchStatus)[metadata[RCNKeyLastFetchStatus] intValue];
  147. }
  148. if (metadata[RCNKeyLastFetchError]) {
  149. self->_lastFetchError = (FIRRemoteConfigError)[metadata[RCNKeyLastFetchError] intValue];
  150. }
  151. if (metadata[RCNKeyLastApplyTime]) {
  152. self->_lastApplyTimeInterval = [metadata[RCNKeyLastApplyTime] doubleValue];
  153. }
  154. if (metadata[RCNKeyLastFetchStatus]) {
  155. self->_lastSetDefaultsTimeInterval = [metadata[RCNKeyLastSetDefaultsTime] doubleValue];
  156. }
  157. }
  158. return metadata;
  159. }
  160. #pragma mark - update DB/cached
  161. // Update internal metadata content to cache and DB.
  162. - (void)updateInternalContentWithResponse:(NSDictionary *)response {
  163. // Remove all the keys with current pakcage name.
  164. [_DBManager deleteRecordWithBundleIdentifier:_bundleIdentifier isInternalDB:YES];
  165. for (NSString *key in _internalMetadata.allKeys) {
  166. if ([key hasPrefix:_bundleIdentifier]) {
  167. [_internalMetadata removeObjectForKey:key];
  168. }
  169. }
  170. for (NSString *entry in response) {
  171. NSData *val = [response[entry] dataUsingEncoding:NSUTF8StringEncoding];
  172. NSArray *values = @[ entry, val ];
  173. _internalMetadata[entry] = response[entry];
  174. [self updateInternalMetadataTableWithValues:values];
  175. }
  176. }
  177. - (void)updateInternalMetadataTableWithValues:(NSArray *)values {
  178. [_DBManager insertInternalMetadataTableWithValues:values completionHandler:nil];
  179. }
  180. /// If the last fetch was not successful, update the (exponential backoff) period that we wait until
  181. /// fetching again. Any subsequent fetch requests will be checked and allowed only if past this
  182. /// throttle end time.
  183. - (void)updateExponentialBackoffTime {
  184. // If not in exponential backoff mode, reset the retry interval.
  185. if (_lastFetchStatus == FIRRemoteConfigFetchStatusSuccess) {
  186. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000057",
  187. @"Throttling: Entering exponential backoff mode.");
  188. _exponentialBackoffRetryInterval = kRCNExponentialBackoffMinimumInterval;
  189. } else {
  190. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000057",
  191. @"Throttling: Updating throttling interval.");
  192. // Double the retry interval until we hit the truncated exponential backoff. More info here:
  193. // https://cloud.google.com/storage/docs/exponential-backoff
  194. _exponentialBackoffRetryInterval =
  195. ((_exponentialBackoffRetryInterval * 2) < kRCNExponentialBackoffMaximumInterval)
  196. ? _exponentialBackoffRetryInterval * 2
  197. : _exponentialBackoffRetryInterval;
  198. }
  199. // Randomize the next retry interval.
  200. int randomPlusMinusInterval = ((arc4random() % 2) == 0) ? -1 : 1;
  201. NSTimeInterval randomizedRetryInterval =
  202. _exponentialBackoffRetryInterval +
  203. (0.5 * _exponentialBackoffRetryInterval * randomPlusMinusInterval);
  204. _exponentialBackoffThrottleEndTime =
  205. [[NSDate date] timeIntervalSince1970] + randomizedRetryInterval;
  206. }
  207. - (void)updateMetadataWithFetchSuccessStatus:(BOOL)fetchSuccess {
  208. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000056", @"Updating metadata with fetch result.");
  209. if (!fetchSuccess) {
  210. [self updateExponentialBackoffTime];
  211. }
  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 isInternalDB:NO];
  233. NSError *error;
  234. // Objects to be serialized cannot be invalid.
  235. if (!_bundleIdentifier) {
  236. return;
  237. }
  238. if (![NSJSONSerialization isValidJSONObject:_customVariables]) {
  239. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000028",
  240. @"Invalid custom variables to be serialized.");
  241. return;
  242. }
  243. if (![NSJSONSerialization isValidJSONObject:_deviceContext]) {
  244. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000029",
  245. @"Invalid device context to be serialized.");
  246. return;
  247. }
  248. if (![NSJSONSerialization isValidJSONObject:_successFetchTimes]) {
  249. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000031",
  250. @"Invalid success fetch times to be serialized.");
  251. return;
  252. }
  253. if (![NSJSONSerialization isValidJSONObject:_failureFetchTimes]) {
  254. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000032",
  255. @"Invalid failure fetch times to be serialized.");
  256. return;
  257. }
  258. NSData *serializedAppContext = [NSJSONSerialization dataWithJSONObject:_customVariables
  259. options:NSJSONWritingPrettyPrinted
  260. error:&error];
  261. NSData *serializedDeviceContext =
  262. [NSJSONSerialization dataWithJSONObject:_deviceContext
  263. options:NSJSONWritingPrettyPrinted
  264. error:&error];
  265. // The digestPerNamespace is not used and only meant for backwards DB compatibility.
  266. NSData *serializedDigestPerNamespace =
  267. [NSJSONSerialization dataWithJSONObject:@{} options:NSJSONWritingPrettyPrinted error:&error];
  268. NSData *serializedSuccessTime = [NSJSONSerialization dataWithJSONObject:_successFetchTimes
  269. options:NSJSONWritingPrettyPrinted
  270. error:&error];
  271. NSData *serializedFailureTime = [NSJSONSerialization dataWithJSONObject:_failureFetchTimes
  272. options:NSJSONWritingPrettyPrinted
  273. error:&error];
  274. if (!serializedDigestPerNamespace || !serializedDeviceContext || !serializedAppContext ||
  275. !serializedSuccessTime || !serializedFailureTime) {
  276. return;
  277. }
  278. NSDictionary *columnNameToValue = @{
  279. RCNKeyBundleIdentifier : _bundleIdentifier,
  280. RCNKeyFetchTime : @(self.lastFetchTimeInterval),
  281. RCNKeyDigestPerNamespace : serializedDigestPerNamespace,
  282. RCNKeyDeviceContext : serializedDeviceContext,
  283. RCNKeyAppContext : serializedAppContext,
  284. RCNKeySuccessFetchTime : serializedSuccessTime,
  285. RCNKeyFailureFetchTime : serializedFailureTime,
  286. RCNKeyLastFetchStatus : [NSString stringWithFormat:@"%ld", (long)_lastFetchStatus],
  287. RCNKeyLastFetchError : [NSString stringWithFormat:@"%ld", (long)_lastFetchError],
  288. RCNKeyLastApplyTime : @(_lastApplyTimeInterval),
  289. RCNKeyLastSetDefaultsTime : @(_lastSetDefaultsTimeInterval)
  290. };
  291. [_DBManager insertMetadataTableWithValues:columnNameToValue completionHandler:nil];
  292. }
  293. #pragma mark - fetch request
  294. /// Returns a fetch request with the latest device and config change.
  295. /// Whenever user issues a fetch api call, collect the latest request.
  296. - (NSString *)nextRequestWithUserProperties:(NSDictionary *)userProperties {
  297. // Note: We only set user properties as mentioned in the new REST API Design doc
  298. NSString *ret = [NSString stringWithFormat:@"{"];
  299. ret = [ret stringByAppendingString:[NSString stringWithFormat:@"app_instance_id:'%@'",
  300. _configInstallationsIdentifier]];
  301. ret = [ret stringByAppendingString:[NSString stringWithFormat:@", app_instance_id_token:'%@'",
  302. _configInstallationsToken]];
  303. ret = [ret stringByAppendingString:[NSString stringWithFormat:@", app_id:'%@'", _googleAppID]];
  304. ret = [ret stringByAppendingString:[NSString stringWithFormat:@", country_code:'%@'",
  305. FIRRemoteConfigDeviceCountry()]];
  306. ret = [ret stringByAppendingString:[NSString stringWithFormat:@", language_code:'%@'",
  307. FIRRemoteConfigDeviceLocale()]];
  308. ret = [ret
  309. stringByAppendingString:[NSString stringWithFormat:@", platform_version:'%@'",
  310. [GULAppEnvironmentUtil systemVersion]]];
  311. ret = [ret stringByAppendingString:[NSString stringWithFormat:@", time_zone:'%@'",
  312. FIRRemoteConfigTimezone()]];
  313. ret = [ret stringByAppendingString:[NSString stringWithFormat:@", package_name:'%@'",
  314. _bundleIdentifier]];
  315. ret = [ret stringByAppendingString:[NSString stringWithFormat:@", app_version:'%@'",
  316. FIRRemoteConfigAppVersion()]];
  317. ret = [ret stringByAppendingString:[NSString stringWithFormat:@", app_build:'%@'",
  318. FIRRemoteConfigAppBuildVersion()]];
  319. ret = [ret stringByAppendingString:[NSString stringWithFormat:@", sdk_version:'%@'",
  320. FIRRemoteConfigPodVersion()]];
  321. if (userProperties && userProperties.count > 0) {
  322. NSError *error;
  323. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:userProperties
  324. options:0
  325. error:&error];
  326. if (!error) {
  327. ret = [ret
  328. stringByAppendingString:[NSString
  329. stringWithFormat:@", analytics_user_properties:%@",
  330. [[NSString alloc]
  331. initWithData:jsonData
  332. encoding:NSUTF8StringEncoding]]];
  333. }
  334. }
  335. ret = [ret stringByAppendingString:@"}"];
  336. return ret;
  337. }
  338. #pragma mark - getter/setter
  339. - (void)setLastFetchError:(FIRRemoteConfigError)lastFetchError {
  340. if (_lastFetchError != lastFetchError) {
  341. _lastFetchError = lastFetchError;
  342. [_DBManager updateMetadataWithOption:RCNUpdateOptionFetchStatus
  343. values:@[ @(_lastFetchStatus), @(_lastFetchError) ]
  344. completionHandler:nil];
  345. }
  346. }
  347. - (NSArray *)successFetchTimes {
  348. return [_successFetchTimes copy];
  349. }
  350. - (NSArray *)failureFetchTimes {
  351. return [_failureFetchTimes copy];
  352. }
  353. - (NSDictionary *)customVariables {
  354. return [_customVariables copy];
  355. }
  356. - (NSDictionary *)internalMetadata {
  357. return [_internalMetadata copy];
  358. }
  359. - (NSDictionary *)deviceContext {
  360. return [_deviceContext copy];
  361. }
  362. - (void)setCustomVariables:(NSDictionary *)customVariables {
  363. _customVariables = [[NSMutableDictionary alloc] initWithDictionary:customVariables];
  364. [self updateMetadataTable];
  365. }
  366. - (void)setMinimumFetchInterval:(NSTimeInterval)minimumFetchInterval {
  367. if (minimumFetchInterval < 0) {
  368. _minimumFetchInterval = 0;
  369. } else {
  370. _minimumFetchInterval = minimumFetchInterval;
  371. }
  372. }
  373. - (void)setFetchTimeout:(NSTimeInterval)fetchTimeout {
  374. if (fetchTimeout <= 0) {
  375. _fetchTimeout = RCNHTTPDefaultConnectionTimeout;
  376. } else {
  377. _fetchTimeout = fetchTimeout;
  378. }
  379. }
  380. - (void)setLastApplyTimeInterval:(NSTimeInterval)lastApplyTimestamp {
  381. _lastApplyTimeInterval = lastApplyTimestamp;
  382. [_DBManager updateMetadataWithOption:RCNUpdateOptionApplyTime
  383. values:@[ @(lastApplyTimestamp) ]
  384. completionHandler:nil];
  385. }
  386. - (void)setLastSetDefaultsTimeInterval:(NSTimeInterval)lastSetDefaultsTimestamp {
  387. _lastSetDefaultsTimeInterval = lastSetDefaultsTimestamp;
  388. [_DBManager updateMetadataWithOption:RCNUpdateOptionDefaultTime
  389. values:@[ @(lastSetDefaultsTimestamp) ]
  390. completionHandler:nil];
  391. }
  392. #pragma mark Throttling
  393. - (BOOL)hasMinimumFetchIntervalElapsed:(NSTimeInterval)minimumFetchInterval {
  394. if (self.lastFetchTimeInterval == 0) return YES;
  395. // Check if last config fetch is within minimum fetch interval in seconds.
  396. NSTimeInterval diffInSeconds = [[NSDate date] timeIntervalSince1970] - self.lastFetchTimeInterval;
  397. return diffInSeconds > minimumFetchInterval;
  398. }
  399. - (BOOL)shouldThrottle {
  400. NSTimeInterval now = [[NSDate date] timeIntervalSince1970];
  401. return ((self.lastFetchTimeInterval > 0) &&
  402. (_lastFetchStatus != FIRRemoteConfigFetchStatusSuccess) &&
  403. (_exponentialBackoffThrottleEndTime - now > 0));
  404. }
  405. @end