diff --git a/bundle.json b/bundle.json index 864b62204b9b0ad5c9dae87b10546fb801542de2..c24df93c9eee55a6fecb732f32ec70992ac54ca2 100644 --- a/bundle.json +++ b/bundle.json @@ -107,7 +107,8 @@ "types.h", "visibility.h", "data_query.h", - "device_status_change_listener.h" + "device_status_change_listener.h", + "store_errno.h" ], "header_base": "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata/include" } diff --git a/frameworks/common/concurrent_map.h b/frameworks/common/concurrent_map.h index 06f0fd9b582428fe62780ccd24d08d258140ff8f..58dc0e92c1defe0bb967582bbf5890e81c29ca1f 100644 --- a/frameworks/common/concurrent_map.h +++ b/frameworks/common/concurrent_map.h @@ -207,7 +207,7 @@ public: if (it != entries_.end()) { return false; } - entries_.insert(value_type{key, action(key)}); + entries_.emplace(key, action(key)); return true; } private: diff --git a/frameworks/innerkitsimpl/distributeddatafwk/src/app_blob.cpp b/frameworks/innerkitsimpl/distributeddatafwk/src/app_blob.cpp deleted file mode 100755 index 8a0058af5215f26e0638aeb11e81836666d9a7d3..0000000000000000000000000000000000000000 --- a/frameworks/innerkitsimpl/distributeddatafwk/src/app_blob.cpp +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "app_blob.h" -#include -namespace OHOS { -namespace AppDistributedKv { -AppBlob::AppBlob(const AppBlob &blob) -{ - blob_ = blob.Data(); -} - -AppBlob::AppBlob(AppBlob &&blob) noexcept -{ - blob_.swap(blob.blob_); -} - -AppBlob &AppBlob::operator=(const AppBlob &blob) -{ - // Self-assignment detection - if (&blob == this) { - return *this; - } - - blob_ = blob.Data(); - return *this; -} - -AppBlob &AppBlob::operator=(AppBlob &&blob) noexcept -{ - // Self-assignment detection - if (&blob == this) { - return *this; - } - - blob_.swap(blob.blob_); - - return *this; -} - -AppBlob::AppBlob(const char *str, size_t n) - : blob_() -{ - if (str != nullptr) { - blob_ = std::vector(str, str + n); - } -} - -AppBlob::AppBlob(const std::string &str) - : blob_(str.begin(), str.end()) -{ -} - -AppBlob::AppBlob(const char *str) - : blob_() -{ - if (str != nullptr) { - blob_ = std::vector(str, str + strlen(str)); - } -} - -AppBlob::AppBlob(const std::vector &bytes) - : blob_(bytes) -{ -} - -const std::vector &AppBlob::Data() const -{ - return blob_; -} - -size_t AppBlob::Size() const -{ - return blob_.size(); -} - -bool AppBlob::Empty() const -{ - return (blob_.empty()); -} - -bool AppBlob::operator==(const AppBlob &blob) const -{ - return blob_ == blob.blob_; -} - -std::string AppBlob::ToString() const -{ - std::string str(blob_.begin(), blob_.end()); - return str; -} - -int AppBlob::Compare(const AppBlob &blob) const -{ - if (blob_ < blob.blob_) { - return -1; - } - if (blob_ == blob.blob_) { - return 0; - } - return 1; -} -} // namespace AppDistributedKv -} // namespace OHOS diff --git a/frameworks/innerkitsimpl/distributeddatafwk/src/app_change_notification.cpp b/frameworks/innerkitsimpl/distributeddatafwk/src/app_change_notification.cpp deleted file mode 100755 index 35c76fcc6250f75a57df410a3a9370d9812eeaad..0000000000000000000000000000000000000000 --- a/frameworks/innerkitsimpl/distributeddatafwk/src/app_change_notification.cpp +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "app_change_notification.h" - -namespace OHOS { -namespace AppDistributedKv { -AppChangeNotification::AppChangeNotification() -{} - -AppChangeNotification::AppChangeNotification(const std::list &insertEntries, - const std::list &updateEntries, - const std::list &deleteEntries, - const std::string &deviceId, - const bool isClear) - : insertEntries_(insertEntries), updateEntries_(updateEntries), deleteEntries_(deleteEntries), - deviceId_(deviceId), isClear_(isClear) -{} - -AppChangeNotification::~AppChangeNotification() -{} - -const std::list &AppChangeNotification::GetInsertEntries() const -{ - return this->insertEntries_; -} - -const std::list &AppChangeNotification::GetUpdateEntries() const -{ - return this->updateEntries_; -} - -const std::list &AppChangeNotification::GetDeleteEntries() const -{ - return this->deleteEntries_; -} - -const std::string &AppChangeNotification::GetDeviceId() const -{ - return this->deviceId_; -} - -bool AppChangeNotification::IsClear() const -{ - return this->isClear_; -} -} // namespace AppDistributedKv -} // namespace OHOS diff --git a/frameworks/innerkitsimpl/distributeddatafwk/src/app_distributed_kv_data_manager.cpp b/frameworks/innerkitsimpl/distributeddatafwk/src/app_distributed_kv_data_manager.cpp deleted file mode 100755 index 5c6a70c58d7afa74d7bfedc39de79bb513e7c307..0000000000000000000000000000000000000000 --- a/frameworks/innerkitsimpl/distributeddatafwk/src/app_distributed_kv_data_manager.cpp +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "app_distributed_kv_data_manager.h" -#include "app_distributed_kv_data_manager_impl.h" - -namespace OHOS { -namespace AppDistributedKv { -std::shared_ptr AppDistributedKvDataManager::GetInstance(const std::string &bundleName, - const std::string &dataDir, - const std::string &userId) -{ - return AppDistributedKvDataManagerImpl::GetInstance(bundleName, dataDir, userId); -} -} // namespace AppDistributedKv -} // namespace OHOS diff --git a/frameworks/innerkitsimpl/distributeddatafwk/src/app_distributed_kv_data_manager_impl.cpp b/frameworks/innerkitsimpl/distributeddatafwk/src/app_distributed_kv_data_manager_impl.cpp deleted file mode 100755 index a464c22eec65ac3998f7382df0da657833974d79..0000000000000000000000000000000000000000 --- a/frameworks/innerkitsimpl/distributeddatafwk/src/app_distributed_kv_data_manager_impl.cpp +++ /dev/null @@ -1,262 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#define LOG_TAG "AppDistributedKvDataManagerImpl" - -#include "app_distributed_kv_data_manager_impl.h" -#include -#include -#include -#include -#include "app_kvstore_impl.h" -#include "communication_provider.h" -#include "constant.h" -#include "types.h" -#include "log_print.h" -#include "reporter.h" -#include "account_delegate.h" -#include "delegate_mgr_callback.h" -#include "process_communicator_impl.h" -#include "kvstore_utils.h" -namespace OHOS { -namespace AppDistributedKv { -using namespace OHOS::DistributedKv; -const std::string DATABASE_DIR = "distributeddb"; -const std::string DEVICE_COLLABORATION_ABBRE = "_DDC"; - -std::mutex AppDistributedKvDataManagerImpl::storeMutex_; -std::map> AppDistributedKvDataManagerImpl::managers_; - -std::shared_ptr AppDistributedKvDataManagerImpl::GetInstance(const std::string &bundleName, - const std::string &dataDir, - const std::string &userId) -{ - ZLOGI("start"); - std::lock_guard lck(storeMutex_); - auto it = managers_.find(bundleName + userId); - if (it != managers_.end()) { - return it->second; - } - - std::string tempDataDir = dataDir; - ZLOGD("tempDataDir : %s", tempDataDir.c_str()); - if (!ForceCreateDirectory(tempDataDir)) { - ZLOGE("create directories %s failed", tempDataDir.c_str()); - FaultMsg msg = {FaultType::SERVICE_FAULT, "device", "GetInstance", Fault::SF_CREATE_DIR}; - Reporter::GetInstance()->ServiceFault()->Report(msg); - return nullptr; - } - // default mode is 0755 - if (!ChangeModeDirectory(tempDataDir, DistributedKv::Constant::DEFAULT_MODE)) { - return nullptr; - } - - std::string appId = bundleName; - if (appId.empty()) { - appId = bundleName; - } - auto status = DistributedDB::KvStoreDelegateManager::SetProcessLabel(appId + DEVICE_COLLABORATION_ABBRE, userId); - if (status != DistributedDB::DBStatus::OK) { - ZLOGE("delegate SetProcessLabel failed: %d.", static_cast(status)); - FaultMsg msg = {FaultType::SERVICE_FAULT, "device", "GetInstance", Fault::SF_PROCESS_LABEL}; - Reporter::GetInstance()->ServiceFault()->Report(msg); - return nullptr; - } - - auto communicator = std::make_shared(); - auto commStatus = DistributedDB::KvStoreDelegateManager::SetProcessCommunicator(communicator); - if (commStatus != DistributedDB::DBStatus::OK) { - ZLOGW("set distributed db communicator failed."); - return nullptr; - } - - auto *delegateManager = new(std::nothrow) DistributedDB::KvStoreDelegateManager(appId, userId); - if (delegateManager == nullptr) { - ZLOGW("new kvStoredelegateManager failed"); - return nullptr; - } - DistributedDB::KvStoreConfig kvStoreConfig { tempDataDir }; - status = delegateManager->SetKvStoreConfig(kvStoreConfig); - if (status != DistributedDB::DBStatus::OK) { - ZLOGE("delegate SetKvStoreConfig failed: %d.", static_cast(status)); - FaultMsg msg = {FaultType::SERVICE_FAULT, "device", "GetInstance", Fault::SF_DATABASE_CONFIG}; - Reporter::GetInstance()->ServiceFault()->Report(msg); - delete delegateManager; - delegateManager = nullptr; - return nullptr; - } - - auto temp = std::make_shared(delegateManager, appId, userId); - if (temp == nullptr) { - delete delegateManager; - delegateManager = nullptr; - ZLOGW("new AppDistributedKvDataManagerImpl failed"); - return nullptr; - } - - managers_.insert({bundleName + userId, temp}); - ZLOGD("return a new managerSingleton_."); - return temp; -} - -AppDistributedKvDataManagerImpl::AppDistributedKvDataManagerImpl( - DistributedDB::KvStoreDelegateManager *delegateManager, const std::string &appId, const std::string &accountId) - : kvStoreDelegateManager_(delegateManager), appId_(appId), accountId_(accountId) -{ - ZLOGI("construct"); -} - -AppDistributedKvDataManagerImpl::~AppDistributedKvDataManagerImpl() -{ - ZLOGI("destruct"); - delete kvStoreDelegateManager_; -} - -Status AppDistributedKvDataManagerImpl::GetKvStore( - const Options &options, const std::string &storeId, - const std::function appKvStore)> &callback) -{ - ZLOGI("start."); - std::string trimmedStoreId = DistributedKv::Constant::TrimCopy(storeId); - if (trimmedStoreId.size() == 0 || trimmedStoreId.size() > DistributedKv::Constant::MAX_STORE_ID_LENGTH) { - ZLOGE("storeId is invalid."); - return Status::INVALID_ARGUMENT; - } - if (kvStoreDelegateManager_ == nullptr) { - ZLOGE("kvStoreDelegateManager_ is nullptr."); - return Status::ILLEGAL_STATE; - } - Status status = Status::ERROR; - DistributedDB::KvStoreNbDelegate::Option dbOption; - dbOption.createIfNecessary = options.createIfMissing; - dbOption.isMemoryDb = !options.persistant; - dbOption.secOption = ConvertSecurityLevel(options.securityLevel); - kvStoreDelegateManager_->GetKvStore( - trimmedStoreId, dbOption, - [&](DistributedDB::DBStatus dbStatus, DistributedDB::KvStoreNbDelegate *kvStoreNbDelegate) { - if (dbStatus == DistributedDB::DBStatus::OK && kvStoreNbDelegate != nullptr) { - status = Status::SUCCESS; - callback(std::make_unique(trimmedStoreId, kvStoreNbDelegate)); - ZLOGI("succeed."); - auto statDelegateMgr = std::make_shared(kvStoreDelegateManager_); - auto statDelegate = std::static_pointer_cast(statDelegateMgr); - Reporter::GetInstance()->DatabaseStatistic()->Report({accountId_, appId_, storeId, 0, statDelegate}); - return; - } - - status = AppKvStoreImpl::ConvertErrorCode(dbStatus); - if (kvStoreNbDelegate == nullptr) { - status = Status::STORE_NOT_FOUND; - } - ZLOGW("appKvStore return nullptr."); - callback(nullptr); - FaultMsg msg = {FaultType::RUNTIME_FAULT, ModuleName::DEVICE, "GetKvStore", Fault::RF_GET_DB}; - Reporter::GetInstance()->ServiceFault()->Report(msg); - }); - - ZLOGI("get status: %d.", static_cast(status)); - return status; -} - -Status AppDistributedKvDataManagerImpl::CloseKvStore(std::unique_ptr appKvStore) -{ - ZLOGI("start."); - if (appKvStore == nullptr) { - ZLOGE("appKvStore is nullptr."); - return Status::INVALID_ARGUMENT; - } - if (kvStoreDelegateManager_ == nullptr) { - ZLOGE("kvStoreDelegateManager_ is nullptr."); - return Status::ILLEGAL_STATE; - } - return reinterpret_cast(appKvStore.get())->Close(kvStoreDelegateManager_); -} - -Status AppDistributedKvDataManagerImpl::DeleteKvStore(const std::string &storeId) -{ - ZLOGI("start."); - if (kvStoreDelegateManager_ == nullptr) { - ZLOGE("kvStoreDelegateManager_ is nullptr."); - return Status::ILLEGAL_STATE; - } - std::string trimmedStoreId = DistributedKv::Constant::TrimCopy(storeId); - if (trimmedStoreId.empty() || trimmedStoreId.size() > DistributedKv::Constant::MAX_STORE_ID_LENGTH) { - ZLOGW("invalid storeId."); - return Status::INVALID_ARGUMENT; - } - DistributedDB::DBStatus status = kvStoreDelegateManager_->DeleteKvStore(trimmedStoreId); - if (status == DistributedDB::DBStatus::OK) { - ZLOGI("delete KVStore succeed."); - return Status::SUCCESS; - } - ZLOGE("delete KVStore failed."); - return Status::ERROR; -} - -Status AppDistributedKvDataManagerImpl::GetKvStoreDiskSize(const std::string &storeId, uint64_t &size) -{ - ZLOGI("start"); - if (kvStoreDelegateManager_ == nullptr) { - ZLOGE("kvStoreDelegateManager_ is nullptr."); - return Status::ILLEGAL_STATE; - } - DistributedDB::DBStatus status = kvStoreDelegateManager_->GetKvStoreDiskSize(storeId, size); - if (status != DistributedDB::DBStatus::OK) { - ZLOGE("Failed to getStoreDiskSize, storeID: %s", storeId.c_str()); - return Status::ERROR; - } - ZLOGI("end, size:%" PRIu64, size); - return Status::SUCCESS; -} - -Status AppDistributedKvDataManagerImpl::RegisterKvStoreCorruptionObserver( - const std::shared_ptr observer) -{ - ZLOGI("start"); - if (observer == nullptr) { - ZLOGE("observer is nullptr."); - return Status::INVALID_ARGUMENT; - } - if (corruptionObserver_ != nullptr) { - return Status::REPEATED_REGISTER; - } - if (kvStoreDelegateManager_ == nullptr) { - return Status::ERROR; - } - corruptionObserver_ = observer; - kvStoreDelegateManager_->SetKvStoreCorruptionHandler([&](const std::string& appId, const std::string& userId, - const std::string& storeId) { - corruptionObserver_->OnCorruption(appId, userId, storeId); - }); - ZLOGD("end"); - return Status::SUCCESS; -} - -DistributedDB::SecurityOption AppDistributedKvDataManagerImpl::ConvertSecurityLevel(int securityLevel) -{ - if (securityLevel < SecurityLevel::NO_LABEL || securityLevel > SecurityLevel::S4) { - return {SecurityLevel::NO_LABEL, DistributedDB::ECE}; - } - switch (securityLevel) { - case SecurityLevel::S3: - return {DistributedDB::S3, DistributedDB::SECE}; - case SecurityLevel::S4: - return {DistributedDB::S4, DistributedDB::ECE}; - default: - return {securityLevel, DistributedDB::ECE}; - } -} -} // namespace AppDistributedKv -} // namespace OHOS diff --git a/frameworks/innerkitsimpl/distributeddatafwk/src/app_distributed_kv_data_manager_impl.h b/frameworks/innerkitsimpl/distributeddatafwk/src/app_distributed_kv_data_manager_impl.h deleted file mode 100755 index 7fa56c8300e0b750603d33175cb7fc0d889c3807..0000000000000000000000000000000000000000 --- a/frameworks/innerkitsimpl/distributeddatafwk/src/app_distributed_kv_data_manager_impl.h +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef APP_DISTRIBUTED_KV_DATA_MANAGER_IMPL_H -#define APP_DISTRIBUTED_KV_DATA_MANAGER_IMPL_H - -#include -#include "app_device_status_change_listener.h" -#include "app_distributed_kv_data_manager.h" -#include "app_kvstore.h" -#include "app_types.h" -#include "kv_store_delegate_manager.h" -#include "process_communicator_impl.h" - -namespace OHOS { -namespace AppDistributedKv { -// This is the overall manager of all kvstore. -// This class provides open, close, delete AppKvStore and manage remote device functions. -class AppDistributedKvDataManagerImpl final : public AppDistributedKvDataManager { -public: - AppDistributedKvDataManagerImpl(DistributedDB::KvStoreDelegateManager *delegateManager, const std::string &appId, - const std::string &accountId); - - static std::shared_ptr GetInstance(const std::string &bundleName, - const std::string &dataDir, - const std::string &userId); - - virtual ~AppDistributedKvDataManagerImpl(); - - Status GetKvStore(const Options &options, const std::string &storeId, - const std::function appKvStore)> &callback) override; - - Status CloseKvStore(std::unique_ptr appKvStore) override; - - Status DeleteKvStore(const std::string &storeId) override; - - Status GetKvStoreDiskSize(const std::string &storeId, uint64_t &size) override; - - Status RegisterKvStoreCorruptionObserver(const std::shared_ptr observer) override; -private: - static DistributedDB::SecurityOption ConvertSecurityLevel(int securityLevel); - - static std::mutex storeMutex_; - - static std::map> managers_; - // pointer of class DistributedDB::KvStoreDelegateManager. defined as void* to avoid exposing inside implementions. - DistributedDB::KvStoreDelegateManager *kvStoreDelegateManager_; - std::string appId_; - std::string accountId_; - std::shared_ptr corruptionObserver_; -}; // class AppDistributedKvDataManagerImpl -} // namespace AppDistributedKv -} // namespace OHOS -#endif // APP_DISTRIBUTED_KV_DATA_MANAGER_IMPL_H diff --git a/frameworks/innerkitsimpl/distributeddatafwk/src/app_kvstore_conflict_data_impl.cpp b/frameworks/innerkitsimpl/distributeddatafwk/src/app_kvstore_conflict_data_impl.cpp deleted file mode 100755 index c8582e891974a7fb0d48068fe677324c5f195dd6..0000000000000000000000000000000000000000 --- a/frameworks/innerkitsimpl/distributeddatafwk/src/app_kvstore_conflict_data_impl.cpp +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#define LOG_TAG "AppKvStoreConflictDataImpl" - -#include "app_kvstore_conflict_data_impl.h" -#include "log_print.h" - -namespace OHOS { -namespace AppDistributedKv { -AppKvStoreConflictDataImpl::AppKvStoreConflictDataImpl(const KvStoreConflictEntry &kvStoreConflictEntry) - : kvStoreConflictEntry_(kvStoreConflictEntry) -{ - ZLOGI("constructor"); -} - -AppKvStoreConflictDataImpl::~AppKvStoreConflictDataImpl() -{ - ZLOGI("destructor"); -} - -AppKvStoreConflictPolicyType AppKvStoreConflictDataImpl::GetType() const -{ - return static_cast(kvStoreConflictEntry_.type); -} - -void AppKvStoreConflictDataImpl::GetKey(Key &key) const -{ - key = kvStoreConflictEntry_.key; -} - -Status AppKvStoreConflictDataImpl::GetValue(ConflictValueType type, Value &value) const -{ - if (type == ConflictValueType::OLD_VALUE) { - if (!kvStoreConflictEntry_.oldData.isDeleted) { - value = kvStoreConflictEntry_.oldData.value; - } - return kvStoreConflictEntry_.oldData.status; - } else { - if (!kvStoreConflictEntry_.newData.isDeleted) { - value = kvStoreConflictEntry_.newData.value; - } - return kvStoreConflictEntry_.newData.status; - } -} - -bool AppKvStoreConflictDataImpl::IsDeleted(ConflictValueType type) const -{ - if (type == ConflictValueType::OLD_VALUE) { - return kvStoreConflictEntry_.oldData.isDeleted; - } - return kvStoreConflictEntry_.newData.isDeleted; -} - -bool AppKvStoreConflictDataImpl::IsNative(ConflictValueType type) const -{ - if (type == ConflictValueType::OLD_VALUE) { - return kvStoreConflictEntry_.oldData.isLocal; - } else { - return kvStoreConflictEntry_.newData.isLocal; - } -} -} // namespace AppDistributedKv -} // namespace OHOS diff --git a/frameworks/innerkitsimpl/distributeddatafwk/src/app_kvstore_conflict_data_impl.h b/frameworks/innerkitsimpl/distributeddatafwk/src/app_kvstore_conflict_data_impl.h deleted file mode 100644 index 75c91de5216958f494eea74c616979f7d58c0be7..0000000000000000000000000000000000000000 --- a/frameworks/innerkitsimpl/distributeddatafwk/src/app_kvstore_conflict_data_impl.h +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef APP_KVSTORE_CONFLICT_DATA_IMPL_H -#define APP_KVSTORE_CONFLICT_DATA_IMPL_H - -#include "app_kvstore_conflict_data.h" -#include "app_types.h" -#include "kv_store_nb_conflict_data.h" - -namespace OHOS { -namespace AppDistributedKv { -struct KvStoreConflictData { - Value value {}; - bool isDeleted = false; - bool isLocal = false; - Status status {}; -}; - -struct KvStoreConflictEntry { - int type = 1; - Key key {}; - KvStoreConflictData oldData {}; - KvStoreConflictData newData {}; -}; - -class AppKvStoreConflictDataImpl final : public AppKvStoreConflictData { -public: - explicit AppKvStoreConflictDataImpl(const KvStoreConflictEntry &kvStoreConflictEntry); - - ~AppKvStoreConflictDataImpl(); - - AppKvStoreConflictPolicyType GetType() const override; - - void GetKey(Key &key) const override; - - Status GetValue(ConflictValueType type, Value &value) const override; - - bool IsDeleted(ConflictValueType type) const override; - - bool IsNative(ConflictValueType type) const override; - -private: - const KvStoreConflictEntry kvStoreConflictEntry_; -}; -} // namespace AppDistributedKv -} // namespace OHOS - -#endif // APP_KVSTORE_CONFLICT_DATA_IMPL_H diff --git a/frameworks/innerkitsimpl/distributeddatafwk/src/app_kvstore_impl.cpp b/frameworks/innerkitsimpl/distributeddatafwk/src/app_kvstore_impl.cpp deleted file mode 100755 index 2ce544b7ad396ed1a9d52194b4b126468a85d652..0000000000000000000000000000000000000000 --- a/frameworks/innerkitsimpl/distributeddatafwk/src/app_kvstore_impl.cpp +++ /dev/null @@ -1,562 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#define LOG_TAG "AppKvStoreImpl" - -#include "app_kvstore_impl.h" -#include -#include -#include -#include "app_kvstore_result_set_impl.h" -#include "app_types.h" -#include "log_print.h" -#include "types.h" -#include "reporter.h" - -namespace OHOS { -namespace AppDistributedKv { -using namespace std::chrono_literals; -using namespace OHOS::DistributedKv; -AppKvStoreImpl::AppKvStoreImpl(const std::string &storeId, DistributedDB::KvStoreNbDelegate *kvStoreNbDelegate) - : storeId_(storeId), kvStoreNbDelegate_(kvStoreNbDelegate) -{ - ZLOGI("constructor appkvstore"); -} - -AppKvStoreImpl::~AppKvStoreImpl() -{ - ZLOGI("destructor appKvStore."); - // This function will be called after DB close, so every Subscribe/Unsubscribe call will fail and no more element - // will be added to observer maps. - { - std::lock_guard localLock(localObserverMapMutex_); - for (auto const &iter : localObserverMap_) { - delete iter.second; - } - localObserverMap_.clear(); - } - { - std::lock_guard syncLock(syncedObserverMapMutex_); - for (auto const &iter : syncedObserverMap_) { - delete iter.second; - } - syncedObserverMap_.clear(); - } -} - -// Get id of this AppKvStore. -const std::string &AppKvStoreImpl::GetStoreId() -{ - return storeId_; -} - -// options: Mark this is a local entry or not. -Status AppKvStoreImpl::Put(const WriteOptions &options, const Key &key, const Value &value) -{ - ZLOGD("start"); - auto trimmedKey = DistributedKv::Constant::TrimCopy>(key.Data()); - // Restrict key and value size to interface specification. - if (trimmedKey.size() == 0 || trimmedKey.size() > DistributedKv::Constant::MAX_KEY_LENGTH || - value.Data().size() > DistributedKv::Constant::MAX_VALUE_LENGTH) { - ZLOGW("invalid_argument."); - return Status::INVALID_ARGUMENT; - } - DistributedDB::Key tmpKey = trimmedKey; - DistributedDB::Value tmpValue = value.Data(); - DistributedDB::DBStatus status; - if (options.local) { - status = kvStoreNbDelegate_->PutLocal(tmpKey, tmpValue); - } else { - status = kvStoreNbDelegate_->Put(tmpKey, tmpValue); - } - if (status == DistributedDB::DBStatus::OK) { - ZLOGD("put succeed."); - Reporter::GetInstance()->VisitStatistic()->Report({appId_, __FUNCTION__}); - return Status::SUCCESS; - } - ZLOGW("put failed. status: %d.", static_cast(status)); - return ConvertErrorCode(status); -} - -// options: mark this delete is a local change or not. -Status AppKvStoreImpl::Delete(const WriteOptions &options, const Key &key) -{ - ZLOGD("start."); - auto trimmedKey = DistributedKv::Constant::TrimCopy>(key.Data()); - if (trimmedKey.size() == 0 || trimmedKey.size() > DistributedKv::Constant::MAX_KEY_LENGTH) { - ZLOGW("invalid argument."); - return Status::INVALID_ARGUMENT; - } - DistributedDB::Key tmpKey = trimmedKey; - DistributedDB::DBStatus status; - if (options.local) { - status = kvStoreNbDelegate_->DeleteLocal(tmpKey); - } else { - status = kvStoreNbDelegate_->Delete(tmpKey); - } - if (status == DistributedDB::DBStatus::OK) { - ZLOGD("succeed."); - Reporter::GetInstance()->VisitStatistic()->Report({appId_, __FUNCTION__}); - return Status::SUCCESS; - } - ZLOGW("failed status: %d.", static_cast(status)); - return ConvertErrorCode(status); -} - -// Get value from AppKvStore by its key. Set options->local to true if you want to get from local kvstore. -// Parameters: -// options: mark we get from local store or remote store. options->batch is a reserved parameter and should -// always be false. -Status AppKvStoreImpl::Get(const ReadOptions &options, const Key &key, Value &value) -{ - ZLOGD("start"); - auto trimmedKey = DistributedKv::Constant::TrimCopy>(key.Data()); - if (trimmedKey.size() == 0 || trimmedKey.size() > DistributedKv::Constant::MAX_KEY_LENGTH) { - return Status::INVALID_ARGUMENT; - } - DistributedDB::Key tmpKey = trimmedKey; - DistributedDB::Value tmpValue; - DistributedDB::DBStatus status; - if (options.local) { - status = kvStoreNbDelegate_->GetLocal(tmpKey, tmpValue); - } else { - status = kvStoreNbDelegate_->Get(tmpKey, tmpValue); - } - ZLOGD("status: %d.", static_cast(status)); - // Value don't have other write method. - Value tmpValueForCopy(tmpValue); - value = tmpValueForCopy; - if (status == DistributedDB::DBStatus::OK) { - Reporter::GetInstance()->VisitStatistic()->Report({appId_, __FUNCTION__}); - return Status::SUCCESS; - } - return ConvertErrorCode(status); -} - -// Get all entries in this store which key start with prefixKey. -// Parameters: -// options: mark we get from local store or remote store. options->batch is a reserved parameter and should -// always be false. -Status AppKvStoreImpl::GetEntries(const Key &prefixKey, std::vector &entries) -{ - ZLOGD("start."); - auto trimmedPrefix = DistributedKv::Constant::TrimCopy>(prefixKey.Data()); - if (trimmedPrefix.size() > DistributedKv::Constant::MAX_KEY_LENGTH) { - return Status::INVALID_ARGUMENT; - } - DistributedDB::Key tmpKeyPrefix = trimmedPrefix; - std::vector dbEntries; - DistributedDB::DBStatus status = kvStoreNbDelegate_->GetEntries(tmpKeyPrefix, dbEntries); - if (status == DistributedDB::DBStatus::OK) { - entries.reserve(dbEntries.size()); - ZLOGD("vector size: %zu status: %d.", dbEntries.size(), static_cast(status)); - for (auto const &dbEntry : dbEntries) { - Key tmpKey(dbEntry.key); - Value tmpValue(dbEntry.value); - entries.push_back({.key = tmpKey, .value = tmpValue}); - } - return Status::SUCCESS; - } - return ConvertErrorCode(status); -} - -// Get all entries in this store which key start with prefixKey. -Status AppKvStoreImpl::GetEntries(const Key &prefixKey, AppKvStoreResultSet *&resultSet) -{ - ZLOGD("start."); - auto trimmedPrefix = DistributedKv::Constant::TrimCopy>(prefixKey.Data()); - if (trimmedPrefix.size() > DistributedKv::Constant::MAX_KEY_LENGTH) { - return Status::INVALID_ARGUMENT; - } - DistributedDB::Key tmpKeyPrefix = trimmedPrefix; - DistributedDB::KvStoreResultSet *dbResultSet = nullptr; - DistributedDB::DBStatus status = kvStoreNbDelegate_->GetEntries(tmpKeyPrefix, dbResultSet); - if (status == DistributedDB::DBStatus::OK) { - resultSet = new (std::nothrow) AppKvStoreResultSetImpl(dbResultSet, kvStoreNbDelegate_); - if (resultSet == nullptr) { - ZLOGW("new resultSet failed."); - return Status::ERROR; - } - return Status::SUCCESS; - } - return ConvertErrorCode(status); -} - -// Close the result set returned by GetEntries(). -Status AppKvStoreImpl::CloseResultSet(AppKvStoreResultSet *&resultSet) -{ - if (resultSet == nullptr) { - return Status::INVALID_ARGUMENT; - } - if (resultSet->Close() == Status::SUCCESS) { - delete resultSet; - resultSet = nullptr; - return Status::SUCCESS; - } - return Status::ERROR; -} - -// Close this kvstore in KvStoreDelegateManager. This method is called before this store object destruct. -Status AppKvStoreImpl::Close(DistributedDB::KvStoreDelegateManager *kvStoreDelegateManager) -{ - if (kvStoreDelegateManager == nullptr) { - return Status::INVALID_ARGUMENT; - } - - DistributedDB::DBStatus status = kvStoreDelegateManager->CloseKvStore(kvStoreNbDelegate_); - if (status == DistributedDB::DBStatus::OK) { - VisitStat vs { appId_, __FUNCTION__ }; - Reporter::GetInstance()->VisitStatistic()->Report(vs); - return Status::SUCCESS; - } - return Status::ERROR; -} - -// Sync store with other devices. This is an asynchronous method, -// sync will fail if there is a syncing operation in progress. -// Parameters: -// deviceIds: device list to sync. -// mode: mode can be set to SyncMode::PUSH, SyncMode::PULL and SyncMode::PUTH_PULL. PUSH_PULL will firstly -// push all not-local store to listed devices, then pull these stores back. -// callback: return map to caller. -// Return: -// Status of this Sync operation. -Status AppKvStoreImpl::Sync(const std::vector &deviceIds, SyncMode mode, - const std::function &)> &callback) -{ - ZLOGD("start."); - DistributedDB::DBStatus status; - DistributedDB::SyncMode dbMode; - if (mode == SyncMode::PUSH) { - dbMode = DistributedDB::SyncMode::SYNC_MODE_PUSH_ONLY; - } else if (mode == SyncMode::PULL) { - dbMode = DistributedDB::SyncMode::SYNC_MODE_PULL_ONLY; - } else { - dbMode = DistributedDB::SyncMode::SYNC_MODE_PUSH_PULL; - } - - bool syncStatus = syncStatus_.try_lock(); - if (!syncStatus) { - ZLOGW("Another sync operation still in progress, still call sync right now."); - } - status = kvStoreNbDelegate_->Sync(deviceIds, dbMode, - [&, callback](const std::map &devices) { - syncStatus_.unlock(); - std::map resultMap; - for (auto device : devices) { - if (device.second == DistributedDB::DBStatus::OK) { - resultMap[device.first] = Status::SUCCESS; - } else if (device.second == DistributedDB::DBStatus::NOT_FOUND) { - resultMap[device.first] = Status::DEVICE_NOT_FOUND; - } else if (device.second == DistributedDB::DBStatus::TIME_OUT) { - resultMap[device.first] = Status::TIME_OUT; - } else { - resultMap[device.first] = Status::ERROR; - } - } - ZLOGD("callback."); - callback(resultMap); - }); - - ZLOGD("end: %d", static_cast(status)); - Reporter::GetInstance()->VisitStatistic()->Report({appId_, __FUNCTION__}); - if (status == DistributedDB::DBStatus::OK) { - return Status::SUCCESS; - } - return ConvertErrorCode(status); -} - -// Register change of this kvstore to a client-defined observer. observer->OnChange method will be called when store -// changes. One observer can subscribe more than one AppKvStore. -// Parameters: -// options: mark this is a local entry or not. -// subscribeType: OBSERVER_CHANGES_NATIVE means native changes of syncable kv store, -// : OBSERVER_CHANGES_FOREIGN means synced data changes from remote devices, -// : OBSERVER_CHANGES_ALL means both native changes and synced data changes. -// observer: observer to subscribe changes. -// Return: -// Status of this subscribe operation. -Status AppKvStoreImpl::SubscribeKvStore(const ReadOptions &options, const SubscribeType &subscribeType, - AppKvStoreObserver *observer) -{ - ZLOGD("start."); - if (observer == nullptr) { - return Status::INVALID_ARGUMENT; - } - DistributedDB::DBStatus dbStatus; - KvStoreObserverNbImpl *nbObserver = new (std::nothrow) KvStoreObserverNbImpl(observer, subscribeType); - if (nbObserver == nullptr) { - ZLOGW("new KvStoreObserverNbImpl failed"); - return Status::ERROR; - } - DistributedDB::Key emptyKey; - if (options.local) { - std::lock_guard lock(localObserverMapMutex_); - bool alreadySubscribed = (localObserverMap_.find(observer) != localObserverMap_.end()); - if (alreadySubscribed) { - delete nbObserver; - return Status::STORE_ALREADY_SUBSCRIBE; - } - - dbStatus = kvStoreNbDelegate_->RegisterObserver( - emptyKey, DistributedDB::ObserverMode::OBSERVER_CHANGES_LOCAL_ONLY, nbObserver); - if (dbStatus == DistributedDB::DBStatus::OK) { - localObserverMap_.insert(std::pair(observer, nbObserver)); - } - } else { - std::lock_guard lock(syncedObserverMapMutex_); - bool alreadySubscribed = (syncedObserverMap_.find(observer) != syncedObserverMap_.end()); - if (alreadySubscribed) { - delete nbObserver; - return Status::STORE_ALREADY_SUBSCRIBE; - } - int dbObserverMode; - if (subscribeType == SubscribeType::OBSERVER_CHANGES_NATIVE) { - dbObserverMode = DistributedDB::ObserverMode::OBSERVER_CHANGES_NATIVE; - } else if (subscribeType == SubscribeType::OBSERVER_CHANGES_FOREIGN) { - dbObserverMode = DistributedDB::ObserverMode::OBSERVER_CHANGES_FOREIGN; - } else { - dbObserverMode = DistributedDB::ObserverMode::OBSERVER_CHANGES_FOREIGN | - DistributedDB::ObserverMode::OBSERVER_CHANGES_NATIVE; - } - dbStatus = kvStoreNbDelegate_->RegisterObserver(emptyKey, dbObserverMode, nbObserver); - if (dbStatus == DistributedDB::DBStatus::OK) { - syncedObserverMap_.insert(std::pair(observer, nbObserver)); - } - } - Reporter::GetInstance()->VisitStatistic()->Report({appId_, __FUNCTION__}); - if (dbStatus == DistributedDB::DBStatus::OK) { - return Status::SUCCESS; - } - - delete nbObserver; - if (dbStatus == DistributedDB::DBStatus::INVALID_ARGS) { - return Status::INVALID_ARGUMENT; - } - if (dbStatus == DistributedDB::DBStatus::DB_ERROR) { - return Status::DB_ERROR; - } - return Status::ERROR; -} - -// Unregister a kvstore to an observer. -// Parameters: -// options: mark this is a local entry or not. -// subscribeType: OBSERVER_CHANGES_NATIVE means native changes of syncable kv store, -// : OBSERVER_CHANGES_FOREIGN means synced data changes from remote devices, -// : OBSERVER_CHANGES_ALL means both native changes and synced data changes. -// observer: observer to unsubscribe this store. -// Return: -// Status of this unsubscribe operation. -Status AppKvStoreImpl::UnSubscribeKvStore(const ReadOptions &options, const SubscribeType &subscribeType, - AppKvStoreObserver *observer) -{ - ZLOGD("start."); - if (observer == nullptr) { - return Status::INVALID_ARGUMENT; - } - DistributedDB::DBStatus dbStatus; - if (options.local) { - std::lock_guard lock(localObserverMapMutex_); - auto nbObserver = localObserverMap_.find(observer); - if (nbObserver == localObserverMap_.end()) { - return Status::STORE_NOT_SUBSCRIBE; - } - dbStatus = kvStoreNbDelegate_->UnRegisterObserver(nbObserver->second); - if (dbStatus == DistributedDB::DBStatus::OK) { - delete nbObserver->second; - localObserverMap_.erase(nbObserver); - } - } else { - std::lock_guard lock(syncedObserverMapMutex_); - auto nbObserver = syncedObserverMap_.find(observer); - if (nbObserver == syncedObserverMap_.end()) { - return Status::STORE_NOT_SUBSCRIBE; - } - dbStatus = kvStoreNbDelegate_->UnRegisterObserver(nbObserver->second); - if (dbStatus == DistributedDB::DBStatus::OK) { - delete nbObserver->second; - syncedObserverMap_.erase(nbObserver); - } - } - Reporter::GetInstance()->VisitStatistic()->Report({appId_, __FUNCTION__}); - if (dbStatus == DistributedDB::DBStatus::OK) { - return Status::SUCCESS; - } - if (dbStatus == DistributedDB::DBStatus::NOT_FOUND) { - return Status::STORE_NOT_SUBSCRIBE; - } - if (dbStatus == DistributedDB::DBStatus::INVALID_ARGS) { - return Status::INVALID_ARGUMENT; - } - return Status::ERROR; -} - -Status AppKvStoreImpl::RemoveDeviceData(const std::string &device) -{ - ZLOGD("start"); - DistributedDB::DBStatus status = kvStoreNbDelegate_->RemoveDeviceData(device); - if (status == DistributedDB::DBStatus::OK) { - return Status::SUCCESS; - } - return Status::ERROR; -} - -Status AppKvStoreImpl::SetConflictResolutionPolicy( - AppKvStoreConflictPolicyType appConflictPolicyType, - std::function callback) -{ - ZLOGD("start."); - int conflictType = static_cast(appConflictPolicyType); - DistributedDB::DBStatus dbStatus = kvStoreNbDelegate_->SetConflictNotifier( - conflictType, [callback, this](const DistributedDB::KvStoreNbConflictData &kvStoreNbConflictData) { - ZLOGD("callback "); - KvStoreConflictEntry kvstoreConflictEntry; - FormKvStoreConflictEntry(kvStoreNbConflictData, kvstoreConflictEntry); - AppKvStoreConflictDataImpl appConflictDataImpl(kvstoreConflictEntry); - callback(appConflictDataImpl); - }); - if (dbStatus != DistributedDB::DBStatus::OK) { - return Status::DB_ERROR; - } - return Status::SUCCESS; -} - -void AppKvStoreImpl::FormKvStoreConflictEntry(const DistributedDB::KvStoreNbConflictData &data, - KvStoreConflictEntry &kvstoreConflictEntry) -{ - kvstoreConflictEntry.type = data.GetType(); - DistributedDB::Key dbKey; - data.GetKey(dbKey); - Key tmpKey(dbKey); - kvstoreConflictEntry.key = tmpKey; - FormKvStoreConflictData(data, DistributedDB::KvStoreNbConflictData::ValueType::OLD_VALUE, - kvstoreConflictEntry.oldData); - FormKvStoreConflictData(data, DistributedDB::KvStoreNbConflictData::ValueType::NEW_VALUE, - kvstoreConflictEntry.newData); -} - -void AppKvStoreImpl::FormKvStoreConflictData(const DistributedDB::KvStoreNbConflictData &data, - DistributedDB::KvStoreNbConflictData::ValueType type, - KvStoreConflictData &kvStoreConflictData) -{ - DistributedDB::DBStatus dbStatus; - kvStoreConflictData.isLocal = data.IsNative(type); - kvStoreConflictData.isDeleted = data.IsDeleted(type); - if (!kvStoreConflictData.isDeleted) { - DistributedDB::Value dbValue; - dbStatus = data.GetValue(type, dbValue); - if (dbStatus != DistributedDB::DBStatus::OK) { - ZLOGE("Failed to handle conflict, error: bad conflict data"); - kvStoreConflictData.status = Status::DB_ERROR; - return; - } - Value tmpValue(dbValue); - kvStoreConflictData.status = Status::SUCCESS; - kvStoreConflictData.value = tmpValue; - } -} - -Status AppKvStoreImpl::Export(const std::string &filePath, const std::vector &passwd) -{ - ZLOGD("export start"); - if (filePath.empty()) { - return Status::INVALID_ARGUMENT; - } - DistributedDB::CipherPassword password; - auto status = password.SetValue(passwd.data(), passwd.size()); - if (status != DistributedDB::CipherPassword::ErrorCode::OK) { - ZLOGE("Failed to set the passwd."); - return Status::DB_ERROR; - } - DistributedDB::DBStatus dbStatus = kvStoreNbDelegate_->Export(filePath, password); - if (dbStatus != DistributedDB::DBStatus::OK) { - ZLOGE("Failed to export, path:%s", filePath.c_str()); - return Status::DB_ERROR; - } - ZLOGD("export end"); - return Status::SUCCESS; -} - -Status AppKvStoreImpl::Import(const std::string &filePath, const std::vector &passwd) -{ - ZLOGD("Import start"); - if (filePath.empty()) { - return Status::INVALID_ARGUMENT; - } - DistributedDB::CipherPassword password; - auto status = password.SetValue(passwd.data(), passwd.size()); - if (status != DistributedDB::CipherPassword::ErrorCode::OK) { - ZLOGE("Failed to set the passwd."); - return Status::DB_ERROR; - } - DistributedDB::DBStatus dbStatus = kvStoreNbDelegate_->Import(filePath, password); - if (dbStatus != DistributedDB::DBStatus::OK) { - ZLOGE("Failed to export, path:%s", filePath.c_str()); - return Status::DB_ERROR; - } - ZLOGD("Import end"); - return Status::SUCCESS; -} - -Status AppKvStoreImpl::GetSecurityLevel(SecurityLevel &securityLevel) const -{ - ZLOGD("start"); - DistributedDB::SecurityOption option; - DistributedDB::DBStatus dbStatus = kvStoreNbDelegate_->GetSecurityOption(option); - if (dbStatus != DistributedDB::DBStatus::OK) { - ZLOGE("Failed to get security level"); - return Status::DB_ERROR; - } - switch (option.securityLabel) { - case DistributedDB::NOT_SET: - case DistributedDB::S0: - case DistributedDB::S1: - case DistributedDB::S2: - securityLevel = static_cast(option.securityLabel); - break; - case DistributedDB::S3: - securityLevel = option.securityFlag ? S3 : S3_EX; - break; - case DistributedDB::S4: - securityLevel = S4; - break; - default: - break; - } - ZLOGD("end"); - return Status::SUCCESS; -} - -Status AppKvStoreImpl::ConvertErrorCode(DistributedDB::DBStatus status) -{ - switch (status) { - case DistributedDB::DBStatus::BUSY: - case DistributedDB::DBStatus::DB_ERROR: - return Status::DB_ERROR; - case DistributedDB::DBStatus::NOT_FOUND: - return Status::KEY_NOT_FOUND; - case DistributedDB::DBStatus::INVALID_ARGS: - return Status::INVALID_ARGUMENT; - case DistributedDB::DBStatus::EKEYREVOKED_ERROR: - case DistributedDB::DBStatus::SECURITY_OPTION_CHECK_ERROR: - return Status::SECURITY_LEVEL_ERROR; - default: - break; - } - return Status::ERROR; -} -} // namespace AppDistributedKv -} // namespace OHOS diff --git a/frameworks/innerkitsimpl/distributeddatafwk/src/app_kvstore_impl.h b/frameworks/innerkitsimpl/distributeddatafwk/src/app_kvstore_impl.h deleted file mode 100755 index c8b61abe2c56ddd57712756484da71af9d744000..0000000000000000000000000000000000000000 --- a/frameworks/innerkitsimpl/distributeddatafwk/src/app_kvstore_impl.h +++ /dev/null @@ -1,189 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef APP_KV_STORE_IMPL_H -#define APP_KV_STORE_IMPL_H - -#include -#include -#include "app_kvstore.h" -#include "app_kvstore_conflict_data_impl.h" -#include "app_kvstore_observer.h" -#include "app_kvstore_result_set.h" -#include "app_types.h" -#include "constant.h" -#include "kv_store_delegate_manager.h" -#include "kv_store_nb_delegate.h" -#include "kvstore_observer_nb_impl.h" - -namespace OHOS { -namespace AppDistributedKv { -class AppKvStoreImpl : public AppKvStore { -public: - AppKvStoreImpl(const std::string &storeId, DistributedDB::KvStoreNbDelegate *kvStoreNbDelegate); - - AppKvStoreImpl(AppKvStoreImpl &&) = delete; - AppKvStoreImpl &operator=(AppKvStoreImpl &&) = delete; - - // forbidden copy constructor. - AppKvStoreImpl(const AppKvStoreImpl &) = delete; - AppKvStoreImpl &operator=(const AppKvStoreImpl &) = delete; - - virtual ~AppKvStoreImpl(); - - // Get id of this AppKvStore. - const std::string &GetStoreId() override; - - // Write a pair of key and value to this store. Set write option to local if you do not this entry sync to other - // devices. - // Parameters: - // options: mark this is a local entry or not. - // key: key of this entry. Should be less than 256 bytes. key will be trimmed before store. - // value: value of this entry. Should be less than (1024 * 1024) bytes. - // Return: - // Status of this put operation. - Status Put(const WriteOptions &options, const Key &key, const Value &value) override; - - // Delete an entry by its key. Set write option to local if you want this delete to be a local change. - // Parameters: - // options: mark this delete is a local change or not. - // key: key of the entry to be deleted. - // Return: - // Status of this delete operation. - Status Delete(const WriteOptions &options, const Key &key) override; - - // Get value from AppKvStore by its key. Set options->local to true if you want to get from local kvstore. - // Parameters: - // options: mark we get from local store or remote store. options->batch is a reserved parameter and should - // always be false. - // key: key of this entry. - // value: value will be returned in this parameter. - // Return: - // Status of this get operation. - Status Get(const ReadOptions &options, const Key &key, Value &value) override; - - // Get all entries in this store which key start with prefixKey. This function will always get from synced store. - // Parameters: - // prefixkey: the prefix to be searched. - // entries: entries will be returned in this parameter. - // Return: - // Status of this GetEntries operation. - Status GetEntries(const Key &prefixKey, std::vector &entries) override; - - // Get all entries in this store which key start with prefixKey. This function will always get from synced store. - // Parameters: - // prefixkey: the prefix to be searched. - // resultSet: resultSet will be returned in this parameter. - // Return: - // Status of this GetEntries operation. - Status GetEntries(const Key &prefixKey, AppKvStoreResultSet *&resultSet) override; - - // Close the result set returned by GetEntries(). - // Parameters: - // resultSet: resultSet will be returned in this parameter. - // Return: - // Status of this GetEntries operation. - Status CloseResultSet(AppKvStoreResultSet *&resultSet) override; - - // Sync store with other devices. This is an asynchronous method, - // sync will fail if there is a syncing operation in progress. - // Parameters: - // deviceIds: device list to sync. - // mode: mode can be set to SyncMode::PUSH, SyncMode::PULL and SyncMode::PUTH_PULL. PUSH_PULL will firstly - // push all not-local store to listed devices, then pull these stores back. - // callback: return map to caller. - // Return: - // Status of this Sync operation. - Status Sync(const std::vector &deviceIds, SyncMode mode, - const std::function &)> &callback) override; - - // Register change of this kvstore to a client-defined observer. observer->OnChange method will be called when store - // changes. One observer can subscribe more than one AppKvStore. - // Parameters: - // options: mark this is a local entry or not. - // subscribeType: OBSERVER_CHANGES_NATIVE means native changes of syncable kv store, - // : OBSERVER_CHANGES_FOREIGN means synced data changes from remote devices, - // : OBSERVER_CHANGES_ALL means both native changes and synced data changes. - // observer: observer to subscribe changes. - // Return: - // Status of this subscribe operation. - Status SubscribeKvStore(const ReadOptions &options, const SubscribeType &subscribeType, - AppKvStoreObserver *observer) override; - - // Unregister a kvstore to an observer. - // Parameters: - // options: mark this is a local entry or not. - // subscribeType: OBSERVER_CHANGES_NATIVE means native changes of syncable kv store, - // : OBSERVER_CHANGES_FOREIGN means synced data changes from remote devices, - // : OBSERVER_CHANGES_LOCAL_ONLY means local changes of local kv store. - // observer: observer to unsubscribe this store. - // Return: - // Status of this unsubscribe operation. - Status UnSubscribeKvStore(const ReadOptions &options, const SubscribeType &subscribeType, - AppKvStoreObserver *observer) override; - - // Close this kvstore in KvStoreDelegateManager. This method is called before this store object destruct. - Status Close(DistributedDB::KvStoreDelegateManager *kvStoreDelegateManager); - - // Remove Devvice data when device offline. - // Parameters: - // device: device id. - // Return: - // Status of this remove operation. - Status RemoveDeviceData(const std::string &device) override; - - // Set policy of conflict resolution. - // Parameters: - // appConflictPolicyType: include CONFLICT_FOREIGN_KEY_ONLY CONFLICT_FOREIGN_KEY_ORIG CONFLICT_NATIVE_ALL. - // callback: conflict resolution callback. - // Return: - // Status of Setting policy operation. - Status SetConflictResolutionPolicy(AppKvStoreConflictPolicyType appConflictPolicyType, - std::function callback) override; - - Status Export(const std::string &filePath, const std::vector &passwd) override; - - Status Import(const std::string &filePath, const std::vector &passwd) override; - - Status GetSecurityLevel(SecurityLevel &securityLevel) const override; - - static Status ConvertErrorCode(DistributedDB::DBStatus status); -private: - void FormKvStoreConflictEntry(const DistributedDB::KvStoreNbConflictData &data, - KvStoreConflictEntry &kvstoreConflictEntry); - void FormKvStoreConflictData(const DistributedDB::KvStoreNbConflictData &data, - DistributedDB::KvStoreNbConflictData::ValueType type, - KvStoreConflictData &kvStoreConflictData); - // user account get from User Account System. - std::string userId_; - // appId get from PMS. - std::string appId_; - // kvstore name. - std::string storeId_; - std::mutex syncStatus_ {}; - - // distributeddb is responsible for free kvStoreNbDelegate_, - // (destruct will be done while calling CloseKvStore in KvStoreDelegateManager) - // so DO NOT free it in AppKvStoreImpl's destructor. - DistributedDB::KvStoreNbDelegate *kvStoreNbDelegate_ = nullptr; - - std::map syncedObserverMap_ {}; - std::mutex syncedObserverMapMutex_ {}; - std::map localObserverMap_ {}; - std::mutex localObserverMapMutex_ {}; -}; -} // namespace AppDistributedKv -} // namespace OHOS -#endif // APP_KV_STORE_IMPL_H diff --git a/frameworks/innerkitsimpl/distributeddatafwk/src/app_kvstore_result_set_impl.cpp b/frameworks/innerkitsimpl/distributeddatafwk/src/app_kvstore_result_set_impl.cpp deleted file mode 100755 index 0cecd9a0f3082d96e3f9aa0d3f6dd59073a40285..0000000000000000000000000000000000000000 --- a/frameworks/innerkitsimpl/distributeddatafwk/src/app_kvstore_result_set_impl.cpp +++ /dev/null @@ -1,148 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#define LOG_TAG "AppKvStoreResultSetImpl" - -#include "app_kvstore_result_set_impl.h" -#include "app_types.h" - -namespace OHOS { -namespace AppDistributedKv { -const int AppKvStoreResultSetImpl::INIT_POSTION = -1; - -AppKvStoreResultSetImpl::AppKvStoreResultSetImpl(DistributedDB::KvStoreResultSet *resultSet, - DistributedDB::KvStoreNbDelegate *delegate) - : kvStoreResultSet_(resultSet), nbDelegate_(delegate) -{ -} - -AppKvStoreResultSetImpl::~AppKvStoreResultSetImpl() -{ -} - -// Returns the count of rows in the result set. -int AppKvStoreResultSetImpl::GetCount() const -{ - return (kvStoreResultSet_ == nullptr) ? 0 : kvStoreResultSet_->GetCount(); -} - -// Returns the current read position of the result set. -int AppKvStoreResultSetImpl::GetPosition() const -{ - return (kvStoreResultSet_ == nullptr) ? INIT_POSTION : kvStoreResultSet_->GetPosition(); -} - -// Move the read position to the first row, return false if the result set is empty. -bool AppKvStoreResultSetImpl::MoveToFirst() -{ - return (kvStoreResultSet_ == nullptr) ? false : kvStoreResultSet_->MoveToFirst(); -} - -// Move the read position to the last row, return false if the result set is empty. -bool AppKvStoreResultSetImpl::MoveToLast() -{ - return (kvStoreResultSet_ == nullptr) ? false : kvStoreResultSet_->MoveToLast(); -} - -// Move the read position to the next row, -// return false if the result set is empty or the read position is already past the last entry in the result set. -bool AppKvStoreResultSetImpl::MoveToNext() -{ - return (kvStoreResultSet_ == nullptr) ? false : kvStoreResultSet_->MoveToNext(); -} - -// Move the read position to the previous row, -// return false if the result set is empty or the read position is already before the first entry in the result set. -bool AppKvStoreResultSetImpl::MoveToPrevious() -{ - return (kvStoreResultSet_ == nullptr) ? false : kvStoreResultSet_->MoveToPrevious(); -} - -// Move the read position by a relative amount from the current position. -bool AppKvStoreResultSetImpl::Move(int offset) -{ - return (kvStoreResultSet_ == nullptr) ? false : kvStoreResultSet_->Move(offset); -} - -// Move the read position to an absolute position value. -bool AppKvStoreResultSetImpl::MoveToPosition(int position) -{ - return (kvStoreResultSet_ == nullptr) ? false : kvStoreResultSet_->MoveToPosition(position); -} - -// Returns whether the read position is pointing to the first row. -bool AppKvStoreResultSetImpl::IsFirst() const -{ - return (kvStoreResultSet_ == nullptr) ? false : kvStoreResultSet_->IsFirst(); -} - -// Returns whether the read position is pointing to the last row. -bool AppKvStoreResultSetImpl::IsLast() const -{ - return (kvStoreResultSet_ == nullptr) ? false : kvStoreResultSet_->IsLast(); -} - -// Returns whether the read position is before the first row. -bool AppKvStoreResultSetImpl::IsBeforeFirst() const -{ - return (kvStoreResultSet_ == nullptr) ? false : kvStoreResultSet_->IsBeforeFirst(); -} - -// Returns whether the read position is after the last row -bool AppKvStoreResultSetImpl::IsAfterLast() const -{ - return (kvStoreResultSet_ == nullptr) ? false : kvStoreResultSet_->IsAfterLast(); -} - -// Get a key-value entry. -Status AppKvStoreResultSetImpl::GetEntry(Entry &entry) const -{ - if (kvStoreResultSet_ == nullptr) { - return Status::ERROR; - } - if (GetCount() == 0) { - return Status::KEY_NOT_FOUND; - } - DistributedDB::Entry dbEntry; - DistributedDB::DBStatus dbStatus = kvStoreResultSet_->GetEntry(dbEntry); - if (dbStatus == DistributedDB::DBStatus::OK) { - Key tmpKey(dbEntry.key); - Value tmpValue(dbEntry.value); - entry.key = tmpKey; - entry.value = tmpValue; - return Status::SUCCESS; - } - return Status::KEY_NOT_FOUND; -} - -Status AppKvStoreResultSetImpl::Close() -{ - if (kvStoreResultSet_ == nullptr) { - return Status::SUCCESS; - } - - if (nbDelegate_ == nullptr) { - return Status::INVALID_ARGUMENT; - } - - auto result = nbDelegate_->CloseResultSet(kvStoreResultSet_); - if (result == DistributedDB::DBStatus::OK) { - return Status::SUCCESS; - } - kvStoreResultSet_ = nullptr; - return Status::ERROR; -} -} // namespace AppDistributedKv -} // namespace OHOS diff --git a/frameworks/innerkitsimpl/distributeddatafwk/src/app_kvstore_result_set_impl.h b/frameworks/innerkitsimpl/distributeddatafwk/src/app_kvstore_result_set_impl.h deleted file mode 100755 index e39eeda2905b4d1aba1a8e9f6103028e9fd22ddb..0000000000000000000000000000000000000000 --- a/frameworks/innerkitsimpl/distributeddatafwk/src/app_kvstore_result_set_impl.h +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef APP_KV_STORE_RESULT_SET_IMPL_H -#define APP_KV_STORE_RESULT_SET_IMPL_H - -#include "app_kvstore_result_set.h" -#include "kv_store_nb_delegate.h" -#include "kv_store_result_set.h" - -namespace OHOS { -namespace AppDistributedKv { -class AppKvStoreResultSetImpl : public AppKvStoreResultSet { -public: - AppKvStoreResultSetImpl(DistributedDB::KvStoreResultSet *resultSet, DistributedDB::KvStoreNbDelegate *delegate); - - ~AppKvStoreResultSetImpl(); - - // Returns the count of rows in the result set. - int GetCount() const override; - - // Returns the current read position of the result set. - int GetPosition() const override; - - // Move the read position to the first row, return false if the result set is empty. - bool MoveToFirst() override; - - // Move the read position to the last row, return false if the result set is empty. - bool MoveToLast() override; - - // Move the read position to the next row, - // return false if the result set is empty or the read position is already past the last entry in the result set. - bool MoveToNext() override; - - // Move the read position to the previous row, - // return false if result set is empty or the read position is already before the first entry in the result set. - bool MoveToPrevious() override; - - // Move the read position by a relative amount from the current position. - bool Move(int offset) override; - - // Move the read position to an absolute position value. - bool MoveToPosition(int position) override; - - // Returns whether the read position is pointing to the first row. - bool IsFirst() const override; - - // Returns whether the read position is pointing to the last row. - bool IsLast() const override; - - // Returns whether the read position is before the first row. - bool IsBeforeFirst() const override; - - // Returns whether the read position is after the last row - bool IsAfterLast() const override; - - // Get a key-value entry. - Status GetEntry(Entry &entry) const override; - - Status Close() override; -private: - DistributedDB::KvStoreResultSet *kvStoreResultSet_ = nullptr; - DistributedDB::KvStoreNbDelegate *nbDelegate_ = nullptr; - static const int INIT_POSTION; -}; -} // namespace AppDistributedKv -} // namespace OHOS -#endif // APP_KV_STORE_RESULT_SET_IMPL_H \ No newline at end of file diff --git a/frameworks/innerkitsimpl/distributeddatafwk/test/BUILD.gn b/frameworks/innerkitsimpl/distributeddatafwk/test/BUILD.gn index b9a3b4f30fc9e8b4da5dde6d20f60e7a996c82ce..c8b4b6fe7ac2b5941f1d7ca1d47e6e5ad7bea597 100755 --- a/frameworks/innerkitsimpl/distributeddatafwk/test/BUILD.gn +++ b/frameworks/innerkitsimpl/distributeddatafwk/test/BUILD.gn @@ -156,81 +156,6 @@ ohos_unittest("BlobTest") { } ############################################################################### -config("app_test_config") { - visibility = [ ":*" ] - - include_dirs = [ - "../include/", - "../../../../interfaces/innerkits/app_distributeddata/include", - "//utils/native/base/include", - "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata/include", - ] -} - -ohos_unittest("AppDistributedKvStoreTest") { - module_out_path = module_output_path - - sources = [ "unittest/app_distributed_kv_store_test.cpp" ] - - configs = [ ":app_test_config" ] - - external_deps = [ "hiviewdfx_hilog_native:libhilog" ] - - deps = [ - "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/app_distributeddata/:app_distributeddata", - "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter:distributeddata_adapter", - "//third_party/googletest:gtest_main", - ] -} - -ohos_unittest("AppDistributedKvDataManagerTest") { - module_out_path = module_output_path - - sources = [ "unittest/app_distributed_kv_data_manager_test.cpp" ] - - configs = [ ":app_test_config" ] - - external_deps = [ "hiviewdfx_hilog_native:libhilog" ] - - deps = [ - "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/app_distributeddata/:app_distributeddata", - "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter:distributeddata_adapter", - "//third_party/googletest:gtest_main", - ] -} - -ohos_unittest("AppBlobTest") { - module_out_path = module_output_path - - sources = [ "unittest/app_blob_test.cpp" ] - - configs = [ ":app_test_config" ] - - external_deps = [ "hiviewdfx_hilog_native:libhilog" ] - - deps = [ - "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/app_distributeddata/:app_distributeddata", - "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter:distributeddata_adapter", - "//third_party/googletest:gtest_main", - ] -} - -ohos_unittest("AppConflictTest") { - module_out_path = module_output_path - - sources = [ "unittest/app_conflict_test.cpp" ] - - configs = [ ":app_test_config" ] - - external_deps = [ "hiviewdfx_hilog_native:libhilog" ] - - deps = [ - "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/app_distributeddata/:app_distributeddata", - "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter:distributeddata_adapter", - "//third_party/googletest:gtest_main", - ] -} - group("unittest") { testonly = true diff --git a/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/app_blob_test.cpp b/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/app_blob_test.cpp deleted file mode 100755 index 42c41d8e657180f622422bde1bcd68e99276049e..0000000000000000000000000000000000000000 --- a/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/app_blob_test.cpp +++ /dev/null @@ -1,196 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include -#include -#include "app_types.h" -using namespace testing::ext; -using namespace OHOS::AppDistributedKv; - -class AppBlobTest : public testing::Test { -public: - static void SetUpTestCase(void); - static void TearDownTestCase(void); - void SetUp(); - void TearDown(); -}; - -void AppBlobTest::SetUpTestCase(void) -{} - -void AppBlobTest::TearDownTestCase(void) -{} - -void AppBlobTest::SetUp(void) -{} - -void AppBlobTest::TearDown(void) -{} - -/** - * @tc.name: AppBlobSize001 - * @tc.desc: Construct a Blob and check its size. - * @tc.type: FUNC - * @tc.require: AR000CCPOL - * @tc.author: liqiao - */ -HWTEST_F(AppBlobTest, AppBlobSize001, TestSize.Level0) -{ - AppBlob blob1; - EXPECT_EQ(blob1.Size(), (size_t)0); - AppBlob blob2 = "1234567890"; - EXPECT_EQ(blob2.Size(), (size_t)10); - AppBlob blob3("12345"); - EXPECT_EQ(blob3.Size(), (size_t)5); - std::string strTmp = "123"; - const char *chr = strTmp.c_str(); - AppBlob blob4(chr); - EXPECT_EQ(blob4.Size(), (size_t)3); - std::vector vec = {'1', '2', '3', '4'}; - AppBlob blob5(vec); - EXPECT_EQ(blob5.Size(), (size_t)4); - const char *chr1 = strTmp.c_str(); - AppBlob blob6(chr1, strlen(chr1)); - EXPECT_EQ(blob6.Size(), (size_t)3); -} - -/** - * @tc.name: AppBlobEmpty001 - * @tc.desc: Construct a Blob and check its empty. - * @tc.type: FUNC - * @tc.require: AR000CCPOL - * @tc.author: liqiao - */ -HWTEST_F(AppBlobTest, AppBlobEmpty001, TestSize.Level0) -{ - AppBlob blob1; - EXPECT_EQ(blob1.Empty(), true); - AppBlob blob2 = "1234567890"; - EXPECT_EQ(blob2.Empty(), false); - AppBlob blob3("12345"); - EXPECT_EQ(blob3.Empty(), false); - std::string strTmp = "123"; - const char *chr = strTmp.c_str(); - AppBlob blob4(chr); - EXPECT_EQ(blob4.Empty(), false); - std::vector vec = {'1', '2', '3', '4'}; - AppBlob blob5(vec); - EXPECT_EQ(blob5.Empty(), false); - const char *chr1 = strTmp.c_str(); - AppBlob blob6(chr1, strlen(chr1)); - EXPECT_EQ(blob6.Empty(), false); -} - -/** - * @tc.name: AppBlobCompare001 - * @tc.desc: Construct a Blob and check its StartsWith function. - * @tc.type: FUNC - * @tc.require: AR000CCPOL - * @tc.author: liqiao - */ -HWTEST_F(AppBlobTest, AppBlobCompare001, TestSize.Level0) -{ - AppBlob blob1 = "1234567890"; - AppBlob blob2("12345"); - EXPECT_EQ(blob1.Compare(blob2), 1); - EXPECT_EQ(blob2.Compare(blob1), -1); - AppBlob blob3("12345"); - EXPECT_EQ(blob2.Compare(blob3), 0); -} - -/** - * @tc.name: AppBlobData001 - * @tc.desc: Construct a Blob and check its Data function. - * @tc.type: FUNC - * @tc.require: AR000CCPOL - * @tc.author: liqiao - */ -HWTEST_F(AppBlobTest, AppBlobData001, TestSize.Level0) -{ - std::vector result = {'1', '2', '3', '4'}; - AppBlob blob1("1234"); - EXPECT_EQ(blob1.Data(), result); - std::vector result2 = {'1', '2', '3', '4', '5'}; - AppBlob blob2("12345"); - EXPECT_EQ(blob2.Data(), result2); -} - -/** - * @tc.name: AppBlobToString001 - * @tc.desc: Construct a Blob and check its ToString function. - * @tc.type: FUNC - * @tc.require: AR000CCPOL - * @tc.author: liqiao - */ -HWTEST_F(AppBlobTest, AppBlobToString001, TestSize.Level0) -{ - AppBlob blob1("1234"); - std::string str = "1234"; - EXPECT_EQ(blob1.ToString(), str); -} - -/** - * @tc.name: AppBlobOperatorEqual001 - * @tc.desc: Construct a Blob and check its operator== function. - * @tc.type: FUNC - * @tc.require: AR000CCPOL - * @tc.author: liqiao - */ -HWTEST_F(AppBlobTest, AppBlobOperatorEqual001, TestSize.Level0) -{ - AppBlob blob1("1234"); - AppBlob blob2("1234"); - EXPECT_EQ(blob1 == blob2, true); - AppBlob blob3("12345"); - EXPECT_EQ(blob1 == blob3, false); -} - -/** - * @tc.name: AppBlobOperator002 - * @tc.desc: Construct a Blob and check its operator= function. - * @tc.type: FUNC - * @tc.require: AR000CCPOL - * @tc.author: liqiao - */ -HWTEST_F(AppBlobTest, AppBlobOperator002, TestSize.Level0) -{ - AppBlob blob1("1234"); - AppBlob blob2 = blob1; - EXPECT_EQ(blob1 == blob2, true); - EXPECT_EQ(blob2.ToString(), "1234"); - blob2 = blob1; - EXPECT_EQ(blob1 == blob2, true); - EXPECT_EQ(blob2.ToString(), "1234"); - blob2 = std::move(blob1); - EXPECT_EQ(blob1 == blob2, true); - EXPECT_EQ(blob2.ToString(), "1234"); -} - -/** - * @tc.name: AppBlobOperator003 - * @tc.desc: Construct a Blob and check its operator= function. - * @tc.type: FUNC - * @tc.require: AR000CCPOL - * @tc.author: liqiao - */ -HWTEST_F(AppBlobTest, AppBlobOperator003, TestSize.Level0) -{ - AppBlob blob1("1234"); - AppBlob blob2 = std::move(blob1); - EXPECT_EQ(blob1 == blob2, false); - EXPECT_EQ(blob1.Empty(), true); - EXPECT_EQ(blob2.ToString(), "1234"); -} \ No newline at end of file diff --git a/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/app_conflict_test.cpp b/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/app_conflict_test.cpp deleted file mode 100755 index aaa929001631c855a6aec664ed3666aef1999118..0000000000000000000000000000000000000000 --- a/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/app_conflict_test.cpp +++ /dev/null @@ -1,224 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#define LOG_TAG "AppConflictTest" - -#include "app_distributed_kv_data_manager.h" -#include -#include -#include -#include -#include -#include -#include "app_kvstore.h" -#include "app_types.h" -#include "log_print.h" - -using namespace testing::ext; -using namespace OHOS::AppDistributedKv; - -class AppConflictTest : public testing::Test { -public: - static void SetUpTestCase(void); - static void TearDownTestCase(void); - void SetUp(); - void TearDown(); - - static std::shared_ptr manager; - static std::unique_ptr appKvStorePtr; // declare kvstore instance. - static Status statusGetKvStore; -}; - -std::shared_ptr AppConflictTest::manager; -std::unique_ptr AppConflictTest::appKvStorePtr = nullptr; -Status AppConflictTest::statusGetKvStore = Status::ERROR; -static const auto OLD_VALUE_TYPE = AppKvStoreConflictData::ConflictValueType::OLD_VALUE; -static const auto NEW_VALUE_TYPE = AppKvStoreConflictData::ConflictValueType::NEW_VALUE; -static const int TIME_SLEEP = 100000; - -struct ConflictDataTest { - AppKvStoreConflictPolicyType type = AppKvStoreConflictPolicyType::CONFLICT_NATIVE_ALL; - Key key; - Value oldValue; - Value newValue; - bool oldIsDeleted = false; - bool newIsDeleted = false; - bool oldIsNative = false; - bool newIsNative = false; - bool operator==(const ConflictDataTest &comparedConflictDataTest) const - { - if (this->type == comparedConflictDataTest.type && - this->key == comparedConflictDataTest.key && - this->oldValue == comparedConflictDataTest.oldValue && - this->newValue == comparedConflictDataTest.newValue && - this->oldIsDeleted == comparedConflictDataTest.oldIsDeleted && - this->newIsDeleted == comparedConflictDataTest.newIsDeleted && - this->oldIsNative == comparedConflictDataTest.oldIsNative && - this->newIsNative == comparedConflictDataTest.newIsNative) { - return true; - } - return false; - } -}; -static std::vector g_conflictData; - -static void ConflictCallback(const AppKvStoreConflictData &data) -{ - ZLOGD("start."); - Key key; - Value oldValue; - Value newValue; - - data.GetKey(key); - data.GetValue(OLD_VALUE_TYPE, oldValue); - data.GetValue(NEW_VALUE_TYPE, newValue); - bool oldIsDeleted = data.IsDeleted(OLD_VALUE_TYPE); - bool newIsDeleted = data.IsDeleted(NEW_VALUE_TYPE); - bool oldIsNative = data.IsNative(OLD_VALUE_TYPE); - bool newIsNative = data.IsNative(NEW_VALUE_TYPE); - g_conflictData.push_back({data.GetType(), key, oldValue, newValue, oldIsDeleted, newIsDeleted, - oldIsNative, newIsNative}); - - ZLOGD("Get key: %s", key.ToString().c_str()); - ZLOGD("Get old value: %s", oldValue.ToString().c_str()); - ZLOGD("Get oldIsDeleted: %d", oldIsDeleted); - ZLOGD("Get newIsDeleted: %d", newIsDeleted); - ZLOGD("Get oldIsNative: %d", oldIsNative); - ZLOGD("Get newIsNative: %d", newIsNative); -} - -void AppConflictTest::SetUpTestCase(void) -{ -} - -void AppConflictTest::TearDownTestCase(void) -{ -} - -void AppConflictTest::SetUp(void) -{ - Options options; - options.createIfMissing = true; - options.encrypt = false; // not supported yet. - options.persistant = true; // not supported yet. - - std::string appId = "odmf"; // define app name. - std::string storeId = "conflictdb"; // define kvstore(database) name. - std::string dataDir = "data/misc_ce/0/odmf_test"; - - manager = AppDistributedKvDataManager::GetInstance(appId, dataDir); - // [create and] open and initialize kvstore instance. - statusGetKvStore = manager->GetKvStore(options, storeId, [&](std::unique_ptr appKvStore) { - appKvStorePtr = std::move(appKvStore); - }); - - g_conflictData.clear(); -} - -void AppConflictTest::TearDown(void) -{ - Status statusRet = manager->CloseKvStore(std::move(appKvStorePtr)); - EXPECT_EQ(statusRet, Status::SUCCESS); - statusRet = manager->DeleteKvStore("conflictdb"); - EXPECT_EQ(statusRet, Status::SUCCESS); -} - -/** - * @tc.name: AppConflict001 - * @tc.desc: set conflict resolution policy and no conflict - * @tc.type: FUNC - * @tc.require: AR000CQDUG - * @tc.author: liuyuhui - */ -HWTEST_F(AppConflictTest, AppConflict001, TestSize.Level1) -{ - ZLOGD("AppConflict001"); - EXPECT_EQ(Status::SUCCESS, statusGetKvStore) << "statusGetKvStore return wrong status"; - EXPECT_NE(nullptr, appKvStorePtr) << "appKvStorePtr is nullptr"; - - Status status = appKvStorePtr->SetConflictResolutionPolicy(AppKvStoreConflictPolicyType::CONFLICT_NATIVE_ALL, - ConflictCallback); - EXPECT_EQ(Status::SUCCESS, status) << "SetConflictResolutionPolicy return wrong status"; - WriteOptions localWrite; - localWrite.local = false; - status = appKvStorePtr->Put(localWrite, "Id1", "conflict"); - EXPECT_EQ(Status::SUCCESS, status) << "Put return wrong status"; - usleep(TIME_SLEEP); - EXPECT_EQ(g_conflictData.empty(), true); -} - -/** - * @tc.name: AppConflict002 - * @tc.desc: set conflict resolution policy and exist conflict -put the same key - * @tc.type: FUNC - * @tc.require: AR000CQDUG - * @tc.author: liuyuhui - */ -HWTEST_F(AppConflictTest, AppConflict002, TestSize.Level1) -{ - ZLOGD("AppConflict002"); - EXPECT_EQ(Status::SUCCESS, statusGetKvStore) << "statusGetKvStore return wrong status"; - EXPECT_NE(nullptr, appKvStorePtr) << "appKvStorePtr is nullptr"; - - WriteOptions localWrite; - localWrite.local = false; - Status status = appKvStorePtr->Put(localWrite, "Id2", "conflict"); - EXPECT_EQ(Status::SUCCESS, status) << "Put return wrong status"; - usleep(TIME_SLEEP); - - status = appKvStorePtr->SetConflictResolutionPolicy(AppKvStoreConflictPolicyType::CONFLICT_NATIVE_ALL, - ConflictCallback); - EXPECT_EQ(Status::SUCCESS, status) << "SetConflictResolutionPolicy return wrong status"; - status = appKvStorePtr->Put(localWrite, "Id2", "conflict_modify"); - EXPECT_EQ(Status::SUCCESS, status) << "Put return wrong status"; - usleep(TIME_SLEEP); - EXPECT_EQ(g_conflictData.empty(), false); - ConflictDataTest expectData = {AppKvStoreConflictPolicyType::CONFLICT_NATIVE_ALL, - "Id2", "conflict", "conflict_modify", false, false, true, true}; - EXPECT_EQ(g_conflictData.front() == expectData, true); -} - -/** - * @tc.name: AppConflict003 - * @tc.desc: set conflict resolution policy and exist conflict -put and delete the same key - * @tc.type: FUNC - * @tc.require: AR000CQDUG - * @tc.author: liuyuhui - */ -HWTEST_F(AppConflictTest, AppConflict003, TestSize.Level1) -{ - ZLOGD("app_conflict_003 start"); - EXPECT_EQ(Status::SUCCESS, statusGetKvStore) << "statusGetKvStore return wrong status"; - EXPECT_NE(nullptr, appKvStorePtr) << "appKvStorePtr is nullptr"; - - WriteOptions localWrite; - localWrite.local = false; - Status status = appKvStorePtr->Put(localWrite, "Id3", "conflict"); - EXPECT_EQ(Status::SUCCESS, status) << "Put return wrong status"; - usleep(TIME_SLEEP); - - status = appKvStorePtr->SetConflictResolutionPolicy(AppKvStoreConflictPolicyType::CONFLICT_NATIVE_ALL, - ConflictCallback); - EXPECT_EQ(Status::SUCCESS, status) << "SetConflictResolutionPolicy return wrong status"; - status = appKvStorePtr->Delete(localWrite, "Id3"); - EXPECT_EQ(Status::SUCCESS, status) << "Delete return wrong status"; - usleep(TIME_SLEEP); - EXPECT_EQ(g_conflictData.empty(), false); - Value newValue; - ConflictDataTest expectData = {AppKvStoreConflictPolicyType::CONFLICT_NATIVE_ALL, - "Id3", "conflict", newValue, false, true, true, true}; - EXPECT_EQ(g_conflictData.front() == expectData, true); - ZLOGD("app_conflict_003 end"); -} diff --git a/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/app_distributed_kv_data_manager_test.cpp b/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/app_distributed_kv_data_manager_test.cpp deleted file mode 100755 index 83005769c49c91840e9ea3ffaaa27b99de32b789..0000000000000000000000000000000000000000 --- a/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/app_distributed_kv_data_manager_test.cpp +++ /dev/null @@ -1,426 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "app_distributed_kv_data_manager.h" -#include -#include -#include -#include "app_kvstore.h" -#include "app_types.h" -#include "app_kvstore_corruption_observer.h" - -#ifdef LOG_TAG -#undef LOG_TAG -#endif -#define LOG_TAG "AppDistributedKvDataManagerTest" - -using namespace testing::ext; -using namespace OHOS::AppDistributedKv; - -class AppDistributedKvDataManagerTest : public testing::Test { -public: - static std::shared_ptr manager; - static Options create; - static Options noCreate; - - static std::string appId; - static std::string storeId64; - static std::string storeId65; - static std::string storeIdEmpty; - - static void SetUpTestCase(void); - static void TearDownTestCase(void); - - static void RemoveAllStore(AppDistributedKvDataManager &manager); - - void SetUp(); - void TearDown(); - AppDistributedKvDataManagerTest(); -}; - -std::shared_ptr AppDistributedKvDataManagerTest::manager; -Options AppDistributedKvDataManagerTest::create; -Options AppDistributedKvDataManagerTest::noCreate; - -std::string AppDistributedKvDataManagerTest::appId; -std::string AppDistributedKvDataManagerTest::storeId64; -std::string AppDistributedKvDataManagerTest::storeId65; -std::string AppDistributedKvDataManagerTest::storeIdEmpty; - -void AppDistributedKvDataManagerTest::SetUpTestCase(void) -{ - create.createIfMissing = true; - create.encrypt = false; - create.persistant = true; - - noCreate.createIfMissing = false; - noCreate.encrypt = false; - noCreate.persistant = true; - - appId = "com.ohos.nb.service"; - std::string dataDir = "data/misc_ce/0/com.ohos.nb.service"; - storeId64 = "a000000000b000000000c000000000d000000000e000000000f000000000g000"; - storeId65 = "a000000000b000000000c000000000d000000000e000000000f000000000g0000" - "a000000000b000000000c000000000d000000000e000000000f000000000g000"; - storeIdEmpty = ""; - std::string userId = "ohosAnonymousUid"; - - manager = AppDistributedKvDataManager::GetInstance(appId, dataDir, userId); -} - -void AppDistributedKvDataManagerTest::TearDownTestCase(void) -{ - manager->DeleteKvStore(storeId64); -} - -void AppDistributedKvDataManagerTest::SetUp(void) -{ - manager->DeleteKvStore(storeId64); -} - -AppDistributedKvDataManagerTest::AppDistributedKvDataManagerTest(void) -{} - -void AppDistributedKvDataManagerTest::TearDown(void) -{ - manager->DeleteKvStore(storeId64); -} - -/** - * @tc.name: AppManagerGetKvstore001 - * @tc.desc: Get an exist KvStore - * @tc.type: FUNC - * @tc.require: AR000CCPOJ - * @tc.author: liqiao - */ -HWTEST_F(AppDistributedKvDataManagerTest, AppManagerGetKvstore001, TestSize.Level1) -{ - std::unique_ptr notExistKvStorePtr; - Status status; - status = manager->GetKvStore(create, storeId64, [&](std::unique_ptr kvStore) { - notExistKvStorePtr = std::move(kvStore); - }); - EXPECT_NE(notExistKvStorePtr, nullptr); - EXPECT_EQ(status, Status::SUCCESS); - - std::unique_ptr existKvStorePtr; - status = manager->GetKvStore(noCreate, storeId64, [&](std::unique_ptr kvStore) { - existKvStorePtr = std::move(kvStore); - }); - EXPECT_NE(existKvStorePtr, nullptr); - EXPECT_EQ(status, Status::SUCCESS); - status = manager->CloseKvStore(std::move(notExistKvStorePtr)); - EXPECT_EQ(status, Status::SUCCESS); - status = manager->CloseKvStore(std::move(existKvStorePtr)); - EXPECT_EQ(status, Status::SUCCESS); -} - -/** - * @tc.name: AppManagerGetKvstore002 - * @tc.desc: Create and get a new KvStore. - * @tc.type: FUNC - * @tc.require: AR000CCPOJ - * @tc.author: liqiao - */ -HWTEST_F(AppDistributedKvDataManagerTest, AppManagerGetKvstore002, TestSize.Level1) -{ - std::unique_ptr notExistKvStorePtr; - Status status; - status = manager->GetKvStore(create, storeId64, [&](std::unique_ptr kvStore) { - notExistKvStorePtr = std::move(kvStore); - }); - EXPECT_NE(notExistKvStorePtr, nullptr); - EXPECT_EQ(status, Status::SUCCESS); - status = manager->CloseKvStore(std::move(notExistKvStorePtr)); - EXPECT_EQ(status, Status::SUCCESS); -} - -/** - * @tc.name: AppManagerGetKvstore003 - * @tc.desc: Get a non-existing KvStore, and the callback function should receive STORE_NOT_FOUND and - * get a nullptr. - * @tc.type: FUNC - * @tc.require: AR000CCPOJ - * @tc.author: liqiao - */ -HWTEST_F(AppDistributedKvDataManagerTest, AppManagerGetKvstore003, TestSize.Level1) -{ - std::unique_ptr notExistKvStorePtr; - Status status; - status = manager->GetKvStore(noCreate, storeId64, [&](std::unique_ptr kvStore) { - notExistKvStorePtr = std::move(kvStore); - }); - EXPECT_EQ(notExistKvStorePtr, nullptr); - EXPECT_EQ(status, Status::STORE_NOT_FOUND); -} - -/** - * @tc.name: AppManagerGetKvstore004 - * @tc.desc: Create a KvStore with an empty storeId, and the callback function should receive - * INVALID_ARGUMENT and got a nullptr. - * @tc.type: FUNC - * @tc.require: AR000CCPOJ - * @tc.author: liqiao - */ -HWTEST_F(AppDistributedKvDataManagerTest, AppManagerGetKvstore004, TestSize.Level1) -{ - std::unique_ptr notExistKvStorePtr; - Status status; - status = manager->GetKvStore(create, storeIdEmpty, [&](std::unique_ptr kvStore) { - notExistKvStorePtr = std::move(kvStore); - }); - EXPECT_EQ(notExistKvStorePtr, nullptr); - EXPECT_EQ(status, Status::INVALID_ARGUMENT); -} - -/** - * @tc.name: AppManagerGetKvstore005 - * @tc.desc: Get a KvStore with an empty storeId, the callback function should receive INVALID_ARGUMENT - * and got a nullptr. - * @tc.type: FUNC - * @tc.require: AR000CCPOJ - * @tc.author: liqiao - */ -HWTEST_F(AppDistributedKvDataManagerTest, AppManagerGetKvstore005, TestSize.Level1) -{ - std::unique_ptr notExistKvStorePtr; - Status status; - status = manager->GetKvStore(noCreate, storeIdEmpty, [&](std::unique_ptr kvStore) { - notExistKvStorePtr = std::move(kvStore); - }); - EXPECT_EQ(notExistKvStorePtr, nullptr); - EXPECT_EQ(status, Status::INVALID_ARGUMENT); -} - -/** - * @tc.name: AppManagerGetKvstore006 - * @tc.desc: Create a KvStore with 65-byte storeId, and the callback function should receive - * INVALID_ARGUMENT and got a nullptr. - * @tc.type: FUNC - * @tc.require: AR000CCPOJ - * @tc.author: liqiao - */ -HWTEST_F(AppDistributedKvDataManagerTest, AppManagerGetKvstore006, TestSize.Level1) -{ - std::unique_ptr notExistKvStorePtr; - Status status; - status = manager->GetKvStore(create, storeId65, [&](std::unique_ptr kvStore) { - notExistKvStorePtr = std::move(kvStore); - }); - EXPECT_EQ(notExistKvStorePtr, nullptr); - EXPECT_EQ(status, Status::INVALID_ARGUMENT); -} - -/** - * @tc.name: AppManagerGetKvstore007 - * @tc.desc: Get a KvStore with 65-byte storeId, and the callback function should receive - * INVALID_ARGUMENT and got a nullptr. - * @tc.type: FUNC - * @tc.require: AR000CCPOJ - * @tc.author: liqiao - */ -HWTEST_F(AppDistributedKvDataManagerTest, AppManagerGetKvstore007, TestSize.Level1) -{ - std::unique_ptr notExistKvStorePtr; - Status status; - status = manager->GetKvStore(noCreate, storeId65, [&](std::unique_ptr kvStore) { - notExistKvStorePtr = std::move(kvStore); - }); - EXPECT_EQ(notExistKvStorePtr, nullptr); - EXPECT_EQ(status, Status::INVALID_ARGUMENT); -} - -/** - * @tc.name: AppManagerCloseKvstore001 - * @tc.desc: Close an opened KVStore, and the callback should return SUCCESS. - * @tc.type: FUNC - * @tc.require: AR000CCPOJ - * @tc.author: liqiao - */ -HWTEST_F(AppDistributedKvDataManagerTest, AppManagerCloseKvstore001, TestSize.Level1) -{ - std::unique_ptr kvStorePtr; - Status status; - status = manager->GetKvStore(create, storeId64, [&](std::unique_ptr kvStore) { - kvStorePtr = std::move(kvStore); - }); - ASSERT_NE(kvStorePtr, nullptr); - ASSERT_EQ(status, Status::SUCCESS); - - Status stat = manager->CloseKvStore(std::move(kvStorePtr)); - EXPECT_EQ(stat, Status::SUCCESS); -} - -/** - * @tc.name: AppManagerCloseKvstore002 - * @tc.desc: Close a closed KvStore, and the callback should return INVALID_ARGUMENT. - * @tc.type: FUNC - * @tc.require: AR000CCPOJ - * @tc.author: liqiao - */ -HWTEST_F(AppDistributedKvDataManagerTest, AppManagerCloseKvstore002, TestSize.Level1) -{ - std::unique_ptr kvStorePtr; - Status status; - status = manager->GetKvStore(create, storeId64, [&](std::unique_ptr kvStore) { - kvStorePtr = std::move(kvStore); - }); - ASSERT_NE(kvStorePtr, nullptr); - ASSERT_EQ(status, Status::SUCCESS); - - manager->CloseKvStore(std::move(kvStorePtr)); - Status stat = manager->CloseKvStore(std::move(kvStorePtr)); - EXPECT_EQ(stat, Status::INVALID_ARGUMENT); -} - -/** - * @tc.name: AppManagerCloseKvstore003 - * @tc.desc: Close a KvStore with empty storeId, and the callback should return INVALID_ARGUMENT. - * @tc.type: FUNC - * @tc.require: AR000CCPOJ - * @tc.author: liqiao - */ -HWTEST_F(AppDistributedKvDataManagerTest, AppManagerCloseKvstore003, TestSize.Level1) -{ - std::unique_ptr kvStorePtr = nullptr; - Status stat = manager->CloseKvStore(nullptr); - EXPECT_EQ(stat, Status::INVALID_ARGUMENT); -} - -/** - * @tc.name: AppManagerDeleteKvStore001 - * @tc.desc: Delete a closed KvStore, and the callback should return SUCCESS. - * @tc.type: FUNC - * @tc.require: AR000CCPOJ - * @tc.author: liqiao - */ -HWTEST_F(AppDistributedKvDataManagerTest, AppManagerDeleteKvStore001, TestSize.Level1) -{ - std::unique_ptr kvStorePtr; - Status status; - status = manager->GetKvStore(create, storeId64, [&](std::unique_ptr kvStore) { - kvStorePtr = std::move(kvStore); - }); - ASSERT_NE(kvStorePtr, nullptr); - ASSERT_EQ(status, Status::SUCCESS); - - Status stat = manager->CloseKvStore(std::move(kvStorePtr)); - ASSERT_EQ(stat, Status::SUCCESS); - - stat = manager->DeleteKvStore(storeId64); - EXPECT_EQ(stat, Status::SUCCESS); -} - -/** - * @tc.name: AppManagerDeleteKvStore002 - * @tc.desc: Delete a opened KvStore, and the callback should return ILLEGAL_STATE. - * @tc.type: FUNC - * @tc.require: AR000CCPOJ - * @tc.author: liqiao - */ -HWTEST_F(AppDistributedKvDataManagerTest, AppManagerDeleteKvStore002, TestSize.Level1) -{ - std::unique_ptr kvStorePtr; - Status status; - status = manager->GetKvStore(create, storeId64, [&](std::unique_ptr kvStore) { - kvStorePtr = std::move(kvStore); - }); - ASSERT_NE(kvStorePtr, nullptr); - ASSERT_EQ(status, Status::SUCCESS); - - // first close it if opened, and then delete it. - status = manager->DeleteKvStore(storeId64); - EXPECT_EQ(status, Status::ERROR); - manager->CloseKvStore(std::move(kvStorePtr)); -} - -/** - * @tc.name: AppManagerDeleteKvStore003 - * @tc.desc: Delete a non-existing KvStore, and the callback should return ERROR. - * @tc.type: FUNC - * @tc.require: AR000CCPOJ - * @tc.author: liqiao - */ -HWTEST_F(AppDistributedKvDataManagerTest, AppManagerDeleteKvStore003, TestSize.Level1) -{ - Status stat = manager->DeleteKvStore(storeId64); - EXPECT_EQ(stat, Status::ERROR); -} - -/** - * @tc.name: AppManagerDeleteKvStore004 - * @tc.desc: Delete a KvStore with an empty storeId, and the callback should return INVALID_ARGUMENT. - * @tc.type: FUNC - * @tc.require: AR000CCPOJ - * @tc.author: liqiao - */ -HWTEST_F(AppDistributedKvDataManagerTest, AppManagerDeleteKvStore004, TestSize.Level1) -{ - Status stat = manager->DeleteKvStore(storeIdEmpty); - EXPECT_EQ(stat, Status::INVALID_ARGUMENT); -} - -/** - * @tc.name: AppManagerDeleteKvStore005 - * @tc.desc: Delete a KvStore with a 65-byte storeId (which exceeds storeId length limit), and the calback should - * return INVALID_ARGUMENT. - * @tc.type: FUNC - * @tc.require: AR000CCPOJ - * @tc.author: liqiao - */ -HWTEST_F(AppDistributedKvDataManagerTest, AppManagerDeleteKvStore005, TestSize.Level1) -{ - Status stat = manager->DeleteKvStore(storeId65); - EXPECT_EQ(stat, Status::INVALID_ARGUMENT); -} - -/** - * @tc.name: GetKvStoreDiskSize001 - * @tc.desc: Get the kvStore disk size. - * @tc.type: FUNC - * @tc.require: AR000CQDTD - * @tc.author: hongbo - */ -HWTEST_F(AppDistributedKvDataManagerTest, GetKvStoreDiskSize001, TestSize.Level1) -{ - uint64_t size; - Status stat = manager->GetKvStoreDiskSize(storeId65, size); - if (stat == Status::SUCCESS) { - uint64_t expect = 0; - EXPECT_GE(size, expect); - } -} - -class CorruptionObserverImpl : public AppKvStoreCorruptionObserver { -public: - ~CorruptionObserverImpl() {} - void OnCorruption(const std::string &appId, const std::string &userId, const std::string &storeId) override; -}; - -void CorruptionObserverImpl::OnCorruption(const std::string &appId, const std::string &userId, - const std::string &storeId) {} -/** - * @tc.name: RegisterKvStoreCorruptionObserver - * @tc.desc: Register the database corruption observer. - * @tc.type: FUNC - * @tc.require: AR000D487D - * @tc.author: hongbo - */ -HWTEST_F(AppDistributedKvDataManagerTest, RegisterKvStoreCorruptionObserver001, TestSize.Level1) -{ - auto observer = std::make_shared(); - Status stat = manager->RegisterKvStoreCorruptionObserver(observer); - EXPECT_EQ(stat, Status::SUCCESS); -} \ No newline at end of file diff --git a/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/app_distributed_kv_store_test.cpp b/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/app_distributed_kv_store_test.cpp deleted file mode 100755 index 5cb1421db11b3cf2c11756fc2a3e9ba59c42b7fd..0000000000000000000000000000000000000000 --- a/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/app_distributed_kv_store_test.cpp +++ /dev/null @@ -1,1698 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "app_distributed_kv_data_manager.h" -#include -#include -#include -#include -#include -#include -#include -#include "app_kvstore.h" -#include "app_types.h" -#include "log_print.h" - -#ifdef LOG_TAG -#undef LOG_TAG -#endif -#define LOG_TAG "AppDistributedKvDataManagerTest" - -using namespace testing::ext; -using namespace OHOS::AppDistributedKv; - -class AppDistributedKvStoreTest : public testing::Test { -public: - static std::shared_ptr manager; - static WriteOptions localWrite, syncWrite; - static ReadOptions localRead, syncRead; - static Options options; - static std::string appId; - static std::string storeId; - static std::string dataDir; - static std::string userId; - static SubscribeType subscribeType; - - static void SetUpTestCase(void); - static void TearDownTestCase(void); - - void SetUp(); - void TearDown(); - AppDistributedKvStoreTest(); -}; - -std::shared_ptr AppDistributedKvStoreTest::manager; - -ReadOptions AppDistributedKvStoreTest::localRead; -ReadOptions AppDistributedKvStoreTest::syncRead; -WriteOptions AppDistributedKvStoreTest::localWrite; -WriteOptions AppDistributedKvStoreTest::syncWrite; -Options AppDistributedKvStoreTest::options; - -SubscribeType AppDistributedKvStoreTest::subscribeType = SubscribeType::DEFAULT; -std::string AppDistributedKvStoreTest::dataDir = "data/misc_ce/0/appKvStoreTest"; -std::string AppDistributedKvStoreTest::appId = "appKvStoreTest"; -std::string AppDistributedKvStoreTest::storeId = "appKvStore0"; -std::string AppDistributedKvStoreTest::userId = "domainUser0"; - -void AppDistributedKvStoreTest::SetUpTestCase(void) -{ - manager = AppDistributedKvDataManager::GetInstance(appId, dataDir, userId); - localRead.local = true; - syncRead.local = false; - localWrite.local = true; - syncWrite.local = false; - options.createIfMissing = true; - options.encrypt = false; - options.persistant = true; -} - -void AppDistributedKvStoreTest::TearDownTestCase(void) -{ -} - -void AppDistributedKvStoreTest::SetUp(void) -{ -} - -AppDistributedKvStoreTest::AppDistributedKvStoreTest(void) -{ -} - -void AppDistributedKvStoreTest::TearDown(void) -{ -} - -class ObserverImpl : public AppKvStoreObserver { -public: - std::vector insertEntries; - std::vector updateEntries; - std::vector deleteEntries; - bool isClear; - ObserverImpl() - { - insertEntries = {}; - updateEntries = {}; - deleteEntries = {}; - isClear = false; - callCount_ = 0; - } - ~ObserverImpl() = default; - - int CallCount() - { - return callCount_; - } - - void OnChange(const AppChangeNotification &appChangeNotification) override - { - const std::list insert = appChangeNotification.GetInsertEntries(); - insertEntries.clear(); - for (const auto &entry : insert) { - insertEntries.push_back(entry); - } - - const std::list update = appChangeNotification.GetUpdateEntries(); - updateEntries.clear(); - for (const auto &entry : update) { - updateEntries.push_back(entry); - } - - const std::list del = appChangeNotification.GetDeleteEntries(); - deleteEntries.clear(); - for (const auto &entry : del) { - deleteEntries.push_back(entry); - } - - isClear = appChangeNotification.IsClear(); - callCount_ += 1; - - ZLOGI("AppChangeNotification OnChange GetDeviceId"); - appChangeNotification.GetDeviceId(); - } - - void Clear() - { - insertEntries.clear(); - updateEntries.clear(); - deleteEntries.clear(); - isClear = false; - callCount_ = 0; - } -private: - int callCount_; -}; - -/** - * @tc.name: AppKvstorePut001 - * @tc.desc: put int data to KvStore - * @tc.type: FUNC - * @tc.require: AR000CCPOL AR000CQS36 - * @tc.author: liqiao - */ -HWTEST_F(AppDistributedKvStoreTest, AppKvstorePut001, TestSize.Level1) -{ - // cover app_kvstore_put_001, app_kvstore_put_local_001, - // app_kvstore_get_001, app_kvstore_get_local_001 - // app_kvstore_independent_001, app_kvstore_independent_002 - std::unique_ptr appKvStorePtr; - Status status; - - status = manager->GetKvStore( - options, "student", [&](std::unique_ptr appKvStore) { - appKvStorePtr = std::move(appKvStore); - }); - EXPECT_EQ(status, Status::SUCCESS); - - status = appKvStorePtr->Put(localWrite, Key("math_score_int"), Value(TransferTypeToByteArray(-383468))); - EXPECT_EQ(status, Status::SUCCESS); - status = appKvStorePtr->Put(syncWrite, Key("math_score_int"), Value(TransferTypeToByteArray(-383469))); - EXPECT_EQ(status, Status::SUCCESS); - - Value ret; - status = appKvStorePtr->Get(localRead, Key("math_score_int"), ret); - EXPECT_EQ(status, Status::SUCCESS); - EXPECT_EQ(TransferByteArrayToType(ret.Data()), -383468); - status = appKvStorePtr->Get(syncRead, Key("math_score_int"), ret); - EXPECT_EQ(status, Status::SUCCESS); - EXPECT_EQ(TransferByteArrayToType(ret.Data()), -383469); - - status = manager->CloseKvStore(std::move(appKvStorePtr)); - EXPECT_EQ(status, Status::SUCCESS); - status = manager->DeleteKvStore("student"); - EXPECT_EQ(status, Status::SUCCESS); -} - -/** - * @tc.name: AppKvstorePut002 - * @tc.desc: put float data to KvStore - * @tc.type: FUNC - * @tc.require: AR000CCPOL AR000CQS36 - * @tc.author: liqiao - */ -HWTEST_F(AppDistributedKvStoreTest, AppKvstorePut002, TestSize.Level1) -{ - // cover app_kvstore_put_002, app_kvstore_put_local_002 - std::unique_ptr appKvStorePtr; - Status status; - - status = manager->GetKvStore( - options, "student", [&](std::unique_ptr appKvStore) { - appKvStorePtr = std::move(appKvStore); - }); - EXPECT_EQ(status, Status::SUCCESS); - - status = appKvStorePtr->Put(localWrite, Key("math_score_float"), Value(TransferTypeToByteArray(3.14f))); - EXPECT_EQ(status, Status::SUCCESS); - status = appKvStorePtr->Put(syncWrite, Key("math_score_float"), Value(TransferTypeToByteArray(3.1416f))); - EXPECT_EQ(status, Status::SUCCESS); - - Value ret; - status = appKvStorePtr->Get(localRead, Key("math_score_float"), ret); - EXPECT_EQ(status, Status::SUCCESS); - float delta = TransferByteArrayToType(ret.Data()) - 3.14f; - EXPECT_LE(std::abs(delta), 0.00001); - status = appKvStorePtr->Get(syncRead, Key("math_score_float"), ret); - EXPECT_EQ(status, Status::SUCCESS); - delta = TransferByteArrayToType(ret.Data()) - 3.1416f; - EXPECT_LE(std::abs(delta), 0.00001); - - status = manager->CloseKvStore(std::move(appKvStorePtr)); - EXPECT_EQ(status, Status::SUCCESS); - status = manager->DeleteKvStore("student"); - EXPECT_EQ(status, Status::SUCCESS); -} - -/** - * @tc.name: AppKvstorePut003 - * @tc.desc: put double data to KvStore - * @tc.type: FUNC - * @tc.require: AR000CCPOL AR000CQS36 - * @tc.author: liqiao - */ -HWTEST_F(AppDistributedKvStoreTest, AppKvstorePut003, TestSize.Level1) -{ - // cover app_kvstore_put_003, app_kvstore_put_local_003 - std::unique_ptr appKvStorePtr; - Status status; - - status = manager->GetKvStore( - options, "student", [&](std::unique_ptr appKvStore) { - appKvStorePtr = std::move(appKvStore); - }); - EXPECT_EQ(status, Status::SUCCESS); - - status = appKvStorePtr->Put(localWrite, Key("math_score_double"), Value(TransferTypeToByteArray(28.785f))); - EXPECT_EQ(status, Status::SUCCESS); - status = appKvStorePtr->Put(syncWrite, Key("math_score_double"), Value(TransferTypeToByteArray(28.790f))); - EXPECT_EQ(status, Status::SUCCESS); - - Value ret; - status = appKvStorePtr->Get(localRead, Key("math_score_double"), ret); - EXPECT_EQ(status, Status::SUCCESS); - double delta = TransferByteArrayToType(ret.Data()) - 28.785f; - EXPECT_LE(std::abs(delta), 0.00001); - status = appKvStorePtr->Get(syncRead, Key("math_score_double"), ret); - EXPECT_EQ(status, Status::SUCCESS); - delta = TransferByteArrayToType(ret.Data()) - 28.790f; - EXPECT_LE(std::abs(delta), 0.00001); - - status = manager->CloseKvStore(std::move(appKvStorePtr)); - EXPECT_EQ(status, Status::SUCCESS); - status = manager->DeleteKvStore("student"); - EXPECT_EQ(status, Status::SUCCESS); -} - -/** - * @tc.name: AppKvstorePut004 - * @tc.desc: put size_t data to KvStore - * @tc.type: FUNC - * @tc.require: AR000CCPOL AR000CQS36 - * @tc.author: liqiao - */ -HWTEST_F(AppDistributedKvStoreTest, AppKvstorePut004, TestSize.Level1) -{ - // cover app_kvstore_put_004, app_kvstore_put_local_004 - std::unique_ptr appKvStorePtr; - Status status; - - status = manager->GetKvStore( - options, "student", [&](std::unique_ptr appKvStore) { - appKvStorePtr = std::move(appKvStore); - }); - EXPECT_EQ(status, Status::SUCCESS); - - status = appKvStorePtr->Put(localWrite, Key("math_score_size_t"), Value(TransferTypeToByteArray(28))); - EXPECT_EQ(status, Status::SUCCESS); - status = appKvStorePtr->Put(syncWrite, Key("math_score_size_t"), Value(TransferTypeToByteArray(29))); - EXPECT_EQ(status, Status::SUCCESS); - Value ret; - status = appKvStorePtr->Get(localRead, Key("math_score_size_t"), ret); - EXPECT_EQ(status, Status::SUCCESS); - EXPECT_EQ(TransferByteArrayToType(ret.Data()), 28u); - status = appKvStorePtr->Get(syncRead, Key("math_score_size_t"), ret); - EXPECT_EQ(status, Status::SUCCESS); - EXPECT_EQ(TransferByteArrayToType(ret.Data()), 29u); - - status = manager->CloseKvStore(std::move(appKvStorePtr)); - EXPECT_EQ(status, Status::SUCCESS); - status = manager->DeleteKvStore("student"); - EXPECT_EQ(status, Status::SUCCESS); -} - -/** - * @tc.name: AppKvstorePut005 - * @tc.desc: put int64_t data to KvStore - * @tc.type: FUNC - * @tc.require: AR000CCPOL AR000CQS36 - * @tc.author: liqiao - */ -HWTEST_F(AppDistributedKvStoreTest, AppKvstorePut005, TestSize.Level1) -{ - // cover app_kvstore_put_005, app_kvstore_put_local_005 - std::unique_ptr appKvStorePtr; - Status status; - - status = manager->GetKvStore( - options, "student", [&](std::unique_ptr appKvStore) { - appKvStorePtr = std::move(appKvStore); - }); - EXPECT_EQ(status, Status::SUCCESS); - - status = - appKvStorePtr->Put(localWrite, Key("math_score_int64_t"), Value(TransferTypeToByteArray(12345678))); - EXPECT_EQ(status, Status::SUCCESS); - status = - appKvStorePtr->Put(syncWrite, Key("math_score_int64_t"), Value(TransferTypeToByteArray(123456789))); - EXPECT_EQ(status, Status::SUCCESS); - Value ret; - status = appKvStorePtr->Get(localRead, Key("math_score_int64_t"), ret); - EXPECT_EQ(status, Status::SUCCESS); - EXPECT_EQ(TransferByteArrayToType(ret.Data()), 12345678u); - status = appKvStorePtr->Get(syncRead, Key("math_score_int64_t"), ret); - EXPECT_EQ(status, Status::SUCCESS); - EXPECT_EQ(TransferByteArrayToType(ret.Data()), 123456789u); - - status = manager->CloseKvStore(std::move(appKvStorePtr)); - EXPECT_EQ(status, Status::SUCCESS); - status = manager->DeleteKvStore("student"); - EXPECT_EQ(status, Status::SUCCESS); -} - -/** - * @tc.name: AppKvstorePut006 - * @tc.desc: put string data to KvStore - * @tc.type: FUNC - * @tc.require: AR000CCPOL AR000CQS36 - * @tc.author: liqiao - */ -HWTEST_F(AppDistributedKvStoreTest, AppKvstorePut006, TestSize.Level1) -{ - // cover app_kvstore_put_006, app_kvstore_put_local_006 - std::unique_ptr appKvStorePtr; - Status status; - - status = manager->GetKvStore( - options, "student", [&](std::unique_ptr appKvStore) { - appKvStorePtr = std::move(appKvStore); - }); - EXPECT_EQ(status, Status::SUCCESS); - - status = appKvStorePtr->Put(localWrite, Key("student_name_zhangsan"), - Value("{\"class\":20, \"age\":18, \"gradle\":\"good\"}")); - EXPECT_EQ(status, Status::SUCCESS); - status = appKvStorePtr->Put(syncWrite, Key("student_name_zhangsan"), - Value("{\"class\":20, \"age\":19, \"gradle\":\"good\"}")); - EXPECT_EQ(status, Status::SUCCESS); - Value ret; - status = appKvStorePtr->Get(localRead, Key("student_name_zhangsan"), ret); - EXPECT_EQ(status, Status::SUCCESS); - EXPECT_EQ(ret.ToString(), std::string("{\"class\":20, \"age\":18, \"gradle\":\"good\"}")); - status = appKvStorePtr->Get(syncRead, Key("student_name_zhangsan"), ret); - EXPECT_EQ(status, Status::SUCCESS); - EXPECT_EQ(ret.ToString(), std::string("{\"class\":20, \"age\":19, \"gradle\":\"good\"}")); - - status = manager->CloseKvStore(std::move(appKvStorePtr)); - EXPECT_EQ(status, Status::SUCCESS); - status = manager->DeleteKvStore("student"); - EXPECT_EQ(status, Status::SUCCESS); -} - -/** - * @tc.name: AppKvstorePut007 - * @tc.desc: put byte array data to KvStore - * @tc.type: FUNC - * @tc.require: AR000CCPOL AR000CQS36 - * @tc.author: liqiao - */ -HWTEST_F(AppDistributedKvStoreTest, AppKvstorePut007, TestSize.Level1) -{ - // cover app_kvstore_put_007, app_kvstore_put_local_007 - std::unique_ptr appKvStorePtr; - Status status; - - status = manager->GetKvStore( - options, "student", [&](std::unique_ptr appKvStore) { - appKvStorePtr = std::move(appKvStore); - }); - EXPECT_EQ(status, Status::SUCCESS); - std::vector val = {0, 1, 2, 0, 0, 5, 6, 0}; - status = appKvStorePtr->Put(localWrite, Key("teacher_name_wanger"), - Value(val)); - EXPECT_EQ(status, Status::SUCCESS); - status = appKvStorePtr->Put(syncWrite, Key("teacher_name_wanger"), - Value(val)); - EXPECT_EQ(status, Status::SUCCESS); - Value ret; - status = appKvStorePtr->Get(localRead, Key("teacher_name_wanger"), ret); - EXPECT_EQ(status, Status::SUCCESS); - ASSERT_EQ(ret.Size(), val.size()); - for(unsigned long i = 0; i < ret.Size(); i++) { - EXPECT_EQ(ret.Data()[i], val[i]); - } - status = appKvStorePtr->Get(syncRead, Key("teacher_name_wanger"), ret); - EXPECT_EQ(status, Status::SUCCESS); - ASSERT_EQ(ret.Size(), val.size()); - for(unsigned long i = 0; i < ret.Size(); i++) { - EXPECT_EQ(ret.Data()[i], val[i]); - } - - status = manager->CloseKvStore(std::move(appKvStorePtr)); - EXPECT_EQ(status, Status::SUCCESS); - status = manager->DeleteKvStore("student"); - EXPECT_EQ(status, Status::SUCCESS); -} - -/** - * @tc.name: AppKvstorePut008 - * @tc.desc: Put data including localWrite and syncWrite to KvStore - * @tc.type: FUNC - * @tc.require: AR000CCPOL AR000CQS36 - * @tc.author: liqiao - */ -HWTEST_F(AppDistributedKvStoreTest, AppKvstorePut008, TestSize.Level1) -{ - // cover app_kvstore_put_008, app_kvstore_put_local_008 - std::unique_ptr appKvStorePtr; - Status status; - - status = manager->GetKvStore( - options, "student", [&](std::unique_ptr appKvStore) { - appKvStorePtr = std::move(appKvStore); - }); - EXPECT_EQ(status, Status::SUCCESS); - - status = appKvStorePtr->Put(localWrite, Key("teacher_name_wanger"), Value("class:20, age:50")); - EXPECT_EQ(status, Status::SUCCESS); - status = appKvStorePtr->Put(syncWrite, Key("teacher_name_wanger"), Value("class:20, age:51")); - EXPECT_EQ(status, Status::SUCCESS); - Value ret; - status = appKvStorePtr->Get(localRead, Key("teacher_name_wanger"), ret); - EXPECT_EQ(status, Status::SUCCESS); - EXPECT_EQ(ret.ToString(), std::string("class:20, age:50")); - status = appKvStorePtr->Get(syncRead, Key("teacher_name_wanger"), ret); - EXPECT_EQ(status, Status::SUCCESS); - EXPECT_EQ(ret.ToString(), std::string("class:20, age:51")); - - status = manager->CloseKvStore(std::move(appKvStorePtr)); - EXPECT_EQ(status, Status::SUCCESS); - status = manager->DeleteKvStore("student"); - EXPECT_EQ(status, Status::SUCCESS); -} - -/** - * @tc.name: AppKvstorePut009 - * @tc.desc: Update data including localWrite and syncWrite in KvStore - * @tc.type: FUNC - * @tc.require: AR000CCPOL AR000CQS36 - * @tc.author: liqiao - */ -HWTEST_F(AppDistributedKvStoreTest, AppKvstorePut009, TestSize.Level1) -{ - // cover app_kvstore_put_009, app_kvstore_put_local_009 - std::unique_ptr appKvStorePtr; - Status status; - - status = manager->GetKvStore( - options, "student", [&](std::unique_ptr appKvStore) { - appKvStorePtr = std::move(appKvStore); - }); - EXPECT_EQ(status, Status::SUCCESS); - - status = appKvStorePtr->Put(localWrite, Key("student_name_lisi"), Value("age:18")); - EXPECT_EQ(status, Status::SUCCESS); - - status = appKvStorePtr->Put(localWrite, Key("student_name_lisi"), Value("age:20")); - EXPECT_EQ(status, Status::SUCCESS); - - status = appKvStorePtr->Put(syncWrite, Key("student_name_lisi"), Value("age:19")); - EXPECT_EQ(status, Status::SUCCESS); - - status = appKvStorePtr->Put(syncWrite, Key("student_name_lisi"), Value("age:21")); - EXPECT_EQ(status, Status::SUCCESS); - - Value ret; - status = appKvStorePtr->Get(localRead, Key("student_name_lisi"), ret); - EXPECT_EQ(status, Status::SUCCESS); - EXPECT_EQ(ret.ToString(), std::string("age:20")); - status = appKvStorePtr->Get(syncRead, Key("student_name_lisi"), ret); - EXPECT_EQ(status, Status::SUCCESS); - EXPECT_EQ(ret.ToString(), std::string("age:21")); - - status = manager->CloseKvStore(std::move(appKvStorePtr)); - EXPECT_EQ(status, Status::SUCCESS); - status = manager->DeleteKvStore("student"); - EXPECT_EQ(status, Status::SUCCESS); -} - -/** - * @tc.name: AppKvstorePut010 - * @tc.desc: put invalid key data to KvStore - * @tc.type: FUNC - * @tc.require: AR000CCPOL AR000CQS36 - * @tc.author: liqiao - */ -HWTEST_F(AppDistributedKvStoreTest, AppKvstorePut010, TestSize.Level1) -{ - // cover app_kvstore_put_010, app_kvstore_put_local_010 - std::unique_ptr appKvStorePtr; - Status status; - - status = manager->GetKvStore( - options, "student", [&](std::unique_ptr appKvStore) { - appKvStorePtr = std::move(appKvStore); - }); - EXPECT_EQ(status, Status::SUCCESS); - - status = appKvStorePtr->Put(localWrite, Key(""), Value("age:18")); - EXPECT_EQ(status, Status::INVALID_ARGUMENT); - - status = appKvStorePtr->Put(syncWrite, Key(""), Value("age:19")); - EXPECT_EQ(status, Status::INVALID_ARGUMENT); - - status = manager->CloseKvStore(std::move(appKvStorePtr)); - EXPECT_EQ(status, Status::SUCCESS); - status = manager->DeleteKvStore("student"); - EXPECT_EQ(status, Status::SUCCESS); -} - -/** - * @tc.name: AppKvstorePut011 - * @tc.desc: Put empty value data to KvStore - * @tc.type: FUNC - * @tc.require: AR000CCPOL AR000CQS36 - * @tc.author: liqiao - */ -HWTEST_F(AppDistributedKvStoreTest, AppKvstorePut011, TestSize.Level1) -{ - // cover app_kvstore_put_011, app_kvstore_put_local_011 - std::unique_ptr appKvStorePtr; - Status status; - - status = manager->GetKvStore( - options, "student", [&](std::unique_ptr appKvStore) { - appKvStorePtr = std::move(appKvStore); - }); - EXPECT_EQ(status, Status::SUCCESS); - - status = appKvStorePtr->Put(localWrite, Key("student_name_lisi"), Value("")); - EXPECT_EQ(status, Status::SUCCESS); - - status = appKvStorePtr->Put(syncWrite, Key("student_name_lisi"), Value("")); - EXPECT_EQ(status, Status::SUCCESS); - - status = manager->CloseKvStore(std::move(appKvStorePtr)); - EXPECT_EQ(status, Status::SUCCESS); - status = manager->DeleteKvStore("student"); - EXPECT_EQ(status, Status::SUCCESS); -} - -std::string Generate1025KeyLen() -{ - // Generate key and the length is more than 1024; - std::string str("prefix"); - for (int i = 0; i < 1024; i++) { - str += "a"; - } - return str; -} - -/** - * @tc.name: AppKvstorePut012 - * @tc.desc: Put key (greater than or equal to 256 bytes) data to KvStore. - * @tc.type: FUNC - * @tc.require: AR000CCPOL AR000CQS36 - * @tc.author: liqiao - */ -HWTEST_F(AppDistributedKvStoreTest, AppKvstorePut012, TestSize.Level1) -{ - // cover app_kvstore_put_012, app_kvstore_put_local_012 - std::unique_ptr appKvStorePtr; - Status status; - std::string str16 = "0123456789abcdef"; - std::string str256 = ""; - for (int i = 0; i < 16; i++) { - str256 = str256 + str16; - } - std::string str257 = str256 + "g"; - ASSERT_EQ(256UL, str256.size()); - ASSERT_EQ(257UL, str257.size()); - - status = manager->GetKvStore( - options, "student", [&](std::unique_ptr appKvStore) { - appKvStorePtr = std::move(appKvStore); - }); - EXPECT_EQ(status, Status::SUCCESS); - - status = appKvStorePtr->Put(localWrite, Key(str256), Value("class:2, age:50")); - EXPECT_EQ(status, Status::SUCCESS); - status = appKvStorePtr->Put(localWrite, Key(Generate1025KeyLen()), Value("class:2, age:50")); - EXPECT_EQ(status, Status::INVALID_ARGUMENT); - - status = appKvStorePtr->Put(syncWrite, Key(str256), Value("class:2, age:51")); - EXPECT_EQ(status, Status::SUCCESS); - status = appKvStorePtr->Put(syncWrite, Key(Generate1025KeyLen()), Value("class:2, age:51")); - EXPECT_EQ(status, Status::INVALID_ARGUMENT); - - status = manager->CloseKvStore(std::move(appKvStorePtr)); - EXPECT_EQ(status, Status::SUCCESS); - status = manager->DeleteKvStore("student"); - EXPECT_EQ(status, Status::SUCCESS); -} - -/** - * @tc.name: AppKvstorePut013 - * @tc.desc: put invalid key data to KvStore. - * @tc.type: FUNC - * @tc.require: AR000CCPOL AR000CQS36 - * @tc.author: liqiao - */ -HWTEST_F(AppDistributedKvStoreTest, app_kvstore_put_013, TestSize.Level1) -{ - // cover app_kvstore_put_013, app_kvstore_put_local_013 - std::unique_ptr appKvStorePtr; - Status status; - - status = manager->GetKvStore( - options, "student", [&](std::unique_ptr appKvStore) { - appKvStorePtr = std::move(appKvStore); - }); - EXPECT_EQ(status, Status::SUCCESS); - - status = appKvStorePtr->Put(localWrite, Key(" "), Value("class:2, age:50")); - EXPECT_EQ(status, Status::INVALID_ARGUMENT); - - status = appKvStorePtr->Put(syncWrite, Key(" "), Value("class:2, age:51")); - EXPECT_EQ(status, Status::INVALID_ARGUMENT); - - status = manager->CloseKvStore(std::move(appKvStorePtr)); - EXPECT_EQ(status, Status::SUCCESS); - status = manager->DeleteKvStore("student"); - EXPECT_EQ(status, Status::SUCCESS); -} - -/** - * @tc.name: AppKvstorePut014 - * @tc.desc: Put value (greater than or equal to 1 M) data to KvStore. - * @tc.type: FUNC - * @tc.require: AR000CCPOL AR000CQS36 - * @tc.author: liqiao - */ -HWTEST_F(AppDistributedKvStoreTest, AppKvstorePut014, TestSize.Level1) -{ - // cover app_kvstore_put_014, app_kvstore_put_local_014 - std::unique_ptr appKvStorePtr; - Status status; - - status = manager->GetKvStore( - options, "student", [&](std::unique_ptr appKvStore) { - appKvStorePtr = std::move(appKvStore); - }); - EXPECT_EQ(status, Status::SUCCESS); - - constexpr int VALUE_MAX_SIZE = 4 * 1024 * 1024; - std::vector valueData(VALUE_MAX_SIZE); - for(int i = 0; i < VALUE_MAX_SIZE; i++) { - valueData[i] = 'a'; - } - - status = appKvStorePtr->Put(localWrite, Key("student_name_lisi"), Value(valueData)); - EXPECT_EQ(status, Status::SUCCESS); - status = appKvStorePtr->Put(syncWrite, Key("student_name_lisa"), Value(valueData)); - EXPECT_EQ(status, Status::SUCCESS); - - valueData.push_back('a'); - status = appKvStorePtr->Put(localWrite, Key("student_name_lisi"), Value(valueData)); - EXPECT_EQ(status, Status::INVALID_ARGUMENT); - status = appKvStorePtr->Put(syncWrite, Key("student_name_lisa"), Value(valueData)); - EXPECT_EQ(status, Status::INVALID_ARGUMENT); - - status = manager->CloseKvStore(std::move(appKvStorePtr)); - EXPECT_EQ(status, Status::SUCCESS); - status = manager->DeleteKvStore("student"); - EXPECT_EQ(status, Status::SUCCESS); -} - -/** - * @tc.name: AppKvstoreDelete001 - * @tc.desc: Delete data from KvStore. - * @tc.type: FUNC - * @tc.require: AR000CCPOL AR000CQS36 - * @tc.author: liqiao - */ -HWTEST_F(AppDistributedKvStoreTest, AppKvstoreDelete001, TestSize.Level1) -{ - // cover app_kvstore_delete_001, app_kvstore_delete_local_001 - // app_kvstore_get_002, app_kvstore_get_local_002 - std::unique_ptr appKvStorePtr; - Status status; - - status = manager->GetKvStore( - options, "student", [&](std::unique_ptr appKvStore) { - appKvStorePtr = std::move(appKvStore); - }); - EXPECT_EQ(status, Status::SUCCESS); - - status = appKvStorePtr->Put(localWrite, Key("math_score_int"), Value(TransferTypeToByteArray(-383468))); - EXPECT_EQ(status, Status::SUCCESS); - status = appKvStorePtr->Delete(localWrite, Key("math_score_int")); - EXPECT_EQ(status, Status::SUCCESS); - status = appKvStorePtr->Put(syncWrite, Key("math_score_int_another"), Value(TransferTypeToByteArray(-383468))); - EXPECT_EQ(status, Status::SUCCESS); - status = appKvStorePtr->Delete(syncWrite, Key("math_score_int_another")); - EXPECT_EQ(status, Status::SUCCESS); - - Value ret; - status = appKvStorePtr->Get(localRead, Key("math_score_int"), ret); - EXPECT_EQ(status, Status::KEY_NOT_FOUND); - status = appKvStorePtr->Get(localRead, Key("math_score_int_another"), ret); - EXPECT_EQ(status, Status::KEY_NOT_FOUND); - - status = manager->CloseKvStore(std::move(appKvStorePtr)); - EXPECT_EQ(status, Status::SUCCESS); - status = manager->DeleteKvStore("student"); - EXPECT_EQ(status, Status::SUCCESS); -} - -/** - * @tc.name: AppKvstoreDelete002 - * @tc.desc: Delete a key which does not exist. - * @tc.type: FUNC - * @tc.require: AR000CCPOL AR000CQS36 - * @tc.author: liqiao - */ -HWTEST_F(AppDistributedKvStoreTest, AppKvstoreDelete002, TestSize.Level1) -{ - // cover app_kvstore_delete_002, app_kvstore_delete_local_002 - std::unique_ptr appKvStorePtr; - Status status; - - status = manager->GetKvStore( - options, "student", [&](std::unique_ptr appKvStore) { - appKvStorePtr = std::move(appKvStore); - }); - EXPECT_EQ(status, Status::SUCCESS); - - status = appKvStorePtr->Put(localWrite, Key("math_score_int"), Value(TransferTypeToByteArray(-383468))); - EXPECT_EQ(status, Status::SUCCESS); - status = appKvStorePtr->Delete(localWrite, Key("math_score_int")); - EXPECT_EQ(status, Status::SUCCESS); - status = appKvStorePtr->Delete(localWrite, Key("math_score_int")); - EXPECT_EQ(status, Status::SUCCESS); - status = appKvStorePtr->Put(syncWrite, Key("math_score_int_another"), Value(TransferTypeToByteArray(-383468))); - EXPECT_EQ(status, Status::SUCCESS); - status = appKvStorePtr->Delete(syncWrite, Key("math_score_int_another")); - EXPECT_EQ(status, Status::SUCCESS); - status = appKvStorePtr->Delete(syncWrite, Key("math_score_int_another")); - EXPECT_EQ(status, Status::SUCCESS); - - Value ret; - status = appKvStorePtr->Get(localRead, Key("math_score_int"), ret); - EXPECT_EQ(status, Status::KEY_NOT_FOUND); - status = appKvStorePtr->Get(localRead, Key("math_score_int_another"), ret); - EXPECT_EQ(status, Status::KEY_NOT_FOUND); - - status = manager->CloseKvStore(std::move(appKvStorePtr)); - EXPECT_EQ(status, Status::SUCCESS); - status = manager->DeleteKvStore("student"); - EXPECT_EQ(status, Status::SUCCESS); -} - -/** - * @tc.name: AppKvstoreDelete003 - * @tc.desc: Delete a key which is invalid. - * @tc.type: FUNC - * @tc.require: AR000CCPOL AR000CQS36 - * @tc.author: liqiao - */ -HWTEST_F(AppDistributedKvStoreTest, AppKvstoreDelete003, TestSize.Level1) -{ - // cover app_kvstore_delete_003, app_kvstore_delete_local_003 - std::unique_ptr appKvStorePtr; - Status status; - - status = manager->GetKvStore( - options, "student", [&](std::unique_ptr appKvStore) { - appKvStorePtr = std::move(appKvStore); - }); - EXPECT_EQ(status, Status::SUCCESS); - - status = appKvStorePtr->Delete(localWrite, Key("")); - EXPECT_EQ(status, Status::INVALID_ARGUMENT); - - status = manager->CloseKvStore(std::move(appKvStorePtr)); - EXPECT_EQ(status, Status::SUCCESS); - status = manager->DeleteKvStore("student"); - EXPECT_EQ(status, Status::SUCCESS); -} - -/** - * @tc.name: AppKvstoreGet001 - * @tc.desc: Get data from KvStore. - * @tc.type: FUNC - * @tc.require: AR000CCPOL AR000CQS36 - * @tc.author: liqiao - */ -HWTEST_F(AppDistributedKvStoreTest, AppKvstoreGet001, TestSize.Level1) -{ - // cover app_kvstore_get_003, app_kvstore_get_local_003 - std::unique_ptr appKvStorePtr; - Status status; - - status = manager->GetKvStore( - options, "student", [&](std::unique_ptr appKvStore) { - appKvStorePtr = std::move(appKvStore); - }); - EXPECT_EQ(status, Status::SUCCESS); - - Value ret; - status = appKvStorePtr->Get(localRead, Key("student_name_lisi"), ret); - EXPECT_EQ(status, Status::KEY_NOT_FOUND); - status = appKvStorePtr->Get(syncRead, Key("student_name_lisi"), ret); - EXPECT_EQ(status, Status::KEY_NOT_FOUND); - - status = manager->CloseKvStore(std::move(appKvStorePtr)); - EXPECT_EQ(status, Status::SUCCESS); - status = manager->DeleteKvStore("student"); - EXPECT_EQ(status, Status::SUCCESS); -} - -/** - * @tc.name: AppKvstoreGetEntries001 - * @tc.desc: Get entries with prefix from KvStore. - * @tc.type: FUNC - * @tc.require: AR000CCPOL AR000CQS36 - * @tc.author: liqiao - */ -HWTEST_F(AppDistributedKvStoreTest, AppKvstoreGetEntries001, TestSize.Level1) -{ - // cover app_kvstore_getentries_001, app_kvstore_getentries_local_001 - std::unique_ptr appKvStorePtr; - Status status; - - status = manager->GetKvStore( - options, "student", [&](std::unique_ptr appKvStore) { - appKvStorePtr = std::move(appKvStore); - }); - EXPECT_EQ(status, Status::SUCCESS); - - std::vector ret; - status = appKvStorePtr->Put(localWrite, Key("student_name_mali"), Value("age:20")); - EXPECT_EQ(status, Status::SUCCESS); - status = appKvStorePtr->Put(localWrite, Key("student_name_caixu"), Value("age:19")); - EXPECT_EQ(status, Status::SUCCESS); - status = appKvStorePtr->Put(localWrite, Key("student_name_liuyue"), Value("age:23")); - EXPECT_EQ(status, Status::SUCCESS); - status = appKvStorePtr->Put(syncWrite, Key("student_name_maliang"), Value("age:21")); - EXPECT_EQ(status, Status::SUCCESS); - status = appKvStorePtr->Put(syncWrite, Key("student_name_zhuangzhou"), Value("age:22")); - EXPECT_EQ(status, Status::SUCCESS); - status = appKvStorePtr->Put(syncWrite, Key("student_name_liuyuxi"), Value("age:24")); - EXPECT_EQ(status, Status::SUCCESS); - status = appKvStorePtr->Put(syncWrite, Key("teacher_name_libai"), Value("age:25")); - EXPECT_EQ(status, Status::SUCCESS); - status = appKvStorePtr->GetEntries(Key("student_name_"), ret); - EXPECT_EQ(status, Status::SUCCESS); - EXPECT_EQ(ret.size(), 3UL); - - std::map result; - for (Entry entry : ret) { - result.insert(std::pair(entry.key.ToString(), entry.value.ToString())); - } - EXPECT_EQ(result["student_name_maliang"], std::string("age:21")); - EXPECT_EQ(result["student_name_zhuangzhou"], std::string("age:22")); - EXPECT_EQ(result["student_name_liuyuxi"], std::string("age:24")); - - status = manager->CloseKvStore(std::move(appKvStorePtr)); - EXPECT_EQ(status, Status::SUCCESS); - status = manager->DeleteKvStore("student"); - EXPECT_EQ(status, Status::SUCCESS); -} - -/** - * @tc.name: AppKvstoreGetEntries002 - * @tc.desc: Get entries with non-existing prefix from KvStore. - * @tc.type: FUNC - * @tc.require: AR000CCPOL AR000CQS36 - * @tc.author: liqiao - */ -HWTEST_F(AppDistributedKvStoreTest, AppKvstoreGetEntries002, TestSize.Level1) -{ - // cover app_kvstore_getentries_002, app_kvstore_getentries_local_002 - std::unique_ptr appKvStorePtr; - Status status; - - status = manager->GetKvStore( - options, "student", [&](std::unique_ptr appKvStore) { - appKvStorePtr = std::move(appKvStore); - }); - EXPECT_EQ(status, Status::SUCCESS); - - std::vector ret; - status = appKvStorePtr->Put(syncWrite, Key("student_name_maliang"), Value("age:21")); - EXPECT_EQ(status, Status::SUCCESS); - status = appKvStorePtr->Put(syncWrite, Key("student_name_zhuangzhou"), Value("age:22")); - EXPECT_EQ(status, Status::SUCCESS); - status = appKvStorePtr->Put(syncWrite, Key("student_name_liuyuxi"), Value("age:24")); - EXPECT_EQ(status, Status::SUCCESS); - status = appKvStorePtr->GetEntries(Key("teacher_name_"), ret); - EXPECT_EQ(status, Status::KEY_NOT_FOUND); - EXPECT_EQ(ret.size(), 0UL); - - status = manager->CloseKvStore(std::move(appKvStorePtr)); - EXPECT_EQ(status, Status::SUCCESS); - status = manager->DeleteKvStore("student"); - EXPECT_EQ(status, Status::SUCCESS); -} - -/** - * @tc.name: AppKvstoreGetEntries003 - * @tc.desc: Get entries with prefix (empty string) from KvStore, and all data should be returned. - * @tc.type: FUNC - * @tc.require: AR000CCPOL AR000CQS36 - * @tc.author: liqiao - */ -HWTEST_F(AppDistributedKvStoreTest, AppKvstoreGetEntries003, TestSize.Level1) -{ - // cover app_kvstore_getentries_003, app_kvstore_getentries_local_003 - std::unique_ptr appKvStorePtr; - Status status; - - status = manager->GetKvStore( - options, "student", [&](std::unique_ptr appKvStore) { - appKvStorePtr = std::move(appKvStore); - }); - EXPECT_EQ(status, Status::SUCCESS); - - std::vector ret; - status = appKvStorePtr->Put(localWrite, Key("student_name_mali"), Value("age:20")); - EXPECT_EQ(status, Status::SUCCESS); - status = appKvStorePtr->Put(syncWrite, Key("student_name_maliang"), Value("age:21")); - EXPECT_EQ(status, Status::SUCCESS); - status = appKvStorePtr->Put(syncWrite, Key("student_name_zhuangzhou"), Value("age:22")); - EXPECT_EQ(status, Status::SUCCESS); - status = appKvStorePtr->Put(syncWrite, Key("student_name_liuyuxi"), Value("age:24")); - EXPECT_EQ(status, Status::SUCCESS); - status = appKvStorePtr->GetEntries(Key(""), ret); - EXPECT_EQ(status, Status::SUCCESS); - EXPECT_EQ(ret.size(), 3UL); - - std::map result; - for (Entry entry : ret) { - result.insert(std::pair(entry.key.ToString(), entry.value.ToString())); - } - EXPECT_EQ(result["student_name_maliang"], std::string("age:21")); - EXPECT_EQ(result["student_name_zhuangzhou"], std::string("age:22")); - EXPECT_EQ(result["student_name_liuyuxi"], std::string("age:24")); - - status = manager->CloseKvStore(std::move(appKvStorePtr)); - EXPECT_EQ(status, Status::SUCCESS); - status = manager->DeleteKvStore("student"); - EXPECT_EQ(status, Status::SUCCESS); -} - -/** - * @tc.name: AppKvstoreGetEntries004 - * @tc.desc: Get entries with prefix (empty string) from KvStore, and all data should be returned. - * @tc.type: FUNC - * @tc.require: AR000CCPOL AR000CQS36 - * @tc.author: liqiao - */ -HWTEST_F(AppDistributedKvStoreTest, AppKvstoreGetEntries004, TestSize.Level1) -{ - // cover app_kvstore_getentries_004, app_kvstore_getentries_local_004 - std::unique_ptr appKvStorePtr; - Status status; - - status = manager->GetKvStore( - options, "student", [&](std::unique_ptr appKvStore) { - appKvStorePtr = std::move(appKvStore); - }); - EXPECT_EQ(status, Status::SUCCESS); - - std::vector ret; - status = appKvStorePtr->Put(localWrite, Key("student_name_mali"), Value("age:20")); - EXPECT_EQ(status, Status::SUCCESS); - status = appKvStorePtr->Put(syncWrite, Key("student_name_maliang"), Value("age:21")); - EXPECT_EQ(status, Status::SUCCESS); - status = appKvStorePtr->Put(syncWrite, Key("student_name_zhuangzhou"), Value("age:22")); - EXPECT_EQ(status, Status::SUCCESS); - status = appKvStorePtr->Put(syncWrite, Key("student_name_liuyuxi"), Value("age:24")); - EXPECT_EQ(status, Status::SUCCESS); - status = appKvStorePtr->GetEntries(Key(" "), ret); - EXPECT_EQ(status, Status::SUCCESS); - EXPECT_EQ(ret.size(), 3UL); - - std::map result; - for (Entry entry : ret) { - result.insert(std::pair(entry.key.ToString(), entry.value.ToString())); - } - EXPECT_EQ(result["student_name_maliang"], std::string("age:21")); - EXPECT_EQ(result["student_name_zhuangzhou"], std::string("age:22")); - EXPECT_EQ(result["student_name_liuyuxi"], std::string("age:24")); - - status = manager->CloseKvStore(std::move(appKvStorePtr)); - EXPECT_EQ(status, Status::SUCCESS); - status = manager->DeleteKvStore("student"); - EXPECT_EQ(status, Status::SUCCESS); -} - -/** - * @tc.name: AppKvstoreGetEntries005 - * @tc.desc: GetEntries - * @tc.type: FUNC - * @tc.require: AR000CCPOL AR000CQS36 - * @tc.author: liqiao - */ -HWTEST_F(AppDistributedKvStoreTest, AppKvstoreGetEntries005, TestSize.Level1) -{ - // cover app_kvstore_getentries_005, app_kvstore_getentries_local_005 - std::unique_ptr appKvStorePtr; - Status status; - - status = manager->GetKvStore( - options, "student", [&](std::unique_ptr appKvStore) { - appKvStorePtr = std::move(appKvStore); - }); - EXPECT_EQ(status, Status::SUCCESS); - - std::string str16 = "0123456789abcdef"; - std::string str240 = ""; - for (int i = 0; i < 15; i++) { - str240 = str240 + str16; - } - std::vector ret; - status = appKvStorePtr->Put(localWrite, Key("student_name_mali"), Value("age:20")); - EXPECT_EQ(status, Status::SUCCESS); - status = appKvStorePtr->Put(syncWrite, Key("student_name_maliang"), Value("age:21")); - EXPECT_EQ(status, Status::SUCCESS); - status = appKvStorePtr->Put(syncWrite, Key("student_name_zhuangzhou"), Value("age:22")); - EXPECT_EQ(status, Status::SUCCESS); - status = appKvStorePtr->Put(syncWrite, Key("student_name_liuyuxi"), Value("age:24")); - EXPECT_EQ(status, Status::SUCCESS); - ASSERT_EQ((std::string("student_name_lisi") + str240).size(), 257UL); // key have max size 256 - status = appKvStorePtr->GetEntries(Key(std::string("student_name_lisi") + Generate1025KeyLen()), ret); - EXPECT_EQ(status, Status::INVALID_ARGUMENT); - - status = manager->CloseKvStore(std::move(appKvStorePtr)); - EXPECT_EQ(status, Status::SUCCESS); - status = manager->DeleteKvStore("student"); - EXPECT_EQ(status, Status::SUCCESS); -} - -/** - * @tc.name: AppKvstoreSubscribeKvStore001 - * @tc.desc: SubscribeKvStore and revieve callback - * @tc.type: FUNC - * @tc.require: AR000CCPOL - * @tc.author: liqiao - */ -HWTEST_F(AppDistributedKvStoreTest, AppKvstoreSubscribeKvStore001, TestSize.Level1) -{ - // cover app_kvstore_subscribekvstore_001, app_kvstore_subscribekvstore_003, - // app_kvstore_subscribekvstore_local_001, app_kvstore_subscribekvstore_local_003 - - // this testcase fails with a small probable. please leave this log print alone. - ZLOGI("testcase app_kvstore_subscribekvstore_001"); - std::unique_ptr appKvStorePtr; - Status status; - - status = manager->GetKvStore( - options, storeId, [&](std::unique_ptr appKvStore) { - appKvStorePtr = std::move(appKvStore); - }); - EXPECT_NE(appKvStorePtr, nullptr); - EXPECT_EQ(status, Status::SUCCESS); - ObserverImpl *observerLocal = new ObserverImpl(); - status = appKvStorePtr->SubscribeKvStore(localRead, subscribeType, observerLocal); - EXPECT_EQ(status, Status::SUCCESS); - ObserverImpl *observerSync = new ObserverImpl(); - status = appKvStorePtr->SubscribeKvStore(syncRead, subscribeType, observerSync); - EXPECT_EQ(status, Status::SUCCESS); - - observerLocal->Clear(); - observerSync->Clear(); - status = appKvStorePtr->Put(localWrite, Key("key_s1"), Value("value")); - EXPECT_EQ(status, Status::SUCCESS); - sleep(1); - EXPECT_EQ(observerLocal->insertEntries.size(), 1UL); - EXPECT_EQ(observerLocal->deleteEntries.size(), 0UL); - EXPECT_EQ(observerSync->insertEntries.size(), 0UL) << "contain " << observerSync->insertEntries[0].key.ToString(); - EXPECT_EQ(observerSync->deleteEntries.size(), 0UL) << "contain " << observerSync->deleteEntries[0].key.ToString(); - std::cout << observerLocal->CallCount() << observerSync->CallCount() << std::endl; - - observerLocal->Clear(); - observerSync->Clear(); - status = appKvStorePtr->Put(syncWrite, Key("key_s1"), Value("value")); - EXPECT_EQ(status, Status::SUCCESS); - status = appKvStorePtr->Delete(syncWrite, Key("key_s1")); - EXPECT_EQ(status, Status::SUCCESS); - sleep(1); - EXPECT_EQ(observerLocal->insertEntries.size(), 0UL); - EXPECT_EQ(observerLocal->deleteEntries.size(), 0UL); - EXPECT_EQ(observerSync->insertEntries.size(), 0UL) << "contain " << observerSync->insertEntries[0].key.ToString(); - EXPECT_EQ(observerSync->deleteEntries.size(), 1UL); - std::cout << observerLocal->CallCount() << observerSync->CallCount() << std::endl; - - EXPECT_EQ(observerLocal->isClear, false); - - status = manager->CloseKvStore(std::move(appKvStorePtr)); - EXPECT_EQ(status, Status::SUCCESS); - - status = manager->DeleteKvStore(storeId); - EXPECT_EQ(status, Status::SUCCESS); - delete observerLocal; - delete observerSync; - observerLocal = nullptr; - observerSync = nullptr; -} - -/** - * @tc.name: AppKvstoreSubscribeKvStore002 - * @tc.desc: SubscribeKvStore observer is nullptr - * @tc.type: FUNC - * @tc.require: AR000CCPOL - * @tc.author: liqiao - */ -HWTEST_F(AppDistributedKvStoreTest, AppKvstoreSubscribeKvStore002, TestSize.Level1) -{ - // cover app_kvstore_subscribekvstore_002, app_kvstore_subscribekvstore_local_002 - std::unique_ptr appKvStorePtr; - Status status; - status = manager->GetKvStore( - options, storeId, [&](std::unique_ptr appKvStore) { - appKvStorePtr = std::move(appKvStore); - }); - EXPECT_NE(appKvStorePtr, nullptr); - EXPECT_EQ(status, Status::SUCCESS); - - status = appKvStorePtr->SubscribeKvStore(localRead, subscribeType, nullptr); - EXPECT_EQ(status, Status::INVALID_ARGUMENT); - status = appKvStorePtr->SubscribeKvStore(syncRead, subscribeType, nullptr); - EXPECT_EQ(status, Status::INVALID_ARGUMENT); - - status = manager->CloseKvStore(std::move(appKvStorePtr)); - EXPECT_EQ(status, Status::SUCCESS); - - status = manager->DeleteKvStore(storeId); - EXPECT_EQ(status, Status::SUCCESS); -} - -/** - * @tc.name: AppKvstoreSubscribeKvStore003 - * @tc.desc: the same observer SubscribeKvStore many times - * @tc.type: FUNC - * @tc.require: AR000CCPOL - * @tc.author: liqiao - */ -HWTEST_F(AppDistributedKvStoreTest, AppKvstoreSubscribeKvStore003, TestSize.Level2) -{ - // cover app_kvstore_subscribekvstore_004, app_kvstore_subscribekvstore_local_004 - std::unique_ptr appKvStorePtr; - Status status; - - status = manager->GetKvStore( - options, storeId, [&](std::unique_ptr appKvStore) { - appKvStorePtr = std::move(appKvStore); - }); - EXPECT_NE(appKvStorePtr, nullptr); - EXPECT_EQ(status, Status::SUCCESS); - - ObserverImpl *observerLocal = new ObserverImpl(); - status = appKvStorePtr->SubscribeKvStore(localRead, subscribeType, observerLocal); - EXPECT_EQ(status, Status::SUCCESS); - status = appKvStorePtr->SubscribeKvStore(localRead, subscribeType, observerLocal); - EXPECT_EQ(status, Status::STORE_ALREADY_SUBSCRIBE); - status = appKvStorePtr->SubscribeKvStore(localRead, subscribeType, observerLocal); - EXPECT_EQ(status, Status::STORE_ALREADY_SUBSCRIBE); - ObserverImpl *observerSync = new ObserverImpl(); - status = appKvStorePtr->SubscribeKvStore(syncRead, subscribeType, observerSync); - EXPECT_EQ(status, Status::SUCCESS); - status = appKvStorePtr->SubscribeKvStore(syncRead, subscribeType, observerSync); - EXPECT_EQ(status, Status::STORE_ALREADY_SUBSCRIBE); - status = appKvStorePtr->SubscribeKvStore(syncRead, subscribeType, observerSync); - EXPECT_EQ(status, Status::STORE_ALREADY_SUBSCRIBE); - - status = appKvStorePtr->Put(localWrite, Key("key"), Value("value")); - EXPECT_EQ(status, Status::SUCCESS); - sleep(1); - EXPECT_EQ(observerLocal->CallCount(), 1); - EXPECT_EQ(observerSync->CallCount(), 0); - - status = appKvStorePtr->Put(syncWrite, Key("key"), Value("value")); - EXPECT_EQ(status, Status::SUCCESS); - status = appKvStorePtr->Delete(syncWrite, Key("key")); - EXPECT_EQ(status, Status::SUCCESS); - sleep(1); - EXPECT_EQ(observerLocal->CallCount(), 1); - EXPECT_EQ(observerSync->CallCount(), 2); - - status = manager->CloseKvStore(std::move(appKvStorePtr)); - EXPECT_EQ(status, Status::SUCCESS); - - status = manager->DeleteKvStore(storeId); - EXPECT_EQ(status, Status::SUCCESS); - delete observerLocal; - delete observerSync; - observerLocal = nullptr; - observerSync = nullptr; -} - -/** - * @tc.name: AppKvstoreSubscribeKvStore004 - * @tc.desc: the different observer SubscribeKvStore many times - * @tc.type: FUNC - * @tc.require: AR000CCPOL - * @tc.author: liqiao - */ -HWTEST_F(AppDistributedKvStoreTest, AppKvstoreSubscribeKvStore004, TestSize.Level2) -{ - // cover app_kvstore_subscribekvstore_004, app_kvstore_subscribekvstore_local_004 - std::unique_ptr appKvStorePtr; - Status status; - - status = manager->GetKvStore( - options, storeId, [&](std::unique_ptr appKvStore) { - appKvStorePtr = std::move(appKvStore); - }); - EXPECT_NE(appKvStorePtr, nullptr); - EXPECT_EQ(status, Status::SUCCESS); - - ObserverImpl *observerLocal1 = new ObserverImpl(); - status = appKvStorePtr->SubscribeKvStore(localRead, subscribeType, observerLocal1); - EXPECT_EQ(status, Status::SUCCESS); - ObserverImpl *observerLocal2 = new ObserverImpl(); - status = appKvStorePtr->SubscribeKvStore(localRead, subscribeType, observerLocal2); - EXPECT_EQ(status, Status::SUCCESS); - ObserverImpl *observerLocal3 = new ObserverImpl(); - status = appKvStorePtr->SubscribeKvStore(localRead, subscribeType, observerLocal3); - EXPECT_EQ(status, Status::SUCCESS); - ObserverImpl *observerSync1 = new ObserverImpl(); - status = appKvStorePtr->SubscribeKvStore(syncRead, subscribeType, observerSync1); - EXPECT_EQ(status, Status::SUCCESS); - ObserverImpl *observerSync2 = new ObserverImpl(); - status = appKvStorePtr->SubscribeKvStore(syncRead, subscribeType, observerSync2); - EXPECT_EQ(status, Status::SUCCESS); - ObserverImpl *observerSync3 = new ObserverImpl(); - status = appKvStorePtr->SubscribeKvStore(syncRead, subscribeType, observerSync3); - EXPECT_EQ(status, Status::SUCCESS); - - status = appKvStorePtr->Put(localWrite, Key("key"), Value("value")); - EXPECT_EQ(status, Status::SUCCESS); - sleep(1); - EXPECT_EQ(observerLocal1->CallCount(), 1); - EXPECT_EQ(observerLocal2->CallCount(), 1); - EXPECT_EQ(observerLocal3->CallCount(), 1); - EXPECT_EQ(observerSync1->CallCount(), 0); - EXPECT_EQ(observerSync2->CallCount(), 0); - EXPECT_EQ(observerSync3->CallCount(), 0); - - status = appKvStorePtr->Put(syncWrite, Key("key"), Value("value")); - EXPECT_EQ(status, Status::SUCCESS); - status = appKvStorePtr->Delete(syncWrite, Key("key")); - EXPECT_EQ(status, Status::SUCCESS); - sleep(1); - EXPECT_EQ(observerLocal1->CallCount(), 1); - EXPECT_EQ(observerLocal2->CallCount(), 1); - EXPECT_EQ(observerLocal3->CallCount(), 1); - EXPECT_EQ(observerSync1->CallCount(), 2); - EXPECT_EQ(observerSync2->CallCount(), 2); - EXPECT_EQ(observerSync3->CallCount(), 2); - - status = manager->CloseKvStore(std::move(appKvStorePtr)); - EXPECT_EQ(status, Status::SUCCESS); - - status = manager->DeleteKvStore(storeId); - EXPECT_EQ(status, Status::SUCCESS); - delete observerLocal1; - delete observerLocal2; - delete observerLocal3; - delete observerSync1; - delete observerSync2; - delete observerSync3; - observerLocal1 = nullptr; - observerLocal2 = nullptr; - observerLocal3 = nullptr; - observerSync1 = nullptr; - observerSync2 = nullptr; - observerSync3 = nullptr; -} - -/** - * @tc.name: AppKvstoreSubscribeKvStore005 - * @tc.desc: SubscribeKvStore and then unSubscribeKvStore - * @tc.type: FUNC - * @tc.require: AR000CCPOL - * @tc.author: liqiao - */ -HWTEST_F(AppDistributedKvStoreTest, AppKvstoreSubscribeKvStore005, TestSize.Level2) -{ - // cover app_kvstore_subscribekvstore_004, app_kvstore_subscribekvstore_local_004 - std::unique_ptr appKvStorePtr; - Status status; - - status = manager->GetKvStore( - options, storeId, [&](std::unique_ptr appKvStore) { - appKvStorePtr = std::move(appKvStore); - }); - EXPECT_NE(appKvStorePtr, nullptr); - EXPECT_EQ(status, Status::SUCCESS); - - ObserverImpl *observerLocal = new ObserverImpl(); - status = appKvStorePtr->SubscribeKvStore(localRead, subscribeType, observerLocal); - EXPECT_EQ(status, Status::SUCCESS); - ObserverImpl *observerSync = new ObserverImpl(); - status = appKvStorePtr->SubscribeKvStore(syncRead, subscribeType, observerSync); - EXPECT_EQ(status, Status::SUCCESS); - - status = appKvStorePtr->Put(localWrite, Key("key"), Value("value")); - EXPECT_EQ(status, Status::SUCCESS); - sleep(1); - EXPECT_EQ(observerLocal->CallCount(), 1); - EXPECT_EQ(observerSync->CallCount(), 0); - status = appKvStorePtr->Put(syncWrite, Key("key"), Value("value")); - EXPECT_EQ(status, Status::SUCCESS); - sleep(1); - EXPECT_EQ(observerLocal->CallCount(), 1); - EXPECT_EQ(observerSync->CallCount(), 1); - - status = appKvStorePtr->UnSubscribeKvStore(localRead, subscribeType, observerLocal); - EXPECT_EQ(status, Status::SUCCESS); - status = appKvStorePtr->UnSubscribeKvStore(syncRead, subscribeType, observerSync); - EXPECT_EQ(status, Status::SUCCESS); - observerLocal->Clear(); - observerSync->Clear(); - - - status = appKvStorePtr->Put(syncWrite, Key("key"), Value("value")); - EXPECT_EQ(status, Status::SUCCESS); - status = appKvStorePtr->Delete(syncWrite, Key("key")); - EXPECT_EQ(status, Status::SUCCESS); - sleep(1); - EXPECT_EQ(observerLocal->CallCount(), 0); - EXPECT_EQ(observerSync->CallCount(), 0); - - status = manager->CloseKvStore(std::move(appKvStorePtr)); - EXPECT_EQ(status, Status::SUCCESS); - - status = manager->DeleteKvStore(storeId); - EXPECT_EQ(status, Status::SUCCESS); - delete observerLocal; - delete observerSync; - observerLocal = nullptr; - observerSync = nullptr; -} - -/** - * @tc.name: AppKvstoreSubscribeKvStore006 - * @tc.desc: SubscribeKvStore and then unSubscribeKvStore, verifying callback condition - * @tc.type: FUNC - * @tc.require: AR000CCPOL - * @tc.author: liqiao - */ -HWTEST_F(AppDistributedKvStoreTest, AppKvstoreSubscribeKvStore006, TestSize.Level2) -{ - // cover app_kvstore_subscribekvstore_007~011, app_kvstore_subscribekvstore_local_007~011 - std::unique_ptr appKvStorePtr; - Status status; - - status = manager->GetKvStore( - options, storeId, [&](std::unique_ptr appKvStore) { - appKvStorePtr = std::move(appKvStore); - }); - EXPECT_NE(appKvStorePtr, nullptr); - EXPECT_EQ(status, Status::SUCCESS); - - status = appKvStorePtr->Put(syncWrite, Key("key"), Value("syncValue")); - EXPECT_EQ(status, Status::SUCCESS); - status = appKvStorePtr->Put(localWrite, Key("key"), Value("localValue")); - EXPECT_EQ(status, Status::SUCCESS); - - ObserverImpl *localObserver = new ObserverImpl(); - ObserverImpl *syncObserver = new ObserverImpl(); - status = appKvStorePtr->SubscribeKvStore(localRead, subscribeType, localObserver); - EXPECT_EQ(status, Status::SUCCESS); - sleep(1); - EXPECT_EQ(localObserver->CallCount(), 0); - EXPECT_EQ(syncObserver->CallCount(), 0); - status = appKvStorePtr->SubscribeKvStore(syncRead, subscribeType, syncObserver); - EXPECT_EQ(status, Status::SUCCESS); - sleep(1); - EXPECT_EQ(localObserver->CallCount(), 0); - EXPECT_EQ(syncObserver->CallCount(), 0); - - status = appKvStorePtr->Put(syncWrite, Key("key1"), Value("syncValue1_")); - EXPECT_EQ(status, Status::SUCCESS); - status = appKvStorePtr->Put(syncWrite, Key("key1"), Value("syncValue1")); - EXPECT_EQ(status, Status::SUCCESS); - status = appKvStorePtr->Put(syncWrite, Key("key2"), Value("syncValue2")); - EXPECT_EQ(status, Status::SUCCESS); - sleep(1); - EXPECT_EQ(localObserver->CallCount(), 0); - EXPECT_EQ(syncObserver->insertEntries.size(), 1UL); - EXPECT_EQ(syncObserver->insertEntries[0].key.ToString(), std::string("key2")); - EXPECT_EQ(syncObserver->insertEntries[0].value.ToString(), std::string("syncValue2")); - EXPECT_EQ(syncObserver->deleteEntries.size(), 0UL); - EXPECT_EQ(syncObserver->CallCount(), 3); - - status = appKvStorePtr->Delete(syncWrite, Key("key1")); - sleep(1); - EXPECT_EQ(status, Status::SUCCESS); - EXPECT_EQ(localObserver->CallCount(), 0); - EXPECT_EQ(syncObserver->insertEntries.size(), 0UL); - EXPECT_EQ(syncObserver->deleteEntries.size(), 1UL); - EXPECT_EQ(syncObserver->deleteEntries[0].key.ToString(), std::string("key1")); - EXPECT_EQ(syncObserver->deleteEntries[0].value.ToString(), std::string("syncValue1")); - EXPECT_EQ(syncObserver->CallCount(), 4); - - status = appKvStorePtr->Put(localWrite, Key("key1"), Value("localvalue1_")); - EXPECT_EQ(status, Status::SUCCESS); - status = appKvStorePtr->Put(localWrite, Key("key1"), Value("localvalue1")); - EXPECT_EQ(status, Status::SUCCESS); - status = appKvStorePtr->Put(localWrite, Key("key2"), Value("localvalue2")); - EXPECT_EQ(status, Status::SUCCESS); - sleep(1); - EXPECT_EQ(syncObserver->CallCount(), 4); - EXPECT_EQ(localObserver->insertEntries.size(), 1UL); - EXPECT_EQ(localObserver->insertEntries[0].key.ToString(), std::string("key2")); - EXPECT_EQ(localObserver->insertEntries[0].value.ToString(), std::string("localvalue2")); - EXPECT_EQ(localObserver->deleteEntries.size(), 0UL); - EXPECT_EQ(localObserver->CallCount(), 3); - - status = appKvStorePtr->Delete(localWrite, Key("key1")); - EXPECT_EQ(status, Status::SUCCESS); - sleep(1); - EXPECT_EQ(syncObserver->CallCount(), 4); - EXPECT_EQ(localObserver->insertEntries.size(), 0UL); - EXPECT_EQ(localObserver->deleteEntries.size(), 1UL); - EXPECT_EQ(localObserver->deleteEntries[0].key.ToString(), std::string("key1")); - EXPECT_EQ(localObserver->deleteEntries[0].value.ToString(), std::string("localvalue1")); - EXPECT_EQ(localObserver->CallCount(), 4); - - status = appKvStorePtr->Delete(localWrite, Key("key10")); - EXPECT_EQ(status, Status::SUCCESS); - status = appKvStorePtr->Delete(syncWrite, Key("key10")); - EXPECT_EQ(status, Status::SUCCESS); - EXPECT_EQ(syncObserver->CallCount(), 4); - EXPECT_EQ(localObserver->CallCount(), 4); - - status = appKvStorePtr->UnSubscribeKvStore(syncRead, subscribeType, syncObserver); - EXPECT_EQ(status, Status::SUCCESS); - status = appKvStorePtr->UnSubscribeKvStore(localRead, subscribeType, localObserver); - EXPECT_EQ(status, Status::SUCCESS); - sleep(1); - EXPECT_EQ(syncObserver->CallCount(), 4); - EXPECT_EQ(localObserver->CallCount(), 4); - - status = appKvStorePtr->Put(syncWrite, Key("key1"), Value("value1")); - EXPECT_EQ(status, Status::SUCCESS); - status = appKvStorePtr->Put(localWrite, Key("key1"), Value("value1")); - EXPECT_EQ(status, Status::SUCCESS); - status = appKvStorePtr->Delete(syncWrite, Key("key2")); - EXPECT_EQ(status, Status::SUCCESS); - status = appKvStorePtr->Delete(localWrite, Key("key2")); - EXPECT_EQ(status, Status::SUCCESS); - sleep(1); - EXPECT_EQ(syncObserver->CallCount(), 4); - EXPECT_EQ(localObserver->CallCount(), 4); - - status = manager->CloseKvStore(std::move(appKvStorePtr)); - EXPECT_EQ(status, Status::SUCCESS); - - status = manager->DeleteKvStore(storeId); - EXPECT_EQ(status, Status::SUCCESS); - delete localObserver; - localObserver = nullptr; - delete syncObserver; - syncObserver = nullptr; -} - -/** - * @tc.name: AppKvstoreSubscribeKvStore007 - * @tc.desc: unSubscribeKvStore many times - * @tc.type: FUNC - * @tc.require: AR000CCPOL - * @tc.author: liqiao - */ -HWTEST_F(AppDistributedKvStoreTest, AppKvstoreSubscribeKvStore007, TestSize.Level1) -{ - // cover app_kvstore_subscribekvstore_014, app_kvstore_subscribekvstore_015, - // app_kvstore_subscribekvstore_local_014, app_kvstore_subscribekvstore_local_015 - std::unique_ptr appKvStorePtr; - Status status; - - status = manager->GetKvStore( - options, storeId, [&](std::unique_ptr appKvStore) { - appKvStorePtr = std::move(appKvStore); - }); - EXPECT_NE(appKvStorePtr, nullptr); - EXPECT_EQ(status, Status::SUCCESS); - ObserverImpl *observerLocal = new ObserverImpl(); - status = appKvStorePtr->UnSubscribeKvStore(localRead, subscribeType, observerLocal); - EXPECT_EQ(status, Status::STORE_NOT_SUBSCRIBE); - ObserverImpl *observerSync = new ObserverImpl(); - status = appKvStorePtr->UnSubscribeKvStore(syncRead, subscribeType, observerSync); - EXPECT_EQ(status, Status::STORE_NOT_SUBSCRIBE); - - status = appKvStorePtr->SubscribeKvStore(localRead, subscribeType, observerLocal); - EXPECT_EQ(status, Status::SUCCESS); - status = appKvStorePtr->SubscribeKvStore(syncRead, subscribeType, observerSync); - EXPECT_EQ(status, Status::SUCCESS); - - status = appKvStorePtr->UnSubscribeKvStore(localRead, subscribeType, observerLocal); - EXPECT_EQ(status, Status::SUCCESS); - status = appKvStorePtr->UnSubscribeKvStore(syncRead, subscribeType, observerSync); - EXPECT_EQ(status, Status::SUCCESS); - - status = appKvStorePtr->UnSubscribeKvStore(localRead, subscribeType, observerLocal); - EXPECT_EQ(status, Status::STORE_NOT_SUBSCRIBE); - status = appKvStorePtr->UnSubscribeKvStore(syncRead, subscribeType, observerSync); - EXPECT_EQ(status, Status::STORE_NOT_SUBSCRIBE); - - status = manager->CloseKvStore(std::move(appKvStorePtr)); - EXPECT_EQ(status, Status::SUCCESS); - - status = manager->DeleteKvStore(storeId); - EXPECT_EQ(status, Status::SUCCESS); - delete observerLocal; - delete observerSync; - observerLocal = nullptr; - observerSync = nullptr; -} - -static void InitResultSetData() -{ - std::unique_ptr appKvStorePtr; - Status status = AppDistributedKvStoreTest::manager->GetKvStore( - AppDistributedKvStoreTest::options, "school", [&](std::unique_ptr appKvStore) { - appKvStorePtr = std::move(appKvStore); - }); - WriteOptions localWrite; - localWrite.local = false; - const std::vector students = {"stu_Id1", "stu_Id2", "stu_Id3", "stu_Id4", "stu_Id5"}; - for (const auto &student : students) { - status = appKvStorePtr->Put(localWrite, Key(student), Value("result_set")); - EXPECT_EQ(status, Status::SUCCESS); - } - const std::vector teachers = {"tch_Id1", "tch_Id2", "tch_Id3", "tch_Id4", "tch_Id5", "tch_Id6"}; - for (const auto &teacher : teachers) { - status = appKvStorePtr->Put(localWrite, Key(teacher), Value("result_set")); - EXPECT_EQ(status, Status::SUCCESS); - } - AppDistributedKvStoreTest::manager->CloseKvStore(std::move(appKvStorePtr)); -} - -/** - * @tc.name: AppKvstoreResultSet001 - * @tc.desc: test ResultSet GetEntries when key not exist - * @tc.type: FUNC - * @tc.require: AR000D08KT - * @tc.author: liuyuhui - */ -HWTEST_F(AppDistributedKvStoreTest, AppKvstoreResultSet001, TestSize.Level1) -{ - /** - * @tc.steps: step1. initialize kvstore. - * @tc.expected: step1. SUCCESS. - */ - std::unique_ptr appKvStorePtr; - Status status = manager->GetKvStore( - options, "school", [&](std::unique_ptr appKvStore) { - appKvStorePtr = std::move(appKvStore); - }); - EXPECT_EQ(status, Status::SUCCESS); - - /** - * @tc.steps: step2. call GetEntries when key not exist. - * @tc.expected: step2. KEY_NOT_FOUND. - */ - AppKvStoreResultSet *appKvStoreResultSet = nullptr; - status = appKvStorePtr->GetEntries(Key("key_no_exist"), appKvStoreResultSet); - EXPECT_EQ(status, Status::SUCCESS); - EXPECT_NE(appKvStoreResultSet, nullptr); - EXPECT_EQ(0, appKvStoreResultSet->GetCount()); - status = appKvStorePtr->CloseResultSet(appKvStoreResultSet); - EXPECT_EQ(status, Status::SUCCESS); - - /** - * @tc.steps: step3. close and delete kvstore. - * @tc.expected: step3. SUCCESS. - */ - status = manager->CloseKvStore(std::move(appKvStorePtr)); - EXPECT_EQ(status, Status::SUCCESS); - status = manager->DeleteKvStore("school"); - EXPECT_EQ(status, Status::SUCCESS); -} - -/** - * @tc.name: AppKvstoreResultSet002 - * @tc.desc: test ResultSet GetEntries - * @tc.type: FUNC - * @tc.require: AR000D08KT - * @tc.author: liuyuhui - */ -HWTEST_F(AppDistributedKvStoreTest, AppKvstoreResultSet002, TestSize.Level1) -{ - InitResultSetData(); - - /** - * @tc.steps: step1. initialize kvstore. - * @tc.expected: step1. SUCCESS. - */ - std::unique_ptr appKvStorePtr; - Status status = manager->GetKvStore( - options, "school", [&](std::unique_ptr appKvStore) { - appKvStorePtr = std::move(appKvStore); - }); - EXPECT_EQ(status, Status::SUCCESS); - - /** - * @tc.steps: step2. call GetEntries with param appKvStoreResultSet. - * @tc.expected: step2. SUCCESS. - */ - AppKvStoreResultSet *appKvStoreResultSet = nullptr; - status = appKvStorePtr->GetEntries(Key("stu_"), appKvStoreResultSet); - EXPECT_NE(appKvStoreResultSet, nullptr); - EXPECT_EQ(status, Status::SUCCESS); - EXPECT_EQ(5, static_cast(appKvStoreResultSet->GetCount())); - - EXPECT_EQ(-1, static_cast(appKvStoreResultSet->GetPosition())); - EXPECT_EQ(true, appKvStoreResultSet->IsBeforeFirst()); - - EXPECT_EQ(true, appKvStoreResultSet->MoveToNext()); - EXPECT_EQ(0, static_cast(appKvStoreResultSet->GetPosition())); - EXPECT_EQ(true, appKvStoreResultSet->IsFirst()); - - EXPECT_EQ(true, appKvStoreResultSet->Move(1)); - EXPECT_EQ(1, static_cast(appKvStoreResultSet->GetPosition())); - EXPECT_EQ(false, appKvStoreResultSet->IsFirst()); - - EXPECT_EQ(true, appKvStoreResultSet->MoveToPosition(2)); - EXPECT_EQ(2, static_cast(appKvStoreResultSet->GetPosition())); - - EXPECT_EQ(true, appKvStoreResultSet->MoveToPrevious()); - EXPECT_EQ(1, static_cast(appKvStoreResultSet->GetPosition())); - - EXPECT_EQ(false, appKvStoreResultSet->IsAfterLast()); - EXPECT_EQ(true, appKvStoreResultSet->MoveToLast()); - EXPECT_EQ(4, static_cast(appKvStoreResultSet->GetPosition())); - EXPECT_EQ(true, appKvStoreResultSet->IsLast()); - Entry entry; - status = appKvStoreResultSet->GetEntry(entry); - EXPECT_EQ(Status::SUCCESS, status); - EXPECT_EQ(entry.key.ToString(), std::string("stu_Id5")); - EXPECT_EQ(entry.value.ToString(), std::string("result_set")); - - EXPECT_EQ(false, appKvStoreResultSet->MoveToNext()); - EXPECT_EQ(true, appKvStoreResultSet->IsAfterLast()); - - EXPECT_EQ(false, appKvStoreResultSet->MoveToNext()); - EXPECT_EQ(true, appKvStoreResultSet->IsAfterLast()); - - EXPECT_EQ(false, appKvStoreResultSet->MoveToPosition(5)); // MoveToPosition more than data size - EXPECT_EQ(false, appKvStoreResultSet->Move(10)); // Move more than data size - - status = appKvStorePtr->CloseResultSet(appKvStoreResultSet); - EXPECT_EQ(status, Status::SUCCESS); - - /** - * @tc.steps: step3. close and delete kvstore. - * @tc.expected: step3. SUCCESS. - */ - status = manager->CloseKvStore(std::move(appKvStorePtr)); - EXPECT_EQ(status, Status::SUCCESS); - status = manager->DeleteKvStore("school"); - EXPECT_EQ(status, Status::SUCCESS); -} diff --git a/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/local_subscribe_store_test.cpp b/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/local_subscribe_store_test.cpp index e6dc58d283a7980d083c79496344b3356e668672..22ef5f8ee5642ccca7c31ef5f27fb94467246803 100755 --- a/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/local_subscribe_store_test.cpp +++ b/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/local_subscribe_store_test.cpp @@ -139,7 +139,9 @@ void KvStoreObserverUnitTest::OnChange(const ChangeNotification &changeNotificat } void KvStoreObserverUnitTest::OnChange(const ChangeNotification &changeNotification) -{} +{ + OnChange(changeNotification, nullptr); +} void KvStoreObserverUnitTest::ResetToZero() { diff --git a/frameworks/jskitsimpl/distributeddata/include/js_field_node.h b/frameworks/jskitsimpl/distributeddata/include/js_field_node.h index 693c499a72900903842bcfa2eea268be820b9887..36aa79e21467c224b5c26f0f281806c84be7ff7a 100644 --- a/frameworks/jskitsimpl/distributeddata/include/js_field_node.h +++ b/frameworks/jskitsimpl/distributeddata/include/js_field_node.h @@ -14,8 +14,8 @@ */ #ifndef OHOS_FIELD_NODE_H #define OHOS_FIELD_NODE_H -#include #include +#include "nlohmann/json.hpp" #include "js_util.h" #include "napi_queue.h" diff --git a/frameworks/jskitsimpl/distributeddata/include/js_kv_manager.h b/frameworks/jskitsimpl/distributeddata/include/js_kv_manager.h index 15fc2795a9671c072bb7c1b1120f83d9ccc09301..0710af8367ee71f97e3c8b512182deb6a099fe3f 100644 --- a/frameworks/jskitsimpl/distributeddata/include/js_kv_manager.h +++ b/frameworks/jskitsimpl/distributeddata/include/js_kv_manager.h @@ -19,11 +19,12 @@ #include "kvstore_death_recipient.h" #include "napi_queue.h" #include "uv_queue.h" +#include "js_observer.h" namespace OHOS::DistributedData { class JsKVManager { public: - JsKVManager(const std::string &bundleName); + JsKVManager(const std::string &bundleName, napi_env env); ~JsKVManager(); static napi_value CreateKVManager(napi_env env, napi_callback_info info); @@ -41,18 +42,18 @@ private: static napi_value Off(napi_env env, napi_callback_info info); private: + class DeathRecipient : public DistributedKv::KvStoreDeathRecipient, public JSObserver { + public: + DeathRecipient(std::shared_ptr uvQueue, napi_value callback) : JSObserver(uvQueue, callback) {}; + virtual ~DeathRecipient() = default; + virtual void OnRemoteDied() override; + }; + DistributedKv::DistributedKvDataManager kvDataManager_ {}; std::string bundleName_ {}; std::mutex deathMutex_ {}; - std::list> deathRecipient_ {}; -}; - -class DeathRecipient : public DistributedKv::KvStoreDeathRecipient, public UvQueue { -public: - DeathRecipient(napi_env env, napi_value callback); - virtual ~DeathRecipient() = default; - - virtual void OnRemoteDied() override; + std::list> deathRecipient_ {}; + std::shared_ptr uvQueue_; }; } #endif // OHOS_KV_MANAGER_H diff --git a/frameworks/jskitsimpl/distributeddata/include/js_kv_store.h b/frameworks/jskitsimpl/distributeddata/include/js_kv_store.h index 5ad046038d3a2a55d55ab12497d0b8c302445745..545a0f6bced5af6a8672b848cbe62ddaa6b4180f 100644 --- a/frameworks/jskitsimpl/distributeddata/include/js_kv_store.h +++ b/frameworks/jskitsimpl/distributeddata/include/js_kv_store.h @@ -15,9 +15,11 @@ #ifndef OHOS_KV_STORE_H #define OHOS_KV_STORE_H #include +#include #include "napi_queue.h" #include "single_kvstore.h" #include "uv_queue.h" +#include "js_observer.h" namespace OHOS::DistributedData { enum { @@ -27,7 +29,6 @@ enum { SUBSCRIBE_LOCAL_REMOTE = 2, /* i.e. SubscribeType::SUBSCRIBE_TYPE_ALL--1 */ SUBSCRIBE_COUNT = 3 }; - /* [NOTES] * OHOS::DistributedData::JsKVStore is NOT related to DistributedKv::KvStore!!! * OHOS::DistributedData::JsKVStore is wrapped for DistributedKv::SingleKvStore... @@ -38,6 +39,7 @@ public: virtual ~JsKVStore(); void SetNative(std::shared_ptr& kvStore); + void SetUvQueue(std::shared_ptr uvQueue); std::shared_ptr& GetNative(); static bool IsInstanceOf(napi_env env, napi_value obj, const std::string& storeId, napi_value constructor); @@ -56,6 +58,22 @@ public: static napi_value SetSyncRange(napi_env env, napi_callback_info info); private: + class DataObserver : public DistributedKv::KvStoreObserver, public JSObserver { + public: + DataObserver(std::shared_ptr uvQueue, napi_value callback) : JSObserver(uvQueue, callback) {}; + virtual ~DataObserver() = default; + void OnChange(const DistributedKv::ChangeNotification& notification, + std::shared_ptr snapshot) override; + void OnChange(const DistributedKv::ChangeNotification& notification) override; + }; + + class SyncObserver : public DistributedKv::KvStoreSyncCallback, public JSObserver { + public: + SyncObserver(std::shared_ptr uvQueue, napi_value callback) : JSObserver(uvQueue, callback) {}; + virtual ~SyncObserver() = default; + void SyncCompleted(const std::map& results) override; + }; + /* private static members */ static void OnDataChange(napi_env env, size_t argc, napi_value* argv, std::shared_ptr ctxt); static void OffDataChange(napi_env env, size_t argc, napi_value* argv, std::shared_ptr ctxt); @@ -64,10 +82,10 @@ private: static void OffSyncComplete(napi_env env, size_t argc, napi_value* argv, std::shared_ptr ctxt); /* private non-static members */ - napi_status Subscribe(uint8_t type, std::shared_ptr observer); - napi_status UnSubscribe(uint8_t type, std::shared_ptr observer); + napi_status Subscribe(uint8_t type, std::shared_ptr observer); + napi_status UnSubscribe(uint8_t type, std::shared_ptr observer); - napi_status RegisterSyncCallback(std::shared_ptr sync); + napi_status RegisterSyncCallback(std::shared_ptr sync); napi_status UnRegisterSyncCallback(); /* private non-static members */ @@ -78,27 +96,10 @@ private: static std::map onEventHandlers_; static std::map offEventHandlers_; - std::shared_ptr syncObserver_ = nullptr; + std::list> syncObservers_; std::mutex listMutex_ {}; - std::list> dataObserver_[SUBSCRIBE_COUNT]; -}; - -class DataObserver : public DistributedKv::KvStoreObserver, public UvQueue { -public: - DataObserver(napi_env env, napi_value callback); - virtual ~DataObserver() = default; - - void OnChange(const DistributedKv::ChangeNotification& notification, - std::shared_ptr snapshot) override; - void OnChange(const DistributedKv::ChangeNotification& notification) override; -}; - -class SyncObserver : public DistributedKv::KvStoreSyncCallback, public UvQueue { -public: - SyncObserver(napi_env env, napi_value callback); - virtual ~SyncObserver() = default; - - void SyncCompleted(const std::map& results) override; + std::list> dataObserver_[SUBSCRIBE_COUNT]; + std::shared_ptr uvQueue_; }; } // namespace OHOS::DistributedData #endif // OHOS_SINGLE_KV_STORE_H diff --git a/interfaces/innerkits/app_distributeddata/include/visibility.h b/frameworks/jskitsimpl/distributeddata/include/js_observer.h similarity index 52% rename from interfaces/innerkits/app_distributeddata/include/visibility.h rename to frameworks/jskitsimpl/distributeddata/include/js_observer.h index a5c2669c888b322f43f0c0864b2209c5a39246e0..3cb7ad6f67c977fbc481f828d4bf49acb52a6656 100644 --- a/interfaces/innerkits/app_distributeddata/include/visibility.h +++ b/frameworks/jskitsimpl/distributeddata/include/js_observer.h @@ -12,14 +12,23 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#ifndef OHOS_DISTRIBUTED_DATA_INTERFACE_APP_DISTRIBUTEDDATA_INCLUDE_COMMON_VISIBILITY_H -#define OHOS_DISTRIBUTED_DATA_INTERFACE_APP_DISTRIBUTEDDATA_INCLUDE_COMMON_VISIBILITY_H -#ifndef API_EXPORT -#define API_EXPORT __attribute__((visibility("default"))) -#endif -#ifndef KVSTORE_API -#define KVSTORE_API API_EXPORT -#endif - -#endif // OHOS_DISTRIBUTED_DATA_INTERFACE_APP_DISTRIBUTEDDATA_INCLUDE_COMMON_VISIBILITY_H +#ifndef OHOS_JS_OBSERVER_H +#define OHOS_JS_OBSERVER_H +#include +#include "uv_queue.h" +namespace OHOS::DistributedData { +class JSObserver : public std::enable_shared_from_this { +public: + JSObserver(std::shared_ptr uvQueue, napi_value callback); + virtual ~JSObserver(); + napi_ref GetCallback(); + void Clear(); +protected: + void AsyncCall(UvQueue::NapiArgsGenerator genArgs = UvQueue::NapiArgsGenerator()); +private: + std::shared_ptr uvQueue_; + napi_ref callback_; +}; +} +#endif // OHOS_JS_OBSERVER_H diff --git a/frameworks/jskitsimpl/distributeddata/include/js_util.h b/frameworks/jskitsimpl/distributeddata/include/js_util.h index d6c2d003de2499301926567f05f1142118e628ae..e1c593439d6b230dfae870f85c1a21a34b8df5c3 100644 --- a/frameworks/jskitsimpl/distributeddata/include/js_util.h +++ b/frameworks/jskitsimpl/distributeddata/include/js_util.h @@ -163,6 +163,8 @@ public: /* napi_unwrap with napi_instanceof */ static napi_status Unwrap(napi_env env, napi_value in, void** out, napi_value constructor); + static bool Equals(napi_env env, napi_value value, napi_ref copy); + private: enum { /* std::map to js::tuple */ diff --git a/frameworks/jskitsimpl/distributeddata/include/uv_queue.h b/frameworks/jskitsimpl/distributeddata/include/uv_queue.h index afb6158330dbad501e1225e97b6b3b8f609dbab5..16c1f22304cd0cdd8058293fcb3667de3b8aafdb 100644 --- a/frameworks/jskitsimpl/distributeddata/include/uv_queue.h +++ b/frameworks/jskitsimpl/distributeddata/include/uv_queue.h @@ -15,32 +15,28 @@ #ifndef OHOS_UV_QUEUE_H #define OHOS_UV_QUEUE_H #include - #include "napi/native_api.h" #include "napi/native_common.h" #include "napi/native_node_api.h" #include "uv.h" namespace OHOS::DistributedData { -class UvQueue { - using NapiArgsGenerator = std::function; - +class UvQueue final { public: - UvQueue(napi_env env, napi_value callback); - virtual ~UvQueue(); - - bool operator==(napi_value value); - - void CallFunction(NapiArgsGenerator genArgs = NapiArgsGenerator()); + using NapiArgsGenerator = std::function; + using NapiCallbackGetter = std::function; + UvQueue(napi_env env); + ~UvQueue(); + napi_env GetEnv(); + void AsyncCall(NapiCallbackGetter getter, NapiArgsGenerator genArgs = NapiArgsGenerator()); private: struct UvEntry { napi_env env; - napi_ref callback; + NapiCallbackGetter callback; NapiArgsGenerator args; }; napi_env env_ = nullptr; - napi_ref callback_ = nullptr; uv_loop_s* loop_ = nullptr; }; } diff --git a/frameworks/jskitsimpl/distributeddata/src/js_kv_manager.cpp b/frameworks/jskitsimpl/distributeddata/src/js_kv_manager.cpp index 5073d5c1b7cb918719c809e1a1d2ee7e87908ed9..36eaf5ac25a9ad3b3edcb38ae90c9413b8d66bae 100644 --- a/frameworks/jskitsimpl/distributeddata/src/js_kv_manager.cpp +++ b/frameworks/jskitsimpl/distributeddata/src/js_kv_manager.cpp @@ -30,8 +30,8 @@ bool IsStoreTypeSupported(Options options) || (options.kvStoreType == KvStoreType::SINGLE_VERSION); } -JsKVManager::JsKVManager(const std::string& bundleName) - : bundleName_(bundleName) +JsKVManager::JsKVManager(const std::string& bundleName, napi_env env) + : bundleName_(bundleName), uvQueue_(std::make_shared(env)) { } @@ -41,6 +41,7 @@ JsKVManager::~JsKVManager() std::lock_guard lck(deathMutex_); for (auto& it : deathRecipient_) { kvDataManager_.UnRegisterKvStoreServiceDeathRecipient(it); + it->Clear(); } deathRecipient_.clear(); } @@ -118,7 +119,6 @@ napi_value JsKVManager::GetKVStore(napi_env env, napi_callback_info info) ZLOGD("GetKVStore in"); auto ctxt = std::make_shared(); ctxt->GetCbInfo(env, info); - auto execute = [ctxt]() { auto kvm = reinterpret_cast(ctxt->native); CHECK_ARGS(ctxt, kvm != nullptr, "KVManager is null, failed!"); @@ -130,6 +130,7 @@ napi_value JsKVManager::GetKVStore(napi_env env, napi_callback_info info) ctxt->status = (status == Status::SUCCESS) ? napi_ok : napi_generic_failure; CHECK_STATUS(ctxt, "KVManager->GetSingleKvStore() failed!"); ctxt->kvStore->SetNative(kvStore); + ctxt->kvStore->SetUvQueue(kvm->uvQueue_); }; auto output = [env, ctxt](napi_value& result) { ctxt->status = napi_get_reference_value(env, ctxt->ref, &result); @@ -272,15 +273,14 @@ napi_value JsKVManager::On(napi_env env, napi_callback_info info) std::lock_guard lck(proxy->deathMutex_); for (auto& it : proxy->deathRecipient_) { - auto recipient = std::static_pointer_cast(it); - if (*recipient == argv[1]) { + if (JSUtil::Equals(env, argv[1], it->GetCallback())) { ZLOGD("KVManager::On callback already register!"); return; } } - auto kvStoreDeathRecipient = std::make_shared(env, argv[1]); - proxy->kvDataManager_.RegisterKvStoreServiceDeathRecipient(kvStoreDeathRecipient); - proxy->deathRecipient_.push_back(kvStoreDeathRecipient); + auto deathRecipient = std::make_shared(proxy->uvQueue_, argv[1]); + proxy->kvDataManager_.RegisterKvStoreServiceDeathRecipient(deathRecipient); + proxy->deathRecipient_.push_back(deathRecipient); ZLOGD("on mapsize: %{public}d", static_cast(proxy->deathRecipient_.size())); }; ctxt->GetCbInfoSync(env, info, input); @@ -311,10 +311,10 @@ napi_value JsKVManager::Off(napi_env env, napi_callback_info info) std::lock_guard lck(proxy->deathMutex_); auto it = proxy->deathRecipient_.begin(); while (it != proxy->deathRecipient_.end()) { - auto recipient = std::static_pointer_cast(*it); // have 2 arguments :: have the [callback] - if ((argc == 1) || *recipient == argv[1]) { + if ((argc == 1) || JSUtil::Equals(env, argv[1], (*it)->GetCallback())) { proxy->kvDataManager_.UnRegisterKvStoreServiceDeathRecipient(*it); + (*it)->Clear(); it = proxy->deathRecipient_.erase(it); } else { ++it; @@ -356,7 +356,7 @@ napi_value JsKVManager::New(napi_env env, napi_callback_info info) ctxt->GetCbInfoSync(env, info, input); NAPI_ASSERT(env, ctxt->status == napi_ok, "invalid arguments!"); - JsKVManager* kvManager = new (std::nothrow) JsKVManager(bundleName); + JsKVManager* kvManager = new (std::nothrow) JsKVManager(bundleName, env); NAPI_ASSERT(env, kvManager !=nullptr, "no memory for kvManager"); auto finalize = [](napi_env env, void* data, void* hint) { @@ -369,13 +369,8 @@ napi_value JsKVManager::New(napi_env env, napi_callback_info info) return ctxt->self; } -DeathRecipient::DeathRecipient(napi_env env, napi_value callback) - : UvQueue(env, callback) -{ -} - -void DeathRecipient::OnRemoteDied() +void JsKVManager::DeathRecipient::OnRemoteDied() { - CallFunction(); + AsyncCall(); } } diff --git a/frameworks/jskitsimpl/distributeddata/src/js_kv_store.cpp b/frameworks/jskitsimpl/distributeddata/src/js_kv_store.cpp index a11488768d70d6d73b90182569a37fec0c66ecd9..8e1e034adf7a2779075eb08c59cbff78e5f60c04 100644 --- a/frameworks/jskitsimpl/distributeddata/src/js_kv_store.cpp +++ b/frameworks/jskitsimpl/distributeddata/src/js_kv_store.cpp @@ -57,17 +57,19 @@ JsKVStore::~JsKVStore() std::lock_guard lck(listMutex_); for (uint8_t type = SUBSCRIBE_LOCAL; type < SUBSCRIBE_COUNT; type++) { - for (auto& it : dataObserver_[type]) { - auto observer = std::static_pointer_cast(it); + for (auto& observer : dataObserver_[type]) { auto subscribeType = ToSubscribeType(type); kvStore_->UnSubscribeKvStore(subscribeType, observer); + observer->Clear(); } dataObserver_[type].clear(); } - if (syncObserver_ != nullptr) { - kvStore_->UnRegisterSyncCallback(); + kvStore_->UnRegisterSyncCallback(); + for (auto &syncObserver : syncObservers_) { + syncObserver->Clear(); } + syncObservers_.clear(); } void JsKVStore::SetNative(std::shared_ptr& kvStore) @@ -439,15 +441,13 @@ void JsKVStore::OnDataChange(napi_env env, size_t argc, napi_value* argv, std::s auto proxy = reinterpret_cast(ctxt->native); std::lock_guard lck(proxy->listMutex_); for (auto& it : proxy->dataObserver_[type]) { - auto observer = std::static_pointer_cast(it); - if (*observer == argv[1]) { + if (JSUtil::Equals(env, argv[1], it->GetCallback())) { ZLOGI("function is already subscribe type"); return; } } - std::shared_ptr observer = std::make_shared(env, argv[1]); - ctxt->status = proxy->Subscribe(type, observer); + ctxt->status = proxy->Subscribe(type, std::make_shared(proxy->uvQueue_, argv[1])); CHECK_STATUS(ctxt, "Subscribe failed!"); } @@ -474,16 +474,15 @@ void JsKVStore::OffDataChange(napi_env env, size_t argc, napi_value* argv, std:: auto proxy = reinterpret_cast(ctxt->native); bool found = false; napi_status status = napi_ok; - auto traverse1Type = [argc, argv, proxy, &found, &status](uint8_t type, auto& observers) { + auto traverseType = [argc, argv, proxy, env, &found, &status](uint8_t type, auto& observers) { auto it = observers.begin(); while (it != observers.end()) { - auto observer = std::static_pointer_cast(*it); - if ((argc == 1) && !(*observer == argv[0])) { + if ((argc == 1) && !JSUtil::Equals(env, argv[0], (*it)->GetCallback())) { ++it; continue; // specified observer and not current iterator } found = true; - status = proxy->UnSubscribe(type, observer); + status = proxy->UnSubscribe(type, *it); if (status != napi_ok) { break; // stop on fail. } @@ -493,13 +492,12 @@ void JsKVStore::OffDataChange(napi_env env, size_t argc, napi_value* argv, std:: std::lock_guard lck(proxy->listMutex_); for (uint8_t type = SUBSCRIBE_LOCAL; type < SUBSCRIBE_COUNT; type++) { - traverse1Type(type, proxy->dataObserver_[type]); + traverseType(type, proxy->dataObserver_[type]); if (status != napi_ok) { break; // stop on fail. } } - found |= (argc == 0); // no specified observer, don't care about found or not. - CHECK_ARGS(ctxt, found, "not Subscribed!"); + CHECK_ARGS(ctxt, found || (argc == 0), "not Subscribed!"); } /* @@ -516,9 +514,8 @@ void JsKVStore::OnSyncComplete(napi_env env, size_t argc, napi_value* argv, std: CHECK_STATUS(ctxt, "napi_typeof failed!"); CHECK_ARGS(ctxt, valueType == napi_function, "invalid arg[1], i.e. invalid callback"); - std::shared_ptr callback = std::make_shared(env, argv[0]); auto proxy = reinterpret_cast(ctxt->native); - ctxt->status = proxy->RegisterSyncCallback(callback); + ctxt->status = proxy->RegisterSyncCallback(std::make_shared(proxy->uvQueue_, argv[0])); CHECK_STATUS(ctxt, "RegisterSyncCallback failed!"); } @@ -538,30 +535,36 @@ void JsKVStore::OffSyncComplete(napi_env env, size_t argc, napi_value* argv, std ctxt->status = napi_typeof(env, argv[0], &valueType); CHECK_STATUS(ctxt, "napi_typeof failed!"); CHECK_ARGS(ctxt, valueType == napi_function, "invalid arg[1], i.e. invalid callback"); - auto observer = std::static_pointer_cast(proxy->syncObserver_); - CHECK_ARGS(ctxt, *observer == argv[0], "invalid arg[1], not Subscribed"); + std::lock_guard lck(proxy->listMutex_); + auto it = proxy->syncObservers_.begin(); + while (it != proxy->syncObservers_.end()) { + if (JSUtil::Equals(env, argv[0], (*it)->GetCallback())) { + (*it)->Clear(); + proxy->syncObservers_.erase(it); + break; + } + } + ctxt->status = napi_ok; } ZLOGI("unsubscribe syncComplete, %{public}s specified observer.", (argc == 0) ? "without": "with"); - - ctxt->status = proxy->UnRegisterSyncCallback(); + if (argc == 0 || proxy->syncObservers_.empty()) { + ctxt->status = proxy->UnRegisterSyncCallback(); + } CHECK_STATUS(ctxt, "UnRegisterSyncCallback failed!"); } /* * [Internal private non-static] */ -napi_status JsKVStore::RegisterSyncCallback(std::shared_ptr callback) +napi_status JsKVStore::RegisterSyncCallback(std::shared_ptr callback) { - if (syncObserver_) { - kvStore_->UnRegisterSyncCallback(); - syncObserver_.reset(); - } - Status status = kvStore_->RegisterSyncCallback(callback); if (status != Status::SUCCESS) { + callback->Clear(); return napi_generic_failure; } - syncObserver_ = callback; + std::lock_guard lck(listMutex_); + syncObservers_.push_back(callback); return napi_ok; } @@ -571,45 +574,53 @@ napi_status JsKVStore::UnRegisterSyncCallback() if (status != Status::SUCCESS) { return napi_generic_failure; } - syncObserver_.reset(); + std::lock_guard lck(listMutex_); + for (auto &syncObserver : syncObservers_) { + syncObserver->Clear(); + } + syncObservers_.clear(); return napi_ok; } -napi_status JsKVStore::Subscribe(uint8_t type, std::shared_ptr observer) +napi_status JsKVStore::Subscribe(uint8_t type, std::shared_ptr observer) { auto subscribeType = ToSubscribeType(type); Status status = kvStore_->SubscribeKvStore(subscribeType, observer); ZLOGD("kvStore_->SubscribeKvStore(%{public}d) return %{public}d", type, status); - if (status == Status::SUCCESS) { - dataObserver_[type].push_back(observer); + if (status != Status::SUCCESS) { + observer->Clear(); + return napi_generic_failure; } - return (status == Status::SUCCESS) ? napi_ok : napi_generic_failure; + dataObserver_[type].push_back(observer); + return napi_ok; } -napi_status JsKVStore::UnSubscribe(uint8_t type, std::shared_ptr observer) +napi_status JsKVStore::UnSubscribe(uint8_t type, std::shared_ptr observer) { auto subscribeType = ToSubscribeType(type); Status status = kvStore_->UnSubscribeKvStore(subscribeType, observer); ZLOGD("kvStore_->UnSubscribeKvStore(%{public}d) return %{public}d", type, status); - return (status == Status::SUCCESS) ? napi_ok : napi_generic_failure; + if (status == Status::SUCCESS) { + observer->Clear(); + return napi_ok; + } + return napi_generic_failure; } -/* - * DataObserver - */ -DataObserver::DataObserver(napi_env env, napi_value callback) - : UvQueue(env, callback) +void JsKVStore::SetUvQueue(std::shared_ptr uvQueue) { + uvQueue_ = uvQueue; } -void DataObserver::OnChange(const ChangeNotification& notification, std::shared_ptr snapshot) +void JsKVStore::DataObserver::OnChange(const ChangeNotification ¬ification, + std::shared_ptr snapshot) { ZLOGD("data change insert:%{public}zu, update:%{public}zu, delete:%{public}zu", notification.GetInsertEntries().size(), notification.GetUpdateEntries().size(), notification.GetDeleteEntries().size()); } -void DataObserver::OnChange(const ChangeNotification& notification) +void JsKVStore::DataObserver::OnChange(const ChangeNotification& notification) { ZLOGD("data change insert:%{public}zu, update:%{public}zu, delete:%{public}zu", notification.GetInsertEntries().size(), notification.GetUpdateEntries().size(), @@ -621,24 +632,16 @@ void DataObserver::OnChange(const ChangeNotification& notification) argc = 1; JSUtil::SetValue(env, notification, argv[0]); }; - CallFunction(args); -} - -/* - * SyncObserver - */ -SyncObserver::SyncObserver(napi_env env, napi_value callback) - : UvQueue(env, callback) -{ + AsyncCall(args); } -void SyncObserver::SyncCompleted(const std::map& results) +void JsKVStore::SyncObserver::SyncCompleted(const std::map& results) { auto args = [results](napi_env env, int& argc, napi_value* argv) { // generate 1 arguments for callback function. argc = 1; JSUtil::SetValue(env, results, argv[0]); }; - CallFunction(args); + AsyncCall(args); } } // namespace OHOS::DistributedData diff --git a/services/distributeddataservice/adapter/include/broadcaster/visibility.h b/frameworks/jskitsimpl/distributeddata/src/js_observer.cpp similarity index 34% rename from services/distributeddataservice/adapter/include/broadcaster/visibility.h rename to frameworks/jskitsimpl/distributeddata/src/js_observer.cpp index babdec0b11723616d2689c8b8ed0d363c6bfdf84..720e53151a60df1d4e3fdee5c4c296b2f81a3299 100644 --- a/services/distributeddataservice/adapter/include/broadcaster/visibility.h +++ b/frameworks/jskitsimpl/distributeddata/src/js_observer.cpp @@ -12,12 +12,49 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#ifndef DISTRIBUTEDDATAMGR_BROADCAST_VISIBILITY_H -#define DISTRIBUTEDDATAMGR_BROADCAST_VISIBILITY_H -#ifndef API_EXPORT -#define API_EXPORT __attribute__((visibility("default"))) -#endif -#ifndef KVSTORE_API -#define KVSTORE_API API_EXPORT -#endif -#endif // DISTRIBUTEDDATAMGR_BROADCAST_VISIBILITY_H + +#include "js_observer.h" + +namespace OHOS::DistributedData { +void JSObserver::Clear() +{ + // Clear() run in js main thread, so it serial run with AsyncCall() lambda, so we can use no lock. + if (callback_ == nullptr) { + return ; + } + napi_delete_reference(uvQueue_->GetEnv(), callback_); + callback_ = nullptr; +} + +JSObserver::JSObserver(std::shared_ptr uvQueue, napi_value callback) + : uvQueue_(uvQueue) +{ + napi_create_reference(uvQueue_->GetEnv(), callback, 1, &callback_); +} + +JSObserver::~JSObserver() +{ +} + +napi_ref JSObserver::GetCallback() +{ + return callback_; +} + +void JSObserver::AsyncCall(UvQueue::NapiArgsGenerator genArgs) +{ + if (callback_ == nullptr) { + return; + } + + uvQueue_->AsyncCall([observer = shared_from_this()](napi_env env) -> napi_value { + // the lambda run in js main thread, so it serial run with Clear(), so we can use no lock. + if (observer->callback_ == nullptr) { + return nullptr; + } + napi_value callback = nullptr; + napi_get_reference_value(env, observer->callback_, &callback); + return callback; + }, genArgs); +} +} \ No newline at end of file diff --git a/frameworks/jskitsimpl/distributeddata/src/js_util.cpp b/frameworks/jskitsimpl/distributeddata/src/js_util.cpp index 9a92202f29e08e073c6ae06f9a4869f2f9181355..c755bbb11f2b29eba3f04e5acb1353c43cb6f1ce 100644 --- a/frameworks/jskitsimpl/distributeddata/src/js_util.cpp +++ b/frameworks/jskitsimpl/distributeddata/src/js_util.cpp @@ -981,4 +981,16 @@ napi_status JSUtil::Unwrap(napi_env env, napi_value in, void** out, napi_value c } return napi_unwrap(env, in, out); } +bool JSUtil::Equals(napi_env env, napi_value value, napi_ref copy) +{ + if (copy == nullptr) { + return (value == nullptr); + } + + napi_value copyValue = nullptr; + napi_get_reference_value(env, copy, ©Value); + bool isEquals = false; + napi_strict_equals(env, value, copyValue, &isEquals); + return isEquals; +} } // OHOS::DistributedData diff --git a/frameworks/jskitsimpl/distributeddata/src/uv_queue.cpp b/frameworks/jskitsimpl/distributeddata/src/uv_queue.cpp index 0af33d9ff84f26cf7c3b794121ac5c135cd09360..97c5745e356a4905ba1d41eea82c97d909d61206 100644 --- a/frameworks/jskitsimpl/distributeddata/src/uv_queue.cpp +++ b/frameworks/jskitsimpl/distributeddata/src/uv_queue.cpp @@ -13,46 +13,51 @@ * limitations under the License. */ #define LOG_TAG "UvQueue" + #include "uv_queue.h" #include "log_print.h" #include "napi_queue.h" namespace OHOS::DistributedData { -UvQueue::UvQueue(napi_env env, napi_value callback) +UvQueue::UvQueue(napi_env env) : env_(env) { - napi_create_reference(env, callback, 1, &callback_); - napi_get_uv_event_loop(env, &loop_); + if (env != nullptr) { + napi_get_uv_event_loop(env, &loop_); + } } UvQueue::~UvQueue() { ZLOGD("no memory leak for queue-callback"); - napi_delete_reference(env_, callback_); + env_ = nullptr; } -bool UvQueue::operator==(napi_value value) +void UvQueue::AsyncCall(NapiCallbackGetter getter, NapiArgsGenerator genArgs) { - napi_value callback = nullptr; - napi_get_reference_value(env_, callback_, &callback); - - bool isEquals = false; - napi_strict_equals(env_, value, callback, &isEquals); - return isEquals; -} + if (loop_ == nullptr || !getter) { + ZLOGE("loop_ or callback is nullptr"); + return; + } -void UvQueue::CallFunction(NapiArgsGenerator genArgs) -{ uv_work_t* work = new (std::nothrow) uv_work_t; if (work == nullptr) { ZLOGE("no memory for uv_work_t"); return; } - work->data = new UvEntry{env_, callback_, std::move(genArgs)}; + work->data = new UvEntry{env_, getter, std::move(genArgs)}; uv_queue_work( loop_, work, [](uv_work_t* work) {}, [](uv_work_t* work, int uvstatus) { - auto *entry = static_cast(work->data); + std::shared_ptr entry(static_cast(work->data), [work](UvEntry *data) { + delete data; + delete work; + }); + napi_value method = entry->callback(entry->env); + if (method == nullptr) { + ZLOGE("the callback is invalid, maybe is cleared!"); + return ; + } int argc = 0; napi_value argv[ARGC_MAX] = { nullptr }; if (entry->args) { @@ -60,19 +65,17 @@ void UvQueue::CallFunction(NapiArgsGenerator genArgs) entry->args(entry->env, argc, argv); } ZLOGD("queue uv_after_work_cb"); - - napi_value callback = nullptr; - napi_get_reference_value(entry->env, entry->callback, &callback); napi_value global = nullptr; napi_get_global(entry->env, &global); napi_value result; - napi_status status = napi_call_function(entry->env, global, callback, argc, argv, &result); + napi_status status = napi_call_function(entry->env, global, method, argc, argv, &result); if (status != napi_ok) { - ZLOGE("notify data change failed status:%{public}d callback:%{public}p", status, callback); + ZLOGE("notify data change failed status:%{public}d callback:%{public}p", status, method); } - delete entry; - delete work; - work = nullptr; }); } +napi_env UvQueue::GetEnv() +{ + return env_; +} } diff --git a/interfaces/innerkits/app_distributeddata/BUILD.gn b/interfaces/innerkits/app_distributeddata/BUILD.gn deleted file mode 100755 index 0c204c35132bbce57164c12f84efe68f6d32f6fa..0000000000000000000000000000000000000000 --- a/interfaces/innerkits/app_distributeddata/BUILD.gn +++ /dev/null @@ -1,96 +0,0 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -import("//build/ohos.gni") - -group("build_module") { - deps = [ ":app_distributeddata" ] -} - -config("distributeddata_test_config") { - visibility = [ ":*" ] - - include_dirs = [ "include" ] -} - -config("distributeddatafwk_config") { - visibility = [ ":*" ] - - cflags = [ "-Wno-multichar" ] - - cflags_cc = [ "-fvisibility=hidden" ] - - include_dirs = [ - "include", - "../../../frameworks/innerkitsimpl/distributeddatafwk/src", - "../../../frameworks/innerkitsimpl/distributeddatafwk/include", - "//utils/native/base/include", - ] -} - -config("distributeddatafwk_public_config") { - visibility = [ "//foundation/distributeddatamgr/distributeddatamgr:*" ] - - include_dirs = [ - "include", - "//utils/native/base/include", - "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/include/permission", - "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/include/account", - "//foundation/distributeddatamgr/distributeddatamgr/frameworks/innerkitsimpl/distributeddatafwk/include", - "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata/include", - "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/include/utils", - ] -} - -ohos_shared_library("app_distributeddata") { - part_name = "distributeddatamgr" - sources = [ - "../../../frameworks/innerkitsimpl/distributeddatafwk/src/app_blob.cpp", - "../../../frameworks/innerkitsimpl/distributeddatafwk/src/app_change_notification.cpp", - "../../../frameworks/innerkitsimpl/distributeddatafwk/src/app_distributed_kv_data_manager.cpp", - "../../../frameworks/innerkitsimpl/distributeddatafwk/src/app_distributed_kv_data_manager_impl.cpp", - "../../../frameworks/innerkitsimpl/distributeddatafwk/src/app_distributed_kv_data_manager_impl.h", - "../../../frameworks/innerkitsimpl/distributeddatafwk/src/app_kvstore_conflict_data_impl.cpp", - "../../../frameworks/innerkitsimpl/distributeddatafwk/src/app_kvstore_impl.cpp", - "../../../frameworks/innerkitsimpl/distributeddatafwk/src/app_kvstore_impl.h", - "../../../frameworks/innerkitsimpl/distributeddatafwk/src/app_kvstore_result_set_impl.cpp", - "include/app_types.h", - ] - - configs = [ ":distributeddatafwk_config" ] - deps = [ - "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter:distributeddata_adapter", - "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/permission:distributeddata_permission_static", - "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/libs/distributeddb:distributeddb", - "//utils/native/base:utils", - ] - - external_deps = [ - "hiviewdfx_hilog_native:libhilog", - "ipc:ipc_core", - ] - - public_configs = [ ":distributeddatafwk_public_config" ] - - subsystem_name = "distributeddatamgr" -} - -config("distributeddatafwk_communication_config") { - visibility = [ ":*" ] - - cflags = [ "-Wno-multichar" ] - - include_dirs = [ - "include", - "//utils/native/base/include", - ] -} diff --git a/interfaces/innerkits/app_distributeddata/include/app_blob.h b/interfaces/innerkits/app_distributeddata/include/app_blob.h deleted file mode 100755 index 41b282251c1df01028ffecbc0e8760d6f030cc34..0000000000000000000000000000000000000000 --- a/interfaces/innerkits/app_distributeddata/include/app_blob.h +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef DISTRIBUTED_KV_APP_BLOB_H -#define DISTRIBUTED_KV_APP_BLOB_H - -#include -#include -#include "visibility.h" - -namespace OHOS { -namespace AppDistributedKv { -class AppBlob { -public: - KVSTORE_API AppBlob() = default; - KVSTORE_API ~AppBlob() = default; - - // Copy constructor for Blob. - KVSTORE_API AppBlob(const AppBlob &blob); - KVSTORE_API AppBlob &operator=(const AppBlob &blob); - - // Move constructor for Blob. - KVSTORE_API AppBlob(AppBlob &&blob) noexcept; - KVSTORE_API AppBlob &operator=(AppBlob &&blob) noexcept; - - // Construct a Blob using std::string. - KVSTORE_API AppBlob(const std::string &str); - - // Construct a Blob using char pointer and len. - KVSTORE_API AppBlob(const char *str, size_t n); - - // Construct a Blob using char pointer. - KVSTORE_API AppBlob(const char *str); - - // Construct a Blob using std::vector. - KVSTORE_API AppBlob(const std::vector &str); - - // Return a reference to the data of the blob. - KVSTORE_API const std::vector &Data() const; - - // Return the length (in bytes) of the referenced data. - KVSTORE_API size_t Size() const; - - // Return true if the length of the referenced data is zero. - KVSTORE_API bool Empty() const; - - KVSTORE_API bool operator==(const AppBlob &) const; - - // Change vector to std::string. - KVSTORE_API std::string ToString() const; - - // comparison. Returns value: - // < 0 if "*this" < "blob", - // == 0 if "*this" == "blob", - // > 0 if "*this" > "blob" - KVSTORE_API int Compare(const AppBlob &blob) const; - -private: - std::vector blob_; -}; -} // namespace AppDistributedKv -} // namespace OHOS - -#endif // DISTRIBUTED_KV_APP_BLOB_H diff --git a/interfaces/innerkits/app_distributeddata/include/app_change_notification.h b/interfaces/innerkits/app_distributeddata/include/app_change_notification.h deleted file mode 100644 index f0f2d1ce2dc9fe3fc82a6f3564dad52fa1a7fba1..0000000000000000000000000000000000000000 --- a/interfaces/innerkits/app_distributeddata/include/app_change_notification.h +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef APP_CHANGE_NOTIFICATION_H -#define APP_CHANGE_NOTIFICATION_H - -#include -#include -#include "app_types.h" - -namespace OHOS { -namespace AppDistributedKv { -class AppChangeNotification final { -public: - AppChangeNotification(); - - // constructor using changing data. - AppChangeNotification(const std::list &insertEntries, const std::list &updateEntries, - const std::list &deleteEntries, const std::string &deviceId, const bool isClear); - - KVSTORE_API ~AppChangeNotification(); - - // Function to get all inserted entries for this changing. - KVSTORE_API const std::list &GetInsertEntries() const; - - // Function to get all updated entries for this changing. - KVSTORE_API const std::list &GetUpdateEntries() const; - - // Function to get all deleted entries for this changing. - KVSTORE_API const std::list &GetDeleteEntries() const; - - // Function to get from device id. - KVSTORE_API const std::string &GetDeviceId() const; - - // Function to check if this change is made by calling clear function. - KVSTORE_API bool IsClear() const; - -private: - std::list insertEntries_; - - std::list updateEntries_; - - std::list deleteEntries_; - - std::string deviceId_; - - bool isClear_ = false; -}; -} // namespace AppDistributedKv -} // namespace OHOS - -#endif // APP_CHANGE_NOTIFICATION_H diff --git a/interfaces/innerkits/app_distributeddata/include/app_distributed_kv_data_manager.h b/interfaces/innerkits/app_distributeddata/include/app_distributed_kv_data_manager.h deleted file mode 100755 index 62d42a2d4abfe115699edecfffa2a8a31e9af4e3..0000000000000000000000000000000000000000 --- a/interfaces/innerkits/app_distributeddata/include/app_distributed_kv_data_manager.h +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef APP_DISTRIBUTED_KV_DATA_MANAGER_H -#define APP_DISTRIBUTED_KV_DATA_MANAGER_H - -#include -#include "app_device_status_change_listener.h" -#include "app_kvstore.h" -#include "app_types.h" -#include "app_kvstore_corruption_observer.h" - -namespace OHOS { -namespace AppDistributedKv { -// This is the overall manager of all kvstore. -// This class provides open, close, delete AppKvStore and manage remote device functions. -class AppDistributedKvDataManager { -public: - // Get AppDistributedKvDataManager singleton for APP process (for jni and dynamic library depended by jni). - // Parameters: - // bundleName: bundleName of your app - // dataDir: the directory to save your db file. Please choose a directory you can visit before phone unlock. - // this parameter will not be checked or used after first successful call. - // userId: name of your user. this stands for multiuser, not for account or linux user. - // Return: - // singleton of AppDistributedKvDataManager, or nullptr on error. - KVSTORE_API static std::shared_ptr GetInstance(const std::string &bundleName, - const std::string &dataDir, - const std::string &userId = "account0"); - - KVSTORE_API AppDistributedKvDataManager() - {} - - KVSTORE_API virtual ~AppDistributedKvDataManager() - {} - - // Open kvstore instance with the given storeId, creating it if needed. - // It is allowed to open the same kvstore concurrently - // multiple times, but only one database instance will be created. - // Parameters: - // options: the config of the kvstore, including encrypt, create if needed and whether need sync between - // devices. - // storeId: the name of the kvstore. - // callback: KvStore instance returned by this call. - // callback will return: - // if Options.createIfMissing is false and kvstore has not been created before, nullptr and Status is - // STORE_NOT_FOUND, - // if storeId is not valid, nullptr and Status is INVALID_ARGUMENT - // otherwise, SUCCESS and the unipue_ptr of AppKvStore, which client can use to operate kvstore, will be - // returned. - // Return: - // Status of this get operation. - KVSTORE_API - virtual Status GetKvStore(const Options &options, const std::string &storeId, - const std::function appKvStore)> &callback) = 0; - - // WARNING: try to close a KvStore while other thread(s) still using it may cause process crash. - // Disconnect kvstore connection from database instance with the given storeId, - // only if all connections to the same database instance are closed, database instance will be freed. - // after this call, kvstore becomes invalid. - // call to it will return nullptr exception. - // Parameters: - // appKvStore: kvstore instance created by GetKvStore. - // Return: - // Status of this close operation. - KVSTORE_API virtual Status CloseKvStore(std::unique_ptr appKvStore) = 0; - - // Delete database file with the given storeId. - // Client should first close all connections to it and then delete it, otherwise delete will return error. - // Parameters: - // storeId: the name of the kvstore. - // Return: - // Status of this delete operation. - KVSTORE_API virtual Status DeleteKvStore(const std::string &storeId) = 0; - - // Get the database size. - KVSTORE_API virtual Status GetKvStoreDiskSize(const std::string &storeId, uint64_t &size) = 0; - - // observe - // Parameters: - // observer: observer which will be callback when corrupted. - // Return: - // Status of this operation. - KVSTORE_API - virtual Status RegisterKvStoreCorruptionObserver(const std::shared_ptr observer) = 0; -protected: - AppDistributedKvDataManager(const AppDistributedKvDataManager &) = delete; - AppDistributedKvDataManager& operator=(const AppDistributedKvDataManager&) = delete; - AppDistributedKvDataManager(AppDistributedKvDataManager &&) = delete; - AppDistributedKvDataManager& operator=(AppDistributedKvDataManager &&) = delete; -}; // class AppDistributedKvDataManager -} // namespace AppDistributedKv -} // namespace OHOS - -#endif // APP_DISTRIBUTED_KV_DATA_MANAGER_H diff --git a/interfaces/innerkits/app_distributeddata/include/app_kvstore.h b/interfaces/innerkits/app_distributeddata/include/app_kvstore.h deleted file mode 100755 index 560081e311bcce6fb40d3f8598fde5ba4dbafd81..0000000000000000000000000000000000000000 --- a/interfaces/innerkits/app_distributeddata/include/app_kvstore.h +++ /dev/null @@ -1,167 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef APP_KV_STORE_H -#define APP_KV_STORE_H - -#include -#include -#include "app_kvstore_conflict_data.h" -#include "app_kvstore_observer.h" -#include "app_types.h" -#include "app_kvstore_result_set.h" - -namespace OHOS { -namespace AppDistributedKv { -// This is a public interface. Implementation of this class is in AppKvStoreImpl. -// This class provides put, delete, search, sync and subscribe functions of a key-value store. -class AppKvStore { -public: - KVSTORE_API virtual ~AppKvStore() - {} - - // Get id of this AppKvStore. - KVSTORE_API virtual const std::string &GetStoreId() = 0; - - // Write a pair of key and value to this store. Set write option to local if you do not this entry sync to other - // devices. - // Parameters: - // options: mark this is a local entry or not. - // key: key of this entry. Should be less than 256 bytes. key will be trimmed before store. - // value: value of this entry. Should be less than (1024 * 1024) bytes. - // Return: - // Status of this put operation. - KVSTORE_API virtual Status Put(const WriteOptions &options, const Key &key, const Value &value) = 0; - - // Delete an entry by its key. Set write option to local if you want this delete to be a local change. - // Parameters: - // options: mark this delete is a local change or not. - // key: key of the entry to be deleted. - // Return: - // Status of this delete operation. - KVSTORE_API virtual Status Delete(const WriteOptions &options, const Key &key) = 0; - - // Get value from AppKvStore by its key. Set options->local to true if you want to get from local kvstore. - // Parameters: - // options: mark we get from local store or remote store. options->batch is a reserved parameter and should - // always be false. - // key: key of this entry. - // value: value will be returned in this parameter. - // Return: - // Status of this get operation. - KVSTORE_API virtual Status Get(const ReadOptions &options, const Key &key, Value &value) = 0; - - // Get all entries in this store which key start with prefixKey. This function will always get from synced store. - // Parameters: - // prefixkey: the prefix to be searched. - // entries: entries will be returned in this parameter. - // Return: - // Status of this GetEntries operation. - KVSTORE_API virtual Status GetEntries(const Key &prefixKey, std::vector &entries) = 0; - - // Get all entries in this store which key start with prefixKey. This function will always get from synced store. - // Parameters: - // prefixkey: the prefix to be searched. - // resultSet: resultSet will be returned in this parameter. - // Return: - // Status of this GetEntries operation. - KVSTORE_API virtual Status GetEntries(const Key &prefixKey, AppKvStoreResultSet *&resultSet) = 0; - - // Close the result set returned by GetEntries(). - // Parameters: - // resultSet: resultSet will be returned in this parameter. - // Return: - // Status of this GetEntries operation. - KVSTORE_API virtual Status CloseResultSet(AppKvStoreResultSet *&resultSet) = 0; - - // Sync store with other devices. This is an asynchronous method, - // sync will fail if there is a syncing operation in progress. - // Parameters: - // deviceIds: device list to sync. - // mode: mode can be set to SyncMode::PUSH, SyncMode::PULL and SyncMode::PUTH_PULL. PUSH_PULL will firstly - // push all not-local store to listed devices, then pull these stores back. - // callback: return map to caller. - // Return: - // Status of this Sync operation. - KVSTORE_API virtual Status Sync(const std::vector &deviceIds, SyncMode mode, - const std::function &)> &callback) = 0; - - // Register change of this kvstore to a client-defined observer. observer->OnChange method will be called when store - // changes. One observer can subscribe more than one AppKvStore. - // Parameters: - // options: mark this is a local entry or not. - // subscribeType: OBSERVER_CHANGES_NATIVE means native changes of syncable kv store, - // : OBSERVER_CHANGES_FOREIGN means synced data changes from remote devices, - // : OBSERVER_CHANGES_ALL means both native changes and synced data changes. - // observer: observer to subscribe changes. - // Return: - // Status of this subscribe operation. - KVSTORE_API virtual Status SubscribeKvStore(const ReadOptions &options, const SubscribeType &subscribeType, - AppKvStoreObserver *observer) = 0; - - // Unregister a kvstore to an observer. - // Parameters: - // options: mark this is a local entry or not. - // subscribeType: reserved parameter. Current is always SubscribeType::DEFAULT. - // observer: observer to unsubscribe this store. - // Return: - // Status of this unsubscribe operation. - KVSTORE_API virtual Status UnSubscribeKvStore(const ReadOptions &options, const SubscribeType &subscribeType, - AppKvStoreObserver *observer) = 0; - - // Remove the device data synced from remote. - // Parameters: - // device: device id. - // Return: - // Status of this remove operation. - KVSTORE_API virtual Status RemoveDeviceData(const std::string &device) = 0; - - // Set policy of conflict resolution. - // Parameters: - // conflictType: include CONFLICT_FOREIGN_KEY_ONLY CONFLICT_FOREIGN_KEY_ORIG CONFLICT_NATIVE_ALL. - // callback: conflict resolution callback. - // Return: - // Status of Setting policy operation. - KVSTORE_API - virtual Status SetConflictResolutionPolicy(AppKvStoreConflictPolicyType conflictType, - std::function callback) = 0; - - // Export current data store to ${filePath} using ${passwd} - // Parameters: - // filePath: directory which store will be saved. - // passwd: can be null, which means dont cipher. - // Return: - // Status of this operation. - KVSTORE_API virtual Status Export(const std::string &filePath, const std::vector &passwd) = 0; - - // Import current data store to ${filePath} using ${passwd} - // Parameters: - // filePath: directory from which will recovery. - // passwd: can be null, which means dont cipher. - // Return: - // Status of this operation. - KVSTORE_API virtual Status Import(const std::string &filePath, const std::vector &passwd) = 0; - - // get security level. - // Parameters: - // securityLevel: the security level. - // Return: - // Status of this operation. - KVSTORE_API virtual Status GetSecurityLevel(SecurityLevel &securityLevel) const = 0; -}; -} // namespace AppDistributedKv -} // namespace OHOS - -#endif // APP_KV_STORE_H diff --git a/interfaces/innerkits/app_distributeddata/include/app_kvstore_conflict_data.h b/interfaces/innerkits/app_distributeddata/include/app_kvstore_conflict_data.h deleted file mode 100644 index 3674e9d9344f8f281bc04c7d0d1786268cf68aa8..0000000000000000000000000000000000000000 --- a/interfaces/innerkits/app_distributeddata/include/app_kvstore_conflict_data.h +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef APP_KVSTOR_CONFLICT_DATA_H -#define APP_KVSTOR_CONFLICT_DATA_H - -#include -#include -#include "app_types.h" - -namespace OHOS { -namespace AppDistributedKv { -class AppKvStoreConflictData { -public: - enum class ConflictValueType { - OLD_VALUE = 0, - NEW_VALUE, - }; - - KVSTORE_API virtual ~AppKvStoreConflictData() = default; - - KVSTORE_API virtual AppKvStoreConflictPolicyType GetType() const = 0; - - KVSTORE_API virtual void GetKey(Key &key) const = 0; - - KVSTORE_API virtual Status GetValue(ConflictValueType type, Value &value) const = 0; - - KVSTORE_API virtual bool IsDeleted(ConflictValueType type) const = 0; - - KVSTORE_API virtual bool IsNative(ConflictValueType type) const = 0; -}; -} // namespace AppDistributedKv -} // namespace OHOS - -#endif // APP_KVSTOR_CONFLICT_DATA_H diff --git a/interfaces/innerkits/app_distributeddata/include/app_kvstore_corruption_observer.h b/interfaces/innerkits/app_distributeddata/include/app_kvstore_corruption_observer.h deleted file mode 100644 index a0d945a35f8ded66d6cd2cb2efa24dfda3bc9ab4..0000000000000000000000000000000000000000 --- a/interfaces/innerkits/app_distributeddata/include/app_kvstore_corruption_observer.h +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef DISTRIBUTEDDATAMGR_APP_KVSTORE_CORRUPTION_OBSERVER_H -#define DISTRIBUTEDDATAMGR_APP_KVSTORE_CORRUPTION_OBSERVER_H -namespace OHOS { -namespace AppDistributedKv { -class AppKvStoreCorruptionObserver { -public: - KVSTORE_API virtual ~AppKvStoreCorruptionObserver() {}; - KVSTORE_API - virtual void OnCorruption(const std::string &appId, const std::string &userId, const std::string &storeId) = 0; -}; -} // namespace AppDistributedKv -} // namespace OHOS -#endif // DISTRIBUTEDDATAMGR_APP_KVSTORE_CORRUPTION_OBSERVER_H diff --git a/interfaces/innerkits/app_distributeddata/include/app_kvstore_observer.h b/interfaces/innerkits/app_distributeddata/include/app_kvstore_observer.h deleted file mode 100644 index b536e50564d07ef505727b8e2a3828f0f5500175..0000000000000000000000000000000000000000 --- a/interfaces/innerkits/app_distributeddata/include/app_kvstore_observer.h +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef APP_KVSTORE_OBSERVER_H -#define APP_KVSTORE_OBSERVER_H - -#include "app_change_notification.h" - -namespace OHOS { -namespace AppDistributedKv { -// This is a abstract classes. Client needs to implement this class by self. -class AppKvStoreObserver { -public: - KVSTORE_API AppKvStoreObserver() = default; - - KVSTORE_API virtual ~AppKvStoreObserver() - {} - // This virtual function will be called on store change. - // Client needs to override this function to receive change notification. - // Parameters: - // ChangeNotification: all changes from other devices. - KVSTORE_API virtual void OnChange(const AppChangeNotification &appChangeNotification) = 0; -}; -} // namespace AppDistributedKv -} // namespace OHOS - -#endif // APP_KV_STORE_OBSERVER_H diff --git a/interfaces/innerkits/app_distributeddata/include/app_kvstore_result_set.h b/interfaces/innerkits/app_distributeddata/include/app_kvstore_result_set.h deleted file mode 100755 index 0e8085b4876e41f1252b793666b4104da0131d68..0000000000000000000000000000000000000000 --- a/interfaces/innerkits/app_distributeddata/include/app_kvstore_result_set.h +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef APP_KV_STORE_RESULT_SET_H -#define APP_KV_STORE_RESULT_SET_H - -#include "app_types.h" - -namespace OHOS { -namespace AppDistributedKv { -class AppKvStoreResultSet { -public: - KVSTORE_API virtual ~AppKvStoreResultSet() - {} - - // Returns the count of rows in the result set. - KVSTORE_API virtual int GetCount() const = 0; - - // Returns the current read position of the result set. - KVSTORE_API virtual int GetPosition() const = 0; - - // Move the read position to the first row, return false if the result set is empty. - KVSTORE_API virtual bool MoveToFirst() = 0; - - // Move the read position to the last row, return false if the result set is empty. - KVSTORE_API virtual bool MoveToLast() = 0; - - // Move the read position to the next row, - // and returns false if the result set is empty or the read position is already - // past the last entry in the result set. - KVSTORE_API virtual bool MoveToNext() = 0; - - // Move the read position to the previous row, - // and returns false if result set is empty or the read position is already - // before the first entry in the result set. - KVSTORE_API virtual bool MoveToPrevious() = 0; - - // Move the read position by a relative amount from the current position. - KVSTORE_API virtual bool Move(int offset) = 0; - - // Move the read position to an absolute position value. - KVSTORE_API virtual bool MoveToPosition(int position) = 0; - - // Returns whether the read position is pointing to the first row. - KVSTORE_API virtual bool IsFirst() const = 0; - - // Returns whether the read position is pointing to the last row. - KVSTORE_API virtual bool IsLast() const = 0; - - // Returns whether the read position is before the first row. - KVSTORE_API virtual bool IsBeforeFirst() const = 0; - - // Returns whether the read position is after the last row. - KVSTORE_API virtual bool IsAfterLast() const = 0; - - // Get a key-value entry. - KVSTORE_API virtual Status GetEntry(Entry &entry) const = 0; - - KVSTORE_API virtual Status Close() = 0; -}; -} // namespace AppDistributedKv -} // namespace OHOS - -#endif // APP_KV_STORE_RESULT_SET_H diff --git a/interfaces/innerkits/app_distributeddata/include/app_types.h b/interfaces/innerkits/app_distributeddata/include/app_types.h deleted file mode 100755 index c36bd26f00629c6939e41c60e4532d0ae89a110f..0000000000000000000000000000000000000000 --- a/interfaces/innerkits/app_distributeddata/include/app_types.h +++ /dev/null @@ -1,173 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef APP_DISTRIBUTED_KVSTORE_APP_TYPES_H -#define APP_DISTRIBUTED_KVSTORE_APP_TYPES_H - -#include -#include -#include -#include -#include "app_blob.h" -#include "visibility.h" - -namespace OHOS { -namespace AppDistributedKv { -// Key set by the client, which can be any non-empty byte array with a length of less than 256 bytes. -using Key = OHOS::AppDistributedKv::AppBlob; - -// Value set by client, which can be any byte array. -using Value = OHOS::AppDistributedKv::AppBlob; - -// User ID from the user account -struct UserId { - std::string userId; -}; - -// App ID from the BMS -struct AppId { - std::string appId; -}; - -struct PipeInfo { - std::string pipeId; - std::string userId; -}; - -struct DeviceInfo { - std::string deviceId; - std::string deviceName; - std::string deviceType; -}; - -enum class MessageType { - DEFAULT = 0, - FILE = 1, -}; - -struct MessageInfo { - MessageType msgType; -}; - -enum class DeviceChangeType { - DEVICE_OFFLINE = 0, - DEVICE_ONLINE = 1, -}; - -struct DeviceId { - std::string deviceId; -}; - -// app_distributed_data_manager using sub error code 0 -constexpr ErrCode APP_DISTRIBUTEDDATAMGR_ERR_OFFSET = ErrCodeOffset(SUBSYS_DISTRIBUTEDDATAMNG, 0); - -enum class Status { - SUCCESS = ERR_OK, - ERROR = APP_DISTRIBUTEDDATAMGR_ERR_OFFSET, - INVALID_ARGUMENT = APP_DISTRIBUTEDDATAMGR_ERR_OFFSET + 1, - ILLEGAL_STATE = APP_DISTRIBUTEDDATAMGR_ERR_OFFSET + 2, - STORE_NOT_OPEN = APP_DISTRIBUTEDDATAMGR_ERR_OFFSET + 3, - STORE_NOT_FOUND = APP_DISTRIBUTEDDATAMGR_ERR_OFFSET + 4, - STORE_ALREADY_SUBSCRIBE = APP_DISTRIBUTEDDATAMGR_ERR_OFFSET + 5, - STORE_NOT_SUBSCRIBE = APP_DISTRIBUTEDDATAMGR_ERR_OFFSET + 6, - KEY_NOT_FOUND = APP_DISTRIBUTEDDATAMGR_ERR_OFFSET + 7, - DB_ERROR = APP_DISTRIBUTEDDATAMGR_ERR_OFFSET + 8, - DEVICE_NOT_FOUND = APP_DISTRIBUTEDDATAMGR_ERR_OFFSET + 9, - NETWORK_ERROR = APP_DISTRIBUTEDDATAMGR_ERR_OFFSET + 10, - NO_DEVICE_CONNECTED = APP_DISTRIBUTEDDATAMGR_ERR_OFFSET + 11, - PERMISSION_DENIED = APP_DISTRIBUTEDDATAMGR_ERR_OFFSET + 12, - TIME_OUT = APP_DISTRIBUTEDDATAMGR_ERR_OFFSET + 13, - REPEATED_REGISTER = APP_DISTRIBUTEDDATAMGR_ERR_OFFSET + 14, - CREATE_SESSION_ERROR = APP_DISTRIBUTEDDATAMGR_ERR_OFFSET + 15, - SECURITY_LEVEL_ERROR = APP_DISTRIBUTEDDATAMGR_ERR_OFFSET + 32, -}; - -enum class SubscribeType { - DEFAULT = 0, // reserved value, to be deleted - OBSERVER_CHANGES_NATIVE = 1, // native changes of syncable KvStore - OBSERVER_CHANGES_FOREIGN = 2, // synced data changes from remote devices - OBSERVER_CHANGES_ALL = 3, // both native changes and synced data changes -}; - -struct Entry { - Key key; - Value value; -}; - -enum class SyncMode { - PULL, - PUSH, - PUSH_PULL, -}; - -enum ConflictResolvePolicy { - LAST_WIN = 0, - DEVICE_COLLABORATION, -}; - -enum SecurityLevel : int { - NO_LABEL, - S0, - S1, - S2, - S3_EX, - S3, - S4, -}; - -struct Options { - bool createIfMissing = false; - bool encrypt = false; - bool persistant = false; - int conflictResolvePolicy = LAST_WIN; - int securityLevel = SecurityLevel::NO_LABEL; -}; - -struct WriteOptions { - bool local; -}; - -struct ReadOptions { - bool local; -}; - -template -std::vector TransferTypeToByteArray(const T &t) -{ - return std::vector(reinterpret_cast(const_cast(&t)), - reinterpret_cast(const_cast(&t)) + sizeof(T)); -} - -template -T TransferByteArrayToType(const std::vector &blob) -{ - // replace assert to HILOG_FATAL when HILOG_FATAL is ok. - if (blob.size() != sizeof(T) || blob.size() == 0) { - constexpr int tSize = sizeof(T); - uint8_t tContent[tSize] = { 0 }; - return *reinterpret_cast(tContent); - } - return *reinterpret_cast(const_cast(&blob[0])); -} - -enum class AppKvStoreConflictPolicyType { - CONFIICT_FOREIGN_KEY_ONLY = 0x01, - CONFLICT_FOREIGN_KEY_ORIG = 0x02, - CONFLICT_NATIVE_ALL = 0x0c, -}; -} // namespace AppDistributedKv -} // namespace OHOS - -#endif // APP_DISTRIBUTED_KVSTORE_TYPES_H diff --git a/interfaces/innerkits/distributeddata/include/distributed_kv_data_manager.h b/interfaces/innerkits/distributeddata/include/distributed_kv_data_manager.h index 4770df7c88ae05e1ee86c3861104b4557df14a44..addffb3d94e949c2cdf0c08e185b95c184131ca9 100644 --- a/interfaces/innerkits/distributeddata/include/distributed_kv_data_manager.h +++ b/interfaces/innerkits/distributeddata/include/distributed_kv_data_manager.h @@ -121,7 +121,7 @@ public: void UnRegisterKvStoreServiceDeathRecipient(std::shared_ptr kvStoreDeathRecipient); // Subscribe device status change, like online or offline. - // Client should override AppDeviceStatusChangeListener and register it by this function, observer->OnDeviceChanged + // Client should override AppDeviceChangeListener and register it by this function, observer->OnDeviceChanged // will be called on remote device status change. // Parameters: // observer: callback for device status change event. @@ -130,7 +130,7 @@ public: KVSTORE_API Status StartWatchDeviceChange(std::shared_ptr observer); // Unsubscribe device status change, like online or offline. - // client should override AppDeviceStatusChangeListener and register it by calling this function, then + // client should override AppDeviceChangeListener and register it by calling this function, then // observer->OnDeviceChanged will no longer be called on remote device status change. // Parameters: // observer: callback for device status change event. diff --git a/interfaces/innerkits/distributeddata/include/store_errno.h b/interfaces/innerkits/distributeddata/include/store_errno.h new file mode 100644 index 0000000000000000000000000000000000000000..f3ff8b294cb89155a7f7403f2f26605d8b976c00 --- /dev/null +++ b/interfaces/innerkits/distributeddata/include/store_errno.h @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DISTRIBUTED_DATA_INTERFACES_DISTRIBUTEDDATA_STORE_ERRNO_H +#define OHOS_DISTRIBUTED_DATA_INTERFACES_DISTRIBUTEDDATA_STORE_ERRNO_H +#include +namespace OHOS::DistributedKv { +constexpr ErrCode DISTRIBUTEDDATAMGR_ERR_OFFSET = ErrCodeOffset(SUBSYS_DISTRIBUTEDDATAMNG, 3); +enum Status : int32_t { + SUCCESS = ERR_OK, + ERROR = DISTRIBUTEDDATAMGR_ERR_OFFSET, + INVALID_ARGUMENT = DISTRIBUTEDDATAMGR_ERR_OFFSET + 1, + ILLEGAL_STATE = DISTRIBUTEDDATAMGR_ERR_OFFSET + 2, + SERVER_UNAVAILABLE = DISTRIBUTEDDATAMGR_ERR_OFFSET + 3, + STORE_NOT_OPEN = DISTRIBUTEDDATAMGR_ERR_OFFSET + 4, + STORE_NOT_FOUND = DISTRIBUTEDDATAMGR_ERR_OFFSET + 5, + STORE_ALREADY_SUBSCRIBE = DISTRIBUTEDDATAMGR_ERR_OFFSET + 6, + STORE_NOT_SUBSCRIBE = DISTRIBUTEDDATAMGR_ERR_OFFSET + 7, + KEY_NOT_FOUND = DISTRIBUTEDDATAMGR_ERR_OFFSET + 8, + DB_ERROR = DISTRIBUTEDDATAMGR_ERR_OFFSET + 9, + NETWORK_ERROR = DISTRIBUTEDDATAMGR_ERR_OFFSET + 10, + NO_DEVICE_CONNECTED = DISTRIBUTEDDATAMGR_ERR_OFFSET + 11, + PERMISSION_DENIED = DISTRIBUTEDDATAMGR_ERR_OFFSET + 12, + IPC_ERROR = DISTRIBUTEDDATAMGR_ERR_OFFSET + 13, + CRYPT_ERROR = DISTRIBUTEDDATAMGR_ERR_OFFSET + 14, + TIME_OUT = DISTRIBUTEDDATAMGR_ERR_OFFSET + 15, + DEVICE_NOT_FOUND = DISTRIBUTEDDATAMGR_ERR_OFFSET + 16, + NOT_SUPPORT = DISTRIBUTEDDATAMGR_ERR_OFFSET + 17, + SCHEMA_MISMATCH = DISTRIBUTEDDATAMGR_ERR_OFFSET + 18, + INVALID_SCHEMA = DISTRIBUTEDDATAMGR_ERR_OFFSET + 19, + READ_ONLY = DISTRIBUTEDDATAMGR_ERR_OFFSET + 20, + INVALID_VALUE_FIELDS = DISTRIBUTEDDATAMGR_ERR_OFFSET + 21, + INVALID_FIELD_TYPE = DISTRIBUTEDDATAMGR_ERR_OFFSET + 22, + CONSTRAIN_VIOLATION = DISTRIBUTEDDATAMGR_ERR_OFFSET + 23, + INVALID_FORMAT = DISTRIBUTEDDATAMGR_ERR_OFFSET + 24, + INVALID_QUERY_FORMAT = DISTRIBUTEDDATAMGR_ERR_OFFSET + 25, + INVALID_QUERY_FIELD = DISTRIBUTEDDATAMGR_ERR_OFFSET + 26, + SYSTEM_ACCOUNT_EVENT_PROCESSING = DISTRIBUTEDDATAMGR_ERR_OFFSET + 27, + RECOVER_SUCCESS = DISTRIBUTEDDATAMGR_ERR_OFFSET + 28, + RECOVER_FAILED = DISTRIBUTEDDATAMGR_ERR_OFFSET + 29, + MIGRATION_KVSTORE_FAILED = DISTRIBUTEDDATAMGR_ERR_OFFSET + 30, + EXCEED_MAX_ACCESS_RATE = DISTRIBUTEDDATAMGR_ERR_OFFSET + 31, + SECURITY_LEVEL_ERROR = DISTRIBUTEDDATAMGR_ERR_OFFSET + 32, + OVER_MAX_SUBSCRIBE_LIMITS = DISTRIBUTEDDATAMGR_ERR_OFFSET + 33, +}; +} +#endif // OHOS_DISTRIBUTED_DATA_INTERFACES_DISTRIBUTEDDATA_STORE_ERRNO_H diff --git a/interfaces/innerkits/distributeddata/include/types.h b/interfaces/innerkits/distributeddata/include/types.h index 4e2b0fe1f588131de98bd2659596f2455a36f8a7..70a9eb36e82a706a7a7fd76619c3302ebed4277c 100755 --- a/interfaces/innerkits/distributeddata/include/types.h +++ b/interfaces/innerkits/distributeddata/include/types.h @@ -19,7 +19,7 @@ #include #include #include -#include +#include "store_errno.h" #include "blob.h" #include "visibility.h" @@ -89,46 +89,6 @@ struct AppThreadInfo { std::int32_t uid; }; -// distributed_data_manager using sub error code 3 -constexpr ErrCode DISTRIBUTEDDATAMGR_ERR_OFFSET = ErrCodeOffset(SUBSYS_DISTRIBUTEDDATAMNG, 3); -enum Status : int32_t { - SUCCESS = ERR_OK, - ERROR = DISTRIBUTEDDATAMGR_ERR_OFFSET, - INVALID_ARGUMENT = DISTRIBUTEDDATAMGR_ERR_OFFSET + 1, - ILLEGAL_STATE = DISTRIBUTEDDATAMGR_ERR_OFFSET + 2, - SERVER_UNAVAILABLE = DISTRIBUTEDDATAMGR_ERR_OFFSET + 3, - STORE_NOT_OPEN = DISTRIBUTEDDATAMGR_ERR_OFFSET + 4, - STORE_NOT_FOUND = DISTRIBUTEDDATAMGR_ERR_OFFSET + 5, - STORE_ALREADY_SUBSCRIBE = DISTRIBUTEDDATAMGR_ERR_OFFSET + 6, - STORE_NOT_SUBSCRIBE = DISTRIBUTEDDATAMGR_ERR_OFFSET + 7, - KEY_NOT_FOUND = DISTRIBUTEDDATAMGR_ERR_OFFSET + 8, - DB_ERROR = DISTRIBUTEDDATAMGR_ERR_OFFSET + 9, - NETWORK_ERROR = DISTRIBUTEDDATAMGR_ERR_OFFSET + 10, - NO_DEVICE_CONNECTED = DISTRIBUTEDDATAMGR_ERR_OFFSET + 11, - PERMISSION_DENIED = DISTRIBUTEDDATAMGR_ERR_OFFSET + 12, - IPC_ERROR = DISTRIBUTEDDATAMGR_ERR_OFFSET + 13, - CRYPT_ERROR = DISTRIBUTEDDATAMGR_ERR_OFFSET + 14, - TIME_OUT = DISTRIBUTEDDATAMGR_ERR_OFFSET + 15, - DEVICE_NOT_FOUND = DISTRIBUTEDDATAMGR_ERR_OFFSET + 16, - NOT_SUPPORT = DISTRIBUTEDDATAMGR_ERR_OFFSET + 17, - SCHEMA_MISMATCH = DISTRIBUTEDDATAMGR_ERR_OFFSET + 18, - INVALID_SCHEMA = DISTRIBUTEDDATAMGR_ERR_OFFSET + 19, - READ_ONLY = DISTRIBUTEDDATAMGR_ERR_OFFSET + 20, - INVALID_VALUE_FIELDS = DISTRIBUTEDDATAMGR_ERR_OFFSET + 21, - INVALID_FIELD_TYPE = DISTRIBUTEDDATAMGR_ERR_OFFSET + 22, - CONSTRAIN_VIOLATION = DISTRIBUTEDDATAMGR_ERR_OFFSET + 23, - INVALID_FORMAT = DISTRIBUTEDDATAMGR_ERR_OFFSET + 24, - INVALID_QUERY_FORMAT = DISTRIBUTEDDATAMGR_ERR_OFFSET + 25, - INVALID_QUERY_FIELD = DISTRIBUTEDDATAMGR_ERR_OFFSET + 26, - SYSTEM_ACCOUNT_EVENT_PROCESSING = DISTRIBUTEDDATAMGR_ERR_OFFSET + 27, - RECOVER_SUCCESS = DISTRIBUTEDDATAMGR_ERR_OFFSET + 28, - RECOVER_FAILED = DISTRIBUTEDDATAMGR_ERR_OFFSET + 29, - MIGRATION_KVSTORE_FAILED = DISTRIBUTEDDATAMGR_ERR_OFFSET + 30, - EXCEED_MAX_ACCESS_RATE = DISTRIBUTEDDATAMGR_ERR_OFFSET + 31, - SECURITY_LEVEL_ERROR = DISTRIBUTEDDATAMGR_ERR_OFFSET + 32, - OVER_MAX_SUBSCRIBE_LIMITS = DISTRIBUTEDDATAMGR_ERR_OFFSET + 33, -}; - enum class SubscribeType { DEFAULT = 0, // default let bms delete SUBSCRIBE_TYPE_LOCAL = 1, // local changes of syncable kv store diff --git a/services/distributeddataservice/adapter/BUILD.gn b/services/distributeddataservice/adapter/BUILD.gn index e770a62d1a2182144412ccf7a09b832f41a7bd56..2ac95ca6b37b633f04af74ef453488ab67b7b583 100755 --- a/services/distributeddataservice/adapter/BUILD.gn +++ b/services/distributeddataservice/adapter/BUILD.gn @@ -32,7 +32,6 @@ config("distributeddata_adapter_public_config") { "include/autils", "include/utils", "include", - "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/app_distributeddata/include", "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata/include/", "//foundation/distributeddatamgr/distributeddatamgr/frameworks/common", ] diff --git a/services/distributeddataservice/adapter/account/src/account_delegate_impl.cpp b/services/distributeddataservice/adapter/account/src/account_delegate_impl.cpp index 61c6ec96be0d61c6cffa306b159dd4fde50c5441..b8c4214c332010c17976202ced83fa081bb47c23 100755 --- a/services/distributeddataservice/adapter/account/src/account_delegate_impl.cpp +++ b/services/distributeddataservice/adapter/account/src/account_delegate_impl.cpp @@ -101,14 +101,14 @@ void AccountDelegateImpl::SubscribeAccountEvent() NotifyAccountChanged(account); }); - std::thread th = std::thread([&]() { + std::thread th = std::thread([eventSubscriber = eventSubscriber_]() { int tryTimes = 0; constexpr int MAX_RETRY_TIME = 300; constexpr int RETRY_WAIT_TIME_S = 1; // we use this method to make sure register success while (tryTimes < MAX_RETRY_TIME) { - auto result = CommonEventManager::SubscribeCommonEvent(eventSubscriber_); + auto result = CommonEventManager::SubscribeCommonEvent(eventSubscriber); if (result) { break; } diff --git a/services/distributeddataservice/adapter/auth/BUILD.gn b/services/distributeddataservice/adapter/auth/BUILD.gn index df2d81bec824f84116f837535a582fa2678ee7e0..153aa5683f3d65d97231e4a63b35d61c640abb3b 100644 --- a/services/distributeddataservice/adapter/auth/BUILD.gn +++ b/services/distributeddataservice/adapter/auth/BUILD.gn @@ -24,7 +24,7 @@ ohos_static_library("distributeddata_auth_static") { "//third_party/json/single_include", "//utils/native/base/include", "//foundation/distributeddatamgr/distributeddatamgr/frameworks/common", - "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/app_distributeddata/include", + "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata/include", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/framework/include", ] diff --git a/services/distributeddataservice/adapter/autils/BUILD.gn b/services/distributeddataservice/adapter/autils/BUILD.gn index 9b2fca5fb110fb6f239fd73a56181c5d339af1a4..249bb269b28a1b08df8fa41d726cb718290e35c8 100755 --- a/services/distributeddataservice/adapter/autils/BUILD.gn +++ b/services/distributeddataservice/adapter/autils/BUILD.gn @@ -28,6 +28,7 @@ ohos_static_library("distributeddata_autils_static") { "../include/log", "//utils/native/base/include", "../include/dfx", + "//foundation/distributeddatamgr/distributeddatamgr/frameworks/common", ] cflags_cc = [ "-fvisibility=hidden" ] diff --git a/services/distributeddataservice/adapter/autils/test/BUILD.gn b/services/distributeddataservice/adapter/autils/test/BUILD.gn index 42d22679d44b341d2b6c206c452ab07bdaf7f779..b984d4db4902e625853d087614f7327f4ee3bf71 100755 --- a/services/distributeddataservice/adapter/autils/test/BUILD.gn +++ b/services/distributeddataservice/adapter/autils/test/BUILD.gn @@ -18,7 +18,7 @@ module_output_path = "distributeddatamgr/distributeddatafwk" config("module_private_config") { visibility = [ ":*" ] - include_dirs = [ "../../include/autils/" ] + include_dirs = [ "../../include/autils/", "//foundation/distributeddatamgr/distributeddatamgr/frameworks/common" ] } ohos_unittest("KvStoreThreadPoolTest") { diff --git a/services/distributeddataservice/adapter/broadcaster/BUILD.gn b/services/distributeddataservice/adapter/broadcaster/BUILD.gn index 772b7444dc25a4b18d53d9d3a2e5c1cab829a6f4..868f373412d753c4e017d7374fe41982736e5cf0 100755 --- a/services/distributeddataservice/adapter/broadcaster/BUILD.gn +++ b/services/distributeddataservice/adapter/broadcaster/BUILD.gn @@ -24,6 +24,7 @@ ohos_static_library("distributeddata_broadcaster_static") { "./src", "//utils/native/base/include", "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata/include", + "//foundation/distributeddatamgr/distributeddatamgr/frameworks/common", ] cflags_cc = [ "-fvisibility=hidden" ] diff --git a/services/distributeddataservice/adapter/communicator/BUILD.gn b/services/distributeddataservice/adapter/communicator/BUILD.gn index 1b4a50999cf1462b1ac56eb0caf19d7858250287..4c85257ed4bfdb64bb03205b73080790036d5a55 100755 --- a/services/distributeddataservice/adapter/communicator/BUILD.gn +++ b/services/distributeddataservice/adapter/communicator/BUILD.gn @@ -36,7 +36,8 @@ ohos_static_library("distributeddata_communicator_static") { "../include/dfx", "../include/log", "../include/autils", - "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/app_distributeddata/include", + "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata/include", + "//foundation/distributeddatamgr/distributeddatamgr/frameworks/common", "//foundation/communication/dsoftbus/core/common/include", ] diff --git a/services/distributeddataservice/adapter/communicator/src/app_device_handler.cpp b/services/distributeddataservice/adapter/communicator/src/app_device_handler.cpp index a1054a664d67d7399ca4e31c3bf1f7fe075be3cd..9f4c7cb34e2456d83d6caa43f90bd812ad297c03 100755 --- a/services/distributeddataservice/adapter/communicator/src/app_device_handler.cpp +++ b/services/distributeddataservice/adapter/communicator/src/app_device_handler.cpp @@ -37,13 +37,13 @@ void AppDeviceHandler::Init() softbusAdapter_->Init(); } -Status AppDeviceHandler::StartWatchDeviceChange(const AppDeviceStatusChangeListener *observer, +Status AppDeviceHandler::StartWatchDeviceChange(const AppDeviceChangeListener *observer, __attribute__((unused)) const PipeInfo &pipeInfo) { return softbusAdapter_->StartWatchDeviceChange(observer, pipeInfo); } -Status AppDeviceHandler::StopWatchDeviceChange(const AppDeviceStatusChangeListener *observer, +Status AppDeviceHandler::StopWatchDeviceChange(const AppDeviceChangeListener *observer, __attribute__((unused)) const PipeInfo &pipeInfo) { return softbusAdapter_->StopWatchDeviceChange(observer, pipeInfo); diff --git a/services/distributeddataservice/adapter/communicator/src/app_device_handler.h b/services/distributeddataservice/adapter/communicator/src/app_device_handler.h index b1dbdef0d76ce3e206d0f190090c37964f7f588e..58061278b9af49a8d879a7481166b590e6f36057 100755 --- a/services/distributeddataservice/adapter/communicator/src/app_device_handler.h +++ b/services/distributeddataservice/adapter/communicator/src/app_device_handler.h @@ -26,9 +26,9 @@ public: void Init(); // add DeviceChangeListener to watch device change; - Status StartWatchDeviceChange(const AppDeviceStatusChangeListener *observer, const PipeInfo &pipeInfo); + Status StartWatchDeviceChange(const AppDeviceChangeListener *observer, const PipeInfo &pipeInfo); // stop DeviceChangeListener to watch device change; - Status StopWatchDeviceChange(const AppDeviceStatusChangeListener *observer, const PipeInfo &pipeInfo); + Status StopWatchDeviceChange(const AppDeviceChangeListener *observer, const PipeInfo &pipeInfo); DeviceInfo GetLocalDevice(); std::vector GetDeviceList() const; diff --git a/services/distributeddataservice/adapter/communicator/src/app_pipe_handler.h b/services/distributeddataservice/adapter/communicator/src/app_pipe_handler.h index b68509690d205345398747a729f77db2f781d77e..1f1e5c3933194789c63f89d5bc76cbab66ec0b66 100755 --- a/services/distributeddataservice/adapter/communicator/src/app_pipe_handler.h +++ b/services/distributeddataservice/adapter/communicator/src/app_pipe_handler.h @@ -20,7 +20,6 @@ #include #include #include -#include "app_types.h" #include "kv_scheduler.h" #include "log_print.h" #include "reporter.h" diff --git a/services/distributeddataservice/adapter/communicator/src/app_pipe_mgr.cpp b/services/distributeddataservice/adapter/communicator/src/app_pipe_mgr.cpp index 26fa9ea2df37b1e0ea711b14edabc5cf1f02c02a..80a53859d430959a6b6b3ac94875c56d03a5310d 100755 --- a/services/distributeddataservice/adapter/communicator/src/app_pipe_mgr.cpp +++ b/services/distributeddataservice/adapter/communicator/src/app_pipe_mgr.cpp @@ -91,7 +91,7 @@ Status AppPipeMgr::Start(const PipeInfo &pipeInfo) auto it = dataBusMap_.find(pipeInfo.pipeId); if (it != dataBusMap_.end()) { ZLOGW("repeated start, pipeInfo:%{public}s.", pipeInfo.pipeId.c_str()); - return Status::REPEATED_REGISTER; + return Status::SUCCESS; } ZLOGD("Start pipeInfo:%{public}s ", pipeInfo.pipeId.c_str()); auto handler = std::make_shared(pipeInfo); @@ -108,24 +108,20 @@ Status AppPipeMgr::Start(const PipeInfo &pipeInfo) // stop server Status AppPipeMgr::Stop(const PipeInfo &pipeInfo) { - std::shared_ptr appPipeHandler; - { - std::lock_guard lock(dataBusMapMutex_); - auto it = dataBusMap_.find(pipeInfo.pipeId); - if (it == dataBusMap_.end()) { - ZLOGW("pipeInfo:%s not found", pipeInfo.pipeId.c_str()); - return Status::KEY_NOT_FOUND; - } - appPipeHandler = it->second; - int ret = appPipeHandler->RemoveSessionServer(pipeInfo.pipeId); - if (ret != 0) { - ZLOGW("Stop pipeInfo:%s ret:%d.", pipeInfo.pipeId.c_str(), ret); - return Status::ERROR; - } - dataBusMap_.erase(pipeInfo.pipeId); - return Status::SUCCESS; + std::lock_guard lock(dataBusMapMutex_); + auto it = dataBusMap_.find(pipeInfo.pipeId); + if (it == dataBusMap_.end()) { + ZLOGW("pipeInfo:%s not found", pipeInfo.pipeId.c_str()); + return Status::KEY_NOT_FOUND; } - return Status::KEY_NOT_FOUND; + std::shared_ptr appPipeHandler = it->second; + int ret = appPipeHandler->RemoveSessionServer(pipeInfo.pipeId); + if (ret != 0) { + ZLOGW("Stop pipeInfo:%s ret:%d.", pipeInfo.pipeId.c_str(), ret); + return Status::ERROR; + } + dataBusMap_.erase(pipeInfo.pipeId); + return Status::SUCCESS; } bool AppPipeMgr::IsSameStartedOnPeer(const struct PipeInfo &pipeInfo, const struct DeviceId &peer) diff --git a/services/distributeddataservice/adapter/communicator/src/app_pipe_mgr.h b/services/distributeddataservice/adapter/communicator/src/app_pipe_mgr.h index 5bca39c888170bdd4b91776b7e4bb6f62a544d31..c942cd46690cfbdf900d1ff44219db110a5227b3 100755 --- a/services/distributeddataservice/adapter/communicator/src/app_pipe_mgr.h +++ b/services/distributeddataservice/adapter/communicator/src/app_pipe_mgr.h @@ -20,7 +20,6 @@ #include #include "app_data_change_listener.h" #include "app_pipe_handler.h" -#include "app_types.h" #include "data_buffer.h" #include "log_print.h" diff --git a/services/distributeddataservice/adapter/communicator/src/communication_provider_impl.cpp b/services/distributeddataservice/adapter/communicator/src/communication_provider_impl.cpp index 54d2fb31fa82a6600833d78a569c2dcde25b0dfa..f4d4c4deeb78da85ba16b9851fb41f928d38267e 100755 --- a/services/distributeddataservice/adapter/communicator/src/communication_provider_impl.cpp +++ b/services/distributeddataservice/adapter/communicator/src/communication_provider_impl.cpp @@ -38,13 +38,13 @@ Status CommunicationProviderImpl::Initialize() return Status::SUCCESS; } -Status CommunicationProviderImpl::StartWatchDeviceChange(const AppDeviceStatusChangeListener *observer, +Status CommunicationProviderImpl::StartWatchDeviceChange(const AppDeviceChangeListener *observer, const PipeInfo &pipeInfo) { return appDeviceHandler_.StartWatchDeviceChange(observer, pipeInfo); } -Status CommunicationProviderImpl::StopWatchDeviceChange(const AppDeviceStatusChangeListener *observer, +Status CommunicationProviderImpl::StopWatchDeviceChange(const AppDeviceChangeListener *observer, const PipeInfo &pipeInfo) { return appDeviceHandler_.StopWatchDeviceChange(observer, pipeInfo); diff --git a/services/distributeddataservice/adapter/communicator/src/communication_provider_impl.h b/services/distributeddataservice/adapter/communicator/src/communication_provider_impl.h index 4f1438334ca44d69fac07a18c01ec902461af49b..927d26328fe2149c6b850df5f172a5238e35c6f0 100755 --- a/services/distributeddataservice/adapter/communicator/src/communication_provider_impl.h +++ b/services/distributeddataservice/adapter/communicator/src/communication_provider_impl.h @@ -30,10 +30,10 @@ public: virtual ~CommunicationProviderImpl(); // add DeviceChangeListener to watch device change; - Status StartWatchDeviceChange(const AppDeviceStatusChangeListener *observer, const PipeInfo &pipeInfo) override; + Status StartWatchDeviceChange(const AppDeviceChangeListener *observer, const PipeInfo &pipeInfo) override; // stop watching device change; - Status StopWatchDeviceChange(const AppDeviceStatusChangeListener *observer, const PipeInfo &pipeInfo) override; + Status StopWatchDeviceChange(const AppDeviceChangeListener *observer, const PipeInfo &pipeInfo) override; // add DataChangeListener to watch data change; Status StartWatchDataChange(const AppDataChangeListener *observer, const PipeInfo &pipeInfo) override; diff --git a/services/distributeddataservice/adapter/communicator/src/softbus_adapter.h b/services/distributeddataservice/adapter/communicator/src/softbus_adapter.h index 409399585c5a45aeb7364351425c20674b4a6d39..a8ec66db28be9644cf68d65905054037d835e2d2 100755 --- a/services/distributeddataservice/adapter/communicator/src/softbus_adapter.h +++ b/services/distributeddataservice/adapter/communicator/src/softbus_adapter.h @@ -21,9 +21,9 @@ #include #include #include +#include #include "app_data_change_listener.h" -#include "app_device_status_change_listener.h" -#include "app_types.h" +#include "app_device_change_listener.h" #include "platform_specific.h" #include "session.h" #include "softbus_bus_center.h" @@ -80,9 +80,9 @@ public: void Init(); // add DeviceChangeListener to watch device change; - Status StartWatchDeviceChange(const AppDeviceStatusChangeListener *observer, const PipeInfo &pipeInfo); + Status StartWatchDeviceChange(const AppDeviceChangeListener *observer, const PipeInfo &pipeInfo); // stop DeviceChangeListener to watch device change; - Status StopWatchDeviceChange(const AppDeviceStatusChangeListener *observer, const PipeInfo &pipeInfo); + Status StopWatchDeviceChange(const AppDeviceChangeListener *observer, const PipeInfo &pipeInfo); void NotifyAll(const DeviceInfo &deviceInfo, const DeviceChangeType &type); DeviceInfo GetLocalDevice(); std::vector GetDeviceList() const; @@ -143,7 +143,7 @@ private: DeviceInfo localInfo_ {}; static std::shared_ptr instance_; std::mutex deviceChangeMutex_; - std::set listeners_ {}; + std::set listeners_ {}; std::mutex dataChangeMutex_ {}; std::map dataChangeListeners_ {}; std::mutex busSessionMutex_ {}; diff --git a/services/distributeddataservice/adapter/communicator/src/softbus_adapter_standard.cpp b/services/distributeddataservice/adapter/communicator/src/softbus_adapter_standard.cpp index e7969ce505b004cec08f6844335542fcc4859a5c..40839076c240cfb01bc118b6fb30e26215906d41 100755 --- a/services/distributeddataservice/adapter/communicator/src/softbus_adapter_standard.cpp +++ b/services/distributeddataservice/adapter/communicator/src/softbus_adapter_standard.cpp @@ -141,7 +141,7 @@ SoftBusAdapter::~SoftBusAdapter() void SoftBusAdapter::Init() { ZLOGI("begin"); - std::thread th = std::thread([&]() { + std::thread th = std::thread([this]() { auto communicator = std::make_shared(); auto retcom = DistributedDB::KvStoreDelegateManager::SetProcessCommunicator(communicator); ZLOGI("set communicator ret:%{public}d.", static_cast(retcom)); @@ -162,7 +162,7 @@ void SoftBusAdapter::Init() th.detach(); } -Status SoftBusAdapter::StartWatchDeviceChange(const AppDeviceStatusChangeListener *observer, +Status SoftBusAdapter::StartWatchDeviceChange(const AppDeviceChangeListener *observer, __attribute__((unused)) const PipeInfo &pipeInfo) { ZLOGI("begin"); @@ -180,7 +180,7 @@ Status SoftBusAdapter::StartWatchDeviceChange(const AppDeviceStatusChangeListene return Status::SUCCESS; } -Status SoftBusAdapter::StopWatchDeviceChange(const AppDeviceStatusChangeListener *observer, +Status SoftBusAdapter::StopWatchDeviceChange(const AppDeviceChangeListener *observer, __attribute__((unused)) const PipeInfo &pipeInfo) { ZLOGI("begin"); @@ -200,7 +200,7 @@ Status SoftBusAdapter::StopWatchDeviceChange(const AppDeviceStatusChangeListener void SoftBusAdapter::NotifyAll(const DeviceInfo &deviceInfo, const DeviceChangeType &type) { std::thread th = std::thread([this, deviceInfo, type]() { - std::vector listeners; + std::vector listeners; { std::lock_guard lock(deviceChangeMutex_); for (const auto &listener : listeners_) { @@ -507,13 +507,13 @@ Status SoftBusAdapter::SendData(const PipeInfo &pipeInfo, const DeviceId &device if (sessionId < 0) { ZLOGW("OpenSession %{public}s, type:%{public}d failed, sessionId:%{public}d", pipeInfo.pipeId.c_str(), info.msgType, sessionId); - return Status::CREATE_SESSION_ERROR; + return Status::NETWORK_ERROR; } int state = GetSessionStatus(sessionId); ZLOGD("waited for notification, state:%{public}d", state); if (state != SOFTBUS_OK) { ZLOGE("OpenSession callback result error"); - return Status::CREATE_SESSION_ERROR; + return Status::NETWORK_ERROR; } ZLOGD("[SendBytes] start,sessionId is %{public}d, size is %{public}d, session type is %{public}d.", sessionId, size, attr.dataType); diff --git a/services/distributeddataservice/adapter/communicator/test/BUILD.gn b/services/distributeddataservice/adapter/communicator/test/BUILD.gn index 448e992298d75fd0f47fc4943ce4fe3c30c62aa1..c65c8e87cc5e774e7f51e5ed339aebc6b9032165 100755 --- a/services/distributeddataservice/adapter/communicator/test/BUILD.gn +++ b/services/distributeddataservice/adapter/communicator/test/BUILD.gn @@ -25,7 +25,7 @@ ohos_unittest("CommunicationProviderTest") { "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/include/autils", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/include/communicator", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/include/dfx", - "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/app_distributeddata/include", + "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata/include", "../src", ] external_deps = [ @@ -47,7 +47,7 @@ config("module_comm_config") { "./unittest/communicator", "./unittest/communicator/include", "//utils/native/base/include", - "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/app_distributeddata/include", + "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata/include", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/include/communicator", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/include/dfx", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/include/log", diff --git a/services/distributeddataservice/adapter/communicator/test/unittest/communication_provider_impl_test.cpp b/services/distributeddataservice/adapter/communicator/test/unittest/communication_provider_impl_test.cpp index ba16334db5a6c92073ef92d73f3ca6349f101df5..a098c5d7cd0e24148c704da5e997bc507a1c722f 100755 --- a/services/distributeddataservice/adapter/communicator/test/unittest/communication_provider_impl_test.cpp +++ b/services/distributeddataservice/adapter/communicator/test/unittest/communication_provider_impl_test.cpp @@ -20,12 +20,9 @@ #include #include #include -#include "app_types.h" -#include "app_device_status_change_listener.h" +#include "app_device_change_listener.h" #include "communication_provider.h" #include "log_print.h" -#include "app_device_handler.h" - using namespace std; using namespace testing::ext; using namespace OHOS::AppDistributedKv; @@ -42,7 +39,7 @@ void AppDataChangeListenerImpl::OnMessage(const OHOS::AppDistributedKv::DeviceIn ZLOGI("data %{public}s %s", info.deviceName.c_str(), ptr); } -class AppDeviceStatusChangeListenerImpl : public AppDeviceStatusChangeListener { +class AppDeviceStatusChangeListenerImpl : public AppDeviceChangeListener { public: void OnDeviceChanged(const OHOS::AppDistributedKv::DeviceInfo &info, const DeviceChangeType &type) const override; @@ -136,9 +133,7 @@ HWTEST_F(CommunicationProviderImplTest, CommunicationProvider006, TestSize.Level ZLOGD("GetDeviceList size: %zu", devices.size()); ASSERT_GE(devices.size(), val); for (const auto &device : devices) { - ZLOGD("GetDeviceList id: %s, name:%s, type:%s", - AppDeviceHandler::ToBeAnonymous(device.deviceId).c_str(), - device.deviceName.c_str(), device.deviceType.c_str()); + ZLOGD("GetDeviceList, name:%s, type:%s", device.deviceName.c_str(), device.deviceType.c_str()); } sleep(1); // avoid thread dnet thread died, then will have pthread; } @@ -156,9 +151,7 @@ HWTEST_F(CommunicationProviderImplTest, CommunicationProvider007, TestSize.Level auto device = CommunicationProvider::GetInstance().GetLocalDevice(); const unsigned long val = 0; ASSERT_GE(device.deviceName.length(), val); - ZLOGD("GetLocalDevice id: %s, name:%s, type:%s", - AppDeviceHandler::ToBeAnonymous(device.deviceId).c_str(), - device.deviceName.c_str(), device.deviceType.c_str()); + ZLOGD("GetLocalDevice, name:%s, type:%s", device.deviceName.c_str(), device.deviceType.c_str()); sleep(1); // avoid thread dnet thread died, then will have pthread; } diff --git a/services/distributeddataservice/adapter/dfx/BUILD.gn b/services/distributeddataservice/adapter/dfx/BUILD.gn index 16dc7d4440d4fa8fdf18fd5fc7140fc3c42f5d04..56a9b999d49db7600c18c65ff8c104bd20be9e12 100755 --- a/services/distributeddataservice/adapter/dfx/BUILD.gn +++ b/services/distributeddataservice/adapter/dfx/BUILD.gn @@ -35,6 +35,7 @@ ohos_static_library("distributeddata_dfx_static") { "../include/log", "../include/autils", "//utils/native/base/include", + "//foundation/distributeddatamgr/distributeddatamgr/frameworks/common", "//third_party/openssl/include/", ] diff --git a/services/distributeddataservice/adapter/include/account/account_delegate.h b/services/distributeddataservice/adapter/include/account/account_delegate.h index e3e17b339f965bd637304e22b502856674bf4d10..8fd49ac9f8c05646c9c13827e0321b98258a2e77 100755 --- a/services/distributeddataservice/adapter/include/account/account_delegate.h +++ b/services/distributeddataservice/adapter/include/account/account_delegate.h @@ -54,7 +54,6 @@ public: KVSTORE_API virtual std::string GetDeviceAccountIdByUID(int32_t uid) const = 0; KVSTORE_API virtual void SubscribeAccountEvent() = 0; KVSTORE_API static AccountDelegate *GetInstance(); - private: using BaseInstance = AccountDelegate *(*)(); static BaseInstance getInstance_; diff --git a/services/distributeddataservice/adapter/include/communicator/app_data_change_listener.h b/services/distributeddataservice/adapter/include/communicator/app_data_change_listener.h index b9c261bc6e8ae67bd370ea92f4444cff12f0411c..2d4090297188f64df9dc4fde1607956047976995 100644 --- a/services/distributeddataservice/adapter/include/communicator/app_data_change_listener.h +++ b/services/distributeddataservice/adapter/include/communicator/app_data_change_listener.h @@ -16,17 +16,16 @@ #ifndef APP_DISTRIBUTEDDATA_INCLUDE_DATA_CHANGE_LISTENER_H #define APP_DISTRIBUTEDDATA_INCLUDE_DATA_CHANGE_LISTENER_H -#include "app_types.h" -#include "visibility.h" +#include "commu_types.h" namespace OHOS { namespace AppDistributedKv { class AppDataChangeListener { public: - KVSTORE_API AppDataChangeListener() = default; - KVSTORE_API virtual ~AppDataChangeListener() {}; + API_EXPORT AppDataChangeListener() = default; + API_EXPORT virtual ~AppDataChangeListener() {}; - KVSTORE_API virtual void OnMessage(const DeviceInfo &info, const uint8_t *ptr, const int size, - const PipeInfo &pipeInfo) const = 0; + API_EXPORT virtual void OnMessage(const DeviceInfo &info, const uint8_t *ptr, const int size, + const PipeInfo &pipeInfo) const = 0; }; } // namespace AppDistributedKv } // namespace OHOS diff --git a/interfaces/innerkits/app_distributeddata/include/app_device_status_change_listener.h b/services/distributeddataservice/adapter/include/communicator/app_device_change_listener.h old mode 100755 new mode 100644 similarity index 76% rename from interfaces/innerkits/app_distributeddata/include/app_device_status_change_listener.h rename to services/distributeddataservice/adapter/include/communicator/app_device_change_listener.h index 83e65db7784ea86a0e37abbe286e163015b821ac..3b928e8bc5752b1a1454e0ade0606216449a6fc8 --- a/interfaces/innerkits/app_distributeddata/include/app_device_status_change_listener.h +++ b/services/distributeddataservice/adapter/include/communicator/app_device_change_listener.h @@ -16,8 +16,7 @@ #ifndef APP_DEVICE_STATUS_CHANGE_LISTENER_H #define APP_DEVICE_STATUS_CHANGE_LISTENER_H -#include "app_types.h" - +#include "commu_types.h" namespace OHOS { namespace AppDistributedKv { enum class ChangeLevelType { @@ -25,11 +24,11 @@ enum class ChangeLevelType { LOW, MIN, }; -class AppDeviceStatusChangeListener { +class AppDeviceChangeListener { public: - KVSTORE_API virtual ~AppDeviceStatusChangeListener() {}; - KVSTORE_API virtual void OnDeviceChanged(const DeviceInfo &info, const DeviceChangeType &type) const = 0; - KVSTORE_API virtual ChangeLevelType GetChangeLevelType() const + API_EXPORT virtual ~AppDeviceChangeListener() {}; + API_EXPORT virtual void OnDeviceChanged(const DeviceInfo &info, const DeviceChangeType &type) const = 0; + API_EXPORT virtual ChangeLevelType GetChangeLevelType() const { return ChangeLevelType::LOW; } diff --git a/services/distributeddataservice/adapter/include/autils/visibility.h b/services/distributeddataservice/adapter/include/communicator/commu_types.h similarity index 40% rename from services/distributeddataservice/adapter/include/autils/visibility.h rename to services/distributeddataservice/adapter/include/communicator/commu_types.h index 92575c65d55c0d45304ab15d8c55afd8ef30bf84..490b4d1c49709755b47a7dcad03230a78011c985 100644 --- a/services/distributeddataservice/adapter/include/autils/visibility.h +++ b/services/distributeddataservice/adapter/include/communicator/commu_types.h @@ -12,12 +12,46 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#ifndef DISTRIBUTEDDATAMGR_AUTILS_VISIBILITY_H -#define DISTRIBUTEDDATAMGR_AUTILS_VISIBILITY_H -#ifndef API_EXPORT -#define API_EXPORT __attribute__((visibility("default"))) -#endif -#ifndef KVSTORE_API -#define KVSTORE_API API_EXPORT -#endif -#endif // DISTRIBUTEDDATAMGR_AUTILS_VISIBILITY_H \ No newline at end of file + +#ifndef OHOS_DISTRIBUTED_DATA_ADAPTER_COMMUNICATOR_COMMU_TYPES_H +#define OHOS_DISTRIBUTED_DATA_ADAPTER_COMMUNICATOR_COMMU_TYPES_H +#include +#include "store_errno.h" +#include "visibility.h" +namespace OHOS::AppDistributedKv { +using Status = DistributedKv::Status; +struct API_EXPORT DeviceInfo { + std::string deviceId; + std::string deviceName; + std::string deviceType; +}; + +struct API_EXPORT PipeInfo { + std::string pipeId; + std::string userId; +}; + +struct API_EXPORT DeviceId { + std::string deviceId; +}; + +enum class API_EXPORT MessageType { + DEFAULT = 0, + FILE = 1, +}; + +struct API_EXPORT MessageInfo { + MessageType msgType; +}; + +enum class API_EXPORT DeviceChangeType { + DEVICE_OFFLINE = 0, + DEVICE_ONLINE = 1, +}; + +enum class API_EXPORT DeviceStatus { + OFFLINE = 0, + ONLINE = 1, +}; +} +#endif // OHOS_DISTRIBUTED_DATA_ADAPTER_COMMUNICATOR_COMMU_TYPES_H diff --git a/services/distributeddataservice/adapter/include/communicator/communication_provider.h b/services/distributeddataservice/adapter/include/communicator/communication_provider.h index 3422a7a42ada64b0e9c35afb3c1860f19b5abe5e..3cd623a96f1a4c6fc5c8db5c797587e02bd7b6bc 100644 --- a/services/distributeddataservice/adapter/include/communicator/communication_provider.h +++ b/services/distributeddataservice/adapter/include/communicator/communication_provider.h @@ -19,68 +19,61 @@ #include #include #include "app_data_change_listener.h" -#include "app_device_status_change_listener.h" -#include "app_types.h" +#include "app_device_change_listener.h" #include "idevice_query.h" -#include "visibility.h" namespace OHOS { namespace AppDistributedKv { class CommunicationProvider { public: // constructor - KVSTORE_API CommunicationProvider() {}; + API_EXPORT CommunicationProvider() {}; // destructor - KVSTORE_API virtual ~CommunicationProvider() {}; + API_EXPORT virtual ~CommunicationProvider() {}; + + // user should use this method to get instance of CommunicationProvider; + API_EXPORT static CommunicationProvider &GetInstance(); + + API_EXPORT static std::shared_ptr MakeCommunicationProvider(); // add DeviceChangeListener to watch device change - KVSTORE_API - virtual Status StartWatchDeviceChange(const AppDeviceStatusChangeListener *observer, const PipeInfo &pipeInfo) = 0; + virtual Status StartWatchDeviceChange(const AppDeviceChangeListener *observer, const PipeInfo &pipeInfo) = 0; // stop DeviceChangeListener to watch device change - KVSTORE_API - virtual Status StopWatchDeviceChange(const AppDeviceStatusChangeListener *observer, const PipeInfo &pipeInfo) = 0; + virtual Status StopWatchDeviceChange(const AppDeviceChangeListener *observer, const PipeInfo &pipeInfo) = 0; // add DataChangeListener to watch data change - KVSTORE_API virtual Status StartWatchDataChange(const AppDataChangeListener *observer, const PipeInfo &pipeInfo) = 0; // stop DataChangeListener to watch data change - KVSTORE_API virtual Status StopWatchDataChange(const AppDataChangeListener *observer, const PipeInfo &pipeInfo) = 0; + virtual Status StopWatchDataChange(const AppDataChangeListener *observer, const PipeInfo &pipeInfo) = 0; // Send data to other device, function will be called back after sent to notify send result - KVSTORE_API virtual Status SendData(const PipeInfo &pipeInfo, const DeviceId &deviceId, const uint8_t *ptr, int size, const MessageInfo &info = {MessageType::DEFAULT}) = 0; // Get online deviceList - KVSTORE_API virtual std::vector GetDeviceList() const = 0; + virtual std::vector GetDeviceList() const = 0; // Get local device information - KVSTORE_API virtual DeviceInfo GetLocalDevice() const = 0; + virtual DeviceInfo GetLocalDevice() const = 0; // start one server to listen data from other devices; - KVSTORE_API virtual Status Start(const PipeInfo &pipeInfo) = 0; + virtual Status Start(const PipeInfo &pipeInfo) = 0; // stop server - KVSTORE_API virtual Status Stop(const PipeInfo &pipeInfo) = 0; - - // user should use this method to get instance of CommunicationProvider; - KVSTORE_API static CommunicationProvider &GetInstance(); - - KVSTORE_API static std::shared_ptr MakeCommunicationProvider(); + virtual Status Stop(const PipeInfo &pipeInfo) = 0; // check peer device pipeInfo Process - KVSTORE_API virtual bool IsSameStartedOnPeer(const PipeInfo &pipeInfo, const DeviceId &peer) const = 0; - - KVSTORE_API virtual void SetDeviceQuery(std::shared_ptr deviceQuery) = 0; - KVSTORE_API virtual std::string GetUuidByNodeId(const std::string &nodeId) const = 0; - KVSTORE_API virtual std::string GetUdidByNodeId(const std::string &nodeId) const = 0; - KVSTORE_API virtual DeviceInfo GetLocalBasicInfo() const = 0; - KVSTORE_API virtual std::vector GetRemoteNodesBasicInfo() const = 0; - KVSTORE_API virtual std::string ToNodeId(const std::string &id) const = 0; - - KVSTORE_API virtual void SetMessageTransFlag(const PipeInfo &pipeInfo, bool flag) = 0; + virtual bool IsSameStartedOnPeer(const PipeInfo &pipeInfo, const DeviceId &peer) const = 0; + + virtual void SetDeviceQuery(std::shared_ptr deviceQuery) = 0; + virtual std::string GetUuidByNodeId(const std::string &nodeId) const = 0; + virtual std::string GetUdidByNodeId(const std::string &nodeId) const = 0; + virtual DeviceInfo GetLocalBasicInfo() const = 0; + virtual std::vector GetRemoteNodesBasicInfo() const = 0; + virtual std::string ToNodeId(const std::string &id) const = 0; + virtual void SetMessageTransFlag(const PipeInfo &pipeInfo, bool flag) = 0; }; } // namespace AppDistributedKv } // namespace OHOS diff --git a/services/distributeddataservice/adapter/include/communicator/idevice_query.h b/services/distributeddataservice/adapter/include/communicator/idevice_query.h index 118f818456ca47ec28c29df55e0423cd0a53810c..d7170e6c91aa67fd8281c3f3f808824cdffe3684 100644 --- a/services/distributeddataservice/adapter/include/communicator/idevice_query.h +++ b/services/distributeddataservice/adapter/include/communicator/idevice_query.h @@ -16,19 +16,18 @@ #ifndef IDEVICE_QUERY_H #define IDEVICE_QUERY_H -#include "app_types.h" -#include "visibility.h" +#include "commu_types.h" namespace OHOS { namespace AppDistributedKv { class IDeviceQuery { public: - KVSTORE_API virtual ~IDeviceQuery() {}; + API_EXPORT virtual ~IDeviceQuery() {}; // Get online deviceList - KVSTORE_API virtual std::vector GetDeviceList() const = 0; + virtual std::vector GetDeviceList() const = 0; // Get local device information - KVSTORE_API virtual DeviceInfo GetLocalDevice() const = 0; + virtual DeviceInfo GetLocalDevice() const = 0; }; } // namespace AppDistributedKv } // namespace OHOS diff --git a/services/distributeddataservice/adapter/include/communicator/process_communicator_impl.h b/services/distributeddataservice/adapter/include/communicator/process_communicator_impl.h index c56b1c1af9d292fb00425365f00a2fac90a67b24..3dc040a2aac5b682313350623a1af7b60fff5969 100755 --- a/services/distributeddataservice/adapter/include/communicator/process_communicator_impl.h +++ b/services/distributeddataservice/adapter/include/communicator/process_communicator_impl.h @@ -24,9 +24,8 @@ namespace OHOS { namespace AppDistributedKv { -class ProcessCommunicatorImpl : public DistributedDB::IProcessCommunicator, - private AppDataChangeListener, - private AppDeviceStatusChangeListener { +class API_EXPORT ProcessCommunicatorImpl : public DistributedDB::IProcessCommunicator, public AppDataChangeListener, + public AppDeviceChangeListener { public: using DBStatus = DistributedDB::DBStatus; using OnDeviceChange = DistributedDB::OnDeviceChange; @@ -35,23 +34,23 @@ public: using RouteHeadHandlerCreator = std::function(const DistributedDB::ExtendInfo &info)>; - KVSTORE_API ProcessCommunicatorImpl(); - KVSTORE_API explicit ProcessCommunicatorImpl(RouteHeadHandlerCreator handlerCreator); - KVSTORE_API ~ProcessCommunicatorImpl() override; + API_EXPORT ProcessCommunicatorImpl(); + API_EXPORT explicit ProcessCommunicatorImpl(RouteHeadHandlerCreator handlerCreator); + API_EXPORT ~ProcessCommunicatorImpl() override; - KVSTORE_API DBStatus Start(const std::string &processLabel) override; - KVSTORE_API DBStatus Stop() override; + DBStatus Start(const std::string &processLabel) override; + DBStatus Stop() override; - KVSTORE_API DBStatus RegOnDeviceChange(const OnDeviceChange &callback) override; - KVSTORE_API DBStatus RegOnDataReceive(const OnDataReceive &callback) override; - - KVSTORE_API DBStatus SendData(const DeviceInfos &dstDevInfo, const uint8_t *data, uint32_t length) override; - KVSTORE_API uint32_t GetMtuSize() override; - KVSTORE_API uint32_t GetMtuSize(const DeviceInfos &devInfo) override; - KVSTORE_API DeviceInfos GetLocalDeviceInfos() override; - KVSTORE_API std::vector GetRemoteOnlineDeviceInfosList() override; - KVSTORE_API bool IsSameProcessLabelStartedOnPeerDevice(const DeviceInfos &peerDevInfo) override; + DBStatus RegOnDeviceChange(const OnDeviceChange &callback) override; + DBStatus RegOnDataReceive(const OnDataReceive &callback) override; + DBStatus SendData(const DeviceInfos &dstDevInfo, const uint8_t *data, uint32_t length) override; + uint32_t GetMtuSize() override; + uint32_t GetMtuSize(const DeviceInfos &devInfo) override; + DeviceInfos GetLocalDeviceInfos() override; + std::vector GetRemoteOnlineDeviceInfosList() override; + bool IsSameProcessLabelStartedOnPeerDevice(const DeviceInfos &peerDevInfo) override; + void OnDeviceChanged(const DeviceInfo &info, const DeviceChangeType &type) const override; API_EXPORT std::shared_ptr GetExtendHeaderHandle( const DistributedDB::ExtendInfo &info) override; API_EXPORT DBStatus CheckAndGetDataHeadInfo( @@ -60,7 +59,6 @@ public: private: void OnMessage(const DeviceInfo &info, const uint8_t *ptr, const int size, const PipeInfo &pipeInfo) const override; - void OnDeviceChanged(const DeviceInfo &info, const DeviceChangeType &type) const override; std::string thisProcessLabel_; OnDeviceChange onDeviceChangeHandler_; diff --git a/services/distributeddataservice/adapter/include/dfx/visibility.h b/services/distributeddataservice/adapter/include/dfx/visibility.h deleted file mode 100644 index b58fa139ad40ec8781ded4af32fb2bb7a691fb78..0000000000000000000000000000000000000000 --- a/services/distributeddataservice/adapter/include/dfx/visibility.h +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef DISTRIBUTEDDATAMGR_DFX_VISIBILITY_H -#define DISTRIBUTEDDATAMGR_DFX_VISIBILITY_H -#ifndef API_EXPORT -#define API_EXPORT __attribute__((visibility("default"))) -#endif -#ifndef KVSTORE_API -#define KVSTORE_API API_EXPORT -#endif -#endif // DISTRIBUTEDDATAMGR_DFX_VISIBILITY_H \ No newline at end of file diff --git a/services/distributeddataservice/adapter/include/log/visibility.h b/services/distributeddataservice/adapter/include/log/visibility.h deleted file mode 100644 index 49ddb4b2bbb4db865cf1d8bab12746dc50ee7e46..0000000000000000000000000000000000000000 --- a/services/distributeddataservice/adapter/include/log/visibility.h +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef DISTRIBUTEDDATAMGR_LOG_VISIBILITY_H -#define DISTRIBUTEDDATAMGR_LOG_VISIBILITY_H -#ifndef API_EXPORT -#define API_EXPORT __attribute__((visibility("default"))) -#endif -#ifndef KVSTORE_API -#define KVSTORE_API API_EXPORT -#endif -#endif // DISTRIBUTEDDATAMGR_LOG_VISIBILITY_H diff --git a/services/distributeddataservice/adapter/include/permission/visibility.h b/services/distributeddataservice/adapter/include/permission/visibility.h deleted file mode 100644 index ffe1d65f113cb04ffc8ffeec97b0657f9f330647..0000000000000000000000000000000000000000 --- a/services/distributeddataservice/adapter/include/permission/visibility.h +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef PERMISSION_VISIBILITY_H -#define PERMISSION_VISIBILITY_H -#ifndef API_EXPORT -#define API_EXPORT __attribute__((visibility ("default"))) -#endif -#ifndef KVSTORE_API -#define KVSTORE_API API_EXPORT -#endif -#endif \ No newline at end of file diff --git a/services/distributeddataservice/adapter/permission/BUILD.gn b/services/distributeddataservice/adapter/permission/BUILD.gn index 8cec1dd1d66ff86ce10aa1beb68d0cd01dc8b794..dc945366862bd9c885327cbb2bf47d8ba61193f2 100755 --- a/services/distributeddataservice/adapter/permission/BUILD.gn +++ b/services/distributeddataservice/adapter/permission/BUILD.gn @@ -27,7 +27,6 @@ ohos_static_library("distributeddata_permission_static") { "//utils/native/base/include", "//foundation/distributeddatamgr/distributeddatamgr/frameworks/common", "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata/include", - "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/app_distributeddata/include", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/framework/include", ] diff --git a/services/distributeddataservice/adapter/utils/BUILD.gn b/services/distributeddataservice/adapter/utils/BUILD.gn index 2b132c9055e5a0646586a50de53b9a24fa5621cd..bcfd6130dbe0d64a5ab660e46e8cad773c3308fb 100755 --- a/services/distributeddataservice/adapter/utils/BUILD.gn +++ b/services/distributeddataservice/adapter/utils/BUILD.gn @@ -26,9 +26,9 @@ ohos_static_library("distributeddata_utils_static") { "../include/utils", "../include/log", "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata/include", - "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/app_distributeddata/include", "//utils/native/base/include", "../include/dfx", + "//foundation/distributeddatamgr/distributeddatamgr/frameworks/common", ] ldflags = [ "-Wl,--exclude-libs,ALL" ] deps = [ diff --git a/services/distributeddataservice/app/BUILD.gn b/services/distributeddataservice/app/BUILD.gn index bf1bfc8a58de8d03529b40dd57cdcd9e04e83de5..39c34668e99953580f3107188cfa41f198dc1f5c 100755 --- a/services/distributeddataservice/app/BUILD.gn +++ b/services/distributeddataservice/app/BUILD.gn @@ -38,7 +38,6 @@ config("module_private_config") { include_dirs = [ "//foundation/distributeddatamgr/distributeddatamgr/frameworks/common", "//foundation/distributeddatamgr/distributeddatamgr/frameworks/innerkitsimpl/distributeddatafwk/include", - "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/app_distributeddata/include", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/service/bootstrap/include", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/service/config/include", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/service/directory/include", @@ -47,8 +46,7 @@ config("module_private_config") { "//foundation/distributeddatamgr/distributeddatamgr/frameworks/innerkitsimpl/rdb/include", "//foundation/distributeddatamgr/distributeddatamgr/frameworks/innerkitsimpl/rdb/src", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/service/rdb", - "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/service/kv", - "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/app_distributeddata/include", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/service/kvdb", "//foundation/distributeddatamgr/distributedfile/interfaces/kits/js/src/mod_securitylabel", "//utils/system/safwk/native/include", "../adapter/include/account", @@ -80,7 +78,6 @@ ohos_shared_library("distributeddataservice") { "src/device_kvstore_impl.cpp", "src/device_kvstore_observer_impl.cpp", "src/device_kvstore_resultset_impl.cpp", - "src/executor_factory.cpp", "src/kvstore_account_observer.cpp", "src/kvstore_app_accessor.cpp", "src/kvstore_app_manager.cpp", @@ -109,7 +106,7 @@ ohos_shared_library("distributeddataservice") { "../service/rdb/rdb_syncer.cpp", ] - kv_sources = [ "../service/kv/user_delegate.cpp" ] + kv_sources = [ "../service/kvdb/user_delegate.cpp", "../service/kvdb/executor_factory.cpp" ] sources += kv_sources sources += rdb_sources diff --git a/services/distributeddataservice/app/src/device_change_listener_impl.h b/services/distributeddataservice/app/src/device_change_listener_impl.h index 0e56b6dca39dfd1df9ddb3ef93c340db0c693b4e..4b27f2e9e29edb931456610c6a1dc2715a8abe0c 100755 --- a/services/distributeddataservice/app/src/device_change_listener_impl.h +++ b/services/distributeddataservice/app/src/device_change_listener_impl.h @@ -17,11 +17,11 @@ #define DEV_DEVICE_CHANGE_LISTENER_IMPL_H #include -#include "app_device_status_change_listener.h" +#include "app_device_change_listener.h" #include "idevice_status_change_listener.h" namespace OHOS::DistributedKv { -class DeviceChangeListenerImpl : public AppDistributedKv::AppDeviceStatusChangeListener { +class DeviceChangeListenerImpl : public AppDistributedKv::AppDeviceChangeListener { public: explicit DeviceChangeListenerImpl(std::map> &observers); diff --git a/services/distributeddataservice/app/src/flowctrl_manager/BUILD.gn b/services/distributeddataservice/app/src/flowctrl_manager/BUILD.gn index d760897529d0335bca678383e535600568352053..d541f18863ac9196b43ebd7dc29db9abe791a8e7 100755 --- a/services/distributeddataservice/app/src/flowctrl_manager/BUILD.gn +++ b/services/distributeddataservice/app/src/flowctrl_manager/BUILD.gn @@ -21,7 +21,6 @@ ohos_static_library("distributeddata_flowctrl_static") { "../../src", "//foundation/distributeddatamgr/distributeddatamgr/frameworks/innerkitsimpl/distributeddatafwk/include", "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata/include", - "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/app_distributeddata/include", "//third_party/json/single_include", "//utils/native/base/include", ] diff --git a/services/distributeddataservice/app/src/kvstore_app_manager.cpp b/services/distributeddataservice/app/src/kvstore_app_manager.cpp index 69c8cbbd3b404d7c9c81db6d2a8f15500e92d242..e9b5a2963e6cbf3a741a87c310350673062eabe9 100755 --- a/services/distributeddataservice/app/src/kvstore_app_manager.cpp +++ b/services/distributeddataservice/app/src/kvstore_app_manager.cpp @@ -21,7 +21,6 @@ #include #include #include - #include #include "account_delegate.h" diff --git a/services/distributeddataservice/app/src/kvstore_data_service.h b/services/distributeddataservice/app/src/kvstore_data_service.h index f83c57944823140878cb78134917647e17be00d1..d5b5e9f22dd25fa0cf1442916db83aed195f177a 100755 --- a/services/distributeddataservice/app/src/kvstore_data_service.h +++ b/services/distributeddataservice/app/src/kvstore_data_service.h @@ -41,9 +41,7 @@ class RdbServiceImpl; namespace OHOS::DistributedKv { class KvStoreAccountObserver; -class KvStoreDataService - : public SystemAbility - , public KvStoreDataServiceStub { +class KvStoreDataService : public SystemAbility, public KvStoreDataServiceStub { DECLARE_SYSTEM_ABILITY(KvStoreDataService); public: diff --git a/services/distributeddataservice/app/src/kvstore_device_listener.h b/services/distributeddataservice/app/src/kvstore_device_listener.h index 2c1eee2b3c2fac9afb497c6997ca104536338b79..e4ed6f224fbd01d39dc7a2c1796b60c86ad936cc 100644 --- a/services/distributeddataservice/app/src/kvstore_device_listener.h +++ b/services/distributeddataservice/app/src/kvstore_device_listener.h @@ -15,12 +15,12 @@ #ifndef DISTRIBUTEDDATAMGR_KVSTORE_DEVICE_LISTENER_H #define DISTRIBUTEDDATAMGR_KVSTORE_DEVICE_LISTENER_H -#include "app_device_status_change_listener.h" +#include "app_device_change_listener.h" namespace OHOS::DistributedKv { -using AppDeviceStatusChangeListener = AppDistributedKv::AppDeviceStatusChangeListener; +using AppDeviceChangeListener = AppDistributedKv::AppDeviceChangeListener; class KvStoreDataService; -class KvStoreDeviceListener : public AppDeviceStatusChangeListener { +class KvStoreDeviceListener : public AppDeviceChangeListener { public: explicit KvStoreDeviceListener(KvStoreDataService &kvStoreDataService); void OnDeviceChanged( diff --git a/services/distributeddataservice/app/src/kvstore_meta_manager.cpp b/services/distributeddataservice/app/src/kvstore_meta_manager.cpp index 92113fcebd95a4f29bdf57f07d132ad82c85f716..d7329cf21b20578c376ad61148bbb3920f2f38ce 100755 --- a/services/distributeddataservice/app/src/kvstore_meta_manager.cpp +++ b/services/distributeddataservice/app/src/kvstore_meta_manager.cpp @@ -40,6 +40,8 @@ #include "rdb_types.h" #include "reporter.h" #include "serializable/serializable.h" +#include "bootstrap.h" +#include "metadata/meta_data_manager.h" #include "user_delegate.h" #include "utils/crypto.h" @@ -69,7 +71,8 @@ KvStoreMetaManager::KvStoreMetaManager() } }), metaDBDirectory_("/data/service/el1/public/database/distributeddata/meta"), - kvStoreDelegateManager_(META_DB_APP_ID, Constant::GetDefaultHarmonyAccountName()) + label_(Bootstrap::GetInstance().GetProcessLabel()), + kvStoreDelegateManager_(Bootstrap::GetInstance().GetProcessLabel(), Constant::GetDefaultHarmonyAccountName()) { ZLOGI("begin."); } @@ -112,11 +115,11 @@ void KvStoreMetaManager::InitMetaData() auto uid = getuid(); const std::string accountId = AccountDelegate::GetInstance()->GetCurrentAccountId(); const std::string userId = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(uid); - auto metaKey = GetMetaKey(userId, "default", META_DB_APP_ID, Constant::SERVICE_META_DB_NAME); + auto metaKey = GetMetaKey(userId, "default", label_, Constant::SERVICE_META_DB_NAME); struct KvStoreMetaData metaData { - .appId = META_DB_APP_ID, + .appId = label_, .appType = "default", - .bundleName = META_DB_APP_ID, + .bundleName = label_, .dataDir = metaDBDirectory_, .deviceAccountId = userId, .deviceId = DeviceKvStoreImpl::GetLocalDeviceId(), @@ -170,6 +173,7 @@ const KvStoreMetaManager::NbDelegate &KvStoreMetaManager::GetMetaKvStore() if (metaDelegate_ == nullptr) { metaDelegate_ = CreateMetaKvStore(); } + MetaDataManager::GetInstance().SetMetaStore(metaDelegate_); return metaDelegate_; } @@ -272,7 +276,7 @@ Status KvStoreMetaManager::CheckUpdateServiceMeta(const std::vector &me DistributedDB::Value dbValue = val; DistributedDB::DBStatus dbStatus; DistributedDB::CipherPassword dbPassword; - std::initializer_list backList = {META_DB_APP_ID, "_", Constant::SERVICE_META_DB_NAME}; + std::initializer_list backList = {label_, "_", Constant::SERVICE_META_DB_NAME}; std::string backupName = Constant::Concatenate(backList); std::initializer_list backFullList = {metaDBDirectory_, "/backup/", BackupHandler::GetHashedBackupName(backupName)}; diff --git a/services/distributeddataservice/app/src/kvstore_meta_manager.h b/services/distributeddataservice/app/src/kvstore_meta_manager.h index 20925958c362f50684a10577d002c6a195196613..98293b2e97e96606e024c4e57b972283f33d753d 100755 --- a/services/distributeddataservice/app/src/kvstore_meta_manager.h +++ b/services/distributeddataservice/app/src/kvstore_meta_manager.h @@ -18,7 +18,7 @@ #include #include -#include "app_device_status_change_listener.h" +#include "app_device_change_listener.h" #include "kv_store_delegate.h" #include "kv_store_delegate_manager.h" #include "kv_store_task.h" @@ -153,16 +153,14 @@ private: class KvStoreMetaManager { public: static constexpr uint32_t META_STORE_VERSION = 0x03000001; - static const inline std::string META_DB_APP_ID = "distributeddata"; enum DatabaseType { KVDB, RDB, }; - using NbDelegate = std::unique_ptr>; + using NbDelegate = std::shared_ptr; using ChangeObserver = std::function &, const std::vector &, CHANGE_FLAG)>; - class MetaDeviceChangeListenerImpl : public AppDistributedKv::AppDeviceStatusChangeListener { + class MetaDeviceChangeListenerImpl : public AppDistributedKv::AppDeviceChangeListener { void OnDeviceChanged(const AppDistributedKv::DeviceInfo &info, const AppDistributedKv::DeviceChangeType &type) const override; @@ -176,6 +174,7 @@ public: void InitMetaParameter(); void InitMetaListener(); void SubscribeMeta(const std::string &keyPrefix, const ChangeObserver &observer); + const NbDelegate &GetMetaKvStore(); Status CheckUpdateServiceMeta(const std::vector &metaKey, FLAG flag, const std::vector &val = {}); @@ -283,6 +282,7 @@ private: NbDelegate metaDelegate_; std::string metaDBDirectory_; + const std::string label_; DistributedDB::KvStoreDelegateManager kvStoreDelegateManager_; std::vector vecRootKeyAlias_ {}; std::vector vecNonce_ {}; diff --git a/services/distributeddataservice/app/src/kvstore_user_manager.cpp b/services/distributeddataservice/app/src/kvstore_user_manager.cpp index 0e472bc0c63b23c41c366aa145c208cccaadc99f..c4bc281c0d2cf11fde91590d4fd79165e17c4e8a 100755 --- a/services/distributeddataservice/app/src/kvstore_user_manager.cpp +++ b/services/distributeddataservice/app/src/kvstore_user_manager.cpp @@ -43,7 +43,7 @@ KvStoreUserManager::~KvStoreUserManager() Status KvStoreUserManager::CloseKvStore(const std::string &appId, const std::string &storeId) { ZLOGI("begin."); - std::lock_guard lg(appMutex_); + std::lock_guard lg(appMutex_); auto it = appMap_.find(appId); if (it != appMap_.end()) { return (it->second).CloseKvStore(storeId); @@ -56,7 +56,7 @@ Status KvStoreUserManager::CloseKvStore(const std::string &appId, const std::str Status KvStoreUserManager::CloseAllKvStore(const std::string &appId) { ZLOGI("begin."); - std::lock_guard lg(appMutex_); + std::lock_guard lg(appMutex_); auto it = appMap_.find(appId); if (it != appMap_.end()) { return (it->second).CloseAllKvStore(); @@ -69,7 +69,7 @@ Status KvStoreUserManager::CloseAllKvStore(const std::string &appId) void KvStoreUserManager::CloseAllKvStore() { ZLOGI("begin."); - std::lock_guard lg(appMutex_); + std::lock_guard lg(appMutex_); for (auto &it : appMap_) { (it.second).CloseAllKvStore(); } @@ -78,7 +78,7 @@ void KvStoreUserManager::CloseAllKvStore() Status KvStoreUserManager::DeleteKvStore(const std::string &bundleName, pid_t uid, const std::string &storeId) { ZLOGI("begin."); - std::lock_guard lg(appMutex_); + std::lock_guard lg(appMutex_); auto it = appMap_.find(bundleName); if (it != appMap_.end()) { auto status = (it->second).DeleteKvStore(storeId); @@ -95,7 +95,7 @@ Status KvStoreUserManager::DeleteKvStore(const std::string &bundleName, pid_t ui void KvStoreUserManager::DeleteAllKvStore() { ZLOGI("begin."); - std::lock_guard lg(appMutex_); + std::lock_guard lg(appMutex_); for (auto &it : appMap_) { (it.second).DeleteAllKvStore(); } @@ -106,7 +106,7 @@ void KvStoreUserManager::DeleteAllKvStore() Status KvStoreUserManager::MigrateAllKvStore(const std::string &harmonyAccountId) { ZLOGI("begin."); - std::lock_guard lg(appMutex_); + std::lock_guard lg(appMutex_); Status status = Status::SUCCESS; for (auto &it : appMap_) { status = (it.second).MigrateAllKvStore(harmonyAccountId); @@ -125,7 +125,7 @@ std::string KvStoreUserManager::GetDbDir(const std::string &bundleName, const Op if (options.kvStoreType == KvStoreType::MULTI_VERSION) { return "default"; } - std::lock_guard lg(appMutex_); + std::lock_guard lg(appMutex_); auto it = appMap_.find(bundleName); if (it != appMap_.end()) { return (it->second).GetDbDir(options); @@ -146,12 +146,14 @@ void KvStoreUserManager::Dump(int fd) const bool KvStoreUserManager::IsStoreOpened(const std::string &appId, const std::string &storeId) { + std::lock_guard lg(appMutex_); auto it = appMap_.find(appId); return it != appMap_.end() && it->second.IsStoreOpened(storeId); } void KvStoreUserManager::SetCompatibleIdentify(const std::string &deviceId) const { + std::lock_guard lg(appMutex_); for (const auto &item : appMap_) { item.second.SetCompatibleIdentify(deviceId); } diff --git a/services/distributeddataservice/app/src/kvstore_user_manager.h b/services/distributeddataservice/app/src/kvstore_user_manager.h index 184c9b9814032c58ba4b14b0f5b36fb153eb0da9..d83982c38573e950d8d3feb3044a6f3791246f51 100755 --- a/services/distributeddataservice/app/src/kvstore_user_manager.h +++ b/services/distributeddataservice/app/src/kvstore_user_manager.h @@ -34,7 +34,7 @@ public: Status GetKvStore(const Options &options, const std::string &bundleName, const std::string &storeId, pid_t uid, const std::vector &cipherKey, sptr &kvStore) { - std::lock_guard lg(appMutex_); + std::lock_guard lg(appMutex_); auto it = appMap_.find(bundleName); if (it == appMap_.end()) { auto result = appMap_.emplace( @@ -70,7 +70,7 @@ public: void SetCompatibleIdentify(const std::string &deviceId) const; private: - std::mutex appMutex_; + mutable std::recursive_mutex appMutex_; std::map appMap_; std::string userId_; }; diff --git a/services/distributeddataservice/app/src/security/security.cpp b/services/distributeddataservice/app/src/security/security.cpp index 3874ac43bf2d8dba5c1b735d58c5669aaa3f01d6..e2a9533ed53f9bfadc09bfee26662095b0965571 100644 --- a/services/distributeddataservice/app/src/security/security.cpp +++ b/services/distributeddataservice/app/src/security/security.cpp @@ -51,7 +51,7 @@ Security::~Security() DBStatus Security::RegOnAccessControlledEvent(const OnAccessControlledEvent &callback) { ZLOGD("add new lock status observer!"); - return NOT_SUPPORT; + return DBStatus::NOT_SUPPORT; } bool Security::IsAccessControlled() const @@ -165,7 +165,7 @@ Sensitive Security::GetSensitiveByUuid(const std::string &uuid) return true; } - auto &network = AppDistributedKv::CommunicationProvider::GetInstance(); + auto &network = AppDistributedKv::CommunicationProvider::GetInstance(); auto devices = network.GetRemoteNodesBasicInfo(); devices.push_back(network.GetLocalBasicInfo()); for (auto &device : devices) { @@ -202,7 +202,7 @@ int32_t Security::GetCurrentUserStatus() const DBStatus Security::SetFileSecurityOption(const std::string &filePath, const SecurityOption &option) { - ZLOGI("set security option %d", option.securityLabel); + ZLOGI("set security option %{public}d", option.securityLabel); if (!IsExits(filePath)) { return INVALID_ARGS; } @@ -211,15 +211,15 @@ DBStatus Security::SetFileSecurityOption(const std::string &filePath, const Secu } auto dataLevel = Convert2Name(option); if (dataLevel.empty()) { - ZLOGE("Invalid label args! label:%d, flag:%d path:%s", + ZLOGE("Invalid label args! label:%d, flag:%{public}d path:%{public}s", option.securityLabel, option.securityFlag, filePath.c_str()); return INVALID_ARGS; } bool result = OHOS::DistributedFS::ModuleSecurityLabel::SecurityLabel::SetSecurityLabel(filePath, dataLevel); if (!result) { - ZLOGE("set security label failed!, result:%d, datalevel:%s", result, dataLevel.c_str()); - return DB_ERROR; + ZLOGE("set security label failed!, result:%d, datalevel:%{public}s", result, dataLevel.c_str()); + return DBStatus::DB_ERROR; } return OK; @@ -228,7 +228,7 @@ DBStatus Security::SetFileSecurityOption(const std::string &filePath, const Secu DBStatus Security::SetDirSecurityOption(const std::string &filePath, const SecurityOption &option) { ZLOGI("the filePath is a directory!"); - return NOT_SUPPORT; + return DBStatus::NOT_SUPPORT; } DBStatus Security::GetFileSecurityOption(const std::string &filePath, SecurityOption &option) const @@ -243,7 +243,7 @@ DBStatus Security::GetFileSecurityOption(const std::string &filePath, SecurityOp option = {NOT_SET, ECE}; return OK; } - ZLOGI("get security option %s", value.c_str()); + ZLOGI("get security option %{public}s", value.c_str()); if (value == "s3") { option = { Convert2Security(value), SECE }; } else { @@ -255,6 +255,6 @@ DBStatus Security::GetFileSecurityOption(const std::string &filePath, SecurityOp DBStatus Security::GetDirSecurityOption(const std::string &filePath, SecurityOption &option) const { ZLOGI("the filePath is a directory!"); - return NOT_SUPPORT; + return DBStatus::NOT_SUPPORT; } } diff --git a/services/distributeddataservice/app/src/security/security.h b/services/distributeddataservice/app/src/security/security.h index b8b7b91789c8964f23ec5e5c905254f4a65d7763..d4bd606235332efb8bdb6fcdc66934f73d272753 100644 --- a/services/distributeddataservice/app/src/security/security.h +++ b/services/distributeddataservice/app/src/security/security.h @@ -20,14 +20,14 @@ #include #include "iprocess_system_api_adapter.h" #include "kv_store_delegate_manager.h" -#include "app_device_status_change_listener.h" +#include "app_device_change_listener.h" #include "visibility.h" #include "sensitive.h" namespace OHOS::DistributedKv { class Security : public DistributedDB::IProcessSystemApiAdapter, - public AppDistributedKv::AppDeviceStatusChangeListener { + public AppDistributedKv::AppDeviceChangeListener { public: using DBStatus = DistributedDB::DBStatus; using OnAccessControlledEvent = DistributedDB::OnAccessControlledEvent; diff --git a/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.cpp b/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.cpp index f763d20d34a47f6b3353ddac5bfa727bc3f798eb..3e487e412cc82d633acb33a8f360bb5b3ebe297f 100644 --- a/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.cpp +++ b/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.cpp @@ -22,6 +22,7 @@ #include "log_print.h" #include "securec.h" #include "upgrade_manager.h" +#include "bootstrap.h" namespace OHOS::DistributedData { using namespace OHOS::DistributedKv; @@ -59,7 +60,7 @@ DistributedDB::DBStatus RouteHeadHandlerImpl::GetHeadDataSize(uint32_t &headSize { ZLOGD("begin"); headSize = 0; - if (appId_ == DistributedKv::KvStoreMetaManager::META_DB_APP_ID) { + if (appId_ == Bootstrap::GetInstance().GetProcessLabel()) { ZLOGI("meta data permitted"); return DistributedDB::OK; } diff --git a/services/distributeddataservice/app/src/session_manager/upgrade_manager.h b/services/distributeddataservice/app/src/session_manager/upgrade_manager.h index 44c67c94a94cce80dcf3d645028501e133262c77..0a297b2379af91444f42e6b0450c5e158ac94f1e 100644 --- a/services/distributeddataservice/app/src/session_manager/upgrade_manager.h +++ b/services/distributeddataservice/app/src/session_manager/upgrade_manager.h @@ -16,6 +16,7 @@ #ifndef DISTRIBUTEDDATAMGR_UPGRADE_MANAGER_H #define DISTRIBUTEDDATAMGR_UPGRADE_MANAGER_H #include +#include #include "concurrent_map.h" #include "kvstore_meta_manager.h" diff --git a/services/distributeddataservice/app/src/single_kvstore_impl.h b/services/distributeddataservice/app/src/single_kvstore_impl.h index 76787224802d23fbfd21114cf69c91bc23a301c8..3348153f39e8e0ed6c6033b6c2d1bb8bf49275c1 100755 --- a/services/distributeddataservice/app/src/single_kvstore_impl.h +++ b/services/distributeddataservice/app/src/single_kvstore_impl.h @@ -20,8 +20,6 @@ #include #include #include - -#include "auth/auth_delegate.h" #include "flowctrl_manager/kvstore_flowctrl_manager.h" #include "ikvstore_observer.h" #include "ikvstore_single.h" diff --git a/services/distributeddataservice/app/src/uninstaller/BUILD.gn b/services/distributeddataservice/app/src/uninstaller/BUILD.gn index c053864f9afafcd285f63049bdc75d3fc5042de3..f802e7a0d93fe27e67866ab9ce4a59b95b891cca 100755 --- a/services/distributeddataservice/app/src/uninstaller/BUILD.gn +++ b/services/distributeddataservice/app/src/uninstaller/BUILD.gn @@ -24,7 +24,6 @@ ohos_static_library("distributeddata_uninstaller_static") { "../../src", "//foundation/distributeddatamgr/distributeddatamgr/frameworks/innerkitsimpl/distributeddatafwk/include", "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata/include", - "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/app_distributeddata/include", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/framework/include", "//third_party/json/single_include", "//utils/native/base/include", diff --git a/services/distributeddataservice/app/test/BUILD.gn b/services/distributeddataservice/app/test/BUILD.gn index 9e5e85048cc4e33492fdf7d5c8bd77f0e490e13a..33e969220f004ec3a452ada4db8aa308ae42a3f4 100755 --- a/services/distributeddataservice/app/test/BUILD.gn +++ b/services/distributeddataservice/app/test/BUILD.gn @@ -21,7 +21,7 @@ config("module_private_config") { "//foundation/distributeddatamgr/distributeddatamgr/frameworks/common", "//foundation/distributeddatamgr/distributeddatamgr/frameworks/innerkitsimpl/distributeddatafwk/include", "//foundation/distributeddatamgr/distributeddatamgr/frameworks/innerkitsimpl/distributeddatafwk/src", - "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/app_distributeddata/include", + "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata/include", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/include/permission", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/include/account", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/include", diff --git a/services/distributeddataservice/framework/BUILD.gn b/services/distributeddataservice/framework/BUILD.gn index fcffaf669e9f7d74e8d4467be99c078081c8483d..a5414835dcdd702cf202ee4898cd6bc57a5b2fa0 100644 --- a/services/distributeddataservice/framework/BUILD.gn +++ b/services/distributeddataservice/framework/BUILD.gn @@ -25,6 +25,9 @@ config("module_public_config") { "//foundation/distributeddatamgr/distributeddatamgr/frameworks/common", "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata/include", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/include", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/libs/distributeddb/include", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/libs/distributeddb/interfaces/include", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/libs/distributeddb/interfaces/include/relational", ] } @@ -41,6 +44,7 @@ ohos_shared_library("distributeddatasvcfwk") { "metadata/store_meta_data.cpp", "metadata/strategy_meta_data.cpp", "metadata/user_meta_data.cpp", + "metadata/meta_data_manager.cpp", "serializable/serializable.cpp", "utils/anonymous.cpp", "utils/block_integer.cpp", diff --git a/services/distributeddataservice/adapter/include/account/visibility.h b/services/distributeddataservice/framework/include/metadata/meta_data_manager.h similarity index 31% rename from services/distributeddataservice/adapter/include/account/visibility.h rename to services/distributeddataservice/framework/include/metadata/meta_data_manager.h index 50f688ff91d39432d1fcd305f91320b9c22cf183..864393bbe7bfe95ac48d7c3b183b01388e837c7c 100644 --- a/services/distributeddataservice/adapter/include/account/visibility.h +++ b/services/distributeddataservice/framework/include/metadata/meta_data_manager.h @@ -12,12 +12,41 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#ifndef DISTRIBUTEDDATAMGR_ACCOUNT_VISIBILITY_H -#define DISTRIBUTEDDATAMGR_ACCOUNT_VISIBILITY_H -#ifndef API_EXPORT -#define API_EXPORT __attribute__((visibility("default"))) -#endif -#ifndef KVSTORE_API -#define KVSTORE_API API_EXPORT -#endif -#endif // DISTRIBUTEDDATAMGR_ACCOUNT_VISIBILITY_H + +#ifndef OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_METADATA_META_DATA_MANAGER_H +#define OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_METADATA_META_DATA_MANAGER_H +#include +#include +#include +#include +#include "concurrent_map.h" +#include "serializable/serializable.h" +namespace DistributedDB { +class KvStoreNbDelegate; +} +namespace OHOS::DistributedData { +class MetaObserver; +class MetaDataManager { +public: + enum Action : int32_t { + INSERT, + UPDATE, + DELETE, + }; + using MetaStore = DistributedDB::KvStoreNbDelegate; + using Observer = std::function; + API_EXPORT static MetaDataManager &GetInstance(); + API_EXPORT void SetMetaStore(std::shared_ptr metaStore); + API_EXPORT bool SaveMeta(const std::string &key, const Serializable &value); + API_EXPORT bool LoadMeta(const std::string &key, Serializable &value); + API_EXPORT bool SubscribeMeta(const std::string &prefix, Observer observer); +private: + MetaDataManager(); + ~MetaDataManager(); + bool inited_ = false; + std::mutex mutex_; + std::shared_ptr metaStore_; + ConcurrentMap> metaObservers_; +}; +} +#endif // OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_METADATA_META_DATA_MANAGER_H diff --git a/services/distributeddataservice/framework/include/metadata/user_meta_data.h b/services/distributeddataservice/framework/include/metadata/user_meta_data.h index 7ed2b61a2568ee2bcd9f076d85988bbcd42c7977..d109897881a16df8b9188fc45bb9fa251432d0eb 100644 --- a/services/distributeddataservice/framework/include/metadata/user_meta_data.h +++ b/services/distributeddataservice/framework/include/metadata/user_meta_data.h @@ -43,7 +43,7 @@ public: class UserMetaRow { public: API_EXPORT static const std::string KEY_PREFIX; - API_EXPORT static std::vector GetKeyFor(const std::string &key); + API_EXPORT static std::string GetKeyFor(const std::string &key); }; } // namespace OHOS::DistributedData diff --git a/services/distributeddataservice/framework/metadata/meta_data_manager.cpp b/services/distributeddataservice/framework/metadata/meta_data_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3b66e9a631aa63b80e2dbc463565095c6a702966 --- /dev/null +++ b/services/distributeddataservice/framework/metadata/meta_data_manager.cpp @@ -0,0 +1,130 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "metadata/meta_data_manager.h" + +#include "kv_store_nb_delegate.h" +namespace OHOS::DistributedData { +class MetaObserver : public DistributedDB::KvStoreObserver { +public: + MetaObserver(std::shared_ptr metaStore, MetaDataManager::Observer observer); + virtual ~MetaObserver(); + + // Database change callback + void OnChange(const DistributedDB::KvStoreChangedData &data) override; +private: + std::shared_ptr metaStore_; + MetaDataManager::Observer observer_; + +}; + +MetaObserver::MetaObserver(std::shared_ptr metaStore, MetaDataManager::Observer observer) + : metaStore_(metaStore), observer_(std::move(observer)) +{ + if (metaStore_ != nullptr) { + int mode = DistributedDB::OBSERVER_CHANGES_NATIVE | DistributedDB::OBSERVER_CHANGES_FOREIGN; + auto status = metaStore_->RegisterObserver(DistributedDB::Key(), mode, this); + if (status != DistributedDB::DBStatus::OK) { + // ZLOGW("register meta observer failed :%{public}d.", status); + } + } +} + +MetaObserver::~MetaObserver() +{ + if (metaStore_ != nullptr) { + metaStore_->UnRegisterObserver(this); + } +} + +void MetaObserver::OnChange(const DistributedDB::KvStoreChangedData &data) +{ + auto values = {&data.GetEntriesInserted(), &data.GetEntriesUpdated(), &data.GetEntriesDeleted()}; + int32_t next = MetaDataManager::INSERT; + for (auto value : values) { + int32_t action = next++; + if (value->empty()) { + continue; + } + for (const auto &entry : *value) { + observer_({entry.key.begin(), entry.key.end()}, {entry.value.begin(), entry.value.end()}, action); + } + } +} + +MetaDataManager &MetaDataManager::GetInstance() +{ + static MetaDataManager instance; + return instance; +} +MetaDataManager::MetaDataManager() +{ + +} +MetaDataManager::~MetaDataManager() +{ + metaObservers_.Clear(); +} +void MetaDataManager::SetMetaStore(std::shared_ptr metaStore) +{ + if (metaStore == nullptr) { + return; + } + + std::lock_guard lg(mutex_); + if (inited_) { + return; + } + metaStore_ = std::move(metaStore); + inited_ = true; +} + +bool MetaDataManager::SaveMeta(const std::string &key, const Serializable &value) +{ + if (!inited_) { + return false; + } + + auto data = Serializable::Marshall(value); + auto status = metaStore_->Put({key.begin(), key.end()}, {data.begin(), data.end()}); + return status == DistributedDB::DBStatus::OK; +} + +bool MetaDataManager::LoadMeta(const std::string &key, Serializable &value) +{ + if (!inited_) { + return false; + } + + DistributedDB::Value data; + auto status = metaStore_->Get({key.begin(), key.end()}, data); + if (status != DistributedDB::DBStatus::OK) { + return false; + } + Serializable::Unmarshall({data.begin(), data.end()}, value); + return true; +} + +bool MetaDataManager::SubscribeMeta(const std::string &prefix, Observer observer) +{ + if (!inited_) { + return false; + } + + return metaObservers_.ComputeIfAbsent(prefix, [this, &observer](const std::string &key) -> auto { + return std::make_shared(metaStore_, observer); + }); +} +} \ No newline at end of file diff --git a/services/distributeddataservice/framework/metadata/user_meta_data.cpp b/services/distributeddataservice/framework/metadata/user_meta_data.cpp index c556e99dc38695f9163bd7b257c41b9be73e6ebb..29e48e3365f725b6e50a69c3323fc5033d24b6b2 100644 --- a/services/distributeddataservice/framework/metadata/user_meta_data.cpp +++ b/services/distributeddataservice/framework/metadata/user_meta_data.cpp @@ -13,7 +13,6 @@ * limitations under the License. */ #include "metadata/user_meta_data.h" - #include "utils/constant.h" namespace OHOS::DistributedData { @@ -56,7 +55,7 @@ UserStatus::UserStatus(int id, bool isActive) : id(id), isActive(isActive) } const std::string UserMetaRow::KEY_PREFIX = "UserMeta"; -std::vector UserMetaRow::GetKeyFor(const std::string &key) +std::string UserMetaRow::GetKeyFor(const std::string &key) { std::string str = Constant::Concatenate({ KEY_PREFIX, Constant::KEY_SEPARATOR, key }); return { str.begin(), str.end() }; diff --git a/services/distributeddataservice/service/directory/include/kvstore_context.h b/services/distributeddataservice/service/directory/include/kvstore_context.h index c42bb7f217930b659d9c585a9afed3e4046e01c5..a60f43bb16e60cc6f83f59dd9f3134d2cfc0f7c9 100644 --- a/services/distributeddataservice/service/directory/include/kvstore_context.h +++ b/services/distributeddataservice/service/directory/include/kvstore_context.h @@ -17,7 +17,6 @@ #define DISTRIBUTEDDATAMGR_KVSTORE_CONTEXT_H #include -#include "types.h" namespace OHOS::DistributedData { struct ClientContext { std::string userId {}; diff --git a/services/distributeddataservice/service/directory/src/directory_manager.cpp b/services/distributeddataservice/service/directory/src/directory_manager.cpp index f4e8f331c7c9cbe91b9743b18bc986ddd81577ef..628092b20af93ece2cbc31ab26383ad78cc3a20b 100644 --- a/services/distributeddataservice/service/directory/src/directory_manager.cpp +++ b/services/distributeddataservice/service/directory/src/directory_manager.cpp @@ -105,7 +105,7 @@ DirectoryManager &DirectoryManager::GetInstance() std::string DirectoryManager::GetStorePath(const StoreMetaData &metaData) { - return {}; + return metaData.dataDir; } std::string DirectoryManager::GetStoreBackupPath(const StoreMetaData &metaData) @@ -115,7 +115,7 @@ std::string DirectoryManager::GetStoreBackupPath(const StoreMetaData &metaData) std::string DirectoryManager::GetMetaDataStorePath() { - return "/data/service/el0/0/database/ddms/metadata/"; + return "/data/service/el1/public/distributeddata/meta/"; } void DirectoryManager::AddParams(const Strategy &strategy) { diff --git a/services/distributeddataservice/app/src/executor_factory.cpp b/services/distributeddataservice/service/kvdb/executor_factory.cpp similarity index 96% rename from services/distributeddataservice/app/src/executor_factory.cpp rename to services/distributeddataservice/service/kvdb/executor_factory.cpp index b87fe785bbe003cfe1e1037dc5c1f1c0700ced60..25cc2b707a1c818c626e79dee1d99d697abd22ff 100644 --- a/services/distributeddataservice/app/src/executor_factory.cpp +++ b/services/distributeddataservice/service/kvdb/executor_factory.cpp @@ -1,46 +1,46 @@ -/* -* Copyright (c) 2022 Huawei Device Co., Ltd. -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -#include "executor_factory.h" - -namespace OHOS::DistributedData { -using namespace OHOS::DistributedKv; -ExecutorFactory &ExecutorFactory::GetInstance() -{ - static ExecutorFactory instance; - return instance; -} - -bool ExecutorFactory::Execute(KvStoreTask &&task) -{ - if (threadPool_ == nullptr) { - return false; - } - threadPool_->AddTask(std::move(task)); - return true; -} - -ExecutorFactory::ExecutorFactory() -{ - threadPool_ = KvStoreThreadPool::GetPool(POOL_SIZE, true); -} - -ExecutorFactory::~ExecutorFactory() -{ - if (threadPool_ != nullptr) { - threadPool_->Stop(); - threadPool_ = nullptr; - } -} +/* +* Copyright (c) 2022 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +#include "executor_factory.h" + +namespace OHOS::DistributedData { +using namespace OHOS::DistributedKv; +ExecutorFactory &ExecutorFactory::GetInstance() +{ + static ExecutorFactory instance; + return instance; +} + +bool ExecutorFactory::Execute(KvStoreTask &&task) +{ + if (threadPool_ == nullptr) { + return false; + } + threadPool_->AddTask(std::move(task)); + return true; +} + +ExecutorFactory::ExecutorFactory() +{ + threadPool_ = KvStoreThreadPool::GetPool(POOL_SIZE, true); +} + +ExecutorFactory::~ExecutorFactory() +{ + if (threadPool_ != nullptr) { + threadPool_->Stop(); + threadPool_ = nullptr; + } +} } // namespace OHOS::DistributedData \ No newline at end of file diff --git a/services/distributeddataservice/app/src/executor_factory.h b/services/distributeddataservice/service/kvdb/executor_factory.h similarity index 97% rename from services/distributeddataservice/app/src/executor_factory.h rename to services/distributeddataservice/service/kvdb/executor_factory.h index c91e2839a190d19e71ca91d72caf713f95a19b6e..efcb6c5e6ceab2bc3fee54b9cef38dddaf87fe96 100644 --- a/services/distributeddataservice/app/src/executor_factory.h +++ b/services/distributeddataservice/service/kvdb/executor_factory.h @@ -1,36 +1,36 @@ -/* -* Copyright (c) 2022 Huawei Device Co., Ltd. -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -#ifndef DISTRIBUTEDDATAMGR_DATAMGR_EXECUTOR_FACTORY_H -#define DISTRIBUTEDDATAMGR_DATAMGR_EXECUTOR_FACTORY_H - -#include "kv_store_thread_pool.h" -namespace OHOS::DistributedData { -using OHOS::DistributedKv::KvStoreTask; -using OHOS::DistributedKv::KvStoreThreadPool; -class ExecutorFactory { -public: - static ExecutorFactory &GetInstance(); - bool Execute(KvStoreTask &&task); - -private: - ExecutorFactory(); - ~ExecutorFactory(); - - static constexpr int POOL_SIZE = 4; - - std::shared_ptr threadPool_; -}; -} // namespace OHOS::DistributedData -#endif // DISTRIBUTEDDATAMGR_DATAMGR_EXECUTOR_FACTORY_H +/* +* Copyright (c) 2022 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +#ifndef DISTRIBUTEDDATAMGR_DATAMGR_EXECUTOR_FACTORY_H +#define DISTRIBUTEDDATAMGR_DATAMGR_EXECUTOR_FACTORY_H + +#include "kv_store_thread_pool.h" +namespace OHOS::DistributedData { +using OHOS::DistributedKv::KvStoreTask; +using OHOS::DistributedKv::KvStoreThreadPool; +class ExecutorFactory { +public: + static ExecutorFactory &GetInstance(); + bool Execute(KvStoreTask &&task); + +private: + ExecutorFactory(); + ~ExecutorFactory(); + + static constexpr int POOL_SIZE = 4; + + std::shared_ptr threadPool_; +}; +} // namespace OHOS::DistributedData +#endif // DISTRIBUTEDDATAMGR_DATAMGR_EXECUTOR_FACTORY_H diff --git a/services/distributeddataservice/service/kv/user_delegate.cpp b/services/distributeddataservice/service/kvdb/user_delegate.cpp similarity index 74% rename from services/distributeddataservice/service/kv/user_delegate.cpp rename to services/distributeddataservice/service/kvdb/user_delegate.cpp index 3f35b4ed8ff2721b303e673077689b62cece7829..ca4511ecab381d125fbcfbd1f9c04c1ac52aae24 100644 --- a/services/distributeddataservice/service/kv/user_delegate.cpp +++ b/services/distributeddataservice/service/kvdb/user_delegate.cpp @@ -1,202 +1,183 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "user_delegate.h" - -#define LOG_TAG "UserDelegate" - -#include "account_delegate.h" -#include "communication_provider.h" -#include "device_kvstore_impl.h" -#include "executor_factory.h" -#include "kvstore_meta_manager.h" -#include "log_print.h" -#include "os_account_manager.h" - -namespace OHOS::DistributedData { -using OHOS::AppDistributedKv::CommunicationProvider; -using namespace OHOS::DistributedKv; -using namespace OHOS::AccountSA; -std::vector UserDelegate::GetLocalUserStatus() -{ - ZLOGI("begin"); - auto deviceInfo = CommunicationProvider::GetInstance().GetLocalDevice(); - if (deviceInfo.deviceId.empty()) { - ZLOGE("failed to get local device id"); - return {}; - } - return GetUsers(deviceInfo.deviceId); -} - -std::vector UserDelegate::GetRemoteUserStatus(const std::string &deviceId) -{ - if (deviceId.empty()) { - ZLOGE("error input device id"); - return {}; - } - return GetUsers(deviceId); -} - -std::vector UserDelegate::GetUsers(const std::string &deviceId) -{ - std::vector userStatus; - if (!deviceUserMap_.Contains(deviceId)) { - LoadFromMeta(deviceId); - } - for (const auto &entry : deviceUserMap_[deviceId]) { - userStatus.emplace_back(entry.first, entry.second); - } - ZLOGI("device:%{public}.10s, users:%{public}s", deviceId.c_str(), Serializable::Marshall(userStatus).c_str()); - return userStatus; -} - -void UserDelegate::DeleteUsers(const std::string &deviceId) -{ - deviceUserMap_.Erase(deviceId); -} - -void UserDelegate::UpdateUsers(const std::string &deviceId, const std::vector &userStatus) -{ - ZLOGI("begin, device:%{public}.10s, users:%{public}u", deviceId.c_str(), userStatus.size()); - deviceUserMap_.ComputeIfPresent(deviceId, [](const auto &key, std::map &userMap) { - for (auto &user : userMap) { - user.second = false; - } - }); - for (auto &user : userStatus) { - deviceUserMap_[deviceId][user.id] = user.isActive; - } - ZLOGI("end, device:%{public}.10s, users:%{public}u", deviceId.c_str(), deviceUserMap_[deviceId].size()); -} - -bool UserDelegate::InitLocalUserMeta() -{ - std::vector osAccountIds = { { 0, true } }; // system user default - auto ret = OsAccountManager::QueryActiveOsAccountIds(osAccountIds); - if (ret != 0 || osAccountIds.empty()) { - ZLOGE("failed to query os accounts, ret:%{public}d", ret); - return false; - } - std::vector userStatus = { { 0, true } }; - for (const auto &user : osAccountIds) { - userStatus.emplace_back(user, true); - } - UserMetaData userMetaData; - userMetaData.deviceId = DeviceKvStoreImpl::GetLocalDeviceId(); - UpdateUsers(userMetaData.deviceId, userStatus); - for (auto &pair : deviceUserMap_[userMetaData.deviceId]) { - userMetaData.users.emplace_back(pair.first, pair.second); - } - - auto &metaDelegate = KvStoreMetaManager::GetInstance().GetMetaKvStore(); - if (metaDelegate == nullptr) { - ZLOGE("GetMetaKvStore return nullptr."); - return false; - } - auto dbKey = UserMetaRow::GetKeyFor(userMetaData.deviceId); - std::string jsonData = UserMetaData::Marshall(userMetaData); - DistributedDB::Value dbValue{ jsonData.begin(), jsonData.end() }; - ret = metaDelegate->Put(dbKey, dbValue); - ZLOGI("put user meta data ret %{public}d", ret); - return ret == DistributedDB::DBStatus::OK; -} - -void UserDelegate::LoadFromMeta(const std::string &deviceId) -{ - auto &metaDelegate = KvStoreMetaManager::GetInstance().GetMetaKvStore(); - if (metaDelegate == nullptr) { - ZLOGE("GetMetaKvStore return nullptr."); - return; - } - - auto dbKey = UserMetaRow::GetKeyFor(deviceId); - DistributedDB::Value dbValue; - auto ret = metaDelegate->Get(dbKey, dbValue); - UserMetaData userMetaData; - ZLOGI("get user meta data ret %{public}d", ret); - if (ret != DistributedDB::DBStatus::OK) { - return; - } - userMetaData.Unmarshall({ dbValue.begin(), dbValue.end() }); - std::map userMap; - for (const auto &user : userMetaData.users) { - userMap[user.id] = user.isActive; - } - deviceUserMap_[deviceId] = userMap; -} - -UserDelegate &UserDelegate::GetInstance() -{ - static UserDelegate instance; - return instance; -} - -void UserDelegate::Init() -{ - KvStoreTask retryTask([this]() { - do { - static constexpr int RETRY_INTERVAL = 500; // millisecond - std::this_thread::sleep_for(std::chrono::milliseconds(RETRY_INTERVAL)); - if (!InitLocalUserMeta()) { - continue; - } - break; - } while (true); - ZLOGI("update user meta ok"); - }); - ExecutorFactory::GetInstance().Execute(std::move(retryTask)); - auto ret = AccountDelegate::GetInstance()->Subscribe(std::make_shared(*this)); - // subscribe user meta in other devices - KvStoreMetaManager::GetInstance().SubscribeMeta(UserMetaRow::KEY_PREFIX, - [this](const std::vector &key, const std::vector &value, CHANGE_FLAG flag) { - UserMetaData metaData; - metaData.Unmarshall({ value.begin(), value.end() }); - ZLOGD("flag:%{public}d, value:%{public}.10s", flag, metaData.deviceId.c_str()); - if (metaData.deviceId == DeviceKvStoreImpl::GetLocalDeviceId()) { - ZLOGD("ignore local device user meta change"); - return; - } - if (flag == CHANGE_FLAG::INSERT || flag == CHANGE_FLAG::UPDATE) { - UpdateUsers(metaData.deviceId, metaData.users); - } else if (flag == CHANGE_FLAG::DELETE) { - DeleteUsers(metaData.deviceId); - } else { - ZLOGD("ignored operation"); - } - }); - ZLOGD("subscribe os account ret:%{public}d", ret); -} - -bool UserDelegate::NotifyUserEvent(const UserDelegate::UserEvent &userEvent) -{ - // update all local user status - return InitLocalUserMeta(); -} - -UserDelegate::LocalUserObserver::LocalUserObserver(UserDelegate &userDelegate) : userDelegate_(userDelegate) -{ -} - -void UserDelegate::LocalUserObserver::OnAccountChanged(const DistributedKv::AccountEventInfo &eventInfo) -{ - ZLOGI("event info:%{public}s, %{public}d", eventInfo.deviceAccountId.c_str(), eventInfo.status); - userDelegate_.NotifyUserEvent({}); // just notify -} - -std::string UserDelegate::LocalUserObserver::Name() -{ - return "user_delegate"; -} -} // namespace OHOS::DistributedData +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "user_delegate.h" + +#define LOG_TAG "UserDelegate" + +#include "account_delegate.h" +#include "communication_provider.h" +#include "device_kvstore_impl.h" +#include "executor_factory.h" +#include "log_print.h" +#include "os_account_manager.h" +#include "metadata/meta_data_manager.h" +namespace OHOS::DistributedData { +using OHOS::AppDistributedKv::CommunicationProvider; +using namespace OHOS::DistributedKv; +using namespace OHOS::AccountSA; +std::string GetLocalDeviceId() +{ + return DeviceKvStoreImpl::GetLocalDeviceId(); +} +std::vector UserDelegate::GetLocalUserStatus() +{ + ZLOGI("begin"); + auto deviceInfo = CommunicationProvider::GetInstance().GetLocalDevice(); + if (deviceInfo.deviceId.empty()) { + ZLOGE("failed to get local device id"); + return {}; + } + return GetUsers(deviceInfo.deviceId); +} + +std::vector UserDelegate::GetRemoteUserStatus(const std::string &deviceId) +{ + if (deviceId.empty()) { + ZLOGE("error input device id"); + return {}; + } + return GetUsers(deviceId); +} + +std::vector UserDelegate::GetUsers(const std::string &deviceId) +{ + std::vector userStatus; + if (!deviceUserMap_.Contains(deviceId)) { + LoadFromMeta(deviceId); + } + for (const auto &entry : deviceUserMap_[deviceId]) { + userStatus.emplace_back(entry.first, entry.second); + } + ZLOGI("device:%{public}.10s, users:%{public}s", deviceId.c_str(), Serializable::Marshall(userStatus).c_str()); + return userStatus; +} + +void UserDelegate::DeleteUsers(const std::string &deviceId) +{ + deviceUserMap_.Erase(deviceId); +} + +void UserDelegate::UpdateUsers(const std::string &deviceId, const std::vector &userStatus) +{ + ZLOGI("begin, device:%{public}.10s, users:%{public}u", deviceId.c_str(), userStatus.size()); + deviceUserMap_.ComputeIfPresent(deviceId, [](const auto &key, std::map &userMap) { + for (auto &user : userMap) { + user.second = false; + } + }); + for (auto &user : userStatus) { + deviceUserMap_[deviceId][user.id] = user.isActive; + } + ZLOGI("end, device:%{public}.10s, users:%{public}u", deviceId.c_str(), deviceUserMap_[deviceId].size()); +} + +bool UserDelegate::InitLocalUserMeta() +{ + std::vector osAccountIds = { { 0, true } }; // system user default + auto ret = OsAccountManager::QueryActiveOsAccountIds(osAccountIds); + if (ret != 0 || osAccountIds.empty()) { + ZLOGE("failed to query os accounts, ret:%{public}d", ret); + return false; + } + std::vector userStatus = { { 0, true } }; + for (const auto &user : osAccountIds) { + userStatus.emplace_back(user, true); + } + UserMetaData userMetaData; + userMetaData.deviceId = GetLocalDeviceId(); + UpdateUsers(userMetaData.deviceId, userStatus); + for (auto &pair : deviceUserMap_[userMetaData.deviceId]) { + userMetaData.users.emplace_back(pair.first, pair.second); + } + + ZLOGI("put user meta data save meta data"); + return MetaDataManager::GetInstance().SaveMeta(UserMetaRow::GetKeyFor(userMetaData.deviceId), userMetaData); +} + +void UserDelegate::LoadFromMeta(const std::string &deviceId) +{ + UserMetaData userMetaData; + MetaDataManager::GetInstance().LoadMeta(UserMetaRow::GetKeyFor(deviceId), userMetaData); + std::map userMap; + for (const auto &user : userMetaData.users) { + userMap[user.id] = user.isActive; + } + deviceUserMap_[deviceId] = userMap; +} + +UserDelegate &UserDelegate::GetInstance() +{ + static UserDelegate instance; + return instance; +} + +void UserDelegate::Init() +{ + KvStoreTask retryTask([this]() { + do { + static constexpr int RETRY_INTERVAL = 500; // millisecond + std::this_thread::sleep_for(std::chrono::milliseconds(RETRY_INTERVAL)); + if (!InitLocalUserMeta()) { + continue; + } + break; + } while (true); + ZLOGI("update user meta ok"); + }); + ExecutorFactory::GetInstance().Execute(std::move(retryTask)); + auto ret = AccountDelegate::GetInstance()->Subscribe(std::make_shared(*this)); + MetaDataManager::GetInstance().SubscribeMeta(UserMetaRow::KEY_PREFIX, + [this](const std::string &key, const std::string &value, int32_t flag) -> auto { + UserMetaData metaData; + UserMetaData::Unmarshall(value, metaData); + ZLOGD("flag:%{public}d, value:%{public}.10s", flag, metaData.deviceId.c_str()); + if (metaData.deviceId == GetLocalDeviceId()) { + ZLOGD("ignore local device user meta change"); + return false; + } + if (flag == MetaDataManager::INSERT || flag == MetaDataManager::UPDATE) { + UpdateUsers(metaData.deviceId, metaData.users); + } else if (flag == MetaDataManager::DELETE) { + DeleteUsers(metaData.deviceId); + } else { + ZLOGD("ignored operation"); + } + return true; + }); + ZLOGD("subscribe os account ret:%{public}d", ret); +} + +bool UserDelegate::NotifyUserEvent(const UserDelegate::UserEvent &userEvent) +{ + // update all local user status + return InitLocalUserMeta(); +} + +UserDelegate::LocalUserObserver::LocalUserObserver(UserDelegate &userDelegate) : userDelegate_(userDelegate) +{ +} + +void UserDelegate::LocalUserObserver::OnAccountChanged(const DistributedKv::AccountEventInfo &eventInfo) +{ + ZLOGI("event info:%{public}s, %{public}d", eventInfo.deviceAccountId.c_str(), eventInfo.status); + userDelegate_.NotifyUserEvent({}); // just notify +} + +std::string UserDelegate::LocalUserObserver::Name() +{ + return "user_delegate"; +} +} // namespace OHOS::DistributedData diff --git a/services/distributeddataservice/service/kv/user_delegate.h b/services/distributeddataservice/service/kvdb/user_delegate.h similarity index 97% rename from services/distributeddataservice/service/kv/user_delegate.h rename to services/distributeddataservice/service/kvdb/user_delegate.h index 75d90a54d68af924548118439df61186af5eeb27..f9909dbfdef20c69d21b34ebb591ab41a22dcf28 100644 --- a/services/distributeddataservice/service/kv/user_delegate.h +++ b/services/distributeddataservice/service/kvdb/user_delegate.h @@ -1,63 +1,63 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef DISTRIBUTEDDATAMGR_USER_DELEGATE_H -#define DISTRIBUTEDDATAMGR_USER_DELEGATE_H - -#include - -#include "account_delegate.h" -#include "concurrent_map.h" -#include "metadata/user_meta_data.h" -#include "visibility.h" - -namespace OHOS::DistributedData { -using AccountDelegate = DistributedKv::AccountDelegate; -using DistributedData::UserStatus; -class UserDelegate { -public: - struct UserEvent { - int id; - bool isActive; - }; - static UserDelegate &GetInstance(); - - void Init(); - std::vector GetLocalUserStatus(); - std::vector GetRemoteUserStatus(const std::string &deviceId); - bool InitLocalUserMeta(); - -private: - class LocalUserObserver : public AccountDelegate::Observer { - public: - explicit LocalUserObserver(UserDelegate &userDelegate); - void OnAccountChanged(const DistributedKv::AccountEventInfo &eventInfo) override; - std::string Name() override; - - private: - UserDelegate &userDelegate_; - }; - std::vector GetUsers(const std::string &deviceId); - void LoadFromMeta(const std::string &deviceId); - void UpdateUsers(const std::string &deviceId, const std::vector &userStatus); - void DeleteUsers(const std::string &deviceId); - bool NotifyUserEvent(const UserEvent &userEvent); - - // device : { user : isActive } - ConcurrentMap> deviceUserMap_; -}; -} // namespace OHOS::DistributedData - -#endif // DISTRIBUTEDDATAMGR_USER_DELEGATE_H +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DISTRIBUTEDDATAMGR_USER_DELEGATE_H +#define DISTRIBUTEDDATAMGR_USER_DELEGATE_H + +#include + +#include "account_delegate.h" +#include "concurrent_map.h" +#include "metadata/user_meta_data.h" +#include "visibility.h" + +namespace OHOS::DistributedData { +using AccountDelegate = DistributedKv::AccountDelegate; +using DistributedData::UserStatus; +class UserDelegate { +public: + struct UserEvent { + int id; + bool isActive; + }; + static UserDelegate &GetInstance(); + + void Init(); + std::vector GetLocalUserStatus(); + std::vector GetRemoteUserStatus(const std::string &deviceId); + bool InitLocalUserMeta(); + +private: + class LocalUserObserver : public AccountDelegate::Observer { + public: + explicit LocalUserObserver(UserDelegate &userDelegate); + void OnAccountChanged(const DistributedKv::AccountEventInfo &eventInfo) override; + std::string Name() override; + + private: + UserDelegate &userDelegate_; + }; + std::vector GetUsers(const std::string &deviceId); + void LoadFromMeta(const std::string &deviceId); + void UpdateUsers(const std::string &deviceId, const std::vector &userStatus); + void DeleteUsers(const std::string &deviceId); + bool NotifyUserEvent(const UserEvent &userEvent); + + // device : { user : isActive } + ConcurrentMap> deviceUserMap_; +}; +} // namespace OHOS::DistributedData + +#endif // DISTRIBUTEDDATAMGR_USER_DELEGATE_H diff --git a/services/distributeddataservice/service/test/config_factory_test.cpp b/services/distributeddataservice/service/test/config_factory_test.cpp index fc9a46c6de68e50b8d16b1a4a764c82e115504a1..d7df502a9eb998f85c16b76e5380d05facda12d1 100644 --- a/services/distributeddataservice/service/test/config_factory_test.cpp +++ b/services/distributeddataservice/service/test/config_factory_test.cpp @@ -84,17 +84,14 @@ HWTEST_F(ConfigFactoryTest, CheckerConfig, TestSize.Level0) { auto *checker = ConfigFactory::GetInstance().GetCheckerConfig(); ASSERT_NE(checker, nullptr); - std::vector checkers{ "SystemChecker", "BundleChecker", "PackageChecker", "ExternalChecker" }; + std::vector checkers{ "SystemChecker", "BundleChecker", "MediaLibraryChecker", "PackageChecker", "ExternalChecker" }; ASSERT_EQ(checker->checkers, checkers); ASSERT_EQ(checker->trusts[0].bundleName, "bundle_manager_service"); ASSERT_EQ(checker->trusts[0].appId, "bundle_manager_service"); ASSERT_EQ(checker->trusts[0].checker, "SystemChecker"); - ASSERT_EQ(checker->trusts[1].bundleName, "form_storage"); - ASSERT_EQ(checker->trusts[1].appId, "form_storage"); - ASSERT_EQ(checker->trusts[1].checker, "SystemChecker"); - ASSERT_EQ(checker->trusts[2].bundleName, "ivi_config_manager"); - ASSERT_EQ(checker->trusts[2].appId, "ivi_config_manager"); - ASSERT_EQ(checker->trusts[2].checker, "SystemChecker"); + ASSERT_EQ(checker->trusts[1].bundleName, "com.ohos.medialibrary.MediaLibraryDataA"); + ASSERT_EQ(checker->trusts[1].appId, "com.ohos.medialibrary.MediaLibraryDataA"); + ASSERT_EQ(checker->trusts[1].checker, "MediaLibraryChecker"); } /** diff --git a/services/distributeddataservice/service/test/directory_manager_test.cpp b/services/distributeddataservice/service/test/directory_manager_test.cpp index 1d2ad8d9daf3fc4d75335c5e25566f96fd0b9916..3bc595de6a80b6de8b2fa50517b4fd3ca1faf2ec 100644 --- a/services/distributeddataservice/service/test/directory_manager_test.cpp +++ b/services/distributeddataservice/service/test/directory_manager_test.cpp @@ -51,10 +51,6 @@ HWTEST_F(DirectoryManagerTest, GetStoragePath01, TestSize.Level0) metaData.securityLevel = SecurityLevel::S2; auto path = DirectoryManager::GetInstance().GetStorePath(metaData); EXPECT_EQ(path, metaData.dataDir); - - metaData.securityLevel = SecurityLevel::S0; - path = DirectoryManager::GetInstance().GetStorePath(metaData); - EXPECT_EQ(path, "/data/misc_de/0/mdds/10/default/com.sample.helloworld/"); } /** @@ -73,10 +69,6 @@ HWTEST_F(DirectoryManagerTest, GetStorageBackupPath01, TestSize.Level0) metaData.securityLevel = SecurityLevel::S2; auto path = DirectoryManager::GetInstance().GetStoreBackupPath(metaData); EXPECT_EQ(path, metaData.dataDir + "/backup/"); - - metaData.securityLevel = SecurityLevel::S0; - path = DirectoryManager::GetInstance().GetStoreBackupPath(metaData); - EXPECT_EQ(path, "/data/misc_de/0/mdds/10/default/com.sample.helloworld/backup/"); } /** @@ -89,8 +81,5 @@ HWTEST_F(DirectoryManagerTest, GetStorageBackupPath01, TestSize.Level0) HWTEST_F(DirectoryManagerTest, GetStorageMetaPath01, TestSize.Level0) { auto path = DirectoryManager::GetInstance().GetMetaDataStorePath(); - EXPECT_EQ(path, "/data/service/el1/public/distributeddata/DistributedKvDataService/Meta/"); - - path = DirectoryManager::GetInstance().GetMetaDataStorePath(); - EXPECT_EQ(path, "/data/misc_de/0/mdds/Meta/"); + EXPECT_EQ(path, "/data/service/el1/public/distributeddata/meta/"); } diff --git a/services/distributeddataservice/test/BUILD.gn b/services/distributeddataservice/test/BUILD.gn index c5c927dc27e7b755c1d1020ed71e8f3977a5700a..0fc02f7a1fc2702e39d8eabf82737320d814def6 100755 --- a/services/distributeddataservice/test/BUILD.gn +++ b/services/distributeddataservice/test/BUILD.gn @@ -42,7 +42,6 @@ config("module_private_config") { "moduletest/common/distributeddb/include", "//utils/native/base/include", "//third_party/sqlite/include", - "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/app_distributeddata/include", "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata/include", "//third_party/openssl/include/", ]