RCNConfigFetch.m 34 KB

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