RCNConfigFetch.m 33 KB

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