FIRRemoteConfig.m 34 KB

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