FIRRemoteConfig.m 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659
  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/RCNConfigFetch.h"
  25. #import "FirebaseRemoteConfig/Sources/Private/RCNConfigSettings.h"
  26. #import "FirebaseRemoteConfig/Sources/RCNConfigConstants.h"
  27. #import "FirebaseRemoteConfig/Sources/RCNConfigContent.h"
  28. #import "FirebaseRemoteConfig/Sources/RCNConfigDBManager.h"
  29. #import "FirebaseRemoteConfig/Sources/RCNConfigExperiment.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. typedef void (^FIRRemoteConfigActivateChangeCompletion)(BOOL changed, NSError *_Nullable error);
  249. - (void)activateWithCompletion:(FIRRemoteConfigActivateChangeCompletion)completion {
  250. [self activateWithEitherHandler:completion deprecatedHandler:nil];
  251. }
  252. - (void)activateWithCompletionHandler:(FIRRemoteConfigActivateCompletion)completionHandler {
  253. [self activateWithEitherHandler:nil deprecatedHandler:completionHandler];
  254. }
  255. - (void)activateWithEitherHandler:(FIRRemoteConfigActivateChangeCompletion)completion
  256. deprecatedHandler:(FIRRemoteConfigActivateCompletion)deprecatedHandler {
  257. __weak FIRRemoteConfig *weakSelf = self;
  258. void (^applyBlock)(void) = ^(void) {
  259. FIRRemoteConfig *strongSelf = weakSelf;
  260. if (!strongSelf) {
  261. NSError *error = [NSError errorWithDomain:FIRRemoteConfigErrorDomain
  262. code:FIRRemoteConfigErrorInternalError
  263. userInfo:@{@"ActivationFailureReason" : @"Internal Error."}];
  264. if (completion) {
  265. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  266. completion(NO, error);
  267. });
  268. } else if (deprecatedHandler) {
  269. deprecatedHandler(error);
  270. }
  271. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000068", @"Internal error activating config.");
  272. return;
  273. }
  274. // Check if the last fetched config has already been activated. Fetches with no data change are
  275. // ignored.
  276. if (strongSelf->_settings.lastETagUpdateTime == 0 ||
  277. strongSelf->_settings.lastETagUpdateTime <= strongSelf->_settings.lastApplyTimeInterval) {
  278. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000069",
  279. @"Most recently fetched config is already activated.");
  280. if (completion) {
  281. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  282. completion(NO, nil);
  283. });
  284. } else if (deprecatedHandler) {
  285. NSError *error = [NSError
  286. errorWithDomain:FIRRemoteConfigErrorDomain
  287. code:FIRRemoteConfigErrorInternalError
  288. userInfo:@{
  289. @"ActivationFailureReason" : @"Most recently fetched config already activated"
  290. }];
  291. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  292. deprecatedHandler(error);
  293. });
  294. }
  295. return;
  296. }
  297. [strongSelf->_configContent copyFromDictionary:self->_configContent.fetchedConfig
  298. toSource:RCNDBSourceActive
  299. forNamespace:self->_FIRNamespace];
  300. [strongSelf updateExperiments];
  301. strongSelf->_settings.lastApplyTimeInterval = [[NSDate date] timeIntervalSince1970];
  302. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000069", @"Config activated.");
  303. if (completion) {
  304. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  305. completion(YES, nil);
  306. });
  307. } else if (deprecatedHandler) {
  308. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  309. deprecatedHandler(nil);
  310. });
  311. }
  312. };
  313. dispatch_async(_queue, applyBlock);
  314. }
  315. - (void)updateExperiments {
  316. [self->_configExperiment updateExperiments];
  317. }
  318. #pragma mark - helpers
  319. - (NSString *)fullyQualifiedNamespace:(NSString *)namespace {
  320. // If this is already a fully qualified namespace, return.
  321. if ([namespace rangeOfString:@":"].location != NSNotFound) {
  322. return namespace;
  323. }
  324. NSString *fullyQualifiedNamespace = [NSString stringWithFormat:@"%@:%@", namespace, _appName];
  325. return fullyQualifiedNamespace;
  326. }
  327. #pragma mark - Get Config Result
  328. - (FIRRemoteConfigValue *)objectForKeyedSubscript:(NSString *)key {
  329. return [self configValueForKey:key];
  330. }
  331. - (FIRRemoteConfigValue *)configValueForKey:(NSString *)key {
  332. return [self configValueForKey:key namespace:_FIRNamespace];
  333. }
  334. - (FIRRemoteConfigValue *)configValueForKey:(NSString *)key namespace:(NSString *)aNamespace {
  335. if (!key || !aNamespace) {
  336. return [[FIRRemoteConfigValue alloc] initWithData:[NSData data]
  337. source:FIRRemoteConfigSourceStatic];
  338. }
  339. NSString *FQNamespace = [self fullyQualifiedNamespace:aNamespace];
  340. __block FIRRemoteConfigValue *value;
  341. dispatch_sync(_queue, ^{
  342. value = self->_configContent.activeConfig[FQNamespace][key];
  343. if (value) {
  344. if (value.source != FIRRemoteConfigSourceRemote) {
  345. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000001",
  346. @"Key %@ should come from source:%zd instead coming from source: %zd.", key,
  347. (long)FIRRemoteConfigSourceRemote, (long)value.source);
  348. }
  349. return;
  350. }
  351. value = self->_configContent.defaultConfig[FQNamespace][key];
  352. if (value) {
  353. return;
  354. }
  355. value = [[FIRRemoteConfigValue alloc] initWithData:[NSData data]
  356. source:FIRRemoteConfigSourceStatic];
  357. });
  358. return value;
  359. }
  360. - (FIRRemoteConfigValue *)configValueForKey:(NSString *)key source:(FIRRemoteConfigSource)source {
  361. return [self configValueForKey:key namespace:_FIRNamespace source:source];
  362. }
  363. - (FIRRemoteConfigValue *)configValueForKey:(NSString *)key
  364. namespace:(NSString *)aNamespace
  365. source:(FIRRemoteConfigSource)source {
  366. if (!key || !aNamespace) {
  367. return [[FIRRemoteConfigValue alloc] initWithData:[NSData data]
  368. source:FIRRemoteConfigSourceStatic];
  369. }
  370. NSString *FQNamespace = [self fullyQualifiedNamespace:aNamespace];
  371. __block FIRRemoteConfigValue *value;
  372. dispatch_sync(_queue, ^{
  373. if (source == FIRRemoteConfigSourceRemote) {
  374. value = self->_configContent.activeConfig[FQNamespace][key];
  375. } else if (source == FIRRemoteConfigSourceDefault) {
  376. value = self->_configContent.defaultConfig[FQNamespace][key];
  377. } else {
  378. value = [[FIRRemoteConfigValue alloc] initWithData:[NSData data]
  379. source:FIRRemoteConfigSourceStatic];
  380. }
  381. });
  382. return value;
  383. }
  384. - (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state
  385. objects:(id __unsafe_unretained[])stackbuf
  386. count:(NSUInteger)len {
  387. __block NSUInteger localValue;
  388. dispatch_sync(_queue, ^{
  389. localValue =
  390. [self->_configContent.activeConfig[self->_FIRNamespace] countByEnumeratingWithState:state
  391. objects:stackbuf
  392. count:len];
  393. });
  394. return localValue;
  395. }
  396. #pragma mark - Properties
  397. #pragma clang diagnostic push
  398. #pragma clang diagnostic ignored "-Wunused-property-ivar"
  399. /// Last fetch completion time.
  400. - (NSDate *)lastFetchTime {
  401. __block NSDate *fetchTime;
  402. dispatch_sync(_queue, ^{
  403. NSTimeInterval lastFetchTime = self->_settings.lastFetchTimeInterval;
  404. fetchTime = [NSDate dateWithTimeIntervalSince1970:lastFetchTime];
  405. });
  406. return fetchTime;
  407. }
  408. #pragma clang diagnostic pop
  409. - (FIRRemoteConfigFetchStatus)lastFetchStatus {
  410. __block FIRRemoteConfigFetchStatus currentStatus;
  411. dispatch_sync(_queue, ^{
  412. currentStatus = self->_settings.lastFetchStatus;
  413. });
  414. return currentStatus;
  415. }
  416. - (NSArray *)allKeysFromSource:(FIRRemoteConfigSource)source {
  417. return [self allKeysFromSource:source namespace:_FIRNamespace];
  418. }
  419. - (NSArray *)allKeysFromSource:(FIRRemoteConfigSource)source namespace:(NSString *)aNamespace {
  420. __block NSArray *keys = [[NSArray alloc] init];
  421. dispatch_sync(_queue, ^{
  422. if (!aNamespace) {
  423. return;
  424. }
  425. NSString *FQNamespace = [self fullyQualifiedNamespace:aNamespace];
  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. return [self keysWithPrefix:prefix namespace:_FIRNamespace];
  445. }
  446. - (nonnull NSSet *)keysWithPrefix:(nullable NSString *)prefix
  447. namespace:(nullable NSString *)aNamespace {
  448. __block NSMutableSet *keys = [[NSMutableSet alloc] init];
  449. __block NSString *namespaceToCheck = aNamespace;
  450. dispatch_sync(_queue, ^{
  451. if (!namespaceToCheck.length) {
  452. return;
  453. }
  454. NSString *FQNamespace = [self fullyQualifiedNamespace:namespaceToCheck];
  455. if (self->_configContent.activeConfig[FQNamespace]) {
  456. NSArray *allKeys = [self->_configContent.activeConfig[FQNamespace] allKeys];
  457. if (!prefix.length) {
  458. keys = [NSMutableSet setWithArray:allKeys];
  459. } else {
  460. for (NSString *key in allKeys) {
  461. if ([key hasPrefix:prefix]) {
  462. [keys addObject:key];
  463. }
  464. }
  465. }
  466. }
  467. });
  468. return [keys copy];
  469. }
  470. #pragma mark - Defaults
  471. - (void)setDefaults:(NSDictionary<NSString *, NSObject *> *)defaults {
  472. [self setDefaults:defaults namespace:_FIRNamespace];
  473. }
  474. - (void)setDefaults:(NSDictionary<NSString *, NSObject *> *)defaultConfig
  475. namespace:(NSString *)aNamespace {
  476. if (!aNamespace) {
  477. FIRLogWarning(kFIRLoggerRemoteConfig, @"I-RCN000036", @"The namespace cannot be empty or nil.");
  478. return;
  479. }
  480. NSString *FQNamespace = [self fullyQualifiedNamespace:aNamespace];
  481. NSDictionary *defaultConfigCopy = [[NSDictionary alloc] init];
  482. if (defaultConfig) {
  483. defaultConfigCopy = [defaultConfig copy];
  484. }
  485. void (^setDefaultsBlock)(void) = ^(void) {
  486. NSDictionary *namespaceToDefaults = @{FQNamespace : defaultConfigCopy};
  487. [self->_configContent copyFromDictionary:namespaceToDefaults
  488. toSource:RCNDBSourceDefault
  489. forNamespace:FQNamespace];
  490. self->_settings.lastSetDefaultsTimeInterval = [[NSDate date] timeIntervalSince1970];
  491. };
  492. dispatch_async(_queue, setDefaultsBlock);
  493. }
  494. - (FIRRemoteConfigValue *)defaultValueForKey:(NSString *)key {
  495. return [self defaultValueForKey:key namespace:_FIRNamespace];
  496. }
  497. - (FIRRemoteConfigValue *)defaultValueForKey:(NSString *)key namespace:(NSString *)aNamespace {
  498. if (!key || !aNamespace) {
  499. return nil;
  500. }
  501. NSString *FQNamespace = [self fullyQualifiedNamespace:aNamespace];
  502. __block FIRRemoteConfigValue *value;
  503. dispatch_sync(_queue, ^{
  504. NSDictionary *defaultConfig = self->_configContent.defaultConfig;
  505. value = defaultConfig[FQNamespace][key];
  506. if (value) {
  507. if (value.source != FIRRemoteConfigSourceDefault) {
  508. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000002",
  509. @"Key %@ should come from source:%zd instead coming from source: %zd", key,
  510. (long)FIRRemoteConfigSourceDefault, (long)value.source);
  511. }
  512. }
  513. });
  514. return value;
  515. }
  516. - (void)setDefaultsFromPlistFileName:(nullable NSString *)fileName {
  517. return [self setDefaultsFromPlistFileName:fileName namespace:_FIRNamespace];
  518. }
  519. - (void)setDefaultsFromPlistFileName:(nullable NSString *)fileName
  520. namespace:(nullable NSString *)namespace {
  521. if (!namespace || namespace.length == 0) {
  522. FIRLogWarning(kFIRLoggerRemoteConfig, @"I-RCN000036", @"The namespace cannot be empty or nil.");
  523. return;
  524. }
  525. NSString *FQNamespace = [self fullyQualifiedNamespace:namespace];
  526. if (!fileName || fileName.length == 0) {
  527. FIRLogWarning(kFIRLoggerRemoteConfig, @"I-RCN000037",
  528. @"The plist file '%@' could not be found by Remote Config.", fileName);
  529. return;
  530. }
  531. NSArray *bundles = @[ [NSBundle mainBundle], [NSBundle bundleForClass:[self class]] ];
  532. for (NSBundle *bundle in bundles) {
  533. NSString *plistFile = [bundle pathForResource:fileName ofType:@"plist"];
  534. // Use the first one we find.
  535. if (plistFile) {
  536. NSDictionary *defaultConfig = [[NSDictionary alloc] initWithContentsOfFile:plistFile];
  537. if (defaultConfig) {
  538. [self setDefaults:defaultConfig namespace:FQNamespace];
  539. }
  540. return;
  541. }
  542. }
  543. FIRLogWarning(kFIRLoggerRemoteConfig, @"I-RCN000037",
  544. @"The plist file '%@' could not be found by Remote Config.", fileName);
  545. }
  546. #pragma mark - custom variables
  547. - (FIRRemoteConfigSettings *)configSettings {
  548. __block BOOL developerModeEnabled = NO;
  549. __block NSTimeInterval minimumFetchInterval = RCNDefaultMinimumFetchInterval;
  550. __block NSTimeInterval fetchTimeout = RCNHTTPDefaultConnectionTimeout;
  551. dispatch_sync(_queue, ^{
  552. developerModeEnabled = [self->_settings.customVariables[kRemoteConfigDeveloperKey] boolValue];
  553. minimumFetchInterval = self->_settings.minimumFetchInterval;
  554. fetchTimeout = self->_settings.fetchTimeout;
  555. });
  556. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000066",
  557. @"Successfully read configSettings. Developer Mode: %@, Minimum Fetch Interval:%f, "
  558. @"Fetch timeout: %f",
  559. developerModeEnabled ? @"true" : @"false", minimumFetchInterval, fetchTimeout);
  560. FIRRemoteConfigSettings *settings =
  561. [[FIRRemoteConfigSettings alloc] initWithDeveloperModeEnabled:developerModeEnabled];
  562. settings.minimumFetchInterval = minimumFetchInterval;
  563. settings.fetchTimeout = fetchTimeout;
  564. /// The NSURLSession needs to be recreated whenever the fetch timeout may be updated.
  565. [_configFetch recreateNetworkSession];
  566. return settings;
  567. }
  568. - (void)setConfigSettings:(FIRRemoteConfigSettings *)configSettings {
  569. void (^setConfigSettingsBlock)(void) = ^(void) {
  570. if (!configSettings) {
  571. return;
  572. }
  573. NSDictionary *settingsToSave = @{
  574. kRemoteConfigDeveloperKey : @(configSettings.isDeveloperModeEnabled),
  575. };
  576. self->_settings.customVariables = settingsToSave;
  577. self->_settings.minimumFetchInterval = configSettings.minimumFetchInterval;
  578. self->_settings.fetchTimeout = configSettings.fetchTimeout;
  579. /// The NSURLSession needs to be recreated whenever the fetch timeout may be updated.
  580. [self->_configFetch recreateNetworkSession];
  581. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000067",
  582. @"Successfully set configSettings. Developer Mode: %@, Minimum Fetch Interval:%f, "
  583. @"Fetch timeout:%f",
  584. configSettings.isDeveloperModeEnabled ? @"true" : @"false",
  585. configSettings.minimumFetchInterval, configSettings.fetchTimeout);
  586. };
  587. dispatch_async(_queue, setConfigSettingsBlock);
  588. }
  589. #pragma clang diagnostic push // "-Wdeprecated-declarations"
  590. @end