FIRRemoteConfig.m 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  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 FIRRemoteConfigUpdateErrorDomain = @"com.google.remoteconfig.update.ErrorDomain";
  36. /// Remote Config Error Info End Time Seconds;
  37. NSString *const FIRRemoteConfigThrottledEndTimeInSecondsKey = @"error_throttled_end_time_seconds";
  38. /// Minimum required time interval between fetch requests made to the backend.
  39. static NSString *const kRemoteConfigMinimumFetchIntervalKey = @"_rcn_minimum_fetch_interval";
  40. /// Timeout value for waiting on a fetch response.
  41. static NSString *const kRemoteConfigFetchTimeoutKey = @"_rcn_fetch_timeout";
  42. /// Notification when config is successfully activated
  43. const NSNotificationName FIRRemoteConfigActivateNotification =
  44. @"FIRRemoteConfigActivateNotification";
  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. // New config has been activated at this point
  295. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000069", @"Config activated.");
  296. [strongSelf->_configContent activatePersonalization];
  297. // Update experiments only for 3p namespace
  298. NSString *namespace = [strongSelf->_FIRNamespace
  299. substringToIndex:[strongSelf->_FIRNamespace rangeOfString:@":"].location];
  300. if ([namespace isEqualToString:FIRNamespaceGoogleMobilePlatform]) {
  301. dispatch_async(dispatch_get_main_queue(), ^{
  302. [self notifyConfigHasActivated];
  303. });
  304. [strongSelf->_configExperiment updateExperimentsWithHandler:^(NSError *_Nullable error) {
  305. if (completion) {
  306. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  307. completion(YES, nil);
  308. });
  309. }
  310. }];
  311. } else {
  312. if (completion) {
  313. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  314. completion(YES, nil);
  315. });
  316. }
  317. }
  318. };
  319. dispatch_async(_queue, applyBlock);
  320. }
  321. - (void)notifyConfigHasActivated {
  322. // Need a valid google app name.
  323. if (!_appName) {
  324. return;
  325. }
  326. // The Remote Config Swift SDK will be listening for this notification so it can tell SwiftUI to
  327. // update the UI.
  328. NSDictionary *appInfoDict = @{kFIRAppNameKey : _appName};
  329. [[NSNotificationCenter defaultCenter] postNotificationName:FIRRemoteConfigActivateNotification
  330. object:self
  331. userInfo:appInfoDict];
  332. }
  333. #pragma mark - helpers
  334. - (NSString *)fullyQualifiedNamespace:(NSString *)namespace {
  335. // If this is already a fully qualified namespace, return.
  336. if ([namespace rangeOfString:@":"].location != NSNotFound) {
  337. return namespace;
  338. }
  339. NSString *fullyQualifiedNamespace = [NSString stringWithFormat:@"%@:%@", namespace, _appName];
  340. return fullyQualifiedNamespace;
  341. }
  342. #pragma mark - Get Config Result
  343. - (FIRRemoteConfigValue *)objectForKeyedSubscript:(NSString *)key {
  344. return [self configValueForKey:key];
  345. }
  346. - (FIRRemoteConfigValue *)configValueForKey:(NSString *)key {
  347. if (!key) {
  348. return [[FIRRemoteConfigValue alloc] initWithData:[NSData data]
  349. source:FIRRemoteConfigSourceStatic];
  350. }
  351. NSString *FQNamespace = [self fullyQualifiedNamespace:_FIRNamespace];
  352. __block FIRRemoteConfigValue *value;
  353. dispatch_sync(_queue, ^{
  354. value = self->_configContent.activeConfig[FQNamespace][key];
  355. if (value) {
  356. if (value.source != FIRRemoteConfigSourceRemote) {
  357. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000001",
  358. @"Key %@ should come from source:%zd instead coming from source: %zd.", key,
  359. (long)FIRRemoteConfigSourceRemote, (long)value.source);
  360. }
  361. [self callListeners:key
  362. config:[self->_configContent getConfigAndMetadataForNamespace:FQNamespace]];
  363. return;
  364. }
  365. value = self->_configContent.defaultConfig[FQNamespace][key];
  366. if (value) {
  367. return;
  368. }
  369. value = [[FIRRemoteConfigValue alloc] initWithData:[NSData data]
  370. source:FIRRemoteConfigSourceStatic];
  371. });
  372. return value;
  373. }
  374. - (FIRRemoteConfigValue *)configValueForKey:(NSString *)key source:(FIRRemoteConfigSource)source {
  375. if (!key) {
  376. return [[FIRRemoteConfigValue alloc] initWithData:[NSData data]
  377. source:FIRRemoteConfigSourceStatic];
  378. }
  379. NSString *FQNamespace = [self fullyQualifiedNamespace:_FIRNamespace];
  380. __block FIRRemoteConfigValue *value;
  381. dispatch_sync(_queue, ^{
  382. if (source == FIRRemoteConfigSourceRemote) {
  383. value = self->_configContent.activeConfig[FQNamespace][key];
  384. } else if (source == FIRRemoteConfigSourceDefault) {
  385. value = self->_configContent.defaultConfig[FQNamespace][key];
  386. } else {
  387. value = [[FIRRemoteConfigValue alloc] initWithData:[NSData data]
  388. source:FIRRemoteConfigSourceStatic];
  389. }
  390. });
  391. return value;
  392. }
  393. - (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state
  394. objects:(id __unsafe_unretained[])stackbuf
  395. count:(NSUInteger)len {
  396. __block NSUInteger localValue;
  397. dispatch_sync(_queue, ^{
  398. localValue =
  399. [self->_configContent.activeConfig[self->_FIRNamespace] countByEnumeratingWithState:state
  400. objects:stackbuf
  401. count:len];
  402. });
  403. return localValue;
  404. }
  405. #pragma mark - Properties
  406. /// Last fetch completion time.
  407. - (NSDate *)lastFetchTime {
  408. __block NSDate *fetchTime;
  409. dispatch_sync(_queue, ^{
  410. NSTimeInterval lastFetchTime = self->_settings.lastFetchTimeInterval;
  411. fetchTime = [NSDate dateWithTimeIntervalSince1970:lastFetchTime];
  412. });
  413. return fetchTime;
  414. }
  415. - (FIRRemoteConfigFetchStatus)lastFetchStatus {
  416. __block FIRRemoteConfigFetchStatus currentStatus;
  417. dispatch_sync(_queue, ^{
  418. currentStatus = self->_settings.lastFetchStatus;
  419. });
  420. return currentStatus;
  421. }
  422. - (NSArray *)allKeysFromSource:(FIRRemoteConfigSource)source {
  423. __block NSArray *keys = [[NSArray alloc] init];
  424. dispatch_sync(_queue, ^{
  425. NSString *FQNamespace = [self fullyQualifiedNamespace:self->_FIRNamespace];
  426. switch (source) {
  427. case FIRRemoteConfigSourceDefault:
  428. if (self->_configContent.defaultConfig[FQNamespace]) {
  429. keys = [[self->_configContent.defaultConfig[FQNamespace] allKeys] copy];
  430. }
  431. break;
  432. case FIRRemoteConfigSourceRemote:
  433. if (self->_configContent.activeConfig[FQNamespace]) {
  434. keys = [[self->_configContent.activeConfig[FQNamespace] allKeys] copy];
  435. }
  436. break;
  437. default:
  438. break;
  439. }
  440. });
  441. return keys;
  442. }
  443. - (nonnull NSSet *)keysWithPrefix:(nullable NSString *)prefix {
  444. __block NSMutableSet *keys = [[NSMutableSet alloc] init];
  445. dispatch_sync(_queue, ^{
  446. NSString *FQNamespace = [self fullyQualifiedNamespace:self->_FIRNamespace];
  447. if (self->_configContent.activeConfig[FQNamespace]) {
  448. NSArray *allKeys = [self->_configContent.activeConfig[FQNamespace] allKeys];
  449. if (!prefix.length) {
  450. keys = [NSMutableSet setWithArray:allKeys];
  451. } else {
  452. for (NSString *key in allKeys) {
  453. if ([key hasPrefix:prefix]) {
  454. [keys addObject:key];
  455. }
  456. }
  457. }
  458. }
  459. });
  460. return [keys copy];
  461. }
  462. #pragma mark - Defaults
  463. - (void)setDefaults:(NSDictionary<NSString *, NSObject *> *)defaultConfig {
  464. NSString *FQNamespace = [self fullyQualifiedNamespace:_FIRNamespace];
  465. NSDictionary *defaultConfigCopy = [[NSDictionary alloc] init];
  466. if (defaultConfig) {
  467. defaultConfigCopy = [defaultConfig copy];
  468. }
  469. void (^setDefaultsBlock)(void) = ^(void) {
  470. NSDictionary *namespaceToDefaults = @{FQNamespace : defaultConfigCopy};
  471. [self->_configContent copyFromDictionary:namespaceToDefaults
  472. toSource:RCNDBSourceDefault
  473. forNamespace:FQNamespace];
  474. self->_settings.lastSetDefaultsTimeInterval = [[NSDate date] timeIntervalSince1970];
  475. };
  476. dispatch_async(_queue, setDefaultsBlock);
  477. }
  478. - (FIRRemoteConfigValue *)defaultValueForKey:(NSString *)key {
  479. NSString *FQNamespace = [self fullyQualifiedNamespace:_FIRNamespace];
  480. __block FIRRemoteConfigValue *value;
  481. dispatch_sync(_queue, ^{
  482. NSDictionary *defaultConfig = self->_configContent.defaultConfig;
  483. value = defaultConfig[FQNamespace][key];
  484. if (value) {
  485. if (value.source != FIRRemoteConfigSourceDefault) {
  486. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000002",
  487. @"Key %@ should come from source:%zd instead coming from source: %zd", key,
  488. (long)FIRRemoteConfigSourceDefault, (long)value.source);
  489. }
  490. }
  491. });
  492. return value;
  493. }
  494. - (void)setDefaultsFromPlistFileName:(nullable NSString *)fileName {
  495. if (!fileName || fileName.length == 0) {
  496. FIRLogWarning(kFIRLoggerRemoteConfig, @"I-RCN000037",
  497. @"The plist file '%@' could not be found by Remote Config.", fileName);
  498. return;
  499. }
  500. NSArray *bundles = @[ [NSBundle mainBundle], [NSBundle bundleForClass:[self class]] ];
  501. for (NSBundle *bundle in bundles) {
  502. NSString *plistFile = [bundle pathForResource:fileName ofType:@"plist"];
  503. // Use the first one we find.
  504. if (plistFile) {
  505. NSDictionary *defaultConfig = [[NSDictionary alloc] initWithContentsOfFile:plistFile];
  506. if (defaultConfig) {
  507. [self setDefaults:defaultConfig];
  508. }
  509. return;
  510. }
  511. }
  512. FIRLogWarning(kFIRLoggerRemoteConfig, @"I-RCN000037",
  513. @"The plist file '%@' could not be found by Remote Config.", fileName);
  514. }
  515. #pragma mark - custom variables
  516. - (FIRRemoteConfigSettings *)configSettings {
  517. __block NSTimeInterval minimumFetchInterval = RCNDefaultMinimumFetchInterval;
  518. __block NSTimeInterval fetchTimeout = RCNHTTPDefaultConnectionTimeout;
  519. dispatch_sync(_queue, ^{
  520. minimumFetchInterval = self->_settings.minimumFetchInterval;
  521. fetchTimeout = self->_settings.fetchTimeout;
  522. });
  523. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000066",
  524. @"Successfully read configSettings. Minimum Fetch Interval:%f, "
  525. @"Fetch timeout: %f",
  526. minimumFetchInterval, fetchTimeout);
  527. FIRRemoteConfigSettings *settings = [[FIRRemoteConfigSettings alloc] init];
  528. settings.minimumFetchInterval = minimumFetchInterval;
  529. settings.fetchTimeout = fetchTimeout;
  530. /// The NSURLSession needs to be recreated whenever the fetch timeout may be updated.
  531. [_configFetch recreateNetworkSession];
  532. return settings;
  533. }
  534. - (void)setConfigSettings:(FIRRemoteConfigSettings *)configSettings {
  535. void (^setConfigSettingsBlock)(void) = ^(void) {
  536. if (!configSettings) {
  537. return;
  538. }
  539. self->_settings.minimumFetchInterval = configSettings.minimumFetchInterval;
  540. self->_settings.fetchTimeout = configSettings.fetchTimeout;
  541. /// The NSURLSession needs to be recreated whenever the fetch timeout may be updated.
  542. [self->_configFetch recreateNetworkSession];
  543. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000067",
  544. @"Successfully set configSettings. Minimum Fetch Interval:%f, "
  545. @"Fetch timeout:%f",
  546. configSettings.minimumFetchInterval, configSettings.fetchTimeout);
  547. };
  548. dispatch_async(_queue, setConfigSettingsBlock);
  549. }
  550. #pragma mark - Realtime
  551. - (FIRConfigUpdateListenerRegistration *)addOnConfigUpdateListener:
  552. (void (^_Nonnull)(FIRRemoteConfigUpdate *update, NSError *_Nullable error))listener {
  553. return [self->_configRealtime addConfigUpdateListener:listener];
  554. }
  555. @end