FIRRemoteConfig.m 25 KB

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