RCNFetch.m 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  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)fetchAllConfigsWithExpirationDuration:(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. if (strongSelf->_settings.isFetchInProgress) {
  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:FIRErrorCodeConfigFailed
  144. userInfo:@{
  145. @"FetchError" : @"Duplicate request while the previous one is pending"
  146. }];
  147. return [strongSelf reportCompletionOnHandler:completionHandler
  148. withStatus:FIRRemoteConfigFetchStatusFailure
  149. withError:error];
  150. }
  151. }
  152. // Check whether cache data is within throttle limit.
  153. if ([strongSelf->_settings shouldThrottle] && !hasDeviceContextChanged) {
  154. // Must set lastFetchStatus before FailReason.
  155. strongSelf->_settings.lastFetchStatus = FIRRemoteConfigFetchStatusThrottled;
  156. strongSelf->_settings.lastFetchError = FIRRemoteConfigErrorThrottled;
  157. NSTimeInterval throttledEndTime = strongSelf->_settings.exponentialBackoffThrottleEndTime;
  158. NSError *error =
  159. [NSError errorWithDomain:FIRRemoteConfigErrorDomain
  160. code:FIRRemoteConfigErrorThrottled
  161. userInfo:@{
  162. FIRRemoteConfigThrottledEndTimeInSecondsKey : @(throttledEndTime)
  163. }];
  164. return [strongSelf reportCompletionOnHandler:completionHandler
  165. withStatus:strongSelf->_settings.lastFetchStatus
  166. withError:error];
  167. }
  168. strongSelf->_settings.isFetchInProgress = YES;
  169. [strongSelf refreshInstanceIDTokenAndFetchCheckInInfoWithCompletionHandler:completionHandler];
  170. });
  171. }
  172. #pragma mark - Fetch helpers
  173. /// Refresh instance ID token before fetching config. Instance ID is an optional field in config
  174. /// request.
  175. - (void)refreshInstanceIDTokenAndFetchCheckInInfoWithCompletionHandler:
  176. (FIRRemoteConfigFetchCompletion)completionHandler {
  177. FIRInstanceID *instanceID = [FIRInstanceID instanceID];
  178. // Only refresh instance ID when a valid sender ID is provided. If not, continue without
  179. // fetching instance ID. Instance ID is for data analytics purpose, which is only optional for
  180. // config fetching.
  181. if (!_options.GCMSenderID) {
  182. [self fetchCheckinInfoWithCompletionHandler:completionHandler];
  183. return;
  184. }
  185. __weak RCNConfigFetch *weakSelf = self;
  186. FIRInstanceIDTokenHandler instanceIDHandler = ^(NSString *token, NSError *error) {
  187. RCNConfigFetch *instanceIDHandlerSelf = weakSelf;
  188. dispatch_async(instanceIDHandlerSelf->_lockQueue, ^{
  189. RCNConfigFetch *strongSelf = instanceIDHandlerSelf;
  190. if (error) {
  191. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000020",
  192. @"Failed to register InstanceID with error : %@.", error);
  193. }
  194. if (token) {
  195. NSError *IIDError;
  196. strongSelf->_settings.configInstanceIDToken = [token copy];
  197. strongSelf->_settings.configInstanceID = [instanceID appInstanceID:&IIDError];
  198. FIRLogInfo(kFIRLoggerRemoteConfig, @"I-RCN000022", @"Success to get iid : %@.",
  199. strongSelf->_settings.configInstanceID);
  200. }
  201. // Continue the fetch regardless of whether fetch of instance ID succeeded.
  202. [strongSelf fetchCheckinInfoWithCompletionHandler:completionHandler];
  203. });
  204. };
  205. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000039", @"Starting requesting token.");
  206. // Note: We expect the GCMSenderID to always be available by the time this request is made.
  207. [instanceID tokenWithAuthorizedEntity:_options.GCMSenderID
  208. scope:kInstanceIDScopeConfig
  209. options:nil
  210. handler:instanceIDHandler];
  211. }
  212. /// Fetch checkin info before fetching config. Checkin info including device authentication ID,
  213. /// secret token and device data version are optional fields in config request.
  214. - (void)fetchCheckinInfoWithCompletionHandler:(FIRRemoteConfigFetchCompletion)completionHandler {
  215. FIRInstanceID *instanceID = [FIRInstanceID instanceID];
  216. __weak RCNConfigFetch *weakSelf = self;
  217. [instanceID fetchCheckinInfoWithHandler:^(FIRInstanceIDCheckinPreferences *preferences,
  218. NSError *error) {
  219. RCNConfigFetch *fetchCheckinInfoWithHandlerSelf = weakSelf;
  220. dispatch_async(fetchCheckinInfoWithHandlerSelf->_lockQueue, ^{
  221. RCNConfigFetch *strongSelf = fetchCheckinInfoWithHandlerSelf;
  222. if (error) {
  223. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000023", @"Failed to fetch checkin info: %@.",
  224. error);
  225. } else {
  226. strongSelf->_settings.deviceAuthID = preferences.deviceID;
  227. strongSelf->_settings.secretToken = preferences.secretToken;
  228. strongSelf->_settings.deviceDataVersion = preferences.deviceDataVersion;
  229. if (strongSelf->_settings.deviceAuthID.length && strongSelf->_settings.secretToken.length) {
  230. FIRLogInfo(kFIRLoggerRemoteConfig, @"I-RCN000024",
  231. @"Success to get device authentication ID: %@, security token: %@.",
  232. self->_settings.deviceAuthID, self->_settings.secretToken);
  233. }
  234. }
  235. // Checkin info is optional, continue fetch config regardless fetch of checkin info
  236. // succeeded.
  237. [strongSelf fetchWithUserPropertiesCompletionHandler:^(NSDictionary *userProperties) {
  238. dispatch_async(strongSelf->_lockQueue, ^{
  239. [strongSelf fetchWithUserProperties:userProperties completionHandler:completionHandler];
  240. });
  241. }];
  242. });
  243. }];
  244. }
  245. - (void)fetchWithUserPropertiesCompletionHandler:
  246. (FIRAInteropUserPropertiesCallback)completionHandler {
  247. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000060", @"Fetch with user properties completed.");
  248. id<FIRAnalyticsInterop> analytics = self->_analytics;
  249. if (analytics == nil) {
  250. completionHandler(@{});
  251. } else {
  252. [analytics getUserPropertiesWithCallback:completionHandler];
  253. }
  254. }
  255. - (void)reportCompletionOnHandler:(FIRRemoteConfigFetchCompletion)completionHandler
  256. withStatus:(FIRRemoteConfigFetchStatus)status
  257. withError:(NSError *)error {
  258. if (completionHandler) {
  259. dispatch_async(dispatch_get_main_queue(), ^{
  260. completionHandler(status, error);
  261. });
  262. }
  263. }
  264. - (void)fetchWithUserProperties:(NSDictionary *)userProperties
  265. completionHandler:(FIRRemoteConfigFetchCompletion)completionHandler {
  266. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000061", @"Fetch with user properties initiated.");
  267. NSString *postRequestString = [_settings nextRequestWithUserProperties:userProperties];
  268. // Get POST request content.
  269. NSData *content = [postRequestString dataUsingEncoding:NSUTF8StringEncoding];
  270. NSError *compressionError;
  271. NSData *compressedContent = [NSData gul_dataByGzippingData:content error:&compressionError];
  272. if (compressionError) {
  273. NSString *errString = [NSString stringWithFormat:@"Failed to compress the config request."];
  274. FIRLogWarning(kFIRLoggerRemoteConfig, @"I-RCN000033", @"%@", errString);
  275. return [self
  276. reportCompletionOnHandler:completionHandler
  277. withStatus:FIRRemoteConfigFetchStatusFailure
  278. withError:[NSError
  279. errorWithDomain:FIRRemoteConfigErrorDomain
  280. code:FIRRemoteConfigErrorInternalError
  281. userInfo:@{NSLocalizedDescriptionKey : errString}]];
  282. }
  283. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000040", @"Start config fetch.");
  284. __weak RCNConfigFetch *weakSelf = self;
  285. RCNConfigFetcherCompletion fetcherCompletion = ^(NSData *data, NSURLResponse *response,
  286. NSError *error) {
  287. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000050",
  288. @"config fetch completed. Error: %@ StatusCode: %ld", (error ? error : @"nil"),
  289. (long)[((NSHTTPURLResponse *)response) statusCode]);
  290. RCNConfigFetch *fetcherCompletionSelf = weakSelf;
  291. if (!fetcherCompletionSelf) {
  292. return;
  293. };
  294. dispatch_async(fetcherCompletionSelf->_lockQueue, ^{
  295. RCNConfigFetch *strongSelf = weakSelf;
  296. if (!strongSelf) {
  297. return;
  298. }
  299. strongSelf->_settings.isFetchInProgress = NO;
  300. NSInteger statusCode = [((NSHTTPURLResponse *)response) statusCode];
  301. if (error || (statusCode != kRCNFetchResponseHTTPStatusCodeOK)) {
  302. // Update failure fetch time and database.
  303. [strongSelf->_settings updateMetadataWithFetchSuccessStatus:NO];
  304. if (error) {
  305. if (strongSelf->_settings.lastFetchStatus == FIRRemoteConfigFetchStatusSuccess) {
  306. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000025",
  307. @"RCN Fetch failure: %@. Using cached config result.", error);
  308. } else {
  309. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000026",
  310. @"RCN Fetch failure: %@. No cached config result.", error);
  311. }
  312. }
  313. if (statusCode != kRCNFetchResponseHTTPStatusCodeOK) {
  314. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000026",
  315. @"RCN Fetch failure. Response http error code: %ld", (long)statusCode);
  316. // Response error code 429, 500, 503 will trigger exponential backoff mode.
  317. if (statusCode == kRCNFetchResponseHTTPStatusTooManyRequests ||
  318. statusCode == kRCNFetchResponseHTTPStatusCodeInternalError ||
  319. statusCode == kRCNFetchResponseHTTPStatusCodeServiceUnavailable ||
  320. statusCode == kRCNFetchResponseHTTPStatusCodeGatewayTimeout) {
  321. if ([strongSelf->_settings shouldThrottle]) {
  322. // Must set lastFetchStatus before FailReason.
  323. strongSelf->_settings.lastFetchStatus = FIRRemoteConfigFetchStatusThrottled;
  324. strongSelf->_settings.lastFetchError = FIRRemoteConfigErrorThrottled;
  325. NSTimeInterval throttledEndTime =
  326. strongSelf->_settings.exponentialBackoffThrottleEndTime;
  327. NSError *error = [NSError
  328. errorWithDomain:FIRRemoteConfigErrorDomain
  329. code:FIRRemoteConfigErrorThrottled
  330. userInfo:@{
  331. FIRRemoteConfigThrottledEndTimeInSecondsKey : @(throttledEndTime)
  332. }];
  333. return [strongSelf reportCompletionOnHandler:completionHandler
  334. withStatus:strongSelf->_settings.lastFetchStatus
  335. withError:error];
  336. } else {
  337. // Return back the received error.
  338. // Must set lastFetchStatus before setting Fetch Error.
  339. strongSelf->_settings.lastFetchStatus = FIRRemoteConfigFetchStatusFailure;
  340. strongSelf->_settings.lastFetchError = FIRRemoteConfigErrorInternalError;
  341. NSDictionary<NSErrorUserInfoKey, id> *userInfo = @{
  342. NSLocalizedDescriptionKey :
  343. (error ? [error localizedDescription]
  344. : [NSString stringWithFormat:@"Internal Error. Status code: %ld",
  345. (long)statusCode])
  346. };
  347. return [strongSelf
  348. reportCompletionOnHandler:completionHandler
  349. withStatus:FIRRemoteConfigFetchStatusFailure
  350. withError:[NSError
  351. errorWithDomain:FIRRemoteConfigErrorDomain
  352. code:FIRRemoteConfigErrorInternalError
  353. userInfo:userInfo]];
  354. }
  355. }
  356. }
  357. }
  358. // Fetch was successful. Check if we have data.
  359. NSError *retError;
  360. if (!data) {
  361. FIRLogInfo(kFIRLoggerRemoteConfig, @"I-RCN000043", @"RCN Fetch: No data in fetch response");
  362. return [strongSelf reportCompletionOnHandler:completionHandler
  363. withStatus:FIRRemoteConfigFetchStatusSuccess
  364. withError:nil];
  365. }
  366. // Config fetch succeeded.
  367. // JSONObjectWithData is always expected to return an NSDictionary in our case
  368. NSMutableDictionary *fetchedConfig =
  369. [NSJSONSerialization JSONObjectWithData:data
  370. options:NSJSONReadingMutableContainers
  371. error:&retError];
  372. if (retError) {
  373. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000042",
  374. @"RCN Fetch failure: %@. Could not parse response data as JSON", error);
  375. }
  376. // Check and log if we received an error from the server
  377. if (fetchedConfig && fetchedConfig.count == 1 && fetchedConfig[RCNFetchResponseKeyError]) {
  378. NSString *errStr = [NSString stringWithFormat:@"RCN Fetch Failure: Server returned error:"];
  379. NSDictionary *errDict = fetchedConfig[RCNFetchResponseKeyError];
  380. if (errDict[RCNFetchResponseKeyErrorCode]) {
  381. errStr = [errStr
  382. stringByAppendingString:[NSString
  383. stringWithFormat:@"code: %@",
  384. errDict[RCNFetchResponseKeyErrorCode]]];
  385. }
  386. if (errDict[RCNFetchResponseKeyErrorStatus]) {
  387. errStr = [errStr stringByAppendingString:
  388. [NSString stringWithFormat:@". Status: %@",
  389. errDict[RCNFetchResponseKeyErrorStatus]]];
  390. }
  391. if (errDict[RCNFetchResponseKeyErrorMessage]) {
  392. errStr =
  393. [errStr stringByAppendingString:
  394. [NSString stringWithFormat:@". Message: %@",
  395. errDict[RCNFetchResponseKeyErrorMessage]]];
  396. }
  397. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000044", @"%@.", errStr);
  398. return [strongSelf
  399. reportCompletionOnHandler:completionHandler
  400. withStatus:FIRRemoteConfigFetchStatusFailure
  401. withError:[NSError
  402. errorWithDomain:FIRRemoteConfigErrorDomain
  403. code:FIRRemoteConfigErrorInternalError
  404. userInfo:@{NSLocalizedDescriptionKey : errStr}]];
  405. }
  406. // Add the fetched config to the database.
  407. if (fetchedConfig) {
  408. // Update config content to cache and DB.
  409. [self->_content updateConfigContentWithResponse:fetchedConfig
  410. forNamespace:self->_FIRNamespace];
  411. // Update experiments.
  412. [strongSelf->_experiment
  413. updateExperimentsWithResponse:fetchedConfig[RCNFetchResponseKeyExperimentDescriptions]];
  414. } else {
  415. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000063",
  416. @"Empty response with no fetched config.");
  417. }
  418. // We had a successful fetch. Update the current eTag in settings.
  419. self->_settings.lastETag = ((NSHTTPURLResponse *)response).allHeaderFields[kETagHeaderName];
  420. [self->_settings updateMetadataWithFetchSuccessStatus:YES];
  421. return [strongSelf reportCompletionOnHandler:completionHandler
  422. withStatus:FIRRemoteConfigFetchStatusSuccess
  423. withError:nil];
  424. });
  425. };
  426. if (gGlobalTestBlock) {
  427. gGlobalTestBlock(fetcherCompletion);
  428. return;
  429. }
  430. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000061", @"Making remote config fetch.");
  431. NSURLSessionDataTask *dataTask = [self URLSessionDataTaskWithContent:compressedContent
  432. completionHandler:fetcherCompletion];
  433. [dataTask resume];
  434. }
  435. + (void)setGlobalTestBlock:(RCNConfigFetcherTestBlock)block {
  436. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000027",
  437. @"Set global test block for NSSessionFetcher, it will not fetch from server.");
  438. gGlobalTestBlock = [block copy];
  439. }
  440. - (NSString *)constructServerURL {
  441. NSString *serverURLStr = [[NSString alloc] initWithString:kServerURLDomain];
  442. serverURLStr = [serverURLStr stringByAppendingString:kServerURLVersion];
  443. if (_options.projectID) {
  444. serverURLStr = [serverURLStr stringByAppendingString:kServerURLProjects];
  445. serverURLStr = [serverURLStr stringByAppendingString:_options.projectID];
  446. } else {
  447. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000070",
  448. @"Missing `projectID` from `FirebaseOptions`, please ensure the configured "
  449. @"`FirebaseApp` is configured with `FirebaseOptions` that contains a `projectID`.");
  450. }
  451. serverURLStr = [serverURLStr stringByAppendingString:kServerURLNamespaces];
  452. // Get the namespace from the fully qualified namespace string of "namespace:FIRAppName".
  453. NSString *namespace =
  454. [_FIRNamespace substringToIndex:[_FIRNamespace rangeOfString:@":"].location];
  455. serverURLStr = [serverURLStr stringByAppendingString:namespace];
  456. serverURLStr = [serverURLStr stringByAppendingString:kServerURLQuery];
  457. if (_options.APIKey) {
  458. serverURLStr = [serverURLStr stringByAppendingString:kServerURLKey];
  459. serverURLStr = [serverURLStr stringByAppendingString:_options.APIKey];
  460. } else {
  461. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000071",
  462. @"Missing `APIKey` from `FirebaseOptions`, please ensure the configured "
  463. @"`FirebaseApp` is configured with `FirebaseOptions` that contains an `APIKey`.");
  464. }
  465. return serverURLStr;
  466. }
  467. - (NSURLSession *)newFetchSession {
  468. NSURLSessionConfiguration *config =
  469. [[NSURLSessionConfiguration defaultSessionConfiguration] copy];
  470. config.timeoutIntervalForRequest = _settings.fetchTimeout;
  471. config.timeoutIntervalForResource = _settings.fetchTimeout;
  472. NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
  473. return session;
  474. }
  475. - (NSURLSessionDataTask *)URLSessionDataTaskWithContent:(NSData *)content
  476. completionHandler:
  477. (RCNConfigFetcherCompletion)fetcherCompletion {
  478. NSURL *URL = [NSURL URLWithString:[self constructServerURL]];
  479. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000046", @"%@",
  480. [NSString stringWithFormat:@"Making config request: %@", [URL absoluteString]]);
  481. NSTimeInterval timeoutInterval = _fetchSession.configuration.timeoutIntervalForResource;
  482. NSMutableURLRequest *URLRequest =
  483. [[NSMutableURLRequest alloc] initWithURL:URL
  484. cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
  485. timeoutInterval:timeoutInterval];
  486. URLRequest.HTTPMethod = kHTTPMethodPost;
  487. [URLRequest setValue:kContentTypeValueJSON forHTTPHeaderField:kContentTypeHeaderName];
  488. [URLRequest setValue:[[NSBundle mainBundle] bundleIdentifier]
  489. forHTTPHeaderField:kiOSBundleIdentifierHeaderName];
  490. [URLRequest setValue:@"gzip" forHTTPHeaderField:kContentEncodingHeaderName];
  491. [URLRequest setValue:@"gzip" forHTTPHeaderField:kAcceptEncodingHeaderName];
  492. // Set the eTag from the last successful fetch, if available.
  493. if (_settings.lastETag) {
  494. [URLRequest setValue:_settings.lastETag forHTTPHeaderField:kIfNoneMatchETagHeaderName];
  495. }
  496. [URLRequest setHTTPBody:content];
  497. return [_fetchSession dataTaskWithRequest:URLRequest completionHandler:fetcherCompletion];
  498. }
  499. @end