RCNConfigFetch.m 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. /*
  2. * Copyright 2019 Google
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #import "FirebaseRemoteConfig/Sources/Private/RCNConfigFetch.h"
  17. #import <GoogleUtilities/GULNSData+zlib.h>
  18. #import "FirebaseCore/Extension/FirebaseCoreInternal.h"
  19. #import "FirebaseInstallations/Source/Library/Private/FirebaseInstallationsInternal.h"
  20. #import "FirebaseRemoteConfig/Sources/Private/RCNConfigSettings.h"
  21. #import "FirebaseRemoteConfig/Sources/RCNConfigConstants.h"
  22. #import "FirebaseRemoteConfig/Sources/RCNConfigContent.h"
  23. #import "FirebaseRemoteConfig/Sources/RCNConfigExperiment.h"
  24. #import "FirebaseRemoteConfig/Sources/RCNDevice.h"
  25. #ifdef RCN_STAGING_SERVER
  26. static NSString *const kServerURLDomain =
  27. @"https://staging-firebaseremoteconfig.sandbox.googleapis.com";
  28. #else
  29. static NSString *const kServerURLDomain = @"https://firebaseremoteconfig.googleapis.com";
  30. #endif
  31. static NSString *const kServerURLVersion = @"/v1";
  32. static NSString *const kServerURLProjects = @"/projects/";
  33. static NSString *const kServerURLNamespaces = @"/namespaces/";
  34. static NSString *const kServerURLQuery = @":fetch?";
  35. static NSString *const kServerURLKey = @"key=";
  36. static NSString *const kRequestJSONKeyAppID = @"app_id";
  37. static NSString *const kHTTPMethodPost = @"POST"; ///< HTTP request method config fetch using
  38. static NSString *const kContentTypeHeaderName = @"Content-Type"; ///< HTTP Header Field Name
  39. static NSString *const kContentEncodingHeaderName =
  40. @"Content-Encoding"; ///< HTTP Header Field Name
  41. static NSString *const kAcceptEncodingHeaderName = @"Accept-Encoding"; ///< HTTP Header Field Name
  42. static NSString *const kETagHeaderName = @"etag"; ///< HTTP Header Field Name
  43. static NSString *const kIfNoneMatchETagHeaderName = @"if-none-match"; ///< HTTP Header Field Name
  44. static NSString *const kInstallationsAuthTokenHeaderName = @"x-goog-firebase-installations-auth";
  45. // Sends the bundle ID. Refer to b/130301479 for details.
  46. static NSString *const kiOSBundleIdentifierHeaderName =
  47. @"X-Ios-Bundle-Identifier"; ///< HTTP Header Field Name
  48. /// Config HTTP request content type proto buffer
  49. static NSString *const kContentTypeValueJSON = @"application/json";
  50. /// HTTP status codes. Ref: https://cloud.google.com/apis/design/errors#error_retries
  51. static NSInteger const kRCNFetchResponseHTTPStatusCodeOK = 200;
  52. static NSInteger const kRCNFetchResponseHTTPStatusTooManyRequests = 429;
  53. static NSInteger const kRCNFetchResponseHTTPStatusCodeInternalError = 500;
  54. static NSInteger const kRCNFetchResponseHTTPStatusCodeServiceUnavailable = 503;
  55. static NSInteger const kRCNFetchResponseHTTPStatusCodeGatewayTimeout = 504;
  56. // Deprecated error code previously from FirebaseCore
  57. static const NSInteger sFIRErrorCodeConfigFailed = -114;
  58. #pragma mark - RCNConfig
  59. @implementation RCNConfigFetch {
  60. RCNConfigContent *_content;
  61. RCNConfigSettings *_settings;
  62. id<FIRAnalyticsInterop> _analytics;
  63. RCNConfigExperiment *_experiment;
  64. dispatch_queue_t _lockQueue; /// Guard the read/write operation.
  65. NSURLSession *_fetchSession; /// Managed internally by the fetch instance.
  66. NSString *_FIRNamespace;
  67. FIROptions *_options;
  68. NSString *_templateVersionNumber;
  69. }
  70. - (instancetype)init {
  71. NSAssert(NO, @"Invalid initializer.");
  72. return nil;
  73. }
  74. /// Designated initializer
  75. - (instancetype)initWithContent:(RCNConfigContent *)content
  76. DBManager:(RCNConfigDBManager *)DBManager
  77. settings:(RCNConfigSettings *)settings
  78. analytics:(nullable id<FIRAnalyticsInterop>)analytics
  79. experiment:(RCNConfigExperiment *)experiment
  80. queue:(dispatch_queue_t)queue
  81. namespace:(NSString *)FIRNamespace
  82. options:(FIROptions *)options {
  83. self = [super init];
  84. if (self) {
  85. _FIRNamespace = FIRNamespace;
  86. _settings = settings;
  87. _analytics = analytics;
  88. _experiment = experiment;
  89. _lockQueue = queue;
  90. _content = content;
  91. _fetchSession = [self newFetchSession];
  92. _options = options;
  93. _templateVersionNumber = [_settings templateVersion];
  94. }
  95. return self;
  96. }
  97. /// Force a new NSURLSession creation for updated config.
  98. - (void)recreateNetworkSession {
  99. if (_fetchSession) {
  100. [_fetchSession invalidateAndCancel];
  101. }
  102. _fetchSession = [self newFetchSession];
  103. }
  104. /// Return the current session. (Tests).
  105. - (NSURLSession *)currentNetworkSession {
  106. return _fetchSession;
  107. }
  108. - (void)dealloc {
  109. [_fetchSession invalidateAndCancel];
  110. }
  111. #pragma mark - Fetch Config API
  112. - (void)fetchConfigWithExpirationDuration:(NSTimeInterval)expirationDuration
  113. completionHandler:(FIRRemoteConfigFetchCompletion)completionHandler {
  114. // Note: We expect the googleAppID to always be available.
  115. BOOL hasDeviceContextChanged =
  116. FIRRemoteConfigHasDeviceContextChanged(_settings.deviceContext, _options.googleAppID);
  117. __weak RCNConfigFetch *weakSelf = self;
  118. dispatch_async(_lockQueue, ^{
  119. RCNConfigFetch *strongSelf = weakSelf;
  120. if (strongSelf == nil) {
  121. return;
  122. }
  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:sFIRErrorCodeConfigFailed
  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 refreshInstallationsTokenWithCompletionHandler:completionHandler];
  173. });
  174. }
  175. #pragma mark - Fetch helpers
  176. - (NSString *)FIRAppNameFromFullyQualifiedNamespace {
  177. return [[_FIRNamespace componentsSeparatedByString:@":"] lastObject];
  178. }
  179. /// Refresh installation ID token before fetching config. installation ID is now mandatory for fetch
  180. /// requests to work.(b/14751422).
  181. - (void)refreshInstallationsTokenWithCompletionHandler:
  182. (FIRRemoteConfigFetchCompletion)completionHandler {
  183. FIRInstallations *installations = [FIRInstallations
  184. installationsWithApp:[FIRApp appNamed:[self FIRAppNameFromFullyQualifiedNamespace]]];
  185. if (!installations || !_options.GCMSenderID) {
  186. NSString *errorDescription = @"Failed to get GCMSenderID";
  187. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000074", @"%@",
  188. [NSString stringWithFormat:@"%@", errorDescription]);
  189. self->_settings.isFetchInProgress = NO;
  190. return [self
  191. reportCompletionOnHandler:completionHandler
  192. withStatus:FIRRemoteConfigFetchStatusFailure
  193. withError:[NSError errorWithDomain:FIRRemoteConfigErrorDomain
  194. code:FIRRemoteConfigErrorInternalError
  195. userInfo:@{
  196. NSLocalizedDescriptionKey : errorDescription
  197. }]];
  198. }
  199. __weak RCNConfigFetch *weakSelf = self;
  200. FIRInstallationsTokenHandler installationsTokenHandler = ^(
  201. FIRInstallationsAuthTokenResult *tokenResult, NSError *error) {
  202. RCNConfigFetch *strongSelf = weakSelf;
  203. if (strongSelf == nil) {
  204. return;
  205. }
  206. if (!tokenResult || !tokenResult.authToken || error) {
  207. NSString *errorDescription =
  208. [NSString stringWithFormat:@"Failed to get installations token. Error : %@.", error];
  209. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000073", @"%@",
  210. [NSString stringWithFormat:@"%@", errorDescription]);
  211. strongSelf->_settings.isFetchInProgress = NO;
  212. return [strongSelf
  213. reportCompletionOnHandler:completionHandler
  214. withStatus:FIRRemoteConfigFetchStatusFailure
  215. withError:[NSError errorWithDomain:FIRRemoteConfigErrorDomain
  216. code:FIRRemoteConfigErrorInternalError
  217. userInfo:@{
  218. NSLocalizedDescriptionKey : errorDescription
  219. }]];
  220. }
  221. // We have a valid token. Get the backing installationID.
  222. [installations installationIDWithCompletion:^(NSString *_Nullable identifier,
  223. NSError *_Nullable error) {
  224. RCNConfigFetch *strongSelf = weakSelf;
  225. if (strongSelf == nil) {
  226. return;
  227. }
  228. // Dispatch to the RC serial queue to update settings on the queue.
  229. dispatch_async(strongSelf->_lockQueue, ^{
  230. RCNConfigFetch *strongSelfQueue = weakSelf;
  231. if (strongSelfQueue == nil) {
  232. return;
  233. }
  234. // Update config settings with the IID and token.
  235. strongSelfQueue->_settings.configInstallationsToken = tokenResult.authToken;
  236. strongSelfQueue->_settings.configInstallationsIdentifier = identifier;
  237. if (!identifier || error) {
  238. NSString *errorDescription =
  239. [NSString stringWithFormat:@"Error getting iid : %@.", error];
  240. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000055", @"%@",
  241. [NSString stringWithFormat:@"%@", errorDescription]);
  242. strongSelfQueue->_settings.isFetchInProgress = NO;
  243. return [strongSelfQueue
  244. reportCompletionOnHandler:completionHandler
  245. withStatus:FIRRemoteConfigFetchStatusFailure
  246. withError:[NSError
  247. errorWithDomain:FIRRemoteConfigErrorDomain
  248. code:FIRRemoteConfigErrorInternalError
  249. userInfo:@{
  250. NSLocalizedDescriptionKey : errorDescription
  251. }]];
  252. }
  253. FIRLogInfo(kFIRLoggerRemoteConfig, @"I-RCN000022", @"Success to get iid : %@.",
  254. strongSelfQueue->_settings.configInstallationsIdentifier);
  255. [strongSelf doFetchCall:completionHandler];
  256. });
  257. }];
  258. };
  259. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000039", @"Starting requesting token.");
  260. [installations authTokenWithCompletion:installationsTokenHandler];
  261. }
  262. - (void)doFetchCall:(FIRRemoteConfigFetchCompletion)completionHandler {
  263. [self getAnalyticsUserPropertiesWithCompletionHandler:^(NSDictionary *userProperties) {
  264. dispatch_async(self->_lockQueue, ^{
  265. [self fetchWithUserProperties:userProperties completionHandler:completionHandler];
  266. });
  267. }];
  268. }
  269. - (void)getAnalyticsUserPropertiesWithCompletionHandler:
  270. (FIRAInteropUserPropertiesCallback)completionHandler {
  271. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000060", @"Fetch with user properties completed.");
  272. id<FIRAnalyticsInterop> analytics = self->_analytics;
  273. if (analytics == nil) {
  274. completionHandler(@{});
  275. } else {
  276. [analytics getUserPropertiesWithCallback:completionHandler];
  277. }
  278. }
  279. - (void)reportCompletionOnHandler:(FIRRemoteConfigFetchCompletion)completionHandler
  280. withStatus:(FIRRemoteConfigFetchStatus)status
  281. withError:(NSError *)error {
  282. if (completionHandler) {
  283. dispatch_async(dispatch_get_main_queue(), ^{
  284. completionHandler(status, error);
  285. });
  286. }
  287. }
  288. - (void)fetchWithUserProperties:(NSDictionary *)userProperties
  289. completionHandler:(FIRRemoteConfigFetchCompletion)completionHandler {
  290. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000061", @"Fetch with user properties initiated.");
  291. NSString *postRequestString = [_settings nextRequestWithUserProperties:userProperties];
  292. // Get POST request content.
  293. NSData *content = [postRequestString dataUsingEncoding:NSUTF8StringEncoding];
  294. NSError *compressionError;
  295. NSData *compressedContent = [NSData gul_dataByGzippingData:content error:&compressionError];
  296. if (compressionError) {
  297. NSString *errString = [NSString stringWithFormat:@"Failed to compress the config request."];
  298. FIRLogWarning(kFIRLoggerRemoteConfig, @"I-RCN000033", @"%@", errString);
  299. self->_settings.isFetchInProgress = NO;
  300. return [self
  301. reportCompletionOnHandler:completionHandler
  302. withStatus:FIRRemoteConfigFetchStatusFailure
  303. withError:[NSError
  304. errorWithDomain:FIRRemoteConfigErrorDomain
  305. code:FIRRemoteConfigErrorInternalError
  306. userInfo:@{NSLocalizedDescriptionKey : errString}]];
  307. }
  308. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000040", @"Start config fetch.");
  309. __weak RCNConfigFetch *weakSelf = self;
  310. RCNConfigFetcherCompletion fetcherCompletion = ^(NSData *data, NSURLResponse *response,
  311. NSError *error) {
  312. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000050",
  313. @"config fetch completed. Error: %@ StatusCode: %ld", (error ? error : @"nil"),
  314. (long)[((NSHTTPURLResponse *)response) statusCode]);
  315. RCNConfigFetch *fetcherCompletionSelf = weakSelf;
  316. if (fetcherCompletionSelf == nil) {
  317. return;
  318. }
  319. // The fetch has completed.
  320. fetcherCompletionSelf->_settings.isFetchInProgress = NO;
  321. dispatch_async(fetcherCompletionSelf->_lockQueue, ^{
  322. RCNConfigFetch *strongSelf = weakSelf;
  323. if (strongSelf == nil) {
  324. return;
  325. }
  326. NSInteger statusCode = [((NSHTTPURLResponse *)response) statusCode];
  327. if (error || (statusCode != kRCNFetchResponseHTTPStatusCodeOK)) {
  328. // Update metadata about fetch failure.
  329. [strongSelf->_settings updateMetadataWithFetchSuccessStatus:NO templateVersion:@"1"];
  330. if (error) {
  331. if (strongSelf->_settings.lastFetchStatus == FIRRemoteConfigFetchStatusSuccess) {
  332. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000025",
  333. @"RCN Fetch failure: %@. Using cached config result.", error);
  334. } else {
  335. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000026",
  336. @"RCN Fetch failure: %@. No cached config result.", error);
  337. }
  338. }
  339. if (statusCode != kRCNFetchResponseHTTPStatusCodeOK) {
  340. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000026",
  341. @"RCN Fetch failure. Response http error code: %ld", (long)statusCode);
  342. // Response error code 429, 500, 503 will trigger exponential backoff mode.
  343. if (statusCode == kRCNFetchResponseHTTPStatusTooManyRequests ||
  344. statusCode == kRCNFetchResponseHTTPStatusCodeInternalError ||
  345. statusCode == kRCNFetchResponseHTTPStatusCodeServiceUnavailable ||
  346. statusCode == kRCNFetchResponseHTTPStatusCodeGatewayTimeout) {
  347. [strongSelf->_settings updateExponentialBackoffTime];
  348. if ([strongSelf->_settings shouldThrottle]) {
  349. // Must set lastFetchStatus before FailReason.
  350. strongSelf->_settings.lastFetchStatus = FIRRemoteConfigFetchStatusThrottled;
  351. strongSelf->_settings.lastFetchError = FIRRemoteConfigErrorThrottled;
  352. NSTimeInterval throttledEndTime =
  353. strongSelf->_settings.exponentialBackoffThrottleEndTime;
  354. NSError *error = [NSError
  355. errorWithDomain:FIRRemoteConfigErrorDomain
  356. code:FIRRemoteConfigErrorThrottled
  357. userInfo:@{
  358. FIRRemoteConfigThrottledEndTimeInSecondsKey : @(throttledEndTime)
  359. }];
  360. return [strongSelf reportCompletionOnHandler:completionHandler
  361. withStatus:strongSelf->_settings.lastFetchStatus
  362. withError:error];
  363. }
  364. }
  365. }
  366. // Return back the received error.
  367. // Must set lastFetchStatus before setting Fetch Error.
  368. strongSelf->_settings.lastFetchStatus = FIRRemoteConfigFetchStatusFailure;
  369. strongSelf->_settings.lastFetchError = FIRRemoteConfigErrorInternalError;
  370. NSDictionary<NSErrorUserInfoKey, id> *userInfo = @{
  371. NSLocalizedDescriptionKey :
  372. ([error localizedDescription]
  373. ?: [NSString
  374. stringWithFormat:@"Internal Error. Status code: %ld", (long)statusCode])
  375. };
  376. return [strongSelf
  377. reportCompletionOnHandler:completionHandler
  378. withStatus:FIRRemoteConfigFetchStatusFailure
  379. withError:[NSError errorWithDomain:FIRRemoteConfigErrorDomain
  380. code:FIRRemoteConfigErrorInternalError
  381. userInfo:userInfo]];
  382. }
  383. // Fetch was successful. Check if we have data.
  384. NSError *retError;
  385. if (!data) {
  386. FIRLogInfo(kFIRLoggerRemoteConfig, @"I-RCN000043", @"RCN Fetch: No data in fetch response");
  387. return [strongSelf reportCompletionOnHandler:completionHandler
  388. withStatus:FIRRemoteConfigFetchStatusSuccess
  389. withError:nil];
  390. }
  391. // Config fetch succeeded.
  392. // JSONObjectWithData is always expected to return an NSDictionary in our case
  393. NSMutableDictionary *fetchedConfig =
  394. [NSJSONSerialization JSONObjectWithData:data
  395. options:NSJSONReadingMutableContainers
  396. error:&retError];
  397. if (retError) {
  398. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000042",
  399. @"RCN Fetch failure: %@. Could not parse response data as JSON", error);
  400. }
  401. // Check and log if we received an error from the server
  402. if (fetchedConfig && fetchedConfig.count == 1 && fetchedConfig[RCNFetchResponseKeyError]) {
  403. NSString *errStr = [NSString stringWithFormat:@"RCN Fetch Failure: Server returned error:"];
  404. NSDictionary *errDict = fetchedConfig[RCNFetchResponseKeyError];
  405. if (errDict[RCNFetchResponseKeyErrorCode]) {
  406. errStr = [errStr
  407. stringByAppendingString:[NSString
  408. stringWithFormat:@"code: %@",
  409. errDict[RCNFetchResponseKeyErrorCode]]];
  410. }
  411. if (errDict[RCNFetchResponseKeyErrorStatus]) {
  412. errStr = [errStr stringByAppendingString:
  413. [NSString stringWithFormat:@". Status: %@",
  414. errDict[RCNFetchResponseKeyErrorStatus]]];
  415. }
  416. if (errDict[RCNFetchResponseKeyErrorMessage]) {
  417. errStr =
  418. [errStr stringByAppendingString:
  419. [NSString stringWithFormat:@". Message: %@",
  420. errDict[RCNFetchResponseKeyErrorMessage]]];
  421. }
  422. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000044", @"%@.", errStr);
  423. return [strongSelf
  424. reportCompletionOnHandler:completionHandler
  425. withStatus:FIRRemoteConfigFetchStatusFailure
  426. withError:[NSError
  427. errorWithDomain:FIRRemoteConfigErrorDomain
  428. code:FIRRemoteConfigErrorInternalError
  429. userInfo:@{NSLocalizedDescriptionKey : errStr}]];
  430. }
  431. // Add the fetched config to the database.
  432. if (fetchedConfig) {
  433. // Update config content to cache and DB.
  434. [strongSelf->_content updateConfigContentWithResponse:fetchedConfig
  435. forNamespace:strongSelf->_FIRNamespace];
  436. // Update experiments only for 3p namespace
  437. NSString *namespace = [strongSelf->_FIRNamespace
  438. substringToIndex:[strongSelf->_FIRNamespace rangeOfString:@":"].location];
  439. if ([namespace isEqualToString:FIRNamespaceGoogleMobilePlatform]) {
  440. [strongSelf->_experiment updateExperimentsWithResponse:
  441. fetchedConfig[RCNFetchResponseKeyExperimentDescriptions]];
  442. }
  443. strongSelf->_templateVersionNumber =
  444. [strongSelf getTemplateVersionNumber:fetchedConfig
  445. keyName:RCNFetchResponseKeyTemplateVersion];
  446. } else {
  447. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000063",
  448. @"Empty response with no fetched config.");
  449. }
  450. // We had a successful fetch. Update the current eTag in settings if different.
  451. NSString *latestETag = ((NSHTTPURLResponse *)response).allHeaderFields[kETagHeaderName];
  452. if (!strongSelf->_settings.lastETag ||
  453. !([strongSelf->_settings.lastETag isEqualToString:latestETag])) {
  454. strongSelf->_settings.lastETag = latestETag;
  455. }
  456. [strongSelf->_settings
  457. updateMetadataWithFetchSuccessStatus:YES
  458. templateVersion:strongSelf->_templateVersionNumber];
  459. return [strongSelf reportCompletionOnHandler:completionHandler
  460. withStatus:FIRRemoteConfigFetchStatusSuccess
  461. withError:nil];
  462. });
  463. };
  464. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000061", @"Making remote config fetch.");
  465. NSURLSessionDataTask *dataTask = [self URLSessionDataTaskWithContent:compressedContent
  466. completionHandler:fetcherCompletion];
  467. [dataTask resume];
  468. }
  469. - (NSString *)constructServerURL {
  470. NSString *serverURLStr = [[NSString alloc] initWithString:kServerURLDomain];
  471. serverURLStr = [serverURLStr stringByAppendingString:kServerURLVersion];
  472. serverURLStr = [serverURLStr stringByAppendingString:kServerURLProjects];
  473. serverURLStr = [serverURLStr stringByAppendingString:_options.projectID];
  474. serverURLStr = [serverURLStr stringByAppendingString:kServerURLNamespaces];
  475. // Get the namespace from the fully qualified namespace string of "namespace:FIRAppName".
  476. NSString *namespace =
  477. [_FIRNamespace substringToIndex:[_FIRNamespace rangeOfString:@":"].location];
  478. serverURLStr = [serverURLStr stringByAppendingString:namespace];
  479. serverURLStr = [serverURLStr stringByAppendingString:kServerURLQuery];
  480. if (_options.APIKey) {
  481. serverURLStr = [serverURLStr stringByAppendingString:kServerURLKey];
  482. serverURLStr = [serverURLStr stringByAppendingString:_options.APIKey];
  483. } else {
  484. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000071",
  485. @"Missing `APIKey` from `FirebaseOptions`, please ensure the configured "
  486. @"`FirebaseApp` is configured with `FirebaseOptions` that contains an `APIKey`.");
  487. }
  488. return serverURLStr;
  489. }
  490. - (NSURLSession *)newFetchSession {
  491. NSURLSessionConfiguration *config =
  492. [[NSURLSessionConfiguration defaultSessionConfiguration] copy];
  493. config.timeoutIntervalForRequest = _settings.fetchTimeout;
  494. config.timeoutIntervalForResource = _settings.fetchTimeout;
  495. NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
  496. return session;
  497. }
  498. - (NSURLSessionDataTask *)URLSessionDataTaskWithContent:(NSData *)content
  499. completionHandler:
  500. (RCNConfigFetcherCompletion)fetcherCompletion {
  501. NSURL *URL = [NSURL URLWithString:[self constructServerURL]];
  502. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000046", @"%@",
  503. [NSString stringWithFormat:@"Making config request: %@", [URL absoluteString]]);
  504. NSTimeInterval timeoutInterval = _fetchSession.configuration.timeoutIntervalForResource;
  505. NSMutableURLRequest *URLRequest =
  506. [[NSMutableURLRequest alloc] initWithURL:URL
  507. cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
  508. timeoutInterval:timeoutInterval];
  509. URLRequest.HTTPMethod = kHTTPMethodPost;
  510. [URLRequest setValue:kContentTypeValueJSON forHTTPHeaderField:kContentTypeHeaderName];
  511. [URLRequest setValue:_settings.configInstallationsToken
  512. forHTTPHeaderField:kInstallationsAuthTokenHeaderName];
  513. [URLRequest setValue:[[NSBundle mainBundle] bundleIdentifier]
  514. forHTTPHeaderField:kiOSBundleIdentifierHeaderName];
  515. [URLRequest setValue:@"gzip" forHTTPHeaderField:kContentEncodingHeaderName];
  516. [URLRequest setValue:@"gzip" forHTTPHeaderField:kAcceptEncodingHeaderName];
  517. // Set the eTag from the last successful fetch, if available.
  518. if (_settings.lastETag) {
  519. [URLRequest setValue:_settings.lastETag forHTTPHeaderField:kIfNoneMatchETagHeaderName];
  520. }
  521. [URLRequest setHTTPBody:content];
  522. return [_fetchSession dataTaskWithRequest:URLRequest completionHandler:fetcherCompletion];
  523. }
  524. - (NSString *)getTemplateVersionNumber:(NSDictionary *)fetchedConfig keyName:(NSString *)keyName {
  525. if (fetchedConfig != nil && [fetchedConfig objectForKey:keyName] &&
  526. [[fetchedConfig objectForKey:keyName] isKindOfClass:[NSString class]]) {
  527. return (NSString *)[fetchedConfig objectForKey:keyName];
  528. }
  529. return @"1";
  530. }
  531. @end