FIRRemoteConfig.m 24 KB

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