RCNConfigFetch.m 33 KB

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