FIRRemoteConfig.m 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  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. [self fetchWithExpirationDuration:_settings.minimumFetchInterval
  191. completionHandler:completionHandler];
  192. }
  193. - (void)fetchWithExpirationDuration:(NSTimeInterval)expirationDuration
  194. completionHandler:(FIRRemoteConfigFetchCompletion)completionHandler {
  195. FIRRemoteConfigFetchCompletion completionHandlerCopy = nil;
  196. if (completionHandler) {
  197. completionHandlerCopy = [completionHandler copy];
  198. }
  199. [_configFetch fetchAllConfigsWithExpirationDuration:expirationDuration
  200. completionHandler:completionHandlerCopy];
  201. }
  202. #pragma mark - fetchAndActivate
  203. - (void)fetchAndActivateWithCompletionHandler:
  204. (FIRRemoteConfigFetchAndActivateCompletion)completionHandler {
  205. __weak FIRRemoteConfig *weakSelf = self;
  206. FIRRemoteConfigFetchCompletion fetchCompletion =
  207. ^(FIRRemoteConfigFetchStatus fetchStatus, NSError *error) {
  208. FIRRemoteConfig *strongSelf = weakSelf;
  209. if (!strongSelf) {
  210. return;
  211. }
  212. // Fetch completed. We are being called on the main queue.
  213. // If fetch is successful, try to activate the fetched config
  214. bool didActivate = false;
  215. if (fetchStatus == FIRRemoteConfigFetchStatusSuccess && !error) {
  216. didActivate = [strongSelf activateFetched];
  217. }
  218. if (completionHandler) {
  219. FIRRemoteConfigFetchAndActivateStatus status = FIRRemoteConfigFetchAndActivateStatusError;
  220. if (fetchStatus == FIRRemoteConfigFetchStatusSuccess) {
  221. status = didActivate ? FIRRemoteConfigFetchAndActivateStatusSuccessFetchedFromRemote
  222. : FIRRemoteConfigFetchAndActivateStatusSuccessUsingPreFetchedData;
  223. } else {
  224. status = FIRRemoteConfigFetchAndActivateStatusError;
  225. }
  226. // Pass along the fetch error e.g. throttled.
  227. completionHandler(status, error);
  228. }
  229. };
  230. [self fetchWithCompletionHandler:fetchCompletion];
  231. }
  232. #pragma mark - apply
  233. - (BOOL)activateFetched {
  234. // TODO: We block on the async activate to complete. This method is deprecated and needs
  235. // to be removed at the next possible breaking change.
  236. __block dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
  237. __block BOOL didActivate = NO;
  238. [self activateWithCompletionHandler:^(NSError *_Nullable error) {
  239. didActivate = error ? false : true;
  240. dispatch_semaphore_signal(semaphore);
  241. }];
  242. dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
  243. return didActivate;
  244. }
  245. - (void)activateWithCompletionHandler:(FIRRemoteConfigActivateCompletion)completionHandler {
  246. __weak FIRRemoteConfig *weakSelf = self;
  247. void (^applyBlock)(void) = ^(void) {
  248. FIRRemoteConfig *strongSelf = weakSelf;
  249. if (!strongSelf) {
  250. NSError *error = [NSError errorWithDomain:FIRRemoteConfigErrorDomain
  251. code:FIRRemoteConfigErrorInternalError
  252. userInfo:@{@"ActivationFailureReason" : @"Internal Error."}];
  253. if (completionHandler) {
  254. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  255. completionHandler(error);
  256. });
  257. }
  258. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000068", @"Internal error activating config.");
  259. return;
  260. }
  261. // If Fetched Config is no fresher than Active Config.
  262. if (strongSelf->_settings.lastFetchTimeInterval == 0 ||
  263. strongSelf->_settings.lastFetchTimeInterval <=
  264. strongSelf->_settings.lastApplyTimeInterval) {
  265. FIRLogWarning(kFIRLoggerRemoteConfig, @"I-RCN000069",
  266. @"Most recently fetched config is already activated.");
  267. NSError *error = [NSError
  268. errorWithDomain:FIRRemoteConfigErrorDomain
  269. code:FIRRemoteConfigErrorInternalError
  270. userInfo:@{
  271. @"ActivationFailureReason" : @"Most recently fetched config is already activated"
  272. }];
  273. if (completionHandler) {
  274. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  275. completionHandler(error);
  276. });
  277. }
  278. return;
  279. }
  280. [strongSelf->_configContent copyFromDictionary:self->_configContent.fetchedConfig
  281. toSource:RCNDBSourceActive
  282. forNamespace:self->_FIRNamespace];
  283. [strongSelf updateExperiments];
  284. strongSelf->_settings.lastApplyTimeInterval = [[NSDate date] timeIntervalSince1970];
  285. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000069", @"Config activated.");
  286. if (completionHandler) {
  287. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  288. completionHandler(nil);
  289. });
  290. }
  291. };
  292. dispatch_async(_queue, applyBlock);
  293. }
  294. - (void)updateExperiments {
  295. [self->_configExperiment updateExperiments];
  296. }
  297. #pragma mark - helpers
  298. - (NSString *)fullyQualifiedNamespace:(NSString *)namespace {
  299. // If this is already a fully qualified namespace, return.
  300. if ([namespace rangeOfString:@":"].location != NSNotFound) {
  301. return namespace;
  302. }
  303. NSString *fullyQualifiedNamespace = [NSString stringWithFormat:@"%@:%@", namespace, _appName];
  304. return fullyQualifiedNamespace;
  305. }
  306. #pragma mark - Get Config Result
  307. - (FIRRemoteConfigValue *)objectForKeyedSubscript:(NSString *)key {
  308. return [self configValueForKey:key];
  309. }
  310. - (FIRRemoteConfigValue *)configValueForKey:(NSString *)key {
  311. return [self configValueForKey:key namespace:_FIRNamespace];
  312. }
  313. - (FIRRemoteConfigValue *)configValueForKey:(NSString *)key namespace:(NSString *)aNamespace {
  314. if (!key || !aNamespace) {
  315. return [[FIRRemoteConfigValue alloc] initWithData:[NSData data]
  316. source:FIRRemoteConfigSourceStatic];
  317. }
  318. NSString *FQNamespace = [self fullyQualifiedNamespace:aNamespace];
  319. __block FIRRemoteConfigValue *value;
  320. dispatch_sync(_queue, ^{
  321. value = self->_configContent.activeConfig[FQNamespace][key];
  322. if (value) {
  323. if (value.source != FIRRemoteConfigSourceRemote) {
  324. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000001",
  325. @"Key %@ should come from source:%zd instead coming from source: %zd.", key,
  326. (long)FIRRemoteConfigSourceRemote, (long)value.source);
  327. }
  328. return;
  329. }
  330. value = self->_configContent.defaultConfig[FQNamespace][key];
  331. if (value) {
  332. return;
  333. }
  334. value = [[FIRRemoteConfigValue alloc] initWithData:[NSData data]
  335. source:FIRRemoteConfigSourceStatic];
  336. });
  337. return value;
  338. }
  339. - (FIRRemoteConfigValue *)configValueForKey:(NSString *)key source:(FIRRemoteConfigSource)source {
  340. return [self configValueForKey:key namespace:_FIRNamespace source:source];
  341. }
  342. - (FIRRemoteConfigValue *)configValueForKey:(NSString *)key
  343. namespace:(NSString *)aNamespace
  344. source:(FIRRemoteConfigSource)source {
  345. if (!key || !aNamespace) {
  346. return [[FIRRemoteConfigValue alloc] initWithData:[NSData data]
  347. source:FIRRemoteConfigSourceStatic];
  348. }
  349. NSString *FQNamespace = [self fullyQualifiedNamespace:aNamespace];
  350. __block FIRRemoteConfigValue *value;
  351. dispatch_sync(_queue, ^{
  352. if (source == FIRRemoteConfigSourceRemote) {
  353. value = self->_configContent.activeConfig[FQNamespace][key];
  354. } else if (source == FIRRemoteConfigSourceDefault) {
  355. value = self->_configContent.defaultConfig[FQNamespace][key];
  356. } else {
  357. value = [[FIRRemoteConfigValue alloc] initWithData:[NSData data]
  358. source:FIRRemoteConfigSourceStatic];
  359. }
  360. });
  361. return value;
  362. }
  363. - (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state
  364. objects:(id __unsafe_unretained[])stackbuf
  365. count:(NSUInteger)len {
  366. __block NSUInteger localValue;
  367. dispatch_sync(_queue, ^{
  368. localValue =
  369. [self->_configContent.activeConfig[self->_FIRNamespace] countByEnumeratingWithState:state
  370. objects:stackbuf
  371. count:len];
  372. });
  373. return localValue;
  374. }
  375. #pragma mark - Properties
  376. /// Last fetch completion time.
  377. - (NSDate *)lastFetchTime {
  378. __block NSDate *fetchTime;
  379. dispatch_sync(_queue, ^{
  380. NSTimeInterval lastFetchTime = self->_settings.lastFetchTimeInterval;
  381. fetchTime = [NSDate dateWithTimeIntervalSince1970:lastFetchTime];
  382. });
  383. return fetchTime;
  384. }
  385. - (FIRRemoteConfigFetchStatus)lastFetchStatus {
  386. __block FIRRemoteConfigFetchStatus currentStatus;
  387. dispatch_sync(_queue, ^{
  388. currentStatus = self->_settings.lastFetchStatus;
  389. });
  390. return currentStatus;
  391. }
  392. - (NSArray *)allKeysFromSource:(FIRRemoteConfigSource)source {
  393. return [self allKeysFromSource:source namespace:_FIRNamespace];
  394. }
  395. - (NSArray *)allKeysFromSource:(FIRRemoteConfigSource)source namespace:(NSString *)aNamespace {
  396. __block NSArray *keys = [[NSArray alloc] init];
  397. dispatch_sync(_queue, ^{
  398. if (!aNamespace) {
  399. return;
  400. }
  401. NSString *FQNamespace = [self fullyQualifiedNamespace:aNamespace];
  402. switch (source) {
  403. case FIRRemoteConfigSourceDefault:
  404. if (self->_configContent.defaultConfig[FQNamespace]) {
  405. keys = [[self->_configContent.defaultConfig[FQNamespace] allKeys] copy];
  406. }
  407. break;
  408. case FIRRemoteConfigSourceRemote:
  409. if (self->_configContent.activeConfig[FQNamespace]) {
  410. keys = [[self->_configContent.activeConfig[FQNamespace] allKeys] copy];
  411. }
  412. break;
  413. default:
  414. break;
  415. }
  416. });
  417. return keys;
  418. }
  419. - (nonnull NSSet *)keysWithPrefix:(nullable NSString *)prefix {
  420. return [self keysWithPrefix:prefix namespace:_FIRNamespace];
  421. }
  422. - (nonnull NSSet *)keysWithPrefix:(nullable NSString *)prefix
  423. namespace:(nullable NSString *)aNamespace {
  424. __block NSMutableSet *keys = [[NSMutableSet alloc] init];
  425. __block NSString *namespaceToCheck = aNamespace;
  426. dispatch_sync(_queue, ^{
  427. if (!namespaceToCheck.length) {
  428. return;
  429. }
  430. NSString *FQNamespace = [self fullyQualifiedNamespace:namespaceToCheck];
  431. if (self->_configContent.activeConfig[FQNamespace]) {
  432. NSArray *allKeys = [self->_configContent.activeConfig[FQNamespace] allKeys];
  433. if (!prefix.length) {
  434. keys = [NSMutableSet setWithArray:allKeys];
  435. } else {
  436. for (NSString *key in allKeys) {
  437. if ([key hasPrefix:prefix]) {
  438. [keys addObject:key];
  439. }
  440. }
  441. }
  442. }
  443. });
  444. return [keys copy];
  445. }
  446. #pragma mark - Defaults
  447. - (void)setDefaults:(NSDictionary<NSString *, NSObject *> *)defaults {
  448. [self setDefaults:defaults namespace:_FIRNamespace];
  449. }
  450. - (void)setDefaults:(NSDictionary<NSString *, NSObject *> *)defaultConfig
  451. namespace:(NSString *)aNamespace {
  452. if (!aNamespace) {
  453. FIRLogWarning(kFIRLoggerRemoteConfig, @"I-RCN000036", @"The namespace cannot be empty or nil.");
  454. return;
  455. }
  456. NSString *FQNamespace = [self fullyQualifiedNamespace:aNamespace];
  457. NSDictionary *defaultConfigCopy = [[NSDictionary alloc] init];
  458. if (defaultConfig) {
  459. defaultConfigCopy = [defaultConfig copy];
  460. }
  461. void (^setDefaultsBlock)(void) = ^(void) {
  462. NSDictionary *namespaceToDefaults = @{FQNamespace : defaultConfigCopy};
  463. [self->_configContent copyFromDictionary:namespaceToDefaults
  464. toSource:RCNDBSourceDefault
  465. forNamespace:FQNamespace];
  466. self->_settings.lastSetDefaultsTimeInterval = [[NSDate date] timeIntervalSince1970];
  467. };
  468. dispatch_async(_queue, setDefaultsBlock);
  469. }
  470. - (FIRRemoteConfigValue *)defaultValueForKey:(NSString *)key {
  471. return [self defaultValueForKey:key namespace:_FIRNamespace];
  472. }
  473. - (FIRRemoteConfigValue *)defaultValueForKey:(NSString *)key namespace:(NSString *)aNamespace {
  474. if (!key || !aNamespace) {
  475. return nil;
  476. }
  477. NSString *FQNamespace = [self fullyQualifiedNamespace:aNamespace];
  478. __block FIRRemoteConfigValue *value;
  479. dispatch_sync(_queue, ^{
  480. NSDictionary *defaultConfig = self->_configContent.defaultConfig;
  481. value = defaultConfig[FQNamespace][key];
  482. if (value) {
  483. if (value.source != FIRRemoteConfigSourceDefault) {
  484. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000002",
  485. @"Key %@ should come from source:%zd instead coming from source: %zd", key,
  486. (long)FIRRemoteConfigSourceDefault, (long)value.source);
  487. }
  488. }
  489. });
  490. return value;
  491. }
  492. - (void)setDefaultsFromPlistFileName:(nullable NSString *)fileName {
  493. return [self setDefaultsFromPlistFileName:fileName namespace:_FIRNamespace];
  494. }
  495. - (void)setDefaultsFromPlistFileName:(nullable NSString *)fileName
  496. namespace:(nullable NSString *)namespace {
  497. if (!namespace || namespace.length == 0) {
  498. FIRLogWarning(kFIRLoggerRemoteConfig, @"I-RCN000036", @"The namespace cannot be empty or nil.");
  499. return;
  500. }
  501. NSString *FQNamespace = [self fullyQualifiedNamespace:namespace];
  502. if (!fileName || fileName.length == 0) {
  503. FIRLogWarning(kFIRLoggerRemoteConfig, @"I-RCN000037",
  504. @"The plist file '%@' could not be found by Remote Config.", fileName);
  505. return;
  506. }
  507. NSArray *bundles = @[ [NSBundle mainBundle], [NSBundle bundleForClass:[self class]] ];
  508. for (NSBundle *bundle in bundles) {
  509. NSString *plistFile = [bundle pathForResource:fileName ofType:@"plist"];
  510. // Use the first one we find.
  511. if (plistFile) {
  512. NSDictionary *defaultConfig = [[NSDictionary alloc] initWithContentsOfFile:plistFile];
  513. if (defaultConfig) {
  514. [self setDefaults:defaultConfig namespace:FQNamespace];
  515. }
  516. return;
  517. }
  518. }
  519. FIRLogWarning(kFIRLoggerRemoteConfig, @"I-RCN000037",
  520. @"The plist file '%@' could not be found by Remote Config.", fileName);
  521. }
  522. #pragma mark - custom variables
  523. - (FIRRemoteConfigSettings *)configSettings {
  524. __block BOOL developerModeEnabled = NO;
  525. __block NSTimeInterval minimumFetchInterval = RCNDefaultMinimumFetchInterval;
  526. __block NSTimeInterval fetchTimeout = RCNHTTPDefaultConnectionTimeout;
  527. dispatch_sync(_queue, ^{
  528. developerModeEnabled = [self->_settings.customVariables[kRemoteConfigDeveloperKey] boolValue];
  529. minimumFetchInterval = self->_settings.minimumFetchInterval;
  530. fetchTimeout = self->_settings.fetchTimeout;
  531. });
  532. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000066",
  533. @"Successfully read configSettings. Developer Mode: %@, Minimum Fetch Interval:%f, "
  534. @"Fetch timeout: %f",
  535. developerModeEnabled ? @"true" : @"false", minimumFetchInterval, fetchTimeout);
  536. FIRRemoteConfigSettings *settings =
  537. [[FIRRemoteConfigSettings alloc] initWithDeveloperModeEnabled:developerModeEnabled];
  538. settings.minimumFetchInterval = minimumFetchInterval;
  539. settings.fetchTimeout = fetchTimeout;
  540. /// The NSURLSession needs to be recreated whenever the fetch timeout may be updated.
  541. [_configFetch recreateNetworkSession];
  542. return settings;
  543. }
  544. - (void)setConfigSettings:(FIRRemoteConfigSettings *)configSettings {
  545. void (^setConfigSettingsBlock)(void) = ^(void) {
  546. if (!configSettings) {
  547. return;
  548. }
  549. NSDictionary *settingsToSave = @{
  550. kRemoteConfigDeveloperKey : @(configSettings.isDeveloperModeEnabled),
  551. };
  552. self->_settings.customVariables = settingsToSave;
  553. self->_settings.minimumFetchInterval = configSettings.minimumFetchInterval;
  554. self->_settings.fetchTimeout = configSettings.fetchTimeout;
  555. /// The NSURLSession needs to be recreated whenever the fetch timeout may be updated.
  556. [self->_configFetch recreateNetworkSession];
  557. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000067",
  558. @"Successfully set configSettings. Developer Mode: %@, Minimum Fetch Interval:%f, "
  559. @"Fetch timeout:%f",
  560. configSettings.isDeveloperModeEnabled ? @"true" : @"false",
  561. configSettings.minimumFetchInterval, configSettings.fetchTimeout);
  562. };
  563. dispatch_async(_queue, setConfigSettingsBlock);
  564. }
  565. #pragma clang diagnostic push // "-Wdeprecated-declarations"
  566. @end