RCNConfigFetch.m 33 KB

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