RCNFetch.m 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  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. FIRInstanceIDTokenHandler instanceIDHandler = ^(NSString *token, NSError *error) {
  186. if (error) {
  187. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000020",
  188. @"Failed to register InstanceID with error : %@.", error);
  189. }
  190. // If the token is available, try to get the instanceID.
  191. __weak RCNConfigFetch *weakSelf = self;
  192. if (token) {
  193. [instanceID getIDWithHandler:^(NSString *_Nullable identity, NSError *_Nullable error) {
  194. RCNConfigFetch *strongSelf = weakSelf;
  195. // Dispatch to the RC serial queue to update settings on the queue.
  196. dispatch_async(strongSelf->_lockQueue, ^{
  197. RCNConfigFetch *strongSelfQueue = weakSelf;
  198. // Update config settings with the IID and token.
  199. strongSelfQueue->_settings.configInstanceIDToken = [token copy];
  200. strongSelfQueue->_settings.configInstanceID = identity;
  201. if (identity && !error) {
  202. FIRLogInfo(kFIRLoggerRemoteConfig, @"I-RCN000022", @"Success to get iid : %@.",
  203. strongSelfQueue->_settings.configInstanceID);
  204. } else {
  205. FIRLogWarning(kFIRLoggerRemoteConfig, @"I-RCN000055", @"Error getting iid : %@.",
  206. error);
  207. }
  208. // Continue the fetch regardless of whether fetch of instance ID succeeded.
  209. [strongSelfQueue fetchCheckinInfoWithCompletionHandler:completionHandler];
  210. });
  211. }];
  212. } else {
  213. dispatch_async(self->_lockQueue, ^{
  214. RCNConfigFetch *strongSelfQueue = weakSelf;
  215. // Continue the fetch regardless of whether fetch of instance ID succeeded.
  216. [strongSelfQueue fetchCheckinInfoWithCompletionHandler:completionHandler];
  217. });
  218. }
  219. };
  220. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000039", @"Starting requesting token.");
  221. // Note: We expect the GCMSenderID to always be available by the time this request is made.
  222. [instanceID tokenWithAuthorizedEntity:_options.GCMSenderID
  223. scope:kInstanceIDScopeConfig
  224. options:nil
  225. handler:instanceIDHandler];
  226. }
  227. /// Fetch checkin info before fetching config. Checkin info including device authentication ID,
  228. /// secret token and device data version are optional fields in config request.
  229. - (void)fetchCheckinInfoWithCompletionHandler:(FIRRemoteConfigFetchCompletion)completionHandler {
  230. FIRInstanceID *instanceID = [FIRInstanceID instanceID];
  231. __weak RCNConfigFetch *weakSelf = self;
  232. [instanceID fetchCheckinInfoWithHandler:^(FIRInstanceIDCheckinPreferences *preferences,
  233. NSError *error) {
  234. RCNConfigFetch *fetchCheckinInfoWithHandlerSelf = weakSelf;
  235. dispatch_async(fetchCheckinInfoWithHandlerSelf->_lockQueue, ^{
  236. RCNConfigFetch *strongSelf = fetchCheckinInfoWithHandlerSelf;
  237. if (error) {
  238. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000023", @"Failed to fetch checkin info: %@.",
  239. error);
  240. } else {
  241. strongSelf->_settings.deviceAuthID = preferences.deviceID;
  242. strongSelf->_settings.secretToken = preferences.secretToken;
  243. strongSelf->_settings.deviceDataVersion = preferences.deviceDataVersion;
  244. if (strongSelf->_settings.deviceAuthID.length && strongSelf->_settings.secretToken.length) {
  245. FIRLogInfo(kFIRLoggerRemoteConfig, @"I-RCN000024",
  246. @"Success to get device authentication ID: %@, security token: %@.",
  247. self->_settings.deviceAuthID, self->_settings.secretToken);
  248. }
  249. }
  250. // Checkin info is optional, continue fetch config regardless fetch of checkin info
  251. // succeeded.
  252. [strongSelf fetchWithUserPropertiesCompletionHandler:^(NSDictionary *userProperties) {
  253. dispatch_async(strongSelf->_lockQueue, ^{
  254. [strongSelf fetchWithUserProperties:userProperties completionHandler:completionHandler];
  255. });
  256. }];
  257. });
  258. }];
  259. }
  260. - (void)fetchWithUserPropertiesCompletionHandler:
  261. (FIRAInteropUserPropertiesCallback)completionHandler {
  262. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000060", @"Fetch with user properties completed.");
  263. id<FIRAnalyticsInterop> analytics = self->_analytics;
  264. if (analytics == nil) {
  265. completionHandler(@{});
  266. } else {
  267. [analytics getUserPropertiesWithCallback:completionHandler];
  268. }
  269. }
  270. - (void)reportCompletionOnHandler:(FIRRemoteConfigFetchCompletion)completionHandler
  271. withStatus:(FIRRemoteConfigFetchStatus)status
  272. withError:(NSError *)error {
  273. if (completionHandler) {
  274. dispatch_async(dispatch_get_main_queue(), ^{
  275. completionHandler(status, error);
  276. });
  277. }
  278. }
  279. - (void)fetchWithUserProperties:(NSDictionary *)userProperties
  280. completionHandler:(FIRRemoteConfigFetchCompletion)completionHandler {
  281. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000061", @"Fetch with user properties initiated.");
  282. NSString *postRequestString = [_settings nextRequestWithUserProperties:userProperties];
  283. // Get POST request content.
  284. NSData *content = [postRequestString dataUsingEncoding:NSUTF8StringEncoding];
  285. NSError *compressionError;
  286. NSData *compressedContent = [NSData gul_dataByGzippingData:content error:&compressionError];
  287. if (compressionError) {
  288. NSString *errString = [NSString stringWithFormat:@"Failed to compress the config request."];
  289. FIRLogWarning(kFIRLoggerRemoteConfig, @"I-RCN000033", @"%@", errString);
  290. return [self
  291. reportCompletionOnHandler:completionHandler
  292. withStatus:FIRRemoteConfigFetchStatusFailure
  293. withError:[NSError
  294. errorWithDomain:FIRRemoteConfigErrorDomain
  295. code:FIRRemoteConfigErrorInternalError
  296. userInfo:@{NSLocalizedDescriptionKey : errString}]];
  297. }
  298. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000040", @"Start config fetch.");
  299. __weak RCNConfigFetch *weakSelf = self;
  300. RCNConfigFetcherCompletion fetcherCompletion = ^(NSData *data, NSURLResponse *response,
  301. NSError *error) {
  302. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000050",
  303. @"config fetch completed. Error: %@ StatusCode: %ld", (error ? error : @"nil"),
  304. (long)[((NSHTTPURLResponse *)response) statusCode]);
  305. RCNConfigFetch *fetcherCompletionSelf = weakSelf;
  306. if (!fetcherCompletionSelf) {
  307. return;
  308. };
  309. dispatch_async(fetcherCompletionSelf->_lockQueue, ^{
  310. RCNConfigFetch *strongSelf = weakSelf;
  311. if (!strongSelf) {
  312. return;
  313. }
  314. strongSelf->_settings.isFetchInProgress = NO;
  315. NSInteger statusCode = [((NSHTTPURLResponse *)response) statusCode];
  316. if (error || (statusCode != kRCNFetchResponseHTTPStatusCodeOK)) {
  317. // Update failure fetch time and database.
  318. [strongSelf->_settings updateMetadataWithFetchSuccessStatus:NO];
  319. if (error) {
  320. if (strongSelf->_settings.lastFetchStatus == FIRRemoteConfigFetchStatusSuccess) {
  321. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000025",
  322. @"RCN Fetch failure: %@. Using cached config result.", error);
  323. } else {
  324. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000026",
  325. @"RCN Fetch failure: %@. No cached config result.", error);
  326. }
  327. }
  328. if (statusCode != kRCNFetchResponseHTTPStatusCodeOK) {
  329. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000026",
  330. @"RCN Fetch failure. Response http error code: %ld", (long)statusCode);
  331. // Response error code 429, 500, 503 will trigger exponential backoff mode.
  332. if (statusCode == kRCNFetchResponseHTTPStatusTooManyRequests ||
  333. statusCode == kRCNFetchResponseHTTPStatusCodeInternalError ||
  334. statusCode == kRCNFetchResponseHTTPStatusCodeServiceUnavailable ||
  335. statusCode == kRCNFetchResponseHTTPStatusCodeGatewayTimeout) {
  336. if ([strongSelf->_settings shouldThrottle]) {
  337. // Must set lastFetchStatus before FailReason.
  338. strongSelf->_settings.lastFetchStatus = FIRRemoteConfigFetchStatusThrottled;
  339. strongSelf->_settings.lastFetchError = FIRRemoteConfigErrorThrottled;
  340. NSTimeInterval throttledEndTime =
  341. strongSelf->_settings.exponentialBackoffThrottleEndTime;
  342. NSError *error = [NSError
  343. errorWithDomain:FIRRemoteConfigErrorDomain
  344. code:FIRRemoteConfigErrorThrottled
  345. userInfo:@{
  346. FIRRemoteConfigThrottledEndTimeInSecondsKey : @(throttledEndTime)
  347. }];
  348. return [strongSelf reportCompletionOnHandler:completionHandler
  349. withStatus:strongSelf->_settings.lastFetchStatus
  350. withError:error];
  351. } else {
  352. // Return back the received error.
  353. // Must set lastFetchStatus before setting Fetch Error.
  354. strongSelf->_settings.lastFetchStatus = FIRRemoteConfigFetchStatusFailure;
  355. strongSelf->_settings.lastFetchError = FIRRemoteConfigErrorInternalError;
  356. NSDictionary<NSErrorUserInfoKey, id> *userInfo = @{
  357. NSLocalizedDescriptionKey :
  358. (error ? [error localizedDescription]
  359. : [NSString stringWithFormat:@"Internal Error. Status code: %ld",
  360. (long)statusCode])
  361. };
  362. return [strongSelf
  363. reportCompletionOnHandler:completionHandler
  364. withStatus:FIRRemoteConfigFetchStatusFailure
  365. withError:[NSError
  366. errorWithDomain:FIRRemoteConfigErrorDomain
  367. code:FIRRemoteConfigErrorInternalError
  368. userInfo:userInfo]];
  369. }
  370. }
  371. }
  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.
  434. self->_settings.lastETag = ((NSHTTPURLResponse *)response).allHeaderFields[kETagHeaderName];
  435. [self->_settings updateMetadataWithFetchSuccessStatus:YES];
  436. return [strongSelf reportCompletionOnHandler:completionHandler
  437. withStatus:FIRRemoteConfigFetchStatusSuccess
  438. withError:nil];
  439. });
  440. };
  441. if (gGlobalTestBlock) {
  442. gGlobalTestBlock(fetcherCompletion);
  443. return;
  444. }
  445. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000061", @"Making remote config fetch.");
  446. NSURLSessionDataTask *dataTask = [self URLSessionDataTaskWithContent:compressedContent
  447. completionHandler:fetcherCompletion];
  448. [dataTask resume];
  449. }
  450. + (void)setGlobalTestBlock:(RCNConfigFetcherTestBlock)block {
  451. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000027",
  452. @"Set global test block for NSSessionFetcher, it will not fetch from server.");
  453. gGlobalTestBlock = [block copy];
  454. }
  455. - (NSString *)constructServerURL {
  456. NSString *serverURLStr = [[NSString alloc] initWithString:kServerURLDomain];
  457. serverURLStr = [serverURLStr stringByAppendingString:kServerURLVersion];
  458. if (_options.projectID) {
  459. serverURLStr = [serverURLStr stringByAppendingString:kServerURLProjects];
  460. serverURLStr = [serverURLStr stringByAppendingString:_options.projectID];
  461. } else {
  462. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000070",
  463. @"Missing `projectID` from `FirebaseOptions`, please ensure the configured "
  464. @"`FirebaseApp` is configured with `FirebaseOptions` that contains a `projectID`.");
  465. }
  466. serverURLStr = [serverURLStr stringByAppendingString:kServerURLNamespaces];
  467. // Get the namespace from the fully qualified namespace string of "namespace:FIRAppName".
  468. NSString *namespace =
  469. [_FIRNamespace substringToIndex:[_FIRNamespace rangeOfString:@":"].location];
  470. serverURLStr = [serverURLStr stringByAppendingString:namespace];
  471. serverURLStr = [serverURLStr stringByAppendingString:kServerURLQuery];
  472. if (_options.APIKey) {
  473. serverURLStr = [serverURLStr stringByAppendingString:kServerURLKey];
  474. serverURLStr = [serverURLStr stringByAppendingString:_options.APIKey];
  475. } else {
  476. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000071",
  477. @"Missing `APIKey` from `FirebaseOptions`, please ensure the configured "
  478. @"`FirebaseApp` is configured with `FirebaseOptions` that contains an `APIKey`.");
  479. }
  480. return serverURLStr;
  481. }
  482. - (NSURLSession *)newFetchSession {
  483. NSURLSessionConfiguration *config =
  484. [[NSURLSessionConfiguration defaultSessionConfiguration] copy];
  485. config.timeoutIntervalForRequest = _settings.fetchTimeout;
  486. config.timeoutIntervalForResource = _settings.fetchTimeout;
  487. NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
  488. return session;
  489. }
  490. - (NSURLSessionDataTask *)URLSessionDataTaskWithContent:(NSData *)content
  491. completionHandler:
  492. (RCNConfigFetcherCompletion)fetcherCompletion {
  493. NSURL *URL = [NSURL URLWithString:[self constructServerURL]];
  494. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000046", @"%@",
  495. [NSString stringWithFormat:@"Making config request: %@", [URL absoluteString]]);
  496. NSTimeInterval timeoutInterval = _fetchSession.configuration.timeoutIntervalForResource;
  497. NSMutableURLRequest *URLRequest =
  498. [[NSMutableURLRequest alloc] initWithURL:URL
  499. cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
  500. timeoutInterval:timeoutInterval];
  501. URLRequest.HTTPMethod = kHTTPMethodPost;
  502. [URLRequest setValue:kContentTypeValueJSON forHTTPHeaderField:kContentTypeHeaderName];
  503. [URLRequest setValue:[[NSBundle mainBundle] bundleIdentifier]
  504. forHTTPHeaderField:kiOSBundleIdentifierHeaderName];
  505. [URLRequest setValue:@"gzip" forHTTPHeaderField:kContentEncodingHeaderName];
  506. [URLRequest setValue:@"gzip" forHTTPHeaderField:kAcceptEncodingHeaderName];
  507. // Set the eTag from the last successful fetch, if available.
  508. if (_settings.lastETag) {
  509. [URLRequest setValue:_settings.lastETag forHTTPHeaderField:kIfNoneMatchETagHeaderName];
  510. }
  511. [URLRequest setHTTPBody:content];
  512. return [_fetchSession dataTaskWithRequest:URLRequest completionHandler:fetcherCompletion];
  513. }
  514. @end