RCNConfigFetch.m 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  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 <GoogleUtilities/GULNSData+zlib.h>
  18. #import "FirebaseCore/Sources/Private/FirebaseCoreInternal.h"
  19. #import "FirebaseInstallations/Source/Library/Private/FirebaseInstallationsInternal.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. dispatch_async(_lockQueue, ^{
  117. RCNConfigFetch *strongSelf = weakSelf;
  118. if (strongSelf == nil) {
  119. return;
  120. }
  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:sFIRErrorCodeConfigFailed
  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. __weak RCNConfigFetch *weakSelf = self;
  198. FIRInstallationsTokenHandler installationsTokenHandler = ^(
  199. FIRInstallationsAuthTokenResult *tokenResult, NSError *error) {
  200. RCNConfigFetch *strongSelf = weakSelf;
  201. if (strongSelf == nil) {
  202. return;
  203. }
  204. if (!tokenResult || !tokenResult.authToken || error) {
  205. NSString *errorDescription =
  206. [NSString stringWithFormat:@"Failed to get installations token. Error : %@.", error];
  207. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000073", @"%@",
  208. [NSString stringWithFormat:@"%@", errorDescription]);
  209. strongSelf->_settings.isFetchInProgress = NO;
  210. return [strongSelf
  211. reportCompletionOnHandler:completionHandler
  212. withStatus:FIRRemoteConfigFetchStatusFailure
  213. withError:[NSError errorWithDomain:FIRRemoteConfigErrorDomain
  214. code:FIRRemoteConfigErrorInternalError
  215. userInfo:@{
  216. NSLocalizedDescriptionKey : errorDescription
  217. }]];
  218. }
  219. // We have a valid token. Get the backing installationID.
  220. [installations installationIDWithCompletion:^(NSString *_Nullable identifier,
  221. NSError *_Nullable error) {
  222. RCNConfigFetch *strongSelf = weakSelf;
  223. if (strongSelf == nil) {
  224. return;
  225. }
  226. // Dispatch to the RC serial queue to update settings on the queue.
  227. dispatch_async(strongSelf->_lockQueue, ^{
  228. RCNConfigFetch *strongSelfQueue = weakSelf;
  229. if (strongSelfQueue == nil) {
  230. return;
  231. }
  232. // Update config settings with the IID and token.
  233. strongSelfQueue->_settings.configInstallationsToken = tokenResult.authToken;
  234. strongSelfQueue->_settings.configInstallationsIdentifier = identifier;
  235. if (!identifier || error) {
  236. NSString *errorDescription =
  237. [NSString stringWithFormat:@"Error getting iid : %@.", error];
  238. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000055", @"%@",
  239. [NSString stringWithFormat:@"%@", errorDescription]);
  240. strongSelfQueue->_settings.isFetchInProgress = NO;
  241. return [strongSelfQueue
  242. reportCompletionOnHandler:completionHandler
  243. withStatus:FIRRemoteConfigFetchStatusFailure
  244. withError:[NSError
  245. errorWithDomain:FIRRemoteConfigErrorDomain
  246. code:FIRRemoteConfigErrorInternalError
  247. userInfo:@{
  248. NSLocalizedDescriptionKey : errorDescription
  249. }]];
  250. }
  251. FIRLogInfo(kFIRLoggerRemoteConfig, @"I-RCN000022", @"Success to get iid : %@.",
  252. strongSelfQueue->_settings.configInstallationsIdentifier);
  253. [strongSelf doFetchCall:completionHandler];
  254. });
  255. }];
  256. };
  257. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000039", @"Starting requesting token.");
  258. [installations authTokenWithCompletion:installationsTokenHandler];
  259. }
  260. - (void)doFetchCall:(FIRRemoteConfigFetchCompletion)completionHandler {
  261. [self getAnalyticsUserPropertiesWithCompletionHandler:^(NSDictionary *userProperties) {
  262. dispatch_async(self->_lockQueue, ^{
  263. [self fetchWithUserProperties:userProperties completionHandler:completionHandler];
  264. });
  265. }];
  266. }
  267. - (void)getAnalyticsUserPropertiesWithCompletionHandler:
  268. (FIRAInteropUserPropertiesCallback)completionHandler {
  269. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000060", @"Fetch with user properties completed.");
  270. id<FIRAnalyticsInterop> analytics = self->_analytics;
  271. if (analytics == nil) {
  272. completionHandler(@{});
  273. } else {
  274. [analytics getUserPropertiesWithCallback:completionHandler];
  275. }
  276. }
  277. - (void)reportCompletionOnHandler:(FIRRemoteConfigFetchCompletion)completionHandler
  278. withStatus:(FIRRemoteConfigFetchStatus)status
  279. withError:(NSError *)error {
  280. if (completionHandler) {
  281. dispatch_async(dispatch_get_main_queue(), ^{
  282. completionHandler(status, error);
  283. });
  284. }
  285. }
  286. - (void)fetchWithUserProperties:(NSDictionary *)userProperties
  287. completionHandler:(FIRRemoteConfigFetchCompletion)completionHandler {
  288. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000061", @"Fetch with user properties initiated.");
  289. NSString *postRequestString = [_settings nextRequestWithUserProperties:userProperties];
  290. // Get POST request content.
  291. NSData *content = [postRequestString dataUsingEncoding:NSUTF8StringEncoding];
  292. NSError *compressionError;
  293. NSData *compressedContent = [NSData gul_dataByGzippingData:content error:&compressionError];
  294. if (compressionError) {
  295. NSString *errString = [NSString stringWithFormat:@"Failed to compress the config request."];
  296. FIRLogWarning(kFIRLoggerRemoteConfig, @"I-RCN000033", @"%@", errString);
  297. self->_settings.isFetchInProgress = NO;
  298. return [self
  299. reportCompletionOnHandler:completionHandler
  300. withStatus:FIRRemoteConfigFetchStatusFailure
  301. withError:[NSError
  302. errorWithDomain:FIRRemoteConfigErrorDomain
  303. code:FIRRemoteConfigErrorInternalError
  304. userInfo:@{NSLocalizedDescriptionKey : errString}]];
  305. }
  306. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000040", @"Start config fetch.");
  307. __weak RCNConfigFetch *weakSelf = self;
  308. RCNConfigFetcherCompletion fetcherCompletion = ^(NSData *data, NSURLResponse *response,
  309. NSError *error) {
  310. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000050",
  311. @"config fetch completed. Error: %@ StatusCode: %ld", (error ? error : @"nil"),
  312. (long)[((NSHTTPURLResponse *)response) statusCode]);
  313. RCNConfigFetch *fetcherCompletionSelf = weakSelf;
  314. if (fetcherCompletionSelf == nil) {
  315. return;
  316. }
  317. // The fetch has completed.
  318. fetcherCompletionSelf->_settings.isFetchInProgress = NO;
  319. dispatch_async(fetcherCompletionSelf->_lockQueue, ^{
  320. RCNConfigFetch *strongSelf = weakSelf;
  321. if (strongSelf == nil) {
  322. return;
  323. }
  324. NSInteger statusCode = [((NSHTTPURLResponse *)response) statusCode];
  325. if (error || (statusCode != kRCNFetchResponseHTTPStatusCodeOK)) {
  326. // Update metadata about fetch failure.
  327. [strongSelf->_settings updateMetadataWithFetchSuccessStatus:NO];
  328. if (error) {
  329. if (strongSelf->_settings.lastFetchStatus == FIRRemoteConfigFetchStatusSuccess) {
  330. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000025",
  331. @"RCN Fetch failure: %@. Using cached config result.", error);
  332. } else {
  333. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000026",
  334. @"RCN Fetch failure: %@. No cached config result.", error);
  335. }
  336. }
  337. if (statusCode != kRCNFetchResponseHTTPStatusCodeOK) {
  338. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000026",
  339. @"RCN Fetch failure. Response http error code: %ld", (long)statusCode);
  340. // Response error code 429, 500, 503 will trigger exponential backoff mode.
  341. if (statusCode == kRCNFetchResponseHTTPStatusTooManyRequests ||
  342. statusCode == kRCNFetchResponseHTTPStatusCodeInternalError ||
  343. statusCode == kRCNFetchResponseHTTPStatusCodeServiceUnavailable ||
  344. statusCode == kRCNFetchResponseHTTPStatusCodeGatewayTimeout) {
  345. if ([strongSelf->_settings shouldThrottle]) {
  346. // Must set lastFetchStatus before FailReason.
  347. strongSelf->_settings.lastFetchStatus = FIRRemoteConfigFetchStatusThrottled;
  348. strongSelf->_settings.lastFetchError = FIRRemoteConfigErrorThrottled;
  349. NSTimeInterval throttledEndTime =
  350. strongSelf->_settings.exponentialBackoffThrottleEndTime;
  351. NSError *error = [NSError
  352. errorWithDomain:FIRRemoteConfigErrorDomain
  353. code:FIRRemoteConfigErrorThrottled
  354. userInfo:@{
  355. FIRRemoteConfigThrottledEndTimeInSecondsKey : @(throttledEndTime)
  356. }];
  357. return [strongSelf reportCompletionOnHandler:completionHandler
  358. withStatus:strongSelf->_settings.lastFetchStatus
  359. withError:error];
  360. }
  361. } // Response error code 429, 500, 503
  362. } // StatusCode != kRCNFetchResponseHTTPStatusCodeOK
  363. // Return back the received error.
  364. // Must set lastFetchStatus before setting Fetch Error.
  365. strongSelf->_settings.lastFetchStatus = FIRRemoteConfigFetchStatusFailure;
  366. strongSelf->_settings.lastFetchError = FIRRemoteConfigErrorInternalError;
  367. NSDictionary<NSErrorUserInfoKey, id> *userInfo = @{
  368. NSLocalizedDescriptionKey :
  369. ([error localizedDescription]
  370. ?: [NSString
  371. stringWithFormat:@"Internal Error. Status code: %ld", (long)statusCode])
  372. };
  373. return [strongSelf
  374. reportCompletionOnHandler:completionHandler
  375. withStatus:FIRRemoteConfigFetchStatusFailure
  376. withError:[NSError errorWithDomain:FIRRemoteConfigErrorDomain
  377. code:FIRRemoteConfigErrorInternalError
  378. userInfo:userInfo]];
  379. }
  380. // Fetch was successful. Check if we have data.
  381. NSError *retError;
  382. if (!data) {
  383. FIRLogInfo(kFIRLoggerRemoteConfig, @"I-RCN000043", @"RCN Fetch: No data in fetch response");
  384. return [strongSelf reportCompletionOnHandler:completionHandler
  385. withStatus:FIRRemoteConfigFetchStatusSuccess
  386. withError:nil];
  387. }
  388. // Config fetch succeeded.
  389. // JSONObjectWithData is always expected to return an NSDictionary in our case
  390. NSMutableDictionary *fetchedConfig =
  391. [NSJSONSerialization JSONObjectWithData:data
  392. options:NSJSONReadingMutableContainers
  393. error:&retError];
  394. if (retError) {
  395. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000042",
  396. @"RCN Fetch failure: %@. Could not parse response data as JSON", error);
  397. }
  398. // Check and log if we received an error from the server
  399. if (fetchedConfig && fetchedConfig.count == 1 && fetchedConfig[RCNFetchResponseKeyError]) {
  400. NSString *errStr = [NSString stringWithFormat:@"RCN Fetch Failure: Server returned error:"];
  401. NSDictionary *errDict = fetchedConfig[RCNFetchResponseKeyError];
  402. if (errDict[RCNFetchResponseKeyErrorCode]) {
  403. errStr = [errStr
  404. stringByAppendingString:[NSString
  405. stringWithFormat:@"code: %@",
  406. errDict[RCNFetchResponseKeyErrorCode]]];
  407. }
  408. if (errDict[RCNFetchResponseKeyErrorStatus]) {
  409. errStr = [errStr stringByAppendingString:
  410. [NSString stringWithFormat:@". Status: %@",
  411. errDict[RCNFetchResponseKeyErrorStatus]]];
  412. }
  413. if (errDict[RCNFetchResponseKeyErrorMessage]) {
  414. errStr =
  415. [errStr stringByAppendingString:
  416. [NSString stringWithFormat:@". Message: %@",
  417. errDict[RCNFetchResponseKeyErrorMessage]]];
  418. }
  419. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000044", @"%@.", errStr);
  420. return [strongSelf
  421. reportCompletionOnHandler:completionHandler
  422. withStatus:FIRRemoteConfigFetchStatusFailure
  423. withError:[NSError
  424. errorWithDomain:FIRRemoteConfigErrorDomain
  425. code:FIRRemoteConfigErrorInternalError
  426. userInfo:@{NSLocalizedDescriptionKey : errStr}]];
  427. }
  428. // Add the fetched config to the database.
  429. if (fetchedConfig) {
  430. // Update config content to cache and DB.
  431. [strongSelf->_content updateConfigContentWithResponse:fetchedConfig
  432. forNamespace:strongSelf->_FIRNamespace];
  433. // Update experiments.
  434. [strongSelf->_experiment
  435. updateExperimentsWithResponse:fetchedConfig[RCNFetchResponseKeyExperimentDescriptions]];
  436. } else {
  437. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000063",
  438. @"Empty response with no fetched config.");
  439. }
  440. // We had a successful fetch. Update the current eTag in settings if different.
  441. NSString *latestETag = ((NSHTTPURLResponse *)response).allHeaderFields[kETagHeaderName];
  442. if (!strongSelf->_settings.lastETag ||
  443. !([strongSelf->_settings.lastETag isEqualToString:latestETag])) {
  444. strongSelf->_settings.lastETag = latestETag;
  445. }
  446. [strongSelf->_settings updateMetadataWithFetchSuccessStatus:YES];
  447. return [strongSelf reportCompletionOnHandler:completionHandler
  448. withStatus:FIRRemoteConfigFetchStatusSuccess
  449. withError:nil];
  450. });
  451. };
  452. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000061", @"Making remote config fetch.");
  453. NSURLSessionDataTask *dataTask = [self URLSessionDataTaskWithContent:compressedContent
  454. completionHandler:fetcherCompletion];
  455. [dataTask resume];
  456. }
  457. - (NSString *)constructServerURL {
  458. NSString *serverURLStr = [[NSString alloc] initWithString:kServerURLDomain];
  459. serverURLStr = [serverURLStr stringByAppendingString:kServerURLVersion];
  460. if (_options.projectID) {
  461. serverURLStr = [serverURLStr stringByAppendingString:kServerURLProjects];
  462. serverURLStr = [serverURLStr stringByAppendingString:_options.projectID];
  463. } else {
  464. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000070",
  465. @"Missing `projectID` from `FirebaseOptions`, please ensure the configured "
  466. @"`FirebaseApp` is configured with `FirebaseOptions` that contains a `projectID`.");
  467. }
  468. serverURLStr = [serverURLStr stringByAppendingString:kServerURLNamespaces];
  469. // Get the namespace from the fully qualified namespace string of "namespace:FIRAppName".
  470. NSString *namespace =
  471. [_FIRNamespace substringToIndex:[_FIRNamespace rangeOfString:@":"].location];
  472. serverURLStr = [serverURLStr stringByAppendingString:namespace];
  473. serverURLStr = [serverURLStr stringByAppendingString:kServerURLQuery];
  474. if (_options.APIKey) {
  475. serverURLStr = [serverURLStr stringByAppendingString:kServerURLKey];
  476. serverURLStr = [serverURLStr stringByAppendingString:_options.APIKey];
  477. } else {
  478. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000071",
  479. @"Missing `APIKey` from `FirebaseOptions`, please ensure the configured "
  480. @"`FirebaseApp` is configured with `FirebaseOptions` that contains an `APIKey`.");
  481. }
  482. return serverURLStr;
  483. }
  484. - (NSURLSession *)newFetchSession {
  485. NSURLSessionConfiguration *config =
  486. [[NSURLSessionConfiguration defaultSessionConfiguration] copy];
  487. config.timeoutIntervalForRequest = _settings.fetchTimeout;
  488. config.timeoutIntervalForResource = _settings.fetchTimeout;
  489. NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
  490. return session;
  491. }
  492. - (NSURLSessionDataTask *)URLSessionDataTaskWithContent:(NSData *)content
  493. completionHandler:
  494. (RCNConfigFetcherCompletion)fetcherCompletion {
  495. NSURL *URL = [NSURL URLWithString:[self constructServerURL]];
  496. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000046", @"%@",
  497. [NSString stringWithFormat:@"Making config request: %@", [URL absoluteString]]);
  498. NSTimeInterval timeoutInterval = _fetchSession.configuration.timeoutIntervalForResource;
  499. NSMutableURLRequest *URLRequest =
  500. [[NSMutableURLRequest alloc] initWithURL:URL
  501. cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
  502. timeoutInterval:timeoutInterval];
  503. URLRequest.HTTPMethod = kHTTPMethodPost;
  504. [URLRequest setValue:kContentTypeValueJSON forHTTPHeaderField:kContentTypeHeaderName];
  505. [URLRequest setValue:_settings.configInstallationsToken
  506. forHTTPHeaderField:kInstallationsAuthTokenHeaderName];
  507. [URLRequest setValue:[[NSBundle mainBundle] bundleIdentifier]
  508. forHTTPHeaderField:kiOSBundleIdentifierHeaderName];
  509. [URLRequest setValue:@"gzip" forHTTPHeaderField:kContentEncodingHeaderName];
  510. [URLRequest setValue:@"gzip" forHTTPHeaderField:kAcceptEncodingHeaderName];
  511. // Set the eTag from the last successful fetch, if available.
  512. if (_settings.lastETag) {
  513. [URLRequest setValue:_settings.lastETag forHTTPHeaderField:kIfNoneMatchETagHeaderName];
  514. }
  515. [URLRequest setHTTPBody:content];
  516. return [_fetchSession dataTaskWithRequest:URLRequest completionHandler:fetcherCompletion];
  517. }
  518. @end