RCNConfigFetch.m 34 KB

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