FIRRemoteConfig.m 26 KB

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