• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "kv_store_delegate_manager.h"
17 
18 #include <algorithm>
19 #include <cstdlib>
20 #include <cctype>
21 #include <map>
22 #include <thread>
23 
24 #include "db_constant.h"
25 #include "platform_specific.h"
26 #include "log_print.h"
27 #include "db_common.h"
28 #include "db_dfx_adapter.h"
29 #include "kv_store_errno.h"
30 #include "kvdb_pragma.h"
31 #include "kvdb_properties.h"
32 #include "kvdb_manager.h"
33 #include "kv_store_nb_delegate_impl.h"
34 #include "network_adapter.h"
35 #include "runtime_config.h"
36 #include "runtime_context.h"
37 #include "param_check_utils.h"
38 #include "auto_launch.h"
39 #include "kv_store_delegate_impl.h"
40 
41 namespace DistributedDB {
42 const std::string KvStoreDelegateManager::DEFAULT_PROCESS_APP_ID = "default";
43 std::mutex KvStoreDelegateManager::communicatorMutex_;
44 std::shared_ptr<IProcessCommunicator> KvStoreDelegateManager::processCommunicator_ = nullptr;
45 std::mutex KvStoreDelegateManager::multiUserMutex_;
46 
47 namespace {
48     const int GET_CONNECT_RETRY = 3;
49     const int RETRY_GET_CONN_INTER = 30;
50 
GetOneConnectionWithRetry(const KvDBProperties & properties,int & errCode)51     IKvDBConnection *GetOneConnectionWithRetry(const KvDBProperties &properties, int &errCode)
52     {
53         for (int i = 0; i < GET_CONNECT_RETRY; i++) {
54             auto conn = KvDBManager::GetDatabaseConnection(properties, errCode);
55             if (conn != nullptr) {
56                 return conn;
57             }
58             if (errCode == -E_STALE) {
59                 std::this_thread::sleep_for(std::chrono::milliseconds(RETRY_GET_CONN_INTER));
60             } else {
61                 return nullptr;
62             }
63         }
64         return nullptr;
65     }
66 
CheckAndGetSchema(bool isMemoryDb,const std::string & schema,SchemaObject & schemaObj)67     DBStatus CheckAndGetSchema(bool isMemoryDb, const std::string &schema, SchemaObject &schemaObj)
68     {
69         if (isMemoryDb && !schema.empty()) {
70             LOGW("[KvStoreDelegateManager] memory database doesn't support the schema.");
71             return NOT_SUPPORT;
72         }
73         if (schema.empty()) {
74             return OK;
75         }
76         schemaObj.ParseFromSchemaString(schema);
77         if (!schemaObj.IsSchemaValid()) {
78             return INVALID_SCHEMA;
79         }
80         return OK;
81     }
82 
InitPropWithNbOption(KvDBProperties & properties,const std::string & storePath,const SchemaObject & schema,const KvStoreNbDelegate::Option & option)83     void InitPropWithNbOption(KvDBProperties &properties,  const std::string &storePath,
84         const SchemaObject &schema, const KvStoreNbDelegate::Option &option)
85     {
86         properties.SetBoolProp(KvDBProperties::CREATE_IF_NECESSARY, option.createIfNecessary);
87         properties.SetIntProp(KvDBProperties::DATABASE_TYPE, KvDBProperties::SINGLE_VER_TYPE);
88         properties.SetBoolProp(KvDBProperties::MEMORY_MODE, option.isMemoryDb);
89         properties.SetBoolProp(KvDBProperties::ENCRYPTED_MODE, option.isEncryptedDb);
90         if (!option.isMemoryDb) { // memory db ignore store path
91             properties.SetStringProp(KvDBProperties::DATA_DIR, storePath);
92         }
93         properties.SetBoolProp(KvDBProperties::CREATE_DIR_BY_STORE_ID_ONLY, option.createDirByStoreIdOnly);
94         properties.SetSchema(schema);
95         properties.SetBoolProp(KvDBProperties::CHECK_INTEGRITY, option.isNeedIntegrityCheck);
96         properties.SetBoolProp(KvDBProperties::RM_CORRUPTED_DB, option.isNeedRmCorruptedDb);
97         if (RuntimeContext::GetInstance()->IsProcessSystemApiAdapterValid()) {
98             properties.SetIntProp(KvDBProperties::SECURITY_LABEL, option.secOption.securityLabel);
99             properties.SetIntProp(KvDBProperties::SECURITY_FLAG, option.secOption.securityFlag);
100         }
101         properties.SetIntProp(KvDBProperties::CONFLICT_RESOLVE_POLICY, option.conflictResolvePolicy);
102 
103         if (option.isEncryptedDb) {
104             properties.SetPassword(option.cipher, option.passwd);
105         }
106         properties.SetBoolProp(KvDBProperties::COMPRESS_ON_SYNC, option.isNeedCompressOnSync);
107         if (option.isNeedCompressOnSync) {
108             properties.SetIntProp(KvDBProperties::COMPRESSION_RATE,
109                 ParamCheckUtils::GetValidCompressionRate(option.compressionRate));
110         }
111         properties.SetBoolProp(KvDBProperties::SYNC_DUAL_TUPLE_MODE, option.syncDualTupleMode);
112         properties.SetBoolProp(KvDBProperties::LOCAL_ONLY, option.localOnly);
113     }
114 
CheckObserverConflictParam(const KvStoreNbDelegate::Option & option)115     bool CheckObserverConflictParam(const KvStoreNbDelegate::Option &option)
116     {
117         if ((option.notifier && !ParamCheckUtils::CheckConflictNotifierType(option.conflictType)) ||
118             (!option.notifier && option.conflictType != 0)) {
119             LOGE("Invalid conflict type, conflict type is [%d]", option.conflictType);
120             return false;
121         }
122         if ((option.observer != nullptr && !ParamCheckUtils::CheckObserver(option.key, option.mode)) ||
123             (option.observer == nullptr && (!option.key.empty() || option.mode != 0))) {
124             LOGE("Invalid observer param, observer mode is [%u]", option.mode);
125             return false;
126         }
127         return true;
128     }
129 
130 #ifndef OMIT_MULTI_VER
InitPropWithOption(KvDBProperties & properties,const std::string & storePath,const KvStoreDelegate::Option & option)131     void InitPropWithOption(KvDBProperties &properties, const std::string &storePath,
132         const KvStoreDelegate::Option &option)
133     {
134         properties.SetBoolProp(KvDBProperties::CREATE_IF_NECESSARY, option.createIfNecessary);
135         properties.SetBoolProp(KvDBProperties::CREATE_DIR_BY_STORE_ID_ONLY, option.createDirByStoreIdOnly);
136         properties.SetIntProp(KvDBProperties::DATABASE_TYPE,
137             ((option.localOnly == true) ? KvDBProperties::LOCAL_TYPE : KvDBProperties::MULTI_VER_TYPE));
138         properties.SetBoolProp(KvDBProperties::MEMORY_MODE, false);
139         properties.SetBoolProp(KvDBProperties::ENCRYPTED_MODE, option.isEncryptedDb);
140         properties.SetStringProp(KvDBProperties::DATA_DIR, storePath);
141         if (option.isEncryptedDb) {
142             properties.SetPassword(option.cipher, option.passwd);
143         }
144     }
145 #endif
146 }
147 
KvStoreDelegateManager(const std::string & appId,const std::string & userId,int32_t instanceId)148 KvStoreDelegateManager::KvStoreDelegateManager(const std::string &appId, const std::string &userId, int32_t instanceId)
149     : appId_(appId),
150       userId_(userId),
151       instanceId_(instanceId)
152 {}
153 
~KvStoreDelegateManager()154 KvStoreDelegateManager::~KvStoreDelegateManager() {}
155 
SetKvStoreConfig(const KvStoreConfig & kvStoreConfig)156 DBStatus KvStoreDelegateManager::SetKvStoreConfig(const KvStoreConfig &kvStoreConfig)
157 {
158     std::string canonicalDir;
159     if (!IsDataDirSafe(kvStoreConfig.dataDir, canonicalDir)) {
160         return INVALID_ARGS;
161     }
162     if (!OS::CheckPathExistence(canonicalDir)) {
163         LOGE("[KvStoreMgr] Data dir doesn't exist or no perm");
164         return INVALID_ARGS;
165     }
166     {
167         std::lock_guard<std::mutex> lock(mutex_);
168         kvStoreConfig_ = kvStoreConfig;
169         kvStoreConfig_.dataDir = canonicalDir;
170     }
171     return OK;
172 }
173 
GetKvStore(const std::string & storeId,const KvStoreDelegate::Option & option,const std::function<void (DBStatus,KvStoreDelegate *)> & callback)174 void KvStoreDelegateManager::GetKvStore(const std::string &storeId, const KvStoreDelegate::Option &option,
175     const std::function<void(DBStatus, KvStoreDelegate *)> &callback)
176 {
177     if (!callback) {
178         LOGE("[KvStoreMgr] Invalid callback for kv store!");
179         return;
180     }
181 #ifndef OMIT_MULTI_VER
182     // Multi version and local database mode not allow the creation of a memory database
183     if (!ParamCheckUtils::CheckStoreParameter(storeId, appId_, userId_) || GetKvStorePath().empty()) {
184         callback(INVALID_ARGS, nullptr);
185         return;
186     }
187 
188     if (option.isEncryptedDb) {
189         if (!ParamCheckUtils::CheckEncryptedParameter(option.cipher, option.passwd)) {
190             callback(INVALID_ARGS, nullptr);
191             return;
192         }
193     }
194 
195     KvDBProperties properties;
196     InitPropWithOption(properties, GetKvStorePath(), option);
197     DBCommon::SetDatabaseIds(properties, appId_, userId_, storeId);
198 
199     int errCode;
200     IKvDBConnection *conn = GetOneConnectionWithRetry(properties, errCode);
201     if (errCode == -E_INVALID_PASSWD_OR_CORRUPTED_DB) {
202         DBDfxAdapter::ReportFault( { DBDfxAdapter::EVENT_OPEN_DATABASE_FAILED, userId_, appId_, storeId, errCode } );
203     }
204     if (conn == nullptr) {
205         DBStatus status = TransferDBErrno(errCode);
206         callback(status, nullptr);
207         return;
208     }
209 
210     auto kvStore = new (std::nothrow) KvStoreDelegateImpl(conn, storeId);
211     if (kvStore == nullptr) {
212         LOGE("[KvStoreMgr] Failed to alloc the delegate");
213         conn->Close();
214         conn = nullptr;
215         callback(DB_ERROR, nullptr);
216         return;
217     }
218     callback(OK, kvStore);
219 #else
220     callback(NOT_SUPPORT, nullptr);
221     return;
222 #endif
223 }
224 
SetObserverNotifier(KvStoreNbDelegate * kvStore,const KvStoreNbDelegate::Option & option)225 DBStatus KvStoreDelegateManager::SetObserverNotifier(KvStoreNbDelegate *kvStore,
226     const KvStoreNbDelegate::Option &option)
227 {
228     DBStatus status;
229     if (option.observer != nullptr) {
230         status = kvStore->RegisterObserver(option.key, option.mode, option.observer);
231         if (status != OK) {
232             LOGE("[KvStoreMgr] RegisterObserver failed.");
233             return status;
234         }
235     }
236     if (option.notifier != nullptr) {
237         status = kvStore->SetConflictNotifier(option.conflictType, option.notifier);
238         if (status != OK) {
239             LOGE("[KvStoreMgr] SetConflictNotifier failed.");
240             return status;
241         }
242     }
243     return OK;
244 }
245 
GetKvStoreParamCheck(const std::string & storeId,const KvStoreNbDelegate::Option & option,const std::function<void (DBStatus,KvStoreNbDelegate *)> & callback) const246 bool KvStoreDelegateManager::GetKvStoreParamCheck(const std::string &storeId, const KvStoreNbDelegate::Option &option,
247     const std::function<void(DBStatus, KvStoreNbDelegate *)> &callback) const
248 {
249     if (!callback) {
250         LOGE("[KvStoreMgr] Invalid callback for kv store");
251         return false;
252     }
253     if (!ParamCheckUtils::CheckStoreParameter(storeId, appId_, userId_) ||
254         (GetKvStorePath().empty() && !option.isMemoryDb)) {
255         LOGE("[KvStoreMgr] Invalid id or path info for the store");
256         callback(INVALID_ARGS, nullptr);
257         return false;
258     }
259 
260     // check if want an encrypted db
261     if (option.isEncryptedDb) {
262         if (option.isMemoryDb) {
263             LOGE("Memory db not support encrypt!");
264             callback(NOT_SUPPORT, nullptr);
265             return false;
266         }
267         if (!ParamCheckUtils::CheckEncryptedParameter(option.cipher, option.passwd)) {
268             callback(INVALID_ARGS, nullptr);
269             return false;
270         }
271     }
272     // check secOption
273     if (!option.isMemoryDb) {
274         if (!ParamCheckUtils::CheckSecOption(option.secOption)) {
275             callback(INVALID_ARGS, nullptr);
276             return false;
277         }
278     } else {
279         if (option.secOption.securityLabel != SecurityLabel::NOT_SET ||
280             option.secOption.securityFlag != 0) {
281             LOGE("Memory db has no physical files, Is not controlled by security labels, so not support set labels");
282             callback(INVALID_ARGS, nullptr);
283             return false;
284         }
285     }
286 
287     if (!CheckObserverConflictParam(option)) {
288         callback(INVALID_ARGS, nullptr);
289         return false;
290     }
291     return true;
292 }
293 
GetKvStore(const std::string & storeId,const KvStoreNbDelegate::Option & option,const std::function<void (DBStatus,KvStoreNbDelegate *)> & callback)294 void KvStoreDelegateManager::GetKvStore(const std::string &storeId, const KvStoreNbDelegate::Option &option,
295     const std::function<void(DBStatus, KvStoreNbDelegate *)> &callback)
296 {
297     if (!GetKvStoreParamCheck(storeId, option, callback)) {
298         return;
299     }
300     // check if schema is supported and valid
301     SchemaObject schema;
302     DBStatus retCode = CheckAndGetSchema(option.isMemoryDb, option.schema, schema);
303     if (retCode != OK) {
304         callback(retCode, nullptr);
305         return;
306     }
307     KvDBProperties properties;
308     InitPropWithNbOption(properties, GetKvStorePath(), schema, option);
309     DBCommon::SetDatabaseIds(properties, appId_, userId_, storeId, instanceId_);
310 
311     int errCode;
312     IKvDBConnection *conn = GetOneConnectionWithRetry(properties, errCode);
313     if (errCode == -E_INVALID_PASSWD_OR_CORRUPTED_DB) {
314         DBDfxAdapter::ReportFault( { DBDfxAdapter::EVENT_OPEN_DATABASE_FAILED, userId_, appId_, storeId, errCode } );
315     }
316     DBStatus status = TransferDBErrno(errCode);
317     if (conn == nullptr) {
318         callback(status, nullptr);
319         return;
320     }
321 
322     auto kvStore = new (std::nothrow) KvStoreNbDelegateImpl(conn, storeId);
323     if (kvStore == nullptr) {
324         conn->Close();
325         conn = nullptr;
326         callback(DB_ERROR, nullptr);
327         return;
328     }
329 
330     status = SetObserverNotifier(kvStore, option);
331     if (status != OK) {
332         CloseKvStore(kvStore);
333         callback(status, nullptr);
334         return;
335     }
336 
337     bool enAutoSync = false;
338     (void)conn->Pragma(PRAGMA_AUTO_SYNC, static_cast<void *>(&enAutoSync));
339 
340     SecurityOption secOption = option.secOption;
341     (void)conn->Pragma(PRAGMA_TRIGGER_TO_MIGRATE_DATA, &secOption);
342 
343     callback(OK, kvStore);
344 }
345 
346 
CloseKvStore(KvStoreDelegate * kvStore)347 DBStatus KvStoreDelegateManager::CloseKvStore(KvStoreDelegate *kvStore)
348 {
349 #ifndef OMIT_MULTI_VER
350     if (kvStore == nullptr) {
351         return INVALID_ARGS;
352     }
353 
354     auto kvStoreImpl = static_cast<KvStoreDelegateImpl *>(kvStore);
355     DBStatus status = kvStoreImpl->Close();
356     if (status == BUSY) {
357         LOGD("DelegateImpl is busy now.");
358         return BUSY;
359     }
360 
361     kvStoreImpl->SetReleaseFlag(true);
362     delete kvStore;
363     kvStore = nullptr;
364     return OK;
365 #else
366     return NOT_SUPPORT;
367 #endif
368 }
369 
CloseKvStore(KvStoreNbDelegate * kvStore)370 DBStatus KvStoreDelegateManager::CloseKvStore(KvStoreNbDelegate *kvStore)
371 {
372     if (kvStore == nullptr) {
373         return INVALID_ARGS;
374     }
375 
376     auto kvStoreImpl = static_cast<KvStoreNbDelegateImpl *>(kvStore);
377     DBStatus status = kvStoreImpl->Close();
378     if (status == BUSY) {
379         LOGD("NbDelegateImpl is busy now.");
380         return BUSY;
381     }
382     kvStoreImpl->SetReleaseFlag(true);
383     delete kvStore;
384     kvStore = nullptr;
385     return OK;
386 }
387 
DeleteKvStore(const std::string & storeId)388 DBStatus KvStoreDelegateManager::DeleteKvStore(const std::string &storeId)
389 {
390     if (!ParamCheckUtils::IsStoreIdSafe(storeId) || GetKvStorePath().empty()) {
391         LOGE("Invalid store info for deleting");
392         return INVALID_ARGS;
393     }
394 
395     KvDBProperties properties;
396     properties.SetStringProp(KvDBProperties::DATA_DIR, GetKvStorePath());
397     DBCommon::SetDatabaseIds(properties, appId_, userId_, storeId);
398     int errCode = KvDBManager::RemoveDatabase(properties);
399     if (errCode == E_OK) {
400         LOGI("Database deleted successfully!");
401         return OK;
402     }
403     LOGE("Delete the kv store error:%d", errCode);
404     return TransferDBErrno(errCode);
405 }
406 
SetProcessLabel(const std::string & appId,const std::string & userId)407 DBStatus KvStoreDelegateManager::SetProcessLabel(const std::string &appId, const std::string &userId)
408 {
409     if (appId.size() > DBConstant::MAX_APP_ID_LENGTH || appId.empty() ||
410         userId.size() > DBConstant::MAX_USER_ID_LENGTH || userId.empty()) {
411         LOGE("Invalid app or user info[%zu]-[%zu]", appId.length(), userId.length());
412         return INVALID_ARGS;
413     }
414 
415     int errCode = KvDBManager::SetProcessLabel(appId, userId);
416     if (errCode != E_OK) {
417         LOGE("Failed to set the process label:%d", errCode);
418         return DB_ERROR;
419     }
420     return OK;
421 }
422 
SetProcessCommunicator(const std::shared_ptr<IProcessCommunicator> & inCommunicator)423 DBStatus KvStoreDelegateManager::SetProcessCommunicator(const std::shared_ptr<IProcessCommunicator> &inCommunicator)
424 {
425     std::lock_guard<std::mutex> lock(communicatorMutex_);
426     if (processCommunicator_ != nullptr) {
427         LOGE("processCommunicator_ is not null!");
428         return DB_ERROR;
429     }
430 
431     std::string processLabel = RuntimeContext::GetInstance()->GetProcessLabel();
432     if (processLabel.empty()) {
433         LOGE("ProcessLabel is not set!");
434         return DB_ERROR;
435     }
436 
437     NetworkAdapter *adapter = new (std::nothrow) NetworkAdapter(processLabel, inCommunicator);
438     if (adapter == nullptr) {
439         LOGE("New NetworkAdapter failed!");
440         return DB_ERROR;
441     }
442     processCommunicator_ = inCommunicator;
443     if (RuntimeContext::GetInstance()->SetCommunicatorAdapter(adapter) != E_OK) {
444         LOGE("SetProcessCommunicator not support!");
445         delete adapter;
446         return DB_ERROR;
447     }
448     KvDBManager::RestoreSyncableKvStore();
449     return OK;
450 }
451 
GetKvStoreDiskSize(const std::string & storeId,uint64_t & size)452 DBStatus KvStoreDelegateManager::GetKvStoreDiskSize(const std::string &storeId, uint64_t &size)
453 {
454     std::string dataDir = GetKvStorePath();
455     if (!ParamCheckUtils::CheckStoreParameter(storeId, appId_, userId_)) {
456         LOGE("[KvStoreMgr] Invalid store info for size");
457         return INVALID_ARGS;
458     }
459     KvDBProperties properties;
460     properties.SetStringProp(KvDBProperties::DATA_DIR, dataDir);
461     DBCommon::SetDatabaseIds(properties, appId_, userId_, storeId);
462     int errCode = KvDBManager::CalculateKvStoreSize(properties, size);
463     if (errCode != E_OK) {
464         if (errCode == -E_NOT_FOUND) {
465             return NOT_FOUND;
466         }
467 
468         LOGE("[KvStoreMgr] Get the file size failed[%d]", errCode);
469         return DB_ERROR;
470     }
471     return OK;
472 }
473 
SetKvStoreCorruptionHandler(const KvStoreCorruptionHandler & handler)474 void KvStoreDelegateManager::SetKvStoreCorruptionHandler(const KvStoreCorruptionHandler &handler)
475 {
476     KvDBManager::SetDatabaseCorruptionHandler(handler);
477 }
478 
GetDatabaseDir(const std::string & storeId,const std::string & appId,const std::string & userId,std::string & directory)479 DBStatus KvStoreDelegateManager::GetDatabaseDir(const std::string &storeId, const std::string &appId,
480     const std::string &userId, std::string &directory)
481 {
482     if (!ParamCheckUtils::CheckStoreParameter(storeId, appId, userId)) {
483         return INVALID_ARGS;
484     }
485 
486     std::string identifier = DBCommon::GenerateIdentifierId(storeId, appId, userId);
487     std::string dir = DBCommon::TransferHashString(identifier);
488     if (dir.empty()) {
489         return DB_ERROR;
490     }
491     directory = DBCommon::TransferStringToHex(dir);
492     return OK;
493 }
494 
GetDatabaseDir(const std::string & storeId,std::string & directory)495 DBStatus KvStoreDelegateManager::GetDatabaseDir(const std::string &storeId, std::string &directory)
496 {
497     if (!ParamCheckUtils::IsStoreIdSafe(storeId)) {
498         return INVALID_ARGS;
499     }
500 
501     if (storeId.find(DBConstant::ID_CONNECTOR) != std::string::npos) {
502         return INVALID_ARGS;
503     }
504 
505     std::string dir = DBCommon::TransferHashString(storeId);
506     if (dir.empty()) {
507         return DB_ERROR;
508     }
509     directory = DBCommon::TransferStringToHex(dir);
510     return OK;
511 }
512 
513 // private
IsDataDirSafe(const std::string & dataDir,std::string & canonicalDir) const514 bool KvStoreDelegateManager::IsDataDirSafe(const std::string &dataDir, std::string &canonicalDir) const
515 {
516     return ParamCheckUtils::CheckDataDir(dataDir, canonicalDir);
517 }
518 
GetKvStorePath() const519 const std::string &KvStoreDelegateManager::GetKvStorePath() const
520 {
521     std::lock_guard<std::mutex> lock(mutex_);
522     return kvStoreConfig_.dataDir;
523 }
524 
SetPermissionCheckCallback(const PermissionCheckCallback & callback)525 DBStatus KvStoreDelegateManager::SetPermissionCheckCallback(const PermissionCheckCallback &callback)
526 {
527     int errCode = RuntimeContext::GetInstance()->SetPermissionCheckCallback(callback);
528     return TransferDBErrno(errCode);
529 }
530 
SetPermissionCheckCallback(const PermissionCheckCallbackV2 & callback)531 DBStatus KvStoreDelegateManager::SetPermissionCheckCallback(const PermissionCheckCallbackV2 &callback)
532 {
533     int errCode = RuntimeContext::GetInstance()->SetPermissionCheckCallback(callback);
534     return TransferDBErrno(errCode);
535 }
536 
EnableKvStoreAutoLaunch(const std::string & userId,const std::string & appId,const std::string & storeId,const AutoLaunchOption & option,const AutoLaunchNotifier & notifier)537 DBStatus KvStoreDelegateManager::EnableKvStoreAutoLaunch(const std::string &userId, const std::string &appId,
538     const std::string &storeId, const AutoLaunchOption &option, const AutoLaunchNotifier &notifier)
539 {
540     if (RuntimeContext::GetInstance() == nullptr) {
541         return DB_ERROR;
542     }
543     AutoLaunchParam param{ userId, appId, storeId, option, notifier, {}};
544     std::shared_ptr<DBProperties> ptr;
545     int errCode = AutoLaunch::GetAutoLaunchProperties(param, DBTypeInner::DB_KV, true, ptr);
546     if (errCode != E_OK) {
547         LOGE("[KvStoreManager] Enable auto launch failed:%d", errCode);
548         return TransferDBErrno(errCode);
549     }
550 
551     std::shared_ptr<KvDBProperties> kvPtr = std::static_pointer_cast<KvDBProperties>(ptr);
552     errCode = RuntimeContext::GetInstance()->EnableKvStoreAutoLaunch(*kvPtr, notifier, option);
553     if (errCode != E_OK) {
554         LOGE("[KvStoreManager] Enable auto launch failed:%d", errCode);
555         return TransferDBErrno(errCode);
556     }
557     LOGI("[KvStoreManager] Enable auto launch");
558     return OK;
559 }
560 
DisableKvStoreAutoLaunch(const std::string & userId,const std::string & appId,const std::string & storeId)561 DBStatus KvStoreDelegateManager::DisableKvStoreAutoLaunch(const std::string &userId, const std::string &appId,
562     const std::string &storeId)
563 {
564     if (RuntimeContext::GetInstance() == nullptr) {
565         return DB_ERROR;
566     }
567 
568     std::string syncIdentifier = DBCommon::GenerateIdentifierId(storeId, appId, userId, 0);
569     std::string hashIdentifier = DBCommon::TransferHashString(syncIdentifier);
570     std::string dualIdentifier = DBCommon::TransferHashString(DBCommon::GenerateDualTupleIdentifierId(storeId, appId));
571     int errCode = RuntimeContext::GetInstance()->DisableKvStoreAutoLaunch(hashIdentifier, dualIdentifier, userId);
572     if (errCode != E_OK) {
573         LOGE("[KvStoreManager] Disable auto launch failed:%d", errCode);
574         return TransferDBErrno(errCode);
575     }
576     LOGI("[KvStoreManager] Disable auto launch");
577     return OK;
578 }
579 
SetAutoLaunchRequestCallback(const AutoLaunchRequestCallback & callback)580 void KvStoreDelegateManager::SetAutoLaunchRequestCallback(const AutoLaunchRequestCallback &callback)
581 {
582     RuntimeContext::GetInstance()->SetAutoLaunchRequestCallback(callback, DBTypeInner::DB_KV);
583 }
584 
GetKvStoreIdentifier(const std::string & userId,const std::string & appId,const std::string & storeId,bool syncDualTupleMode)585 std::string KvStoreDelegateManager::GetKvStoreIdentifier(const std::string &userId, const std::string &appId,
586     const std::string &storeId, bool syncDualTupleMode)
587 {
588     return RuntimeConfig::GetStoreIdentifier(userId, appId, storeId, syncDualTupleMode);
589 }
590 
SetProcessSystemAPIAdapter(const std::shared_ptr<IProcessSystemApiAdapter> & adapter)591 DBStatus KvStoreDelegateManager::SetProcessSystemAPIAdapter(const std::shared_ptr<IProcessSystemApiAdapter> &adapter)
592 {
593     return TransferDBErrno(RuntimeContext::GetInstance()->SetProcessSystemApiAdapter(adapter));
594 }
595 
SetStoreStatusNotifier(const StoreStatusNotifier & notifier)596 void KvStoreDelegateManager::SetStoreStatusNotifier(const StoreStatusNotifier &notifier)
597 {
598     RuntimeContext::GetInstance()->SetStoreStatusNotifier(notifier);
599 }
600 
SetSyncActivationCheckCallback(const SyncActivationCheckCallback & callback)601 DBStatus KvStoreDelegateManager::SetSyncActivationCheckCallback(const SyncActivationCheckCallback &callback)
602 {
603     std::lock_guard<std::mutex> lock(multiUserMutex_);
604     int errCode = RuntimeContext::GetInstance()->SetSyncActivationCheckCallback(callback);
605     return TransferDBErrno(errCode);
606 }
607 
NotifyUserChanged()608 DBStatus KvStoreDelegateManager::NotifyUserChanged()
609 {
610     std::lock_guard<std::mutex> lock(multiUserMutex_);
611     int errCode = RuntimeContext::GetInstance()->NotifyUserChanged();
612     return TransferDBErrno(errCode);
613 }
614 
IsProcessSystemApiAdapterValid()615 bool KvStoreDelegateManager::IsProcessSystemApiAdapterValid()
616 {
617     return RuntimeContext::GetInstance()->IsProcessSystemApiAdapterValid();
618 }
619 } // namespace DistributedDB
620