FIRRemoteConfig.m 25 KB

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