FIRRemoteConfig.m 34 KB

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