RCNConfigContent.m 13 KB

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