RCNFetch.m 27 KB

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