RCNConfigFetch.m 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693
  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 "FirebaseRemoteConfig/Sources/Private/FIRRemoteConfig_Private.h"
  18. #import <GoogleUtilities/GULNSData+zlib.h>
  19. #import "FirebaseCore/Extension/FirebaseCoreInternal.h"
  20. #import "FirebaseInstallations/Source/Library/Private/FirebaseInstallationsInternal.h"
  21. #import "FirebaseRemoteConfig/Sources/Private/RCNConfigSettings.h"
  22. #import "FirebaseRemoteConfig/Sources/RCNConfigConstants.h"
  23. #import "FirebaseRemoteConfig/Sources/RCNConfigContent.h"
  24. #import "FirebaseRemoteConfig/Sources/RCNConfigExperiment.h"
  25. #import "FirebaseRemoteConfig/Sources/RCNConfigSessionConfiguration.h"
  26. #import "FirebaseRemoteConfig/Sources/RCNDevice.h"
  27. @import FirebaseRemoteConfigInterop;
  28. #ifdef RCN_STAGING_SERVER
  29. static NSString *const kServerURLDomain =
  30. @"https://staging-firebaseremoteconfig.sandbox.googleapis.com";
  31. #else
  32. static NSString *const kServerURLDomain = @"https://firebaseremoteconfig.googleapis.com";
  33. #endif
  34. static NSString *const kServerURLVersion = @"/v1";
  35. static NSString *const kServerURLProjects = @"/projects/";
  36. static NSString *const kServerURLNamespaces = @"/namespaces/";
  37. static NSString *const kServerURLQuery = @":fetch?";
  38. static NSString *const kServerURLKey = @"key=";
  39. static NSString *const kRequestJSONKeyAppID = @"app_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. static NSString *const kInstallationsAuthTokenHeaderName = @"x-goog-firebase-installations-auth";
  48. // Sends the bundle ID. Refer to b/130301479 for details.
  49. static NSString *const kiOSBundleIdentifierHeaderName =
  50. @"X-Ios-Bundle-Identifier"; ///< HTTP Header Field Name
  51. static NSString *const kFetchTypeHeaderName =
  52. @"X-Firebase-RC-Fetch-Type"; ///< Custom Http header key to identify the fetch type
  53. static NSString *const kBaseFetchType = @"BASE"; ///< Fetch identifier for Base Fetch
  54. static NSString *const kRealtimeFetchType = @"REALTIME"; ///< Fetch identifier for Realtime Fetch
  55. /// Config HTTP request content type proto buffer
  56. static NSString *const kContentTypeValueJSON = @"application/json";
  57. /// HTTP status codes. Ref: https://cloud.google.com/apis/design/errors#error_retries
  58. static NSInteger const kRCNFetchResponseHTTPStatusCodeOK = 200;
  59. static NSInteger const kRCNFetchResponseHTTPStatusTooManyRequests = 429;
  60. static NSInteger const kRCNFetchResponseHTTPStatusCodeInternalError = 500;
  61. static NSInteger const kRCNFetchResponseHTTPStatusCodeServiceUnavailable = 503;
  62. static NSInteger const kRCNFetchResponseHTTPStatusCodeGatewayTimeout = 504;
  63. #pragma mark - RCNConfig
  64. @implementation RCNConfigFetch {
  65. RCNConfigContent *_content;
  66. RCNConfigSettings *_settings;
  67. id<FIRAnalyticsInterop> _analytics;
  68. RCNConfigExperiment *_experiment;
  69. dispatch_queue_t _lockQueue; /// Guard the read/write operation.
  70. NSURLSession *_fetchSession; /// Managed internally by the fetch instance.
  71. NSString *_FIRNamespace;
  72. FIROptions *_options;
  73. NSString *_templateVersionNumber;
  74. }
  75. - (instancetype)init {
  76. NSAssert(NO, @"Invalid initializer.");
  77. return nil;
  78. }
  79. /// Designated initializer
  80. - (instancetype)initWithContent:(RCNConfigContent *)content
  81. DBManager:(RCNConfigDBManager *)DBManager
  82. settings:(RCNConfigSettings *)settings
  83. analytics:(nullable id<FIRAnalyticsInterop>)analytics
  84. experiment:(RCNConfigExperiment *)experiment
  85. queue:(dispatch_queue_t)queue
  86. namespace:(NSString *)FIRNamespace
  87. options:(FIROptions *)options {
  88. self = [super init];
  89. if (self) {
  90. _FIRNamespace = FIRNamespace;
  91. _settings = settings;
  92. _analytics = analytics;
  93. _experiment = experiment;
  94. _lockQueue = queue;
  95. _content = content;
  96. _fetchSession = [self newFetchSession];
  97. _options = options;
  98. _templateVersionNumber = [self->_settings lastFetchedTemplateVersion];
  99. }
  100. return self;
  101. }
  102. /// Force a new NSURLSession creation for updated config.
  103. - (void)recreateNetworkSession {
  104. if (_fetchSession) {
  105. [_fetchSession invalidateAndCancel];
  106. }
  107. _fetchSession = [self newFetchSession];
  108. }
  109. /// Return the current session. (Tests).
  110. - (NSURLSession *)currentNetworkSession {
  111. return _fetchSession;
  112. }
  113. - (void)dealloc {
  114. [_fetchSession invalidateAndCancel];
  115. }
  116. #pragma mark - Fetch Config API
  117. - (void)fetchConfigWithExpirationDuration:(NSTimeInterval)expirationDuration
  118. completionHandler:
  119. (_Nullable FIRRemoteConfigFetchCompletion)completionHandler {
  120. // Note: We expect the googleAppID to always be available.
  121. BOOL hasDeviceContextChanged =
  122. FIRRemoteConfigHasDeviceContextChanged(_settings.deviceContext, _options.googleAppID);
  123. __weak RCNConfigFetch *weakSelf = self;
  124. dispatch_async(_lockQueue, ^{
  125. RCNConfigFetch *strongSelf = weakSelf;
  126. if (strongSelf == nil) {
  127. return;
  128. }
  129. // Check whether we are outside of the minimum fetch interval.
  130. if (![strongSelf->_settings hasMinimumFetchIntervalElapsed:expirationDuration] &&
  131. !hasDeviceContextChanged) {
  132. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000051", @"Returning cached data.");
  133. return [strongSelf reportCompletionOnHandler:completionHandler
  134. withStatus:FIRRemoteConfigFetchStatusSuccess
  135. withError:nil];
  136. }
  137. // Check if a fetch is already in progress.
  138. if (strongSelf->_settings.isFetchInProgress) {
  139. // Check if we have some fetched data.
  140. if (strongSelf->_settings.lastFetchTimeInterval > 0) {
  141. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000052",
  142. @"A fetch is already in progress. Using previous fetch results.");
  143. return [strongSelf reportCompletionOnHandler:completionHandler
  144. withStatus:strongSelf->_settings.lastFetchStatus
  145. withError:nil];
  146. } else {
  147. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000053",
  148. @"A fetch is already in progress. Ignoring duplicate request.");
  149. return [strongSelf reportCompletionOnHandler:completionHandler
  150. withStatus:FIRRemoteConfigFetchStatusFailure
  151. withError:nil];
  152. }
  153. }
  154. // Check whether cache data is within throttle limit.
  155. if ([strongSelf->_settings shouldThrottle] && !hasDeviceContextChanged) {
  156. // Must set lastFetchStatus before FailReason.
  157. strongSelf->_settings.lastFetchStatus = FIRRemoteConfigFetchStatusThrottled;
  158. strongSelf->_settings.lastFetchError = FIRRemoteConfigErrorThrottled;
  159. NSTimeInterval throttledEndTime = strongSelf->_settings.exponentialBackoffThrottleEndTime;
  160. NSError *error =
  161. [NSError errorWithDomain:FIRRemoteConfigErrorDomain
  162. code:FIRRemoteConfigErrorThrottled
  163. userInfo:@{
  164. FIRRemoteConfigThrottledEndTimeInSecondsKey : @(throttledEndTime)
  165. }];
  166. return [strongSelf reportCompletionOnHandler:completionHandler
  167. withStatus:strongSelf->_settings.lastFetchStatus
  168. withError:error];
  169. }
  170. strongSelf->_settings.isFetchInProgress = YES;
  171. NSString *fetchTypeHeader = [NSString stringWithFormat:@"%@/1", kBaseFetchType];
  172. [strongSelf refreshInstallationsTokenWithFetchHeader:fetchTypeHeader
  173. completionHandler:completionHandler
  174. updateCompletionHandler:nil];
  175. });
  176. }
  177. #pragma mark - Fetch helpers
  178. - (void)realtimeFetchConfigWithNoExpirationDuration:(NSInteger)fetchAttemptNumber
  179. completionHandler:(RCNConfigFetchCompletion)completionHandler {
  180. // Note: We expect the googleAppID to always be available.
  181. BOOL hasDeviceContextChanged =
  182. FIRRemoteConfigHasDeviceContextChanged(_settings.deviceContext, _options.googleAppID);
  183. __weak RCNConfigFetch *weakSelf = self;
  184. dispatch_async(_lockQueue, ^{
  185. RCNConfigFetch *strongSelf = weakSelf;
  186. if (strongSelf == nil) {
  187. return;
  188. }
  189. // Check whether cache data is within throttle limit.
  190. if ([strongSelf->_settings shouldThrottle] && !hasDeviceContextChanged) {
  191. // Must set lastFetchStatus before FailReason.
  192. strongSelf->_settings.lastFetchStatus = FIRRemoteConfigFetchStatusThrottled;
  193. strongSelf->_settings.lastFetchError = FIRRemoteConfigErrorThrottled;
  194. NSTimeInterval throttledEndTime = strongSelf->_settings.exponentialBackoffThrottleEndTime;
  195. NSError *error =
  196. [NSError errorWithDomain:FIRRemoteConfigErrorDomain
  197. code:FIRRemoteConfigErrorThrottled
  198. userInfo:@{
  199. FIRRemoteConfigThrottledEndTimeInSecondsKey : @(throttledEndTime)
  200. }];
  201. return [strongSelf reportCompletionWithStatus:FIRRemoteConfigFetchStatusFailure
  202. withUpdate:nil
  203. withError:error
  204. completionHandler:nil
  205. updateCompletionHandler:completionHandler];
  206. }
  207. strongSelf->_settings.isFetchInProgress = YES;
  208. NSString *fetchTypeHeader =
  209. [NSString stringWithFormat:@"%@/%ld", kRealtimeFetchType, (long)fetchAttemptNumber];
  210. [strongSelf refreshInstallationsTokenWithFetchHeader:fetchTypeHeader
  211. completionHandler:nil
  212. updateCompletionHandler:completionHandler];
  213. });
  214. }
  215. - (NSString *)FIRAppNameFromFullyQualifiedNamespace {
  216. return [[_FIRNamespace componentsSeparatedByString:@":"] lastObject];
  217. }
  218. /// Refresh installation ID token before fetching config. installation ID is now mandatory for fetch
  219. /// requests to work.(b/14751422).
  220. - (void)refreshInstallationsTokenWithFetchHeader:(NSString *)fetchTypeHeader
  221. completionHandler:(FIRRemoteConfigFetchCompletion)completionHandler
  222. updateCompletionHandler:(RCNConfigFetchCompletion)updateCompletionHandler {
  223. FIRInstallations *installations = [FIRInstallations
  224. installationsWithApp:[FIRApp appNamed:[self FIRAppNameFromFullyQualifiedNamespace]]];
  225. if (!installations || !_options.GCMSenderID) {
  226. NSString *errorDescription = @"Failed to get GCMSenderID";
  227. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000074", @"%@",
  228. [NSString stringWithFormat:@"%@", errorDescription]);
  229. self->_settings.isFetchInProgress = NO;
  230. return [self
  231. reportCompletionOnHandler:completionHandler
  232. withStatus:FIRRemoteConfigFetchStatusFailure
  233. withError:[NSError errorWithDomain:FIRRemoteConfigErrorDomain
  234. code:FIRRemoteConfigErrorInternalError
  235. userInfo:@{
  236. NSLocalizedDescriptionKey : errorDescription
  237. }]];
  238. }
  239. __weak RCNConfigFetch *weakSelf = self;
  240. FIRInstallationsTokenHandler installationsTokenHandler = ^(
  241. FIRInstallationsAuthTokenResult *tokenResult, NSError *error) {
  242. RCNConfigFetch *strongSelf = weakSelf;
  243. if (strongSelf == nil) {
  244. return;
  245. }
  246. if (!tokenResult || !tokenResult.authToken || error) {
  247. NSString *errorDescription =
  248. [NSString stringWithFormat:@"Failed to get installations token. Error : %@.", error];
  249. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000073", @"%@",
  250. [NSString stringWithFormat:@"%@", errorDescription]);
  251. strongSelf->_settings.isFetchInProgress = NO;
  252. NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
  253. userInfo[NSLocalizedDescriptionKey] = errorDescription;
  254. userInfo[NSUnderlyingErrorKey] = error.userInfo[NSUnderlyingErrorKey];
  255. return [strongSelf
  256. reportCompletionOnHandler:completionHandler
  257. withStatus:FIRRemoteConfigFetchStatusFailure
  258. withError:[NSError errorWithDomain:FIRRemoteConfigErrorDomain
  259. code:FIRRemoteConfigErrorInternalError
  260. userInfo:userInfo]];
  261. }
  262. // We have a valid token. Get the backing installationID.
  263. [installations installationIDWithCompletion:^(NSString *_Nullable identifier,
  264. NSError *_Nullable error) {
  265. RCNConfigFetch *strongSelf = weakSelf;
  266. if (strongSelf == nil) {
  267. return;
  268. }
  269. // Dispatch to the RC serial queue to update settings on the queue.
  270. dispatch_async(strongSelf->_lockQueue, ^{
  271. RCNConfigFetch *strongSelfQueue = weakSelf;
  272. if (strongSelfQueue == nil) {
  273. return;
  274. }
  275. // Update config settings with the IID and token.
  276. strongSelfQueue->_settings.configInstallationsToken = tokenResult.authToken;
  277. strongSelfQueue->_settings.configInstallationsIdentifier = identifier;
  278. if (!identifier || error) {
  279. NSString *errorDescription =
  280. [NSString stringWithFormat:@"Error getting iid : %@.", error];
  281. NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
  282. userInfo[NSLocalizedDescriptionKey] = errorDescription;
  283. userInfo[NSUnderlyingErrorKey] = error.userInfo[NSUnderlyingErrorKey];
  284. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000055", @"%@",
  285. [NSString stringWithFormat:@"%@", errorDescription]);
  286. strongSelfQueue->_settings.isFetchInProgress = NO;
  287. return [strongSelfQueue
  288. reportCompletionOnHandler:completionHandler
  289. withStatus:FIRRemoteConfigFetchStatusFailure
  290. withError:[NSError errorWithDomain:FIRRemoteConfigErrorDomain
  291. code:FIRRemoteConfigErrorInternalError
  292. userInfo:userInfo]];
  293. }
  294. FIRLogInfo(kFIRLoggerRemoteConfig, @"I-RCN000022", @"Success to get iid : %@.",
  295. strongSelfQueue->_settings.configInstallationsIdentifier);
  296. [strongSelf doFetchCall:fetchTypeHeader
  297. completionHandler:completionHandler
  298. updateCompletionHandler:updateCompletionHandler];
  299. });
  300. }];
  301. };
  302. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000039", @"Starting requesting token.");
  303. [installations authTokenWithCompletion:installationsTokenHandler];
  304. }
  305. - (void)doFetchCall:(NSString *)fetchTypeHeader
  306. completionHandler:(FIRRemoteConfigFetchCompletion)completionHandler
  307. updateCompletionHandler:(RCNConfigFetchCompletion)updateCompletionHandler {
  308. [self getAnalyticsUserPropertiesWithCompletionHandler:^(NSDictionary *userProperties) {
  309. dispatch_async(self->_lockQueue, ^{
  310. [self fetchWithUserProperties:userProperties
  311. fetchTypeHeader:fetchTypeHeader
  312. completionHandler:completionHandler
  313. updateCompletionHandler:updateCompletionHandler];
  314. });
  315. }];
  316. }
  317. - (void)getAnalyticsUserPropertiesWithCompletionHandler:
  318. (FIRAInteropUserPropertiesCallback)completionHandler {
  319. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000060", @"Fetch with user properties completed.");
  320. id<FIRAnalyticsInterop> analytics = self->_analytics;
  321. if (analytics == nil) {
  322. completionHandler(@{});
  323. } else {
  324. [analytics getUserPropertiesWithCallback:completionHandler];
  325. }
  326. }
  327. - (void)reportCompletionOnHandler:(FIRRemoteConfigFetchCompletion)completionHandler
  328. withStatus:(FIRRemoteConfigFetchStatus)status
  329. withError:(NSError *)error {
  330. [self reportCompletionWithStatus:status
  331. withUpdate:nil
  332. withError:error
  333. completionHandler:completionHandler
  334. updateCompletionHandler:nil];
  335. }
  336. - (void)reportCompletionWithStatus:(FIRRemoteConfigFetchStatus)status
  337. withUpdate:(FIRRemoteConfigUpdate *)update
  338. withError:(NSError *)error
  339. completionHandler:(FIRRemoteConfigFetchCompletion)completionHandler
  340. updateCompletionHandler:(RCNConfigFetchCompletion)updateCompletionHandler {
  341. if (completionHandler) {
  342. dispatch_async(dispatch_get_main_queue(), ^{
  343. completionHandler(status, error);
  344. });
  345. }
  346. // if completion handler expects a config update response
  347. if (updateCompletionHandler) {
  348. dispatch_async(dispatch_get_main_queue(), ^{
  349. updateCompletionHandler(status, update, error);
  350. });
  351. }
  352. }
  353. - (void)fetchWithUserProperties:(NSDictionary *)userProperties
  354. fetchTypeHeader:(NSString *)fetchTypeHeader
  355. completionHandler:(FIRRemoteConfigFetchCompletion)completionHandler
  356. updateCompletionHandler:(RCNConfigFetchCompletion)updateCompletionHandler {
  357. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000061", @"Fetch with user properties initiated.");
  358. NSString *postRequestString = [_settings nextRequestWithUserProperties:userProperties];
  359. // Get POST request content.
  360. NSData *content = [postRequestString dataUsingEncoding:NSUTF8StringEncoding];
  361. NSError *compressionError;
  362. NSData *compressedContent = [NSData gul_dataByGzippingData:content error:&compressionError];
  363. if (compressionError) {
  364. NSString *errString = [NSString stringWithFormat:@"Failed to compress the config request."];
  365. FIRLogWarning(kFIRLoggerRemoteConfig, @"I-RCN000033", @"%@", errString);
  366. NSError *error = [NSError errorWithDomain:FIRRemoteConfigErrorDomain
  367. code:FIRRemoteConfigErrorInternalError
  368. userInfo:@{NSLocalizedDescriptionKey : errString}];
  369. self->_settings.isFetchInProgress = NO;
  370. return [self reportCompletionWithStatus:FIRRemoteConfigFetchStatusFailure
  371. withUpdate:nil
  372. withError:error
  373. completionHandler:completionHandler
  374. updateCompletionHandler:updateCompletionHandler];
  375. }
  376. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000040", @"Start config fetch.");
  377. __weak RCNConfigFetch *weakSelf = self;
  378. RCNConfigFetcherCompletion fetcherCompletion = ^(NSData *data, NSURLResponse *response,
  379. NSError *error) {
  380. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000050",
  381. @"config fetch completed. Error: %@ StatusCode: %ld", (error ? error : @"nil"),
  382. (long)[((NSHTTPURLResponse *)response) statusCode]);
  383. RCNConfigFetch *fetcherCompletionSelf = weakSelf;
  384. if (fetcherCompletionSelf == nil) {
  385. return;
  386. }
  387. // The fetch has completed.
  388. fetcherCompletionSelf->_settings.isFetchInProgress = NO;
  389. dispatch_async(fetcherCompletionSelf->_lockQueue, ^{
  390. RCNConfigFetch *strongSelf = weakSelf;
  391. if (strongSelf == nil) {
  392. return;
  393. }
  394. NSInteger statusCode = [((NSHTTPURLResponse *)response) statusCode];
  395. if (error || (statusCode != kRCNFetchResponseHTTPStatusCodeOK)) {
  396. // Update metadata about fetch failure.
  397. [strongSelf->_settings updateMetadataWithFetchSuccessStatus:NO templateVersion:nil];
  398. if (error) {
  399. if (strongSelf->_settings.lastFetchStatus == FIRRemoteConfigFetchStatusSuccess) {
  400. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000025",
  401. @"RCN Fetch failure: %@. Using cached config result.", error);
  402. } else {
  403. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000026",
  404. @"RCN Fetch failure: %@. No cached config result.", error);
  405. }
  406. }
  407. if (statusCode != kRCNFetchResponseHTTPStatusCodeOK) {
  408. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000026",
  409. @"RCN Fetch failure. Response http error code: %ld", (long)statusCode);
  410. // Response error code 429, 500, 503 will trigger exponential backoff mode.
  411. // TODO: check error code in helper
  412. if (statusCode == kRCNFetchResponseHTTPStatusTooManyRequests ||
  413. statusCode == kRCNFetchResponseHTTPStatusCodeInternalError ||
  414. statusCode == kRCNFetchResponseHTTPStatusCodeServiceUnavailable ||
  415. statusCode == kRCNFetchResponseHTTPStatusCodeGatewayTimeout) {
  416. [strongSelf->_settings updateExponentialBackoffTime];
  417. if ([strongSelf->_settings shouldThrottle]) {
  418. // Must set lastFetchStatus before FailReason.
  419. strongSelf->_settings.lastFetchStatus = FIRRemoteConfigFetchStatusThrottled;
  420. strongSelf->_settings.lastFetchError = FIRRemoteConfigErrorThrottled;
  421. NSTimeInterval throttledEndTime =
  422. strongSelf->_settings.exponentialBackoffThrottleEndTime;
  423. NSError *error = [NSError
  424. errorWithDomain:FIRRemoteConfigErrorDomain
  425. code:FIRRemoteConfigErrorThrottled
  426. userInfo:@{
  427. FIRRemoteConfigThrottledEndTimeInSecondsKey : @(throttledEndTime)
  428. }];
  429. return [strongSelf reportCompletionWithStatus:strongSelf->_settings.lastFetchStatus
  430. withUpdate:nil
  431. withError:error
  432. completionHandler:completionHandler
  433. updateCompletionHandler:updateCompletionHandler];
  434. }
  435. }
  436. }
  437. // Return back the received error.
  438. // Must set lastFetchStatus before setting Fetch Error.
  439. strongSelf->_settings.lastFetchStatus = FIRRemoteConfigFetchStatusFailure;
  440. strongSelf->_settings.lastFetchError = FIRRemoteConfigErrorInternalError;
  441. NSMutableDictionary<NSErrorUserInfoKey, id> *userInfo = [NSMutableDictionary dictionary];
  442. userInfo[NSUnderlyingErrorKey] = error;
  443. userInfo[NSLocalizedDescriptionKey] =
  444. error.localizedDescription
  445. ?: [NSString
  446. stringWithFormat:@"Internal Error. Status code: %ld", (long)statusCode];
  447. return [strongSelf
  448. reportCompletionWithStatus:FIRRemoteConfigFetchStatusFailure
  449. withUpdate:nil
  450. withError:[NSError errorWithDomain:FIRRemoteConfigErrorDomain
  451. code:FIRRemoteConfigErrorInternalError
  452. userInfo:userInfo]
  453. completionHandler:completionHandler
  454. updateCompletionHandler:updateCompletionHandler];
  455. }
  456. // Fetch was successful. Check if we have data.
  457. NSError *retError;
  458. if (!data) {
  459. FIRLogInfo(kFIRLoggerRemoteConfig, @"I-RCN000043", @"RCN Fetch: No data in fetch response");
  460. // There may still be a difference between fetched and active config
  461. FIRRemoteConfigUpdate *update =
  462. [strongSelf->_content getConfigUpdateForNamespace:strongSelf->_FIRNamespace];
  463. return [strongSelf reportCompletionWithStatus:FIRRemoteConfigFetchStatusSuccess
  464. withUpdate:update
  465. withError:nil
  466. completionHandler:completionHandler
  467. updateCompletionHandler:updateCompletionHandler];
  468. }
  469. // Config fetch succeeded.
  470. // JSONObjectWithData is always expected to return an NSDictionary in our case
  471. NSMutableDictionary *fetchedConfig =
  472. [NSJSONSerialization JSONObjectWithData:data
  473. options:NSJSONReadingMutableContainers
  474. error:&retError];
  475. if (retError) {
  476. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000042",
  477. @"RCN Fetch failure: %@. Could not parse response data as JSON", error);
  478. }
  479. // Check and log if we received an error from the server
  480. if (fetchedConfig && fetchedConfig.count == 1 && fetchedConfig[RCNFetchResponseKeyError]) {
  481. NSString *errStr = [NSString stringWithFormat:@"RCN Fetch Failure: Server returned error:"];
  482. NSDictionary *errDict = fetchedConfig[RCNFetchResponseKeyError];
  483. if (errDict[RCNFetchResponseKeyErrorCode]) {
  484. errStr = [errStr
  485. stringByAppendingString:[NSString
  486. stringWithFormat:@"code: %@",
  487. errDict[RCNFetchResponseKeyErrorCode]]];
  488. }
  489. if (errDict[RCNFetchResponseKeyErrorStatus]) {
  490. errStr = [errStr stringByAppendingString:
  491. [NSString stringWithFormat:@". Status: %@",
  492. errDict[RCNFetchResponseKeyErrorStatus]]];
  493. }
  494. if (errDict[RCNFetchResponseKeyErrorMessage]) {
  495. errStr =
  496. [errStr stringByAppendingString:
  497. [NSString stringWithFormat:@". Message: %@",
  498. errDict[RCNFetchResponseKeyErrorMessage]]];
  499. }
  500. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000044", @"%@.", errStr);
  501. NSError *error = [NSError errorWithDomain:FIRRemoteConfigErrorDomain
  502. code:FIRRemoteConfigErrorInternalError
  503. userInfo:@{NSLocalizedDescriptionKey : errStr}];
  504. return [strongSelf reportCompletionWithStatus:FIRRemoteConfigFetchStatusFailure
  505. withUpdate:nil
  506. withError:error
  507. completionHandler:completionHandler
  508. updateCompletionHandler:updateCompletionHandler];
  509. }
  510. // Add the fetched config to the database.
  511. if (fetchedConfig) {
  512. // Update config content to cache and DB.
  513. [strongSelf->_content updateConfigContentWithResponse:fetchedConfig
  514. forNamespace:strongSelf->_FIRNamespace];
  515. // Update experiments only for 3p namespace
  516. NSString *namespace = [strongSelf->_FIRNamespace
  517. substringToIndex:[strongSelf->_FIRNamespace rangeOfString:@":"].location];
  518. if ([namespace isEqualToString:FIRRemoteConfigConstants.FIRNamespaceGoogleMobilePlatform]) {
  519. [strongSelf->_experiment updateExperimentsWithResponse:
  520. fetchedConfig[RCNFetchResponseKeyExperimentDescriptions]];
  521. }
  522. strongSelf->_templateVersionNumber = [strongSelf getTemplateVersionNumber:fetchedConfig];
  523. } else {
  524. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000063",
  525. @"Empty response with no fetched config.");
  526. }
  527. // We had a successful fetch. Update the current eTag in settings if different.
  528. NSString *latestETag = ((NSHTTPURLResponse *)response).allHeaderFields[kETagHeaderName];
  529. if (!strongSelf->_settings.lastETag ||
  530. !([strongSelf->_settings.lastETag isEqualToString:latestETag])) {
  531. strongSelf->_settings.lastETag = latestETag;
  532. }
  533. // Compute config update after successful fetch
  534. FIRRemoteConfigUpdate *update =
  535. [strongSelf->_content getConfigUpdateForNamespace:strongSelf->_FIRNamespace];
  536. [strongSelf->_settings
  537. updateMetadataWithFetchSuccessStatus:YES
  538. templateVersion:strongSelf->_templateVersionNumber];
  539. return [strongSelf reportCompletionWithStatus:FIRRemoteConfigFetchStatusSuccess
  540. withUpdate:update
  541. withError:nil
  542. completionHandler:completionHandler
  543. updateCompletionHandler:updateCompletionHandler];
  544. });
  545. };
  546. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000061", @"Making remote config fetch.");
  547. NSURLSessionDataTask *dataTask = [self URLSessionDataTaskWithContent:compressedContent
  548. fetchTypeHeader:fetchTypeHeader
  549. completionHandler:fetcherCompletion];
  550. [dataTask resume];
  551. }
  552. - (NSString *)constructServerURL {
  553. NSString *serverURLStr = [[NSString alloc] initWithString:kServerURLDomain];
  554. serverURLStr = [serverURLStr stringByAppendingString:kServerURLVersion];
  555. serverURLStr = [serverURLStr stringByAppendingString:kServerURLProjects];
  556. serverURLStr = [serverURLStr stringByAppendingString:_options.projectID];
  557. serverURLStr = [serverURLStr stringByAppendingString:kServerURLNamespaces];
  558. // Get the namespace from the fully qualified namespace string of "namespace:FIRAppName".
  559. NSString *namespace =
  560. [_FIRNamespace substringToIndex:[_FIRNamespace rangeOfString:@":"].location];
  561. serverURLStr = [serverURLStr stringByAppendingString:namespace];
  562. serverURLStr = [serverURLStr stringByAppendingString:kServerURLQuery];
  563. if (_options.APIKey) {
  564. serverURLStr = [serverURLStr stringByAppendingString:kServerURLKey];
  565. serverURLStr = [serverURLStr stringByAppendingString:_options.APIKey];
  566. } else {
  567. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000071",
  568. @"Missing `APIKey` from `FirebaseOptions`, please ensure the configured "
  569. @"`FirebaseApp` is configured with `FirebaseOptions` that contains an `APIKey`.");
  570. }
  571. return serverURLStr;
  572. }
  573. - (NSURLSession *)newFetchSession {
  574. NSURLSessionConfiguration *config =
  575. [RCNConfigSessionConfiguration remoteConfigSessionConfiguration];
  576. config.timeoutIntervalForRequest = _settings.fetchTimeout;
  577. config.timeoutIntervalForResource = _settings.fetchTimeout;
  578. NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
  579. return session;
  580. }
  581. - (NSURLSessionDataTask *)URLSessionDataTaskWithContent:(NSData *)content
  582. fetchTypeHeader:(NSString *)fetchTypeHeader
  583. completionHandler:
  584. (RCNConfigFetcherCompletion)fetcherCompletion {
  585. NSURL *URL = [NSURL URLWithString:[self constructServerURL]];
  586. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000046", @"%@",
  587. [NSString stringWithFormat:@"Making config request: %@", [URL absoluteString]]);
  588. NSTimeInterval timeoutInterval = _fetchSession.configuration.timeoutIntervalForResource;
  589. NSMutableURLRequest *URLRequest =
  590. [[NSMutableURLRequest alloc] initWithURL:URL
  591. cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
  592. timeoutInterval:timeoutInterval];
  593. URLRequest.HTTPMethod = kHTTPMethodPost;
  594. [URLRequest setValue:kContentTypeValueJSON forHTTPHeaderField:kContentTypeHeaderName];
  595. [URLRequest setValue:_settings.configInstallationsToken
  596. forHTTPHeaderField:kInstallationsAuthTokenHeaderName];
  597. [URLRequest setValue:[[NSBundle mainBundle] bundleIdentifier]
  598. forHTTPHeaderField:kiOSBundleIdentifierHeaderName];
  599. [URLRequest setValue:@"gzip" forHTTPHeaderField:kContentEncodingHeaderName];
  600. [URLRequest setValue:@"gzip" forHTTPHeaderField:kAcceptEncodingHeaderName];
  601. [URLRequest setValue:fetchTypeHeader forHTTPHeaderField:kFetchTypeHeaderName];
  602. // Set the eTag from the last successful fetch, if available.
  603. if (_settings.lastETag) {
  604. [URLRequest setValue:_settings.lastETag forHTTPHeaderField:kIfNoneMatchETagHeaderName];
  605. }
  606. [URLRequest setHTTPBody:content];
  607. return [_fetchSession dataTaskWithRequest:URLRequest completionHandler:fetcherCompletion];
  608. }
  609. - (NSString *)getTemplateVersionNumber:(NSDictionary *)fetchedConfig {
  610. if (fetchedConfig != nil && [fetchedConfig objectForKey:RCNFetchResponseKeyTemplateVersion] &&
  611. [[fetchedConfig objectForKey:RCNFetchResponseKeyTemplateVersion]
  612. isKindOfClass:[NSString class]]) {
  613. return (NSString *)[fetchedConfig objectForKey:RCNFetchResponseKeyTemplateVersion];
  614. }
  615. return @"0";
  616. }
  617. @end