RCNConfigContent.swift 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. import Foundation
  2. class RCNConfigContent {
  3. /// Active config data that is currently used.
  4. private var _activeConfig: NSMutableDictionary
  5. /// Pending config (aka Fetched config) data that is latest data from server that might or might
  6. /// not be applied.
  7. private var _fetchedConfig: NSMutableDictionary
  8. /// Default config provided by user.
  9. private var _defaultConfig: NSMutableDictionary
  10. /// Active Personalization metadata that is currently used.
  11. private var _activePersonalization: NSDictionary
  12. /// Pending Personalization metadata that is latest data from server that might or might not be
  13. /// applied.
  14. private var _fetchedPersonalization: NSDictionary
  15. /// Active Rollout metadata that is currently used.
  16. private var _activeRolloutMetadata: [NSDictionary]
  17. /// Pending Rollout metadata that is latest data from server that might or might not be applied.
  18. private var _fetchedRolloutMetadata: [NSDictionary]
  19. /// DBManager
  20. private var _DBManager: RCNConfigDBManager?
  21. /// Current bundle identifier;
  22. private var _bundleIdentifier: String
  23. /// Blocks all config reads until we have read from the database. This only
  24. /// potentially blocks on the first read. Should be a no-wait for all subsequent reads once we
  25. /// have data read into memory from the database.
  26. private var _dispatch_group: DispatchGroup
  27. /// Boolean indicating if initial DB load of fetched,active and default config has succeeded.
  28. private var _isConfigLoadFromDBCompleted: Bool
  29. /// Boolean indicating that the load from database has initiated at least once.
  30. private var _isDatabaseLoadAlreadyInitiated: Bool
  31. static let sharedInstance = RCNConfigContent(DBManager: RCNConfigDBManager.sharedInstance())
  32. init(DBManager: RCNConfigDBManager) {
  33. _activeConfig = NSMutableDictionary()
  34. _fetchedConfig = NSMutableDictionary()
  35. _defaultConfig = NSMutableDictionary()
  36. _activePersonalization = [:]
  37. _fetchedPersonalization = [:]
  38. _activeRolloutMetadata = []
  39. _fetchedRolloutMetadata = []
  40. _bundleIdentifier = Bundle.main.bundleIdentifier ?? ""
  41. if _bundleIdentifier == "" {
  42. FIRLogNotice(RCNRemoteConfigQueueLabel, @"I-RCN000038",
  43. "Main bundle identifier is missing. Remote Config might not work properly.")
  44. }
  45. _DBManager = DBManager
  46. // Waits for both config and Personalization data to load.
  47. _dispatch_group = DispatchGroup()
  48. loadConfigFromMainTable()
  49. }
  50. // MARK: - Database
  51. func loadConfigFromMainTable() {
  52. if _DBManager == nil {
  53. return
  54. }
  55. NSAssert(!_isDatabaseLoadAlreadyInitiated, "Database load has already been initiated")
  56. _isDatabaseLoadAlreadyInitiated = true
  57. _dispatch_group.enter()
  58. _DBManager?.loadMain(bundleIdentifier: _bundleIdentifier ?? "") {
  59. success, fetchedConfig, activeConfig, defaultConfig, rolloutMetadata in
  60. self.fetchedConfig = fetchedConfig?.mutableCopy() ?? NSMutableDictionary()
  61. self.activeConfig = activeConfig?.mutableCopy() ?? NSMutableDictionary()
  62. self.defaultConfig = defaultConfig?.mutableCopy() ?? NSMutableDictionary()
  63. self->_fetchedRolloutMetadata = rolloutMetadata[RCNRolloutTableKeyFetchedMetadata] as? [NSDictionary] ?? []
  64. self->_activeRolloutMetadata = rolloutMetadata[RCNRolloutTableKeyActiveMetadata] as? [NSDictionary] ?? []
  65. self->_isConfigLoadFromDBCompleted = true
  66. self->_isDatabaseLoadAlreadyInitiated = true
  67. self.loadPersonalization(completionHandler: {(success, fetchedPersonalization, activePersonalization,
  68. defaultConfig, rolloutsMetadata) in
  69. self->_fetchedPersonalization = fetchedPersonalization ?? [:]
  70. self->_activePersonalization = activePersonalization ?? [:]
  71. })
  72. _dispatch_group.leave()
  73. }
  74. }
  75. func copyFromDictionary(from fromDict: [String : Any], toSource source: RCNDBSource,
  76. forNamespace namespace: String) {
  77. // Make sure database load has completed.
  78. checkAndWaitForInitialDatabaseLoad()
  79. var toDict = NSMutableDictionary()
  80. var source : FIRRemoteConfigSource = .remote
  81. switch source {
  82. case .active:
  83. toDict = _activeConfig
  84. source = .remote
  85. // Completely wipe out DB first.
  86. _DBManager?.deleteRecordFromMainTable(namespace: namespace, bundleIdentifier: self.bundleIdentifier ?? "", fromSource: .active)
  87. break
  88. case .`default`:
  89. toDict = _defaultConfig
  90. source = .default
  91. break
  92. default:
  93. toDict = _activeConfig
  94. source = .remote
  95. break
  96. }
  97. toDict[FIRNamespace] = [:]
  98. let config = fromDict[FIRNamespace] as! [String : Any]
  99. for key in config {
  100. if (source == .default) {
  101. let value = config[key] as! NSObject
  102. var valueData: NSData? = nil
  103. if let value = value as? NSData {
  104. valueData = value
  105. } else if let value = value as? String {
  106. valueData = value.data(using: .utf8)
  107. } else if let value = value as? NSNumber {
  108. valueData = [(NSNumber *)value stringValue].data(using: .utf8)
  109. } else if let value = value as? NSDate {
  110. let dateFormatter = DateFormatter()
  111. dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
  112. let strValue = dateFormatter.string(from: value as! Date)
  113. valueData = strValue.data(using: .utf8)
  114. } else if let value = value as? NSArray {
  115. do {
  116. valueData = try JSONSerialization.data(withJSONObject: value, options: [])
  117. } catch {
  118. print("invalid array value for key \(key)")
  119. }
  120. } else if let value = value as? NSDictionary {
  121. do {
  122. valueData = try JSONSerialization.data(withJSONObject: value, options: [])
  123. } catch {
  124. print("invalid dictionary value for key \(key)")
  125. }
  126. } else {
  127. continue
  128. }
  129. _fetchedConfig[FIRNamespace][key] = FIRRemoteConfigValue(data: valueData, source: source)
  130. let values = [_bundleIdentifier, FIRNamespace, key, valueData] as [Any]
  131. //[self updateMainTableWithValues:values fromSource:DBSource]
  132. } else {
  133. guard let value = config[key] as? FIRRemoteConfigValue else {
  134. continue
  135. }
  136. _fetchedConfig[FIRNamespace][key] =
  137. FIRRemoteConfigValue(data: value.dataValue, source: source)
  138. let values = [_bundleIdentifier, FIRNamespace, key, value.dataValue] as [Any]
  139. }
  140. }
  141. }
  142. func checkAndWaitForInitialDatabaseLoad() -> Bool {
  143. RCN_MUST_NOT_BE_MAIN_THREAD()
  144. // Block all further calls to active/fetched/default
  145. // configs until load is done.
  146. if (!_isConfigLoadFromDBCompleted) {
  147. let _ = _dispatch_group.wait(timeout: .now() + kDatabaseLoadTimeoutSecs)
  148. }
  149. _isConfigLoadFromDBCompleted = true;
  150. return true
  151. }
  152. //MARK - DB
  153. func updateMainTableWithValues(values: [Any], fromSource: RCNDBSource) {
  154. _DBManager?.insertMainTableWithValues(values: values, fromSource: source, completionHandler: nil)
  155. }
  156. //MARK - Update
  157. func copyFromDictionary(from fromDict: [String : Any], toSource toSource: RCNDBSource, forNamespace: String) {
  158. if !fromDict.isEmpty {
  159. FIRLogError(RCNRemoteConfigQueueLabel, "I-RCN000007",
  160. "The source dictionary to copy from does not exist.")
  161. return;
  162. }
  163. var toDict = NSMutableDictionary()
  164. var source : FIRRemoteConfigSource = .remote
  165. switch toSource {
  166. case .default:
  167. toDict = _defaultConfig;
  168. break;
  169. case .fetched:
  170. FIRLogWarning(RCNRemoteConfigQueueLabel, "I-RCN000008",
  171. "This shouldn't happen. Destination dictionary should never be pending type.")
  172. return;
  173. case .active:
  174. toDict = _activeConfig;
  175. [toDict removeAllObjects];
  176. break;
  177. default:
  178. toDict = _activeConfig;
  179. [toDict removeAllObjects];
  180. break;
  181. }
  182. }
  183. func updateConfigContentWithResponse(response: [String : Any], forNamespace currentNamespace: String) {
  184. // Make sure database load has completed.
  185. checkAndWaitForInitialDatabaseLoad()
  186. guard let state = response[RCNFetchResponseKeyState] as? String else {
  187. return
  188. }
  189. FIRLogDebug(RCNRemoteConfigQueueLabel, "I-RCN000059",
  190. "Updating config content from Response for namespace:\(currentNamespace) with state: %@",
  191. response[RCNFetchResponseKeyState] ?? "")
  192. if state == RCNFetchResponseKeyStateNoChange {
  193. handleNoChangeStateForConfigNamespace(currentNamespace: currentNamespace)
  194. } else if state == RCNFetchResponseKeyStateEmptyConfig {
  195. handleEmptyConfigStateForConfigNamespace(currentNamespace: currentNamespace)
  196. return;
  197. } else if ([state isEqualToString:RCNFetchResponseKeyStateNoTemplate]) {
  198. handleNoTemplateStateForConfigNamespace(currentNamespace: currentNamespace)
  199. return;
  200. } else if ([state isEqualToString:RCNFetchResponseKeyStateUpdate]) {
  201. handleUpdateStateForConfigNamespace(currentNamespace: currentNamespace, withEntries: response[RCNFetchResponseKeyEntries] as! [String : String])
  202. handleUpdatePersonalization(metadata: response[RCNFetchResponseKeyPersonalizationMetadata] as? [String : Any])
  203. handleUpdateRolloutFetchedMetadata(metadata: response[RCNFetchResponseKeyRolloutMetadata] as? [NSDictionary])
  204. return;
  205. }
  206. return;
  207. }
  208. // MARK: - Private
  209. func handleNoChangeStateForConfigNamespace(currentNamespace: String) {
  210. if _fetchedConfig[currentNamespace] == nil {
  211. _fetchedConfig[currentNamespace] = [[NSMutableDictionary alloc] init];
  212. }
  213. }
  214. func handleEmptyConfigStateForConfigNamespace(currentNamespace: String) {
  215. if (_fetchedConfig[currentNamespace] != nil) {
  216. _fetchedConfig[currentNamespace].removeAllObjects()
  217. } else {
  218. // If namespace has empty status and it doesn't exist in _fetchedConfig, we will
  219. // still add an entry for that namespace. Even if it will not be persisted in database.
  220. // TODO: Add generics for all collection types.
  221. _fetchedConfig[currentNamespace] = [[NSMutableDictionary alloc] init];
  222. }
  223. _DBManager?.deleteRecordFromMainTable(namespace: currentNamespace,
  224. bundleIdentifier: _bundleIdentifier,
  225. fromSource: .fetched);
  226. }
  227. func handleNoTemplateStateForConfigNamespace(currentNamespace: String) {
  228. // Remove the namespace.
  229. _fetchedConfig.removeValue(forKey: currentNamespace)
  230. _DBManager?.deleteRecordFromMainTable(namespace: currentNamespace,
  231. bundleIdentifier: _bundleIdentifier,
  232. fromSource: .fetched);
  233. }
  234. func handleUpdateStateForConfigNamespace(currentNamespace: String, withEntries: [String: String]) {
  235. FIRLogDebug(RCNRemoteConfigQueueLabel, "I-RCN000058", "Update config in DB for namespace:\(currentNamespace)");
  236. // Clear before updating
  237. _DBManager?.deleteRecordFromMainTable(namespace: currentNamespace,
  238. bundleIdentifier: _bundleIdentifier,
  239. fromSource: .fetched);
  240. if (_fetchedConfig[currentNamespace] != nil) {
  241. _fetchedConfig[currentNamespace].removeAllObjects();
  242. } else {
  243. _fetchedConfig[currentNamespace] = [[NSMutableDictionary alloc] init];
  244. }
  245. // Store the fetched config values.
  246. for key in entries.keys {
  247. let valueData = entries[key]?.data(using: .utf8)
  248. _fetchedConfig[currentNamespace][key] = FIRRemoteConfigValue(data: valueData, source: .remote)
  249. let values = [_bundleIdentifier, FIRNamespace, key, valueData] as [Any];
  250. }
  251. }
  252. func handleUpdatePersonalization(metadata: [String : Any]?) {
  253. if metadata == nil {
  254. return;
  255. }
  256. _fetchedPersonalization = metadata ?? [:]
  257. [_DBManager insertOrUpdatePersonalizationConfig:metadata ?? [:] fromSource: .fetched]
  258. }
  259. func handleUpdateRolloutFetchedMetadata(metadata: [NSDictionary]?) {
  260. if (metadata == nil) {
  261. return
  262. }
  263. _fetchedRolloutMetadata = metadata ?? []
  264. [_DBManager insertOrUpdateRolloutTableWithKey:RCNRolloutTableKeyFetchedMetadata
  265. value:_fetchedRolloutMetadata completionHandler:nil];
  266. }
  267. func initializationSuccessful() -> Bool{
  268. return true
  269. }
  270. //MARK - Get Config
  271. func defaultValueForFullyQualifiedNamespace(namespace:String, key:String) -> FIRRemoteConfigValue{
  272. let value = self.defaultConfig[namespace]?[key];
  273. if value == nil {
  274. return FIRRemoteConfigValue(data: Data(), source: .static);
  275. }
  276. return value ?? FIRRemoteConfigValue(data: Data(), source: .static)
  277. }
  278. func checkAndWaitForInitialDatabaseLoad() -> Bool {
  279. /// Wait until load is done. This should be a no-op for subsequent calls.
  280. if (!_isConfigLoadFromDBCompleted) {
  281. let _ = _dispatch_group.wait(timeout: DispatchTime.now() + kDatabaseLoadTimeoutSecs)
  282. // Wait until load is done. This should be a no-op for subsequent calls.
  283. //_isConfigLoadFromDBCompleted = true
  284. }
  285. return true
  286. }
  287. //MARK - update main table
  288. func updateMainTableWithValues(values: [Any], fromSource: RCNDBSource) {
  289. _DBManager?.insertMainTableWithValues(values: values, fromSource: .fetched, completionHandler: nil)
  290. }
  291. func updateConfigContent(response: [String : Any], forNamespace currentNamespace: String) {
  292. // Make sure database load has completed.
  293. checkAndWaitForInitialDatabaseLoad()
  294. guard let state = response[RCNFetchResponseKeyState] as? String else {
  295. return
  296. }
  297. FIRLogDebug(RCNRemoteConfigQueueLabel, "I-RCN000059",
  298. "Updating config content from Response for namespace:\(currentNamespace) with state: %@",
  299. response[RCNFetchResponseKeyState] ?? "")
  300. if state == RCNFetchResponseKeyStateNoChange {
  301. handleNoChangeStateForConfigNamespace(currentNamespace: currentNamespace)
  302. } else if state == RCNFetchResponseKeyStateEmptyConfig {
  303. handleEmptyConfigStateForConfigNamespace(currentNamespace: currentNamespace)
  304. return;
  305. } else if ([state isEqualToString:RCNFetchResponseKeyStateNoTemplate]) {
  306. handleNoTemplateStateForConfigNamespace(currentNamespace: currentNamespace)
  307. return;
  308. } else if ([state isEqualToString:RCNFetchResponseKeyStateUpdate]) {
  309. handleUpdateStateForConfigNamespace(currentNamespace: currentNamespace,
  310. withEntries: response[RCNFetchResponseKeyEntries] as! [String : String])
  311. handleUpdatePersonalization(metadata: response[RCNFetchResponseKeyPersonalizationMetadata] as? [String : Any])
  312. handleUpdateRolloutFetchedMetadata(metadata: response[RCNFetchResponseKeyRolloutMetadata] as? [NSDictionary])
  313. return;
  314. }
  315. }
  316. func handleNoChangeStateForConfigNamespace(currentNamespace: String) {
  317. if _fetchedConfig[currentNamespace] == nil {
  318. _fetchedConfig[currentNamespace] = NSMutableDictionary()
  319. }
  320. }
  321. func handleEmptyConfigStateForConfigNamespace(currentNamespace: String) {
  322. if _fetchedConfig[currentNamespace] != nil {
  323. _fetchedConfig[currentNamespace].removeAllObjects()
  324. } else {
  325. // If namespace has empty status and it doesn't exist in _fetchedConfig, we will
  326. // still add an entry for that namespace. Even if it will not be persisted in database.
  327. // TODO: Add generics for all collection types.
  328. _fetchedConfig[currentNamespace] = NSMutableDictionary()
  329. }
  330. _DBManager?.deleteRecordFromMainTable(namespace: currentNamespace, bundleIdentifier: _bundleIdentifier, fromSource: .fetched)
  331. }
  332. func handleNoTemplateStateForConfigNamespace(currentNamespace: String) {
  333. // Remove the namespace.
  334. _fetchedConfig.removeValue(forKey: currentNamespace)
  335. _DBManager?.deleteRecordFromMainTable(namespace: currentNamespace,
  336. bundleIdentifier: _bundleIdentifier,
  337. fromSource: .fetched);
  338. }
  339. func handleUpdateStateForConfigNamespace(currentNamespace: String, withEntries: [String: String]) {
  340. FIRLogDebug(RCNRemoteConfigQueueLabel, "I-RCN000058", "Update config in DB for namespace:\(currentNamespace)");
  341. // Clear before updating
  342. _DBManager?.deleteRecordFromMainTable(namespace: currentNamespace,
  343. bundleIdentifier: _bundleIdentifier, fromSource: .fetched);
  344. if _fetchedConfig[currentNamespace] != nil) {
  345. _fetchedConfig[currentNamespace].removeAllObjects()
  346. } else {
  347. _fetchedConfig[currentNamespace] = NSMutableDictionary()
  348. }
  349. // Store the fetched config values.
  350. for key in entries.keys {
  351. let valueData = entries[key]?.data(using: .utf8)
  352. _fetchedConfig[currentNamespace][key] = FIRRemoteConfigValue(data: valueData, source: .remote)
  353. let values = [_bundleIdentifier, FIRNamespace, key, valueData] as [Any];
  354. }
  355. }
  356. func handleUpdatePersonalization(metadata: [String : Any]?) {
  357. _fetchedPersonalization = metadata ?? [:]
  358. _DBManager?.insertOrUpdatePersonalizationConfig(metadata ?? [:], fromSource: .fetched)
  359. }
  360. func handleUpdateRolloutFetchedMetadata(metadata: [NSDictionary]?) {
  361. if (metadata == nil) {
  362. return
  363. }
  364. _fetchedRolloutMetadata = metadata ?? []
  365. [_DBManager insertOrUpdateRolloutTableWithKey:RCNRolloutTableKeyFetchedMetadata
  366. value:_fetchedRolloutMetadata completionHandler:nil];
  367. }
  368. func initializationSuccessful() -> Bool {
  369. return true
  370. }
  371. //MARK: - Helpers
  372. func checkAndWaitForInitialDatabaseLoad() -> Bool{
  373. if (!_isConfigLoadFromDBCompleted) {
  374. let _ = _dispatch_group.wait(timeout: DispatchTime.now() + kDatabaseLoadTimeoutSecs)
  375. // Wait until load is done. This should be a no-op for subsequent calls.
  376. //_isConfigLoadFromDBCompleted = true
  377. }
  378. return true
  379. }
  380. //MARK: - Get config result
  381. func defaultValueForFullyQualifiedNamespace(namespace:String, key:String) -> FIRRemoteConfigValue{
  382. let value = self.defaultConfig[namespace]?[key];
  383. if value == nil {
  384. return FIRRemoteConfigValue(data: Data(), source: .static);
  385. }
  386. return value ?? FIRRemoteConfigValue(data: Data(), source: .static)
  387. }
  388. }