RCNConfigContent.m 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  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/RCNConfigContent.h"
  17. #import "FirebaseRemoteConfig/Sources/Public/FirebaseRemoteConfig/FIRRemoteConfig.h"
  18. #import "FirebaseRemoteConfig/Sources/RCNConfigConstants.h"
  19. #import "FirebaseRemoteConfig/Sources/RCNConfigDBManager.h"
  20. #import "FirebaseRemoteConfig/Sources/RCNConfigDefines.h"
  21. #import "FirebaseRemoteConfig/Sources/RCNConfigValue_Internal.h"
  22. #import "FirebaseCore/Sources/Private/FirebaseCoreInternal.h"
  23. @implementation RCNConfigContent {
  24. /// Active config data that is currently used.
  25. NSMutableDictionary *_activeConfig;
  26. /// Pending config (aka Fetched config) data that is latest data from server that might or might
  27. /// not be applied.
  28. NSMutableDictionary *_fetchedConfig;
  29. /// Default config provided by user.
  30. NSMutableDictionary *_defaultConfig;
  31. /// Active Personalization metadata that is currently used.
  32. NSDictionary *_activePersonalization;
  33. /// Pending Personalization metadata that is latest data from server that might or might not be
  34. /// applied.
  35. NSDictionary *_fetchedPersonalization;
  36. /// DBManager
  37. RCNConfigDBManager *_DBManager;
  38. /// Current bundle identifier;
  39. NSString *_bundleIdentifier;
  40. /// Dispatch semaphore to block all config reads until we have read from the database. This only
  41. /// potentially blocks on the first read. Should be a no-wait for all subsequent reads once we
  42. /// have data read into memory from the database.
  43. dispatch_semaphore_t _configLoadFromDBSemaphore;
  44. /// Boolean indicating if initial DB load of fetched,active and default config has succeeded.
  45. BOOL _isConfigLoadFromDBCompleted;
  46. /// Boolean indicating that the load from database has initiated at least once.
  47. BOOL _isDatabaseLoadAlreadyInitiated;
  48. }
  49. /// Default timeout when waiting to read data from database.
  50. static const NSTimeInterval kDatabaseLoadTimeoutSecs = 30.0;
  51. /// Singleton instance of RCNConfigContent.
  52. + (instancetype)sharedInstance {
  53. static dispatch_once_t onceToken;
  54. static RCNConfigContent *sharedInstance;
  55. dispatch_once(&onceToken, ^{
  56. sharedInstance =
  57. [[RCNConfigContent alloc] initWithDBManager:[RCNConfigDBManager sharedInstance]];
  58. });
  59. return sharedInstance;
  60. }
  61. - (instancetype)init {
  62. NSAssert(NO, @"Invalid initializer.");
  63. return nil;
  64. }
  65. /// Designated initializer
  66. - (instancetype)initWithDBManager:(RCNConfigDBManager *)DBManager {
  67. self = [super init];
  68. if (self) {
  69. _activeConfig = [[NSMutableDictionary alloc] init];
  70. _fetchedConfig = [[NSMutableDictionary alloc] init];
  71. _defaultConfig = [[NSMutableDictionary alloc] init];
  72. _activePersonalization = [[NSDictionary alloc] init];
  73. _fetchedPersonalization = [[NSDictionary alloc] init];
  74. _bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];
  75. if (!_bundleIdentifier) {
  76. FIRLogNotice(kFIRLoggerRemoteConfig, @"I-RCN000038",
  77. @"Main bundle identifier is missing. Remote Config might not work properly.");
  78. _bundleIdentifier = @"";
  79. }
  80. _DBManager = DBManager;
  81. // Waits for both config and Personalization data to load.
  82. _configLoadFromDBSemaphore = dispatch_semaphore_create(1);
  83. [self loadConfigFromMainTable];
  84. }
  85. return self;
  86. }
  87. // Blocking call that returns true/false once database load completes / times out.
  88. // @return Initialization status.
  89. - (BOOL)initializationSuccessful {
  90. RCN_MUST_NOT_BE_MAIN_THREAD();
  91. BOOL isDatabaseLoadSuccessful = [self checkAndWaitForInitialDatabaseLoad];
  92. return isDatabaseLoadSuccessful;
  93. }
  94. #pragma mark - database
  95. /// This method is only meant to be called at init time. The underlying logic will need to be
  96. /// revaluated if the assumption changes at a later time.
  97. - (void)loadConfigFromMainTable {
  98. if (!_DBManager) {
  99. return;
  100. }
  101. NSAssert(!_isDatabaseLoadAlreadyInitiated, @"Database load has already been initiated");
  102. _isDatabaseLoadAlreadyInitiated = true;
  103. [_DBManager
  104. loadMainWithBundleIdentifier:_bundleIdentifier
  105. completionHandler:^(BOOL success, NSDictionary *fetchedConfig,
  106. NSDictionary *activeConfig, NSDictionary *defaultConfig) {
  107. self->_fetchedConfig = [fetchedConfig mutableCopy];
  108. self->_activeConfig = [activeConfig mutableCopy];
  109. self->_defaultConfig = [defaultConfig mutableCopy];
  110. dispatch_semaphore_signal(self->_configLoadFromDBSemaphore);
  111. }];
  112. [_DBManager loadPersonalizationWithCompletionHandler:^(
  113. BOOL success, NSDictionary *fetchedPersonalization,
  114. NSDictionary *activePersonalization, NSDictionary *defaultConfig) {
  115. self->_fetchedPersonalization = [fetchedPersonalization copy];
  116. self->_activePersonalization = [activePersonalization copy];
  117. dispatch_semaphore_signal(self->_configLoadFromDBSemaphore);
  118. }];
  119. }
  120. /// Update the current config result to main table.
  121. /// @param values Values in a row to write to the table.
  122. /// @param source The source the config data is coming from. It determines which table to write to.
  123. - (void)updateMainTableWithValues:(NSArray *)values fromSource:(RCNDBSource)source {
  124. [_DBManager insertMainTableWithValues:values fromSource:source completionHandler:nil];
  125. }
  126. #pragma mark - update
  127. /// This function is for copying dictionary when user set up a default config or when user clicks
  128. /// activate. For now the DBSource can only be Active or Default.
  129. - (void)copyFromDictionary:(NSDictionary *)fromDict
  130. toSource:(RCNDBSource)DBSource
  131. forNamespace:(NSString *)FIRNamespace {
  132. // Make sure database load has completed.
  133. [self checkAndWaitForInitialDatabaseLoad];
  134. NSMutableDictionary *toDict;
  135. if (!fromDict) {
  136. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000007",
  137. @"The source dictionary to copy from does not exist.");
  138. return;
  139. }
  140. FIRRemoteConfigSource source = FIRRemoteConfigSourceRemote;
  141. switch (DBSource) {
  142. case RCNDBSourceDefault:
  143. toDict = _defaultConfig;
  144. source = FIRRemoteConfigSourceDefault;
  145. break;
  146. case RCNDBSourceFetched:
  147. FIRLogWarning(kFIRLoggerRemoteConfig, @"I-RCN000008",
  148. @"This shouldn't happen. Destination dictionary should never be pending type.");
  149. return;
  150. case RCNDBSourceActive:
  151. toDict = _activeConfig;
  152. source = FIRRemoteConfigSourceRemote;
  153. [toDict removeObjectForKey:FIRNamespace];
  154. break;
  155. default:
  156. toDict = _activeConfig;
  157. source = FIRRemoteConfigSourceRemote;
  158. [toDict removeObjectForKey:FIRNamespace];
  159. break;
  160. }
  161. // Completely wipe out DB first.
  162. [_DBManager deleteRecordFromMainTableWithNamespace:FIRNamespace
  163. bundleIdentifier:_bundleIdentifier
  164. fromSource:DBSource];
  165. toDict[FIRNamespace] = [[NSMutableDictionary alloc] init];
  166. NSDictionary *config = fromDict[FIRNamespace];
  167. for (NSString *key in config) {
  168. if (DBSource == FIRRemoteConfigSourceDefault) {
  169. NSObject *value = config[key];
  170. NSData *valueData;
  171. if ([value isKindOfClass:[NSData class]]) {
  172. valueData = (NSData *)value;
  173. } else if ([value isKindOfClass:[NSString class]]) {
  174. valueData = [(NSString *)value dataUsingEncoding:NSUTF8StringEncoding];
  175. } else if ([value isKindOfClass:[NSNumber class]]) {
  176. NSString *strValue = [(NSNumber *)value stringValue];
  177. valueData = [(NSString *)strValue dataUsingEncoding:NSUTF8StringEncoding];
  178. } else if ([value isKindOfClass:[NSDate class]]) {
  179. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  180. [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
  181. NSString *strValue = [dateFormatter stringFromDate:(NSDate *)value];
  182. valueData = [(NSString *)strValue dataUsingEncoding:NSUTF8StringEncoding];
  183. } else {
  184. continue;
  185. }
  186. toDict[FIRNamespace][key] = [[FIRRemoteConfigValue alloc] initWithData:valueData
  187. source:source];
  188. NSArray *values = @[ _bundleIdentifier, FIRNamespace, key, valueData ];
  189. [self updateMainTableWithValues:values fromSource:DBSource];
  190. } else {
  191. FIRRemoteConfigValue *value = config[key];
  192. toDict[FIRNamespace][key] = [[FIRRemoteConfigValue alloc] initWithData:value.dataValue
  193. source:source];
  194. NSArray *values = @[ _bundleIdentifier, FIRNamespace, key, value.dataValue ];
  195. [self updateMainTableWithValues:values fromSource:DBSource];
  196. }
  197. }
  198. }
  199. - (void)updateConfigContentWithResponse:(NSDictionary *)response
  200. forNamespace:(NSString *)currentNamespace {
  201. // Make sure database load has completed.
  202. [self checkAndWaitForInitialDatabaseLoad];
  203. NSString *state = response[RCNFetchResponseKeyState];
  204. if (!state) {
  205. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000049", @"State field in fetch response is nil.");
  206. return;
  207. }
  208. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000059",
  209. @"Updating config content from Response for namespace:%@ with state: %@",
  210. currentNamespace, response[RCNFetchResponseKeyState]);
  211. if ([state isEqualToString:RCNFetchResponseKeyStateNoChange]) {
  212. [self handleNoChangeStateForConfigNamespace:currentNamespace];
  213. return;
  214. }
  215. /// Handle empty config state
  216. if ([state isEqualToString:RCNFetchResponseKeyStateEmptyConfig]) {
  217. [self handleEmptyConfigStateForConfigNamespace:currentNamespace];
  218. return;
  219. }
  220. /// Handle no template state.
  221. if ([state isEqualToString:RCNFetchResponseKeyStateNoTemplate]) {
  222. [self handleNoTemplateStateForConfigNamespace:currentNamespace];
  223. return;
  224. }
  225. /// Handle update state
  226. if ([state isEqualToString:RCNFetchResponseKeyStateUpdate]) {
  227. [self handleUpdateStateForConfigNamespace:currentNamespace
  228. withEntries:response[RCNFetchResponseKeyEntries]];
  229. [self handleUpdatePersonalization:response[RCNFetchResponseKeyPersonalizationMetadata]];
  230. return;
  231. }
  232. }
  233. - (void)activatePersonalization {
  234. _activePersonalization = _fetchedPersonalization;
  235. [_DBManager insertOrUpdatePersonalizationConfig:_activePersonalization
  236. fromSource:RCNDBSourceActive];
  237. }
  238. #pragma mark State handling
  239. - (void)handleNoChangeStateForConfigNamespace:(NSString *)currentNamespace {
  240. if (!_fetchedConfig[currentNamespace]) {
  241. _fetchedConfig[currentNamespace] = [[NSMutableDictionary alloc] init];
  242. }
  243. }
  244. - (void)handleEmptyConfigStateForConfigNamespace:(NSString *)currentNamespace {
  245. if (_fetchedConfig[currentNamespace]) {
  246. [_fetchedConfig[currentNamespace] removeAllObjects];
  247. } else {
  248. // If namespace has empty status and it doesn't exist in _fetchedConfig, we will
  249. // still add an entry for that namespace. Even if it will not be persisted in database.
  250. // TODO: Add generics for all collection types.
  251. _fetchedConfig[currentNamespace] = [[NSMutableDictionary alloc] init];
  252. }
  253. [_DBManager deleteRecordFromMainTableWithNamespace:currentNamespace
  254. bundleIdentifier:_bundleIdentifier
  255. fromSource:RCNDBSourceFetched];
  256. }
  257. - (void)handleNoTemplateStateForConfigNamespace:(NSString *)currentNamespace {
  258. // Remove the namespace.
  259. [_fetchedConfig removeObjectForKey:currentNamespace];
  260. [_DBManager deleteRecordFromMainTableWithNamespace:currentNamespace
  261. bundleIdentifier:_bundleIdentifier
  262. fromSource:RCNDBSourceFetched];
  263. }
  264. - (void)handleUpdateStateForConfigNamespace:(NSString *)currentNamespace
  265. withEntries:(NSDictionary *)entries {
  266. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000058", @"Update config in DB for namespace:%@",
  267. currentNamespace);
  268. // Clear before updating
  269. [_DBManager deleteRecordFromMainTableWithNamespace:currentNamespace
  270. bundleIdentifier:_bundleIdentifier
  271. fromSource:RCNDBSourceFetched];
  272. if ([_fetchedConfig objectForKey:currentNamespace]) {
  273. [_fetchedConfig[currentNamespace] removeAllObjects];
  274. } else {
  275. _fetchedConfig[currentNamespace] = [[NSMutableDictionary alloc] init];
  276. }
  277. // Store the fetched config values.
  278. for (NSString *key in entries) {
  279. NSData *valueData = [entries[key] dataUsingEncoding:NSUTF8StringEncoding];
  280. if (!valueData) {
  281. continue;
  282. }
  283. _fetchedConfig[currentNamespace][key] =
  284. [[FIRRemoteConfigValue alloc] initWithData:valueData source:FIRRemoteConfigSourceRemote];
  285. NSArray *values = @[ _bundleIdentifier, currentNamespace, key, valueData ];
  286. [self updateMainTableWithValues:values fromSource:RCNDBSourceFetched];
  287. }
  288. }
  289. - (void)handleUpdatePersonalization:(NSDictionary *)metadata {
  290. if (!metadata) {
  291. return;
  292. }
  293. _fetchedPersonalization = metadata;
  294. [_DBManager insertOrUpdatePersonalizationConfig:metadata fromSource:RCNDBSourceFetched];
  295. }
  296. #pragma mark - getter/setter
  297. - (NSDictionary *)fetchedConfig {
  298. /// If this is the first time reading the fetchedConfig, we might still be reading it from the
  299. /// database.
  300. [self checkAndWaitForInitialDatabaseLoad];
  301. return _fetchedConfig;
  302. }
  303. - (NSDictionary *)activeConfig {
  304. /// If this is the first time reading the activeConfig, we might still be reading it from the
  305. /// database.
  306. [self checkAndWaitForInitialDatabaseLoad];
  307. return _activeConfig;
  308. }
  309. - (NSDictionary *)defaultConfig {
  310. /// If this is the first time reading the fetchedConfig, we might still be reading it from the
  311. /// database.
  312. [self checkAndWaitForInitialDatabaseLoad];
  313. return _defaultConfig;
  314. }
  315. - (NSDictionary *)getConfigAndMetadataForNamespace:(NSString *)FIRNamespace {
  316. /// If this is the first time reading the active metadata, we might still be reading it from the
  317. /// database.
  318. [self checkAndWaitForInitialDatabaseLoad];
  319. return @{
  320. RCNFetchResponseKeyEntries : _activeConfig[FIRNamespace],
  321. RCNFetchResponseKeyPersonalizationMetadata : _activePersonalization
  322. };
  323. }
  324. /// We load the database async at init time. Block all further calls to active/fetched/default
  325. /// configs until load is done.
  326. /// @return Database load completion status.
  327. - (BOOL)checkAndWaitForInitialDatabaseLoad {
  328. /// Wait on semaphore until done. This should be a no-op for subsequent calls.
  329. if (!_isConfigLoadFromDBCompleted) {
  330. long result = dispatch_semaphore_wait(
  331. _configLoadFromDBSemaphore,
  332. dispatch_time(DISPATCH_TIME_NOW, (int64_t)(kDatabaseLoadTimeoutSecs * NSEC_PER_SEC)));
  333. if (result != 0) {
  334. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000048",
  335. @"Timed out waiting for fetched config to be loaded from DB");
  336. return false;
  337. }
  338. _isConfigLoadFromDBCompleted = true;
  339. }
  340. return true;
  341. }
  342. @end