RCNConfigFetch.m 33 KB

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