RCNConfigFetch.m 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  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/Extension/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. NSString *_templateVersionNumber;
  69. }
  70. - (instancetype)init {
  71. NSAssert(NO, @"Invalid initializer.");
  72. return nil;
  73. }
  74. /// Designated initializer
  75. - (instancetype)initWithContent:(RCNConfigContent *)content
  76. DBManager:(RCNConfigDBManager *)DBManager
  77. settings:(RCNConfigSettings *)settings
  78. analytics:(nullable id<FIRAnalyticsInterop>)analytics
  79. experiment:(RCNConfigExperiment *)experiment
  80. queue:(dispatch_queue_t)queue
  81. namespace:(NSString *)FIRNamespace
  82. options:(FIROptions *)options {
  83. self = [super init];
  84. if (self) {
  85. _FIRNamespace = FIRNamespace;
  86. _settings = settings;
  87. _analytics = analytics;
  88. _experiment = experiment;
  89. _lockQueue = queue;
  90. _content = content;
  91. _fetchSession = [self newFetchSession];
  92. _options = options;
  93. _templateVersionNumber = [self->_settings lastTemplateVersion];
  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. excludeEtagHeaderForRealtime:(bool)excludeEtagHeaderForRealtime {
  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. dispatch_async(_lockQueue, ^{
  120. RCNConfigFetch *strongSelf = weakSelf;
  121. if (strongSelf == nil) {
  122. return;
  123. }
  124. // Check whether we are outside of the minimum fetch interval.
  125. if (![strongSelf->_settings hasMinimumFetchIntervalElapsed:expirationDuration] &&
  126. !hasDeviceContextChanged) {
  127. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000051", @"Returning cached data.");
  128. return [strongSelf reportCompletionOnHandler:completionHandler
  129. withStatus:FIRRemoteConfigFetchStatusSuccess
  130. withError:nil];
  131. }
  132. // Check if a fetch is already in progress.
  133. if (strongSelf->_settings.isFetchInProgress) {
  134. // Check if we have some fetched data.
  135. if (strongSelf->_settings.lastFetchTimeInterval > 0) {
  136. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000052",
  137. @"A fetch is already in progress. Using previous fetch results.");
  138. return [strongSelf reportCompletionOnHandler:completionHandler
  139. withStatus:strongSelf->_settings.lastFetchStatus
  140. withError:nil];
  141. } else {
  142. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000053",
  143. @"A fetch is already in progress. Ignoring duplicate request.");
  144. NSError *error =
  145. [NSError errorWithDomain:FIRRemoteConfigErrorDomain
  146. code:sFIRErrorCodeConfigFailed
  147. userInfo:@{
  148. NSLocalizedDescriptionKey :
  149. @"FetchError: Duplicate request while the previous one is pending"
  150. }];
  151. return [strongSelf reportCompletionOnHandler:completionHandler
  152. withStatus:FIRRemoteConfigFetchStatusFailure
  153. withError:error];
  154. }
  155. }
  156. // Check whether cache data is within throttle limit.
  157. if ([strongSelf->_settings shouldThrottle] && !hasDeviceContextChanged) {
  158. // Must set lastFetchStatus before FailReason.
  159. strongSelf->_settings.lastFetchStatus = FIRRemoteConfigFetchStatusThrottled;
  160. strongSelf->_settings.lastFetchError = FIRRemoteConfigErrorThrottled;
  161. NSTimeInterval throttledEndTime = strongSelf->_settings.exponentialBackoffThrottleEndTime;
  162. NSError *error =
  163. [NSError errorWithDomain:FIRRemoteConfigErrorDomain
  164. code:FIRRemoteConfigErrorThrottled
  165. userInfo:@{
  166. FIRRemoteConfigThrottledEndTimeInSecondsKey : @(throttledEndTime)
  167. }];
  168. return [strongSelf reportCompletionOnHandler:completionHandler
  169. withStatus:strongSelf->_settings.lastFetchStatus
  170. withError:error];
  171. }
  172. strongSelf->_settings.isFetchInProgress = YES;
  173. [strongSelf refreshInstallationsTokenWithCompletionHandler:completionHandler
  174. excludeEtagHeaderForRealtime:excludeEtagHeaderForRealtime];
  175. });
  176. }
  177. #pragma mark - Fetch helpers
  178. - (NSString *)FIRAppNameFromFullyQualifiedNamespace {
  179. return [[_FIRNamespace componentsSeparatedByString:@":"] lastObject];
  180. }
  181. /// Refresh installation ID token before fetching config. installation ID is now mandatory for fetch
  182. /// requests to work.(b/14751422).
  183. - (void)refreshInstallationsTokenWithCompletionHandler:
  184. (FIRRemoteConfigFetchCompletion)completionHandler
  185. excludeEtagHeaderForRealtime:(bool)excludeEtagHeaderForRealtime {
  186. FIRInstallations *installations = [FIRInstallations
  187. installationsWithApp:[FIRApp appNamed:[self FIRAppNameFromFullyQualifiedNamespace]]];
  188. if (!installations || !_options.GCMSenderID) {
  189. NSString *errorDescription = @"Failed to get GCMSenderID";
  190. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000074", @"%@",
  191. [NSString stringWithFormat:@"%@", errorDescription]);
  192. self->_settings.isFetchInProgress = NO;
  193. return [self
  194. reportCompletionOnHandler:completionHandler
  195. withStatus:FIRRemoteConfigFetchStatusFailure
  196. withError:[NSError errorWithDomain:FIRRemoteConfigErrorDomain
  197. code:FIRRemoteConfigErrorInternalError
  198. userInfo:@{
  199. NSLocalizedDescriptionKey : errorDescription
  200. }]];
  201. }
  202. __weak RCNConfigFetch *weakSelf = self;
  203. FIRInstallationsTokenHandler installationsTokenHandler = ^(
  204. FIRInstallationsAuthTokenResult *tokenResult, NSError *error) {
  205. RCNConfigFetch *strongSelf = weakSelf;
  206. if (strongSelf == nil) {
  207. return;
  208. }
  209. if (!tokenResult || !tokenResult.authToken || error) {
  210. NSString *errorDescription =
  211. [NSString stringWithFormat:@"Failed to get installations token. Error : %@.", error];
  212. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000073", @"%@",
  213. [NSString stringWithFormat:@"%@", errorDescription]);
  214. strongSelf->_settings.isFetchInProgress = NO;
  215. return [strongSelf
  216. reportCompletionOnHandler:completionHandler
  217. withStatus:FIRRemoteConfigFetchStatusFailure
  218. withError:[NSError errorWithDomain:FIRRemoteConfigErrorDomain
  219. code:FIRRemoteConfigErrorInternalError
  220. userInfo:@{
  221. NSLocalizedDescriptionKey : errorDescription
  222. }]];
  223. }
  224. // We have a valid token. Get the backing installationID.
  225. [installations installationIDWithCompletion:^(NSString *_Nullable identifier,
  226. NSError *_Nullable error) {
  227. RCNConfigFetch *strongSelf = weakSelf;
  228. if (strongSelf == nil) {
  229. return;
  230. }
  231. // Dispatch to the RC serial queue to update settings on the queue.
  232. dispatch_async(strongSelf->_lockQueue, ^{
  233. RCNConfigFetch *strongSelfQueue = weakSelf;
  234. if (strongSelfQueue == nil) {
  235. return;
  236. }
  237. // Update config settings with the IID and token.
  238. strongSelfQueue->_settings.configInstallationsToken = tokenResult.authToken;
  239. strongSelfQueue->_settings.configInstallationsIdentifier = identifier;
  240. if (!identifier || error) {
  241. NSString *errorDescription =
  242. [NSString stringWithFormat:@"Error getting iid : %@.", error];
  243. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000055", @"%@",
  244. [NSString stringWithFormat:@"%@", errorDescription]);
  245. strongSelfQueue->_settings.isFetchInProgress = NO;
  246. return [strongSelfQueue
  247. reportCompletionOnHandler:completionHandler
  248. withStatus:FIRRemoteConfigFetchStatusFailure
  249. withError:[NSError
  250. errorWithDomain:FIRRemoteConfigErrorDomain
  251. code:FIRRemoteConfigErrorInternalError
  252. userInfo:@{
  253. NSLocalizedDescriptionKey : errorDescription
  254. }]];
  255. }
  256. FIRLogInfo(kFIRLoggerRemoteConfig, @"I-RCN000022", @"Success to get iid : %@.",
  257. strongSelfQueue->_settings.configInstallationsIdentifier);
  258. [strongSelf doFetchCall:completionHandler
  259. excludeEtagHeaderForRealtime:excludeEtagHeaderForRealtime];
  260. });
  261. }];
  262. };
  263. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000039", @"Starting requesting token.");
  264. [installations authTokenWithCompletion:installationsTokenHandler];
  265. }
  266. - (void)doFetchCall:(FIRRemoteConfigFetchCompletion)completionHandler
  267. excludeEtagHeaderForRealtime:(bool)excludeEtagHeaderForRealtime {
  268. [self getAnalyticsUserPropertiesWithCompletionHandler:^(NSDictionary *userProperties) {
  269. dispatch_async(self->_lockQueue, ^{
  270. [self fetchWithUserProperties:userProperties
  271. completionHandler:completionHandler
  272. excludeEtagHeaderForRealtime:excludeEtagHeaderForRealtime];
  273. });
  274. }];
  275. }
  276. - (void)getAnalyticsUserPropertiesWithCompletionHandler:
  277. (FIRAInteropUserPropertiesCallback)completionHandler {
  278. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000060", @"Fetch with user properties completed.");
  279. id<FIRAnalyticsInterop> analytics = self->_analytics;
  280. if (analytics == nil) {
  281. completionHandler(@{});
  282. } else {
  283. [analytics getUserPropertiesWithCallback:completionHandler];
  284. }
  285. }
  286. - (void)reportCompletionOnHandler:(FIRRemoteConfigFetchCompletion)completionHandler
  287. withStatus:(FIRRemoteConfigFetchStatus)status
  288. withError:(NSError *)error {
  289. if (completionHandler) {
  290. dispatch_async(dispatch_get_main_queue(), ^{
  291. completionHandler(status, error);
  292. });
  293. }
  294. }
  295. - (void)fetchWithUserProperties:(NSDictionary *)userProperties
  296. completionHandler:(FIRRemoteConfigFetchCompletion)completionHandler
  297. excludeEtagHeaderForRealtime:(bool)excludeEtagHeaderForRealtime {
  298. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000061", @"Fetch with user properties initiated.");
  299. NSString *postRequestString = [_settings nextRequestWithUserProperties:userProperties];
  300. // Get POST request content.
  301. NSData *content = [postRequestString dataUsingEncoding:NSUTF8StringEncoding];
  302. NSError *compressionError;
  303. NSData *compressedContent = [NSData gul_dataByGzippingData:content error:&compressionError];
  304. if (compressionError) {
  305. NSString *errString = [NSString stringWithFormat:@"Failed to compress the config request."];
  306. FIRLogWarning(kFIRLoggerRemoteConfig, @"I-RCN000033", @"%@", errString);
  307. self->_settings.isFetchInProgress = NO;
  308. return [self
  309. reportCompletionOnHandler:completionHandler
  310. withStatus:FIRRemoteConfigFetchStatusFailure
  311. withError:[NSError
  312. errorWithDomain:FIRRemoteConfigErrorDomain
  313. code:FIRRemoteConfigErrorInternalError
  314. userInfo:@{NSLocalizedDescriptionKey : errString}]];
  315. }
  316. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000040", @"Start config fetch.");
  317. __weak RCNConfigFetch *weakSelf = self;
  318. RCNConfigFetcherCompletion fetcherCompletion = ^(NSData *data, NSURLResponse *response,
  319. NSError *error) {
  320. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000050",
  321. @"config fetch completed. Error: %@ StatusCode: %ld", (error ? error : @"nil"),
  322. (long)[((NSHTTPURLResponse *)response) statusCode]);
  323. RCNConfigFetch *fetcherCompletionSelf = weakSelf;
  324. if (fetcherCompletionSelf == nil) {
  325. return;
  326. }
  327. // The fetch has completed.
  328. fetcherCompletionSelf->_settings.isFetchInProgress = NO;
  329. dispatch_async(fetcherCompletionSelf->_lockQueue, ^{
  330. RCNConfigFetch *strongSelf = weakSelf;
  331. if (strongSelf == nil) {
  332. return;
  333. }
  334. NSInteger statusCode = [((NSHTTPURLResponse *)response) statusCode];
  335. if (error || (statusCode != kRCNFetchResponseHTTPStatusCodeOK)) {
  336. // Update metadata about fetch failure.
  337. [strongSelf->_settings updateMetadataWithFetchSuccessStatus:NO templateVersion:nil];
  338. if (error) {
  339. if (strongSelf->_settings.lastFetchStatus == FIRRemoteConfigFetchStatusSuccess) {
  340. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000025",
  341. @"RCN Fetch failure: %@. Using cached config result.", error);
  342. } else {
  343. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000026",
  344. @"RCN Fetch failure: %@. No cached config result.", error);
  345. }
  346. }
  347. if (statusCode != kRCNFetchResponseHTTPStatusCodeOK) {
  348. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000026",
  349. @"RCN Fetch failure. Response http error code: %ld", (long)statusCode);
  350. // Response error code 429, 500, 503 will trigger exponential backoff mode.
  351. if (statusCode == kRCNFetchResponseHTTPStatusTooManyRequests ||
  352. statusCode == kRCNFetchResponseHTTPStatusCodeInternalError ||
  353. statusCode == kRCNFetchResponseHTTPStatusCodeServiceUnavailable ||
  354. statusCode == kRCNFetchResponseHTTPStatusCodeGatewayTimeout) {
  355. [strongSelf->_settings updateExponentialBackoffTime];
  356. if ([strongSelf->_settings shouldThrottle]) {
  357. // Must set lastFetchStatus before FailReason.
  358. strongSelf->_settings.lastFetchStatus = FIRRemoteConfigFetchStatusThrottled;
  359. strongSelf->_settings.lastFetchError = FIRRemoteConfigErrorThrottled;
  360. NSTimeInterval throttledEndTime =
  361. strongSelf->_settings.exponentialBackoffThrottleEndTime;
  362. NSError *error = [NSError
  363. errorWithDomain:FIRRemoteConfigErrorDomain
  364. code:FIRRemoteConfigErrorThrottled
  365. userInfo:@{
  366. FIRRemoteConfigThrottledEndTimeInSecondsKey : @(throttledEndTime)
  367. }];
  368. return [strongSelf reportCompletionOnHandler:completionHandler
  369. withStatus:strongSelf->_settings.lastFetchStatus
  370. withError:error];
  371. }
  372. }
  373. }
  374. // Return back the received error.
  375. // Must set lastFetchStatus before setting Fetch Error.
  376. strongSelf->_settings.lastFetchStatus = FIRRemoteConfigFetchStatusFailure;
  377. strongSelf->_settings.lastFetchError = FIRRemoteConfigErrorInternalError;
  378. NSDictionary<NSErrorUserInfoKey, id> *userInfo = @{
  379. NSLocalizedDescriptionKey :
  380. ([error localizedDescription]
  381. ?: [NSString
  382. stringWithFormat:@"Internal Error. Status code: %ld", (long)statusCode])
  383. };
  384. return [strongSelf
  385. reportCompletionOnHandler:completionHandler
  386. withStatus:FIRRemoteConfigFetchStatusFailure
  387. withError:[NSError errorWithDomain:FIRRemoteConfigErrorDomain
  388. code:FIRRemoteConfigErrorInternalError
  389. userInfo:userInfo]];
  390. }
  391. // Fetch was successful. Check if we have data.
  392. NSError *retError;
  393. if (!data) {
  394. FIRLogInfo(kFIRLoggerRemoteConfig, @"I-RCN000043", @"RCN Fetch: No data in fetch response");
  395. return [strongSelf reportCompletionOnHandler:completionHandler
  396. withStatus:FIRRemoteConfigFetchStatusSuccess
  397. withError:nil];
  398. }
  399. // Config fetch succeeded.
  400. // JSONObjectWithData is always expected to return an NSDictionary in our case
  401. NSMutableDictionary *fetchedConfig =
  402. [NSJSONSerialization JSONObjectWithData:data
  403. options:NSJSONReadingMutableContainers
  404. error:&retError];
  405. if (retError) {
  406. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000042",
  407. @"RCN Fetch failure: %@. Could not parse response data as JSON", error);
  408. }
  409. // Check and log if we received an error from the server
  410. if (fetchedConfig && fetchedConfig.count == 1 && fetchedConfig[RCNFetchResponseKeyError]) {
  411. NSString *errStr = [NSString stringWithFormat:@"RCN Fetch Failure: Server returned error:"];
  412. NSDictionary *errDict = fetchedConfig[RCNFetchResponseKeyError];
  413. if (errDict[RCNFetchResponseKeyErrorCode]) {
  414. errStr = [errStr
  415. stringByAppendingString:[NSString
  416. stringWithFormat:@"code: %@",
  417. errDict[RCNFetchResponseKeyErrorCode]]];
  418. }
  419. if (errDict[RCNFetchResponseKeyErrorStatus]) {
  420. errStr = [errStr stringByAppendingString:
  421. [NSString stringWithFormat:@". Status: %@",
  422. errDict[RCNFetchResponseKeyErrorStatus]]];
  423. }
  424. if (errDict[RCNFetchResponseKeyErrorMessage]) {
  425. errStr =
  426. [errStr stringByAppendingString:
  427. [NSString stringWithFormat:@". Message: %@",
  428. errDict[RCNFetchResponseKeyErrorMessage]]];
  429. }
  430. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000044", @"%@.", errStr);
  431. return [strongSelf
  432. reportCompletionOnHandler:completionHandler
  433. withStatus:FIRRemoteConfigFetchStatusFailure
  434. withError:[NSError
  435. errorWithDomain:FIRRemoteConfigErrorDomain
  436. code:FIRRemoteConfigErrorInternalError
  437. userInfo:@{NSLocalizedDescriptionKey : errStr}]];
  438. }
  439. // Add the fetched config to the database.
  440. if (fetchedConfig) {
  441. // Update config content to cache and DB.
  442. [strongSelf->_content updateConfigContentWithResponse:fetchedConfig
  443. forNamespace:strongSelf->_FIRNamespace];
  444. // Update experiments only for 3p namespace
  445. NSString *namespace = [strongSelf->_FIRNamespace
  446. substringToIndex:[strongSelf->_FIRNamespace rangeOfString:@":"].location];
  447. if ([namespace isEqualToString:FIRNamespaceGoogleMobilePlatform]) {
  448. [strongSelf->_experiment updateExperimentsWithResponse:
  449. fetchedConfig[RCNFetchResponseKeyExperimentDescriptions]];
  450. }
  451. strongSelf->_templateVersionNumber = [strongSelf getTemplateVersionNumber:fetchedConfig];
  452. } else {
  453. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000063",
  454. @"Empty response with no fetched config.");
  455. }
  456. // We had a successful fetch. Update the current eTag in settings if different.
  457. NSString *latestETag = ((NSHTTPURLResponse *)response).allHeaderFields[kETagHeaderName];
  458. if (!strongSelf->_settings.lastETag ||
  459. !([strongSelf->_settings.lastETag isEqualToString:latestETag])) {
  460. strongSelf->_settings.lastETag = latestETag;
  461. }
  462. [strongSelf->_settings
  463. updateMetadataWithFetchSuccessStatus:YES
  464. templateVersion:strongSelf->_templateVersionNumber];
  465. return [strongSelf reportCompletionOnHandler:completionHandler
  466. withStatus:FIRRemoteConfigFetchStatusSuccess
  467. withError:nil];
  468. });
  469. };
  470. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000061", @"Making remote config fetch.");
  471. NSURLSessionDataTask *dataTask =
  472. [self URLSessionDataTaskWithContent:compressedContent
  473. completionHandler:fetcherCompletion
  474. excludeEtagHeaderForRealtime:excludeEtagHeaderForRealtime];
  475. [dataTask resume];
  476. }
  477. - (NSString *)constructServerURL {
  478. NSString *serverURLStr = [[NSString alloc] initWithString:kServerURLDomain];
  479. serverURLStr = [serverURLStr stringByAppendingString:kServerURLVersion];
  480. serverURLStr = [serverURLStr stringByAppendingString:kServerURLProjects];
  481. serverURLStr = [serverURLStr stringByAppendingString:_options.projectID];
  482. serverURLStr = [serverURLStr stringByAppendingString:kServerURLNamespaces];
  483. // Get the namespace from the fully qualified namespace string of "namespace:FIRAppName".
  484. NSString *namespace =
  485. [_FIRNamespace substringToIndex:[_FIRNamespace rangeOfString:@":"].location];
  486. serverURLStr = [serverURLStr stringByAppendingString:namespace];
  487. serverURLStr = [serverURLStr stringByAppendingString:kServerURLQuery];
  488. if (_options.APIKey) {
  489. serverURLStr = [serverURLStr stringByAppendingString:kServerURLKey];
  490. serverURLStr = [serverURLStr stringByAppendingString:_options.APIKey];
  491. } else {
  492. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000071",
  493. @"Missing `APIKey` from `FirebaseOptions`, please ensure the configured "
  494. @"`FirebaseApp` is configured with `FirebaseOptions` that contains an `APIKey`.");
  495. }
  496. return serverURLStr;
  497. }
  498. - (NSURLSession *)newFetchSession {
  499. NSURLSessionConfiguration *config =
  500. [[NSURLSessionConfiguration defaultSessionConfiguration] copy];
  501. config.timeoutIntervalForRequest = _settings.fetchTimeout;
  502. config.timeoutIntervalForResource = _settings.fetchTimeout;
  503. NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
  504. return session;
  505. }
  506. - (NSURLSessionDataTask *)URLSessionDataTaskWithContent:(NSData *)content
  507. completionHandler:
  508. (RCNConfigFetcherCompletion)fetcherCompletion
  509. excludeEtagHeaderForRealtime:(bool)excludeEtagHeaderForRealtime {
  510. NSURL *URL = [NSURL URLWithString:[self constructServerURL]];
  511. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000046", @"%@",
  512. [NSString stringWithFormat:@"Making config request: %@", [URL absoluteString]]);
  513. NSTimeInterval timeoutInterval = _fetchSession.configuration.timeoutIntervalForResource;
  514. NSMutableURLRequest *URLRequest =
  515. [[NSMutableURLRequest alloc] initWithURL:URL
  516. cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
  517. timeoutInterval:timeoutInterval];
  518. URLRequest.HTTPMethod = kHTTPMethodPost;
  519. [URLRequest setValue:kContentTypeValueJSON forHTTPHeaderField:kContentTypeHeaderName];
  520. [URLRequest setValue:_settings.configInstallationsToken
  521. forHTTPHeaderField:kInstallationsAuthTokenHeaderName];
  522. [URLRequest setValue:[[NSBundle mainBundle] bundleIdentifier]
  523. forHTTPHeaderField:kiOSBundleIdentifierHeaderName];
  524. [URLRequest setValue:@"gzip" forHTTPHeaderField:kContentEncodingHeaderName];
  525. [URLRequest setValue:@"gzip" forHTTPHeaderField:kAcceptEncodingHeaderName];
  526. // Set the eTag from the last successful fetch, if available.
  527. if (_settings.lastETag && !excludeEtagHeaderForRealtime) {
  528. [URLRequest setValue:_settings.lastETag forHTTPHeaderField:kIfNoneMatchETagHeaderName];
  529. }
  530. [URLRequest setHTTPBody:content];
  531. return [_fetchSession dataTaskWithRequest:URLRequest completionHandler:fetcherCompletion];
  532. }
  533. - (NSString *)getTemplateVersionNumber:(NSDictionary *)fetchedConfig {
  534. if (fetchedConfig != nil && [fetchedConfig objectForKey:RCNFetchResponseKeyTemplateVersion] &&
  535. [[fetchedConfig objectForKey:RCNFetchResponseKeyTemplateVersion]
  536. isKindOfClass:[NSString class]]) {
  537. return (NSString *)[fetchedConfig objectForKey:RCNFetchResponseKeyTemplateVersion];
  538. }
  539. return @"0";
  540. }
  541. @end