RCNConfigContent.m 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  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. _configLoadFromDBSemaphore = dispatch_semaphore_create(0);
  82. [self loadConfigFromMainTable];
  83. }
  84. return self;
  85. }
  86. // Blocking call that returns true/false once database load completes / times out.
  87. // @return Initialization status.
  88. - (BOOL)initializationSuccessful {
  89. RCN_MUST_NOT_BE_MAIN_THREAD();
  90. BOOL isDatabaseLoadSuccessful = [self checkAndWaitForInitialDatabaseLoad];
  91. return isDatabaseLoadSuccessful;
  92. }
  93. #pragma mark - database
  94. /// This method is only meant to be called at init time. The underlying logic will need to be
  95. /// revaluated if the assumption changes at a later time.
  96. - (void)loadConfigFromMainTable {
  97. if (!_DBManager) {
  98. return;
  99. }
  100. NSAssert(!_isDatabaseLoadAlreadyInitiated, @"Database load has already been initiated");
  101. _isDatabaseLoadAlreadyInitiated = true;
  102. [_DBManager
  103. loadMainWithBundleIdentifier:_bundleIdentifier
  104. completionHandler:^(BOOL success, NSDictionary *fetchedConfig,
  105. NSDictionary *activeConfig, NSDictionary *defaultConfig) {
  106. self->_fetchedConfig = [fetchedConfig mutableCopy];
  107. self->_activeConfig = [activeConfig mutableCopy];
  108. self->_defaultConfig = [defaultConfig mutableCopy];
  109. dispatch_semaphore_signal(self->_configLoadFromDBSemaphore);
  110. }];
  111. // TODO(karenzeng): Refactor personalization to be returned in loadMainWithBundleIdentifier above
  112. [_DBManager loadPersonalizationWithCompletionHandler:^(
  113. BOOL success, NSDictionary *fetchedPersonalization,
  114. NSDictionary *activePersonalization, NSDictionary *defaultConfig) {
  115. self->_fetchedPersonalization = [fetchedPersonalization copy];
  116. self->_activePersonalization = [activePersonalization copy];
  117. }];
  118. }
  119. /// Update the current config result to main table.
  120. /// @param values Values in a row to write to the table.
  121. /// @param source The source the config data is coming from. It determines which table to write to.
  122. - (void)updateMainTableWithValues:(NSArray *)values fromSource:(RCNDBSource)source {
  123. [_DBManager insertMainTableWithValues:values fromSource:source completionHandler:nil];
  124. }
  125. #pragma mark - update
  126. /// This function is for copying dictionary when user set up a default config or when user clicks
  127. /// activate. For now the DBSource can only be Active or Default.
  128. - (void)copyFromDictionary:(NSDictionary *)fromDict
  129. toSource:(RCNDBSource)DBSource
  130. forNamespace:(NSString *)FIRNamespace {
  131. // Make sure database load has completed.
  132. [self checkAndWaitForInitialDatabaseLoad];
  133. NSMutableDictionary *toDict;
  134. if (!fromDict) {
  135. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000007",
  136. @"The source dictionary to copy from does not exist.");
  137. return;
  138. }
  139. FIRRemoteConfigSource source = FIRRemoteConfigSourceRemote;
  140. switch (DBSource) {
  141. case RCNDBSourceDefault:
  142. toDict = _defaultConfig;
  143. source = FIRRemoteConfigSourceDefault;
  144. break;
  145. case RCNDBSourceFetched:
  146. FIRLogWarning(kFIRLoggerRemoteConfig, @"I-RCN000008",
  147. @"This shouldn't happen. Destination dictionary should never be pending type.");
  148. return;
  149. case RCNDBSourceActive:
  150. toDict = _activeConfig;
  151. source = FIRRemoteConfigSourceRemote;
  152. [toDict removeObjectForKey:FIRNamespace];
  153. break;
  154. default:
  155. toDict = _activeConfig;
  156. source = FIRRemoteConfigSourceRemote;
  157. [toDict removeObjectForKey:FIRNamespace];
  158. break;
  159. }
  160. // Completely wipe out DB first.
  161. [_DBManager deleteRecordFromMainTableWithNamespace:FIRNamespace
  162. bundleIdentifier:_bundleIdentifier
  163. fromSource:DBSource];
  164. toDict[FIRNamespace] = [[NSMutableDictionary alloc] init];
  165. NSDictionary *config = fromDict[FIRNamespace];
  166. for (NSString *key in config) {
  167. if (DBSource == FIRRemoteConfigSourceDefault) {
  168. NSObject *value = config[key];
  169. NSData *valueData;
  170. if ([value isKindOfClass:[NSData class]]) {
  171. valueData = (NSData *)value;
  172. } else if ([value isKindOfClass:[NSString class]]) {
  173. valueData = [(NSString *)value dataUsingEncoding:NSUTF8StringEncoding];
  174. } else if ([value isKindOfClass:[NSNumber class]]) {
  175. NSString *strValue = [(NSNumber *)value stringValue];
  176. valueData = [(NSString *)strValue dataUsingEncoding:NSUTF8StringEncoding];
  177. } else if ([value isKindOfClass:[NSDate class]]) {
  178. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  179. [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
  180. NSString *strValue = [dateFormatter stringFromDate:(NSDate *)value];
  181. valueData = [(NSString *)strValue dataUsingEncoding:NSUTF8StringEncoding];
  182. } else {
  183. continue;
  184. }
  185. toDict[FIRNamespace][key] = [[FIRRemoteConfigValue alloc] initWithData:valueData
  186. source:source];
  187. NSArray *values = @[ _bundleIdentifier, FIRNamespace, key, valueData ];
  188. [self updateMainTableWithValues:values fromSource:DBSource];
  189. } else {
  190. FIRRemoteConfigValue *value = config[key];
  191. toDict[FIRNamespace][key] = [[FIRRemoteConfigValue alloc] initWithData:value.dataValue
  192. source:source];
  193. NSArray *values = @[ _bundleIdentifier, FIRNamespace, key, value.dataValue ];
  194. [self updateMainTableWithValues:values fromSource:DBSource];
  195. }
  196. }
  197. }
  198. - (void)updateConfigContentWithResponse:(NSDictionary *)response
  199. forNamespace:(NSString *)currentNamespace {
  200. // Make sure database load has completed.
  201. [self checkAndWaitForInitialDatabaseLoad];
  202. NSString *state = response[RCNFetchResponseKeyState];
  203. if (!state) {
  204. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000049", @"State field in fetch response is nil.");
  205. return;
  206. }
  207. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000059",
  208. @"Updating config content from Response for namespace:%@ with state: %@",
  209. currentNamespace, response[RCNFetchResponseKeyState]);
  210. if ([state isEqualToString:RCNFetchResponseKeyStateNoChange]) {
  211. [self handleNoChangeStateForConfigNamespace:currentNamespace];
  212. return;
  213. }
  214. /// Handle empty config state
  215. if ([state isEqualToString:RCNFetchResponseKeyStateEmptyConfig]) {
  216. [self handleEmptyConfigStateForConfigNamespace:currentNamespace];
  217. return;
  218. }
  219. /// Handle no template state.
  220. if ([state isEqualToString:RCNFetchResponseKeyStateNoTemplate]) {
  221. [self handleNoTemplateStateForConfigNamespace:currentNamespace];
  222. return;
  223. }
  224. /// Handle update state
  225. if ([state isEqualToString:RCNFetchResponseKeyStateUpdate]) {
  226. [self handleUpdateStateForConfigNamespace:currentNamespace
  227. withEntries:response[RCNFetchResponseKeyEntries]];
  228. [self handleUpdatePersonalization:response[RCNFetchResponseKeyPersonalizationMetadata]];
  229. return;
  230. }
  231. }
  232. - (void)activatePersonalization {
  233. _activePersonalization = _fetchedPersonalization;
  234. [_DBManager insertOrUpdatePersonalizationConfig:_activePersonalization
  235. fromSource:RCNDBSourceActive];
  236. }
  237. #pragma mark State handling
  238. - (void)handleNoChangeStateForConfigNamespace:(NSString *)currentNamespace {
  239. if (!_fetchedConfig[currentNamespace]) {
  240. _fetchedConfig[currentNamespace] = [[NSMutableDictionary alloc] init];
  241. }
  242. }
  243. - (void)handleEmptyConfigStateForConfigNamespace:(NSString *)currentNamespace {
  244. if (_fetchedConfig[currentNamespace]) {
  245. [_fetchedConfig[currentNamespace] removeAllObjects];
  246. } else {
  247. // If namespace has empty status and it doesn't exist in _fetchedConfig, we will
  248. // still add an entry for that namespace. Even if it will not be persisted in database.
  249. // TODO: Add generics for all collection types.
  250. _fetchedConfig[currentNamespace] = [[NSMutableDictionary alloc] init];
  251. }
  252. [_DBManager deleteRecordFromMainTableWithNamespace:currentNamespace
  253. bundleIdentifier:_bundleIdentifier
  254. fromSource:RCNDBSourceFetched];
  255. }
  256. - (void)handleNoTemplateStateForConfigNamespace:(NSString *)currentNamespace {
  257. // Remove the namespace.
  258. [_fetchedConfig removeObjectForKey:currentNamespace];
  259. [_DBManager deleteRecordFromMainTableWithNamespace:currentNamespace
  260. bundleIdentifier:_bundleIdentifier
  261. fromSource:RCNDBSourceFetched];
  262. }
  263. - (void)handleUpdateStateForConfigNamespace:(NSString *)currentNamespace
  264. withEntries:(NSDictionary *)entries {
  265. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000058", @"Update config in DB for namespace:%@",
  266. currentNamespace);
  267. // Clear before updating
  268. [_DBManager deleteRecordFromMainTableWithNamespace:currentNamespace
  269. bundleIdentifier:_bundleIdentifier
  270. fromSource:RCNDBSourceFetched];
  271. if ([_fetchedConfig objectForKey:currentNamespace]) {
  272. [_fetchedConfig[currentNamespace] removeAllObjects];
  273. } else {
  274. _fetchedConfig[currentNamespace] = [[NSMutableDictionary alloc] init];
  275. }
  276. // Store the fetched config values.
  277. for (NSString *key in entries) {
  278. NSData *valueData = [entries[key] dataUsingEncoding:NSUTF8StringEncoding];
  279. if (!valueData) {
  280. continue;
  281. }
  282. _fetchedConfig[currentNamespace][key] =
  283. [[FIRRemoteConfigValue alloc] initWithData:valueData source:FIRRemoteConfigSourceRemote];
  284. NSArray *values = @[ _bundleIdentifier, currentNamespace, key, valueData ];
  285. [self updateMainTableWithValues:values fromSource:RCNDBSourceFetched];
  286. }
  287. }
  288. - (void)handleUpdatePersonalization:(NSDictionary *)metadata {
  289. if (!metadata) {
  290. return;
  291. }
  292. _fetchedPersonalization = metadata;
  293. [_DBManager insertOrUpdatePersonalizationConfig:metadata fromSource:RCNDBSourceFetched];
  294. }
  295. #pragma mark - getter/setter
  296. - (NSDictionary *)fetchedConfig {
  297. /// If this is the first time reading the fetchedConfig, we might still be reading it from the
  298. /// database.
  299. [self checkAndWaitForInitialDatabaseLoad];
  300. return _fetchedConfig;
  301. }
  302. - (NSDictionary *)activeConfig {
  303. /// If this is the first time reading the activeConfig, we might still be reading it from the
  304. /// database.
  305. [self checkAndWaitForInitialDatabaseLoad];
  306. return _activeConfig;
  307. }
  308. - (NSDictionary *)defaultConfig {
  309. /// If this is the first time reading the fetchedConfig, we might still be reading it from the
  310. /// database.
  311. [self checkAndWaitForInitialDatabaseLoad];
  312. return _defaultConfig;
  313. }
  314. - (NSDictionary *)getConfigAndMetadataForNamespace:(NSString *)FIRNamespace {
  315. /// If this is the first time reading the active metadata, we might still be reading it from the
  316. /// database.
  317. [self checkAndWaitForInitialDatabaseLoad];
  318. return @{
  319. RCNFetchResponseKeyEntries : _activeConfig[FIRNamespace],
  320. RCNFetchResponseKeyPersonalizationMetadata : _activePersonalization
  321. };
  322. }
  323. /// We load the database async at init time. Block all further calls to active/fetched/default
  324. /// configs until load is done.
  325. /// @return Database load completion status.
  326. - (BOOL)checkAndWaitForInitialDatabaseLoad {
  327. /// Wait on semaphore until done. This should be a no-op for subsequent calls.
  328. if (!_isConfigLoadFromDBCompleted) {
  329. long result = dispatch_semaphore_wait(
  330. _configLoadFromDBSemaphore,
  331. dispatch_time(DISPATCH_TIME_NOW, (int64_t)(kDatabaseLoadTimeoutSecs * NSEC_PER_SEC)));
  332. if (result != 0) {
  333. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000048",
  334. @"Timed out waiting for fetched config to be loaded from DB");
  335. return false;
  336. }
  337. _isConfigLoadFromDBCompleted = true;
  338. }
  339. return true;
  340. }
  341. @end