FIRRemoteConfig.m 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638
  1. /*
  2. * Copyright 2019 Google
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #import <FirebaseRemoteConfig/FIRRemoteConfig.h>
  17. #import <FirebaseABTesting/FIRExperimentController.h>
  18. #import <FirebaseCore/FIRAppInternal.h>
  19. #import <FirebaseCore/FIRComponentContainer.h>
  20. #import <FirebaseCore/FIRLogger.h>
  21. #import <FirebaseCore/FIROptionsInternal.h>
  22. #import "FirebaseRemoteConfig/Sources/FIRRemoteConfigComponent.h"
  23. #import "FirebaseRemoteConfig/Sources/Private/FIRRemoteConfig_Private.h"
  24. #import "FirebaseRemoteConfig/Sources/Private/RCNConfigSettings.h"
  25. #import "FirebaseRemoteConfig/Sources/RCNConfigConstants.h"
  26. #import "FirebaseRemoteConfig/Sources/RCNConfigContent.h"
  27. #import "FirebaseRemoteConfig/Sources/RCNConfigDBManager.h"
  28. #import "FirebaseRemoteConfig/Sources/RCNConfigExperiment.h"
  29. #import "FirebaseRemoteConfig/Sources/RCNConfigFetch.h"
  30. #import "FirebaseRemoteConfig/Sources/RCNConfigValue_Internal.h"
  31. #import "FirebaseRemoteConfig/Sources/RCNDevice.h"
  32. /// Remote Config Error Domain.
  33. /// TODO: Rename according to obj-c style for constants.
  34. NSString *const FIRRemoteConfigErrorDomain = @"com.google.remoteconfig.ErrorDomain";
  35. /// Remote Config Error Info End Time Seconds;
  36. NSString *const FIRRemoteConfigThrottledEndTimeInSecondsKey = @"error_throttled_end_time_seconds";
  37. /// Remote Config Developer Mode Key
  38. static NSString *const kRemoteConfigDeveloperKey = @"_rcn_developer";
  39. /// Minimum required time interval between fetch requests made to the backend.
  40. static NSString *const kRemoteConfigMinimumFetchIntervalKey = @"_rcn_minimum_fetch_interval";
  41. /// Timeout value for waiting on a fetch response.
  42. static NSString *const kRemoteConfigFetchTimeoutKey = @"_rcn_fetch_timeout";
  43. @interface FIRRemoteConfigSettings () {
  44. BOOL _developerModeEnabled;
  45. }
  46. @end
  47. // Implementations depend upon multiple deprecated APIs
  48. #pragma clang diagnostic push
  49. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  50. @implementation FIRRemoteConfigSettings
  51. - (instancetype)initWithDeveloperModeEnabled:(BOOL)developerModeEnabled {
  52. self = [self init];
  53. if (self) {
  54. _developerModeEnabled = developerModeEnabled;
  55. }
  56. return self;
  57. }
  58. - (instancetype)init {
  59. self = [super init];
  60. if (self) {
  61. _developerModeEnabled = NO;
  62. _minimumFetchInterval = RCNDefaultMinimumFetchInterval;
  63. _fetchTimeout = RCNHTTPDefaultConnectionTimeout;
  64. }
  65. return self;
  66. }
  67. - (BOOL)isDeveloperModeEnabled {
  68. return _developerModeEnabled;
  69. }
  70. @end
  71. @implementation FIRRemoteConfig {
  72. /// All the config content.
  73. RCNConfigContent *_configContent;
  74. RCNConfigDBManager *_DBManager;
  75. RCNConfigSettings *_settings;
  76. RCNConfigFetch *_configFetch;
  77. RCNConfigExperiment *_configExperiment;
  78. dispatch_queue_t _queue;
  79. NSString *_appName;
  80. }
  81. static NSMutableDictionary<NSString *, NSMutableDictionary<NSString *, FIRRemoteConfig *> *>
  82. *RCInstances;
  83. + (nonnull FIRRemoteConfig *)remoteConfigWithApp:(FIRApp *_Nonnull)firebaseApp {
  84. return [FIRRemoteConfig remoteConfigWithFIRNamespace:FIRNamespaceGoogleMobilePlatform
  85. app:firebaseApp];
  86. }
  87. + (nonnull FIRRemoteConfig *)remoteConfigWithFIRNamespace:(NSString *_Nonnull)firebaseNamespace {
  88. if (![FIRApp isDefaultAppConfigured]) {
  89. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000047",
  90. @"FIRApp not configured. Please make sure you have called [FIRApp configure]");
  91. // TODO: Maybe throw an exception here? That'd be a breaking change though, but at this point
  92. // RC can't work as expected.
  93. }
  94. return [FIRRemoteConfig remoteConfigWithFIRNamespace:firebaseNamespace app:[FIRApp defaultApp]];
  95. }
  96. + (nonnull FIRRemoteConfig *)remoteConfigWithFIRNamespace:(NSString *_Nonnull)firebaseNamespace
  97. app:(FIRApp *_Nonnull)firebaseApp {
  98. // Use the provider to generate and return instances of FIRRemoteConfig for this specific app and
  99. // namespace. This will ensure the app is configured before Remote Config can return an instance.
  100. id<FIRRemoteConfigProvider> provider =
  101. FIR_COMPONENT(FIRRemoteConfigProvider, firebaseApp.container);
  102. return [provider remoteConfigForNamespace:firebaseNamespace];
  103. }
  104. + (FIRRemoteConfig *)remoteConfig {
  105. // If the default app is not configured at this point, warn the developer.
  106. if (![FIRApp isDefaultAppConfigured]) {
  107. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000047",
  108. @"FIRApp not configured. Please make sure you have called [FIRApp configure]");
  109. // TODO: Maybe throw an exception here? That'd be a breaking change though, but at this point
  110. // RC can't work as expected.
  111. }
  112. return [FIRRemoteConfig remoteConfigWithFIRNamespace:FIRNamespaceGoogleMobilePlatform
  113. app:[FIRApp defaultApp]];
  114. }
  115. /// Singleton instance of serial queue for queuing all incoming RC calls.
  116. + (dispatch_queue_t)sharedRemoteConfigSerialQueue {
  117. static dispatch_once_t onceToken;
  118. static dispatch_queue_t sharedRemoteConfigQueue;
  119. dispatch_once(&onceToken, ^{
  120. sharedRemoteConfigQueue =
  121. dispatch_queue_create(RCNRemoteConfigQueueLabel, DISPATCH_QUEUE_SERIAL);
  122. });
  123. return sharedRemoteConfigQueue;
  124. }
  125. /// Designated initializer
  126. - (instancetype)initWithAppName:(NSString *)appName
  127. FIROptions:(FIROptions *)options
  128. namespace:(NSString *)FIRNamespace
  129. DBManager:(RCNConfigDBManager *)DBManager
  130. configContent:(RCNConfigContent *)configContent
  131. analytics:(nullable id<FIRAnalyticsInterop>)analytics {
  132. self = [super init];
  133. if (self) {
  134. _appName = appName;
  135. _DBManager = DBManager;
  136. // The fully qualified Firebase namespace is namespace:firappname.
  137. _FIRNamespace = [NSString stringWithFormat:@"%@:%@", FIRNamespace, appName];
  138. // Initialize RCConfigContent if not already.
  139. _configContent = configContent;
  140. _settings = [[RCNConfigSettings alloc] initWithDatabaseManager:_DBManager
  141. namespace:_FIRNamespace
  142. firebaseAppName:appName
  143. googleAppID:options.googleAppID];
  144. FIRExperimentController *experimentController = [FIRExperimentController sharedInstance];
  145. _configExperiment = [[RCNConfigExperiment alloc] initWithDBManager:_DBManager
  146. experimentController:experimentController];
  147. /// Serial queue for read and write lock.
  148. _queue = [FIRRemoteConfig sharedRemoteConfigSerialQueue];
  149. // Initialize with default config settings.
  150. [self setDefaultConfigSettings];
  151. _configFetch = [[RCNConfigFetch alloc] initWithContent:_configContent
  152. DBManager:_DBManager
  153. settings:_settings
  154. analytics:analytics
  155. experiment:_configExperiment
  156. queue:_queue
  157. namespace:_FIRNamespace
  158. options:options];
  159. [_settings loadConfigFromMetadataTable];
  160. }
  161. return self;
  162. }
  163. // Initialize with default config settings.
  164. - (void)setDefaultConfigSettings {
  165. // Set the default config settings.
  166. self->_settings.fetchTimeout = RCNHTTPDefaultConnectionTimeout;
  167. self->_settings.minimumFetchInterval = RCNDefaultMinimumFetchInterval;
  168. }
  169. - (void)ensureInitializedWithCompletionHandler:
  170. (nonnull FIRRemoteConfigInitializationCompletion)completionHandler {
  171. __weak FIRRemoteConfig *weakSelf = self;
  172. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  173. FIRRemoteConfig *strongSelf = weakSelf;
  174. if (!strongSelf) {
  175. return;
  176. }
  177. BOOL initializationSuccess = [self->_configContent initializationSuccessful];
  178. NSError *error = nil;
  179. if (!initializationSuccess) {
  180. error = [[NSError alloc]
  181. initWithDomain:FIRRemoteConfigErrorDomain
  182. code:FIRRemoteConfigErrorInternalError
  183. userInfo:@{NSLocalizedDescriptionKey : @"Timed out waiting for database load."}];
  184. }
  185. completionHandler(error);
  186. });
  187. }
  188. #pragma mark - fetch
  189. - (void)fetchWithCompletionHandler:(FIRRemoteConfigFetchCompletion)completionHandler {
  190. dispatch_async(_queue, ^{
  191. [self fetchWithExpirationDuration:self->_settings.minimumFetchInterval
  192. completionHandler:completionHandler];
  193. });
  194. }
  195. - (void)fetchWithExpirationDuration:(NSTimeInterval)expirationDuration
  196. completionHandler:(FIRRemoteConfigFetchCompletion)completionHandler {
  197. FIRRemoteConfigFetchCompletion completionHandlerCopy = nil;
  198. if (completionHandler) {
  199. completionHandlerCopy = [completionHandler copy];
  200. }
  201. [_configFetch fetchConfigWithExpirationDuration:expirationDuration
  202. completionHandler:completionHandlerCopy];
  203. }
  204. #pragma mark - fetchAndActivate
  205. - (void)fetchAndActivateWithCompletionHandler:
  206. (FIRRemoteConfigFetchAndActivateCompletion)completionHandler {
  207. __weak FIRRemoteConfig *weakSelf = self;
  208. FIRRemoteConfigFetchCompletion fetchCompletion =
  209. ^(FIRRemoteConfigFetchStatus fetchStatus, NSError *fetchError) {
  210. FIRRemoteConfig *strongSelf = weakSelf;
  211. if (!strongSelf) {
  212. return;
  213. }
  214. // Fetch completed. We are being called on the main queue.
  215. // If fetch is successful, try to activate the fetched config
  216. if (fetchStatus == FIRRemoteConfigFetchStatusSuccess && !fetchError) {
  217. [strongSelf activateWithCompletionHandler:^(NSError *_Nullable activateError) {
  218. if (completionHandler) {
  219. FIRRemoteConfigFetchAndActivateStatus status =
  220. activateError ? FIRRemoteConfigFetchAndActivateStatusSuccessUsingPreFetchedData
  221. : FIRRemoteConfigFetchAndActivateStatusSuccessFetchedFromRemote;
  222. completionHandler(status, nil);
  223. }
  224. }];
  225. } else if (completionHandler) {
  226. FIRRemoteConfigFetchAndActivateStatus status =
  227. fetchStatus == FIRRemoteConfigFetchStatusSuccess
  228. ? FIRRemoteConfigFetchAndActivateStatusSuccessUsingPreFetchedData
  229. : FIRRemoteConfigFetchAndActivateStatusError;
  230. completionHandler(status, fetchError);
  231. }
  232. };
  233. [self fetchWithCompletionHandler:fetchCompletion];
  234. }
  235. #pragma mark - apply
  236. - (BOOL)activateFetched {
  237. // TODO: We block on the async activate to complete. This method is deprecated and needs
  238. // to be removed at the next possible breaking change.
  239. __block dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
  240. __block BOOL didActivate = NO;
  241. [self activateWithCompletionHandler:^(NSError *_Nullable error) {
  242. didActivate = error ? false : true;
  243. dispatch_semaphore_signal(semaphore);
  244. }];
  245. dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
  246. return didActivate;
  247. }
  248. - (void)activateWithCompletionHandler:(FIRRemoteConfigActivateCompletion)completionHandler {
  249. __weak FIRRemoteConfig *weakSelf = self;
  250. void (^applyBlock)(void) = ^(void) {
  251. FIRRemoteConfig *strongSelf = weakSelf;
  252. if (!strongSelf) {
  253. NSError *error = [NSError errorWithDomain:FIRRemoteConfigErrorDomain
  254. code:FIRRemoteConfigErrorInternalError
  255. userInfo:@{@"ActivationFailureReason" : @"Internal Error."}];
  256. if (completionHandler) {
  257. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  258. completionHandler(error);
  259. });
  260. }
  261. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000068", @"Internal error activating config.");
  262. return;
  263. }
  264. // Check if the last fetched config has already been activated. Fetches with no data change are
  265. // ignored.
  266. if (strongSelf->_settings.lastETagUpdateTime == 0 ||
  267. strongSelf->_settings.lastETagUpdateTime <= strongSelf->_settings.lastApplyTimeInterval) {
  268. FIRLogWarning(kFIRLoggerRemoteConfig, @"I-RCN000069",
  269. @"Most recently fetched config is already activated.");
  270. NSError *error = [NSError
  271. errorWithDomain:FIRRemoteConfigErrorDomain
  272. code:FIRRemoteConfigErrorInternalError
  273. userInfo:@{
  274. @"ActivationFailureReason" : @"Most recently fetched config is already activated"
  275. }];
  276. if (completionHandler) {
  277. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  278. completionHandler(error);
  279. });
  280. }
  281. return;
  282. }
  283. [strongSelf->_configContent copyFromDictionary:self->_configContent.fetchedConfig
  284. toSource:RCNDBSourceActive
  285. forNamespace:self->_FIRNamespace];
  286. [strongSelf updateExperiments];
  287. strongSelf->_settings.lastApplyTimeInterval = [[NSDate date] timeIntervalSince1970];
  288. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000069", @"Config activated.");
  289. if (completionHandler) {
  290. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  291. completionHandler(nil);
  292. });
  293. }
  294. };
  295. dispatch_async(_queue, applyBlock);
  296. }
  297. - (void)updateExperiments {
  298. [self->_configExperiment updateExperiments];
  299. }
  300. #pragma mark - helpers
  301. - (NSString *)fullyQualifiedNamespace:(NSString *)namespace {
  302. // If this is already a fully qualified namespace, return.
  303. if ([namespace rangeOfString:@":"].location != NSNotFound) {
  304. return namespace;
  305. }
  306. NSString *fullyQualifiedNamespace = [NSString stringWithFormat:@"%@:%@", namespace, _appName];
  307. return fullyQualifiedNamespace;
  308. }
  309. #pragma mark - Get Config Result
  310. - (FIRRemoteConfigValue *)objectForKeyedSubscript:(NSString *)key {
  311. return [self configValueForKey:key];
  312. }
  313. - (FIRRemoteConfigValue *)configValueForKey:(NSString *)key {
  314. return [self configValueForKey:key namespace:_FIRNamespace];
  315. }
  316. - (FIRRemoteConfigValue *)configValueForKey:(NSString *)key namespace:(NSString *)aNamespace {
  317. if (!key || !aNamespace) {
  318. return [[FIRRemoteConfigValue alloc] initWithData:[NSData data]
  319. source:FIRRemoteConfigSourceStatic];
  320. }
  321. NSString *FQNamespace = [self fullyQualifiedNamespace:aNamespace];
  322. __block FIRRemoteConfigValue *value;
  323. dispatch_sync(_queue, ^{
  324. value = self->_configContent.activeConfig[FQNamespace][key];
  325. if (value) {
  326. if (value.source != FIRRemoteConfigSourceRemote) {
  327. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000001",
  328. @"Key %@ should come from source:%zd instead coming from source: %zd.", key,
  329. (long)FIRRemoteConfigSourceRemote, (long)value.source);
  330. }
  331. return;
  332. }
  333. value = self->_configContent.defaultConfig[FQNamespace][key];
  334. if (value) {
  335. return;
  336. }
  337. value = [[FIRRemoteConfigValue alloc] initWithData:[NSData data]
  338. source:FIRRemoteConfigSourceStatic];
  339. });
  340. return value;
  341. }
  342. - (FIRRemoteConfigValue *)configValueForKey:(NSString *)key source:(FIRRemoteConfigSource)source {
  343. return [self configValueForKey:key namespace:_FIRNamespace source:source];
  344. }
  345. - (FIRRemoteConfigValue *)configValueForKey:(NSString *)key
  346. namespace:(NSString *)aNamespace
  347. source:(FIRRemoteConfigSource)source {
  348. if (!key || !aNamespace) {
  349. return [[FIRRemoteConfigValue alloc] initWithData:[NSData data]
  350. source:FIRRemoteConfigSourceStatic];
  351. }
  352. NSString *FQNamespace = [self fullyQualifiedNamespace:aNamespace];
  353. __block FIRRemoteConfigValue *value;
  354. dispatch_sync(_queue, ^{
  355. if (source == FIRRemoteConfigSourceRemote) {
  356. value = self->_configContent.activeConfig[FQNamespace][key];
  357. } else if (source == FIRRemoteConfigSourceDefault) {
  358. value = self->_configContent.defaultConfig[FQNamespace][key];
  359. } else {
  360. value = [[FIRRemoteConfigValue alloc] initWithData:[NSData data]
  361. source:FIRRemoteConfigSourceStatic];
  362. }
  363. });
  364. return value;
  365. }
  366. - (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state
  367. objects:(id __unsafe_unretained[])stackbuf
  368. count:(NSUInteger)len {
  369. __block NSUInteger localValue;
  370. dispatch_sync(_queue, ^{
  371. localValue =
  372. [self->_configContent.activeConfig[self->_FIRNamespace] countByEnumeratingWithState:state
  373. objects:stackbuf
  374. count:len];
  375. });
  376. return localValue;
  377. }
  378. #pragma mark - Properties
  379. #pragma clang diagnostic push
  380. #pragma clang diagnostic ignored "-Wunused-property-ivar"
  381. /// Last fetch completion time.
  382. - (NSDate *)lastFetchTime {
  383. __block NSDate *fetchTime;
  384. dispatch_sync(_queue, ^{
  385. NSTimeInterval lastFetchTime = self->_settings.lastFetchTimeInterval;
  386. fetchTime = [NSDate dateWithTimeIntervalSince1970:lastFetchTime];
  387. });
  388. return fetchTime;
  389. }
  390. #pragma clang diagnostic pop
  391. - (FIRRemoteConfigFetchStatus)lastFetchStatus {
  392. __block FIRRemoteConfigFetchStatus currentStatus;
  393. dispatch_sync(_queue, ^{
  394. currentStatus = self->_settings.lastFetchStatus;
  395. });
  396. return currentStatus;
  397. }
  398. - (NSArray *)allKeysFromSource:(FIRRemoteConfigSource)source {
  399. return [self allKeysFromSource:source namespace:_FIRNamespace];
  400. }
  401. - (NSArray *)allKeysFromSource:(FIRRemoteConfigSource)source namespace:(NSString *)aNamespace {
  402. __block NSArray *keys = [[NSArray alloc] init];
  403. dispatch_sync(_queue, ^{
  404. if (!aNamespace) {
  405. return;
  406. }
  407. NSString *FQNamespace = [self fullyQualifiedNamespace:aNamespace];
  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. return [self keysWithPrefix:prefix namespace:_FIRNamespace];
  427. }
  428. - (nonnull NSSet *)keysWithPrefix:(nullable NSString *)prefix
  429. namespace:(nullable NSString *)aNamespace {
  430. __block NSMutableSet *keys = [[NSMutableSet alloc] init];
  431. __block NSString *namespaceToCheck = aNamespace;
  432. dispatch_sync(_queue, ^{
  433. if (!namespaceToCheck.length) {
  434. return;
  435. }
  436. NSString *FQNamespace = [self fullyQualifiedNamespace:namespaceToCheck];
  437. if (self->_configContent.activeConfig[FQNamespace]) {
  438. NSArray *allKeys = [self->_configContent.activeConfig[FQNamespace] allKeys];
  439. if (!prefix.length) {
  440. keys = [NSMutableSet setWithArray:allKeys];
  441. } else {
  442. for (NSString *key in allKeys) {
  443. if ([key hasPrefix:prefix]) {
  444. [keys addObject:key];
  445. }
  446. }
  447. }
  448. }
  449. });
  450. return [keys copy];
  451. }
  452. #pragma mark - Defaults
  453. - (void)setDefaults:(NSDictionary<NSString *, NSObject *> *)defaults {
  454. [self setDefaults:defaults namespace:_FIRNamespace];
  455. }
  456. - (void)setDefaults:(NSDictionary<NSString *, NSObject *> *)defaultConfig
  457. namespace:(NSString *)aNamespace {
  458. if (!aNamespace) {
  459. FIRLogWarning(kFIRLoggerRemoteConfig, @"I-RCN000036", @"The namespace cannot be empty or nil.");
  460. return;
  461. }
  462. NSString *FQNamespace = [self fullyQualifiedNamespace:aNamespace];
  463. NSDictionary *defaultConfigCopy = [[NSDictionary alloc] init];
  464. if (defaultConfig) {
  465. defaultConfigCopy = [defaultConfig copy];
  466. }
  467. void (^setDefaultsBlock)(void) = ^(void) {
  468. NSDictionary *namespaceToDefaults = @{FQNamespace : defaultConfigCopy};
  469. [self->_configContent copyFromDictionary:namespaceToDefaults
  470. toSource:RCNDBSourceDefault
  471. forNamespace:FQNamespace];
  472. self->_settings.lastSetDefaultsTimeInterval = [[NSDate date] timeIntervalSince1970];
  473. };
  474. dispatch_async(_queue, setDefaultsBlock);
  475. }
  476. - (FIRRemoteConfigValue *)defaultValueForKey:(NSString *)key {
  477. return [self defaultValueForKey:key namespace:_FIRNamespace];
  478. }
  479. - (FIRRemoteConfigValue *)defaultValueForKey:(NSString *)key namespace:(NSString *)aNamespace {
  480. if (!key || !aNamespace) {
  481. return nil;
  482. }
  483. NSString *FQNamespace = [self fullyQualifiedNamespace:aNamespace];
  484. __block FIRRemoteConfigValue *value;
  485. dispatch_sync(_queue, ^{
  486. NSDictionary *defaultConfig = self->_configContent.defaultConfig;
  487. value = defaultConfig[FQNamespace][key];
  488. if (value) {
  489. if (value.source != FIRRemoteConfigSourceDefault) {
  490. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000002",
  491. @"Key %@ should come from source:%zd instead coming from source: %zd", key,
  492. (long)FIRRemoteConfigSourceDefault, (long)value.source);
  493. }
  494. }
  495. });
  496. return value;
  497. }
  498. - (void)setDefaultsFromPlistFileName:(nullable NSString *)fileName {
  499. return [self setDefaultsFromPlistFileName:fileName namespace:_FIRNamespace];
  500. }
  501. - (void)setDefaultsFromPlistFileName:(nullable NSString *)fileName
  502. namespace:(nullable NSString *)namespace {
  503. if (!namespace || namespace.length == 0) {
  504. FIRLogWarning(kFIRLoggerRemoteConfig, @"I-RCN000036", @"The namespace cannot be empty or nil.");
  505. return;
  506. }
  507. NSString *FQNamespace = [self fullyQualifiedNamespace:namespace];
  508. if (!fileName || fileName.length == 0) {
  509. FIRLogWarning(kFIRLoggerRemoteConfig, @"I-RCN000037",
  510. @"The plist file '%@' could not be found by Remote Config.", fileName);
  511. return;
  512. }
  513. NSArray *bundles = @[ [NSBundle mainBundle], [NSBundle bundleForClass:[self class]] ];
  514. for (NSBundle *bundle in bundles) {
  515. NSString *plistFile = [bundle pathForResource:fileName ofType:@"plist"];
  516. // Use the first one we find.
  517. if (plistFile) {
  518. NSDictionary *defaultConfig = [[NSDictionary alloc] initWithContentsOfFile:plistFile];
  519. if (defaultConfig) {
  520. [self setDefaults:defaultConfig namespace:FQNamespace];
  521. }
  522. return;
  523. }
  524. }
  525. FIRLogWarning(kFIRLoggerRemoteConfig, @"I-RCN000037",
  526. @"The plist file '%@' could not be found by Remote Config.", fileName);
  527. }
  528. #pragma mark - custom variables
  529. - (FIRRemoteConfigSettings *)configSettings {
  530. __block BOOL developerModeEnabled = NO;
  531. __block NSTimeInterval minimumFetchInterval = RCNDefaultMinimumFetchInterval;
  532. __block NSTimeInterval fetchTimeout = RCNHTTPDefaultConnectionTimeout;
  533. dispatch_sync(_queue, ^{
  534. developerModeEnabled = [self->_settings.customVariables[kRemoteConfigDeveloperKey] boolValue];
  535. minimumFetchInterval = self->_settings.minimumFetchInterval;
  536. fetchTimeout = self->_settings.fetchTimeout;
  537. });
  538. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000066",
  539. @"Successfully read configSettings. Developer Mode: %@, Minimum Fetch Interval:%f, "
  540. @"Fetch timeout: %f",
  541. developerModeEnabled ? @"true" : @"false", minimumFetchInterval, fetchTimeout);
  542. FIRRemoteConfigSettings *settings =
  543. [[FIRRemoteConfigSettings alloc] initWithDeveloperModeEnabled:developerModeEnabled];
  544. settings.minimumFetchInterval = minimumFetchInterval;
  545. settings.fetchTimeout = fetchTimeout;
  546. /// The NSURLSession needs to be recreated whenever the fetch timeout may be updated.
  547. [_configFetch recreateNetworkSession];
  548. return settings;
  549. }
  550. - (void)setConfigSettings:(FIRRemoteConfigSettings *)configSettings {
  551. void (^setConfigSettingsBlock)(void) = ^(void) {
  552. if (!configSettings) {
  553. return;
  554. }
  555. NSDictionary *settingsToSave = @{
  556. kRemoteConfigDeveloperKey : @(configSettings.isDeveloperModeEnabled),
  557. };
  558. self->_settings.customVariables = settingsToSave;
  559. self->_settings.minimumFetchInterval = configSettings.minimumFetchInterval;
  560. self->_settings.fetchTimeout = configSettings.fetchTimeout;
  561. /// The NSURLSession needs to be recreated whenever the fetch timeout may be updated.
  562. [self->_configFetch recreateNetworkSession];
  563. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000067",
  564. @"Successfully set configSettings. Developer Mode: %@, Minimum Fetch Interval:%f, "
  565. @"Fetch timeout:%f",
  566. configSettings.isDeveloperModeEnabled ? @"true" : @"false",
  567. configSettings.minimumFetchInterval, configSettings.fetchTimeout);
  568. };
  569. dispatch_async(_queue, setConfigSettingsBlock);
  570. }
  571. #pragma clang diagnostic push // "-Wdeprecated-declarations"
  572. @end