RCNFetch.m 29 KB

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