FIRRemoteConfig.m 29 KB

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