RCNFetch.m 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  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/RCNConfigFetch.h"
  17. #import <FirebaseCore/FIRApp.h>
  18. #import <FirebaseCore/FIRLogger.h>
  19. #import <FirebaseCore/FIROptions.h>
  20. #import <FirebaseInstallations/FirebaseInstallations.h>
  21. #import <GoogleUtilities/GULNSData+zlib.h>
  22. #import "FirebaseRemoteConfig/Sources/Private/RCNConfigSettings.h"
  23. #import "FirebaseRemoteConfig/Sources/RCNConfigConstants.h"
  24. #import "FirebaseRemoteConfig/Sources/RCNConfigContent.h"
  25. #import "FirebaseRemoteConfig/Sources/RCNConfigExperiment.h"
  26. #import "FirebaseRemoteConfig/Sources/RCNDevice.h"
  27. #ifdef RCN_STAGING_SERVER
  28. static NSString *const kServerURLDomain =
  29. @"https://staging-firebaseremoteconfig.sandbox.googleapis.com";
  30. #else
  31. static NSString *const kServerURLDomain = @"https://firebaseremoteconfig.googleapis.com";
  32. #endif
  33. static NSString *const kServerURLVersion = @"/v1";
  34. static NSString *const kServerURLProjects = @"/projects/";
  35. static NSString *const kServerURLNamespaces = @"/namespaces/";
  36. static NSString *const kServerURLQuery = @":fetch?";
  37. static NSString *const kServerURLKey = @"key=";
  38. static NSString *const kRequestJSONKeyAppID = @"app_id";
  39. static NSString *const kHTTPMethodPost = @"POST"; ///< HTTP request method config fetch using
  40. static NSString *const kContentTypeHeaderName = @"Content-Type"; ///< HTTP Header Field Name
  41. static NSString *const kContentEncodingHeaderName =
  42. @"Content-Encoding"; ///< HTTP Header Field Name
  43. static NSString *const kAcceptEncodingHeaderName = @"Accept-Encoding"; ///< HTTP Header Field Name
  44. static NSString *const kETagHeaderName = @"etag"; ///< HTTP Header Field Name
  45. static NSString *const kIfNoneMatchETagHeaderName = @"if-none-match"; ///< HTTP Header Field Name
  46. static NSString *const kInstallationsAuthTokenHeaderName = @"x-goog-firebase-installations-auth";
  47. // Sends the bundle ID. Refer to b/130301479 for details.
  48. static NSString *const kiOSBundleIdentifierHeaderName =
  49. @"X-Ios-Bundle-Identifier"; ///< HTTP Header Field Name
  50. /// Config HTTP request content type proto buffer
  51. static NSString *const kContentTypeValueJSON = @"application/json";
  52. /// HTTP status codes. Ref: https://cloud.google.com/apis/design/errors#error_retries
  53. static NSInteger const kRCNFetchResponseHTTPStatusCodeOK = 200;
  54. static NSInteger const kRCNFetchResponseHTTPStatusTooManyRequests = 429;
  55. static NSInteger const kRCNFetchResponseHTTPStatusCodeInternalError = 500;
  56. static NSInteger const kRCNFetchResponseHTTPStatusCodeServiceUnavailable = 503;
  57. static NSInteger const kRCNFetchResponseHTTPStatusCodeGatewayTimeout = 504;
  58. // Deprecated error code previously from FirebaseCore
  59. static const NSInteger FIRErrorCodeConfigFailed = -114;
  60. #pragma mark - RCNConfig
  61. @implementation RCNConfigFetch {
  62. RCNConfigContent *_content;
  63. RCNConfigSettings *_settings;
  64. id<FIRAnalyticsInterop> _analytics;
  65. RCNConfigExperiment *_experiment;
  66. dispatch_queue_t _lockQueue; /// Guard the read/write operation.
  67. NSURLSession *_fetchSession; /// Managed internally by the fetch instance.
  68. NSString *_FIRNamespace;
  69. FIROptions *_options;
  70. }
  71. - (instancetype)init {
  72. NSAssert(NO, @"Invalid initializer.");
  73. return nil;
  74. }
  75. /// Designated initializer
  76. - (instancetype)initWithContent:(RCNConfigContent *)content
  77. DBManager:(RCNConfigDBManager *)DBManager
  78. settings:(RCNConfigSettings *)settings
  79. analytics:(nullable id<FIRAnalyticsInterop>)analytics
  80. experiment:(RCNConfigExperiment *)experiment
  81. queue:(dispatch_queue_t)queue
  82. namespace:(NSString *)FIRNamespace
  83. options:(FIROptions *)options {
  84. self = [super init];
  85. if (self) {
  86. _FIRNamespace = FIRNamespace;
  87. _settings = settings;
  88. _analytics = analytics;
  89. _experiment = experiment;
  90. _lockQueue = queue;
  91. _content = content;
  92. _fetchSession = [self newFetchSession];
  93. _options = options;
  94. }
  95. return self;
  96. }
  97. /// Force a new NSURLSession creation for updated config.
  98. - (void)recreateNetworkSession {
  99. if (_fetchSession) {
  100. [_fetchSession invalidateAndCancel];
  101. }
  102. _fetchSession = [self newFetchSession];
  103. }
  104. /// Return the current session. (Tests).
  105. - (NSURLSession *)currentNetworkSession {
  106. return _fetchSession;
  107. }
  108. - (void)dealloc {
  109. [_fetchSession invalidateAndCancel];
  110. }
  111. #pragma mark - Fetch Config API
  112. - (void)fetchConfigWithExpirationDuration:(NSTimeInterval)expirationDuration
  113. completionHandler:(FIRRemoteConfigFetchCompletion)completionHandler {
  114. // Note: We expect the googleAppID to always be available.
  115. BOOL hasDeviceContextChanged =
  116. FIRRemoteConfigHasDeviceContextChanged(_settings.deviceContext, _options.googleAppID);
  117. __weak RCNConfigFetch *weakSelf = self;
  118. RCNConfigFetch *fetchWithExpirationSelf = weakSelf;
  119. dispatch_async(fetchWithExpirationSelf->_lockQueue, ^{
  120. RCNConfigFetch *strongSelf = fetchWithExpirationSelf;
  121. // Check whether we are outside of the minimum fetch interval.
  122. if (![strongSelf->_settings hasMinimumFetchIntervalElapsed:expirationDuration] &&
  123. !hasDeviceContextChanged) {
  124. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000051", @"Returning cached data.");
  125. return [strongSelf reportCompletionOnHandler:completionHandler
  126. withStatus:FIRRemoteConfigFetchStatusSuccess
  127. withError:nil];
  128. }
  129. // Check if a fetch is already in progress.
  130. if (strongSelf->_settings.isFetchInProgress) {
  131. // Check if we have some fetched data.
  132. if (strongSelf->_settings.lastFetchTimeInterval > 0) {
  133. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000052",
  134. @"A fetch is already in progress. Using previous fetch results.");
  135. return [strongSelf reportCompletionOnHandler:completionHandler
  136. withStatus:strongSelf->_settings.lastFetchStatus
  137. withError:nil];
  138. } else {
  139. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000053",
  140. @"A fetch is already in progress. Ignoring duplicate request.");
  141. NSError *error =
  142. [NSError errorWithDomain:FIRRemoteConfigErrorDomain
  143. code:FIRErrorCodeConfigFailed
  144. userInfo:@{
  145. NSLocalizedDescriptionKey :
  146. @"FetchError: Duplicate request while the previous one is pending"
  147. }];
  148. return [strongSelf reportCompletionOnHandler:completionHandler
  149. withStatus:FIRRemoteConfigFetchStatusFailure
  150. withError:error];
  151. }
  152. }
  153. // Check whether cache data is within throttle limit.
  154. if ([strongSelf->_settings shouldThrottle] && !hasDeviceContextChanged) {
  155. // Must set lastFetchStatus before FailReason.
  156. strongSelf->_settings.lastFetchStatus = FIRRemoteConfigFetchStatusThrottled;
  157. strongSelf->_settings.lastFetchError = FIRRemoteConfigErrorThrottled;
  158. NSTimeInterval throttledEndTime = strongSelf->_settings.exponentialBackoffThrottleEndTime;
  159. NSError *error =
  160. [NSError errorWithDomain:FIRRemoteConfigErrorDomain
  161. code:FIRRemoteConfigErrorThrottled
  162. userInfo:@{
  163. FIRRemoteConfigThrottledEndTimeInSecondsKey : @(throttledEndTime)
  164. }];
  165. return [strongSelf reportCompletionOnHandler:completionHandler
  166. withStatus:strongSelf->_settings.lastFetchStatus
  167. withError:error];
  168. }
  169. strongSelf->_settings.isFetchInProgress = YES;
  170. [strongSelf refreshInstallationsTokenWithCompletionHandler:completionHandler];
  171. });
  172. }
  173. #pragma mark - Fetch helpers
  174. - (NSString *)FIRAppNameFromFullyQualifiedNamespace {
  175. return [[_FIRNamespace componentsSeparatedByString:@":"] lastObject];
  176. }
  177. /// Refresh installation ID token before fetching config. installation ID is now mandatory for fetch
  178. /// requests to work.(b/14751422).
  179. - (void)refreshInstallationsTokenWithCompletionHandler:
  180. (FIRRemoteConfigFetchCompletion)completionHandler {
  181. FIRInstallations *installations = [FIRInstallations
  182. installationsWithApp:[FIRApp appNamed:[self FIRAppNameFromFullyQualifiedNamespace]]];
  183. if (!installations || !_options.GCMSenderID) {
  184. NSString *errorDescription = @"Failed to get GCMSenderID";
  185. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000074", @"%@",
  186. [NSString stringWithFormat:@"%@", errorDescription]);
  187. self->_settings.isFetchInProgress = NO;
  188. return [self
  189. reportCompletionOnHandler:completionHandler
  190. withStatus:FIRRemoteConfigFetchStatusFailure
  191. withError:[NSError errorWithDomain:FIRRemoteConfigErrorDomain
  192. code:FIRRemoteConfigErrorInternalError
  193. userInfo:@{
  194. NSLocalizedDescriptionKey : errorDescription
  195. }]];
  196. }
  197. FIRInstallationsTokenHandler installationsTokenHandler = ^(
  198. FIRInstallationsAuthTokenResult *tokenResult, NSError *error) {
  199. if (!tokenResult || !tokenResult.authToken || error) {
  200. NSString *errorDescription =
  201. [NSString stringWithFormat:@"Failed to get installations token. Error : %@.", error];
  202. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000073", @"%@",
  203. [NSString stringWithFormat:@"%@", errorDescription]);
  204. self->_settings.isFetchInProgress = NO;
  205. return [self
  206. reportCompletionOnHandler:completionHandler
  207. withStatus:FIRRemoteConfigFetchStatusFailure
  208. withError:[NSError errorWithDomain:FIRRemoteConfigErrorDomain
  209. code:FIRRemoteConfigErrorInternalError
  210. userInfo:@{
  211. NSLocalizedDescriptionKey : errorDescription
  212. }]];
  213. }
  214. // We have a valid token. Get the backing installationID.
  215. __weak RCNConfigFetch *weakSelf = self;
  216. [installations installationIDWithCompletion:^(NSString *_Nullable identifier,
  217. NSError *_Nullable error) {
  218. RCNConfigFetch *strongSelf = weakSelf;
  219. // Dispatch to the RC serial queue to update settings on the queue.
  220. dispatch_async(strongSelf->_lockQueue, ^{
  221. RCNConfigFetch *strongSelfQueue = weakSelf;
  222. // Update config settings with the IID and token.
  223. strongSelfQueue->_settings.configInstallationsToken = tokenResult.authToken;
  224. strongSelfQueue->_settings.configInstallationsIdentifier = identifier;
  225. if (!identifier || error) {
  226. NSString *errorDescription =
  227. [NSString stringWithFormat:@"Error getting iid : %@.", error];
  228. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000055", @"%@",
  229. [NSString stringWithFormat:@"%@", errorDescription]);
  230. strongSelfQueue->_settings.isFetchInProgress = NO;
  231. return [strongSelfQueue
  232. reportCompletionOnHandler:completionHandler
  233. withStatus:FIRRemoteConfigFetchStatusFailure
  234. withError:[NSError
  235. errorWithDomain:FIRRemoteConfigErrorDomain
  236. code:FIRRemoteConfigErrorInternalError
  237. userInfo:@{
  238. NSLocalizedDescriptionKey : errorDescription
  239. }]];
  240. }
  241. FIRLogInfo(kFIRLoggerRemoteConfig, @"I-RCN000022", @"Success to get iid : %@.",
  242. strongSelfQueue->_settings.configInstallationsIdentifier);
  243. [strongSelf doFetchCall:completionHandler];
  244. });
  245. }];
  246. };
  247. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000039", @"Starting requesting token.");
  248. [installations authTokenWithCompletion:installationsTokenHandler];
  249. }
  250. - (void)doFetchCall:(FIRRemoteConfigFetchCompletion)completionHandler {
  251. [self getAnalyticsUserPropertiesWithCompletionHandler:^(NSDictionary *userProperties) {
  252. dispatch_async(self->_lockQueue, ^{
  253. [self fetchWithUserProperties:userProperties completionHandler:completionHandler];
  254. });
  255. }];
  256. }
  257. - (void)getAnalyticsUserPropertiesWithCompletionHandler:
  258. (FIRAInteropUserPropertiesCallback)completionHandler {
  259. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000060", @"Fetch with user properties completed.");
  260. id<FIRAnalyticsInterop> analytics = self->_analytics;
  261. if (analytics == nil) {
  262. completionHandler(@{});
  263. } else {
  264. [analytics getUserPropertiesWithCallback:completionHandler];
  265. }
  266. }
  267. - (void)reportCompletionOnHandler:(FIRRemoteConfigFetchCompletion)completionHandler
  268. withStatus:(FIRRemoteConfigFetchStatus)status
  269. withError:(NSError *)error {
  270. if (completionHandler) {
  271. dispatch_async(dispatch_get_main_queue(), ^{
  272. completionHandler(status, error);
  273. });
  274. }
  275. }
  276. - (void)fetchWithUserProperties:(NSDictionary *)userProperties
  277. completionHandler:(FIRRemoteConfigFetchCompletion)completionHandler {
  278. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000061", @"Fetch with user properties initiated.");
  279. NSString *postRequestString = [_settings nextRequestWithUserProperties:userProperties];
  280. // Get POST request content.
  281. NSData *content = [postRequestString dataUsingEncoding:NSUTF8StringEncoding];
  282. NSError *compressionError;
  283. NSData *compressedContent = [NSData gul_dataByGzippingData:content error:&compressionError];
  284. if (compressionError) {
  285. NSString *errString = [NSString stringWithFormat:@"Failed to compress the config request."];
  286. FIRLogWarning(kFIRLoggerRemoteConfig, @"I-RCN000033", @"%@", errString);
  287. self->_settings.isFetchInProgress = NO;
  288. return [self
  289. reportCompletionOnHandler:completionHandler
  290. withStatus:FIRRemoteConfigFetchStatusFailure
  291. withError:[NSError
  292. errorWithDomain:FIRRemoteConfigErrorDomain
  293. code:FIRRemoteConfigErrorInternalError
  294. userInfo:@{NSLocalizedDescriptionKey : errString}]];
  295. }
  296. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000040", @"Start config fetch.");
  297. __weak RCNConfigFetch *weakSelf = self;
  298. RCNConfigFetcherCompletion fetcherCompletion = ^(NSData *data, NSURLResponse *response,
  299. NSError *error) {
  300. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000050",
  301. @"config fetch completed. Error: %@ StatusCode: %ld", (error ? error : @"nil"),
  302. (long)[((NSHTTPURLResponse *)response) statusCode]);
  303. // The fetch has completed.
  304. self->_settings.isFetchInProgress = NO;
  305. RCNConfigFetch *fetcherCompletionSelf = weakSelf;
  306. if (!fetcherCompletionSelf) {
  307. return;
  308. };
  309. dispatch_async(fetcherCompletionSelf->_lockQueue, ^{
  310. RCNConfigFetch *strongSelf = weakSelf;
  311. if (!strongSelf) {
  312. return;
  313. }
  314. NSInteger statusCode = [((NSHTTPURLResponse *)response) statusCode];
  315. if (error || (statusCode != kRCNFetchResponseHTTPStatusCodeOK)) {
  316. // Update metadata about fetch failure.
  317. [strongSelf->_settings updateMetadataWithFetchSuccessStatus:NO];
  318. if (error) {
  319. if (strongSelf->_settings.lastFetchStatus == FIRRemoteConfigFetchStatusSuccess) {
  320. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000025",
  321. @"RCN Fetch failure: %@. Using cached config result.", error);
  322. } else {
  323. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000026",
  324. @"RCN Fetch failure: %@. No cached config result.", error);
  325. }
  326. }
  327. if (statusCode != kRCNFetchResponseHTTPStatusCodeOK) {
  328. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000026",
  329. @"RCN Fetch failure. Response http error code: %ld", (long)statusCode);
  330. // Response error code 429, 500, 503 will trigger exponential backoff mode.
  331. if (statusCode == kRCNFetchResponseHTTPStatusTooManyRequests ||
  332. statusCode == kRCNFetchResponseHTTPStatusCodeInternalError ||
  333. statusCode == kRCNFetchResponseHTTPStatusCodeServiceUnavailable ||
  334. statusCode == kRCNFetchResponseHTTPStatusCodeGatewayTimeout) {
  335. if ([strongSelf->_settings shouldThrottle]) {
  336. // Must set lastFetchStatus before FailReason.
  337. strongSelf->_settings.lastFetchStatus = FIRRemoteConfigFetchStatusThrottled;
  338. strongSelf->_settings.lastFetchError = FIRRemoteConfigErrorThrottled;
  339. NSTimeInterval throttledEndTime =
  340. strongSelf->_settings.exponentialBackoffThrottleEndTime;
  341. NSError *error = [NSError
  342. errorWithDomain:FIRRemoteConfigErrorDomain
  343. code:FIRRemoteConfigErrorThrottled
  344. userInfo:@{
  345. FIRRemoteConfigThrottledEndTimeInSecondsKey : @(throttledEndTime)
  346. }];
  347. return [strongSelf reportCompletionOnHandler:completionHandler
  348. withStatus:strongSelf->_settings.lastFetchStatus
  349. withError:error];
  350. }
  351. } // Response error code 429, 500, 503
  352. } // StatusCode != kRCNFetchResponseHTTPStatusCodeOK
  353. // Return back the received error.
  354. // Must set lastFetchStatus before setting Fetch Error.
  355. strongSelf->_settings.lastFetchStatus = FIRRemoteConfigFetchStatusFailure;
  356. strongSelf->_settings.lastFetchError = FIRRemoteConfigErrorInternalError;
  357. NSDictionary<NSErrorUserInfoKey, id> *userInfo = @{
  358. NSLocalizedDescriptionKey :
  359. (error ? [error localizedDescription]
  360. : [NSString
  361. stringWithFormat:@"Internal Error. Status code: %ld", (long)statusCode])
  362. };
  363. return [strongSelf
  364. reportCompletionOnHandler:completionHandler
  365. withStatus:FIRRemoteConfigFetchStatusFailure
  366. withError:[NSError errorWithDomain:FIRRemoteConfigErrorDomain
  367. code:FIRRemoteConfigErrorInternalError
  368. userInfo:userInfo]];
  369. }
  370. // Fetch was successful. Check if we have data.
  371. NSError *retError;
  372. if (!data) {
  373. FIRLogInfo(kFIRLoggerRemoteConfig, @"I-RCN000043", @"RCN Fetch: No data in fetch response");
  374. return [strongSelf reportCompletionOnHandler:completionHandler
  375. withStatus:FIRRemoteConfigFetchStatusSuccess
  376. withError:nil];
  377. }
  378. // Config fetch succeeded.
  379. // JSONObjectWithData is always expected to return an NSDictionary in our case
  380. NSMutableDictionary *fetchedConfig =
  381. [NSJSONSerialization JSONObjectWithData:data
  382. options:NSJSONReadingMutableContainers
  383. error:&retError];
  384. if (retError) {
  385. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000042",
  386. @"RCN Fetch failure: %@. Could not parse response data as JSON", error);
  387. }
  388. // Check and log if we received an error from the server
  389. if (fetchedConfig && fetchedConfig.count == 1 && fetchedConfig[RCNFetchResponseKeyError]) {
  390. NSString *errStr = [NSString stringWithFormat:@"RCN Fetch Failure: Server returned error:"];
  391. NSDictionary *errDict = fetchedConfig[RCNFetchResponseKeyError];
  392. if (errDict[RCNFetchResponseKeyErrorCode]) {
  393. errStr = [errStr
  394. stringByAppendingString:[NSString
  395. stringWithFormat:@"code: %@",
  396. errDict[RCNFetchResponseKeyErrorCode]]];
  397. }
  398. if (errDict[RCNFetchResponseKeyErrorStatus]) {
  399. errStr = [errStr stringByAppendingString:
  400. [NSString stringWithFormat:@". Status: %@",
  401. errDict[RCNFetchResponseKeyErrorStatus]]];
  402. }
  403. if (errDict[RCNFetchResponseKeyErrorMessage]) {
  404. errStr =
  405. [errStr stringByAppendingString:
  406. [NSString stringWithFormat:@". Message: %@",
  407. errDict[RCNFetchResponseKeyErrorMessage]]];
  408. }
  409. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000044", @"%@.", errStr);
  410. return [strongSelf
  411. reportCompletionOnHandler:completionHandler
  412. withStatus:FIRRemoteConfigFetchStatusFailure
  413. withError:[NSError
  414. errorWithDomain:FIRRemoteConfigErrorDomain
  415. code:FIRRemoteConfigErrorInternalError
  416. userInfo:@{NSLocalizedDescriptionKey : errStr}]];
  417. }
  418. // Add the fetched config to the database.
  419. if (fetchedConfig) {
  420. // Update config content to cache and DB.
  421. [self->_content updateConfigContentWithResponse:fetchedConfig
  422. forNamespace:self->_FIRNamespace];
  423. // Update experiments.
  424. [strongSelf->_experiment
  425. updateExperimentsWithResponse:fetchedConfig[RCNFetchResponseKeyExperimentDescriptions]];
  426. } else {
  427. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000063",
  428. @"Empty response with no fetched config.");
  429. }
  430. // We had a successful fetch. Update the current eTag in settings if different.
  431. NSString *latestETag = ((NSHTTPURLResponse *)response).allHeaderFields[kETagHeaderName];
  432. if (!self->_settings.lastETag || !([self->_settings.lastETag isEqualToString:latestETag])) {
  433. self->_settings.lastETag = latestETag;
  434. }
  435. [self->_settings updateMetadataWithFetchSuccessStatus:YES];
  436. return [strongSelf reportCompletionOnHandler:completionHandler
  437. withStatus:FIRRemoteConfigFetchStatusSuccess
  438. withError:nil];
  439. });
  440. };
  441. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000061", @"Making remote config fetch.");
  442. NSURLSessionDataTask *dataTask = [self URLSessionDataTaskWithContent:compressedContent
  443. completionHandler:fetcherCompletion];
  444. [dataTask resume];
  445. }
  446. - (NSString *)constructServerURL {
  447. NSString *serverURLStr = [[NSString alloc] initWithString:kServerURLDomain];
  448. serverURLStr = [serverURLStr stringByAppendingString:kServerURLVersion];
  449. if (_options.projectID) {
  450. serverURLStr = [serverURLStr stringByAppendingString:kServerURLProjects];
  451. serverURLStr = [serverURLStr stringByAppendingString:_options.projectID];
  452. } else {
  453. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000070",
  454. @"Missing `projectID` from `FirebaseOptions`, please ensure the configured "
  455. @"`FirebaseApp` is configured with `FirebaseOptions` that contains a `projectID`.");
  456. }
  457. serverURLStr = [serverURLStr stringByAppendingString:kServerURLNamespaces];
  458. // Get the namespace from the fully qualified namespace string of "namespace:FIRAppName".
  459. NSString *namespace =
  460. [_FIRNamespace substringToIndex:[_FIRNamespace rangeOfString:@":"].location];
  461. serverURLStr = [serverURLStr stringByAppendingString:namespace];
  462. serverURLStr = [serverURLStr stringByAppendingString:kServerURLQuery];
  463. if (_options.APIKey) {
  464. serverURLStr = [serverURLStr stringByAppendingString:kServerURLKey];
  465. serverURLStr = [serverURLStr stringByAppendingString:_options.APIKey];
  466. } else {
  467. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000071",
  468. @"Missing `APIKey` from `FirebaseOptions`, please ensure the configured "
  469. @"`FirebaseApp` is configured with `FirebaseOptions` that contains an `APIKey`.");
  470. }
  471. return serverURLStr;
  472. }
  473. - (NSURLSession *)newFetchSession {
  474. NSURLSessionConfiguration *config =
  475. [[NSURLSessionConfiguration defaultSessionConfiguration] copy];
  476. config.timeoutIntervalForRequest = _settings.fetchTimeout;
  477. config.timeoutIntervalForResource = _settings.fetchTimeout;
  478. NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
  479. return session;
  480. }
  481. - (NSURLSessionDataTask *)URLSessionDataTaskWithContent:(NSData *)content
  482. completionHandler:
  483. (RCNConfigFetcherCompletion)fetcherCompletion {
  484. NSURL *URL = [NSURL URLWithString:[self constructServerURL]];
  485. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000046", @"%@",
  486. [NSString stringWithFormat:@"Making config request: %@", [URL absoluteString]]);
  487. NSTimeInterval timeoutInterval = _fetchSession.configuration.timeoutIntervalForResource;
  488. NSMutableURLRequest *URLRequest =
  489. [[NSMutableURLRequest alloc] initWithURL:URL
  490. cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
  491. timeoutInterval:timeoutInterval];
  492. URLRequest.HTTPMethod = kHTTPMethodPost;
  493. [URLRequest setValue:kContentTypeValueJSON forHTTPHeaderField:kContentTypeHeaderName];
  494. [URLRequest setValue:_settings.configInstallationsToken
  495. forHTTPHeaderField:kInstallationsAuthTokenHeaderName];
  496. [URLRequest setValue:[[NSBundle mainBundle] bundleIdentifier]
  497. forHTTPHeaderField:kiOSBundleIdentifierHeaderName];
  498. [URLRequest setValue:@"gzip" forHTTPHeaderField:kContentEncodingHeaderName];
  499. [URLRequest setValue:@"gzip" forHTTPHeaderField:kAcceptEncodingHeaderName];
  500. // Set the eTag from the last successful fetch, if available.
  501. if (_settings.lastETag) {
  502. [URLRequest setValue:_settings.lastETag forHTTPHeaderField:kIfNoneMatchETagHeaderName];
  503. }
  504. [URLRequest setHTTPBody:content];
  505. return [_fetchSession dataTaskWithRequest:URLRequest completionHandler:fetcherCompletion];
  506. }
  507. @end