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