RCNFetch.m 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  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/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. static RCNConfigFetcherTestBlock gGlobalTestBlock;
  61. #pragma mark - RCNConfig
  62. @implementation RCNConfigFetch {
  63. RCNConfigContent *_content;
  64. RCNConfigSettings *_settings;
  65. id<FIRAnalyticsInterop> _analytics;
  66. RCNConfigExperiment *_experiment;
  67. dispatch_queue_t _lockQueue; /// Guard the read/write operation.
  68. NSURLSession *_fetchSession; /// Managed internally by the fetch instance.
  69. NSString *_FIRNamespace;
  70. FIROptions *_options;
  71. }
  72. - (instancetype)init {
  73. NSAssert(NO, @"Invalid initializer.");
  74. return nil;
  75. }
  76. /// Designated initializer
  77. - (instancetype)initWithContent:(RCNConfigContent *)content
  78. DBManager:(RCNConfigDBManager *)DBManager
  79. settings:(RCNConfigSettings *)settings
  80. analytics:(nullable id<FIRAnalyticsInterop>)analytics
  81. experiment:(RCNConfigExperiment *)experiment
  82. queue:(dispatch_queue_t)queue
  83. namespace:(NSString *)FIRNamespace
  84. options:(FIROptions *)options {
  85. self = [super init];
  86. if (self) {
  87. _FIRNamespace = FIRNamespace;
  88. _settings = settings;
  89. _analytics = analytics;
  90. _experiment = experiment;
  91. _lockQueue = queue;
  92. _content = content;
  93. _fetchSession = [self newFetchSession];
  94. _options = options;
  95. }
  96. return self;
  97. }
  98. /// Force a new NSURLSession creation for updated config.
  99. - (void)recreateNetworkSession {
  100. if (_fetchSession) {
  101. [_fetchSession invalidateAndCancel];
  102. }
  103. _fetchSession = [self newFetchSession];
  104. }
  105. /// Return the current session. (Tests).
  106. - (NSURLSession *)currentNetworkSession {
  107. return _fetchSession;
  108. }
  109. - (void)dealloc {
  110. [_fetchSession invalidateAndCancel];
  111. }
  112. #pragma mark - Fetch Config API
  113. - (void)fetchConfigWithExpirationDuration:(NSTimeInterval)expirationDuration
  114. completionHandler:(FIRRemoteConfigFetchCompletion)completionHandler {
  115. // Note: We expect the googleAppID to always be available.
  116. BOOL hasDeviceContextChanged =
  117. FIRRemoteConfigHasDeviceContextChanged(_settings.deviceContext, _options.googleAppID);
  118. __weak RCNConfigFetch *weakSelf = self;
  119. RCNConfigFetch *fetchWithExpirationSelf = weakSelf;
  120. dispatch_async(fetchWithExpirationSelf->_lockQueue, ^{
  121. RCNConfigFetch *strongSelf = fetchWithExpirationSelf;
  122. // Check whether we are outside of the minimum fetch interval.
  123. if (![strongSelf->_settings hasMinimumFetchIntervalElapsed:expirationDuration] &&
  124. !hasDeviceContextChanged) {
  125. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000051", @"Returning cached data.");
  126. return [strongSelf reportCompletionOnHandler:completionHandler
  127. withStatus:FIRRemoteConfigFetchStatusSuccess
  128. withError:nil];
  129. }
  130. // Check if a fetch is already in progress.
  131. if (strongSelf->_settings.isFetchInProgress) {
  132. // Check if we have some fetched data.
  133. if (strongSelf->_settings.lastFetchTimeInterval > 0) {
  134. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000052",
  135. @"A fetch is already in progress. Using previous fetch results.");
  136. return [strongSelf reportCompletionOnHandler:completionHandler
  137. withStatus:strongSelf->_settings.lastFetchStatus
  138. withError:nil];
  139. } else {
  140. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000053",
  141. @"A fetch is already in progress. Ignoring duplicate request.");
  142. NSError *error =
  143. [NSError errorWithDomain:FIRRemoteConfigErrorDomain
  144. code:FIRErrorCodeConfigFailed
  145. userInfo:@{
  146. NSLocalizedDescriptionKey :
  147. @"FetchError: Duplicate request while the previous one is pending"
  148. }];
  149. return [strongSelf reportCompletionOnHandler:completionHandler
  150. withStatus:FIRRemoteConfigFetchStatusFailure
  151. withError:error];
  152. }
  153. }
  154. // Check whether cache data is within throttle limit.
  155. if ([strongSelf->_settings shouldThrottle] && !hasDeviceContextChanged) {
  156. // Must set lastFetchStatus before FailReason.
  157. strongSelf->_settings.lastFetchStatus = FIRRemoteConfigFetchStatusThrottled;
  158. strongSelf->_settings.lastFetchError = FIRRemoteConfigErrorThrottled;
  159. NSTimeInterval throttledEndTime = strongSelf->_settings.exponentialBackoffThrottleEndTime;
  160. NSError *error =
  161. [NSError errorWithDomain:FIRRemoteConfigErrorDomain
  162. code:FIRRemoteConfigErrorThrottled
  163. userInfo:@{
  164. FIRRemoteConfigThrottledEndTimeInSecondsKey : @(throttledEndTime)
  165. }];
  166. return [strongSelf reportCompletionOnHandler:completionHandler
  167. withStatus:strongSelf->_settings.lastFetchStatus
  168. withError:error];
  169. }
  170. strongSelf->_settings.isFetchInProgress = YES;
  171. [strongSelf refreshInstallationsTokenWithCompletionHandler:completionHandler];
  172. });
  173. }
  174. #pragma mark - Fetch helpers
  175. - (NSString *)FIRAppNameFromFullyQualifiedNamespace {
  176. return [[_FIRNamespace componentsSeparatedByString:@":"] lastObject];
  177. }
  178. /// Refresh installation ID token before fetching config. installation ID is now mandatory for fetch
  179. /// requests to work.(b/14751422).
  180. - (void)refreshInstallationsTokenWithCompletionHandler:
  181. (FIRRemoteConfigFetchCompletion)completionHandler {
  182. FIRInstallations *installations = [FIRInstallations
  183. installationsWithApp:[FIRApp appNamed:[self FIRAppNameFromFullyQualifiedNamespace]]];
  184. if (!installations || !_options.GCMSenderID) {
  185. NSString *errorDescription = @"Failed to get GCMSenderID";
  186. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000074", @"%@",
  187. [NSString stringWithFormat:@"%@", errorDescription]);
  188. self->_settings.isFetchInProgress = NO;
  189. return [self
  190. reportCompletionOnHandler:completionHandler
  191. withStatus:FIRRemoteConfigFetchStatusFailure
  192. withError:[NSError errorWithDomain:FIRRemoteConfigErrorDomain
  193. code:FIRRemoteConfigErrorInternalError
  194. userInfo:@{
  195. NSLocalizedDescriptionKey : errorDescription
  196. }]];
  197. }
  198. FIRInstallationsTokenHandler installationsTokenHandler = ^(
  199. FIRInstallationsAuthTokenResult *tokenResult, NSError *error) {
  200. if (!tokenResult || !tokenResult.authToken || error) {
  201. NSString *errorDescription =
  202. [NSString stringWithFormat:@"Failed to get installations token. Error : %@.", error];
  203. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000073", @"%@",
  204. [NSString stringWithFormat:@"%@", errorDescription]);
  205. self->_settings.isFetchInProgress = NO;
  206. return [self
  207. reportCompletionOnHandler:completionHandler
  208. withStatus:FIRRemoteConfigFetchStatusFailure
  209. withError:[NSError errorWithDomain:FIRRemoteConfigErrorDomain
  210. code:FIRRemoteConfigErrorInternalError
  211. userInfo:@{
  212. NSLocalizedDescriptionKey : errorDescription
  213. }]];
  214. }
  215. // We have a valid token. Get the backing installationID.
  216. __weak RCNConfigFetch *weakSelf = self;
  217. [installations installationIDWithCompletion:^(NSString *_Nullable identifier,
  218. NSError *_Nullable error) {
  219. RCNConfigFetch *strongSelf = weakSelf;
  220. // Dispatch to the RC serial queue to update settings on the queue.
  221. dispatch_async(strongSelf->_lockQueue, ^{
  222. RCNConfigFetch *strongSelfQueue = weakSelf;
  223. // Update config settings with the IID and token.
  224. strongSelfQueue->_settings.configInstallationsToken = tokenResult.authToken;
  225. strongSelfQueue->_settings.configInstallationsIdentifier = identifier;
  226. if (!identifier || error) {
  227. NSString *errorDescription =
  228. [NSString stringWithFormat:@"Error getting iid : %@.", error];
  229. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000055", @"%@",
  230. [NSString stringWithFormat:@"%@", errorDescription]);
  231. strongSelfQueue->_settings.isFetchInProgress = NO;
  232. return [strongSelfQueue
  233. reportCompletionOnHandler:completionHandler
  234. withStatus:FIRRemoteConfigFetchStatusFailure
  235. withError:[NSError
  236. errorWithDomain:FIRRemoteConfigErrorDomain
  237. code:FIRRemoteConfigErrorInternalError
  238. userInfo:@{
  239. NSLocalizedDescriptionKey : errorDescription
  240. }]];
  241. }
  242. FIRLogInfo(kFIRLoggerRemoteConfig, @"I-RCN000022", @"Success to get iid : %@.",
  243. strongSelfQueue->_settings.configInstallationsIdentifier);
  244. [strongSelf
  245. getAnalyticsUserPropertiesWithCompletionHandler:^(NSDictionary *userProperties) {
  246. dispatch_async(strongSelf->_lockQueue, ^{
  247. [strongSelf fetchWithUserProperties:userProperties
  248. completionHandler:completionHandler];
  249. });
  250. }];
  251. });
  252. }];
  253. };
  254. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000039", @"Starting requesting token.");
  255. [installations authTokenWithCompletion:installationsTokenHandler];
  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. if (gGlobalTestBlock) {
  442. gGlobalTestBlock(fetcherCompletion);
  443. return;
  444. }
  445. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000061", @"Making remote config fetch.");
  446. NSURLSessionDataTask *dataTask = [self URLSessionDataTaskWithContent:compressedContent
  447. completionHandler:fetcherCompletion];
  448. [dataTask resume];
  449. }
  450. + (void)setGlobalTestBlock:(RCNConfigFetcherTestBlock)block {
  451. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000027",
  452. @"Set global test block for NSSessionFetcher, it will not fetch from server.");
  453. gGlobalTestBlock = [block copy];
  454. }
  455. - (NSString *)constructServerURL {
  456. NSString *serverURLStr = [[NSString alloc] initWithString:kServerURLDomain];
  457. serverURLStr = [serverURLStr stringByAppendingString:kServerURLVersion];
  458. if (_options.projectID) {
  459. serverURLStr = [serverURLStr stringByAppendingString:kServerURLProjects];
  460. serverURLStr = [serverURLStr stringByAppendingString:_options.projectID];
  461. } else {
  462. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000070",
  463. @"Missing `projectID` from `FirebaseOptions`, please ensure the configured "
  464. @"`FirebaseApp` is configured with `FirebaseOptions` that contains a `projectID`.");
  465. }
  466. serverURLStr = [serverURLStr stringByAppendingString:kServerURLNamespaces];
  467. // Get the namespace from the fully qualified namespace string of "namespace:FIRAppName".
  468. NSString *namespace =
  469. [_FIRNamespace substringToIndex:[_FIRNamespace rangeOfString:@":"].location];
  470. serverURLStr = [serverURLStr stringByAppendingString:namespace];
  471. serverURLStr = [serverURLStr stringByAppendingString:kServerURLQuery];
  472. if (_options.APIKey) {
  473. serverURLStr = [serverURLStr stringByAppendingString:kServerURLKey];
  474. serverURLStr = [serverURLStr stringByAppendingString:_options.APIKey];
  475. } else {
  476. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000071",
  477. @"Missing `APIKey` from `FirebaseOptions`, please ensure the configured "
  478. @"`FirebaseApp` is configured with `FirebaseOptions` that contains an `APIKey`.");
  479. }
  480. return serverURLStr;
  481. }
  482. - (NSURLSession *)newFetchSession {
  483. NSURLSessionConfiguration *config =
  484. [[NSURLSessionConfiguration defaultSessionConfiguration] copy];
  485. config.timeoutIntervalForRequest = _settings.fetchTimeout;
  486. config.timeoutIntervalForResource = _settings.fetchTimeout;
  487. NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
  488. return session;
  489. }
  490. - (NSURLSessionDataTask *)URLSessionDataTaskWithContent:(NSData *)content
  491. completionHandler:
  492. (RCNConfigFetcherCompletion)fetcherCompletion {
  493. NSURL *URL = [NSURL URLWithString:[self constructServerURL]];
  494. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000046", @"%@",
  495. [NSString stringWithFormat:@"Making config request: %@", [URL absoluteString]]);
  496. NSTimeInterval timeoutInterval = _fetchSession.configuration.timeoutIntervalForResource;
  497. NSMutableURLRequest *URLRequest =
  498. [[NSMutableURLRequest alloc] initWithURL:URL
  499. cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
  500. timeoutInterval:timeoutInterval];
  501. URLRequest.HTTPMethod = kHTTPMethodPost;
  502. [URLRequest setValue:kContentTypeValueJSON forHTTPHeaderField:kContentTypeHeaderName];
  503. [URLRequest setValue:_settings.configInstallationsToken
  504. forHTTPHeaderField:kInstallationsAuthTokenHeaderName];
  505. [URLRequest setValue:[[NSBundle mainBundle] bundleIdentifier]
  506. forHTTPHeaderField:kiOSBundleIdentifierHeaderName];
  507. [URLRequest setValue:@"gzip" forHTTPHeaderField:kContentEncodingHeaderName];
  508. [URLRequest setValue:@"gzip" forHTTPHeaderField:kAcceptEncodingHeaderName];
  509. // Set the eTag from the last successful fetch, if available.
  510. if (_settings.lastETag) {
  511. [URLRequest setValue:_settings.lastETag forHTTPHeaderField:kIfNoneMatchETagHeaderName];
  512. }
  513. [URLRequest setHTTPBody:content];
  514. return [_fetchSession dataTaskWithRequest:URLRequest completionHandler:fetcherCompletion];
  515. }
  516. @end