FIRRemoteConfig.m 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  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/Public/FirebaseRemoteConfig/FIRRemoteConfig.h"
  17. #import "FirebaseABTesting/Sources/Private/FirebaseABTestingInternal.h"
  18. #import "FirebaseCore/Sources/Private/FirebaseCoreInternal.h"
  19. #import "FirebaseRemoteConfig/Sources/FIRRemoteConfigComponent.h"
  20. #import "FirebaseRemoteConfig/Sources/Private/FIRRemoteConfig_Private.h"
  21. #import "FirebaseRemoteConfig/Sources/Private/RCNConfigFetch.h"
  22. #import "FirebaseRemoteConfig/Sources/Private/RCNConfigSettings.h"
  23. #import "FirebaseRemoteConfig/Sources/RCNConfigConstants.h"
  24. #import "FirebaseRemoteConfig/Sources/RCNConfigContent.h"
  25. #import "FirebaseRemoteConfig/Sources/RCNConfigDBManager.h"
  26. #import "FirebaseRemoteConfig/Sources/RCNConfigExperiment.h"
  27. #import "FirebaseRemoteConfig/Sources/RCNConfigValue_Internal.h"
  28. #import "FirebaseRemoteConfig/Sources/RCNDevice.h"
  29. #import "FirebaseRemoteConfig/Sources/RCNPersonalization.h"
  30. /// Remote Config Error Domain.
  31. /// TODO: Rename according to obj-c style for constants.
  32. NSString *const FIRRemoteConfigErrorDomain = @"com.google.remoteconfig.ErrorDomain";
  33. /// Remote Config Error Info End Time Seconds;
  34. NSString *const FIRRemoteConfigThrottledEndTimeInSecondsKey = @"error_throttled_end_time_seconds";
  35. /// Minimum required time interval between fetch requests made to the backend.
  36. static NSString *const kRemoteConfigMinimumFetchIntervalKey = @"_rcn_minimum_fetch_interval";
  37. /// Timeout value for waiting on a fetch response.
  38. static NSString *const kRemoteConfigFetchTimeoutKey = @"_rcn_fetch_timeout";
  39. /// Listener for the get methods.
  40. typedef void (^FIRRemoteConfigListener)(NSString *_Nonnull, NSDictionary *_Nonnull);
  41. @implementation FIRRemoteConfigSettings
  42. - (instancetype)init {
  43. self = [super init];
  44. if (self) {
  45. _minimumFetchInterval = RCNDefaultMinimumFetchInterval;
  46. _fetchTimeout = RCNHTTPDefaultConnectionTimeout;
  47. }
  48. return self;
  49. }
  50. @end
  51. @implementation FIRRemoteConfig {
  52. /// All the config content.
  53. RCNConfigContent *_configContent;
  54. RCNConfigDBManager *_DBManager;
  55. RCNConfigSettings *_settings;
  56. RCNConfigFetch *_configFetch;
  57. RCNConfigExperiment *_configExperiment;
  58. dispatch_queue_t _queue;
  59. NSString *_appName;
  60. NSMutableArray *_listeners;
  61. }
  62. static NSMutableDictionary<NSString *, NSMutableDictionary<NSString *, FIRRemoteConfig *> *>
  63. *RCInstances;
  64. + (nonnull FIRRemoteConfig *)remoteConfigWithApp:(FIRApp *_Nonnull)firebaseApp {
  65. return [FIRRemoteConfig remoteConfigWithFIRNamespace:FIRNamespaceGoogleMobilePlatform
  66. app:firebaseApp];
  67. }
  68. + (nonnull FIRRemoteConfig *)remoteConfigWithFIRNamespace:(NSString *_Nonnull)firebaseNamespace {
  69. if (![FIRApp isDefaultAppConfigured]) {
  70. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000047",
  71. @"FIRApp not configured. Please make sure you have called [FIRApp configure]");
  72. // TODO: Maybe throw an exception here? That'd be a breaking change though, but at this point
  73. // RC can't work as expected.
  74. }
  75. return [FIRRemoteConfig remoteConfigWithFIRNamespace:firebaseNamespace app:[FIRApp defaultApp]];
  76. }
  77. + (nonnull FIRRemoteConfig *)remoteConfigWithFIRNamespace:(NSString *_Nonnull)firebaseNamespace
  78. app:(FIRApp *_Nonnull)firebaseApp {
  79. // Use the provider to generate and return instances of FIRRemoteConfig for this specific app and
  80. // namespace. This will ensure the app is configured before Remote Config can return an instance.
  81. id<FIRRemoteConfigProvider> provider =
  82. FIR_COMPONENT(FIRRemoteConfigProvider, firebaseApp.container);
  83. return [provider remoteConfigForNamespace:firebaseNamespace];
  84. }
  85. + (FIRRemoteConfig *)remoteConfig {
  86. // If the default app is not configured at this point, warn the developer.
  87. if (![FIRApp isDefaultAppConfigured]) {
  88. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000047",
  89. @"FIRApp not configured. Please make sure you have called [FIRApp configure]");
  90. // TODO: Maybe throw an exception here? That'd be a breaking change though, but at this point
  91. // RC can't work as expected.
  92. }
  93. return [FIRRemoteConfig remoteConfigWithFIRNamespace:FIRNamespaceGoogleMobilePlatform
  94. app:[FIRApp defaultApp]];
  95. }
  96. /// Singleton instance of serial queue for queuing all incoming RC calls.
  97. + (dispatch_queue_t)sharedRemoteConfigSerialQueue {
  98. static dispatch_once_t onceToken;
  99. static dispatch_queue_t sharedRemoteConfigQueue;
  100. dispatch_once(&onceToken, ^{
  101. sharedRemoteConfigQueue =
  102. dispatch_queue_create(RCNRemoteConfigQueueLabel, DISPATCH_QUEUE_SERIAL);
  103. });
  104. return sharedRemoteConfigQueue;
  105. }
  106. /// Designated initializer
  107. - (instancetype)initWithAppName:(NSString *)appName
  108. FIROptions:(FIROptions *)options
  109. namespace:(NSString *)FIRNamespace
  110. DBManager:(RCNConfigDBManager *)DBManager
  111. configContent:(RCNConfigContent *)configContent
  112. analytics:(nullable id<FIRAnalyticsInterop>)analytics {
  113. self = [super init];
  114. if (self) {
  115. _appName = appName;
  116. _DBManager = DBManager;
  117. // The fully qualified Firebase namespace is namespace:firappname.
  118. _FIRNamespace = [NSString stringWithFormat:@"%@:%@", FIRNamespace, appName];
  119. // Initialize RCConfigContent if not already.
  120. _configContent = configContent;
  121. _settings = [[RCNConfigSettings alloc] initWithDatabaseManager:_DBManager
  122. namespace:_FIRNamespace
  123. firebaseAppName:appName
  124. googleAppID:options.googleAppID];
  125. FIRExperimentController *experimentController = [FIRExperimentController sharedInstance];
  126. _configExperiment = [[RCNConfigExperiment alloc] initWithDBManager:_DBManager
  127. experimentController:experimentController];
  128. /// Serial queue for read and write lock.
  129. _queue = [FIRRemoteConfig sharedRemoteConfigSerialQueue];
  130. // Initialize with default config settings.
  131. [self setDefaultConfigSettings];
  132. _configFetch = [[RCNConfigFetch alloc] initWithContent:_configContent
  133. DBManager:_DBManager
  134. settings:_settings
  135. analytics:analytics
  136. experiment:_configExperiment
  137. queue:_queue
  138. namespace:_FIRNamespace
  139. options:options];
  140. [_settings loadConfigFromMetadataTable];
  141. if (analytics) {
  142. _listeners = [[NSMutableArray alloc] init];
  143. RCNPersonalization *personalization =
  144. [[RCNPersonalization alloc] initWithAnalytics:analytics];
  145. [self addListener:^(NSString *key, NSDictionary *config) {
  146. [personalization logArmActive:key config:config];
  147. }];
  148. }
  149. }
  150. return self;
  151. }
  152. // Initialize with default config settings.
  153. - (void)setDefaultConfigSettings {
  154. // Set the default config settings.
  155. self->_settings.fetchTimeout = RCNHTTPDefaultConnectionTimeout;
  156. self->_settings.minimumFetchInterval = RCNDefaultMinimumFetchInterval;
  157. }
  158. - (void)ensureInitializedWithCompletionHandler:
  159. (nonnull FIRRemoteConfigInitializationCompletion)completionHandler {
  160. __weak FIRRemoteConfig *weakSelf = self;
  161. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  162. FIRRemoteConfig *strongSelf = weakSelf;
  163. if (!strongSelf) {
  164. return;
  165. }
  166. BOOL initializationSuccess = [self->_configContent initializationSuccessful];
  167. NSError *error = nil;
  168. if (!initializationSuccess) {
  169. error = [[NSError alloc]
  170. initWithDomain:FIRRemoteConfigErrorDomain
  171. code:FIRRemoteConfigErrorInternalError
  172. userInfo:@{NSLocalizedDescriptionKey : @"Timed out waiting for database load."}];
  173. }
  174. completionHandler(error);
  175. });
  176. }
  177. /// Adds a listener that will be called whenever one of the get methods is called.
  178. /// @param listener Function that takes in the parameter key and the config.
  179. - (void)addListener:(nonnull FIRRemoteConfigListener)listener {
  180. @synchronized(_listeners) {
  181. [_listeners addObject:listener];
  182. }
  183. }
  184. - (void)callListeners:(NSString *)key config:(NSDictionary *)config {
  185. @synchronized(_listeners) {
  186. for (FIRRemoteConfigListener listener in _listeners) {
  187. dispatch_async(_queue, ^{
  188. listener(key, config);
  189. });
  190. }
  191. }
  192. }
  193. #pragma mark - fetch
  194. - (void)fetchWithCompletionHandler:(FIRRemoteConfigFetchCompletion)completionHandler {
  195. dispatch_async(_queue, ^{
  196. [self fetchWithExpirationDuration:self->_settings.minimumFetchInterval
  197. completionHandler:completionHandler];
  198. });
  199. }
  200. - (void)fetchWithExpirationDuration:(NSTimeInterval)expirationDuration
  201. completionHandler:(FIRRemoteConfigFetchCompletion)completionHandler {
  202. FIRRemoteConfigFetchCompletion completionHandlerCopy = nil;
  203. if (completionHandler) {
  204. completionHandlerCopy = [completionHandler copy];
  205. }
  206. [_configFetch fetchConfigWithExpirationDuration:expirationDuration
  207. completionHandler:completionHandlerCopy];
  208. }
  209. #pragma mark - fetchAndActivate
  210. - (void)fetchAndActivateWithCompletionHandler:
  211. (FIRRemoteConfigFetchAndActivateCompletion)completionHandler {
  212. __weak FIRRemoteConfig *weakSelf = self;
  213. FIRRemoteConfigFetchCompletion fetchCompletion = ^(FIRRemoteConfigFetchStatus fetchStatus,
  214. NSError *fetchError) {
  215. FIRRemoteConfig *strongSelf = weakSelf;
  216. if (!strongSelf) {
  217. return;
  218. }
  219. // Fetch completed. We are being called on the main queue.
  220. // If fetch is successful, try to activate the fetched config
  221. if (fetchStatus == FIRRemoteConfigFetchStatusSuccess && !fetchError) {
  222. [strongSelf
  223. activateFromFetchAndActivate:true
  224. withCompletion:^(BOOL changed, NSError *_Nullable activateError) {
  225. if (completionHandler) {
  226. FIRRemoteConfigFetchAndActivateStatus status =
  227. activateError
  228. ? FIRRemoteConfigFetchAndActivateStatusSuccessUsingPreFetchedData
  229. : FIRRemoteConfigFetchAndActivateStatusSuccessFetchedFromRemote;
  230. dispatch_async(dispatch_get_main_queue(), ^{
  231. completionHandler(status, nil);
  232. });
  233. }
  234. }];
  235. } else if (completionHandler) {
  236. FIRRemoteConfigFetchAndActivateStatus status =
  237. fetchStatus == FIRRemoteConfigFetchStatusSuccess
  238. ? FIRRemoteConfigFetchAndActivateStatusSuccessUsingPreFetchedData
  239. : FIRRemoteConfigFetchAndActivateStatusError;
  240. dispatch_async(dispatch_get_main_queue(), ^{
  241. completionHandler(status, fetchError);
  242. });
  243. }
  244. };
  245. [self fetchWithCompletionHandler:fetchCompletion];
  246. }
  247. #pragma mark - apply
  248. typedef void (^FIRRemoteConfigActivateChangeCompletion)(BOOL changed, NSError *_Nullable error);
  249. - (void)activateWithCompletion:(FIRRemoteConfigActivateChangeCompletion)completion {
  250. [self activateFromFetchAndActivate:false withCompletion:completion];
  251. }
  252. - (void)activateFromFetchAndActivate:(BOOL)isFetchAndActivate
  253. withCompletion:(FIRRemoteConfigActivateChangeCompletion)completion {
  254. __weak FIRRemoteConfig *weakSelf = self;
  255. void (^applyBlock)(void) = ^(void) {
  256. FIRRemoteConfig *strongSelf = weakSelf;
  257. if (!strongSelf) {
  258. NSError *error = [NSError errorWithDomain:FIRRemoteConfigErrorDomain
  259. code:FIRRemoteConfigErrorInternalError
  260. userInfo:@{@"ActivationFailureReason" : @"Internal Error."}];
  261. if (completion) {
  262. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  263. completion(NO, error);
  264. });
  265. }
  266. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000068", @"Internal error activating config.");
  267. return;
  268. }
  269. // Check if the last fetched config has already been activated. Fetches with no data change are
  270. // ignored.
  271. if (strongSelf->_settings.lastETagUpdateTime == 0 ||
  272. strongSelf->_settings.lastETagUpdateTime <= strongSelf->_settings.lastApplyTimeInterval) {
  273. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000069",
  274. @"Most recently fetched config is already activated.");
  275. if (completion) {
  276. NSError *error =
  277. isFetchAndActivate
  278. ? [NSError errorWithDomain:FIRRemoteConfigErrorDomain
  279. code:FIRRemoteConfigErrorInternalError
  280. userInfo:@{
  281. @"ActivationFailureReason" :
  282. @"Most recently fetched config already activated"
  283. }]
  284. : nil;
  285. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  286. completion(NO, error);
  287. });
  288. }
  289. return;
  290. }
  291. [strongSelf->_configContent copyFromDictionary:self->_configContent.fetchedConfig
  292. toSource:RCNDBSourceActive
  293. forNamespace:self->_FIRNamespace];
  294. strongSelf->_settings.lastApplyTimeInterval = [[NSDate date] timeIntervalSince1970];
  295. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000069", @"Config activated.");
  296. [strongSelf->_configContent activatePersonalization];
  297. [strongSelf->_configExperiment updateExperimentsWithHandler:^(NSError *_Nullable error) {
  298. if (completion) {
  299. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  300. completion(YES, nil);
  301. });
  302. }
  303. }];
  304. };
  305. dispatch_async(_queue, applyBlock);
  306. }
  307. #pragma mark - helpers
  308. - (NSString *)fullyQualifiedNamespace:(NSString *)namespace {
  309. // If this is already a fully qualified namespace, return.
  310. if ([namespace rangeOfString:@":"].location != NSNotFound) {
  311. return namespace;
  312. }
  313. NSString *fullyQualifiedNamespace = [NSString stringWithFormat:@"%@:%@", namespace, _appName];
  314. return fullyQualifiedNamespace;
  315. }
  316. #pragma mark - Get Config Result
  317. - (FIRRemoteConfigValue *)objectForKeyedSubscript:(NSString *)key {
  318. return [self configValueForKey:key];
  319. }
  320. - (FIRRemoteConfigValue *)configValueForKey:(NSString *)key {
  321. if (!key) {
  322. return [[FIRRemoteConfigValue alloc] initWithData:[NSData data]
  323. source:FIRRemoteConfigSourceStatic];
  324. }
  325. NSString *FQNamespace = [self fullyQualifiedNamespace:_FIRNamespace];
  326. __block FIRRemoteConfigValue *value;
  327. dispatch_sync(_queue, ^{
  328. value = self->_configContent.activeConfig[FQNamespace][key];
  329. if (value) {
  330. if (value.source != FIRRemoteConfigSourceRemote) {
  331. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000001",
  332. @"Key %@ should come from source:%zd instead coming from source: %zd.", key,
  333. (long)FIRRemoteConfigSourceRemote, (long)value.source);
  334. }
  335. [self callListeners:key
  336. config:[self->_configContent getConfigAndMetadataForNamespace:FQNamespace]];
  337. return;
  338. }
  339. value = self->_configContent.defaultConfig[FQNamespace][key];
  340. if (value) {
  341. return;
  342. }
  343. value = [[FIRRemoteConfigValue alloc] initWithData:[NSData data]
  344. source:FIRRemoteConfigSourceStatic];
  345. });
  346. return value;
  347. }
  348. - (FIRRemoteConfigValue *)configValueForKey:(NSString *)key source:(FIRRemoteConfigSource)source {
  349. if (!key) {
  350. return [[FIRRemoteConfigValue alloc] initWithData:[NSData data]
  351. source:FIRRemoteConfigSourceStatic];
  352. }
  353. NSString *FQNamespace = [self fullyQualifiedNamespace:_FIRNamespace];
  354. __block FIRRemoteConfigValue *value;
  355. dispatch_sync(_queue, ^{
  356. if (source == FIRRemoteConfigSourceRemote) {
  357. value = self->_configContent.activeConfig[FQNamespace][key];
  358. } else if (source == FIRRemoteConfigSourceDefault) {
  359. value = self->_configContent.defaultConfig[FQNamespace][key];
  360. } else {
  361. value = [[FIRRemoteConfigValue alloc] initWithData:[NSData data]
  362. source:FIRRemoteConfigSourceStatic];
  363. }
  364. });
  365. return value;
  366. }
  367. - (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state
  368. objects:(id __unsafe_unretained[])stackbuf
  369. count:(NSUInteger)len {
  370. __block NSUInteger localValue;
  371. dispatch_sync(_queue, ^{
  372. localValue =
  373. [self->_configContent.activeConfig[self->_FIRNamespace] countByEnumeratingWithState:state
  374. objects:stackbuf
  375. count:len];
  376. });
  377. return localValue;
  378. }
  379. #pragma mark - Properties
  380. /// Last fetch completion time.
  381. - (NSDate *)lastFetchTime {
  382. __block NSDate *fetchTime;
  383. dispatch_sync(_queue, ^{
  384. NSTimeInterval lastFetchTime = self->_settings.lastFetchTimeInterval;
  385. fetchTime = [NSDate dateWithTimeIntervalSince1970:lastFetchTime];
  386. });
  387. return fetchTime;
  388. }
  389. - (FIRRemoteConfigFetchStatus)lastFetchStatus {
  390. __block FIRRemoteConfigFetchStatus currentStatus;
  391. dispatch_sync(_queue, ^{
  392. currentStatus = self->_settings.lastFetchStatus;
  393. });
  394. return currentStatus;
  395. }
  396. - (NSArray *)allKeysFromSource:(FIRRemoteConfigSource)source {
  397. __block NSArray *keys = [[NSArray alloc] init];
  398. dispatch_sync(_queue, ^{
  399. NSString *FQNamespace = [self fullyQualifiedNamespace:self->_FIRNamespace];
  400. switch (source) {
  401. case FIRRemoteConfigSourceDefault:
  402. if (self->_configContent.defaultConfig[FQNamespace]) {
  403. keys = [[self->_configContent.defaultConfig[FQNamespace] allKeys] copy];
  404. }
  405. break;
  406. case FIRRemoteConfigSourceRemote:
  407. if (self->_configContent.activeConfig[FQNamespace]) {
  408. keys = [[self->_configContent.activeConfig[FQNamespace] allKeys] copy];
  409. }
  410. break;
  411. default:
  412. break;
  413. }
  414. });
  415. return keys;
  416. }
  417. - (nonnull NSSet *)keysWithPrefix:(nullable NSString *)prefix {
  418. __block NSMutableSet *keys = [[NSMutableSet alloc] init];
  419. dispatch_sync(_queue, ^{
  420. NSString *FQNamespace = [self fullyQualifiedNamespace:self->_FIRNamespace];
  421. if (self->_configContent.activeConfig[FQNamespace]) {
  422. NSArray *allKeys = [self->_configContent.activeConfig[FQNamespace] allKeys];
  423. if (!prefix.length) {
  424. keys = [NSMutableSet setWithArray:allKeys];
  425. } else {
  426. for (NSString *key in allKeys) {
  427. if ([key hasPrefix:prefix]) {
  428. [keys addObject:key];
  429. }
  430. }
  431. }
  432. }
  433. });
  434. return [keys copy];
  435. }
  436. #pragma mark - Defaults
  437. - (void)setDefaults:(NSDictionary<NSString *, NSObject *> *)defaultConfig {
  438. NSString *FQNamespace = [self fullyQualifiedNamespace:_FIRNamespace];
  439. NSDictionary *defaultConfigCopy = [[NSDictionary alloc] init];
  440. if (defaultConfig) {
  441. defaultConfigCopy = [defaultConfig copy];
  442. }
  443. void (^setDefaultsBlock)(void) = ^(void) {
  444. NSDictionary *namespaceToDefaults = @{FQNamespace : defaultConfigCopy};
  445. [self->_configContent copyFromDictionary:namespaceToDefaults
  446. toSource:RCNDBSourceDefault
  447. forNamespace:FQNamespace];
  448. self->_settings.lastSetDefaultsTimeInterval = [[NSDate date] timeIntervalSince1970];
  449. };
  450. dispatch_async(_queue, setDefaultsBlock);
  451. }
  452. - (FIRRemoteConfigValue *)defaultValueForKey:(NSString *)key {
  453. NSString *FQNamespace = [self fullyQualifiedNamespace:_FIRNamespace];
  454. __block FIRRemoteConfigValue *value;
  455. dispatch_sync(_queue, ^{
  456. NSDictionary *defaultConfig = self->_configContent.defaultConfig;
  457. value = defaultConfig[FQNamespace][key];
  458. if (value) {
  459. if (value.source != FIRRemoteConfigSourceDefault) {
  460. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000002",
  461. @"Key %@ should come from source:%zd instead coming from source: %zd", key,
  462. (long)FIRRemoteConfigSourceDefault, (long)value.source);
  463. }
  464. }
  465. });
  466. return value;
  467. }
  468. - (void)setDefaultsFromPlistFileName:(nullable NSString *)fileName {
  469. if (!fileName || fileName.length == 0) {
  470. FIRLogWarning(kFIRLoggerRemoteConfig, @"I-RCN000037",
  471. @"The plist file '%@' could not be found by Remote Config.", fileName);
  472. return;
  473. }
  474. NSArray *bundles = @[ [NSBundle mainBundle], [NSBundle bundleForClass:[self class]] ];
  475. for (NSBundle *bundle in bundles) {
  476. NSString *plistFile = [bundle pathForResource:fileName ofType:@"plist"];
  477. // Use the first one we find.
  478. if (plistFile) {
  479. NSDictionary *defaultConfig = [[NSDictionary alloc] initWithContentsOfFile:plistFile];
  480. if (defaultConfig) {
  481. [self setDefaults:defaultConfig];
  482. }
  483. return;
  484. }
  485. }
  486. FIRLogWarning(kFIRLoggerRemoteConfig, @"I-RCN000037",
  487. @"The plist file '%@' could not be found by Remote Config.", fileName);
  488. }
  489. #pragma mark - custom variables
  490. - (FIRRemoteConfigSettings *)configSettings {
  491. __block NSTimeInterval minimumFetchInterval = RCNDefaultMinimumFetchInterval;
  492. __block NSTimeInterval fetchTimeout = RCNHTTPDefaultConnectionTimeout;
  493. dispatch_sync(_queue, ^{
  494. minimumFetchInterval = self->_settings.minimumFetchInterval;
  495. fetchTimeout = self->_settings.fetchTimeout;
  496. });
  497. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000066",
  498. @"Successfully read configSettings. Minimum Fetch Interval:%f, "
  499. @"Fetch timeout: %f",
  500. minimumFetchInterval, fetchTimeout);
  501. FIRRemoteConfigSettings *settings = [[FIRRemoteConfigSettings alloc] init];
  502. settings.minimumFetchInterval = minimumFetchInterval;
  503. settings.fetchTimeout = fetchTimeout;
  504. /// The NSURLSession needs to be recreated whenever the fetch timeout may be updated.
  505. [_configFetch recreateNetworkSession];
  506. return settings;
  507. }
  508. - (void)setConfigSettings:(FIRRemoteConfigSettings *)configSettings {
  509. void (^setConfigSettingsBlock)(void) = ^(void) {
  510. if (!configSettings) {
  511. return;
  512. }
  513. self->_settings.minimumFetchInterval = configSettings.minimumFetchInterval;
  514. self->_settings.fetchTimeout = configSettings.fetchTimeout;
  515. /// The NSURLSession needs to be recreated whenever the fetch timeout may be updated.
  516. [self->_configFetch recreateNetworkSession];
  517. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000067",
  518. @"Successfully set configSettings. Minimum Fetch Interval:%f, "
  519. @"Fetch timeout:%f",
  520. configSettings.minimumFetchInterval, configSettings.fetchTimeout);
  521. };
  522. dispatch_async(_queue, setConfigSettingsBlock);
  523. }
  524. @end