FIRRemoteConfig.m 25 KB

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