RCNConfigFetch.m 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  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. // Key to retrive fetch config template version number
  59. static NSString *const kTemplateVersionNumberKey = @"templateVersion";
  60. #pragma mark - RCNConfig
  61. @implementation RCNConfigFetch {
  62. RCNConfigContent *_content;
  63. RCNConfigSettings *_settings;
  64. id<FIRAnalyticsInterop> _analytics;
  65. RCNConfigExperiment *_experiment;
  66. dispatch_queue_t _lockQueue; /// Guard the read/write operation.
  67. NSURLSession *_fetchSession; /// Managed internally by the fetch instance.
  68. NSString *_FIRNamespace;
  69. FIROptions *_options;
  70. NSString *_templateVersionNumber;
  71. }
  72. - (instancetype)init {
  73. NSAssert(NO, @"Invalid initializer.");
  74. return nil;
  75. }
  76. /// Designated initializer
  77. - (instancetype)initWithContent:(RCNConfigContent *)content
  78. DBManager:(RCNConfigDBManager *)DBManager
  79. settings:(RCNConfigSettings *)settings
  80. analytics:(nullable id<FIRAnalyticsInterop>)analytics
  81. experiment:(RCNConfigExperiment *)experiment
  82. queue:(dispatch_queue_t)queue
  83. namespace:(NSString *)FIRNamespace
  84. options:(FIROptions *)options {
  85. self = [super init];
  86. if (self) {
  87. _FIRNamespace = FIRNamespace;
  88. _settings = settings;
  89. _analytics = analytics;
  90. _experiment = experiment;
  91. _lockQueue = queue;
  92. _content = content;
  93. _fetchSession = [self newFetchSession];
  94. _options = options;
  95. _templateVersionNumber = [self getTemplateVersionNumber:_content.fetchedConfig];
  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. dispatch_async(_lockQueue, ^{
  121. RCNConfigFetch *strongSelf = weakSelf;
  122. if (strongSelf == nil) {
  123. return;
  124. }
  125. // Check whether we are outside of the minimum fetch interval.
  126. if (![strongSelf->_settings hasMinimumFetchIntervalElapsed:expirationDuration] &&
  127. !hasDeviceContextChanged) {
  128. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000051", @"Returning cached data.");
  129. return [strongSelf reportCompletionOnHandler:completionHandler
  130. withStatus:FIRRemoteConfigFetchStatusSuccess
  131. withError:nil];
  132. }
  133. // Check if a fetch is already in progress.
  134. if (strongSelf->_settings.isFetchInProgress) {
  135. // Check if we have some fetched data.
  136. if (strongSelf->_settings.lastFetchTimeInterval > 0) {
  137. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000052",
  138. @"A fetch is already in progress. Using previous fetch results.");
  139. return [strongSelf reportCompletionOnHandler:completionHandler
  140. withStatus:strongSelf->_settings.lastFetchStatus
  141. withError:nil];
  142. } else {
  143. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000053",
  144. @"A fetch is already in progress. Ignoring duplicate request.");
  145. NSError *error =
  146. [NSError errorWithDomain:FIRRemoteConfigErrorDomain
  147. code:sFIRErrorCodeConfigFailed
  148. userInfo:@{
  149. NSLocalizedDescriptionKey :
  150. @"FetchError: Duplicate request while the previous one is pending"
  151. }];
  152. return [strongSelf reportCompletionOnHandler:completionHandler
  153. withStatus:FIRRemoteConfigFetchStatusFailure
  154. withError:error];
  155. }
  156. }
  157. // Check whether cache data is within throttle limit.
  158. if ([strongSelf->_settings shouldThrottle] && !hasDeviceContextChanged) {
  159. // Must set lastFetchStatus before FailReason.
  160. strongSelf->_settings.lastFetchStatus = FIRRemoteConfigFetchStatusThrottled;
  161. strongSelf->_settings.lastFetchError = FIRRemoteConfigErrorThrottled;
  162. NSTimeInterval throttledEndTime = strongSelf->_settings.exponentialBackoffThrottleEndTime;
  163. NSError *error =
  164. [NSError errorWithDomain:FIRRemoteConfigErrorDomain
  165. code:FIRRemoteConfigErrorThrottled
  166. userInfo:@{
  167. FIRRemoteConfigThrottledEndTimeInSecondsKey : @(throttledEndTime)
  168. }];
  169. return [strongSelf reportCompletionOnHandler:completionHandler
  170. withStatus:strongSelf->_settings.lastFetchStatus
  171. withError:error];
  172. }
  173. strongSelf->_settings.isFetchInProgress = YES;
  174. [strongSelf refreshInstallationsTokenWithCompletionHandler:completionHandler];
  175. });
  176. }
  177. #pragma mark - Fetch helpers
  178. - (NSString *)FIRAppNameFromFullyQualifiedNamespace {
  179. return [[_FIRNamespace componentsSeparatedByString:@":"] lastObject];
  180. }
  181. /// Refresh installation ID token before fetching config. installation ID is now mandatory for fetch
  182. /// requests to work.(b/14751422).
  183. - (void)refreshInstallationsTokenWithCompletionHandler:
  184. (FIRRemoteConfigFetchCompletion)completionHandler {
  185. FIRInstallations *installations = [FIRInstallations
  186. installationsWithApp:[FIRApp appNamed:[self FIRAppNameFromFullyQualifiedNamespace]]];
  187. if (!installations || !_options.GCMSenderID) {
  188. NSString *errorDescription = @"Failed to get GCMSenderID";
  189. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000074", @"%@",
  190. [NSString stringWithFormat:@"%@", errorDescription]);
  191. self->_settings.isFetchInProgress = NO;
  192. return [self
  193. reportCompletionOnHandler:completionHandler
  194. withStatus:FIRRemoteConfigFetchStatusFailure
  195. withError:[NSError errorWithDomain:FIRRemoteConfigErrorDomain
  196. code:FIRRemoteConfigErrorInternalError
  197. userInfo:@{
  198. NSLocalizedDescriptionKey : errorDescription
  199. }]];
  200. }
  201. __weak RCNConfigFetch *weakSelf = self;
  202. FIRInstallationsTokenHandler installationsTokenHandler = ^(
  203. FIRInstallationsAuthTokenResult *tokenResult, NSError *error) {
  204. RCNConfigFetch *strongSelf = weakSelf;
  205. if (strongSelf == nil) {
  206. return;
  207. }
  208. if (!tokenResult || !tokenResult.authToken || error) {
  209. NSString *errorDescription =
  210. [NSString stringWithFormat:@"Failed to get installations token. Error : %@.", error];
  211. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000073", @"%@",
  212. [NSString stringWithFormat:@"%@", errorDescription]);
  213. strongSelf->_settings.isFetchInProgress = NO;
  214. return [strongSelf
  215. reportCompletionOnHandler:completionHandler
  216. withStatus:FIRRemoteConfigFetchStatusFailure
  217. withError:[NSError errorWithDomain:FIRRemoteConfigErrorDomain
  218. code:FIRRemoteConfigErrorInternalError
  219. userInfo:@{
  220. NSLocalizedDescriptionKey : errorDescription
  221. }]];
  222. }
  223. // We have a valid token. Get the backing installationID.
  224. [installations installationIDWithCompletion:^(NSString *_Nullable identifier,
  225. NSError *_Nullable error) {
  226. RCNConfigFetch *strongSelf = weakSelf;
  227. if (strongSelf == nil) {
  228. return;
  229. }
  230. // Dispatch to the RC serial queue to update settings on the queue.
  231. dispatch_async(strongSelf->_lockQueue, ^{
  232. RCNConfigFetch *strongSelfQueue = weakSelf;
  233. if (strongSelfQueue == nil) {
  234. return;
  235. }
  236. // Update config settings with the IID and token.
  237. strongSelfQueue->_settings.configInstallationsToken = tokenResult.authToken;
  238. strongSelfQueue->_settings.configInstallationsIdentifier = identifier;
  239. if (!identifier || error) {
  240. NSString *errorDescription =
  241. [NSString stringWithFormat:@"Error getting iid : %@.", error];
  242. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000055", @"%@",
  243. [NSString stringWithFormat:@"%@", errorDescription]);
  244. strongSelfQueue->_settings.isFetchInProgress = NO;
  245. return [strongSelfQueue
  246. reportCompletionOnHandler:completionHandler
  247. withStatus:FIRRemoteConfigFetchStatusFailure
  248. withError:[NSError
  249. errorWithDomain:FIRRemoteConfigErrorDomain
  250. code:FIRRemoteConfigErrorInternalError
  251. userInfo:@{
  252. NSLocalizedDescriptionKey : errorDescription
  253. }]];
  254. }
  255. FIRLogInfo(kFIRLoggerRemoteConfig, @"I-RCN000022", @"Success to get iid : %@.",
  256. strongSelfQueue->_settings.configInstallationsIdentifier);
  257. [strongSelf doFetchCall:completionHandler];
  258. });
  259. }];
  260. };
  261. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000039", @"Starting requesting token.");
  262. [installations authTokenWithCompletion:installationsTokenHandler];
  263. }
  264. - (void)doFetchCall:(FIRRemoteConfigFetchCompletion)completionHandler {
  265. [self getAnalyticsUserPropertiesWithCompletionHandler:^(NSDictionary *userProperties) {
  266. dispatch_async(self->_lockQueue, ^{
  267. [self fetchWithUserProperties:userProperties completionHandler:completionHandler];
  268. });
  269. }];
  270. }
  271. - (void)getAnalyticsUserPropertiesWithCompletionHandler:
  272. (FIRAInteropUserPropertiesCallback)completionHandler {
  273. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000060", @"Fetch with user properties completed.");
  274. id<FIRAnalyticsInterop> analytics = self->_analytics;
  275. if (analytics == nil) {
  276. completionHandler(@{});
  277. } else {
  278. [analytics getUserPropertiesWithCallback:completionHandler];
  279. }
  280. }
  281. - (void)reportCompletionOnHandler:(FIRRemoteConfigFetchCompletion)completionHandler
  282. withStatus:(FIRRemoteConfigFetchStatus)status
  283. withError:(NSError *)error {
  284. if (completionHandler) {
  285. dispatch_async(dispatch_get_main_queue(), ^{
  286. completionHandler(status, error);
  287. });
  288. }
  289. }
  290. - (void)fetchWithUserProperties:(NSDictionary *)userProperties
  291. completionHandler:(FIRRemoteConfigFetchCompletion)completionHandler {
  292. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000061", @"Fetch with user properties initiated.");
  293. NSString *postRequestString = [_settings nextRequestWithUserProperties:userProperties];
  294. // Get POST request content.
  295. NSData *content = [postRequestString dataUsingEncoding:NSUTF8StringEncoding];
  296. NSError *compressionError;
  297. NSData *compressedContent = [NSData gul_dataByGzippingData:content error:&compressionError];
  298. if (compressionError) {
  299. NSString *errString = [NSString stringWithFormat:@"Failed to compress the config request."];
  300. FIRLogWarning(kFIRLoggerRemoteConfig, @"I-RCN000033", @"%@", errString);
  301. self->_settings.isFetchInProgress = NO;
  302. return [self
  303. reportCompletionOnHandler:completionHandler
  304. withStatus:FIRRemoteConfigFetchStatusFailure
  305. withError:[NSError
  306. errorWithDomain:FIRRemoteConfigErrorDomain
  307. code:FIRRemoteConfigErrorInternalError
  308. userInfo:@{NSLocalizedDescriptionKey : errString}]];
  309. }
  310. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000040", @"Start config fetch.");
  311. __weak RCNConfigFetch *weakSelf = self;
  312. RCNConfigFetcherCompletion fetcherCompletion = ^(NSData *data, NSURLResponse *response,
  313. NSError *error) {
  314. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000050",
  315. @"config fetch completed. Error: %@ StatusCode: %ld", (error ? error : @"nil"),
  316. (long)[((NSHTTPURLResponse *)response) statusCode]);
  317. RCNConfigFetch *fetcherCompletionSelf = weakSelf;
  318. if (fetcherCompletionSelf == nil) {
  319. return;
  320. }
  321. // The fetch has completed.
  322. fetcherCompletionSelf->_settings.isFetchInProgress = NO;
  323. dispatch_async(fetcherCompletionSelf->_lockQueue, ^{
  324. RCNConfigFetch *strongSelf = weakSelf;
  325. if (strongSelf == nil) {
  326. return;
  327. }
  328. NSInteger statusCode = [((NSHTTPURLResponse *)response) statusCode];
  329. if (error || (statusCode != kRCNFetchResponseHTTPStatusCodeOK)) {
  330. // Update metadata about fetch failure.
  331. [strongSelf->_settings updateMetadataWithFetchSuccessStatus:NO];
  332. if (error) {
  333. if (strongSelf->_settings.lastFetchStatus == FIRRemoteConfigFetchStatusSuccess) {
  334. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000025",
  335. @"RCN Fetch failure: %@. Using cached config result.", error);
  336. } else {
  337. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000026",
  338. @"RCN Fetch failure: %@. No cached config result.", error);
  339. }
  340. }
  341. if (statusCode != kRCNFetchResponseHTTPStatusCodeOK) {
  342. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000026",
  343. @"RCN Fetch failure. Response http error code: %ld", (long)statusCode);
  344. // Response error code 429, 500, 503 will trigger exponential backoff mode.
  345. if (statusCode == kRCNFetchResponseHTTPStatusTooManyRequests ||
  346. statusCode == kRCNFetchResponseHTTPStatusCodeInternalError ||
  347. statusCode == kRCNFetchResponseHTTPStatusCodeServiceUnavailable ||
  348. statusCode == kRCNFetchResponseHTTPStatusCodeGatewayTimeout) {
  349. [strongSelf->_settings updateExponentialBackoffTime];
  350. if ([strongSelf->_settings shouldThrottle]) {
  351. // Must set lastFetchStatus before FailReason.
  352. strongSelf->_settings.lastFetchStatus = FIRRemoteConfigFetchStatusThrottled;
  353. strongSelf->_settings.lastFetchError = FIRRemoteConfigErrorThrottled;
  354. NSTimeInterval throttledEndTime =
  355. strongSelf->_settings.exponentialBackoffThrottleEndTime;
  356. NSError *error = [NSError
  357. errorWithDomain:FIRRemoteConfigErrorDomain
  358. code:FIRRemoteConfigErrorThrottled
  359. userInfo:@{
  360. FIRRemoteConfigThrottledEndTimeInSecondsKey : @(throttledEndTime)
  361. }];
  362. return [strongSelf reportCompletionOnHandler:completionHandler
  363. withStatus:strongSelf->_settings.lastFetchStatus
  364. withError:error];
  365. }
  366. }
  367. }
  368. // Return back the received error.
  369. // Must set lastFetchStatus before setting Fetch Error.
  370. strongSelf->_settings.lastFetchStatus = FIRRemoteConfigFetchStatusFailure;
  371. strongSelf->_settings.lastFetchError = FIRRemoteConfigErrorInternalError;
  372. NSDictionary<NSErrorUserInfoKey, id> *userInfo = @{
  373. NSLocalizedDescriptionKey :
  374. ([error localizedDescription]
  375. ?: [NSString
  376. stringWithFormat:@"Internal Error. Status code: %ld", (long)statusCode])
  377. };
  378. return [strongSelf
  379. reportCompletionOnHandler:completionHandler
  380. withStatus:FIRRemoteConfigFetchStatusFailure
  381. withError:[NSError errorWithDomain:FIRRemoteConfigErrorDomain
  382. code:FIRRemoteConfigErrorInternalError
  383. userInfo:userInfo]];
  384. }
  385. // Fetch was successful. Check if we have data.
  386. NSError *retError;
  387. if (!data) {
  388. FIRLogInfo(kFIRLoggerRemoteConfig, @"I-RCN000043", @"RCN Fetch: No data in fetch response");
  389. return [strongSelf reportCompletionOnHandler:completionHandler
  390. withStatus:FIRRemoteConfigFetchStatusSuccess
  391. withError:nil];
  392. }
  393. // Config fetch succeeded.
  394. // JSONObjectWithData is always expected to return an NSDictionary in our case
  395. NSMutableDictionary *fetchedConfig =
  396. [NSJSONSerialization JSONObjectWithData:data
  397. options:NSJSONReadingMutableContainers
  398. error:&retError];
  399. if (retError) {
  400. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000042",
  401. @"RCN Fetch failure: %@. Could not parse response data as JSON", error);
  402. }
  403. // Check and log if we received an error from the server
  404. if (fetchedConfig && fetchedConfig.count == 1 && fetchedConfig[RCNFetchResponseKeyError]) {
  405. NSString *errStr = [NSString stringWithFormat:@"RCN Fetch Failure: Server returned error:"];
  406. NSDictionary *errDict = fetchedConfig[RCNFetchResponseKeyError];
  407. if (errDict[RCNFetchResponseKeyErrorCode]) {
  408. errStr = [errStr
  409. stringByAppendingString:[NSString
  410. stringWithFormat:@"code: %@",
  411. errDict[RCNFetchResponseKeyErrorCode]]];
  412. }
  413. if (errDict[RCNFetchResponseKeyErrorStatus]) {
  414. errStr = [errStr stringByAppendingString:
  415. [NSString stringWithFormat:@". Status: %@",
  416. errDict[RCNFetchResponseKeyErrorStatus]]];
  417. }
  418. if (errDict[RCNFetchResponseKeyErrorMessage]) {
  419. errStr =
  420. [errStr stringByAppendingString:
  421. [NSString stringWithFormat:@". Message: %@",
  422. errDict[RCNFetchResponseKeyErrorMessage]]];
  423. }
  424. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000044", @"%@.", errStr);
  425. return [strongSelf
  426. reportCompletionOnHandler:completionHandler
  427. withStatus:FIRRemoteConfigFetchStatusFailure
  428. withError:[NSError
  429. errorWithDomain:FIRRemoteConfigErrorDomain
  430. code:FIRRemoteConfigErrorInternalError
  431. userInfo:@{NSLocalizedDescriptionKey : errStr}]];
  432. }
  433. // Add the fetched config to the database.
  434. if (fetchedConfig) {
  435. // Update config content to cache and DB.
  436. [strongSelf->_content updateConfigContentWithResponse:fetchedConfig
  437. forNamespace:strongSelf->_FIRNamespace];
  438. // Update experiments only for 3p namespace
  439. NSString *namespace = [strongSelf->_FIRNamespace
  440. substringToIndex:[strongSelf->_FIRNamespace rangeOfString:@":"].location];
  441. if ([namespace isEqualToString:FIRNamespaceGoogleMobilePlatform]) {
  442. [strongSelf->_experiment updateExperimentsWithResponse:
  443. fetchedConfig[RCNFetchResponseKeyExperimentDescriptions]];
  444. }
  445. strongSelf->_templateVersionNumber = [strongSelf getTemplateVersionNumber:fetchedConfig];
  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 updateMetadataWithFetchSuccessStatus:YES];
  457. return [strongSelf reportCompletionOnHandler:completionHandler
  458. withStatus:FIRRemoteConfigFetchStatusSuccess
  459. withError:nil];
  460. });
  461. };
  462. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000061", @"Making remote config fetch.");
  463. NSURLSessionDataTask *dataTask = [self URLSessionDataTaskWithContent:compressedContent
  464. completionHandler:fetcherCompletion];
  465. [dataTask resume];
  466. }
  467. - (NSString *)constructServerURL {
  468. NSString *serverURLStr = [[NSString alloc] initWithString:kServerURLDomain];
  469. serverURLStr = [serverURLStr stringByAppendingString:kServerURLVersion];
  470. serverURLStr = [serverURLStr stringByAppendingString:kServerURLProjects];
  471. serverURLStr = [serverURLStr stringByAppendingString:_options.projectID];
  472. serverURLStr = [serverURLStr stringByAppendingString:kServerURLNamespaces];
  473. // Get the namespace from the fully qualified namespace string of "namespace:FIRAppName".
  474. NSString *namespace =
  475. [_FIRNamespace substringToIndex:[_FIRNamespace rangeOfString:@":"].location];
  476. serverURLStr = [serverURLStr stringByAppendingString:namespace];
  477. serverURLStr = [serverURLStr stringByAppendingString:kServerURLQuery];
  478. if (_options.APIKey) {
  479. serverURLStr = [serverURLStr stringByAppendingString:kServerURLKey];
  480. serverURLStr = [serverURLStr stringByAppendingString:_options.APIKey];
  481. } else {
  482. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000071",
  483. @"Missing `APIKey` from `FirebaseOptions`, please ensure the configured "
  484. @"`FirebaseApp` is configured with `FirebaseOptions` that contains an `APIKey`.");
  485. }
  486. return serverURLStr;
  487. }
  488. - (NSURLSession *)newFetchSession {
  489. NSURLSessionConfiguration *config =
  490. [[NSURLSessionConfiguration defaultSessionConfiguration] copy];
  491. config.timeoutIntervalForRequest = _settings.fetchTimeout;
  492. config.timeoutIntervalForResource = _settings.fetchTimeout;
  493. NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
  494. return session;
  495. }
  496. - (NSURLSessionDataTask *)URLSessionDataTaskWithContent:(NSData *)content
  497. completionHandler:
  498. (RCNConfigFetcherCompletion)fetcherCompletion {
  499. NSURL *URL = [NSURL URLWithString:[self constructServerURL]];
  500. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000046", @"%@",
  501. [NSString stringWithFormat:@"Making config request: %@", [URL absoluteString]]);
  502. NSTimeInterval timeoutInterval = _fetchSession.configuration.timeoutIntervalForResource;
  503. NSMutableURLRequest *URLRequest =
  504. [[NSMutableURLRequest alloc] initWithURL:URL
  505. cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
  506. timeoutInterval:timeoutInterval];
  507. URLRequest.HTTPMethod = kHTTPMethodPost;
  508. [URLRequest setValue:kContentTypeValueJSON forHTTPHeaderField:kContentTypeHeaderName];
  509. [URLRequest setValue:_settings.configInstallationsToken
  510. forHTTPHeaderField:kInstallationsAuthTokenHeaderName];
  511. [URLRequest setValue:[[NSBundle mainBundle] bundleIdentifier]
  512. forHTTPHeaderField:kiOSBundleIdentifierHeaderName];
  513. [URLRequest setValue:@"gzip" forHTTPHeaderField:kContentEncodingHeaderName];
  514. [URLRequest setValue:@"gzip" forHTTPHeaderField:kAcceptEncodingHeaderName];
  515. // Set the eTag from the last successful fetch, if available.
  516. if (_settings.lastETag) {
  517. [URLRequest setValue:_settings.lastETag forHTTPHeaderField:kIfNoneMatchETagHeaderName];
  518. }
  519. [URLRequest setHTTPBody:content];
  520. return [_fetchSession dataTaskWithRequest:URLRequest completionHandler:fetcherCompletion];
  521. }
  522. - (NSString *)getTemplateVersionNumber:(NSDictionary *)fetchedConfig {
  523. if (fetchedConfig != nil && [fetchedConfig objectForKey:kTemplateVersionNumberKey] &&
  524. [[fetchedConfig objectForKey:kTemplateVersionNumberKey] isKindOfClass:[NSString class]]) {
  525. return (NSString *)[fetchedConfig objectForKey:kTemplateVersionNumberKey];
  526. }
  527. return @"1";
  528. }
  529. @end