kv_store部件化

Signed-off-by: wangkai <wangkai424@huawei.com>
This commit is contained in:
wangkai 2022-08-01 19:36:05 +08:00
parent 69c697f109
commit b51868bde2
826 changed files with 205593 additions and 7 deletions

69
OAT.xml Normal file
View File

@ -0,0 +1,69 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- 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.
-->
<!-- OAT(OSS Audit Tool) configuration guide:
basedir: Root dir, the basedir + project path is the real source file location.
licensefile:
1.If the project don't have "LICENSE" in root dir, please define all the license files in this project in , OAT will check license files according to this rule.
tasklist(only for batch mode):
1. task: Define oat check thread, each task will start a new thread.
2. task name: Only an name, no practical effect.
3. task policy: Default policy for projects under this task, this field is required and the specified policy must defined in policylist.
4. task filter: Default filefilter for projects under this task, this field is required and the specified filefilter must defined in filefilterlist.
5. task project: Projects to be checked, the path field define the source root dir of the project.
policyList:
1. policy: All policyitems will be merged to default OAT.xml rules, the name of policy doesn't affect OAT check process.
2. policyitem: The fields type, name, path, desc is required, and the fields rule, group, filefilter is optional,the default value is:
<policyitem type="" name="" path="" desc="" rule="may" group="defaultGroup" filefilter="defaultPolicyFilter"/>
3. policyitem type:
"compatibility" is used to check license compatibility in the specified path;
"license" is used to check source license header in the specified path;
"copyright" is used to check source copyright header in the specified path;
"import" is used to check source dependency in the specified path, such as import ... ,include ...
"filetype" is used to check file type in the specified path, supported file types: archive, binary
"filename" is used to check whether the specified file exists in the specified path(support projectroot in default OAT.xml), supported file names: LICENSE, README, README.OpenSource
4. policyitem name: This field is used for define the license, copyright, "*" means match all, the "!" prefix means could not match this value. For example, "!GPL" means can not use GPL license.
5. policyitem path: This field is used for define the source file scope to apply this policyitem, the "!" prefix means exclude the files. For example, "!.*/lib/.*" means files in lib dir will be exclude while process this policyitem.
6. policyitem rule and group: These two fields are used together to merge policy results. "may" policyitems in the same group means any one in this group passed, the result will be passed.
7. policyitem filefilter: Used to bind filefilter which define filter rules.
8. filefilter: Filter rules, the type filename is used to filter file name, the type filepath is used to filter file path.
Note:If the text contains special characters, please escape them according to the following rules:
" == &gt;
& == &gt;
' == &gt;
< == &gt;
> == &gt;
-->
<configuration>
<oatconfig>
<licensefile></licensefile>
<policylist>
<policy name="projectPolicy" desc="">
</policy>
</policylist>
<filefilterlist>
<filefilter name="defaultFilter" desc="Files not to check">
<filteritem type="filename" name="*.ha|*.hap|*.rpk" desc="valid and invalid bundle files for tests"/>
<filteritem type="filepath" name="figures/.*" desc="Self-developed image"/>
</filefilter>
</filefilterlist>
</oatconfig>
</configuration>

View File

@ -3,34 +3,133 @@
"version": "3.1.0",
"license": "Apache License 2.0",
"description": "",
"domain": "os",
"language": "",
"publishAs": "code-segment",
"private": false,
"tags": [
"foundation"
],
"keywords": [
"distributeddatamgr",
"kv_store"
],
"envs": [],
"author": {
"name": "",
"email": "",
"url": ""
},
"contributors": [
{
"name": "",
"email": "",
"url": ""
}
],
"segment": {
"destPath": "foundation/distributeddatamgr/kv_store/interfaces/inner_api/kv_store"
"destPath": [
"foundation/distributeddatamgr/kv_store/interfaces/inner_api/kv_store",
"foundation/distributeddatamgr/kv_store"
]
},
"dirs": {},
"scripts": {},
"component": {
"name": "kv_store",
"subsystem": "distributeddatamgr",
"syscap": [
"SystemCapability.DistributedDataManager.KVStore.Core",
"SystemCapability.DistributedDataManager.KVStore.Lite",
"SystemCapability.DistributedDataManager.KVStore.DistributedKVStore"
],
"features": [],
"adapted_system_type": [
"mini",
"small"
"small",
"standard"
],
"rom": "13KB",
"ram": "80KB",
"deps": {
"thrid_party": [ "bounds_checking_function" ],
"thrid_party": [
"bounds_checking_function",
"uv_static",
"sqlite",
"libz",
"jsoncpp",
"libcrypto_shared"
],
"kernel_special": {},
"board_special": {},
"components": [
"utils_lite"
"utils_lite",
"libuv",
"common_event_service",
"bundle_framework",
"safwk",
"zlib",
"init",
"os_account",
"common",
"samgr_standard",
"dataclassification",
"dsoftbus",
"jsoncpp",
"hitrace_native",
"access_token",
"huks",
"ability_base",
"ability_runtime",
"hiviewdfx_hilog_native",
"hisysevent_native",
"device_auth",
"ipc",
"napi"
]
},
"build": {
"sub_component": [ "//foundation/distributeddatamgr/kv_store/interfaces/inner_api/kv_store" ],
"inner_kits": [],
"test": []
"sub_component": [
"//foundation/distributeddatamgr/kv_store/frameworks/innerkitsimpl/kvdb/distributeddb:build_module",
"//foundation/distributeddatamgr/kv_store/interfaces/innerkits/distributeddata:build_module",
"//foundation/distributeddatamgr/kv_store/interfaces/jskits/distributeddata:build_module",
"//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/app:build_module",
"//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/framework:build_module",
"//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/service:build_module",
"//foundation/distributeddatamgr/kv_store/conf:build_module",
"//foundation/distributeddatamgr/kv_store/interfaces/inner_api/kv_store"
],
"inner_kits": [
{
"name": "//foundation/distributeddatamgr/kv_store/interfaces/innerkits/distributeddata:distributeddata_inner",
"header": {
"header_files": [
"blob.h",
"change_notification.h",
"distributed_kv_data_manager.h",
"kvstore.h",
"kvstore_death_recipient.h",
"kvstore_observer.h",
"kvstore_result_set.h",
"kvstore_sync_callback.h",
"single_kvstore.h",
"types.h",
"visibility.h",
"data_query.h",
"device_status_change_listener.h",
"store_errno.h"
],
"header_base": "//foundation/distributeddatamgr/kv_store/interfaces/innerkits/distributeddata/include"
}
}
],
"test": [
"//foundation/distributeddatamgr/kv_store:build_native_test",
"//foundation/distributeddatamgr/kv_store/frameworks/innerkitsimpl/kvdb/distributeddb/test:distributeddatamgr_fuzztest",
"//foundation/distributeddatamgr/kv_store:fuzztest",
"//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/test:fuzztest",
"//foundation/distributeddatamgr/kv_store:distributedtest"
]
}
}
}

25
conf/BUILD.gn Normal file
View File

@ -0,0 +1,25 @@
# 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")
import("//build/ohos_var.gni")
#/system/etc/distributeddata/conf
group("build_module") {
deps = [ ":default_conf" ]
}
ohos_prebuilt_etc("default_conf") {
source = "config.json"
relative_install_dir = "distributeddata/conf"
subsystem_name = "distributeddatamgr"
part_name = "kv_store"
}

80
conf/config.json Normal file
View File

@ -0,0 +1,80 @@
{
"processLabel": "distributeddata",
"metaData": "service_meta",
"version": "000.000.001",
"features": ["kvdb", "rdb", "object", "backup", "data_sync"],
"components": [
{
"description": "3rd party adapter",
"lib": "libconfigdemo.z.so",
"constructor": "",
"destructor": "",
"params": {
"key": "value",
"count": 1
}
},
{
"lib": "libconfigdemo2.z.so"
}
],
"bundleChecker": {
"checkers": [
"SystemChecker",
"BundleChecker",
"MediaLibraryChecker",
"PackageChecker",
"ExternalChecker"
],
"trusts": [
{
"bundleName": "bundle_manager_service",
"appId": "bundle_manager_service",
"checker": "SystemChecker"
},
{
"bundleName": "com.ohos.medialibrary.medialibrarydata",
"appId": "com.ohos.medialibrary.medialibrarydata",
"checker": "MediaLibraryChecker"
}
]
},
"networks": {
"chains": [
"loadBalance",
"authentication",
"traffic-control",
"router",
"transport",
"fault-inject"
],
"routers": [
"OHOSRouter"
],
"transports": [
"softbus"
],
"protocols": [
{
"name": "OHOS softbus",
"address": "ohos.distributeddata",
"transport": "softbus"
}
]
},
"directory": {
"strategy": [
{
"version": 0,
"pattern": "/data/{security}/0/mdds/{userId}/default/{bundleName}",
"metaPath": "/data/misc_de/0/mdds/Meta",
"autoCreate": true
},
{
"version": 50331651,
"pattern": "/data/{type}/{area}/{userId}/database/{bundleName}/{hapName}/{store}",
"metaPath": "/data/service/el1/public/database/distributeddata/meta"
}
]
}
}

View File

@ -0,0 +1,248 @@
/*
* 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_FRAMEWORKS_COMMON_CONCURRENT_MAP_H
#define OHOS_DISTRIBUTED_DATA_FRAMEWORKS_COMMON_CONCURRENT_MAP_H
#include <functional>
#include <map>
#include <mutex>
namespace OHOS {
template<typename _Key, typename _Tp>
class ConcurrentMap {
public:
using key_type = typename std::map<_Key, _Tp>::key_type;
using mapped_type = typename std::map<_Key, _Tp>::mapped_type;
using value_type = typename std::map<_Key, _Tp>::value_type;
using size_type = typename std::map<_Key, _Tp>::size_type;
using reference = typename std::map<_Key, _Tp>::reference;
using const_reference = typename std::map<_Key, _Tp>::const_reference;
ConcurrentMap() = default;
~ConcurrentMap()
{
Clear();
}
ConcurrentMap(const ConcurrentMap &other)
{
operator=(std::move(other));
}
ConcurrentMap &operator=(const ConcurrentMap &other) noexcept
{
if (this == &other) {
return *this;
}
auto tmp = other.Clone();
std::lock_guard<decltype(mutex_)> lock(mutex_);
entries_ = std::move(tmp);
return *this;
}
ConcurrentMap(ConcurrentMap &&other) noexcept
{
operator=(std::move(other));
}
ConcurrentMap &operator=(ConcurrentMap &&other) noexcept
{
if (this == &other) {
return *this;
}
auto tmp = other.Steal();
std::lock_guard<decltype(mutex_)> lock(mutex_);
entries_ = std::move(tmp);
return *this;
}
template<typename... _Args>
bool Emplace(_Args &&...__args) noexcept
{
std::lock_guard<decltype(mutex_)> lock(mutex_);
auto it = entries_.emplace(std::forward<_Args>(__args)...);
return it->second;
}
std::pair<bool, mapped_type> Find(const key_type &key) const noexcept
{
std::lock_guard<decltype(mutex_)> lock(mutex_);
auto it = entries_.find(key);
if (it == entries_.end()) {
return std::pair { false, mapped_type() };
}
return std::pair { true, it->second };
}
bool Contains(const key_type &key) const noexcept
{
std::lock_guard<decltype(mutex_)> lock(mutex_);
return (entries_.find(key) != entries_.end());
}
template <typename _Obj>
bool InsertOrAssign(const key_type &key, _Obj &&obj) noexcept
{
std::lock_guard<decltype(mutex_)> lock(mutex_);
auto it = entries_.insert_or_assign(key, std::forward<_Obj>(obj));
return it.second;
}
bool Insert(const key_type &key, const mapped_type &value) noexcept
{
std::lock_guard<decltype(mutex_)> lock(mutex_);
auto it = entries_.insert(value_type { key, value });
return it.second;
}
size_type Erase(const key_type &key) noexcept
{
std::lock_guard<decltype(mutex_)> lock(mutex_);
return entries_.erase(key);
}
void Clear() noexcept
{
std::lock_guard<decltype(mutex_)> lock(mutex_);
return entries_.clear();
}
bool Empty() const noexcept
{
std::lock_guard<decltype(mutex_)> lock(mutex_);
return entries_.empty();
}
size_type Size() const noexcept
{
std::lock_guard<decltype(mutex_)> lock(mutex_);
return entries_.size();
}
// The action`s return true mains meet the erase condition
// The action`s return false mains not meet the erase condition
size_type EraseIf(const std::function<bool(const key_type &key, mapped_type &value)> &action) noexcept
{
if (action == nullptr) {
return 0;
}
std::lock_guard<decltype(mutex_)> lock(mutex_);
#if __cplusplus > 201703L
auto count = std::erase_if(entries_,
[&action](value_type &value) -> bool { return action(value.first, value.second); });
#else
auto count = entries_.size();
for (auto it = entries_.begin(); it != entries_.end();) {
if (action((*it).first, (*it).second)) {
it = entries_.erase(it);
} else {
++it;
}
}
count -= entries_.size();
#endif
return count;
}
mapped_type &operator[](const key_type &key) noexcept
{
std::lock_guard<decltype(mutex_)> lock(mutex_);
return entries_[key];
}
void ForEach(const std::function<bool(const key_type &, mapped_type &)> &action)
{
if (action == nullptr) {
return;
}
std::lock_guard<decltype(mutex_)> lock(mutex_);
for (auto &[key, value] : entries_) {
if (action(key, value)) {
break;
}
}
}
// The action's return value mains that the element is keep in map or not; true mains keep, false mains remove.
bool Compute(const key_type &key, const std::function<bool(const key_type &, mapped_type &)> &action)
{
if (action == nullptr) {
return false;
}
std::lock_guard<decltype(mutex_)> lock(mutex_);
auto it = entries_.find(key);
if (it == entries_.end()) {
auto result = entries_.emplace(key, mapped_type());
it = result.second ? result.first : entries_.end();
}
if (it == entries_.end()) {
return false;
}
if (!action(it->first, it->second)) {
entries_.erase(key);
}
return true;
}
// The action's return value mains that the element is keep in map or not; true mains keep, false mains remove.
bool ComputeIfPresent(const key_type &key, const std::function<bool(const key_type &, mapped_type &)> &action)
{
if (action == nullptr) {
return false;
}
std::lock_guard<decltype(mutex_)> lock(mutex_);
auto it = entries_.find(key);
if (it == entries_.end()) {
return false;
}
if (!action(key, it->second)) {
entries_.erase(key);
}
return true;
}
bool ComputeIfAbsent(const key_type &key, const std::function<mapped_type(const key_type &)> &action)
{
if (action == nullptr) {
return false;
}
std::lock_guard<decltype(mutex_)> lock(mutex_);
auto it = entries_.find(key);
if (it != entries_.end()) {
return false;
}
entries_.emplace(key, action(key));
return true;
}
private:
std::map<_Key, _Tp> Steal() noexcept
{
std::lock_guard<decltype(mutex_)> lock(mutex_);
return std::move(entries_);
}
std::map<_Key, _Tp> Clone() const noexcept
{
std::lock_guard<decltype(mutex_)> lock(mutex_);
return entries_;
}
private:
mutable std::recursive_mutex mutex_;
std::map<_Key, _Tp> entries_;
};
} // namespace OHOS
#endif // OHOS_DISTRIBUTED_DATA_FRAMEWORKS_COMMON_CONCURRENT_MAP_H

View File

@ -0,0 +1,69 @@
/*
* 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 DISTRIBUTEDDATA_LOG_PRINT_H
#define DISTRIBUTEDDATA_LOG_PRINT_H
#define OS_OHOS
#if defined OS_OHOS // log for OHOS
#include "hilog/log.h"
namespace OHOS {
namespace DistributedKv {
static inline OHOS::HiviewDFX::HiLogLabel LogLabel()
{
return { LOG_CORE, 0xD001610, "ZDDS" };
}
} // end namespace DistributesdKv
namespace DistributedData {
static inline OHOS::HiviewDFX::HiLogLabel LogLabel()
{
return { LOG_CORE, 0xD001611, "ZDD" };
}
} // end namespace DistributedData
namespace AppDistributedKv {
static inline OHOS::HiviewDFX::HiLogLabel LogLabel()
{
return { LOG_CORE, 0xD001620, "ZDDC" };
}
} // namespace AppDistributedKv
namespace DistributedRdb {
static inline OHOS::HiviewDFX::HiLogLabel LogLabel()
{
return { LOG_CORE, 0xD001655, "DRDB" };
}
} // end namespace DistributedRdb
} // end namespace OHOS
#define ZLOGD(fmt, ...) \
OHOS::HiviewDFX::HiLog::Debug(LogLabel(), LOG_TAG "::%{public}s: " fmt, __FUNCTION__, ##__VA_ARGS__)
#define ZLOGI(fmt, ...) \
OHOS::HiviewDFX::HiLog::Info(LogLabel(), LOG_TAG "::%{public}s: " fmt, __FUNCTION__, ##__VA_ARGS__)
#define ZLOGW(fmt, ...) \
OHOS::HiviewDFX::HiLog::Warn(LogLabel(), LOG_TAG "::%{public}s: " fmt, __FUNCTION__, ##__VA_ARGS__)
#define ZLOGE(fmt, ...) \
OHOS::HiviewDFX::HiLog::Error(LogLabel(), LOG_TAG "::%{public}s: " fmt, __FUNCTION__, ##__VA_ARGS__)
#else
#error // unknown system
#endif
#endif // DISTRIBUTEDDATA_LOG_PRINT_H

View File

@ -0,0 +1,224 @@
/*
* 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_FRAMEWORKS_COMMON_LRU_BUCKET_H
#define OHOS_DISTRIBUTED_DATA_FRAMEWORKS_COMMON_LRU_BUCKET_H
#include <map>
#include <mutex>
#include <list>
namespace OHOS {
template<typename _Key, typename _Tp>
class LRUBucket {
public:
LRUBucket(size_t capacity)
: size_(0), capacity_(capacity) {}
LRUBucket(LRUBucket &&bucket) noexcept = delete;
LRUBucket(const LRUBucket &bucket) = delete;
LRUBucket &operator=(LRUBucket &&bucket) noexcept = delete;
LRUBucket &operator=(const LRUBucket &bucket) = delete;
~LRUBucket()
{
std::lock_guard<decltype(mutex_)> lock(mutex_);
while (size_ > 0) {
PopBack();
}
}
size_t Size() const
{
return size_;
}
size_t Capacity() const
{
return capacity_;
}
bool ResetCapacity(size_t capacity)
{
std::lock_guard<decltype(mutex_)> lock(mutex_);
capacity_ = capacity;
while (capacity_ < size_) {
PopBack();
}
return capacity_ == capacity;
}
/**
* The time complexity is O(log(index size))
**/
bool Get(const _Key &key, _Tp &value)
{
std::lock_guard<decltype(mutex_)> lock(mutex_);
auto it = indexes_.find(key);
if (it != indexes_.end()) {
// move node from the list;
Remove(it->second);
// insert node to the head
Insert(&head_, it->second);
value = it->second->value_;
return true;
}
return false;
}
/**
* The time complexity is O(log(index size))
**/
bool Set(const _Key &key, const _Tp &value)
{
std::lock_guard<decltype(mutex_)> lock(mutex_);
if (capacity_ == 0) {
return false;
}
auto it = indexes_.find(key);
if (it != indexes_.end()) {
Update(it->second, value);
Remove(it->second);
Insert(&head_, it->second);
return true;
}
while (capacity_ <= size_) {
PopBack();
}
auto *node = new(std::nothrow) Node(value);
if (node == nullptr) {
return false;
}
Insert(&head_, node);
auto pair = indexes_.emplace(key, node);
node->iterator_ = pair.first;
return true;
}
/**
* Just update the values, not change the lru
**/
bool Update(const _Key &key, const _Tp &value)
{
std::lock_guard<decltype(mutex_)> lock(mutex_);
auto it = indexes_.find(key);
if (it != indexes_.end()) {
Update(it->second, value);
return true;
}
return false;
}
/**
* The time complexity is O(min(indexes, values))
* Just update the values, not change the lru chain
*/
bool Update(const std::map<_Key, _Tp> &values)
{
std::lock_guard<decltype(mutex_)> lock(mutex_);
auto idx = indexes_.begin();
auto val = values.begin();
bool updated = false;
auto comp = indexes_.key_comp();
while (idx != indexes_.end() && val != values.end()) {
if (comp(idx->first, val->first)) {
++idx;
continue;
}
if (comp(val->first, idx->first)) {
++val;
continue;
}
updated = true;
Update(idx->second, val->second);
++idx;
++val;
}
return updated;
}
/**
* The time complexity is O(log(index size))
* */
bool Delete(const _Key &key)
{
std::lock_guard<decltype(mutex_)> lock(mutex_);
auto it = indexes_.find(key);
if (it != indexes_.end()) {
Remove(it->second);
Delete(it->second);
return true;
}
return false;
}
private:
struct Node final {
using iterator = typename std::map<_Key, Node *>::iterator;
Node(const _Tp &value) : value_(value) {}
Node() : value_() {}
~Node() = default;
_Tp value_;
iterator iterator_;
Node *prev_ = this;
Node *next_ = this;
};
void PopBack()
{
auto *node = head_.prev_;
Remove(node);
Delete(node);
}
void Update(Node *node, const _Tp &value)
{
node->value_ = value;
}
void Remove(Node *node)
{
node->prev_->next_ = node->next_;
node->next_->prev_ = node->prev_;
size_--;
}
void Insert(Node *prev, Node *node)
{
prev->next_->prev_ = node;
node->next_ = prev->next_;
prev->next_ = node;
node->prev_ = prev;
size_++;
}
void Delete(Node *node)
{
indexes_.erase(node->iterator_);
delete node;
}
mutable std::recursive_mutex mutex_;
std::map<_Key, Node *> indexes_;
Node head_;
size_t size_;
size_t capacity_;
};
} // namespace OHOS
#endif // OHOS_DISTRIBUTED_DATA_FRAMEWORKS_COMMON_LRU_BUCKET_H

View File

@ -0,0 +1,319 @@
/*
* 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.
*/
#define LOG_TAG "LRUBucketTest"
#include "lru_bucket.h"
#include "gtest/gtest.h"
using namespace testing::ext;
template<typename _Key, typename _Tp> using LRUBucket = OHOS::LRUBucket<_Key, _Tp>;
class LRUBucketTest : public testing::Test {
public:
struct TestValue {
std::string id;
std::string name;
std::string testCase;
};
static constexpr size_t TEST_CAPACITY = 10;
static void SetUpTestCase(void) {}
static void TearDownTestCase(void) {}
protected:
void SetUp()
{
bucket_.ResetCapacity(0);
bucket_.ResetCapacity(TEST_CAPACITY);
for (size_t i = 0; i < TEST_CAPACITY; ++i) {
std::string key = std::string("test_") + std::to_string(i);
TestValue value = {key, key, "case"};
bucket_.Set(key, value);
}
}
void TearDown() {}
LRUBucket<std::string, TestValue> bucket_{TEST_CAPACITY};
};
/**
* @tc.name: insert
* @tc.desc: Set the value to the lru bucket, whose capacity is more than one.
* @tc.type: FUNC
* @tc.require:
* @tc.author: Sven Wang
*/
HWTEST_F(LRUBucketTest, insert, TestSize.Level0)
{
bucket_.Set("test_10", {"test_10", "test_10", "case"});
TestValue value;
ASSERT_TRUE(!bucket_.Get("test_0", value));
ASSERT_TRUE(bucket_.Get("test_6", value));
ASSERT_TRUE(bucket_.ResetCapacity(1));
ASSERT_TRUE(bucket_.Capacity() == 1);
ASSERT_TRUE(bucket_.Size() <= 1);
ASSERT_TRUE(bucket_.Get("test_6", value));
}
/**
* @tc.name: cap_one_insert
* @tc.desc: Set the value to the lru bucket, whose capacity is one.
* @tc.type: FUNC
* @tc.require:
* @tc.author: Sven Wang
*/
HWTEST_F(LRUBucketTest, cap_one_insert, TestSize.Level0)
{
bucket_.ResetCapacity(1);
for (size_t i = 0; i <= TEST_CAPACITY; ++i) {
std::string key = std::string("test_") + std::to_string(i);
TestValue value = {key, key, "find"};
bucket_.Set(key, value);
}
TestValue value;
ASSERT_TRUE(!bucket_.Get("test_0", value));
ASSERT_TRUE(bucket_.Get("test_10", value));
}
/**
* @tc.name: cap_zero_insert
* @tc.desc: Set the value to the lru bucket, whose capacity is zero.
* @tc.type: FUNC
* @tc.require:
* @tc.author: Sven Wang
*/
HWTEST_F(LRUBucketTest, cap_zero_insert, TestSize.Level0)
{
bucket_.ResetCapacity(0);
for (size_t i = 0; i <= TEST_CAPACITY; ++i) {
std::string key = std::string("test_") + std::to_string(i);
TestValue value = {key, key, "find"};
bucket_.Set(key, value);
}
TestValue value;
ASSERT_TRUE(!bucket_.Get("test_10", value));
}
/**
* @tc.name: find_head
* @tc.desc: find the head element from the lru bucket.
* @tc.type: FUNC
* @tc.require:
* @tc.author: Sven Wang
*/
HWTEST_F(LRUBucketTest, find_head, TestSize.Level0)
{
TestValue value;
ASSERT_TRUE(bucket_.ResetCapacity(1));
ASSERT_TRUE(bucket_.Capacity() == 1);
ASSERT_TRUE(bucket_.Size() <= 1);
ASSERT_TRUE(bucket_.Get("test_9", value));
}
/**
* @tc.name: find_tail
* @tc.desc: find the tail element, then the element will move to head.
* @tc.type: FUNC
* @tc.require:
* @tc.author: Sven Wang
*/
HWTEST_F(LRUBucketTest, find_tail, TestSize.Level0)
{
TestValue value;
ASSERT_TRUE(bucket_.Get("test_0", value));
ASSERT_TRUE(bucket_.ResetCapacity(1));
ASSERT_TRUE(bucket_.Capacity() == 1);
ASSERT_TRUE(bucket_.Size() <= 1);
ASSERT_TRUE(bucket_.Get("test_0", value));
}
/**
* @tc.name: find_mid
* @tc.desc: find the mid element, then the element will move to head.
* @tc.type: FUNC
* @tc.require:
* @tc.author: Sven Wang
*/
HWTEST_F(LRUBucketTest, find_mid, TestSize.Level0)
{
TestValue value;
ASSERT_TRUE(bucket_.Get("test_5", value));
ASSERT_TRUE(bucket_.ResetCapacity(1));
ASSERT_TRUE(bucket_.Capacity() == 1);
ASSERT_TRUE(bucket_.Size() <= 1);
ASSERT_TRUE(bucket_.Get("test_5", value));
}
/**
* @tc.name: find_and_insert
* @tc.desc: find the tail element, then the element will move to head.
* @tc.type: FUNC
* @tc.require:
* @tc.author: Sven Wang
*/
HWTEST_F(LRUBucketTest, find_and_insert, TestSize.Level0)
{
TestValue value;
if (!bucket_.Get("MyTest", value)) {
bucket_.Set("MyTest", {"MyTest", "MyTest", "case"});
}
ASSERT_TRUE(bucket_.Get("MyTest", value));
if (!bucket_.Get("test_0", value)) {
bucket_.Set("test_0", {"test_0", "test_0", "case"});
}
ASSERT_TRUE(bucket_.Get("test_0", value));
ASSERT_TRUE(bucket_.Get("test_5", value));
ASSERT_TRUE(bucket_.Get("test_4", value));
ASSERT_TRUE(!bucket_.Get("test_1", value));
ASSERT_TRUE(bucket_.Get("test_2", value));
}
/**
* @tc.name: del_head
* @tc.desc: delete the head element, then the next element will move to head.
* @tc.type: FUNC
* @tc.require:
* @tc.author: Sven Wang
*/
HWTEST_F(LRUBucketTest, del_head, TestSize.Level0)
{
TestValue value;
ASSERT_TRUE(bucket_.Delete("test_9"));
ASSERT_TRUE(!bucket_.Get("test_9", value));
ASSERT_TRUE(bucket_.ResetCapacity(1));
ASSERT_TRUE(bucket_.Capacity() == 1);
ASSERT_TRUE(bucket_.Size() <= 1);
ASSERT_TRUE(bucket_.Get("test_8", value));
}
/**
* @tc.name: del_head
* @tc.desc: delete the tail element, then the lru chain keep valid.
* @tc.type: FUNC
* @tc.require:
* @tc.author: Sven Wang
*/
HWTEST_F(LRUBucketTest, del_tail, TestSize.Level0)
{
TestValue value;
ASSERT_TRUE(bucket_.Delete("test_0"));
ASSERT_TRUE(!bucket_.Get("test_0", value));
ASSERT_TRUE(bucket_.Get("test_4", value));
ASSERT_TRUE(bucket_.ResetCapacity(1));
ASSERT_TRUE(bucket_.Capacity() == 1);
ASSERT_TRUE(bucket_.Size() <= 1);
ASSERT_TRUE(bucket_.Get("test_4", value));
}
/**
* @tc.name: del_mid
* @tc.desc: delete the mid element, then the lru chain keep valid.
* @tc.type: FUNC
* @tc.require:
* @tc.author: Sven Wang
*/
HWTEST_F(LRUBucketTest, del_mid, TestSize.Level0)
{
TestValue value;
ASSERT_TRUE(bucket_.Delete("test_5"));
ASSERT_TRUE(!bucket_.Get("test_5", value));
ASSERT_TRUE(bucket_.Get("test_4", value));
ASSERT_TRUE(bucket_.Get("test_6", value));
ASSERT_TRUE(bucket_.ResetCapacity(2));
ASSERT_TRUE(bucket_.Capacity() == 2);
ASSERT_TRUE(bucket_.Size() <= 2);
ASSERT_TRUE(bucket_.Get("test_4", value));
ASSERT_TRUE(bucket_.Get("test_6", value));
}
/**
* @tc.name: del_mid
* @tc.desc: the lru bucket has only one element, then delete it.
* @tc.type: FUNC
* @tc.require:
* @tc.author: Sven Wang
*/
HWTEST_F(LRUBucketTest, cap_one_del, TestSize.Level0)
{
TestValue value;
bucket_.ResetCapacity(1);
ASSERT_TRUE(bucket_.Delete("test_9"));
ASSERT_TRUE(!bucket_.Get("test_9", value));
}
/**
* @tc.name: del_mid
* @tc.desc: the lru bucket has no element.
* @tc.type: FUNC
* @tc.require:
* @tc.author: Sven Wang
*/
HWTEST_F(LRUBucketTest, cap_zero_del, TestSize.Level0)
{
TestValue value;
bucket_.ResetCapacity(0);
ASSERT_TRUE(!bucket_.Delete("test_9"));
ASSERT_TRUE(!bucket_.Get("test_9", value));
}
/**
* @tc.name: update_one
* @tc.desc: update the value and the lru chain won't change.
* @tc.type: FUNC
* @tc.require:
* @tc.author: Sven Wang
*/
HWTEST_F(LRUBucketTest, update_one, TestSize.Level0)
{
TestValue value;
ASSERT_TRUE(bucket_.Update("test_4", {"test_4", "test_4", "update"}));
ASSERT_TRUE(bucket_.Get("test_4", value));
ASSERT_TRUE(value.testCase == "update");
ASSERT_TRUE(bucket_.Update("test_9", {"test_9", "test_9", "update"}));
ASSERT_TRUE(bucket_.ResetCapacity(1));
ASSERT_TRUE(bucket_.Capacity() == 1);
ASSERT_TRUE(bucket_.Size() <= 1);
ASSERT_TRUE(bucket_.Get("test_4", value));
ASSERT_TRUE(!bucket_.Get("test_9", value));
}
/**
* @tc.name: update_several
* @tc.desc: update several values and the lru chain won't change.
* @tc.type: FUNC
* @tc.require:
* @tc.author: Sven Wang
*/
HWTEST_F(LRUBucketTest, update_several, TestSize.Level0)
{
TestValue value;
std::map<std::string, TestValue> values = {{"test_2", {"test_2", "test_2", "update"}},
{"test_3", {"test_3", "test_3", "update"}},
{"test_6", {"test_6", "test_6", "update"}}};
ASSERT_TRUE(bucket_.Update(values));
ASSERT_TRUE(bucket_.ResetCapacity(3));
ASSERT_TRUE(bucket_.Capacity() == 3);
ASSERT_TRUE(bucket_.Size() <= 3);
ASSERT_TRUE(!bucket_.Get("test_2", value));
ASSERT_TRUE(!bucket_.Get("test_3", value));
ASSERT_TRUE(!bucket_.Get("test_6", value));
ASSERT_TRUE(bucket_.Get("test_9", value));
ASSERT_TRUE(bucket_.Get("test_8", value));
ASSERT_TRUE(bucket_.Get("test_7", value));
}

View File

@ -0,0 +1,26 @@
/*
* 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_FRAMEWORKS_COMMON_VISIBILITY_H
#define OHOS_DISTRIBUTED_DATA_FRAMEWORKS_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_FRAMEWORKS_COMMON_VISIBILITY_H

View File

@ -0,0 +1,129 @@
/*
* 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_FRAMEWORKS_INNERKITSIMPL_NATIVE_PREFERENCES_INCLUDE_COV_UTIL_H
#define OHOS_DISTRIBUTED_DATA_FRAMEWORKS_INNERKITSIMPL_NATIVE_PREFERENCES_INCLUDE_COV_UTIL_H
#include <string>
#include <variant>
#include <set>
#include "data_query.h"
namespace OHOS {
namespace DistributedKv {
class CovUtil final {
public:
template<typename _VTp, typename _TTp, typename _First>
static auto FillField(const std::string &field, const _VTp &data, _TTp &target)
{
return target();
}
template<typename _VTp, typename _TTp, typename _First, typename _Second, typename ..._Rest>
static auto FillField(const std::string &field, const _VTp &data, _TTp &target)
{
if ((sizeof ...(_Rest) + 1) == data.index()) {
return target(field, std::get<(sizeof ...(_Rest) + 1)>(data));
}
return FillField<_VTp, _TTp, _Second, _Rest...>(field, data, target);
}
template<typename _TTp, typename ..._Types>
static auto FillField(const std::string &field, const std::variant<_Types...> &data, _TTp &target)
{
return FillField<decltype(data), _TTp, _Types...>(field, data, target);
}
};
enum class QueryType {
EQUAL = 0,
NOT_EQUAL = 1,
GREATER = 2,
LESS = 3,
GREATER_OR_EQUAL = 4,
LESS_OR_EQUAL = 5,
IN = 6,
NOT_IN = 7
};
class Querys {
public:
Querys(OHOS::DistributedKv::DataQuery *dataQuery, QueryType type) : dataQuery_(dataQuery), type_(type) {};
template<typename T>
int operator()(const std::string &field, const T &value)
{
if (type_ == QueryType::EQUAL) {
dataQuery_->EqualTo(field, value);
} else if (type_ == QueryType::NOT_EQUAL) {
dataQuery_->NotEqualTo(field, value);
} else if (type_ == QueryType::GREATER) {
dataQuery_->GreaterThan(field, value);
} else if (type_ == QueryType::LESS) {
dataQuery_->LessThan(field, value);
} else if (type_ == QueryType::GREATER_OR_EQUAL) {
dataQuery_->GreaterThanOrEqualTo(field, value);
} else if (type_ == QueryType::LESS_OR_EQUAL) {
dataQuery_->LessThanOrEqualTo(field, value);
}
return 0;
}
template<typename T>
int operator()(const std::string &field, const std::vector<T> &value)
{
return 0;
}
int operator()()
{
return 0;
}
private:
OHOS::DistributedKv::DataQuery *dataQuery_;
QueryType type_;
};
class InOrNotIn {
public:
InOrNotIn(OHOS::DistributedKv::DataQuery *dataQuery, QueryType type) : dataQuery_(dataQuery), type_(type) {};
template<typename T>
int operator()(const std::string &field, const T &value)
{
return 0;
}
template<typename T>
int operator()(const std::string &field, const std::vector<T> &value)
{
if (type_ == QueryType::IN) {
dataQuery_->In(field, value);
} else if (type_ == QueryType::NOT_IN) {
dataQuery_->NotIn(field, value);
}
return 0;
}
int operator()()
{
return 0;
}
private:
OHOS::DistributedKv::DataQuery *dataQuery_;
QueryType type_;
};
}
}
#endif // OHOS_DISTRIBUTED_DATA_FRAMEWORKS_INNERKITSIMPL_NATIVE_PREFERENCES_INCLUDE_COV_UTIL_H

View File

@ -0,0 +1,48 @@
/*
* 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 DEV_IDEVICE_STATUS_CHANGE_LISTENER_H
#define DEV_IDEVICE_STATUS_CHANGE_LISTENER_H
#include "iremote_broker.h"
#include "iremote_proxy.h"
#include "iremote_stub.h"
#include "types.h"
namespace OHOS {
namespace DistributedKv {
class IDeviceStatusChangeListener : public IRemoteBroker {
public:
DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.DistributedKv.IDeviceStatusChangeListener");
virtual void OnChange(const DeviceInfo &results, const DeviceChangeType &type) = 0;
};
class DeviceStatusChangeListenerStub : public IRemoteStub<IDeviceStatusChangeListener> {
public:
int OnRemoteRequest(uint32_t code, MessageParcel &data,
MessageParcel &reply, MessageOption &option) override;
};
class DeviceStatusChangeListenerProxy : public IRemoteProxy<IDeviceStatusChangeListener> {
public:
explicit DeviceStatusChangeListenerProxy(const sptr<IRemoteObject> &impl);
~DeviceStatusChangeListenerProxy() = default;
void OnChange(const DeviceInfo &results, const DeviceChangeType &type) override;
private:
static inline BrokerDelegator<DeviceStatusChangeListenerProxy> delegator_;
};
} // namespace DistributedKv
} // namespace OHOS
#endif // DEV_IDEVICE_STATUS_CHANGE_LISTENER_H

View File

@ -0,0 +1,44 @@
/*
* 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 I_KVSTORE_CLIENT_DEATH_OBSERVER_H
#define I_KVSTORE_CLIENT_DEATH_OBSERVER_H
#include "iremote_broker.h"
#include "iremote_proxy.h"
#include "iremote_stub.h"
namespace OHOS {
namespace DistributedKv {
class IKvStoreClientDeathObserver : public IRemoteBroker {
public:
DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.DistributedKv.IKvStoreClientDeathObserver");
};
class KvStoreClientDeathObserverStub : public IRemoteStub<IKvStoreClientDeathObserver> {
public:
};
class KvStoreClientDeathObserverProxy : public IRemoteProxy<IKvStoreClientDeathObserver> {
public:
explicit KvStoreClientDeathObserverProxy(const sptr<IRemoteObject> &impl);
~KvStoreClientDeathObserverProxy() = default;
private:
static inline BrokerDelegator<KvStoreClientDeathObserverProxy> delegator_;
};
} // namespace DistributedKv
} // namespace OHOS
#endif // I_KVSTORE_CLIENT_DEATH_OBSERVER_H

View File

@ -0,0 +1,178 @@
/*
* 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 I_KV_STORE_DATA_SERVICE_H
#define I_KV_STORE_DATA_SERVICE_H
#include "iremote_broker.h"
#include "ikvstore_client_death_observer.h"
#include "ikvstore_observer.h"
#include "ikvstore_single.h"
#include "iremote_proxy.h"
#include "iremote_stub.h"
#include "message_parcel.h"
#include "types.h"
#include "idevice_status_change_listener.h"
namespace OHOS::DistributedKv {
/*
* IPC-friendly Options struct without std::string schema field.
* Passing a struct with an std::string field is a potential security exploit.
*
*/
struct OptionsIpc {
bool createIfMissing;
bool encrypt;
bool persistent;
bool backup;
bool autoSync;
int securityLevel;
SyncPolicy syncPolicy;
KvStoreType kvStoreType;
bool syncable; // let bms delete first
bool dataOwnership; // true indicates the ownership of distributed data is DEVICE, otherwise, ACCOUNT
};
class IKvStoreDataService : public IRemoteBroker {
public:
enum {
GETALLKVSTOREID,
CLOSEKVSTORE,
CLOSEALLKVSTORE,
DELETEKVSTORE,
DELETEALLKVSTORE,
REGISTERCLIENTDEATHOBSERVER,
GETSINGLEKVSTORE,
GETLOCALDEVICE,
GETREMOTEDEVICES,
STARTWATCHDEVICECHANGE,
STOPWATCHDEVICECHANGE,
GET_RDB_SERVICE,
GET_KVDB_SERVICE,
GET_OBJECT_SERVICE,
SERVICE_CMD_LAST,
DATAUSAGESTART = 20,
DATAUSAGEEND = 40,
};
DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.DistributedKv.IKvStoreDataService");
virtual Status GetSingleKvStore(const Options &options, const AppId &appId, const StoreId &storeId,
std::function<void(sptr<ISingleKvStore>)> callback) = 0;
/* get all kv store names */
virtual void GetAllKvStoreId(const AppId &appId, std::function<void(Status, std::vector<StoreId> &)> callback) = 0;
/* open kv store instance will not receive subscribe any more. */
virtual Status CloseKvStore(const AppId &appId, const StoreId &id) = 0;
/* close all kvstore. */
virtual Status CloseAllKvStore(const AppId &appId) = 0;
/* delete kv store */
virtual Status DeleteKvStore(const AppId &appId, const StoreId &id) = 0;
/* delete kv store */
virtual Status DeleteAllKvStore(const AppId &appId) = 0;
virtual Status RegisterClientDeathObserver(const AppId &appId, sptr<IRemoteObject> observer) = 0;
virtual Status GetLocalDevice(DeviceInfo &device) = 0;
virtual Status GetRemoteDevices(std::vector<DeviceInfo> &deviceInfoList, DeviceFilterStrategy strategy) = 0;
virtual Status StartWatchDeviceChange(sptr<IDeviceStatusChangeListener> observer,
DeviceFilterStrategy strategy) = 0;
virtual Status StopWatchDeviceChange(sptr<IDeviceStatusChangeListener> observer) = 0;
virtual sptr<IRemoteObject> GetRdbService() = 0;
virtual sptr<IRemoteObject> GetKVdbService() = 0;
virtual sptr<IRemoteObject> GetObjectService() = 0;
};
class KvStoreDataServiceStub : public IRemoteStub<IKvStoreDataService> {
public:
int OnRemoteRequest(uint32_t code, MessageParcel &data,
MessageParcel &reply, MessageOption &option) override;
private:
int32_t GetAllKvStoreIdOnRemote(MessageParcel &data, MessageParcel &reply);
int32_t CloseKvStoreOnRemote(MessageParcel &data, MessageParcel &reply);
int32_t CloseAllKvStoreOnRemote(MessageParcel &data, MessageParcel &reply);
int32_t DeleteKvStoreOnRemote(MessageParcel &data, MessageParcel &reply);
int32_t DeleteAllKvStoreOnRemote(MessageParcel &data, MessageParcel &reply);
int32_t RegisterClientDeathObserverOnRemote(MessageParcel &data, MessageParcel &reply);
int32_t GetLocalDeviceOnRemote(MessageParcel &data, MessageParcel &reply);
int32_t GetRemoteDevicesOnRemote(MessageParcel &data, MessageParcel &reply);
int32_t StartWatchDeviceChangeOnRemote(MessageParcel &data, MessageParcel &reply);
int32_t StopWatchDeviceChangeOnRemote(MessageParcel &data, MessageParcel &reply);
int32_t GetSingleKvStoreOnRemote(MessageParcel &data, MessageParcel &reply);
int32_t GetRdbServiceOnRemote(MessageParcel& data, MessageParcel& reply);
int32_t GetKVdbServiceOnRemote(MessageParcel& data, MessageParcel& reply);
int32_t GetObjectServiceOnRemote(MessageParcel &data, MessageParcel &reply);
using RequestHandler = int32_t(KvStoreDataServiceStub::*)(MessageParcel&, MessageParcel&);
static constexpr RequestHandler HANDLERS[SERVICE_CMD_LAST] = {
[GETALLKVSTOREID] = &KvStoreDataServiceStub::GetAllKvStoreIdOnRemote,
[CLOSEKVSTORE] = &KvStoreDataServiceStub::CloseKvStoreOnRemote,
[CLOSEALLKVSTORE] = &KvStoreDataServiceStub::CloseAllKvStoreOnRemote,
[DELETEKVSTORE] = &KvStoreDataServiceStub::DeleteKvStoreOnRemote,
[DELETEALLKVSTORE] = &KvStoreDataServiceStub::DeleteAllKvStoreOnRemote,
[REGISTERCLIENTDEATHOBSERVER] = &KvStoreDataServiceStub::RegisterClientDeathObserverOnRemote,
[GETSINGLEKVSTORE] = &KvStoreDataServiceStub::GetSingleKvStoreOnRemote,
[GETLOCALDEVICE] = &KvStoreDataServiceStub::GetLocalDeviceOnRemote,
[GETREMOTEDEVICES] = &KvStoreDataServiceStub::GetRemoteDevicesOnRemote,
[STARTWATCHDEVICECHANGE] = &KvStoreDataServiceStub::StartWatchDeviceChangeOnRemote,
[STOPWATCHDEVICECHANGE] = &KvStoreDataServiceStub::StopWatchDeviceChangeOnRemote,
[GET_RDB_SERVICE] = &KvStoreDataServiceStub::GetRdbServiceOnRemote,
[GET_KVDB_SERVICE] = &KvStoreDataServiceStub::GetKVdbServiceOnRemote,
[GET_OBJECT_SERVICE] = &KvStoreDataServiceStub::GetObjectServiceOnRemote,
};
};
class KvStoreDataServiceProxy : public IRemoteProxy<IKvStoreDataService> {
public:
explicit KvStoreDataServiceProxy(const sptr<IRemoteObject> &impl);
~KvStoreDataServiceProxy() = default;
virtual Status GetSingleKvStore(const Options &options, const AppId &appId, const StoreId &storeId,
std::function<void(sptr<ISingleKvStore>)> callback);
/* get all kv store names */
virtual void GetAllKvStoreId(const AppId &appId, std::function<void(Status, std::vector<StoreId> &)> callback);
/* open kv store instance will not receive subscribe any more. */
virtual Status CloseKvStore(const AppId &appId, const StoreId &storeId);
/* close all kvstore. */
virtual Status CloseAllKvStore(const AppId &appId);
/* delete kv store */
virtual Status DeleteKvStore(const AppId &appId, const StoreId &id);
/* delete kv store */
virtual Status DeleteAllKvStore(const AppId &appId);
virtual Status RegisterClientDeathObserver(const AppId &appId, sptr<IRemoteObject> observer);
virtual Status GetLocalDevice(DeviceInfo &device);
virtual Status GetRemoteDevices(std::vector<DeviceInfo> &deviceInfoList, DeviceFilterStrategy strategy);
virtual Status StartWatchDeviceChange(sptr<IDeviceStatusChangeListener> observer, DeviceFilterStrategy strategy);
virtual Status StopWatchDeviceChange(sptr<IDeviceStatusChangeListener> observer);
virtual sptr<IRemoteObject> GetRdbService();
virtual sptr<IRemoteObject> GetKVdbService();
virtual sptr<IRemoteObject> GetObjectService();
private:
static inline BrokerDelegator<KvStoreDataServiceProxy> delegator_;
};
} // namespace OHOS::DistributedKv
#endif // I_KV_STORE_DATA_SERVICE_H

View File

@ -0,0 +1,50 @@
/*
* 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 I_KVSTORE_OBSERVER_H
#define I_KVSTORE_OBSERVER_H
#include "change_notification.h"
#include "iremote_broker.h"
#include "ikvstore_observer.h"
#include "iremote_proxy.h"
#include "iremote_stub.h"
namespace OHOS {
namespace DistributedKv {
class IKvStoreObserver : public IRemoteBroker {
public:
DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.DistributedKv.IKvStoreObserver");
virtual void OnChange(const ChangeNotification &changeNotification) = 0;
};
class KvStoreObserverStub : public IRemoteStub<IKvStoreObserver> {
public:
int OnRemoteRequest(uint32_t code, MessageParcel &data,
MessageParcel &reply, MessageOption &option) override;
};
class KvStoreObserverProxy : public IRemoteProxy<IKvStoreObserver> {
public:
explicit KvStoreObserverProxy(const sptr<IRemoteObject> &impl);
~KvStoreObserverProxy() = default;
void OnChange(const ChangeNotification &changeNotification) override;
private:
static inline BrokerDelegator<KvStoreObserverProxy> delegator_;
};
} // namespace DistributedKv
} // namespace OHOS
#endif // I_KVSTORE_OBSERVER_H

View File

@ -0,0 +1,102 @@
/*
* 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 I_KVSTORE_RESULTSET_H
#define I_KVSTORE_RESULTSET_H
#include "message_parcel.h"
#include "iremote_broker.h"
#include "ikvstore_observer.h"
#include "iremote_proxy.h"
#include "iremote_stub.h"
#include "types.h"
namespace OHOS::DistributedKv {
class IKvStoreResultSet : public IRemoteBroker {
public:
DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.DistributedKv.IKvStoreResultSet")
virtual int GetCount() = 0;
virtual int GetPosition() = 0;
virtual bool MoveToFirst() = 0;
virtual bool MoveToLast() = 0;
virtual bool MoveToNext() = 0;
virtual bool MoveToPrevious() = 0;
virtual bool Move(int offset) = 0;
virtual bool MoveToPosition(int position) = 0;
virtual bool IsFirst() = 0;
virtual bool IsLast() = 0;
virtual bool IsBeforeFirst() = 0;
virtual bool IsAfterLast() = 0;
virtual Status GetEntry(Entry &entry) = 0;
};
class KvStoreResultSetStub : public IRemoteStub<IKvStoreResultSet> {
public:
int OnRemoteRequest(uint32_t code, MessageParcel &data,
MessageParcel &reply, MessageOption &option) override;
private:
int GetEntryOnRemote(MessageParcel &reply);
};
class KvStoreResultSetProxy : public IRemoteProxy<IKvStoreResultSet> {
public:
explicit KvStoreResultSetProxy(const sptr<IRemoteObject> &impl);
~KvStoreResultSetProxy() = default;
virtual int GetCount();
virtual int GetPosition();
virtual bool MoveToFirst();
virtual bool MoveToLast();
virtual bool MoveToNext();
virtual bool MoveToPrevious();
virtual bool Move(int offset);
virtual bool MoveToPosition(int position);
virtual bool IsFirst();
virtual bool IsLast();
virtual bool IsBeforeFirst();
virtual bool IsAfterLast();
virtual Status GetEntry(Entry &entry);
private:
virtual int SendRequest(uint32_t code);
virtual bool SendRequestRetBool(uint32_t code);
static inline BrokerDelegator<KvStoreResultSetProxy> delegator_;
};
} // namespace OHOS::DistributedKv
#endif // I_KVSTORE_RESULTSET_H

View File

@ -0,0 +1,214 @@
/*
* 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 I_SINGLE_KVSTORE_H
#define I_SINGLE_KVSTORE_H
#include <map>
#include "message_parcel.h"
#include "iremote_broker.h"
#include "ikvstore_observer.h"
#include "ikvstore_sync_callback.h"
#include "iremote_proxy.h"
#include "iremote_stub.h"
#include "types.h"
#include "ikvstore_resultset.h"
namespace OHOS {
namespace DistributedKv {
class ISingleKvStore : public IRemoteBroker {
public:
enum {
PUT,
DELETE,
GET,
SUBSCRIBEKVSTORE,
UNSUBSCRIBEKVSTORE,
GETENTRIES,
GETRESULTSET,
CLOSERESULTSET,
REMOVEDEVICEDATA,
SYNC,
REGISTERSYNCCALLBACK,
UNREGISTERSYNCCALLBACK,
PUTBATCH,
DELETEBATCH,
STARTTRANSACTION,
COMMIT,
ROLLBACK,
GETENTRIESWITHQUERY,
GETRESULTSETWITHQUERY,
GETCOUNTWITHQUERY,
CONTROL,
SETCAPABILITYENABLED,
SETCAPABILITYRANGE,
SETSECURITLEVEL,
SYNC_WITH_CONDITION,
SUBSCRIBE,
UNSUBSCRIBE,
SINGLE_CMD_LAST,
};
DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.DistributedKv.ISingleKvStore")
virtual Status Put(const Key &key, const Value &value) = 0;
virtual Status Delete(const Key &key) = 0;
virtual Status Get(const Key &key, Value &value) = 0;
virtual Status SubscribeKvStore(const SubscribeType subscribeType, sptr<IKvStoreObserver> observer) = 0;
virtual Status UnSubscribeKvStore(const SubscribeType subscribeType, sptr<IKvStoreObserver> observer) = 0;
virtual Status GetEntries(const Key &prefixKey, std::vector<Entry> &entries) = 0;
virtual Status GetEntriesWithQuery(const std::string &query, std::vector<Entry> &entries) = 0;
virtual void GetResultSet(const Key &prefixKey,
std::function<void(Status, sptr<IKvStoreResultSet>)> callback) = 0;
virtual void GetResultSetWithQuery(const std::string &query,
std::function<void(Status, sptr<IKvStoreResultSet>)> callback) = 0;
virtual Status CloseResultSet(sptr<IKvStoreResultSet> resultSet) = 0;
virtual Status GetCountWithQuery(const std::string &query, int &result) = 0;
virtual Status Sync(const std::vector<std::string> &deviceIds, SyncMode mode,
uint32_t allowedDelayMs, uint64_t sequenceId) = 0;
virtual Status RemoveDeviceData(const std::string &device) = 0;
virtual Status RegisterSyncCallback(sptr<IKvStoreSyncCallback> callback) = 0;
virtual Status UnRegisterSyncCallback() = 0;
virtual Status PutBatch(const std::vector<Entry> &entries) = 0;
virtual Status DeleteBatch(const std::vector<Key> &keys) = 0;
virtual Status StartTransaction() = 0;
virtual Status Commit() = 0;
virtual Status Rollback() = 0;
virtual Status Control(KvControlCmd cmd, const KvParam &inputParam, sptr<KvParam> &output) = 0;
virtual Status SetCapabilityEnabled(bool enabled) = 0;
virtual Status SetCapabilityRange(const std::vector<std::string> &localLabels,
const std::vector<std::string> &remoteSupportLabels) = 0;
virtual Status GetSecurityLevel(SecurityLevel &securityLevel) = 0;
virtual Status Sync(const std::vector<std::string> &deviceIds, SyncMode mode,
const std::string &query, uint64_t sequenceId) = 0;
virtual Status Subscribe(const std::vector<std::string> &deviceIds, const std::string &query,
uint64_t sequenceId) = 0;
virtual Status UnSubscribe(const std::vector<std::string> &deviceIds, const std::string &query,
uint64_t sequenceId) = 0;
};
class SingleKvStoreStub : public IRemoteStub<ISingleKvStore> {
public:
int OnRemoteRequest(uint32_t code, MessageParcel &data,
MessageParcel &reply, MessageOption &option) override;
private:
int PutOnRemote(MessageParcel &data, MessageParcel &reply);
int DeleteOnRemote(MessageParcel &data, MessageParcel &reply);
int GetOnRemote(MessageParcel &data, MessageParcel &reply);
int SubscribeKvStoreOnRemote(MessageParcel &data, MessageParcel &reply);
int UnSubscribeKvStoreOnRemote(MessageParcel &data, MessageParcel &reply);
int GetEntriesOnRemote(MessageParcel &data, MessageParcel &reply);
int GetEntriesWithQueryOnRemote(MessageParcel &data, MessageParcel &reply);
int SyncOnRemote(MessageParcel &data, MessageParcel &reply);
int GetResultSetOnRemote(MessageParcel &data, MessageParcel &reply);
int GetResultSetWithQueryOnRemote(MessageParcel &data, MessageParcel &reply);
int GetCountWithQueryOnRemote(MessageParcel &data, MessageParcel &reply);
int CloseResultSetOnRemote(MessageParcel &data, MessageParcel &reply);
int RemoveDeviceDataOnRemote(MessageParcel &data, MessageParcel &reply);
int RegisterSyncCallbackOnRemote(MessageParcel &data, MessageParcel &reply);
int UnRegisterSyncCallbackOnRemote(MessageParcel &data, MessageParcel &reply);
int PutBatchOnRemote(MessageParcel &data, MessageParcel &reply);
int DeleteBatchOnRemote(MessageParcel &data, MessageParcel &reply);
int StartTransactionOnRemote(MessageParcel &data, MessageParcel &reply);
int CommitOnRemote(MessageParcel &data, MessageParcel &reply);
int RollbackOnRemote(MessageParcel &data, MessageParcel &reply);
int ControlOnRemote(MessageParcel &data, MessageParcel &reply);
int OnCapabilityEnableRequest(MessageParcel &data, MessageParcel &reply);
int OnCapabilityRangeRequest(MessageParcel &data, MessageParcel &reply);
int OnSecurityLevelRequest(MessageParcel &data, MessageParcel &reply);
int OnSyncRequest(MessageParcel &data, MessageParcel &reply);
int OnSubscribeRequest(MessageParcel &data, MessageParcel &reply);
int OnUnSubscribeRequest(MessageParcel &data, MessageParcel &reply);
int WriteEntriesParcelable(MessageParcel &reply, Status status, std::vector<Entry> entries, int bufferSize);
int GetTotalEntriesSize(std::vector<Entry> entries);
using RequestHandler = int(SingleKvStoreStub::*)(MessageParcel&, MessageParcel&);
static constexpr RequestHandler HANDLERS[SINGLE_CMD_LAST] = {
[PUT] = &SingleKvStoreStub::PutOnRemote,
[DELETE] = &SingleKvStoreStub::DeleteOnRemote,
[GET] = &SingleKvStoreStub::GetOnRemote,
[SUBSCRIBEKVSTORE] = &SingleKvStoreStub::SubscribeKvStoreOnRemote,
[UNSUBSCRIBEKVSTORE] = &SingleKvStoreStub::UnSubscribeKvStoreOnRemote,
[GETENTRIES] = &SingleKvStoreStub::GetEntriesOnRemote,
[GETRESULTSET] = &SingleKvStoreStub::GetResultSetOnRemote,
[CLOSERESULTSET] = &SingleKvStoreStub::CloseResultSetOnRemote,
[REMOVEDEVICEDATA] = &SingleKvStoreStub::RemoveDeviceDataOnRemote,
[SYNC] = &SingleKvStoreStub::SyncOnRemote,
[REGISTERSYNCCALLBACK] = &SingleKvStoreStub::RegisterSyncCallbackOnRemote,
[UNREGISTERSYNCCALLBACK] = &SingleKvStoreStub::UnRegisterSyncCallbackOnRemote,
[PUTBATCH] = &SingleKvStoreStub::PutBatchOnRemote,
[DELETEBATCH] = &SingleKvStoreStub::DeleteBatchOnRemote,
[STARTTRANSACTION] = &SingleKvStoreStub::StartTransactionOnRemote,
[COMMIT] = &SingleKvStoreStub::CommitOnRemote,
[ROLLBACK] = &SingleKvStoreStub::RollbackOnRemote,
[GETENTRIESWITHQUERY] = &SingleKvStoreStub::GetEntriesWithQueryOnRemote,
[GETRESULTSETWITHQUERY] = &SingleKvStoreStub::GetResultSetWithQueryOnRemote,
[GETCOUNTWITHQUERY] = &SingleKvStoreStub::GetCountWithQueryOnRemote,
[CONTROL] = &SingleKvStoreStub::ControlOnRemote,
[SETCAPABILITYENABLED] = &SingleKvStoreStub::OnCapabilityEnableRequest,
[SETCAPABILITYRANGE] = &SingleKvStoreStub::OnCapabilityRangeRequest,
[SETSECURITLEVEL] = &SingleKvStoreStub::OnSecurityLevelRequest,
[SYNC_WITH_CONDITION] = &SingleKvStoreStub::OnSyncRequest,
[SUBSCRIBE] = &SingleKvStoreStub::OnSubscribeRequest,
[UNSUBSCRIBE] = &SingleKvStoreStub::OnUnSubscribeRequest,
};
};
class SingleKvStoreProxy : public IRemoteProxy<ISingleKvStore> {
public:
explicit SingleKvStoreProxy(const sptr<IRemoteObject> &impl);
~SingleKvStoreProxy() = default;
virtual Status Put(const Key &key, const Value &value);
virtual Status Delete(const Key &key);
virtual Status Get(const Key &key, Value &value);
virtual Status SubscribeKvStore(const SubscribeType subscribeType, sptr<IKvStoreObserver> observer);
virtual Status UnSubscribeKvStore(const SubscribeType subscribeType, sptr<IKvStoreObserver> observer);
virtual Status GetEntries(const Key &prefixKey, std::vector<Entry> &entries);
virtual Status GetEntriesWithQuery(const std::string &query, std::vector<Entry> &entries);
virtual void GetResultSet(const Key &prefixKey, std::function<void(Status, sptr<IKvStoreResultSet>)> callback);
virtual void GetResultSetWithQuery(const std::string &query,
std::function<void(Status, sptr<IKvStoreResultSet>)> callback);
virtual Status CloseResultSet(sptr<IKvStoreResultSet> resultSet);
virtual Status GetCountWithQuery(const std::string &query, int &result);
virtual Status Sync(const std::vector<std::string> &deviceIds, SyncMode mode, uint32_t allowedDelayMs,
uint64_t sequenceId);
virtual Status Sync(const std::vector<std::string> &deviceIds, SyncMode mode,
const std::string &query, uint64_t sequenceId);
virtual Status RemoveDeviceData(const std::string &device);
virtual Status RegisterSyncCallback(sptr<IKvStoreSyncCallback> callback);
virtual Status UnRegisterSyncCallback();
virtual Status PutBatch(const std::vector<Entry> &entries);
virtual Status DeleteBatch(const std::vector<Key> &keys);
virtual Status StartTransaction();
virtual Status Commit();
virtual Status Rollback();
virtual Status Control(KvControlCmd cmd, const KvParam &inputParam, sptr<KvParam> &output);
virtual Status SetCapabilityEnabled(bool enabled);
virtual Status SetCapabilityRange(const std::vector<std::string> &localLabels,
const std::vector<std::string> &remoteSupportLabels);
virtual Status GetSecurityLevel(SecurityLevel &securityLevel);
virtual Status Subscribe(const std::vector<std::string> &deviceIds, const std::string &query,
uint64_t sequenceId);
virtual Status UnSubscribe(const std::vector<std::string> &deviceIds, const std::string &query,
uint64_t sequenceId);
private:
static inline BrokerDelegator<SingleKvStoreProxy> delegator_;
};
} // namespace DistributedKv
} // namespace OHOS
#endif // I_SINGLE_KVSTORE_H

View File

@ -0,0 +1,50 @@
/*
* 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 I_KVSTORE_SYNC_CALLBACK_H
#define I_KVSTORE_SYNC_CALLBACK_H
#include <map>
#include "iremote_broker.h"
#include "iremote_proxy.h"
#include "iremote_stub.h"
#include "types.h"
namespace OHOS {
namespace DistributedKv {
class IKvStoreSyncCallback : public IRemoteBroker {
public:
DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.DistributedKv.IKvStoreSyncCallback");
virtual void SyncCompleted(const std::map<std::string, Status> &results, uint64_t sequenceId) = 0;
};
class KvStoreSyncCallbackStub : public IRemoteStub<IKvStoreSyncCallback> {
public:
int OnRemoteRequest(uint32_t code, MessageParcel &data,
MessageParcel &reply, MessageOption &option) override;
};
class KvStoreSyncCallbackProxy : public IRemoteProxy<IKvStoreSyncCallback> {
public:
explicit KvStoreSyncCallbackProxy(const sptr<IRemoteObject> &impl);
~KvStoreSyncCallbackProxy() = default;
void SyncCompleted(const std::map<std::string, Status> &results, uint64_t sequenceId) override;
private:
static inline BrokerDelegator<KvStoreSyncCallbackProxy> delegator_;
};
} // namespace DistributedKv
} // namespace OHOS
#endif // I_KVSTORE_SYNC_CALLBACK_H

View File

@ -0,0 +1,28 @@
/*
* 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 INNER_TYPES_H
#define INNER_TYPES_H
namespace OHOS {
namespace DistributedKv {
enum class InnerStatus {
SUCCESS = 0,
DECREASE_REFCOUNT,
ERROR,
};
} // namespace DistributedKv
} // namespace OHOS
#endif

View File

@ -0,0 +1,299 @@
/*
* 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 DISTRIBUTED_DATA_FRAMEWORKS_COMMON_ITYPES_UTIL_H
#define DISTRIBUTED_DATA_FRAMEWORKS_COMMON_ITYPES_UTIL_H
#include <climits>
#include <memory>
#include "change_notification.h"
#include "message_parcel.h"
#include "rdb_types.h"
#include "types.h"
namespace OHOS::DistributedKv {
class ITypesUtil final {
public:
static bool Marshal(MessageParcel &data);
static bool Unmarshal(MessageParcel &data);
static bool Marshalling(uint32_t input, MessageParcel &data);
static bool Unmarshalling(uint32_t &output, MessageParcel &data);
static bool Marshalling(int32_t input, MessageParcel &data);
static bool Unmarshalling(int32_t &output, MessageParcel &data);
static bool Marshalling(uint64_t input, MessageParcel &data);
static bool Unmarshalling(uint64_t &output, MessageParcel &data);
static bool Marshalling(const std::string &input, MessageParcel &data);
static bool Unmarshalling(std::string &output, MessageParcel &data);
static bool Marshalling(const std::vector<uint8_t> &input, MessageParcel &data);
static bool Unmarshalling(std::vector<uint8_t> &output, MessageParcel &data);
static bool Marshalling(const Blob &blob, MessageParcel &data);
static bool Unmarshalling(Blob &output, MessageParcel &data);
static bool Marshalling(const Entry &entry, MessageParcel &data);
static bool Unmarshalling(Entry &output, MessageParcel &data);
static bool Marshalling(const DeviceInfo &entry, MessageParcel &data);
static bool Unmarshalling(DeviceInfo &output, MessageParcel &data);
static bool Marshalling(const ChangeNotification &notification, MessageParcel &parcel);
static bool Unmarshalling(ChangeNotification &output, MessageParcel &parcel);
static bool Marshalling(const DistributedRdb::RdbSyncerParam &param, MessageParcel &parcel);
static bool Unmarshalling(DistributedRdb::RdbSyncerParam &param, MessageParcel &parcel);
static bool Marshalling(const DistributedRdb::SyncOption &option, MessageParcel &parcel);
static bool Unmarshalling(DistributedRdb::SyncOption &option, MessageParcel &parcel);
static bool Marshalling(const DistributedRdb::RdbPredicates &predicates, MessageParcel &parcel);
static bool Unmarshalling(DistributedRdb::RdbPredicates &predicates, MessageParcel &parcel);
static bool Marshalling(const Options &input, MessageParcel &data);
static bool Unmarshalling(Options &output, MessageParcel &data);
static bool Marshalling(const sptr<IRemoteObject> &input, MessageParcel &data);
static bool Unmarshalling(sptr<IRemoteObject> &output, MessageParcel &data);
static int64_t GetTotalSize(const std::vector<Entry> &entries);
static int64_t GetTotalSize(const std::vector<Key> &entries);
template<class T>
static bool Marshalling(const std::vector<T> &val, MessageParcel &parcel);
template<class T>
static bool Unmarshalling(std::vector<T> &val, MessageParcel &parcel);
template<class K, class V>
static bool Marshalling(const std::map<K, V> &val, MessageParcel &parcel);
template<class K, class V>
static bool Unmarshalling(std::map<K, V> &val, MessageParcel &parcel);
template<typename T, typename... Types>
static bool Marshal(MessageParcel &parcel, const T &first, const Types &...others);
template<typename T, typename... Types>
static bool Unmarshal(MessageParcel &parcel, T &first, Types &...others);
template<typename T>
static Status MarshalToBuffer(const T &input, int size, MessageParcel &data);
template<typename T>
static Status MarshalToBuffer(const std::vector<T> &input, int size, MessageParcel &data);
template<typename T>
static Status UnmarshalFromBuffer(MessageParcel &data, int size, T &output);
template<typename T>
static Status UnmarshalFromBuffer(MessageParcel &data, int size, std::vector<T> &output);
};
template<class T>
bool ITypesUtil::Marshalling(const std::vector<T> &val, MessageParcel &parcel)
{
if (val.size() > INT_MAX) {
return false;
}
if (!parcel.WriteInt32(static_cast<int32_t>(val.size()))) {
return false;
}
for (auto &v : val) {
if (!Marshalling(v, parcel)) {
return false;
}
}
return true;
}
template<class T>
bool ITypesUtil::Unmarshalling(std::vector<T> &val, MessageParcel &parcel)
{
int32_t len = parcel.ReadInt32();
if (len < 0) {
return false;
}
size_t readAbleSize = parcel.GetReadableBytes();
size_t size = static_cast<size_t>(len);
if ((size > readAbleSize) || (size > val.max_size())) {
return false;
}
val.resize(size);
if (val.size() < size) {
return false;
}
for (auto &v : val) {
if (!Unmarshalling(v, parcel)) {
return false;
}
}
return true;
}
template<typename T>
Status ITypesUtil::MarshalToBuffer(const T &input, int size, MessageParcel &data)
{
std::unique_ptr<uint8_t[]> buffer = std::make_unique<uint8_t[]>(size);
if (!data.WriteBool(buffer != nullptr)) {
return Status::IPC_ERROR;
}
if (buffer == nullptr) {
return Status::ILLEGAL_STATE;
}
int leftSize = size;
uint8_t *cursor = buffer.get();
if (!input.WriteToBuffer(cursor, leftSize)) {
return Status::IPC_ERROR;
}
return data.WriteRawData(buffer.get(), size) ? Status::SUCCESS : Status::IPC_ERROR;
}
template<typename T>
Status ITypesUtil::MarshalToBuffer(const std::vector<T> &input, int size, MessageParcel &data)
{
std::unique_ptr<uint8_t[]> buffer = std::make_unique<uint8_t[]>(size);
if (!data.WriteBool(buffer != nullptr)) {
return Status::IPC_ERROR;
}
if (buffer == nullptr) {
return Status::ILLEGAL_STATE;
}
uint8_t *cursor = buffer.get();
for (const auto &entry : input) {
if (!entry.WriteToBuffer(cursor, size)) {
return Status::IPC_ERROR;
}
}
if (!data.WriteInt32(input.size())) {
return Status::IPC_ERROR;
}
return data.WriteRawData(buffer.get(), size) ? Status::SUCCESS : Status::IPC_ERROR;
}
template<typename T>
Status ITypesUtil::UnmarshalFromBuffer(MessageParcel &data, int size, T &output)
{
if (size < 0) {
return Status::INVALID_ARGUMENT;
}
if (!data.ReadBool()) {
return Status::ILLEGAL_STATE;
}
const uint8_t *buffer = reinterpret_cast<const uint8_t *>(data.ReadRawData(size));
if (buffer == nullptr) {
return Status::INVALID_ARGUMENT;
}
return output.ReadFromBuffer(buffer, size) ? Status::SUCCESS : Status::IPC_ERROR;
}
template<typename T>
Status ITypesUtil::UnmarshalFromBuffer(MessageParcel &data, int size, std::vector<T> &output)
{
if (size < 0) {
return Status::INVALID_ARGUMENT;
}
if (!data.ReadBool()) {
return Status::ILLEGAL_STATE;
}
int count = data.ReadInt32();
const uint8_t *buffer = reinterpret_cast<const uint8_t *>(data.ReadRawData(size));
if (count < 0 || buffer == nullptr) {
return Status::INVALID_ARGUMENT;
}
output.resize(count);
for (auto &entry : output) {
if (!entry.ReadFromBuffer(buffer, size)) {
output.clear();
return Status::IPC_ERROR;
}
}
return Status::SUCCESS;
}
template<typename T, typename... Types>
bool ITypesUtil::Marshal(MessageParcel &parcel, const T &first, const Types &...others)
{
if (!Marshalling(first, parcel)) {
return false;
}
return Marshal(parcel, others...);
}
template<typename T, typename... Types>
bool ITypesUtil::Unmarshal(MessageParcel &parcel, T &first, Types &...others)
{
if (!Unmarshalling(first, parcel)) {
return false;
}
return Unmarshal(parcel, others...);
}
template<class K, class V>
bool ITypesUtil::Marshalling(const std::map<K, V> &result, MessageParcel &parcel)
{
if (!parcel.WriteInt32(static_cast<int32_t>(result.size()))) {
return false;
}
for (const auto &entry : result) {
if (!Marshalling(entry.first, parcel)) {
return false;
}
if (!Marshalling(entry.second, parcel)) {
return false;
}
}
return true;
}
template<class K, class V>
bool ITypesUtil::Unmarshalling(std::map<K, V> &val, MessageParcel &parcel)
{
int32_t size = 0;
if (!parcel.ReadInt32(size)) {
return false;
}
if (size < 0) {
return false;
}
size_t readAbleSize = parcel.GetReadableBytes();
size_t len = static_cast<size_t>(size);
if ((len > readAbleSize) || len > val.max_size()) {
return false;
}
for (int32_t i = 0; i < size; i++) {
K key;
if (!Unmarshalling(key, parcel)) {
return false;
}
V value;
if (!Unmarshalling(value, parcel)) {
return false;
}
val.insert({ key, value });
}
return true;
}
} // namespace OHOS::DistributedKv
#endif

View File

@ -0,0 +1,51 @@
/*
* 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 KVSTORE_DATASHARE_BRIDGE_H
#define KVSTORE_DATASHARE_BRIDGE_H
#include "kvstore_result_set.h"
#include "single_kvstore.h"
#include "result_set_bridge.h"
#include "datashare_errno.h"
namespace OHOS {
namespace DistributedKv {
class KvStoreDataShareBridge : public DataShare::ResultSetBridge {
public:
KvStoreDataShareBridge(std::shared_ptr<KvStoreResultSet> kvResultSet);
~KvStoreDataShareBridge() = default;
int GetRowCount(int32_t &count) override;
int GetAllColumnNames(std::vector<std::string> &columnNames) override;
bool OnGo(int32_t startRowIndex, int32_t targetRowIndex, DataShare::ResultSetBridge::Writer &writer) override;
private:
int Count();
bool FillBlock(int startRowIndex, DataShare::ResultSetBridge::Writer &writer);
static constexpr int32_t INVALID_COUNT = -1;
int32_t resultRowCount {INVALID_COUNT};
std::shared_ptr<KvStoreResultSet> kvResultSet_;
};
} // namespace DistributedKv
} // namespace OHOS
#endif // KVSTORE_DATASHARE_BRIDGE_H

View File

@ -0,0 +1,235 @@
/*
* 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 "Blob"
#include "blob.h"
#include <securec.h>
#include "log_print.h"
namespace OHOS {
namespace DistributedKv {
Blob::Blob() { }
Blob::Blob(const Blob &blob)
{
blob_ = blob.Data();
}
Blob::Blob(Blob &&blob)
{
blob_.swap(blob.blob_);
}
Blob &Blob::operator=(const Blob &blob)
{
// Self-assignment detection
if (&blob == this) {
return *this;
}
blob_ = blob.Data();
return *this;
}
Blob &Blob::operator=(Blob &&blob)
{
// Self-assignment detection
if (&blob == this) {
return *this;
}
blob_.swap(blob.blob_);
return *this;
}
Blob::Blob(const char *str, size_t n)
: blob_()
{
if (str != nullptr) {
blob_ = std::vector<uint8_t>(str, str + n);
}
}
Blob::Blob(const std::string &str)
: blob_(str.begin(), str.end())
{
}
Blob &Blob::operator=(const std::string &str)
{
blob_ = { str.begin(), str.end() };
return *this;
}
Blob::Blob(const char *str)
: blob_()
{
if (str != nullptr) {
blob_ = std::vector<uint8_t>(str, str + strlen(str));
}
}
Blob &Blob::operator=(const char *str)
{
if (str != nullptr) {
blob_ = std::vector<uint8_t>(str, str + strlen(str));
}
return *this;
}
Blob::Blob(const std::vector<uint8_t> &bytes)
: blob_(bytes)
{
}
Blob::Blob(std::vector<uint8_t> &&bytes)
: blob_(std::move(bytes))
{
}
const std::vector<uint8_t> &Blob::Data() const
{
return blob_;
}
Blob::operator const std::vector<uint8_t> &() const
{
return Data();
}
Blob::operator std::vector<uint8_t> &&() noexcept
{
return std::move(blob_);
}
size_t Blob::Size() const
{
return blob_.size();
}
int Blob::RawSize() const
{
return sizeof(int) + blob_.size();
}
bool Blob::Empty() const
{
return blob_.empty();
}
uint8_t Blob::operator[](size_t n) const
{
if (n >= Size()) {
ZLOGE("Trying to get a out-of-range Blob member.");
return 0;
}
return blob_[n];
}
bool Blob::operator==(const Blob &blob) const
{
return blob_ == blob.blob_;
}
void Blob::Clear()
{
blob_.clear();
}
std::string Blob::ToString() const
{
std::string str(blob_.begin(), blob_.end());
return str;
}
int Blob::Compare(const Blob &blob) const
{
if (blob_ < blob.blob_) {
return -1;
}
if (blob_ == blob.blob_) {
return 0;
}
return 1;
}
bool Blob::StartsWith(const Blob &blob) const
{
size_t len = blob.Size();
if (Size() < len) {
return false;
}
for (size_t i = 0; i < len; ++i) {
if (blob_[i] != blob.blob_[i]) {
return false;
}
}
return true;
}
bool Blob::Marshalling(Parcel &parcel) const
{
return parcel.WriteUInt8Vector(this->blob_);
}
Blob *Blob::Unmarshalling(Parcel &parcel)
{
std::vector<uint8_t> blobData;
if (!parcel.ReadUInt8Vector(&blobData)) {
return nullptr;
}
return new Blob(blobData);
}
/* write blob size and data to memory buffer. return error when bufferLeftSize not enough. */
bool Blob::WriteToBuffer(uint8_t *&cursorPtr, int &bufferLeftSize) const
{
if (cursorPtr == nullptr || bufferLeftSize < static_cast<int>(blob_.size() + sizeof(int))) {
return false;
}
*reinterpret_cast<int32_t *>(cursorPtr) = static_cast<int32_t>(blob_.size());
bufferLeftSize -= sizeof(int32_t);
cursorPtr += sizeof(int32_t);
errno_t err = memcpy_s(cursorPtr, bufferLeftSize, blob_.data(), blob_.size());
if (err != EOK) {
return false;
}
cursorPtr += blob_.size();
bufferLeftSize -= blob_.size();
return true;
}
/* read a blob from memory buffer. */
bool Blob::ReadFromBuffer(const uint8_t *&cursorPtr, int &bufferLeftSize)
{
if (cursorPtr == nullptr || bufferLeftSize < static_cast<int>(sizeof(int))) {
return false;
}
int blobSize = *reinterpret_cast<const int *>(cursorPtr);
bufferLeftSize -= sizeof(int) + blobSize;
if (blobSize < 0 || bufferLeftSize < 0) {
return false;
}
cursorPtr += sizeof(int);
blob_ = std::vector<uint8_t>(cursorPtr, cursorPtr + blobSize);
cursorPtr += blobSize;
return true;
}
} // namespace DistributedKv
} // namespace OHOS

View File

@ -0,0 +1,154 @@
/*
* 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 "ChangeNotification"
#include "change_notification.h"
#include "constant.h"
#include "log_print.h"
namespace OHOS {
namespace DistributedKv {
ChangeNotification::ChangeNotification(std::vector<Entry> &&insertEntries, std::vector<Entry> &&updateEntries,
std::vector<Entry> &&deleteEntries, const std::string &deviceId, bool isClear)
: insertEntries_(std::move(insertEntries)), updateEntries_(std::move(updateEntries)),
deleteEntries_(std::move(deleteEntries)), deviceId_(deviceId), isClear_(isClear)
{}
ChangeNotification::~ChangeNotification()
{}
const std::vector<Entry> &ChangeNotification::GetInsertEntries() const
{
return insertEntries_;
}
const std::vector<Entry> &ChangeNotification::GetUpdateEntries() const
{
return updateEntries_;
}
const std::vector<Entry> &ChangeNotification::GetDeleteEntries() const
{
return deleteEntries_;
}
const std::string &ChangeNotification::GetDeviceId() const
{
return deviceId_;
}
bool ChangeNotification::IsClear() const
{
return isClear_;
}
bool ChangeNotification::Marshalling(Parcel &parcel) const
{
if (!parcel.SetMaxCapacity(Constant::MAX_IPC_CAPACITY)) {
return false;
}
int32_t lenInsert = static_cast<int32_t>(insertEntries_.size());
if (!parcel.WriteInt32(lenInsert)) {
return false;
}
for (const auto &entry : insertEntries_) {
if (!parcel.WriteParcelable(&entry)) {
return false;
}
}
int32_t lenUpdate = static_cast<int32_t>(updateEntries_.size());
if (!parcel.WriteInt32(lenUpdate)) {
return false;
}
for (const auto &entry : updateEntries_) {
if (!parcel.WriteParcelable(&entry)) {
return false;
}
}
int32_t lenDelete = static_cast<int32_t>(deleteEntries_.size());
if (!parcel.WriteInt32(lenDelete)) {
return false;
}
for (const auto &entry : deleteEntries_) {
if (!parcel.WriteParcelable(&entry)) {
return false;
}
}
if (!parcel.WriteString(deviceId_)) {
ZLOGE("WriteString deviceId_ failed.");
return false;
}
return parcel.WriteBool(isClear_);
}
ChangeNotification *ChangeNotification::Unmarshalling(Parcel &parcel)
{
std::vector<Entry> insertEntries;
std::vector<Entry> updateEntries;
std::vector<Entry> deleteEntries;
int lenInsert = parcel.ReadInt32();
if (lenInsert < 0) {
ZLOGE("lenInsert is %d", lenInsert);
return nullptr;
}
for (int i = 0; i < lenInsert; i++) {
sptr<Entry> entryTmp = parcel.ReadParcelable<Entry>();
if (entryTmp != nullptr) {
insertEntries.push_back(*entryTmp);
} else {
ZLOGE("insertEntries get nullptr");
return nullptr;
}
}
int lenUpdate = parcel.ReadInt32();
if (lenUpdate < 0) {
ZLOGE("lenUpdate is %d", lenUpdate);
return nullptr;
}
for (int i = 0; i < lenUpdate; i++) {
sptr<Entry> entryTmp = parcel.ReadParcelable<Entry>();
if (entryTmp != nullptr) {
updateEntries.push_back(*entryTmp);
} else {
ZLOGE("updateEntries get nullptr");
return nullptr;
}
}
int lenDelete = parcel.ReadInt32();
if (lenDelete < 0) {
ZLOGE("lenDelete is %d", lenDelete);
return nullptr;
}
for (int i = 0; i < lenDelete; i++) {
sptr<Entry> entryTmp = parcel.ReadParcelable<Entry>();
if (entryTmp != nullptr) {
deleteEntries.push_back(*entryTmp);
} else {
ZLOGE("deleteEntries get nullptr");
return nullptr;
}
}
std::string deviceId = parcel.ReadString();
bool isClear = parcel.ReadBool();
return new(std::nothrow) ChangeNotification(std::move(insertEntries), std::move(updateEntries),
std::move(deleteEntries), deviceId, isClear);
}
} // namespace DistributedKv
} // namespace OHOS

View File

@ -0,0 +1,787 @@
/*
* 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 "DataQuery"
#include "data_query.h"
#include "log_print.h"
#include "query.h"
namespace OHOS {
namespace DistributedKv {
const char * const DataQuery::EQUAL_TO = "^EQUAL";
const char * const DataQuery::NOT_EQUAL_TO = "^NOT_EQUAL";
const char * const DataQuery::GREATER_THAN = "^GREATER";
const char * const DataQuery::LESS_THAN = "^LESS";
const char * const DataQuery::GREATER_THAN_OR_EQUAL_TO = "^GREATER_EQUAL";
const char * const DataQuery::LESS_THAN_OR_EQUAL_TO = "^LESS_EQUAL";
const char * const DataQuery::IS_NULL = "^IS_NULL";
const char * const DataQuery::IN = "^IN";
const char * const DataQuery::NOT_IN = "^NOT_IN";
const char * const DataQuery::LIKE = "^LIKE";
const char * const DataQuery::NOT_LIKE = "^NOT_LIKE";
const char * const DataQuery::AND = "^AND";
const char * const DataQuery::OR = "^OR";
const char * const DataQuery::ORDER_BY_ASC = "^ASC";
const char * const DataQuery::ORDER_BY_DESC = "^DESC";
const char * const DataQuery::LIMIT = "^LIMIT";
const char * const DataQuery::SPACE = " ";
const char * const DataQuery::SPECIAL = "^";
const char * const DataQuery::SPECIAL_ESCAPE = "(^)";
const char * const DataQuery::SPACE_ESCAPE = "^^";
const char * const DataQuery::EMPTY_STRING = "^EMPTY_STRING";
const char * const DataQuery::START_IN = "^START";
const char * const DataQuery::END_IN = "^END";
const char * const DataQuery::BEGIN_GROUP = "^BEGIN_GROUP";
const char * const DataQuery::END_GROUP = "^END_GROUP";
const char * const DataQuery::KEY_PREFIX = "^KEY_PREFIX";
const char * const DataQuery::DEVICE_ID = "^DEVICE_ID";
const char * const DataQuery::IS_NOT_NULL = "^IS_NOT_NULL";
const char * const DataQuery::TYPE_STRING = "STRING";
const char * const DataQuery::TYPE_INTEGER = "INTEGER";
const char * const DataQuery::TYPE_LONG = "LONG";
const char * const DataQuery::TYPE_DOUBLE = "DOUBLE";
const char * const DataQuery::TYPE_BOOLEAN = "BOOL";
const char * const DataQuery::VALUE_TRUE = "true";
const char * const DataQuery::VALUE_FALSE = "false";
const char * const DataQuery::SUGGEST_INDEX = "^SUGGEST_INDEX";
const char * const DataQuery::IN_KEYS = "^IN_KEYS";
constexpr int MAX_QUERY_LENGTH = 5 * 1024; // Max query string length 5k
DataQuery::DataQuery()
{
query_ = std::make_shared<DistributedDB::Query>();
}
DataQuery& DataQuery::Reset()
{
str_ = "";
hasKeys_ = false;
hasPrefix_ = false;
deviceId_ = "";
prefix_ = "";
query_ = std::make_shared<DistributedDB::Query>();
return *this;
}
DataQuery& DataQuery::EqualTo(const std::string &field, const int value)
{
std::string myField = field;
if (ValidateField(myField)) {
AppendCommon(EQUAL_TO, TYPE_INTEGER, myField, value);
query_->EqualTo(field, value);
}
return *this;
}
DataQuery& DataQuery::EqualTo(const std::string &field, const int64_t value)
{
std::string myField = field;
if (ValidateField(myField)) {
AppendCommon(EQUAL_TO, TYPE_LONG, myField, value);
query_->EqualTo(field, value);
}
return *this;
}
DataQuery& DataQuery::EqualTo(const std::string &field, const double value)
{
std::string myField = field;
if (ValidateField(myField)) {
AppendCommon(EQUAL_TO, TYPE_DOUBLE, myField, value);
query_->EqualTo(field, value);
}
return *this;
}
DataQuery& DataQuery::EqualTo(const std::string &field, const std::string &value)
{
std::string myField = field;
std::string myValue = value;
if (ValidateField(myField)) {
AppendCommonString(EQUAL_TO, TYPE_STRING, myField, myValue);
query_->EqualTo(field, value);
}
return *this;
}
DataQuery& DataQuery::EqualTo(const std::string &field, const bool value)
{
std::string myField = field;
if (ValidateField(myField)) {
AppendCommonBoolean(EQUAL_TO, TYPE_BOOLEAN, myField, value);
query_->EqualTo(field, value);
}
return *this;
}
DataQuery& DataQuery::NotEqualTo(const std::string &field, const int value)
{
std::string myField = field;
if (ValidateField(myField)) {
AppendCommon(NOT_EQUAL_TO, TYPE_INTEGER, myField, value);
query_->NotEqualTo(field, value);
}
return *this;
}
DataQuery& DataQuery::NotEqualTo(const std::string &field, const int64_t value)
{
std::string myField = field;
if (ValidateField(myField)) {
AppendCommon(NOT_EQUAL_TO, TYPE_LONG, myField, value);
query_->NotEqualTo(field, value);
}
return *this;
}
DataQuery& DataQuery::NotEqualTo(const std::string &field, const double value)
{
std::string myField = field;
if (ValidateField(myField)) {
AppendCommon(NOT_EQUAL_TO, TYPE_DOUBLE, myField, value);
query_->NotEqualTo(field, value);
}
return *this;
}
DataQuery& DataQuery::NotEqualTo(const std::string &field, const std::string &value)
{
std::string myField = field;
std::string myValue = value;
if (ValidateField(myField)) {
AppendCommonString(NOT_EQUAL_TO, TYPE_STRING, myField, myValue);
query_->NotEqualTo(field, value);
}
return *this;
}
DataQuery& DataQuery::NotEqualTo(const std::string &field, const bool value)
{
std::string myField = field;
if (ValidateField(myField)) {
AppendCommonBoolean(NOT_EQUAL_TO, TYPE_BOOLEAN, myField, value);
query_->NotEqualTo(field, value);
}
return *this;
}
DataQuery& DataQuery::GreaterThan(const std::string &field, const int value)
{
std::string myField = field;
if (ValidateField(myField)) {
AppendCommon(GREATER_THAN, TYPE_INTEGER, myField, value);
query_->GreaterThan(field, value);
}
return *this;
}
DataQuery& DataQuery::GreaterThan(const std::string &field, const int64_t value)
{
std::string myField = field;
if (ValidateField(myField)) {
AppendCommon(GREATER_THAN, TYPE_LONG, myField, value);
query_->GreaterThan(field, value);
}
return *this;
}
DataQuery& DataQuery::GreaterThan(const std::string &field, const double value)
{
std::string myField = field;
if (ValidateField(myField)) {
AppendCommon(GREATER_THAN, TYPE_DOUBLE, myField, value);
query_->GreaterThan(field, value);
}
return *this;
}
DataQuery& DataQuery::GreaterThan(const std::string &field, const std::string &value)
{
std::string myField = field;
std::string myValue = value;
if (ValidateField(myField)) {
AppendCommonString(GREATER_THAN, TYPE_STRING, myField, myValue);
query_->GreaterThan(field, value);
}
return *this;
}
DataQuery& DataQuery::LessThan(const std::string &field, const int value)
{
std::string myField = field;
if (ValidateField(myField)) {
AppendCommon(LESS_THAN, TYPE_INTEGER, myField, value);
query_->LessThan(field, value);
}
return *this;
}
DataQuery& DataQuery::LessThan(const std::string &field, const int64_t value)
{
std::string myField = field;
if (ValidateField(myField)) {
AppendCommon(LESS_THAN, TYPE_LONG, myField, value);
query_->LessThan(field, value);
}
return *this;
}
DataQuery& DataQuery::LessThan(const std::string &field, const double value)
{
std::string myField = field;
if (ValidateField(myField)) {
AppendCommon(LESS_THAN, TYPE_DOUBLE, myField, value);
query_->LessThan(field, value);
}
return *this;
}
DataQuery& DataQuery::LessThan(const std::string &field, const std::string &value)
{
std::string myField = field;
std::string myValue = value;
if (ValidateField(myField)) {
AppendCommonString(LESS_THAN, TYPE_STRING, myField, myValue);
query_->LessThan(field, value);
}
return *this;
}
DataQuery& DataQuery::GreaterThanOrEqualTo(const std::string &field, const int value)
{
std::string myField = field;
if (ValidateField(myField)) {
AppendCommon(GREATER_THAN_OR_EQUAL_TO, TYPE_INTEGER, myField, value);
query_->GreaterThanOrEqualTo(field, value);
}
return *this;
}
DataQuery& DataQuery::GreaterThanOrEqualTo(const std::string &field, const int64_t value)
{
std::string myField = field;
if (ValidateField(myField)) {
AppendCommon(GREATER_THAN_OR_EQUAL_TO, TYPE_LONG, myField, value);
query_->GreaterThanOrEqualTo(field, value);
}
return *this;
}
DataQuery& DataQuery::GreaterThanOrEqualTo(const std::string &field, const double value)
{
std::string myField = field;
if (ValidateField(myField)) {
AppendCommon(GREATER_THAN_OR_EQUAL_TO, TYPE_DOUBLE, myField, value);
query_->GreaterThanOrEqualTo(field, value);
}
return *this;
}
DataQuery& DataQuery::GreaterThanOrEqualTo(const std::string &field, const std::string &value)
{
std::string myField = field;
std::string myValue = value;
if (ValidateField(myField)) {
AppendCommonString(GREATER_THAN_OR_EQUAL_TO, TYPE_STRING, myField, myValue);
query_->GreaterThanOrEqualTo(field, value);
}
return *this;
}
DataQuery& DataQuery::LessThanOrEqualTo(const std::string &field, const int value)
{
std::string myField = field;
if (ValidateField(myField)) {
AppendCommon(LESS_THAN_OR_EQUAL_TO, TYPE_INTEGER, myField, value);
query_->LessThanOrEqualTo(field, value);
}
return *this;
}
DataQuery& DataQuery::LessThanOrEqualTo(const std::string &field, const int64_t value)
{
std::string myField = field;
if (ValidateField(myField)) {
AppendCommon(LESS_THAN_OR_EQUAL_TO, TYPE_LONG, myField, value);
query_->LessThanOrEqualTo(field, value);
}
return *this;
}
DataQuery& DataQuery::LessThanOrEqualTo(const std::string &field, const double value)
{
std::string myField = field;
if (ValidateField(myField)) {
AppendCommon(LESS_THAN_OR_EQUAL_TO, TYPE_DOUBLE, myField, value);
query_->LessThanOrEqualTo(field, value);
}
return *this;
}
DataQuery& DataQuery::LessThanOrEqualTo(const std::string &field, const std::string &value)
{
std::string myField = field;
std::string myValue = value;
if (ValidateField(myField)) {
AppendCommonString(LESS_THAN_OR_EQUAL_TO, TYPE_STRING, myField, myValue);
query_->LessThanOrEqualTo(field, value);
}
return *this;
}
DataQuery& DataQuery::IsNull(const std::string &field)
{
std::string myField = field;
if (ValidateField(myField)) {
str_.append(SPACE);
str_.append(IS_NULL);
str_.append(SPACE);
EscapeSpace(myField);
str_.append(myField);
query_->IsNull(field);
}
return *this;
}
DataQuery& DataQuery::IsNotNull(const std::string &field)
{
std::string myField = field;
if (ValidateField(myField)) {
str_.append(SPACE);
str_.append(IS_NOT_NULL);
str_.append(SPACE);
EscapeSpace(myField);
str_.append(myField);
query_->IsNotNull(field);
}
return *this;
}
DataQuery& DataQuery::In(const std::string &field, const std::vector<int> &valueList)
{
ZLOGD("DataQuery::In int");
std::string myField = field;
if (ValidateField(myField)) {
AppendCommonList(IN, TYPE_INTEGER, myField, valueList);
query_->In(field, valueList);
}
return *this;
}
DataQuery& DataQuery::In(const std::string &field, const std::vector<int64_t> &valueList)
{
ZLOGD("DataQuery::In int64_t");
std::string myField = field;
if (ValidateField(myField)) {
AppendCommonList(IN, TYPE_LONG, myField, valueList);
query_->In(field, valueList);
}
return *this;
}
DataQuery& DataQuery::In(const std::string &field, const std::vector<double> &valueList)
{
ZLOGD("DataQuery::In double");
std::string myField = field;
if (ValidateField(myField)) {
AppendCommonList(IN, TYPE_DOUBLE, myField, valueList);
query_->In(field, valueList);
}
return *this;
}
DataQuery& DataQuery::In(const std::string &field, const std::vector<std::string> &valueList)
{
ZLOGD("DataQuery::In string");
std::string myField = field;
std::vector<std::string> myValueList(valueList);
if (ValidateField(myField)) {
AppendCommonListString(IN, TYPE_STRING, myField, myValueList);
query_->In(field, valueList);
}
return *this;
}
DataQuery& DataQuery::NotIn(const std::string &field, const std::vector<int> &valueList)
{
ZLOGD("DataQuery::NotIn int");
std::string myField = field;
if (ValidateField(myField)) {
AppendCommonList(NOT_IN, TYPE_INTEGER, myField, valueList);
query_->NotIn(field, valueList);
}
return *this;
}
DataQuery& DataQuery::NotIn(const std::string &field, const std::vector<int64_t> &valueList)
{
ZLOGD("DataQuery::NotIn int64_t");
std::string myField = field;
if (ValidateField(myField)) {
AppendCommonList(NOT_IN, TYPE_LONG, myField, valueList);
query_->NotIn(field, valueList);
}
return *this;
}
DataQuery& DataQuery::NotIn(const std::string &field, const std::vector<double> &valueList)
{
ZLOGD("DataQuery::NotIn double");
std::string myField = field;
if (ValidateField(myField)) {
AppendCommonList(NOT_IN, TYPE_DOUBLE, myField, valueList);
query_->NotIn(field, valueList);
}
return *this;
}
DataQuery& DataQuery::NotIn(const std::string &field, const std::vector<std::string> &valueList)
{
ZLOGD("DataQuery::NotIn string");
std::string myField = field;
std::vector<std::string> myValueList(valueList);
if (ValidateField(myField)) {
AppendCommonListString(NOT_IN, TYPE_STRING, myField, myValueList);
query_->NotIn(field, valueList);
}
return *this;
}
DataQuery& DataQuery::Like(const std::string &field, const std::string &value)
{
std::string myField = field;
std::string myValue = value;
if (ValidateField(myField)) {
AppendCommonString(LIKE, myField, myValue);
query_->Like(field, value);
}
return *this;
}
DataQuery& DataQuery::Unlike(const std::string &field, const std::string &value)
{
std::string myField = field;
std::string myValue = value;
if (ValidateField(myField)) {
AppendCommonString(NOT_LIKE, myField, myValue);
query_->NotLike(field, value);
}
return *this;
}
DataQuery& DataQuery::And()
{
str_.append(SPACE);
str_.append(AND);
query_->And();
return *this;
}
DataQuery& DataQuery::Or()
{
str_.append(SPACE);
str_.append(OR);
query_->Or();
return *this;
}
DataQuery& DataQuery::OrderByAsc(const std::string &field)
{
std::string myField = field;
if (ValidateField(myField)) {
str_.append(SPACE);
str_.append(ORDER_BY_ASC);
str_.append(SPACE);
EscapeSpace(myField);
str_.append(myField);
query_->OrderBy(field);
}
return *this;
}
DataQuery& DataQuery::OrderByDesc(const std::string &field)
{
std::string myField = field;
if (ValidateField(myField)) {
str_.append(SPACE);
str_.append(ORDER_BY_DESC);
str_.append(SPACE);
EscapeSpace(myField);
str_.append(myField);
query_->OrderBy(field, false);
}
return *this;
}
DataQuery& DataQuery::Limit(const int number, const int offset)
{
if (number < 0 || offset < 0) {
ZLOGE("Invalid number param");
return *this;
}
str_.append(SPACE);
str_.append(LIMIT);
str_.append(SPACE);
str_.append(BasicToString(number));
str_.append(SPACE);
str_.append(BasicToString(offset));
query_->Limit(number, offset);
return *this;
}
DataQuery& DataQuery::BeginGroup()
{
str_.append(SPACE);
str_.append(BEGIN_GROUP);
query_->BeginGroup();
return *this;
}
DataQuery& DataQuery::EndGroup()
{
str_.append(SPACE);
str_.append(END_GROUP);
query_->EndGroup();
return *this;
}
DataQuery& DataQuery::KeyPrefix(const std::string &prefix)
{
std::string myPrefix = prefix;
if (ValidateField(myPrefix)) {
str_.append(SPACE);
str_.append(KEY_PREFIX);
str_.append(SPACE);
EscapeSpace(myPrefix);
str_.append(myPrefix);
prefix_ = prefix;
hasPrefix_ = true;
}
return *this;
}
DataQuery& DataQuery::DeviceId(const std::string &deviceId)
{
std::string device = deviceId;
if (ValidateField(device)) {
std::string start;
start.append(SPACE);
start.append(DEVICE_ID);
start.append(SPACE);
EscapeSpace(device);
start.append(device);
str_ = start + str_; // start with diveceId
deviceId_ = deviceId;
}
return *this;
}
DataQuery& DataQuery::SetSuggestIndex(const std::string &index)
{
std::string suggestIndex = index;
if (ValidateField(suggestIndex)) {
str_.append(SPACE);
str_.append(SUGGEST_INDEX);
str_.append(SPACE);
EscapeSpace(suggestIndex);
str_.append(suggestIndex);
query_->SuggestIndex(index);
}
return *this;
}
DataQuery& DataQuery::InKeys(const std::vector<std::string> &keys)
{
if (keys.empty()) {
ZLOGE("Invalid number param");
return *this;
}
if (hasKeys_) {
ZLOGE("cannot set inkeys more than once");
return *this;
}
hasKeys_ = true;
str_.append(SPACE);
str_.append(IN_KEYS);
str_.append(SPACE);
str_.append(START_IN);
str_.append(SPACE);
for (std::string key : keys) {
if (ValidateField(key)) {
EscapeSpace(key);
str_.append(key);
str_.append(SPACE);
}
}
str_.append(END_IN);
keys_ = keys;
return *this;
}
std::string DataQuery::ToString() const
{
if (str_.length() > MAX_QUERY_LENGTH) {
ZLOGE("Query is too long");
return std::string();
}
std::string str(str_.begin(), str_.end());
return str;
}
template<typename T>
void DataQuery::AppendCommon(const std::string &keyword, const std::string &fieldType,
std::string &field, const T &value)
{
str_.append(SPACE);
str_.append(keyword);
str_.append(SPACE);
str_.append(fieldType);
str_.append(SPACE);
EscapeSpace(field);
str_.append(field);
str_.append(SPACE);
str_.append(BasicToString(value));
}
void DataQuery::AppendCommonString(const std::string &keyword, const std::string &fieldType,
std::string &field, std::string &value)
{
str_.append(SPACE);
str_.append(keyword);
str_.append(SPACE);
str_.append(fieldType);
str_.append(SPACE);
EscapeSpace(field);
str_.append(field);
str_.append(SPACE);
EscapeSpace(value);
str_.append(value);
}
void DataQuery::AppendCommonBoolean(const std::string &keyword, const std::string &fieldType,
std::string &field, const bool &value)
{
str_.append(SPACE);
str_.append(keyword);
str_.append(SPACE);
str_.append(fieldType);
str_.append(SPACE);
EscapeSpace(field);
str_.append(field);
str_.append(SPACE);
if (value) {
str_.append(VALUE_TRUE);
} else {
str_.append(VALUE_FALSE);
}
}
void DataQuery::AppendCommonString(const std::string &keyword, std::string &field, std::string &value)
{
str_.append(SPACE);
str_.append(keyword);
str_.append(SPACE);
EscapeSpace(field);
str_.append(field);
str_.append(SPACE);
EscapeSpace(value);
str_.append(value);
}
template<typename T>
void DataQuery::AppendCommonList(const std::string &keyword, const std::string &fieldType,
std::string &field, const std::vector<T> &valueList)
{
str_.append(SPACE);
str_.append(keyword);
str_.append(SPACE);
str_.append(fieldType);
str_.append(SPACE);
EscapeSpace(field);
str_.append(field);
str_.append(SPACE);
str_.append(START_IN);
str_.append(SPACE);
for (T object : valueList) {
str_.append(BasicToString(object));
str_.append(SPACE);
}
str_.append(END_IN);
}
void DataQuery::AppendCommonListString(const std::string &keyword, const std::string &fieldType,
std::string &field, std::vector<std::string> &valueList)
{
str_.append(SPACE);
str_.append(keyword);
str_.append(SPACE);
str_.append(fieldType);
str_.append(SPACE);
EscapeSpace(field);
str_.append(field);
str_.append(SPACE);
str_.append(START_IN);
str_.append(SPACE);
for (std::string str : valueList) {
EscapeSpace(str);
str_.append(str);
str_.append(SPACE);
}
str_.append(END_IN);
}
void DataQuery::EscapeSpace(std::string &input)
{
if (input.length() == 0) {
input = EMPTY_STRING;
}
size_t index = 0; // search from the beginning of the string
while (true) {
index = input.find(DataQuery::SPECIAL, index);
if (index == std::string::npos) {
break;
}
input.replace(index, 1, DataQuery::SPECIAL_ESCAPE); // 1 char to be replaced
index += 3; // replaced with 3 chars, keep searching the remaining string
}
index = 0; // search from the beginning of the string
while (true) {
index = input.find(DataQuery::SPACE, index);
if (index == std::string::npos) {
break;
}
input.replace(index, 1, DataQuery::SPACE_ESCAPE); // 1 char to be replaced
index += 2; // replaced with 2 chars, keep searching the remaining string
}
}
bool DataQuery::ValidateField(const std::string &field)
{
if (field.empty() || field.find(DataQuery::SPECIAL) != std::string::npos) {
ZLOGE("invalid string argument");
return false;
}
return true;
}
template<typename T>
std::string DataQuery::BasicToString(const T &value)
{
std::ostringstream oss;
oss << value;
return oss.str();
}
} // namespace DistributedKv
} // namespace OHOS

View File

@ -0,0 +1,53 @@
/*
* 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_DELEGATE_MGR_CALLBACK_H
#define DISTRIBUTEDDATAMGR_DELEGATE_MGR_CALLBACK_H
#include "db_meta_callback_delegate.h"
namespace OHOS {
namespace AppDistributedKv {
class DelegateMgrCallback : public DistributedKv::DbMetaCallbackDelegate {
public:
virtual ~DelegateMgrCallback() {}
explicit DelegateMgrCallback(DistributedDB::KvStoreDelegateManager *delegate)
: delegate_(delegate) {}
bool GetKvStoreDiskSize(const std::string &storeId, uint64_t &size) override
{
if (IsDestruct()) {
return false;
}
return delegate_->GetKvStoreDiskSize(storeId, size) == DistributedDB::DBStatus::OK;
}
void GetKvStoreKeys(std::vector<DistributedKv::StoreInfo> &entries) override
{
(void) entries;
}
bool IsDestruct()
{
return delegate_ == nullptr;
}
private:
DistributedDB::KvStoreDelegateManager *delegate_ {};
};
} // namespace AppDistributedKv
} // namespace OHOS
#endif // DISTRIBUTEDDATAMGR_DELEGATE_MGR_CALLBACK_H

View File

@ -0,0 +1,30 @@
/*
* 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 "device_status_change_listener_client.h"
#include <utility>
namespace OHOS::DistributedKv {
DeviceStatusChangeListenerClient::DeviceStatusChangeListenerClient(
std::shared_ptr<DeviceStatusChangeListener> listener) : listener_(std::move(listener))
{}
void DeviceStatusChangeListenerClient::OnChange(const DeviceInfo &results, const DeviceChangeType &type)
{
if (listener_ != nullptr) {
listener_->OnDeviceChanged(results, type);
}
}
} // namespace OHOS::DistributedKv

View File

@ -0,0 +1,32 @@
/*
* 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 DEV_DEVICE_STATUS_CHANGE_LISTENER_IMPL_H
#define DEV_DEVICE_STATUS_CHANGE_LISTENER_IMPL_H
#include "idevice_status_change_listener.h"
#include "device_status_change_listener.h"
namespace OHOS::DistributedKv {
class DeviceStatusChangeListenerClient : public DeviceStatusChangeListenerStub {
public:
explicit DeviceStatusChangeListenerClient(std::shared_ptr<DeviceStatusChangeListener> listener);
void OnChange(const DeviceInfo &results, const DeviceChangeType &type) override;
~DeviceStatusChangeListenerClient() {}
private:
std::shared_ptr<DeviceStatusChangeListener> listener_;
};
}
#endif // DEV_DEVICE_STATUS_CHANGE_LISTENER_IMPL_H

View File

@ -0,0 +1,328 @@
/*
* 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 "DistributedKvDataManager"
#include "distributed_kv_data_manager.h"
#include "communication_provider.h"
#include "constant.h"
#include "dds_trace.h"
#include "device_status_change_listener_client.h"
#include "ikvstore_data_service.h"
#include "kvstore_service_death_notifier.h"
#include "log_print.h"
#include "refbase.h"
#include "single_kvstore_client.h"
#include "store_manager.h"
namespace OHOS {
namespace DistributedKv {
using namespace OHOS::DistributedDataDfx;
DistributedKvDataManager::DistributedKvDataManager()
{}
DistributedKvDataManager::~DistributedKvDataManager()
{}
Status DistributedKvDataManager::GetSingleKvStore(const Options &options, const AppId &appId, const StoreId &storeId,
std::shared_ptr<SingleKvStore> &singleKvStore)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__),
TraceSwitch::BYTRACE_ON | TraceSwitch::API_PERFORMANCE_TRACE_ON | TraceSwitch::TRACE_CHAIN_ON);
singleKvStore = nullptr;
std::string storeIdTmp = Constant::TrimCopy<std::string>(storeId.storeId);
if (storeIdTmp.size() == 0 || storeIdTmp.size() > Constant::MAX_STORE_ID_LENGTH) {
ZLOGE("invalid storeId.");
return Status::INVALID_ARGUMENT;
}
KvStoreServiceDeathNotifier::SetAppId(appId);
if (!options.baseDir.empty()) {
Status status = Status::INVALID_ARGUMENT;
singleKvStore = StoreManager::GetInstance().GetKVStore(appId, storeId, options, status);
return status;
}
sptr<IKvStoreDataService> kvDataServiceProxy = KvStoreServiceDeathNotifier::GetDistributedKvDataService();
Status status = Status::SERVER_UNAVAILABLE;
if (kvDataServiceProxy == nullptr) {
ZLOGE("proxy is nullptr.");
return status;
}
ZLOGD("call proxy.");
sptr<ISingleKvStore> proxyTmp;
status = kvDataServiceProxy->GetSingleKvStore(options, appId, storeId,
[&](sptr<ISingleKvStore> proxy) { proxyTmp = std::move(proxy); });
if (status == Status::RECOVER_SUCCESS) {
ZLOGE("proxy recover success: %d", static_cast<int>(status));
singleKvStore = std::make_shared<SingleKvStoreClient>(std::move(proxyTmp), storeIdTmp);
return status;
}
if (status != Status::SUCCESS) {
ZLOGE("proxy return error: %d", static_cast<int>(status));
return status;
}
if (proxyTmp == nullptr) {
ZLOGE("proxy return nullptr.");
return status;
}
singleKvStore = std::make_shared<SingleKvStoreClient>(std::move(proxyTmp), storeIdTmp);
return status;
}
Status DistributedKvDataManager::GetAllKvStoreId(const AppId &appId, std::vector<StoreId> &storeIds)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
KvStoreServiceDeathNotifier::SetAppId(appId);
sptr<IKvStoreDataService> kvDataServiceProxy = KvStoreServiceDeathNotifier::GetDistributedKvDataService();
if (kvDataServiceProxy == nullptr) {
ZLOGE("proxy is nullptr.");
return Status::SERVER_UNAVAILABLE;
}
Status status;
kvDataServiceProxy->GetAllKvStoreId(appId, [&status, &storeIds](auto statusTmp, auto &ids) {
status = statusTmp;
storeIds = std::move(ids);
});
return status;
}
Status DistributedKvDataManager::CloseKvStore(const AppId &appId, const StoreId &storeId)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__),
TraceSwitch::BYTRACE_ON | TraceSwitch::TRACE_CHAIN_ON);
KvStoreServiceDeathNotifier::SetAppId(appId);
std::string storeIdTmp = Constant::TrimCopy<std::string>(storeId.storeId);
if (storeIdTmp.size() == 0 || storeIdTmp.size() > Constant::MAX_STORE_ID_LENGTH) {
ZLOGE("invalid storeId.");
return Status::INVALID_ARGUMENT;
}
auto status = StoreManager::GetInstance().CloseKVStore(appId, storeId);
if (status == SUCCESS) {
return status;
}
sptr<IKvStoreDataService> kvDataServiceProxy = KvStoreServiceDeathNotifier::GetDistributedKvDataService();
if (kvDataServiceProxy != nullptr) {
return kvDataServiceProxy->CloseKvStore(appId, storeId);
}
ZLOGE("proxy is nullptr.");
return Status::SERVER_UNAVAILABLE;
}
Status DistributedKvDataManager::CloseKvStore(const AppId &appId, std::shared_ptr<SingleKvStore> &kvStorePtr)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__),
TraceSwitch::BYTRACE_ON | TraceSwitch::TRACE_CHAIN_ON);
if (kvStorePtr == nullptr) {
ZLOGE("kvStorePtr is nullptr.");
return Status::INVALID_ARGUMENT;
}
KvStoreServiceDeathNotifier::SetAppId(appId);
StoreId storeId = kvStorePtr->GetStoreId();
kvStorePtr = nullptr;
auto status = StoreManager::GetInstance().CloseKVStore(appId, storeId);
if (status == SUCCESS) {
return status;
}
sptr<IKvStoreDataService> kvDataServiceProxy = KvStoreServiceDeathNotifier::GetDistributedKvDataService();
if (kvDataServiceProxy != nullptr) {
return kvDataServiceProxy->CloseKvStore(appId, storeId);
}
ZLOGE("proxy is nullptr.");
return Status::SERVER_UNAVAILABLE;
}
Status DistributedKvDataManager::CloseAllKvStore(const AppId &appId)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__),
TraceSwitch::BYTRACE_ON | TraceSwitch::TRACE_CHAIN_ON);
KvStoreServiceDeathNotifier::SetAppId(appId);
auto status = StoreManager::GetInstance().CloseAllKVStore(appId);
Status remote = SERVER_UNAVAILABLE;
sptr<IKvStoreDataService> kvDataServiceProxy = KvStoreServiceDeathNotifier::GetDistributedKvDataService();
if (kvDataServiceProxy != nullptr) {
remote = kvDataServiceProxy->CloseAllKvStore(appId);
}
if (status != SUCCESS && status != STORE_NOT_OPEN) {
return status;
}
if (remote != SUCCESS && remote != STORE_NOT_OPEN) {
return remote;
}
if (status == STORE_NOT_OPEN && remote == STORE_NOT_OPEN) {
return STORE_NOT_OPEN;
}
return SUCCESS;
}
Status DistributedKvDataManager::DeleteKvStore(const AppId &appId, const StoreId &storeId, const std::string &path)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__),
TraceSwitch::BYTRACE_ON | TraceSwitch::TRACE_CHAIN_ON);
std::string storeIdTmp = Constant::TrimCopy<std::string>(storeId.storeId);
if (storeIdTmp.size() == 0 || storeIdTmp.size() > Constant::MAX_STORE_ID_LENGTH) {
ZLOGE("invalid storeId.");
return Status::INVALID_ARGUMENT;
}
KvStoreServiceDeathNotifier::SetAppId(appId);
if (!path.empty()) {
return StoreManager::GetInstance().Delete(appId, storeId, path);
}
sptr<IKvStoreDataService> kvDataServiceProxy = KvStoreServiceDeathNotifier::GetDistributedKvDataService();
if (kvDataServiceProxy != nullptr) {
return kvDataServiceProxy->DeleteKvStore(appId, storeId);
}
ZLOGE("proxy is nullptr.");
return Status::SERVER_UNAVAILABLE;
}
Status DistributedKvDataManager::DeleteAllKvStore(const AppId &appId, const std::string &path)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__),
TraceSwitch::BYTRACE_ON | TraceSwitch::TRACE_CHAIN_ON);
KvStoreServiceDeathNotifier::SetAppId(appId);
if (!path.empty()) {
std::vector<StoreId> storeIds;
Status status = GetAllKvStoreId(appId, storeIds);
if (status != SUCCESS) {
return status;
}
for (auto &storeId : storeIds) {
status = StoreManager::GetInstance().Delete(appId, storeId, path);
if (status != SUCCESS) {
return status;
}
}
return SUCCESS;
}
sptr<IKvStoreDataService> kvDataServiceProxy = KvStoreServiceDeathNotifier::GetDistributedKvDataService();
if (kvDataServiceProxy != nullptr) {
return kvDataServiceProxy->DeleteAllKvStore(appId);
}
ZLOGE("proxy is nullptr.");
return Status::SERVER_UNAVAILABLE;
}
void DistributedKvDataManager::RegisterKvStoreServiceDeathRecipient(
std::shared_ptr<KvStoreDeathRecipient> kvStoreDeathRecipient)
{
ZLOGD("begin");
if (kvStoreDeathRecipient == nullptr) {
ZLOGW("Register KvStoreService Death Recipient input is null.");
return;
}
KvStoreServiceDeathNotifier::AddServiceDeathWatcher(kvStoreDeathRecipient);
}
void DistributedKvDataManager::UnRegisterKvStoreServiceDeathRecipient(
std::shared_ptr<KvStoreDeathRecipient> kvStoreDeathRecipient)
{
ZLOGD("begin");
if (kvStoreDeathRecipient == nullptr) {
ZLOGW("UnRegister KvStoreService Death Recipient input is null.");
return;
}
KvStoreServiceDeathNotifier::RemoveServiceDeathWatcher(kvStoreDeathRecipient);
}
Status DistributedKvDataManager::GetLocalDevice(DeviceInfo &localDevice)
{
sptr<IKvStoreDataService> kvDataServiceProxy = KvStoreServiceDeathNotifier::GetDistributedKvDataService();
if (kvDataServiceProxy == nullptr) {
ZLOGE("proxy is nullptr.");
return Status::ERROR;
}
return kvDataServiceProxy->GetLocalDevice(localDevice);
}
Status DistributedKvDataManager::GetDeviceList(std::vector<DeviceInfo> &deviceInfoList, DeviceFilterStrategy strategy)
{
sptr<IKvStoreDataService> kvDataServiceProxy = KvStoreServiceDeathNotifier::GetDistributedKvDataService();
if (kvDataServiceProxy == nullptr) {
ZLOGE("proxy is nullptr.");
return Status::ERROR;
}
return kvDataServiceProxy->GetRemoteDevices(deviceInfoList, strategy);
}
static std::map<DeviceStatusChangeListener *, sptr<IDeviceStatusChangeListener>> deviceObservers_;
static std::mutex deviceObserversMapMutex_;
Status DistributedKvDataManager::StartWatchDeviceChange(std::shared_ptr<DeviceStatusChangeListener> observer)
{
sptr<DeviceStatusChangeListenerClient> ipcObserver = new(std::nothrow) DeviceStatusChangeListenerClient(observer);
if (ipcObserver == nullptr) {
ZLOGW("new DeviceStatusChangeListenerClient failed");
return Status::ERROR;
}
sptr<IKvStoreDataService> kvDataServiceProxy = KvStoreServiceDeathNotifier::GetDistributedKvDataService();
if (kvDataServiceProxy == nullptr) {
ZLOGE("proxy is nullptr.");
return Status::ERROR;
}
Status status = kvDataServiceProxy->StartWatchDeviceChange(ipcObserver, observer->GetFilterStrategy());
if (status == Status::SUCCESS) {
{
std::lock_guard<std::mutex> lck(deviceObserversMapMutex_);
deviceObservers_.insert({observer.get(), ipcObserver});
}
return Status::SUCCESS;
}
ZLOGE("watch failed.");
return Status::ERROR;
}
Status DistributedKvDataManager::StopWatchDeviceChange(std::shared_ptr<DeviceStatusChangeListener> observer)
{
sptr<IKvStoreDataService> kvDataServiceProxy = KvStoreServiceDeathNotifier::GetDistributedKvDataService();
if (kvDataServiceProxy == nullptr) {
ZLOGE("proxy is nullptr.");
return Status::ERROR;
}
std::lock_guard<std::mutex> lck(deviceObserversMapMutex_);
auto it = deviceObservers_.find(observer.get());
if (it == deviceObservers_.end()) {
ZLOGW(" not start watch device change.");
return Status::ERROR;
}
Status status = kvDataServiceProxy->StopWatchDeviceChange(it->second);
if (status == Status::SUCCESS) {
deviceObservers_.erase(it->first);
} else {
ZLOGW("stop watch failed code=%d.", static_cast<int>(status));
}
return status;
}
} // namespace DistributedKv
} // namespace OHOS

View File

@ -0,0 +1,77 @@
/*
* 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 "DevChangeStatusListener"
#include "idevice_status_change_listener.h"
#include <ipc_skeleton.h>
#include "log_print.h"
#include "itypes_util.h"
namespace OHOS {
namespace DistributedKv {
enum {
ONCHANGE,
};
DeviceStatusChangeListenerProxy::DeviceStatusChangeListenerProxy(const sptr<IRemoteObject> &impl)
: IRemoteProxy<IDeviceStatusChangeListener>(impl)
{}
void DeviceStatusChangeListenerProxy::OnChange(const DeviceInfo &results, const DeviceChangeType &type)
{
MessageParcel data;
MessageParcel reply;
if (!data.WriteInterfaceToken(DeviceStatusChangeListenerProxy::GetDescriptor())) {
ZLOGE("write descriptor failed");
return;
}
if (!data.WriteInt32(static_cast<int>(type)) || !ITypesUtil::Marshalling(results, data)) {
ZLOGW("SendRequest write parcel type failed.");
return;
}
MessageOption mo { MessageOption::TF_ASYNC };
int error = Remote()->SendRequest(ONCHANGE, data, reply, mo);
if (error != 0) {
ZLOGW("SendRequest failed, error %d", error);
}
}
int DeviceStatusChangeListenerStub::OnRemoteRequest(uint32_t code, MessageParcel &data,
MessageParcel &reply, MessageOption &option)
{
ZLOGD("code:%{public}u, callingPid:%{public}d", code, IPCSkeleton::GetCallingPid());
std::u16string descriptor = DeviceStatusChangeListenerStub::GetDescriptor();
std::u16string remoteDescriptor = data.ReadInterfaceToken();
if (descriptor != remoteDescriptor) {
ZLOGE("local descriptor is not equal to remote");
return -1;
}
switch (code) {
case ONCHANGE: {
DeviceChangeType type = static_cast<DeviceChangeType>(data.ReadInt32());
DeviceInfo deviceInfo;
if (ITypesUtil::Unmarshal(data, deviceInfo)) {
OnChange(deviceInfo, type);
} else {
ZLOGW("device info is null");
}
return 0;
}
default:
return IPCObjectStub::OnRemoteRequest(code, data, reply, option);
}
}
} // namespace DistributedKv
} // namespace OHOS

View File

@ -0,0 +1,24 @@
/*
* 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 "ikvstore_client_death_observer.h"
namespace OHOS {
namespace DistributedKv {
KvStoreClientDeathObserverProxy::KvStoreClientDeathObserverProxy(const sptr<IRemoteObject> &impl)
: IRemoteProxy<IKvStoreClientDeathObserver>(impl)
{}
} // namespace DistributedKv
} // namespace OHOS

View File

@ -0,0 +1,635 @@
/*
* 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 "KvStoreDataServiceProxy"
#include "ikvstore_data_service.h"
#include <ipc_skeleton.h>
#include "constant.h"
#include "irdb_service.h"
#include "rdb_service_proxy.h"
#include "itypes_util.h"
#include "message_parcel.h"
#include "types.h"
#include "log_print.h"
namespace OHOS {
namespace DistributedKv {
constexpr KvStoreDataServiceStub::RequestHandler KvStoreDataServiceStub::HANDLERS[SERVICE_CMD_LAST];
KvStoreDataServiceProxy::KvStoreDataServiceProxy(const sptr<IRemoteObject> &impl)
: IRemoteProxy<IKvStoreDataService>(impl)
{
ZLOGI("init data service proxy.");
}
Status KvStoreDataServiceProxy::GetSingleKvStore(const Options &options, const AppId &appId, const StoreId &storeId,
std::function<void(sptr<ISingleKvStore>)> callback)
{
ZLOGI("%s %s", appId.appId.c_str(), storeId.storeId.c_str());
MessageParcel data;
MessageParcel reply;
if (!data.WriteInterfaceToken(KvStoreDataServiceProxy::GetDescriptor())) {
ZLOGE("write descriptor failed");
return Status::IPC_ERROR;
}
if (!data.SetMaxCapacity(Constant::MAX_IPC_CAPACITY)) {
ZLOGW("SetMaxCapacity failed.");
return Status::IPC_ERROR;
}
// Passing a struct with an std::string field is a potential security exploit.
OptionsIpc optionsIpc;
optionsIpc.createIfMissing = options.createIfMissing;
optionsIpc.encrypt = options.encrypt;
optionsIpc.persistent = options.persistent;
optionsIpc.backup = options.backup;
optionsIpc.autoSync = options.autoSync;
optionsIpc.securityLevel = options.securityLevel;
optionsIpc.syncPolicy = options.syncPolicy;
optionsIpc.kvStoreType = options.kvStoreType;
optionsIpc.syncable = options.syncable;
std::string schemaString = options.schema;
if (!data.WriteBuffer(&optionsIpc, sizeof(OptionsIpc)) ||
!data.WriteString(appId.appId) ||
!data.WriteString(storeId.storeId) ||
!data.WriteString(schemaString)) {
ZLOGW("failed to write parcel.");
return Status::IPC_ERROR;
}
MessageOption mo { MessageOption::TF_SYNC };
int32_t error = Remote()->SendRequest(GETSINGLEKVSTORE, data, reply, mo);
if (error != 0) {
ZLOGW("failed during IPC. errCode %d", error);
return Status::IPC_ERROR;
}
Status status = static_cast<Status>(reply.ReadInt32());
if (status == Status::SUCCESS) {
sptr<IRemoteObject> remote = reply.ReadRemoteObject();
if (remote != nullptr) {
sptr<ISingleKvStore> kvstoreImplProxy = iface_cast<ISingleKvStore>(remote);
callback(std::move(kvstoreImplProxy));
}
} else {
callback(nullptr);
}
return status;
}
void KvStoreDataServiceProxy::GetAllKvStoreId(const AppId &appId,
std::function<void(Status, std::vector<StoreId> &)> callback)
{
MessageParcel data;
MessageParcel reply;
if (!data.WriteInterfaceToken(KvStoreDataServiceProxy::GetDescriptor())) {
ZLOGE("write descriptor failed");
return;
}
if (!data.WriteString(appId.appId)) {
ZLOGW("failed to write parcel.");
return;
}
std::vector<StoreId> storeIds;
MessageOption mo { MessageOption::TF_SYNC };
int32_t error = Remote()->SendRequest(GETALLKVSTOREID, data, reply, mo);
if (error != 0) {
ZLOGW("failed during IPC. errCode %d", error);
callback(Status::IPC_ERROR, storeIds);
return;
}
std::vector<std::string> stores;
reply.ReadStringVector(&stores);
for (const auto &id: stores) {
storeIds.push_back({id});
}
Status status = static_cast<Status>(reply.ReadInt32());
callback(status, storeIds);
}
Status KvStoreDataServiceProxy::CloseKvStore(const AppId &appId, const StoreId &storeId)
{
MessageParcel data;
MessageParcel reply;
if (!data.WriteInterfaceToken(KvStoreDataServiceProxy::GetDescriptor())) {
ZLOGE("write descriptor failed");
return Status::IPC_ERROR;
}
if (!data.WriteString(appId.appId) ||
!data.WriteString(storeId.storeId)) {
ZLOGW("failed to write parcel.");
return Status::IPC_ERROR;
}
MessageOption mo { MessageOption::TF_SYNC };
int32_t error = Remote()->SendRequest(CLOSEKVSTORE, data, reply, mo);
if (error != 0) {
ZLOGW("failed during IPC. errCode %d", error);
return Status::IPC_ERROR;
}
return static_cast<Status>(reply.ReadInt32());
}
/* close all opened kvstore */
Status KvStoreDataServiceProxy::CloseAllKvStore(const AppId &appId)
{
MessageParcel data;
MessageParcel reply;
if (!data.WriteInterfaceToken(KvStoreDataServiceProxy::GetDescriptor())) {
ZLOGE("write descriptor failed");
return Status::IPC_ERROR;
}
if (!data.WriteString(appId.appId)) {
ZLOGW("failed to write parcel.");
return Status::IPC_ERROR;
}
MessageOption mo { MessageOption::TF_SYNC };
int32_t error = Remote()->SendRequest(CLOSEALLKVSTORE, data, reply, mo);
if (error != 0) {
ZLOGW("failed during IPC. errCode %d", error);
return Status::IPC_ERROR;
}
return static_cast<Status>(reply.ReadInt32());
}
Status KvStoreDataServiceProxy::DeleteKvStore(const AppId &appId, const StoreId &storeId)
{
MessageParcel data;
MessageParcel reply;
if (!data.WriteInterfaceToken(KvStoreDataServiceProxy::GetDescriptor())) {
ZLOGE("write descriptor failed");
return Status::IPC_ERROR;
}
if (!data.WriteString(appId.appId) ||
!data.WriteString(storeId.storeId)) {
ZLOGW("failed to write parcel.");
return Status::IPC_ERROR;
}
MessageOption mo { MessageOption::TF_SYNC };
int32_t error = Remote()->SendRequest(DELETEKVSTORE, data, reply, mo);
if (error != 0) {
ZLOGW("failed during IPC. errCode %d", error);
return Status::IPC_ERROR;
}
return static_cast<Status>(reply.ReadInt32());
}
/* delete all kv store */
Status KvStoreDataServiceProxy::DeleteAllKvStore(const AppId &appId)
{
MessageParcel data;
MessageParcel reply;
if (!data.WriteInterfaceToken(KvStoreDataServiceProxy::GetDescriptor())) {
ZLOGE("write descriptor failed");
return Status::IPC_ERROR;
}
if (!data.WriteString(appId.appId)) {
ZLOGW("failed to write parcel.");
return Status::IPC_ERROR;
}
MessageOption mo { MessageOption::TF_SYNC };
int32_t error = Remote()->SendRequest(DELETEALLKVSTORE, data, reply, mo);
if (error != 0) {
ZLOGW("failed during IPC. errCode %d", error);
return Status::IPC_ERROR;
}
return static_cast<Status>(reply.ReadInt32());
}
Status KvStoreDataServiceProxy::RegisterClientDeathObserver(const AppId &appId, sptr<IRemoteObject> observer)
{
MessageParcel data;
MessageParcel reply;
if (!data.WriteInterfaceToken(KvStoreDataServiceProxy::GetDescriptor())) {
ZLOGE("write descriptor failed");
return Status::IPC_ERROR;
}
if (!data.WriteString(appId.appId)) {
ZLOGW("failed to write string.");
return Status::IPC_ERROR;
}
if (observer != nullptr) {
if (!data.WriteRemoteObject(observer)) {
ZLOGW("failed to write parcel.");
return Status::IPC_ERROR;
}
} else {
return Status::INVALID_ARGUMENT;
}
MessageOption mo { MessageOption::TF_SYNC };
int32_t error = Remote()->SendRequest(REGISTERCLIENTDEATHOBSERVER, data, reply, mo);
if (error != 0) {
ZLOGW("failed during IPC. errCode %d", error);
return Status::IPC_ERROR;
}
return static_cast<Status>(reply.ReadInt32());
}
Status KvStoreDataServiceProxy::GetLocalDevice(OHOS::DistributedKv::DeviceInfo &device)
{
MessageParcel data;
MessageParcel reply;
if (!data.WriteInterfaceToken(KvStoreDataServiceProxy::GetDescriptor())) {
ZLOGE("write descriptor failed");
return Status::IPC_ERROR;
}
MessageOption mo { MessageOption::TF_SYNC };
int32_t error = Remote()->SendRequest(GETLOCALDEVICE, data, reply, mo);
if (error != 0) {
ZLOGW("SendRequest returned %d", error);
return Status::IPC_ERROR;
}
Status status = static_cast<Status>(reply.ReadInt32());
if (status == Status::SUCCESS) {
device = {reply.ReadString(), reply.ReadString(), reply.ReadString()};
}
return status;
}
Status KvStoreDataServiceProxy::GetRemoteDevices(std::vector<DeviceInfo> &deviceInfoList, DeviceFilterStrategy strategy)
{
MessageParcel data;
if (!data.WriteInterfaceToken(KvStoreDataServiceProxy::GetDescriptor())) {
ZLOGE("write descriptor failed");
return Status::IPC_ERROR;
}
if (!data.WriteInt32(static_cast<int>(strategy))) {
ZLOGW("write int failed.");
return Status::IPC_ERROR;
}
MessageParcel reply;
MessageOption mo { MessageOption::TF_SYNC };
int32_t error = Remote()->SendRequest(GETREMOTEDEVICES, data, reply, mo);
if (error != 0) {
ZLOGW("SendRequest returned %d", error);
return Status::IPC_ERROR;
}
Status status = static_cast<Status>(reply.ReadInt32());
if (status == Status::SUCCESS) {
int len = reply.ReadInt32();
for (int i = 0; i < len; i++) {
DeviceInfo deviceInfo = {
.deviceId = reply.ReadString(),
.deviceName = reply.ReadString(),
.deviceType = reply.ReadString()
};
deviceInfoList.push_back(std::move(deviceInfo));
}
}
return status;
}
Status KvStoreDataServiceProxy::StartWatchDeviceChange(sptr<IDeviceStatusChangeListener> observer,
DeviceFilterStrategy strategy)
{
MessageParcel data;
if (!data.WriteInterfaceToken(KvStoreDataServiceProxy::GetDescriptor())) {
ZLOGE("write descriptor failed");
return Status::IPC_ERROR;
}
if (!data.WriteInt32(static_cast<int>(strategy))) {
ZLOGW("write int failed.");
return Status::IPC_ERROR;
}
if (observer != nullptr) {
if (!data.WriteRemoteObject(observer->AsObject().GetRefPtr())) {
return Status::IPC_ERROR;
}
} else {
return Status::INVALID_ARGUMENT;
}
MessageParcel reply;
MessageOption mo { MessageOption::TF_SYNC };
int32_t error = Remote()->SendRequest(STARTWATCHDEVICECHANGE, data, reply, mo);
if (error != 0) {
ZLOGW("SendRequest returned %d", error);
return Status::IPC_ERROR;
}
return static_cast<Status>(reply.ReadInt32());
}
Status KvStoreDataServiceProxy::StopWatchDeviceChange(sptr<IDeviceStatusChangeListener> observer)
{
MessageParcel data;
if (!data.WriteInterfaceToken(KvStoreDataServiceProxy::GetDescriptor())) {
ZLOGE("write descriptor failed");
return Status::IPC_ERROR;
}
if (observer != nullptr) {
if (!data.WriteRemoteObject(observer->AsObject().GetRefPtr())) {
return Status::IPC_ERROR;
}
} else {
return Status::INVALID_ARGUMENT;
}
MessageParcel reply;
MessageOption mo { MessageOption::TF_SYNC };
int32_t error = Remote()->SendRequest(STOPWATCHDEVICECHANGE, data, reply, mo);
if (error != 0) {
ZLOGW("SendRequest returned %d", error);
return Status::IPC_ERROR;
}
return static_cast<Status>(reply.ReadInt32());
}
sptr<IRemoteObject> KvStoreDataServiceProxy::GetRdbService()
{
ZLOGI("enter");
MessageParcel data;
if (!data.WriteInterfaceToken(KvStoreDataServiceProxy::GetDescriptor())) {
ZLOGE("write descriptor failed");
return nullptr;
}
MessageParcel reply;
MessageOption mo { MessageOption::TF_SYNC };
int32_t error = Remote()->SendRequest(GET_RDB_SERVICE, data, reply, mo);
if (error != 0) {
ZLOGE("SendRequest returned %{public}d", error);
return nullptr;
}
auto remoteObject = reply.ReadRemoteObject();
if (remoteObject == nullptr) {
ZLOGE("remote object is nullptr");
return nullptr;
}
return remoteObject;
}
sptr<IRemoteObject> KvStoreDataServiceProxy::GetObjectService()
{
ZLOGI("enter");
MessageParcel data;
if (!data.WriteInterfaceToken(KvStoreDataServiceProxy::GetDescriptor())) {
ZLOGE("write descriptor failed");
return nullptr;
}
MessageParcel reply;
MessageOption mo { MessageOption::TF_SYNC };
int32_t error = Remote()->SendRequest(GET_OBJECT_SERVICE, data, reply, mo);
if (error != 0) {
ZLOGE("SendRequest returned %{public}d", error);
return nullptr;
}
auto remoteObject = reply.ReadRemoteObject();
if (remoteObject == nullptr) {
ZLOGE("remote object is nullptr");
return nullptr;
}
return remoteObject;
}
sptr<IRemoteObject> KvStoreDataServiceProxy::GetKVdbService()
{
ZLOGI("enter");
MessageParcel data;
if (!data.WriteInterfaceToken(KvStoreDataServiceProxy::GetDescriptor())) {
ZLOGE("write descriptor failed");
return nullptr;
}
MessageParcel reply;
MessageOption mo { MessageOption::TF_SYNC };
int32_t error = Remote()->SendRequest(GET_KVDB_SERVICE, data, reply, mo);
if (error != 0) {
ZLOGE("SendRequest returned %{public}d", error);
return nullptr;
}
auto remoteObject = reply.ReadRemoteObject();
if (remoteObject == nullptr) {
ZLOGE("remote object is nullptr");
return nullptr;
}
return remoteObject;
}
int32_t KvStoreDataServiceStub::GetAllKvStoreIdOnRemote(MessageParcel &data, MessageParcel &reply)
{
AppId appId = { Constant::TrimCopy<std::string>(data.ReadString())};
std::vector<std::string> storeIdList;
Status statusTmp;
GetAllKvStoreId(appId, [&](Status status, std::vector<StoreId> &storeIds) {
for (const auto &id : storeIds) {
storeIdList.push_back(id.storeId);
}
statusTmp = status;
});
if (!reply.WriteStringVector(storeIdList)) {
return -1;
}
if (!reply.WriteInt32(static_cast<int>(statusTmp))) {
return -1;
}
return 0;
}
int32_t KvStoreDataServiceStub::GetRemoteDevicesOnRemote(MessageParcel &data, MessageParcel &reply)
{
std::vector<DeviceInfo> infos;
DeviceFilterStrategy strategy = static_cast<DeviceFilterStrategy>(data.ReadInt32());
Status status = GetRemoteDevices(infos, strategy);
if (!reply.WriteInt32(static_cast<int>(status))) {
return -1;
}
if (status == Status::SUCCESS) {
if (!reply.WriteInt32(infos.size())) {
return -1;
}
for (DeviceInfo const &info : infos) {
if (!reply.WriteString(info.deviceId) || !reply.WriteString(info.deviceName) ||
!reply.WriteString(info.deviceType)) {
return -1;
}
}
}
return 0;
}
int32_t KvStoreDataServiceStub::StartWatchDeviceChangeOnRemote(MessageParcel &data, MessageParcel &reply)
{
DeviceFilterStrategy strategy = static_cast<DeviceFilterStrategy>(data.ReadInt32());
sptr<IRemoteObject> remote = data.ReadRemoteObject();
if (remote == nullptr) {
ZLOGW("observerProxy nullptr after ipc");
if (!reply.WriteInt32(static_cast<int>(Status::IPC_ERROR))) {
return -1;
}
return 0;
}
sptr<IDeviceStatusChangeListener> observerProxy = iface_cast<IDeviceStatusChangeListener>(remote);
Status status = StartWatchDeviceChange(std::move(observerProxy), strategy);
if (!reply.WriteInt32(static_cast<int>(status))) {
return -1;
}
return 0;
}
int32_t KvStoreDataServiceStub::StopWatchDeviceChangeOnRemote(MessageParcel &data, MessageParcel &reply)
{
sptr<IRemoteObject> remote = data.ReadRemoteObject();
if (remote == nullptr) {
ZLOGW("observerProxy nullptr after ipc");
if (!reply.WriteInt32(static_cast<int>(Status::IPC_ERROR))) {
return -1;
}
return 0;
}
sptr<IDeviceStatusChangeListener> observerProxy = iface_cast<IDeviceStatusChangeListener>(remote);
Status status = StopWatchDeviceChange(std::move(observerProxy));
if (!reply.WriteInt32(static_cast<int>(status))) {
return -1;
}
return 0;
}
int32_t KvStoreDataServiceStub::GetSingleKvStoreOnRemote(MessageParcel &data, MessageParcel &reply)
{
const OptionsIpc *optionIpcPtr = reinterpret_cast<const OptionsIpc *>(data.ReadBuffer(sizeof(OptionsIpc)));
if (optionIpcPtr == nullptr) {
ZLOGW("optionPtr is nullptr");
if (!reply.WriteInt32(static_cast<int>(Status::INVALID_ARGUMENT))) {
return -1;
}
return 0;
}
OptionsIpc optionsIpc = *optionIpcPtr;
AppId appId = { Constant::TrimCopy<std::string>(data.ReadString())};
StoreId storeId = { Constant::TrimCopy<std::string>(data.ReadString())};
Options options;
options.createIfMissing = optionsIpc.createIfMissing;
options.encrypt = optionsIpc.encrypt;
options.persistent = optionsIpc.persistent;
options.backup = optionsIpc.backup;
options.autoSync = optionsIpc.autoSync;
options.securityLevel = optionsIpc.securityLevel;
options.syncPolicy = optionsIpc.syncPolicy;
options.kvStoreType = optionsIpc.kvStoreType;
options.syncable = optionsIpc.syncable;
options.schema = data.ReadString();
sptr<ISingleKvStore> proxyTmp;
Status status = GetSingleKvStore(options, appId, storeId,
[&](sptr<ISingleKvStore> proxy) { proxyTmp = std::move(proxy); });
if (!reply.WriteInt32(static_cast<int>(status))) {
return -1;
}
if (status == Status::SUCCESS && proxyTmp != nullptr) {
if (!reply.WriteRemoteObject(proxyTmp->AsObject().GetRefPtr())) {
return -1;
}
}
return 0;
}
int32_t KvStoreDataServiceStub::CloseKvStoreOnRemote(MessageParcel &data, MessageParcel &reply)
{
AppId appId = { Constant::TrimCopy<std::string>(data.ReadString())};
StoreId storeId = { Constant::TrimCopy<std::string>(data.ReadString())};
Status status = CloseKvStore(appId, storeId);
if (!reply.WriteInt32(static_cast<int>(status))) {
return -1;
}
return 0;
}
int32_t KvStoreDataServiceStub::CloseAllKvStoreOnRemote(MessageParcel &data, MessageParcel &reply)
{
AppId appId = { Constant::TrimCopy<std::string>(data.ReadString())};
Status status = CloseAllKvStore(appId);
if (!reply.WriteInt32(static_cast<int>(status))) {
return -1;
}
return 0;
}
int32_t KvStoreDataServiceStub::DeleteKvStoreOnRemote(MessageParcel &data, MessageParcel &reply)
{
AppId appId = { Constant::TrimCopy<std::string>(data.ReadString())};
StoreId storeId = { Constant::TrimCopy<std::string>(data.ReadString())};
Status status = DeleteKvStore(appId, storeId);
if (!reply.WriteInt32(static_cast<int>(status))) {
return -1;
}
return 0;
}
int32_t KvStoreDataServiceStub::DeleteAllKvStoreOnRemote(MessageParcel &data, MessageParcel &reply)
{
AppId appId = { Constant::TrimCopy<std::string>(data.ReadString())};
Status status = DeleteAllKvStore(appId);
if (!reply.WriteInt32(static_cast<int>(status))) {
return -1;
}
return 0;
}
int32_t KvStoreDataServiceStub::RegisterClientDeathObserverOnRemote(MessageParcel &data, MessageParcel &reply)
{
AppId appId = { Constant::TrimCopy<std::string>(data.ReadString())};
sptr<IRemoteObject> kvStoreClientDeathObserverProxy = data.ReadRemoteObject();
if (kvStoreClientDeathObserverProxy == nullptr) {
return -1;
}
Status status = RegisterClientDeathObserver(appId, std::move(kvStoreClientDeathObserverProxy));
if (!reply.WriteInt32(static_cast<int>(status))) {
return -1;
}
return 0;
}
int32_t KvStoreDataServiceStub::GetLocalDeviceOnRemote(MessageParcel &data, MessageParcel &reply)
{
DeviceInfo info;
Status status = GetLocalDevice(info);
if (!reply.WriteInt32(static_cast<int>(status)) || !reply.WriteString(info.deviceId) ||
!reply.WriteString(info.deviceName) || !reply.WriteString(info.deviceType)) {
return -1;
}
return 0;
}
int32_t KvStoreDataServiceStub::GetRdbServiceOnRemote(MessageParcel &data, MessageParcel &reply)
{
reply.WriteRemoteObject(GetRdbService());
return 0;
}
int32_t KvStoreDataServiceStub::GetKVdbServiceOnRemote(MessageParcel &data, MessageParcel &reply)
{
reply.WriteRemoteObject(GetKVdbService());
return 0;
}
int32_t KvStoreDataServiceStub::GetObjectServiceOnRemote(MessageParcel &data, MessageParcel &reply)
{
reply.WriteRemoteObject(GetObjectService());
return 0;
}
int32_t KvStoreDataServiceStub::OnRemoteRequest(uint32_t code, MessageParcel &data,
MessageParcel &reply, MessageOption &option)
{
ZLOGD("code:%{public}u, callingPid:%{public}d", code, IPCSkeleton::GetCallingPid());
std::u16string descriptor = KvStoreDataServiceStub::GetDescriptor();
std::u16string remoteDescriptor = data.ReadInterfaceToken();
if (descriptor != remoteDescriptor) {
ZLOGE("local descriptor is not equal to remote");
return -1;
}
if (code >= 0 && code < SERVICE_CMD_LAST) {
return (this->*HANDLERS[code])(data, reply);
} else {
MessageOption mo { MessageOption::TF_SYNC };
return IPCObjectStub::OnRemoteRequest(code, data, reply, mo);
}
}
} // namespace DistributedKv
} // namespace OHOS

View File

@ -0,0 +1,223 @@
/*
* 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 "KvStoreObserverProxy"
#include "ikvstore_observer.h"
#include <chrono>
#include <cinttypes>
#include <ipc_skeleton.h>
#include "constant.h"
#include "log_print.h"
#include "message_parcel.h"
namespace OHOS {
namespace DistributedKv {
using namespace std::chrono;
enum {
ONCHANGE,
};
KvStoreObserverProxy::KvStoreObserverProxy(const sptr<IRemoteObject> &impl) : IRemoteProxy<IKvStoreObserver>(impl)
{}
int64_t GetBufferSize(const std::vector<Entry> &entries)
{
int64_t bufferSize = 0;
for (const auto &item : entries) {
bufferSize += item.key.RawSize() + item.value.RawSize();
}
return bufferSize;
}
bool WriteEntryToParcelByBuf(MessageParcel &data, const int64_t &bufferSize, const std::vector<Entry> &list)
{
std::unique_ptr<uint8_t, void(*)(uint8_t *)> buffer(new uint8_t[bufferSize], [](uint8_t *ptr) { delete[] ptr; });
if (buffer == nullptr) {
ZLOGE("buffer is null");
return false;
}
int bufLeftSize = bufferSize;
uint8_t *cursor = buffer.get();
for (const auto &item : list) {
if (!item.key.WriteToBuffer(cursor, bufLeftSize) ||
!item.value.WriteToBuffer(cursor, bufLeftSize)) {
ZLOGE("write item to buff failed");
return false;
}
}
if (!data.WriteRawData(buffer.get(), bufferSize)) {
ZLOGE("bigDataOnchange write RawData from buff failed");
return false;
}
return true;
}
bool WriteListToParcelByBuf(MessageParcel &data, const int64_t &bufferSize, const std::vector<Entry> &list)
{
if (!data.WriteInt32(list.size()) ||
!data.WriteInt32(bufferSize)) {
ZLOGE("write entriesLen or bufferSize fails");
return false;
}
if (bufferSize == 0) {
return true;
}
if (!WriteEntryToParcelByBuf(data, bufferSize, list)) {
ZLOGE("bigDataOnchange write RawData to parcel failed");
return false;
}
return true;
}
void KvStoreObserverProxy::OnChange(const ChangeNotification &changeNotification)
{
MessageParcel data;
MessageParcel reply;
if (!data.WriteInterfaceToken(KvStoreObserverProxy::GetDescriptor())) {
ZLOGE("write descriptor failed");
return;
}
int64_t insertBufferSize = GetBufferSize(changeNotification.GetInsertEntries());
int64_t updateBufferSize = GetBufferSize(changeNotification.GetUpdateEntries());
int64_t deleteBufferSize = GetBufferSize(changeNotification.GetDeleteEntries());
int64_t totalBufferSize = insertBufferSize + updateBufferSize + deleteBufferSize + sizeof(bool);
if (!data.WriteInt32(totalBufferSize)) {
ZLOGE("Write ChangeNotification buffer size to parcel failed.");
return;
}
ZLOGD("I(%" PRId64") U(%" PRId64") D(%" PRId64") T(%" PRId64")",
insertBufferSize, updateBufferSize, deleteBufferSize, totalBufferSize);
if (totalBufferSize < Constant::SWITCH_RAW_DATA_SIZE) {
if (!data.WriteParcelable(&changeNotification)) {
ZLOGW("Write ChangeNotification to parcel failed.");
return;
}
} else {
if (!WriteListToParcelByBuf(data, insertBufferSize, changeNotification.GetInsertEntries()) ||
!WriteListToParcelByBuf(data, updateBufferSize, changeNotification.GetUpdateEntries()) ||
!WriteListToParcelByBuf(data, deleteBufferSize, changeNotification.GetDeleteEntries()) ||
!data.WriteString(changeNotification.GetDeviceId()) ||
!data.WriteBool(changeNotification.IsClear())) {
ZLOGE("WriteChangeList to Parcel by buffer failed");
return;
}
}
MessageOption mo { MessageOption::TF_WAIT_TIME };
int error = Remote()->SendRequest(ONCHANGE, data, reply, mo);
if (error != 0) {
ZLOGE("SendRequest failed, error %d", error);
}
}
bool ReadFromBuff(MessageParcel &data, const int &len, const int &bufferSize, std::vector<Entry> &entries)
{
const uint8_t *buffer = reinterpret_cast<const uint8_t *>(data.ReadRawData(bufferSize));
if (buffer == nullptr) {
ZLOGE("new buffer failed");
return false;
}
int bufferLeftSize = bufferSize;
const uint8_t *cursor = buffer;
Entry entry;
for (int i = 0; i < len; i++) {
if (!entry.key.ReadFromBuffer(cursor, bufferLeftSize) ||
!entry.value.ReadFromBuffer(cursor, bufferLeftSize)) {
ZLOGE("read key and value from buff failed");
return false;
}
entries.push_back(std::move(entry));
}
return true;
}
bool ReadListFromBuf(MessageParcel &data, std::vector<Entry> &entries)
{
int len = data.ReadInt32();
if (len < 0) {
ZLOGE("read onChangeLen failed len %d", len);
return false;
}
int bufferSize = data.ReadInt32();
if (bufferSize == 0) {
return true;
}
if (!ReadFromBuff(data, len, bufferSize, entries)) {
ZLOGE("bigDataOnchange read buff from parcel filed");
return false;
}
return true;
}
int32_t KvStoreObserverStub::OnRemoteRequest(uint32_t code, MessageParcel &data,
MessageParcel &reply, MessageOption &option)
{
ZLOGD("code:%{public}u, callingPid:%{public}d", code, IPCSkeleton::GetCallingPid());
std::u16string descriptor = KvStoreObserverStub::GetDescriptor();
std::u16string remoteDescriptor = data.ReadInterfaceToken();
if (descriptor != remoteDescriptor) {
ZLOGE("local descriptor is not equal to remote");
return -1;
}
switch (code) {
case ONCHANGE: {
const int errorResult = -1;
int totalBuffSize = data.ReadInt32();
if (totalBuffSize < Constant::SWITCH_RAW_DATA_SIZE) {
sptr<ChangeNotification> changeNotification = data.ReadParcelable<ChangeNotification>();
if (changeNotification == nullptr) {
ZLOGE("changeNotification is nullptr");
return errorResult;
}
OnChange(*changeNotification);
} else {
std::vector<Entry> insertEntries;
bool result = ReadListFromBuf(data, insertEntries);
if (!result) {
ZLOGE("read insertList from buff filed");
return errorResult;
}
std::vector<Entry> updateEntries;
result = ReadListFromBuf(data, updateEntries);
if (!result) {
ZLOGE("read updateList from buff filed");
return errorResult;
}
std::vector<Entry> deleteEntries;
result = ReadListFromBuf(data, deleteEntries);
if (!result) {
ZLOGE("read deleteList from buff filed");
return errorResult;
}
std::string deviceId = data.ReadString();
bool isClear = data.ReadBool();
ChangeNotification change(std::move(insertEntries), std::move(updateEntries), std::move(deleteEntries),
deviceId, isClear);
OnChange(change);
}
return 0;
}
default:
return IPCObjectStub::OnRemoteRequest(code, data, reply, option);
}
}
} // namespace DistributedKv
} // namespace OHOS

View File

@ -0,0 +1,367 @@
/*
* 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 "KvStoreResultSetProxy"
#include "ikvstore_resultset.h"
#include <ipc_skeleton.h>
#include "constant.h"
#include "message_parcel.h"
#include "log_print.h"
#include "itypes_util.h"
namespace OHOS::DistributedKv {
enum {
GETCOUNT,
GETPOSITION,
MOVETOFIRST,
MOVETOLAST,
MOVETONEXT,
MOVETOPREVIOUS,
MOVE,
MOVETOPOSITION,
ISFIRST,
ISLAST,
ISBEFOREFIRST,
ISAFTERLAST,
GETENTRY,
};
KvStoreResultSetProxy::KvStoreResultSetProxy(const sptr<IRemoteObject> &impl) : IRemoteProxy<IKvStoreResultSet>(impl)
{}
int KvStoreResultSetProxy::GetCount()
{
return SendRequest(GETCOUNT);
}
int KvStoreResultSetProxy::GetPosition()
{
return SendRequest(GETPOSITION);
}
bool KvStoreResultSetProxy::MoveToFirst()
{
return SendRequestRetBool(MOVETOFIRST);
}
bool KvStoreResultSetProxy::MoveToLast()
{
return SendRequestRetBool(MOVETOLAST);
}
bool KvStoreResultSetProxy::MoveToNext()
{
return SendRequestRetBool(MOVETONEXT);
}
bool KvStoreResultSetProxy::MoveToPrevious()
{
return SendRequestRetBool(MOVETOPREVIOUS);
}
bool KvStoreResultSetProxy::Move(int offset)
{
MessageParcel data, reply;
if (!data.WriteInterfaceToken(KvStoreResultSetProxy::GetDescriptor())) {
ZLOGE("write descriptor failed");
return false;
}
bool ret = data.WriteInt32(offset);
if (!ret) {
return ret;
}
MessageOption mo { MessageOption::TF_SYNC };
int32_t error = Remote()->SendRequest(MOVE, data, reply, mo);
if (error != 0) {
ZLOGW("SendRequest returned %d, code=%d", error, MOVE);
return false;
}
return reply.ReadBool();
}
bool KvStoreResultSetProxy::MoveToPosition(int position)
{
MessageParcel data, reply;
if (!data.WriteInterfaceToken(KvStoreResultSetProxy::GetDescriptor())) {
ZLOGE("write descriptor failed");
return false;
}
bool ret = data.WriteInt32(position);
if (!ret) {
return ret;
}
MessageOption mo { MessageOption::TF_SYNC };
int32_t error = Remote()->SendRequest(MOVETOPOSITION, data, reply, mo);
if (error != 0) {
ZLOGW("SendRequest returned %d, code=%d", error, MOVETOPOSITION);
return false;
}
return reply.ReadBool();
}
bool KvStoreResultSetProxy::IsFirst()
{
return SendRequestRetBool(ISFIRST);
}
bool KvStoreResultSetProxy::IsLast()
{
return SendRequestRetBool(ISLAST);
}
bool KvStoreResultSetProxy::IsBeforeFirst()
{
return SendRequestRetBool(ISBEFOREFIRST);
}
bool KvStoreResultSetProxy::IsAfterLast()
{
return SendRequestRetBool(ISAFTERLAST);
}
Status KvStoreResultSetProxy::GetEntry(Entry &entry)
{
MessageParcel data, reply;
if (!data.WriteInterfaceToken(KvStoreResultSetProxy::GetDescriptor())) {
ZLOGE("write descriptor failed");
return Status::IPC_ERROR;
}
bool ret = reply.SetMaxCapacity(Constant::MAX_IPC_CAPACITY); // 800K
if (!ret) {
ZLOGE("set max capacity failed.");
return Status::ERROR;
}
MessageOption mo { MessageOption::TF_SYNC };
ZLOGI("start");
int32_t error = Remote()->SendRequest(GETENTRY, data, reply, mo);
if (error != 0) {
ZLOGE("SendRequest failed, error is %d", error);
return Status::IPC_ERROR;
}
int32_t status = 0;
int32_t bufferSize = 0;
if (!ITypesUtil::Unmarshal(reply, status, bufferSize)) {
ZLOGE("read status or bufferSize failed");
return Status::ERROR;
}
if (bufferSize < Constant::SWITCH_RAW_DATA_SIZE) {
if (!ITypesUtil::Unmarshal(reply, entry)) {
ZLOGE("read entry failed");
return Status::ERROR;
}
return Status::SUCCESS;
}
ZLOGI("getting large data");
if (bufferSize > static_cast<int64_t>(reply.GetRawDataCapacity())) {
ZLOGW("bufferSize %d larger than message parcel limit", bufferSize);
return Status::ERROR;
}
status = ITypesUtil::UnmarshalFromBuffer(reply, bufferSize, entry);
if (status != Status::SUCCESS) {
ZLOGE("read entry failed (%{public}d).", status);
return Status::ERROR;
}
return Status::SUCCESS;
}
int KvStoreResultSetProxy::SendRequest(uint32_t code)
{
MessageParcel data, reply;
if (!data.WriteInterfaceToken(KvStoreResultSetProxy::GetDescriptor())) {
ZLOGE("write descriptor failed");
return -1;
}
MessageOption mo { MessageOption::TF_SYNC };
int32_t error = Remote()->SendRequest(code, data, reply, mo);
if (error != 0) {
ZLOGW("SendRequest returned %d, code=%d", error, code);
return -1;
}
return reply.ReadInt32();
}
bool KvStoreResultSetProxy::SendRequestRetBool(uint32_t code)
{
MessageParcel data, reply;
if (!data.WriteInterfaceToken(KvStoreResultSetProxy::GetDescriptor())) {
ZLOGE("write descriptor failed");
return false;
}
MessageOption mo { MessageOption::TF_SYNC };
int32_t error = Remote()->SendRequest(code, data, reply, mo);
if (error != 0) {
ZLOGW("SendRequestRetBool returned %d, code=%d", error, code);
return false;
}
return reply.ReadBool();
}
int KvStoreResultSetStub::GetEntryOnRemote(MessageParcel &reply)
{
if (!reply.SetMaxCapacity(Constant::MAX_IPC_CAPACITY)) {
ZLOGE("set reply MessageParcel capacity failed");
return -1;
}
Entry entry;
int32_t status = GetEntry(entry);
int32_t bufferSize = entry.RawSize();
if (!ITypesUtil::Marshal(reply, status, bufferSize)) {
ZLOGE("write status or bufferSize failed.");
return -1;
}
if (bufferSize < Constant::SWITCH_RAW_DATA_SIZE) {
if (!ITypesUtil::Marshal(reply, entry)) {
ZLOGE("write entry failed.");
return -1;
}
return 0;
}
ZLOGI("getting big data");
if (bufferSize > static_cast<int64_t>(reply.GetRawDataCapacity())) {
ZLOGW("bufferSize %d larger than message parcel limit", bufferSize);
return 0;
}
status = ITypesUtil::MarshalToBuffer(entry, bufferSize, reply);
if (status != Status::SUCCESS) {
ZLOGE("write entry failed (%{public}d).", status);
return -1;
}
return 0;
}
int KvStoreResultSetStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply,
MessageOption &option)
{
ZLOGD("code:%{public}u, callingPid:%{public}d", code, IPCSkeleton::GetCallingPid());
std::u16string descriptor = KvStoreResultSetStub::GetDescriptor();
std::u16string remoteDescriptor = data.ReadInterfaceToken();
if (descriptor != remoteDescriptor) {
ZLOGE("local descriptor is not equal to remote");
return -1;
}
switch (code) {
case GETCOUNT: {
int count = GetCount();
bool ret = reply.WriteInt32(count);
if (!ret) {
ZLOGW("ResultSet service side GetCount fail.");
}
return 0;
}
case GETPOSITION: {
int position = GetPosition();
bool ret = reply.WriteInt32(position);
if (!ret) {
ZLOGW("ResultSet service side GetPosition fail.");
}
return 0;
}
case MOVETOFIRST: {
bool isFirst = MoveToFirst();
bool ret = reply.WriteBool(isFirst);
if (!ret) {
ZLOGW("ResultSet service side GetPosition fail.");
}
return 0;
}
case MOVETOLAST: {
bool isLast = MoveToLast();
bool ret = reply.WriteBool(isLast);
if (!ret) {
ZLOGW("ResultSet service side GetPosition fail.");
}
return 0;
}
case MOVETONEXT: {
bool isNext = MoveToNext();
bool ret = reply.WriteBool(isNext);
if (!ret) {
ZLOGW("ResultSet service side MoveToNext fail.");
}
return 0;
}
case MOVETOPREVIOUS: {
bool boolRet = MoveToPrevious();
bool ret = reply.WriteBool(boolRet);
if (!ret) {
ZLOGW("ResultSet service side MoveToPrevious fail.");
}
return 0;
}
case MOVE: {
uint32_t offset = data.ReadUint32();
bool boolRet = Move(offset);
bool ret = reply.WriteBool(boolRet);
if (!ret) {
ZLOGW("ResultSet service side Move fail.");
}
return 0;
}
case MOVETOPOSITION: {
uint32_t position = data.ReadUint32();
bool boolRet = MoveToPosition(position);
bool ret = reply.WriteBool(boolRet);
if (!ret) {
ZLOGW("ResultSet service side MoveToPosition fail.");
}
return 0;
}
case ISFIRST: {
bool boolRet = IsFirst();
bool ret = reply.WriteBool(boolRet);
if (!ret) {
ZLOGW("ResultSet service side IsFirst fail.");
}
return 0;
}
case ISLAST: {
bool boolRet = IsLast();
bool ret = reply.WriteBool(boolRet);
if (!ret) {
ZLOGW("ResultSet service side IsLast fail.");
}
return 0;
}
case ISBEFOREFIRST: {
bool boolRet = IsBeforeFirst();
bool ret = reply.WriteBool(boolRet);
if (!ret) {
ZLOGW("ResultSet service side IsBeforeFirst fail.");
}
return 0;
}
case ISAFTERLAST: {
bool boolRet = IsAfterLast();
bool ret = reply.WriteBool(boolRet);
if (!ret) {
ZLOGW("ResultSet service side IsAfterLast fail.");
}
return 0;
}
case GETENTRY: {
return GetEntryOnRemote(reply);
}
default: {
ZLOGW("OnRemoteRequest default %{public}u", code);
MessageOption mo { MessageOption::TF_SYNC };
return IPCObjectStub::OnRemoteRequest(code, data, reply, mo);
}
}
}
} // namespace OHOS::DistributedKv

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,99 @@
/*
* 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 "KvStoreSyncCallbackProxy"
#include "ikvstore_sync_callback.h"
#include <chrono>
#include <ctime>
#include <ipc_skeleton.h>
#include <map>
#include "log_print.h"
#include "message_parcel.h"
#include "message_option.h"
#include "types.h"
namespace OHOS {
namespace DistributedKv {
enum {
SYNCCOMPLETED,
};
constexpr int32_t MAX_DEVICES = 4096;
KvStoreSyncCallbackProxy::KvStoreSyncCallbackProxy(const sptr<IRemoteObject> &impl)
: IRemoteProxy<IKvStoreSyncCallback>(impl)
{}
void KvStoreSyncCallbackProxy::SyncCompleted(const std::map<std::string, Status> &results, uint64_t sequenceId)
{
MessageParcel data;
MessageParcel reply;
if (!data.WriteInterfaceToken(KvStoreSyncCallbackProxy::GetDescriptor())) {
ZLOGE("write descriptor failed");
return;
}
if (!data.WriteInt32(static_cast<int>(results.size()))) {
ZLOGW("write results size error.");
return;
}
for (auto const &[k, v] : results) {
if (!data.WriteString(k) ||
!data.WriteInt32(static_cast<int>(v))) {
ZLOGW("write results error.");
return;
}
}
if (!data.WriteUint64(sequenceId)) {
ZLOGW("write label error.");
return;
}
MessageOption mo { MessageOption::TF_SYNC };
int error = Remote()->SendRequest(SYNCCOMPLETED, data, reply, mo);
if (error != 0) {
ZLOGW("SendRequest failed, error %d", error);
}
}
int32_t KvStoreSyncCallbackStub::OnRemoteRequest(uint32_t code, MessageParcel &data,
MessageParcel &reply, MessageOption &option)
{
ZLOGD("code:%{public}u, callingPid:%{public}d", code, IPCSkeleton::GetCallingPid());
std::u16string descriptor = KvStoreSyncCallbackStub::GetDescriptor();
std::u16string remoteDescriptor = data.ReadInterfaceToken();
if (descriptor != remoteDescriptor) {
ZLOGE("local descriptor is not equal to remote");
return -1;
}
switch (code) {
case SYNCCOMPLETED: {
std::map<std::string, Status> results;
int32_t size = data.ReadInt32();
if (size < 0 || size > MAX_DEVICES) {
ZLOGW("size < 0(%d)", size);
return 0;
}
for (int32_t i = 0; i < size; i++) {
results.insert(std::pair<std::string, Status>(data.ReadString(),
static_cast<Status>(data.ReadInt32())));
}
uint64_t sequenceId = data.ReadUint64();
SyncCompleted(results, sequenceId);
return 0;
}
default:
return IPCObjectStub::OnRemoteRequest(code, data, reply, option);
}
}
} // namespace DistributedKv
} // namespace OHOS

View File

@ -0,0 +1,436 @@
/*
* 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.
*/
#define LOG_TAG "ITypesUtil"
#include "itypes_util.h"
#include "iremote_object.h"
#include "autils/constant.h"
#include "log_print.h"
namespace OHOS::DistributedKv {
bool ITypesUtil::Marshal(MessageParcel &data)
{
return true;
}
bool ITypesUtil::Unmarshal(MessageParcel &data)
{
return true;
}
bool ITypesUtil::Marshalling(uint32_t input, MessageParcel &data)
{
return data.WriteUint32(input);
}
bool ITypesUtil::Unmarshalling(uint32_t &output, MessageParcel &data)
{
return data.ReadUint32(output);
}
bool ITypesUtil::Marshalling(int32_t input, MessageParcel &data)
{
return data.WriteInt32(input);
}
bool ITypesUtil::Unmarshalling(int32_t &output, MessageParcel &data)
{
return data.ReadInt32(output);
}
bool ITypesUtil::Marshalling(uint64_t input, MessageParcel &data)
{
return data.WriteUint64(input);
}
bool ITypesUtil::Unmarshalling(uint64_t &output, MessageParcel &data)
{
return data.ReadUint64(output);
}
bool ITypesUtil::Marshalling(const std::string &input, MessageParcel &data)
{
return data.WriteString(input);
}
bool ITypesUtil::Unmarshalling(std::string &output, MessageParcel &data)
{
return data.ReadString(output);
}
bool ITypesUtil::Marshalling(const std::vector<uint8_t> &input, MessageParcel &data)
{
return data.WriteUInt8Vector(input);
}
bool ITypesUtil::Unmarshalling(std::vector<uint8_t> &output, MessageParcel &data)
{
return data.ReadUInt8Vector(&output);
}
bool ITypesUtil::Marshalling(const Blob &blob, MessageParcel &data)
{
return data.WriteUInt8Vector(blob.Data());
}
bool ITypesUtil::Unmarshalling(Blob &output, MessageParcel &data)
{
std::vector<uint8_t> blob;
bool result = data.ReadUInt8Vector(&blob);
output = blob;
return result;
}
bool ITypesUtil::Marshalling(const Entry &entry, MessageParcel &data)
{
if (!Marshalling(entry.key, data)) {
return false;
}
return Marshalling(entry.value, data);
}
bool ITypesUtil::Unmarshalling(Entry &output, MessageParcel &data)
{
if (!Unmarshalling(output.key, data)) {
return false;
}
return Unmarshalling(output.value, data);
}
bool ITypesUtil::Marshalling(const DeviceInfo &entry, MessageParcel &data)
{
if (!data.WriteString(entry.deviceId)) {
return false;
}
if (!data.WriteString(entry.deviceName)) {
return false;
}
return data.WriteString(entry.deviceType);
}
bool ITypesUtil::Unmarshalling(DeviceInfo &output, MessageParcel &data)
{
if (!data.ReadString(output.deviceId)) {
return false;
}
if (!data.ReadString(output.deviceName)) {
return false;
}
return data.ReadString(output.deviceType);
}
bool ITypesUtil::Marshalling(const ChangeNotification &notification, MessageParcel &parcel)
{
if (!Marshalling(notification.GetInsertEntries(), parcel)) {
return false;
}
if (!Marshalling(notification.GetUpdateEntries(), parcel)) {
return false;
}
if (!Marshalling(notification.GetDeleteEntries(), parcel)) {
return false;
}
if (!parcel.WriteString(notification.GetDeviceId())) {
ZLOGE("WriteString deviceId_ failed.");
return false;
}
return parcel.WriteBool(notification.IsClear());
}
bool ITypesUtil::Unmarshalling(ChangeNotification &output, MessageParcel &parcel)
{
std::vector<Entry> insertEntries;
if (!Unmarshalling(insertEntries, parcel)) {
return false;
}
std::vector<Entry> updateEntries;
if (!Unmarshalling(updateEntries, parcel)) {
return false;
}
std::vector<Entry> deleteEntries;
if (!Unmarshalling(deleteEntries, parcel)) {
return false;
}
std::string deviceId;
if (!parcel.ReadString(deviceId)) {
ZLOGE("WriteString deviceId_ failed.");
return false;
}
bool isClear = false;
if (!parcel.ReadBool(isClear)) {
ZLOGE("WriteString deviceId_ failed.");
return false;
}
output = ChangeNotification(
std::move(insertEntries), std::move(updateEntries), std::move(deleteEntries), deviceId, isClear);
return true;
}
bool ITypesUtil::Marshalling(const DistributedRdb::RdbSyncerParam &param, MessageParcel &parcel)
{
if (!parcel.WriteString(param.bundleName_)) {
ZLOGE("RdbStoreParam write bundle name failed");
return false;
}
if (!parcel.WriteString(param.hapName_)) {
ZLOGE("RdbStoreParam write directory failed");
return false;
}
if (!parcel.WriteString(param.storeName_)) {
ZLOGE("RdbStoreParam write store name failed");
return false;
}
if (!parcel.WriteInt32(param.area_)) {
ZLOGE("RdbStoreParam write security level failed");
return false;
}
if (!parcel.WriteInt32(param.level_)) {
ZLOGE("RdbStoreParam write security level failed");
return false;
}
if (!parcel.WriteInt32(param.type_)) {
ZLOGE("RdbStoreParam write type failed");
return false;
}
if (!parcel.WriteBool(param.isAutoSync_)) {
ZLOGE("RdbStoreParam write auto sync failed");
return false;
}
return true;
}
bool ITypesUtil::Unmarshalling(DistributedRdb::RdbSyncerParam &param, MessageParcel &parcel)
{
if (!parcel.ReadString(param.bundleName_)) {
ZLOGE("RdbStoreParam read bundle name failed");
return false;
}
if (!parcel.ReadString(param.hapName_)) {
ZLOGE("RdbStoreParam read directory failed");
return false;
}
if (!parcel.ReadString(param.storeName_)) {
ZLOGE("RdbStoreParam read store name failed");
return false;
}
if (!parcel.ReadInt32(param.area_)) {
ZLOGE("RdbStoreParam read security level failed");
return false;
}
if (!parcel.ReadInt32(param.level_)) {
ZLOGE("RdbStoreParam read security level failed");
return false;
}
if (!parcel.ReadInt32(param.type_)) {
ZLOGE("RdbStoreParam read type failed");
return false;
}
if (!parcel.ReadBool(param.isAutoSync_)) {
ZLOGE("RdbStoreParam read auto sync failed");
return false;
}
return true;
}
bool ITypesUtil::Marshalling(const DistributedRdb::SyncOption &option, MessageParcel &parcel)
{
if (!parcel.WriteInt32(option.mode)) {
ZLOGE("SyncOption write mode failed");
return false;
}
if (!parcel.WriteBool(option.isBlock)) {
ZLOGE("SyncOption write isBlock failed");
return false;
}
return true;
}
bool ITypesUtil::Unmarshalling(DistributedRdb::SyncOption &option, MessageParcel &parcel)
{
int32_t mode;
if (!parcel.ReadInt32(mode)) {
ZLOGE("SyncOption read mode failed");
return false;
}
option.mode = static_cast<DistributedRdb::SyncMode>(mode);
if (!parcel.ReadBool(option.isBlock)) {
ZLOGE("SyncOption read isBlock failed");
return false;
}
return true;
}
bool ITypesUtil::Marshalling(const DistributedRdb::RdbPredicates &predicates, MessageParcel &parcel)
{
if (!parcel.WriteString(predicates.table_)) {
ZLOGE("predicate write table failed");
return false;
}
if (!parcel.WriteStringVector(predicates.devices_)) {
ZLOGE("predicate write devices failed");
return false;
}
if (!parcel.WriteUint32(predicates.operations_.size())) {
ZLOGE("predicate write operation size failed");
return false;
}
for (const auto &operation : predicates.operations_) {
if (!parcel.WriteInt32(operation.operator_)) {
ZLOGE("predicate write operator failed");
return false;
}
if (!parcel.WriteString(operation.field_)) {
ZLOGE("predicate write field failed");
return false;
}
if (!parcel.WriteStringVector(operation.values_)) {
ZLOGE("predicate write values failed");
return false;
}
}
return true;
}
bool ITypesUtil::Unmarshalling(DistributedRdb::RdbPredicates &predicates, MessageParcel &parcel)
{
if (!parcel.ReadString(predicates.table_)) {
ZLOGE("predicate read table failed");
return false;
}
if (!parcel.ReadStringVector(&predicates.devices_)) {
ZLOGE("predicate read devices failed");
return false;
}
uint32_t size = 0;
if (!parcel.ReadUint32(size)) {
ZLOGE("predicate read operation size failed");
return false;
}
for (uint32_t i = 0; i < size; i++) {
int32_t op;
if (!parcel.ReadInt32(op)) {
ZLOGE("predicate read operator failed");
return false;
}
DistributedRdb::RdbPredicateOperation operation;
operation.operator_ = static_cast<DistributedRdb::RdbPredicateOperator>(op);
if (!parcel.ReadString(operation.field_)) {
ZLOGE("predicate read field failed");
return false;
}
if (!parcel.ReadStringVector(&operation.values_)) {
ZLOGE("predicate read values failed");
return false;
}
predicates.operations_.push_back(std::move(operation));
}
return true;
}
bool ITypesUtil::Marshalling(const Options &input, MessageParcel &data)
{
if (!data.WriteString(input.schema)) {
ZLOGE("schema is failed");
return false;
}
if (!data.WriteString(input.hapName)) {
ZLOGE("hapName is failed");
return false;
}
std::unique_ptr<uint8_t[]> buffer = std::make_unique<uint8_t[]>(sizeof(input));
Options *target = reinterpret_cast<Options *>(buffer.get());
target->createIfMissing = input.createIfMissing;
target->encrypt = input.encrypt;
target->persistent = input.persistent;
target->backup = input.backup;
target->autoSync = input.autoSync;
target->syncable = input.syncable;
target->securityLevel = input.securityLevel;
target->area = input.area;
target->syncPolicy = input.syncPolicy;
target->kvStoreType = input.kvStoreType;
return data.WriteRawData(buffer.get(), sizeof(input));
}
bool ITypesUtil::Unmarshalling(Options &output, MessageParcel &data)
{
if (!data.ReadString(output.schema)) {
ZLOGE("read schema failed");
return false;
}
if (!data.ReadString(output.hapName)) {
ZLOGE("read hapName failed");
return false;
}
const Options *source = reinterpret_cast<const Options *>(data.ReadRawData(sizeof(output)));
if (source == nullptr) {
return false;
}
output.createIfMissing = source->createIfMissing;
output.encrypt = source->encrypt;
output.persistent = source->persistent;
output.backup = source->backup;
output.autoSync = source->autoSync;
output.securityLevel = source->securityLevel;
output.area = source->area;
output.syncPolicy = source->syncPolicy;
output.kvStoreType = source->kvStoreType;
output.syncable = source->syncable;
return true;
}
bool ITypesUtil::Marshalling(const sptr<IRemoteObject> &input, MessageParcel &data)
{
return data.WriteRemoteObject(input);
}
bool ITypesUtil::Unmarshalling(sptr<IRemoteObject> &output, MessageParcel &data)
{
output = data.ReadRemoteObject();
return true;
}
int64_t ITypesUtil::GetTotalSize(const std::vector<Entry> &entries)
{
int64_t bufferSize = 1;
for (const auto &item : entries) {
if (item.key.Size() > Constant::MAX_KEY_LENGTH || item.value.Size() > Constant::MAX_VALUE_LENGTH) {
return -bufferSize;
}
bufferSize += item.key.RawSize() + item.value.RawSize();
}
return bufferSize - 1;
}
int64_t ITypesUtil::GetTotalSize(const std::vector<Key> &entries)
{
int64_t bufferSize = 1;
for (const auto &item : entries) {
if (item.Size() > Constant::MAX_KEY_LENGTH) {
return -bufferSize;
}
bufferSize += item.RawSize();
}
return bufferSize - 1;
}
} // namespace OHOS::DistributedKv

View File

@ -0,0 +1,262 @@
/*
* 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.
*/
#define LOG_TAG "KvUtils"
#include "kv_utils.h"
#include <endian.h>
#include "cov_util.h"
#include "log_print.h"
#include "data_query.h"
#include "kvstore_datashare_bridge.h"
namespace OHOS {
namespace DistributedKv {
using namespace DataShare;
using namespace DistributedData;
const std::string KvUtils::KEY = "key";
const std::string KvUtils::VALUE = "value";
constexpr KvUtils::QueryHandler KvUtils::HANDLERS[LAST_TYPE];
std::shared_ptr<ResultSetBridge> KvUtils::ToResultSetBridge(std::shared_ptr<KvStoreResultSet> resultSet)
{
if (resultSet == nullptr) {
ZLOGE("param error, kvResultSet nullptr");
return nullptr;
}
return std::make_shared<KvStoreDataShareBridge>(resultSet);
}
Status KvUtils::ToQuery(const DataShareAbsPredicates &predicates, DataQuery &query)
{
const auto &operations = predicates.GetOperationList();
for (const auto &oper : operations) {
if (oper.operation < 0 || oper.operation >= LAST_TYPE) {
ZLOGE("operation param error");
return Status::NOT_SUPPORT;
}
(*HANDLERS[oper.operation])(oper, query);
}
return Status::SUCCESS;
}
std::vector<Entry> KvUtils::ToEntries(const std::vector<DataShareValuesBucket> &valueBuckets)
{
std::vector<Entry> entries;
for (const auto &val : valueBuckets) {
Entry entry = ToEntry(val);
entries.push_back(entry);
}
return entries;
}
Entry KvUtils::ToEntry(const DataShareValuesBucket &valueBucket)
{
const auto &values = valueBucket.valuesMap;
if (values.empty()) {
ZLOGE("valuesMap is null");
return {};
}
Entry entry;
Status status = ToEntryData(values, KEY, entry.key);
if (status != Status::SUCCESS) {
ZLOGE("GetEntry key failed: %{public}d", status);
return {};
}
status = ToEntryData(values, VALUE, entry.value);
if (status != Status::SUCCESS) {
ZLOGE("GetEntry value failed: %{public}d", status);
return {};
}
return entry;
}
Status KvUtils::GetKeys(const DataShareAbsPredicates &predicates, std::vector<Key> &keys)
{
const auto &operations = predicates.GetOperationList();
if (operations.empty()) {
ZLOGE("operations is null");
return Status::ERROR;
}
std::vector<std::string> myKeys;
for (const auto &oper : operations) {
if (oper.operation != IN_KEY) {
ZLOGE("find operation failed");
return Status::NOT_SUPPORT;
}
std::vector<std::string> val = oper.para1;
myKeys.insert(myKeys.end(), val.begin(), val.end());
}
for (const auto &it : myKeys) {
keys.push_back(it.c_str());
}
return Status::SUCCESS;
}
Status KvUtils::ToEntryData(const std::map<std::string, DataShareValueObject> &valuesMap,
const std::string field, Blob &blob)
{
auto it = valuesMap.find(field);
if (it == valuesMap.end()) {
ZLOGE("field is not find!");
return Status::ERROR;
}
DataShareValueObjectType type = it->second.type;
std::vector<uint8_t> uData;
if (type == DataShareValueObjectType::TYPE_BLOB) {
ZLOGE("Value bucket type blob");
std::vector<uint8_t> data = it->second;
uData.push_back(KvUtils::BYTE_ARRAY);
uData.insert(uData.end(), data.begin(), data.end());
} else if (type == DataShareValueObjectType::TYPE_INT) {
ZLOGE("Value bucket type int");
int64_t data = it->second;
uint64_t data64 = htobe64(*reinterpret_cast<uint64_t*>(&data));
uint8_t *dataU8 = reinterpret_cast<uint8_t*>(&data64);
uData.push_back(KvUtils::INTEGER);
uData.insert(uData.end(), dataU8, dataU8 + sizeof(int64_t) / sizeof(uint8_t));
} else if (type == DataShareValueObjectType::TYPE_DOUBLE) {
ZLOGE("Value bucket type double");
double data = it->second;
uint64_t data64 = htobe64(*reinterpret_cast<uint64_t*>(&data));
uint8_t *dataU8 = reinterpret_cast<uint8_t*>(&data64);
uData.push_back(KvUtils::DOUBLE);
uData.insert(uData.end(), dataU8, dataU8 + sizeof(double) / sizeof(uint8_t));
} else if (type == DataShareValueObjectType::TYPE_BOOL) {
ZLOGE("Value bucket type bool");
bool data = it->second;
uData.push_back(KvUtils::BOOLEAN);
uData.push_back(static_cast<uint8_t>(data));
} else if (type == DataShareValueObjectType::TYPE_STRING) {
ZLOGE("Value bucket type string");
std::string data = it->second;
uData.push_back(KvUtils::STRING);
uData.assign(data.begin(), data.end());
}
blob = Blob(uData);
return Status::SUCCESS;
}
void KvUtils::NoSupport(const DataShare::OperationItem &oper, DataQuery &query)
{
ZLOGE("invalid operation:%{public}d", oper.operation);
}
void KvUtils::InKeys(const OperationItem &oper, DataQuery &query)
{
query.InKeys(oper.para1);
}
void KvUtils::KeyPrefix(const OperationItem &oper, DataQuery &query)
{
query.KeyPrefix(oper.para1);
}
void KvUtils::EqualTo(const OperationItem &oper, DataQuery &query)
{
Querys equal(&query, QueryType::EQUAL);
CovUtil::FillField(oper.para1, oper.para2.value, equal);
}
void KvUtils::NotEqualTo(const OperationItem &oper, DataQuery &query)
{
Querys notEqual(&query, QueryType::NOT_EQUAL);
CovUtil::FillField(oper.para1, oper.para2.value, notEqual);
}
void KvUtils::GreaterThan(const OperationItem &oper, DataQuery &query)
{
Querys greater(&query, QueryType::GREATER);
CovUtil::FillField(oper.para1, oper.para2.value, greater);
}
void KvUtils::LessThan(const OperationItem &oper, DataQuery &query)
{
Querys less(&query, QueryType::LESS);
CovUtil::FillField(oper.para1, oper.para2.value, less);
}
void KvUtils::GreaterThanOrEqualTo(const OperationItem &oper, DataQuery &query)
{
Querys greaterOrEqual(&query, QueryType::GREATER_OR_EQUAL);
CovUtil::FillField(oper.para1, oper.para2.value, greaterOrEqual);
}
void KvUtils::LessThanOrEqualTo(const OperationItem &oper, DataQuery &query)
{
Querys lessOrEqual(&query, QueryType::LESS_OR_EQUAL);
CovUtil::FillField(oper.para1, oper.para2.value, lessOrEqual);
}
void KvUtils::And(const OperationItem &oper, DataQuery &query)
{
query.And();
}
void KvUtils::Or(const OperationItem &oper, DataQuery &query)
{
query.Or();
}
void KvUtils::IsNull(const OperationItem &oper, DataQuery &query)
{
query.IsNull(oper.para1);
}
void KvUtils::IsNotNull(const OperationItem &oper, DataQuery &query)
{
query.IsNotNull(oper.para1);
}
void KvUtils::In(const OperationItem &oper, DataQuery &query)
{
InOrNotIn in(&query, QueryType::IN);
CovUtil::FillField(oper.para1, oper.para2.value, in);
}
void KvUtils::NotIn(const OperationItem &oper, DataQuery &query)
{
InOrNotIn notIn(&query, QueryType::NOT_IN);
CovUtil::FillField(oper.para1, oper.para2.value, notIn);
}
void KvUtils::Like(const OperationItem &oper, DataQuery &query)
{
query.Like(oper.para1, oper.para2);
}
void KvUtils::Unlike(const OperationItem &oper, DataQuery &query)
{
query.Unlike(oper.para1, oper.para2);
}
void KvUtils::OrderByAsc(const OperationItem &oper, DataQuery &query)
{
query.OrderByAsc(oper.para1);
}
void KvUtils::OrderByDesc(const OperationItem &oper, DataQuery &query)
{
query.OrderByDesc(oper.para1);
}
void KvUtils::Limit(const OperationItem &oper, DataQuery &query)
{
query.Limit(oper.para1, oper.para2);
}
} // namespace DistributedKv
} // namespace OHOS

View File

@ -0,0 +1,33 @@
/*
* 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 "KvStoreClientDeathObserver"
#include "kvstore_client_death_observer.h"
#include "log_print.h"
namespace OHOS {
namespace DistributedKv {
KvStoreClientDeathObserver::KvStoreClientDeathObserver()
{
ZLOGI("this client death observer");
}
KvStoreClientDeathObserver::~KvStoreClientDeathObserver()
{
ZLOGI("destructor this client death observer");
}
} // namespace DistributedKv
} // namespace OHOS

View File

@ -0,0 +1,31 @@
/*
* 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 KVSTORE_CLIENT_DEATH_OBSERVER_H
#define KVSTORE_CLIENT_DEATH_OBSERVER_H
#include "ikvstore_client_death_observer.h"
namespace OHOS {
namespace DistributedKv {
class KvStoreClientDeathObserver : public KvStoreClientDeathObserverStub {
public:
KvStoreClientDeathObserver();
virtual ~KvStoreClientDeathObserver();
};
} // namespace DistributedKv
} // namespace OHOS
#endif // KVSTORE_CLIENT_DEATH_OBSERVER_H

View File

@ -0,0 +1,107 @@
/*
* 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.
*/
#define LOG_TAG "KvStoreDataShareBridge"
#include "constant.h"
#include "log_print.h"
#include "kvstore_datashare_bridge.h"
namespace OHOS {
namespace DistributedKv {
using namespace DataShare;
KvStoreDataShareBridge::KvStoreDataShareBridge(std::shared_ptr<KvStoreResultSet> kvResultSet)
:kvResultSet_(kvResultSet) {};
int KvStoreDataShareBridge::GetRowCount(int32_t &count)
{
count = Count();
return count == INVALID_COUNT ? E_ERROR : E_OK;
}
int KvStoreDataShareBridge::GetAllColumnNames(std::vector<std::string> &columnsName)
{
columnsName = { "key", "value" };
return E_OK;
}
bool KvStoreDataShareBridge::FillBlock(int pos, ResultSetBridge::Writer &writer)
{
if (kvResultSet_ == nullptr) {
ZLOGE("kvResultSet_ nullptr");
return false;
}
bool isMoved = kvResultSet_->MoveToPosition(pos);
if (!isMoved) {
ZLOGE("MoveToPosition failed");
return false;
}
Entry entry;
Status status = kvResultSet_->GetEntry(entry);
if (status != Status::SUCCESS) {
ZLOGE("GetEntry failed %{public}d", status);
return false;
}
int statusAlloc = writer.AllocRow();
if (statusAlloc != E_OK) {
ZLOGE("SharedBlock is full: %{public}d", statusAlloc);
return false;
}
int keyStatus = writer.Write(0, entry.key.ToString().c_str(), entry.key.Size() + 1);
if (keyStatus != E_OK) {
ZLOGE("WriteBlob key error: %{public}d", keyStatus);
return false;
}
int valueStatus = writer.Write(1, entry.value.ToString().c_str(), entry.value.Size() + 1);
if (valueStatus != E_OK) {
ZLOGE("WriteBlob value error: %{public}d", valueStatus);
return false;
}
return true;
}
int KvStoreDataShareBridge::Count()
{
if (kvResultSet_ == nullptr) {
ZLOGE("kvResultSet_ nullptr");
return INVALID_COUNT;
}
if (resultRowCount != INVALID_COUNT) {
return resultRowCount;
}
int count = kvResultSet_->GetCount();
if (count < 0) {
ZLOGE("kvResultSet count invalid: %{public}d", count);
return INVALID_COUNT;
}
resultRowCount = count;
return count;
}
bool KvStoreDataShareBridge::OnGo(int32_t start, int32_t target, ResultSetBridge::Writer &writer)
{
if ((start < 0) || (target < 0) || (start > target) || (target >= Count())) {
ZLOGE("nowRowIndex out of line: %{public}d", target);
return false;
}
for (int pos = start; pos <= target; pos++) {
bool ret = FillBlock(pos, writer);
if (!ret) {
ZLOGE("nowRowIndex out of line: %{public}d", target);
return ret;
}
}
return true;
}
} // namespace DistributedKv
} // namespace OHOS

View File

@ -0,0 +1,43 @@
/*
* 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 "KvStoreObserverClient"
#include "kvstore_observer_client.h"
#include "log_print.h"
namespace OHOS {
namespace DistributedKv {
KvStoreObserverClient::KvStoreObserverClient(std::shared_ptr<KvStoreObserver> kvStoreObserver)
: kvStoreObserver_(kvStoreObserver)
{
ZLOGI("start");
}
KvStoreObserverClient::~KvStoreObserverClient()
{
ZLOGI("end");
}
void KvStoreObserverClient::OnChange(const ChangeNotification &changeNotification)
{
ZLOGI("start");
if (kvStoreObserver_ != nullptr) {
ZLOGI("SINGLE_VERSION start");
kvStoreObserver_->OnChange(changeNotification);
}
}
} // namespace DistributedKv
} // namespace OHOS

View File

@ -0,0 +1,43 @@
/*
* 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 KVSTORE_OBSERVER_CLIENT_H
#define KVSTORE_OBSERVER_CLIENT_H
#include <memory>
#include "change_notification.h"
#include "ikvstore_observer.h"
#include "kvstore_observer.h"
#include "refbase.h"
namespace OHOS {
namespace DistributedKv {
class KvStoreObserverClient : public KvStoreObserverStub {
public:
explicit KvStoreObserverClient(std::shared_ptr<KvStoreObserver> kvStoreObserver);
~KvStoreObserverClient();
void OnChange(const ChangeNotification &changeNotification) override;
private:
static const int MAX_TRY_COUNT = 10;
// client is responsible for free it when call UnSubscribeKvStore.
std::shared_ptr<KvStoreObserver> kvStoreObserver_;
};
} // namespace DistributedKv
} // namespace OHOS
#endif // KVSTORE_OBSERVER_CLIENT_H

View File

@ -0,0 +1,87 @@
/*
* 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 KVSTORE_OBSERVER_IMPL_H
#define KVSTORE_OBSERVER_IMPL_H
#include <list>
#include "app_types.h"
#include "kv_store_observer.h"
#include "log_print.h"
namespace OHOS {
namespace AppDistributedKv {
class KvStoreObserverNbImpl : public DistributedDB::KvStoreObserver {
public:
KvStoreObserverNbImpl(AppKvStoreObserver *appKvStoreObserver, const SubscribeType &subscribeType)
{
appKvStoreObserver_ = appKvStoreObserver;
subscribeType_ = subscribeType;
}
virtual void OnChange(const DistributedDB::KvStoreChangedData &data)
{
if (appKvStoreObserver_ == nullptr) {
ZLOGE("appKvStoreObserver_ is nullptr.");
return;
}
std::list<DistributedDB::Entry> insertList = data.GetEntriesInserted();
std::list<DistributedDB::Entry> updateList = data.GetEntriesUpdated();
std::list<DistributedDB::Entry> deletedList = data.GetEntriesDeleted();
std::list<Entry> insertListTmp;
std::list<Entry> updateListTmp;
std::list<Entry> deletedListTmp;
for (const auto &entry : insertList) {
Key key(entry.key);
Value value(entry.value);
Entry tmpEntry;
tmpEntry.key = key;
tmpEntry.value = value;
insertListTmp.push_back(tmpEntry);
}
for (const auto &entry : updateList) {
Key key(entry.key);
Value value(entry.value);
Entry tmpEntry;
tmpEntry.key = key;
tmpEntry.value = value;
updateListTmp.push_back(tmpEntry);
}
for (const auto &entry : deletedList) {
Key key(entry.key);
Value value(entry.value);
Entry tmpEntry;
tmpEntry.key = key;
tmpEntry.value = value;
deletedListTmp.push_back(tmpEntry);
}
AppChangeNotification changeNotification(insertListTmp, updateListTmp, deletedListTmp, std::string(), false);
appKvStoreObserver_->OnChange(changeNotification);
}
virtual ~KvStoreObserverNbImpl()
{}
private:
AppKvStoreObserver *appKvStoreObserver_;
SubscribeType subscribeType_;
};
} // namespace AppDistributedKv
} // namespace OHOS
#endif // APP_KV_STORE_OBSERVER_H

View File

@ -0,0 +1,108 @@
/*
* 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 "KvStoreResultSetClient"
#include "dds_trace.h"
#include "kvstore_resultset_client.h"
namespace OHOS::DistributedKv {
using namespace OHOS::DistributedDataDfx;
KvStoreResultSetClient::KvStoreResultSetClient(sptr<IKvStoreResultSet> kvStoreProxy)
:kvStoreResultSetProxy_(kvStoreProxy)
{}
int KvStoreResultSetClient::GetCount() const
{
return kvStoreResultSetProxy_->GetCount();
}
int KvStoreResultSetClient::GetPosition() const
{
return kvStoreResultSetProxy_->GetPosition();
}
bool KvStoreResultSetClient::MoveToFirst()
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
return kvStoreResultSetProxy_->MoveToFirst();
}
bool KvStoreResultSetClient::MoveToLast()
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
return kvStoreResultSetProxy_->MoveToLast();
}
bool KvStoreResultSetClient::MoveToNext()
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
return kvStoreResultSetProxy_->MoveToNext();
}
bool KvStoreResultSetClient::MoveToPrevious()
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
return kvStoreResultSetProxy_->MoveToPrevious();
}
bool KvStoreResultSetClient::Move(int offset)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
return kvStoreResultSetProxy_->Move(offset);
}
bool KvStoreResultSetClient::MoveToPosition(int position)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
return kvStoreResultSetProxy_->MoveToPosition(position);
}
bool KvStoreResultSetClient::IsFirst() const
{
return kvStoreResultSetProxy_->IsFirst();
}
bool KvStoreResultSetClient::IsLast() const
{
return kvStoreResultSetProxy_->IsLast();
}
bool KvStoreResultSetClient::IsBeforeFirst() const
{
return kvStoreResultSetProxy_->IsBeforeFirst();
}
bool KvStoreResultSetClient::IsAfterLast() const
{
return kvStoreResultSetProxy_->IsAfterLast();
}
Status KvStoreResultSetClient::GetEntry(Entry &entry) const
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
return kvStoreResultSetProxy_->GetEntry(entry);
}
Status KvStoreResultSetClient::Close()
{
return NOT_SUPPORT;
}
sptr<IKvStoreResultSet> KvStoreResultSetClient::GetKvStoreResultSetProxy() const
{
return kvStoreResultSetProxy_;
}
} // namespace OHOS::DistributedKv

View File

@ -0,0 +1,63 @@
/*
* 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_KVSTORE_RESULTSET_CLIENT_H
#define DISTRIBUTEDDATAMGR_KVSTORE_RESULTSET_CLIENT_H
#include "ikvstore_resultset.h"
#include "kvstore_result_set.h"
namespace OHOS::DistributedKv {
class KvStoreResultSetClient : public KvStoreResultSet {
public:
explicit KvStoreResultSetClient(sptr<IKvStoreResultSet> kvStoreProxy);
~KvStoreResultSetClient()
{}
int GetCount() const override;
int GetPosition() const override;
bool MoveToFirst() override;
bool MoveToLast() override;
bool MoveToNext() override;
bool MoveToPrevious() override;
bool Move(int offset) override;
bool MoveToPosition(int position) override;
bool IsFirst() const override;
bool IsLast() const override;
bool IsBeforeFirst() const override;
bool IsAfterLast() const override;
Status GetEntry(Entry &entry) const override;
Status Close() override;
sptr<IKvStoreResultSet> GetKvStoreResultSetProxy() const;
private:
sptr<IKvStoreResultSet> kvStoreResultSetProxy_;
};
} // namespace OHOS::DistributedKv
#endif // DISTRIBUTEDDATAMGR_KVSTORE_RESULTSET_CLIENT_H

View File

@ -0,0 +1,155 @@
/*
* 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 "KvStoreServiceDeathNotifier"
#include "kvstore_service_death_notifier.h"
#include "if_system_ability_manager.h"
#include "ipc_skeleton.h"
#include "iservice_registry.h"
#include "kvstore_client_death_observer.h"
#include "log_print.h"
#include "refbase.h"
#include "system_ability_definition.h"
namespace OHOS {
namespace DistributedKv {
AppId KvStoreServiceDeathNotifier::appId_;
std::mutex KvStoreServiceDeathNotifier::mutex_;
std::mutex KvStoreServiceDeathNotifier::watchMutex_;
sptr<IKvStoreDataService> KvStoreServiceDeathNotifier::kvDataServiceProxy_;
sptr<KvStoreServiceDeathNotifier::ServiceDeathRecipient> KvStoreServiceDeathNotifier::deathRecipientPtr_;
sptr<IRemoteObject> KvStoreServiceDeathNotifier::clientDeathObserverPtr_;
std::set<std::shared_ptr<KvStoreDeathRecipient>> KvStoreServiceDeathNotifier::serviceDeathWatchers_;
void KvStoreServiceDeathNotifier::SetAppId(const AppId &appId)
{
std::lock_guard<decltype(mutex_)> lg(mutex_);
appId_ = appId;
}
AppId KvStoreServiceDeathNotifier::GetAppId()
{
std::lock_guard<decltype(mutex_)> lg(mutex_);
return appId_;
}
sptr<IKvStoreDataService> KvStoreServiceDeathNotifier::GetDistributedKvDataService()
{
ZLOGD("begin.");
std::lock_guard<std::mutex> lg(watchMutex_);
if (kvDataServiceProxy_ != nullptr) {
return kvDataServiceProxy_;
}
ZLOGI("create remote proxy.");
auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
if (samgr == nullptr) {
ZLOGE("get samgr fail.");
return nullptr;
}
auto remote = samgr->CheckSystemAbility(DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID);
kvDataServiceProxy_ = iface_cast<IKvStoreDataService>(remote);
if (kvDataServiceProxy_ == nullptr) {
ZLOGE("initialize proxy failed.");
return nullptr;
}
if (deathRecipientPtr_ == nullptr) {
deathRecipientPtr_ = new (std::nothrow) ServiceDeathRecipient();
if (deathRecipientPtr_ == nullptr) {
ZLOGW("new KvStoreDeathRecipient failed");
return nullptr;
}
}
if ((remote->IsProxyObject()) && (!remote->AddDeathRecipient(deathRecipientPtr_))) {
ZLOGE("failed to add death recipient.");
}
RegisterClientDeathObserver();
return kvDataServiceProxy_;
}
void KvStoreServiceDeathNotifier::RegisterClientDeathObserver()
{
if (kvDataServiceProxy_ == nullptr) {
return;
}
if (clientDeathObserverPtr_ == nullptr) {
clientDeathObserverPtr_ = new (std::nothrow) KvStoreClientDeathObserver();
}
if (clientDeathObserverPtr_ == nullptr) {
ZLOGW("new KvStoreClientDeathObserver failed");
return;
}
kvDataServiceProxy_->RegisterClientDeathObserver(GetAppId(), clientDeathObserverPtr_);
}
void KvStoreServiceDeathNotifier::AddServiceDeathWatcher(std::shared_ptr<KvStoreDeathRecipient> watcher)
{
std::lock_guard<std::mutex> lg(watchMutex_);
auto ret = serviceDeathWatchers_.insert(std::move(watcher));
if (ret.second) {
ZLOGI("success set size: %zu", serviceDeathWatchers_.size());
} else {
ZLOGE("failed set size: %zu", serviceDeathWatchers_.size());
}
}
void KvStoreServiceDeathNotifier::RemoveServiceDeathWatcher(std::shared_ptr<KvStoreDeathRecipient> watcher)
{
std::lock_guard<std::mutex> lg(watchMutex_);
auto it = serviceDeathWatchers_.find(std::move(watcher));
if (it != serviceDeathWatchers_.end()) {
serviceDeathWatchers_.erase(it);
ZLOGI("find & erase set size: %zu", serviceDeathWatchers_.size());
} else {
ZLOGE("no found set size: %zu", serviceDeathWatchers_.size());
}
}
void KvStoreServiceDeathNotifier::ServiceDeathRecipient::OnRemoteDied(const wptr<IRemoteObject> &remote)
{
ZLOGW("DistributedDataMgrService died.");
// Need to do this with the lock held
std::lock_guard<std::mutex> lg(watchMutex_);
kvDataServiceProxy_ = nullptr;
ZLOGI("watcher set size: %zu", serviceDeathWatchers_.size());
for (const auto &watcher : serviceDeathWatchers_) {
if (watcher == nullptr) {
ZLOGI("watcher is nullptr");
continue;
}
std::thread th = std::thread([watcher]() {
watcher->OnRemoteDied();
});
th.detach();
}
}
KvStoreServiceDeathNotifier::ServiceDeathRecipient::ServiceDeathRecipient()
{
ZLOGI("constructor.");
}
KvStoreServiceDeathNotifier::ServiceDeathRecipient::~ServiceDeathRecipient()
{
ZLOGI("destructor.");
}
} // namespace DistributedKv
} // namespace OHOS

View File

@ -0,0 +1,67 @@
/*
* 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 KVSTORE_SERVICE_DEATH_NOTIFIER_H
#define KVSTORE_SERVICE_DEATH_NOTIFIER_H
#include <memory>
#include <set>
#include <thread>
#include "ikvstore_data_service.h"
#include "iremote_object.h"
#include "kvstore_death_recipient.h"
#include "refbase.h"
namespace OHOS {
namespace DistributedKv {
class KvStoreServiceDeathNotifier final {
public:
KvStoreServiceDeathNotifier() = delete;
~KvStoreServiceDeathNotifier() = delete;
// get DistributedKvDataService proxy object.
static sptr<IKvStoreDataService> GetDistributedKvDataService();
// temporarily used, should get in service side from binder.
static void SetAppId(const AppId &appId);
static AppId GetAppId();
// add watcher for server die msg.
static void AddServiceDeathWatcher(std::shared_ptr<KvStoreDeathRecipient> watcher);
// remove watcher for server die msg.
static void RemoveServiceDeathWatcher(std::shared_ptr<KvStoreDeathRecipient> watcher);
private:
class ServiceDeathRecipient : public IRemoteObject::DeathRecipient {
public:
ServiceDeathRecipient();
virtual ~ServiceDeathRecipient();
void OnRemoteDied(const wptr<IRemoteObject> &remote) override;
};
// add watcher for server die msg.
static void RegisterClientDeathObserver();
static AppId appId_;
// lock for kvDataServiceProxy_ and serviceDeathWatchers_.
static std::mutex watchMutex_;
static std::mutex mutex_;
static sptr<IKvStoreDataService> kvDataServiceProxy_;
static sptr<ServiceDeathRecipient> deathRecipientPtr_;
static sptr<IRemoteObject> clientDeathObserverPtr_;
// set of watchers for server die msg.
static std::set<std::shared_ptr<KvStoreDeathRecipient>> serviceDeathWatchers_;
};
} // namespace DistributedKv
} // namespace OHOS
#endif // KVSTORE_SERVICE_DEATH_NOTIFIER_H

View File

@ -0,0 +1,60 @@
/*
* 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 "KvStoreSyncCallbackClient"
#include "kvstore_sync_callback_client.h"
#include <cinttypes>
#include <atomic>
#include "dds_trace.h"
#include "log_print.h"
namespace OHOS {
namespace DistributedKv {
using namespace OHOS::DistributedDataDfx;
KvStoreSyncCallbackClient::~KvStoreSyncCallbackClient()
{
syncCallbackInfo_.Clear();
}
void KvStoreSyncCallbackClient::SyncCompleted(const std::map<std::string, Status> &results, uint64_t sequenceId)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__), TraceSwitch::BYTRACE_ON);
auto finded = syncCallbackInfo_.Find(sequenceId);
if (finded.first) {
finded.second->SyncCompleted(results);
DeleteSyncCallback(sequenceId);
}
}
void KvStoreSyncCallbackClient::AddSyncCallback(
const std::shared_ptr<KvStoreSyncCallback> callback, uint64_t sequenceId)
{
if (callback == nullptr) {
ZLOGE("callback is nullptr");
return;
}
auto inserted = syncCallbackInfo_.Insert(sequenceId, callback);
if (!inserted) {
ZLOGE("The sequeuceId %{public}" PRIu64 "is repeat!", sequenceId);
}
}
void KvStoreSyncCallbackClient::DeleteSyncCallback(uint64_t sequenceId)
{
syncCallbackInfo_.Erase(sequenceId);
}
} // namespace DistributedKv
} // namespace OHOS

View File

@ -0,0 +1,42 @@
/*
* 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 KVSTORE_SYNC_CALLBACK_CLIENT_H
#define KVSTORE_SYNC_CALLBACK_CLIENT_H
#include <mutex>
#include "concurrent_map.h"
#include "ikvstore_sync_callback.h"
#include "kvstore_sync_callback.h"
namespace OHOS {
namespace DistributedKv {
class KvStoreSyncCallbackClient : public KvStoreSyncCallbackStub {
public:
KvStoreSyncCallbackClient() = default;
virtual ~KvStoreSyncCallbackClient();
void SyncCompleted(const std::map<std::string, Status> &results, uint64_t sequenceId) override;
void AddSyncCallback(const std::shared_ptr<KvStoreSyncCallback> callback, uint64_t sequenceId);
void DeleteSyncCallback(uint64_t sequenceId);
private:
ConcurrentMap<uint64_t, std::shared_ptr<KvStoreSyncCallback>> syncCallbackInfo_;
};
} // namespace DistributedKv
} // namespace OHOS
#endif // KVSTORE_SYNC_CALLBACK_CLIENT_H

View File

@ -0,0 +1,523 @@
/*
* 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 "SingleKvStoreClient"
#include "single_kvstore_client.h"
#include "constant.h"
#include "dds_trace.h"
#include "kvstore_observer_client.h"
#include "kvstore_resultset_client.h"
#include "kvstore_sync_callback_client.h"
#include "log_print.h"
#include "kvstore_utils.h"
namespace OHOS::DistributedKv {
using namespace OHOS::DistributedDataDfx;
SingleKvStoreClient::SingleKvStoreClient(sptr<ISingleKvStore> kvStoreProxy, const std::string &storeId)
: kvStoreProxy_(kvStoreProxy), storeId_(storeId), syncCallbackClient_(new KvStoreSyncCallbackClient()),
syncObserver_(std::make_shared<SyncObserver>())
{}
SingleKvStoreClient::~SingleKvStoreClient()
{
kvStoreProxy_->UnRegisterSyncCallback();
syncObserver_->Clean();
}
StoreId SingleKvStoreClient::GetStoreId() const
{
StoreId storeId;
storeId.storeId = storeId_;
return storeId;
}
Status SingleKvStoreClient::GetEntries(const Key &prefix, std::vector<Entry> &entries) const
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__), TraceSwitch::BYTRACE_ON);
if (kvStoreProxy_ == nullptr) {
ZLOGE("kvstore proxy is nullptr.");
return Status::SERVER_UNAVAILABLE;
}
return kvStoreProxy_->GetEntries(prefix, entries);
}
Status SingleKvStoreClient::GetEntries(const DataQuery &query, std::vector<Entry> &entries) const
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__), TraceSwitch::BYTRACE_ON);
if (kvStoreProxy_ == nullptr) {
ZLOGE("kvstore proxy is nullptr.");
return Status::SERVER_UNAVAILABLE;
}
ZLOGD("Cpp client GetEntries");
return kvStoreProxy_->GetEntriesWithQuery(query.ToString(), entries);
}
Status SingleKvStoreClient::GetResultSet(const Key &prefix, std::shared_ptr<KvStoreResultSet> &resultSet) const
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__), TraceSwitch::BYTRACE_ON);
resultSet = nullptr;
Status statusTmp = Status::SERVER_UNAVAILABLE;
if (kvStoreProxy_ == nullptr) {
ZLOGE("kvstore proxy is nullptr.");
return statusTmp;
}
sptr<IKvStoreResultSet> resultSetTmp;
auto callFun = [&](Status status, sptr<IKvStoreResultSet> proxy) {
statusTmp = status;
resultSetTmp = proxy;
};
kvStoreProxy_->GetResultSet(prefix, callFun);
if (statusTmp != Status::SUCCESS) {
ZLOGE("return error: %d.", static_cast<int>(statusTmp));
return statusTmp;
}
if (resultSetTmp == nullptr) {
ZLOGE("resultSetTmp is nullptr.");
return statusTmp;
}
resultSet = std::shared_ptr<KvStoreResultSetClient>(
new KvStoreResultSetClient(resultSetTmp), [proxy = kvStoreProxy_] (auto result) {
ZLOGE("kvstore proxy ResultSet closed.");
proxy->CloseResultSet(result->GetKvStoreResultSetProxy());
});
return statusTmp;
}
Status SingleKvStoreClient::GetResultSet(const DataQuery &query,
std::shared_ptr<KvStoreResultSet> &resultSet) const
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__), TraceSwitch::BYTRACE_ON);
resultSet = nullptr;
Status statusTmp = Status::SERVER_UNAVAILABLE;
if (kvStoreProxy_ == nullptr) {
ZLOGE("kvstore proxy is nullptr.");
return statusTmp;
}
ZLOGD("Cpp client GetResultSet");
sptr<IKvStoreResultSet> resultSetTmp;
auto callFun = [&](Status status, sptr<IKvStoreResultSet> proxy) {
statusTmp = status;
resultSetTmp = proxy;
};
kvStoreProxy_->GetResultSetWithQuery(query.ToString(), callFun);
if (statusTmp != Status::SUCCESS) {
ZLOGE("return error: %d.", static_cast<int>(statusTmp));
return statusTmp;
}
if (resultSetTmp == nullptr) {
ZLOGE("resultSetTmp is nullptr.");
return statusTmp;
}
resultSet = std::shared_ptr<KvStoreResultSetClient>(
new KvStoreResultSetClient(resultSetTmp), [proxy = kvStoreProxy_] (auto result) {
ZLOGE("kvstore proxy ResultSetwithquery closed.");
proxy->CloseResultSet(result->GetKvStoreResultSetProxy());
});
return statusTmp;
}
Status SingleKvStoreClient::CloseResultSet(std::shared_ptr<KvStoreResultSet> &resultSet)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
auto resultSetTmp = std::move(resultSet);
if (resultSetTmp == nullptr) {
ZLOGE("resultSet is nullptr.");
return Status::INVALID_ARGUMENT;
}
if (kvStoreProxy_ == nullptr) {
ZLOGE("kvstore proxy is nullptr.");
return Status::SERVER_UNAVAILABLE;
}
auto resultSetClient = reinterpret_cast<KvStoreResultSetClient *>(resultSetTmp.get());
return kvStoreProxy_->CloseResultSet(resultSetClient->GetKvStoreResultSetProxy());
}
Status SingleKvStoreClient::GetCount(const DataQuery &query, int &count) const
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__), TraceSwitch::BYTRACE_ON);
if (kvStoreProxy_ == nullptr) {
ZLOGE("kvstore proxy is nullptr.");
return Status::SERVER_UNAVAILABLE;
}
ZLOGD("Cpp client GetCount");
return kvStoreProxy_->GetCountWithQuery(query.ToString(), count);
}
Status SingleKvStoreClient::Sync(const std::vector<std::string> &devices, SyncMode mode, uint32_t delay)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__),
TraceSwitch::BYTRACE_ON | TraceSwitch::TRACE_CHAIN_ON);
if (kvStoreProxy_ == nullptr) {
ZLOGE("kvstore proxy is nullptr.");
return Status::SERVER_UNAVAILABLE;
}
if (devices.empty()) {
ZLOGW("deviceIds is empty.");
return Status::INVALID_ARGUMENT;
}
uint64_t sequenceId = KvStoreUtils::GenerateSequenceId();
syncCallbackClient_->AddSyncCallback(syncObserver_, sequenceId);
RegisterCallback();
return kvStoreProxy_->Sync(devices, mode, delay, sequenceId);
}
Status SingleKvStoreClient::RemoveDeviceData(const std::string &device)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
if (kvStoreProxy_ == nullptr) {
ZLOGE("kvstore proxy is nullptr.");
return Status::SERVER_UNAVAILABLE;
}
if (device.empty()) {
ZLOGW("device is empty.");
return Status::INVALID_ARGUMENT;
}
return kvStoreProxy_->RemoveDeviceData(device);
}
Status SingleKvStoreClient::Delete(const Key &key)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
ZLOGI("begin.");
std::vector<uint8_t> keyData = Constant::TrimCopy<std::vector<uint8_t>>(key.Data());
if (keyData.size() == 0 || keyData.size() > Constant::MAX_KEY_LENGTH) {
ZLOGE("invalid key.");
return Status::INVALID_ARGUMENT;
}
if (kvStoreProxy_ == nullptr) {
ZLOGE("kvstore proxy is nullptr.");
return Status::SERVER_UNAVAILABLE;
}
return kvStoreProxy_->Delete(key);
}
Status SingleKvStoreClient::Put(const Key &key, const Value &value)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__), TraceSwitch::BYTRACE_ON);
ZLOGI("key: %zu value: %zu.", key.Size(), value.Size());
std::vector<uint8_t> keyData = Constant::TrimCopy<std::vector<uint8_t>>(key.Data());
if (keyData.size() == 0 || keyData.size() > Constant::MAX_KEY_LENGTH ||
value.Size() > Constant::MAX_VALUE_LENGTH) {
ZLOGE("invalid key or value.");
return Status::INVALID_ARGUMENT;
}
if (kvStoreProxy_ == nullptr) {
ZLOGE("kvstore proxy is nullptr.");
return Status::SERVER_UNAVAILABLE;
}
return kvStoreProxy_->Put(key, value);
}
Status SingleKvStoreClient::Get(const Key &key, Value &value)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__), TraceSwitch::BYTRACE_ON);
if (kvStoreProxy_ == nullptr) {
ZLOGE("kvstore proxy is nullptr.");
return Status::SERVER_UNAVAILABLE;
}
return kvStoreProxy_->Get(key, value);
}
Status SingleKvStoreClient::SubscribeKvStore(SubscribeType subscribeType, std::shared_ptr<KvStoreObserver> observer)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
if (observer == nullptr) {
ZLOGW("return INVALID_ARGUMENT.");
return Status::INVALID_ARGUMENT;
}
std::lock_guard<std::mutex> lck(observerMapMutex_);
// change this to map.contains() after c++20
if (registeredObservers_.count(observer.get()) == 1) {
ZLOGW("return STORE_ALREADY_SUBSCRIBE.");
return Status::STORE_ALREADY_SUBSCRIBE;
}
// remove storeId after remove SubscribeKvStore function in manager. currently reserve for convenience.
sptr<KvStoreObserverClient> ipcObserver = new (std::nothrow) KvStoreObserverClient(observer);
if (ipcObserver == nullptr) {
ZLOGW("new KvStoreObserverClient failed");
return Status::ERROR;
}
Status status = kvStoreProxy_->SubscribeKvStore(subscribeType, ipcObserver);
if (status == Status::SUCCESS) {
const auto temp = registeredObservers_.insert({observer.get(), ipcObserver});
if (!temp.second) {
ZLOGW("local insert error");
return Status::ERROR;
}
}
return status;
}
Status SingleKvStoreClient::UnSubscribeKvStore(SubscribeType subscribeType, std::shared_ptr<KvStoreObserver> observer)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
if (observer == nullptr) {
ZLOGW("return INVALID_ARGUMENT.");
return Status::INVALID_ARGUMENT;
}
std::lock_guard<std::mutex> lck(observerMapMutex_);
auto it = registeredObservers_.find(observer.get());
if (it == registeredObservers_.end()) {
ZLOGW(" STORE NOT SUBSCRIBE.");
return Status::STORE_NOT_SUBSCRIBE;
}
Status status = kvStoreProxy_->UnSubscribeKvStore(subscribeType, it->second);
if (status == Status::SUCCESS) {
registeredObservers_.erase(it);
} else {
ZLOGW("single unSubscribe failed code=%d.", static_cast<int>(status));
}
return status;
}
Status SingleKvStoreClient::RegisterSyncCallback(std::shared_ptr<KvStoreSyncCallback> callback)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__), TraceSwitch::BYTRACE_ON);
ZLOGI("begin.");
if (callback == nullptr) {
ZLOGW("return INVALID_ARGUMENT.");
return Status::INVALID_ARGUMENT;
}
syncObserver_->Add(callback);
RegisterCallback();
return Status::SUCCESS;
}
Status SingleKvStoreClient::RegisterCallback()
{
if (isRegisterSyncCallback_) {
return Status::SUCCESS;
}
std::lock_guard lg(registerCallbackMutex_);
if (isRegisterSyncCallback_) {
return Status::SUCCESS;
}
auto status = kvStoreProxy_->RegisterSyncCallback(syncCallbackClient_);
if (status != Status::SUCCESS) {
ZLOGE("RegisterSyncCallback is not success.");
return status;
}
isRegisterSyncCallback_ = true;
return Status::SUCCESS;
}
Status SingleKvStoreClient::UnRegisterSyncCallback()
{
ZLOGI("begin.");
syncObserver_->Clean();
return Status::SUCCESS;
}
Status SingleKvStoreClient::PutBatch(const std::vector<Entry> &entries)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__), TraceSwitch::BYTRACE_ON);
ZLOGI("entry size: %zu", entries.size());
if (entries.size() > Constant::MAX_BATCH_SIZE) {
ZLOGE("batch size must less than 128.");
return Status::INVALID_ARGUMENT;
}
if (kvStoreProxy_ != nullptr) {
return kvStoreProxy_->PutBatch(entries);
}
ZLOGE("singleKvstore proxy is nullptr.");
return Status::SERVER_UNAVAILABLE;
}
Status SingleKvStoreClient::DeleteBatch(const std::vector<Key> &keys)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
if (keys.size() > Constant::MAX_BATCH_SIZE) {
ZLOGE("batch size must less than 128.");
return Status::INVALID_ARGUMENT;
}
if (kvStoreProxy_ != nullptr) {
return kvStoreProxy_->DeleteBatch(keys);
}
ZLOGE("singleKvstore proxy is nullptr.");
return Status::SERVER_UNAVAILABLE;
}
Status SingleKvStoreClient::StartTransaction()
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__), TraceSwitch::BYTRACE_ON);
if (kvStoreProxy_ != nullptr) {
return kvStoreProxy_->StartTransaction();
}
ZLOGE("singleKvstore proxy is nullptr.");
return Status::SERVER_UNAVAILABLE;
}
Status SingleKvStoreClient::Commit()
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__), TraceSwitch::BYTRACE_ON);
if (kvStoreProxy_ != nullptr) {
return kvStoreProxy_->Commit();
}
ZLOGE("singleKvstore proxy is nullptr.");
return Status::SERVER_UNAVAILABLE;
}
Status SingleKvStoreClient::Rollback()
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__), TraceSwitch::BYTRACE_ON);
if (kvStoreProxy_ != nullptr) {
return kvStoreProxy_->Rollback();
}
ZLOGE("singleKvstore proxy is nullptr.");
return Status::SERVER_UNAVAILABLE;
}
Status SingleKvStoreClient::SetSyncParam(const KvSyncParam &syncParam)
{
KvParam input(TransferTypeToByteArray<uint32_t>(syncParam.allowedDelayMs));
KvParam output;
return Control(KvControlCmd::SET_SYNC_PARAM, input, output);
}
Status SingleKvStoreClient::GetSyncParam(KvSyncParam &syncParam)
{
KvParam inputEmpty;
KvParam output;
Status ret = Control(KvControlCmd::GET_SYNC_PARAM, inputEmpty, output);
if (ret != Status::SUCCESS) {
return ret;
}
if (output.Size() == sizeof(uint32_t)) {
syncParam.allowedDelayMs = TransferByteArrayToType<uint32_t>(output.Data());
return Status::SUCCESS;
}
return Status::ERROR;
}
Status SingleKvStoreClient::Control(KvControlCmd cmd, const KvParam &inputParam, KvParam &output)
{
ZLOGI("begin.");
if (kvStoreProxy_ != nullptr) {
sptr<KvParam> kvParam;
Status status = kvStoreProxy_->Control(cmd, inputParam, kvParam);
if ((status == Status::SUCCESS) && (kvParam != nullptr)) {
output = *kvParam;
}
return status;
}
ZLOGE("singleKvstore proxy is nullptr.");
return Status::SERVER_UNAVAILABLE;
}
Status SingleKvStoreClient::SetCapabilityEnabled(bool enabled) const
{
if (kvStoreProxy_ != nullptr) {
return kvStoreProxy_->SetCapabilityEnabled(enabled);
}
ZLOGE("singleKvstore proxy is nullptr.");
return Status::SERVER_UNAVAILABLE;
}
Status SingleKvStoreClient::SetCapabilityRange(const std::vector<std::string> &localLabels,
const std::vector<std::string> &remoteLabels) const
{
if (kvStoreProxy_ != nullptr) {
return kvStoreProxy_->SetCapabilityRange(localLabels, remoteLabels);
}
ZLOGE("singleKvstore proxy is nullptr.");
return Status::SERVER_UNAVAILABLE;
}
Status SingleKvStoreClient::GetSecurityLevel(SecurityLevel &secLevel) const
{
if (kvStoreProxy_ != nullptr) {
return kvStoreProxy_->GetSecurityLevel(secLevel);
}
ZLOGE("singleKvstore proxy is nullptr.");
return Status::SERVER_UNAVAILABLE;
}
Status SingleKvStoreClient::Sync(const std::vector<std::string> &devices, SyncMode mode,
const DataQuery &query, std::shared_ptr<KvStoreSyncCallback> callback)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__), TraceSwitch::BYTRACE_ON);
if (kvStoreProxy_ == nullptr) {
ZLOGE("singleKvstore proxy is nullptr.");
return Status::SERVER_UNAVAILABLE;
}
if (devices.empty()) {
ZLOGW("deviceIds is empty.");
return Status::INVALID_ARGUMENT;
}
uint64_t sequenceId = KvStoreUtils::GenerateSequenceId();
if (callback != nullptr) {
syncCallbackClient_->AddSyncCallback(callback, sequenceId);
} else {
syncCallbackClient_->AddSyncCallback(syncObserver_, sequenceId);
}
RegisterCallback();
return kvStoreProxy_->Sync(devices, mode, query.ToString(), sequenceId);
}
Status SingleKvStoreClient::SubscribeWithQuery(const std::vector<std::string> &devices, const DataQuery &query)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__), TraceSwitch::BYTRACE_ON);
if (kvStoreProxy_ == nullptr) {
ZLOGE("singleKvstore proxy is nullptr.");
return Status::SERVER_UNAVAILABLE;
}
if (devices.empty()) {
ZLOGW("deviceIds is empty.");
return Status::INVALID_ARGUMENT;
}
uint64_t sequenceId = KvStoreUtils::GenerateSequenceId();
syncCallbackClient_->AddSyncCallback(syncObserver_, sequenceId);
RegisterCallback();
return kvStoreProxy_->Subscribe(devices, query.ToString(), sequenceId);
}
Status SingleKvStoreClient::UnsubscribeWithQuery(const std::vector<std::string> &deviceIds, const DataQuery &query)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__), TraceSwitch::BYTRACE_ON);
if (kvStoreProxy_ == nullptr) {
ZLOGE("singleKvstore proxy is nullptr.");
return Status::SERVER_UNAVAILABLE;
}
if (deviceIds.empty()) {
ZLOGW("deviceIds is empty.");
return Status::INVALID_ARGUMENT;
}
uint64_t sequenceId = KvStoreUtils::GenerateSequenceId();
syncCallbackClient_->AddSyncCallback(syncObserver_, sequenceId);
return kvStoreProxy_->UnSubscribe(deviceIds, query.ToString(), sequenceId);
}
} // namespace OHOS::DistributedKv

View File

@ -0,0 +1,105 @@
/*
* 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 DISTRIBUTEDDATAMGR2_SINGLE_KVSTORE_CLIENT_H
#define DISTRIBUTEDDATAMGR2_SINGLE_KVSTORE_CLIENT_H
#include <atomic>
#include "data_query.h"
#include "ikvstore_single.h"
#include "single_kvstore.h"
#include "kvstore_sync_callback_client.h"
#include "sync_observer.h"
namespace OHOS::DistributedKv {
class SingleKvStoreClient : public SingleKvStore {
public:
explicit SingleKvStoreClient(sptr<ISingleKvStore> kvStoreProxy, const std::string &storeId);
~SingleKvStoreClient();
StoreId GetStoreId() const override;
Status GetEntries(const Key &prefix, std::vector<Entry> &entries) const override;
Status GetEntries(const DataQuery &query, std::vector<Entry> &entries) const override;
Status GetResultSet(const Key &prefix, std::shared_ptr<KvStoreResultSet> &resultSet) const override;
Status GetResultSet(const DataQuery &query, std::shared_ptr<KvStoreResultSet> &resultSet) const override;
Status CloseResultSet(std::shared_ptr<KvStoreResultSet> &resultSet) override;
Status GetCount(const DataQuery &query, int &count) const override;
Status Sync(const std::vector<std::string> &devices, SyncMode mode, uint32_t delay) override;
Status RemoveDeviceData(const std::string &device) override;
Status Delete(const Key &key) override;
Status Put(const Key &key, const Value &value) override;
Status Get(const Key &key, Value &value) override;
Status SubscribeKvStore(SubscribeType subscribeType, std::shared_ptr<KvStoreObserver> observer) override;
Status UnSubscribeKvStore(SubscribeType subscribeType, std::shared_ptr<KvStoreObserver> observer) override;
Status RegisterSyncCallback(std::shared_ptr<KvStoreSyncCallback> callback) override;
Status RegisterCallback();
Status UnRegisterSyncCallback() override;
Status PutBatch(const std::vector<Entry> &entries) override;
Status DeleteBatch(const std::vector<Key> &keys) override;
Status StartTransaction() override;
Status Commit() override;
Status Rollback() override;
Status SetSyncParam(const KvSyncParam &syncParam) override;
Status GetSyncParam(KvSyncParam &syncParam) override;
Status SetCapabilityEnabled(bool enabled) const override;
Status SetCapabilityRange(const std::vector<std::string> &localLabels,
const std::vector<std::string> &remoteLabels) const override;
Status GetSecurityLevel(SecurityLevel &secLevel) const override;
Status Sync(const std::vector<std::string> &devices, SyncMode mode, const DataQuery &query,
std::shared_ptr<KvStoreSyncCallback> syncCallback) override;
Status SubscribeWithQuery(const std::vector<std::string> &devices, const DataQuery &query) override;
Status UnsubscribeWithQuery(const std::vector<std::string> &devices, const DataQuery &query) override;
protected:
Status Control(KvControlCmd cmd, const KvParam &inputParam, KvParam &outputParam);
private:
sptr<ISingleKvStore> kvStoreProxy_;
std::map<KvStoreObserver *, sptr<IKvStoreObserver>> registeredObservers_;
std::mutex observerMapMutex_;
std::string storeId_;
sptr<KvStoreSyncCallbackClient> syncCallbackClient_;
std::shared_ptr<SyncObserver> syncObserver_;
bool isRegisterSyncCallback_ = false;
std::mutex registerCallbackMutex_;
};
} // namespace OHOS::DistributedKv
#endif // DISTRIBUTEDDATAMGR2_SINGLE_KVSTORE_CLIENT_H

View File

@ -0,0 +1,50 @@
/*
* 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 "sync_observer.h"
namespace OHOS::DistributedKv {
SyncObserver::SyncObserver(const std::vector<std::shared_ptr<KvStoreSyncCallback>> &callbacks)
:callbacks_(callbacks)
{};
SyncObserver::SyncObserver()
{
std::lock_guard<decltype(mutex_)> lock(mutex_);
callbacks_.clear();
}
bool SyncObserver::Add(const std::shared_ptr<KvStoreSyncCallback> callback)
{
std::lock_guard<decltype(mutex_)> lock(mutex_);
callbacks_.push_back(callback);
return true;
}
bool SyncObserver::Clean()
{
std::lock_guard<decltype(mutex_)> lock(mutex_);
callbacks_.clear();
return true;
}
void SyncObserver::SyncCompleted(const std::map<std::string, DistributedKv::Status> &results)
{
std::lock_guard<decltype(mutex_)> lock(mutex_);
for (auto &callback : callbacks_) {
callback->SyncCompleted(results);
}
}
} // namespace OHOS::DistributedKv

View File

@ -0,0 +1,44 @@
/*
* 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_SYNC_OBSERVER_H
#define DISTRIBUTEDDATAMGR_DATAMGR_SYNC_OBSERVER_H
#include <vector>
#include <memory>
#include <mutex>
#include "kvstore_sync_callback.h"
namespace OHOS::DistributedKv {
class SyncObserver : public KvStoreSyncCallback {
public:
explicit SyncObserver(const std::vector<std::shared_ptr<KvStoreSyncCallback>> &callbacks);
SyncObserver();
virtual ~SyncObserver() = default;
bool Add(const std::shared_ptr<KvStoreSyncCallback> callback);
bool Clean();
void SyncCompleted(const std::map<std::string, DistributedKv::Status> &results) override;
private:
std::recursive_mutex mutex_;
std::vector<std::shared_ptr<KvStoreSyncCallback>> callbacks_;
};
} // namespace OHOS::DistributedKv
#endif // DISTRIBUTEDDATAMGR_DATAMGR_SYNC_OBSERVER_H

View File

@ -0,0 +1,213 @@
# 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/test.gni")
module_output_path = "distributeddatamgr/distributeddatafwk"
###############################################################################
config("module_private_config") {
visibility = [ ":*" ]
include_dirs = [
"../include/",
"../../../../interfaces/innerkits/distributeddata/",
# TEMP MODIFICATION FOR PMS
"../../../../services/distributeddataservice/app/include",
# for ipc_core interfaces.
"//commonlibrary/c_utils/base/include",
"//foundation/distributeddatamgr/kv_store/interfaces/innerkits/distributeddata/include",
]
}
ohos_unittest("DistributedKvDataManagerTest") {
module_out_path = module_output_path
sources = [ "unittest/distributed_kv_data_manager_test.cpp" ]
configs = [ ":module_private_config" ]
external_deps = [
"c_utils:utils",
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"samgr_standard:samgr_proxy",
]
deps = [
"//foundation/distributeddatamgr/kv_store/interfaces/innerkits/distributeddata:distributeddata_inner",
"//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/adapter:distributeddata_adapter",
"//third_party/googletest:gtest_main",
]
}
ohos_unittest("DistributedKvDataManagerEncryptTest") {
module_out_path = module_output_path
sources = [ "unittest/distributed_kv_data_manager_encrypt_test.cpp" ]
configs = [ ":module_private_config" ]
external_deps = [
"c_utils:utils",
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"samgr_standard:samgr_proxy",
]
deps = [
"//foundation/distributeddatamgr/kv_store/interfaces/innerkits/distributeddata:distributeddata_inner",
"//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/adapter:distributeddata_adapter",
"//third_party/googletest:gtest_main",
]
}
ohos_unittest("LocalSubscribeStoreTest") {
module_out_path = module_output_path
sources = [ "unittest/local_subscribe_store_test.cpp" ]
configs = [ ":module_private_config" ]
external_deps = [
"c_utils:utils",
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"samgr_standard:samgr_proxy",
]
deps = [
"//foundation/distributeddatamgr/kv_store/interfaces/innerkits/distributeddata:distributeddata_inner",
"//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/adapter:distributeddata_adapter",
"//third_party/googletest:gtest_main",
]
}
ohos_unittest("LocalSubscribeDeviceStoreTest") {
module_out_path = module_output_path
sources = [ "unittest/local_subscribe_device_store_test.cpp" ]
configs = [ ":module_private_config" ]
external_deps = [
"c_utils:utils",
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"samgr_standard:samgr_proxy",
]
deps = [
"//foundation/distributeddatamgr/kv_store/interfaces/innerkits/distributeddata:distributeddata_inner",
"//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/adapter:distributeddata_adapter",
"//third_party/googletest:gtest_main",
]
}
ohos_unittest("SingleKvStoreClientQueryTest") {
module_out_path = module_output_path
sources = [ "unittest/single_kvstore_client_query_test.cpp" ]
configs = [ ":module_private_config" ]
external_deps = [
"c_utils:utils",
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"samgr_standard:samgr_proxy",
]
deps = [
"//foundation/distributeddatamgr/kv_store/interfaces/innerkits/distributeddata:distributeddata_inner",
"//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/adapter:distributeddata_adapter",
"//third_party/googletest:gtest_main",
]
}
ohos_unittest("SingleKvStoreClientTest") {
module_out_path = module_output_path
sources = [ "unittest/single_kvstore_client_test.cpp" ]
configs = [ ":module_private_config" ]
external_deps = [
"c_utils:utils",
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"samgr_standard:samgr_proxy",
]
deps = [
"//foundation/distributeddatamgr/kv_store/interfaces/innerkits/distributeddata:distributeddata_inner",
"//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/adapter:distributeddata_adapter",
"//third_party/googletest:gtest_main",
]
}
ohos_unittest("DeviceKvStoreTest") {
module_out_path = module_output_path
sources = [ "unittest/device_kvstore_test.cpp" ]
configs = [ ":module_private_config" ]
external_deps = [
"c_utils:utils",
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"samgr_standard:samgr_proxy",
]
deps = [
"//foundation/distributeddatamgr/kv_store/interfaces/innerkits/distributeddata:distributeddata_inner",
"//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/adapter:distributeddata_adapter",
"//third_party/googletest:gtest_main",
]
}
ohos_unittest("BlobTest") {
module_out_path = module_output_path
sources = [ "unittest/blob_test.cpp" ]
configs = [ ":module_private_config" ]
deps = [
"//foundation/distributeddatamgr/kv_store/interfaces/innerkits/distributeddata:distributeddata_inner",
"//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/adapter:distributeddata_adapter",
"//third_party/googletest:gtest_main",
]
external_deps = [ "c_utils:utils" ]
}
###############################################################################
group("unittest") {
testonly = true
deps = []
deps += [
":BlobTest",
":DeviceKvStoreTest",
":DistributedKvDataManagerEncryptTest",
":DistributedKvDataManagerTest",
":LocalSubscribeDeviceStoreTest",
":LocalSubscribeStoreTest",
":SingleKvStoreClientQueryTest",
":SingleKvStoreClientTest",
]
}

View File

@ -0,0 +1,251 @@
/*
* 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 <gtest/gtest.h>
#include <cstdint>
#include <vector>
#include "types.h"
using namespace testing::ext;
using namespace OHOS::DistributedKv;
class BlobTest : public testing::Test {
public:
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
};
void BlobTest::SetUpTestCase(void)
{}
void BlobTest::TearDownTestCase(void)
{}
void BlobTest::SetUp(void)
{}
void BlobTest::TearDown(void)
{}
/**
* @tc.name: Size001
* @tc.desc: construct a Blob and check its size.
* @tc.type: FUNC
* @tc.require: AR000C6GBG
* @tc.author: liqiao
*/
HWTEST_F(BlobTest, Size001, TestSize.Level0)
{
Blob blob1;
EXPECT_EQ(blob1.Size(), (size_t)0);
Blob blob2 = "1234567890";
EXPECT_EQ(blob2.Size(), (size_t)10);
Blob blob3("12345");
EXPECT_EQ(blob3.Size(), (size_t)5);
std::string strTmp = "123";
const char *chr = strTmp.c_str();
Blob blob4(chr);
EXPECT_EQ(blob4.Size(), (size_t)3);
std::vector<uint8_t> vec = {'1', '2', '3', '4'};
Blob blob5(vec);
EXPECT_EQ(blob5.Size(), (size_t)4);
const char *chr1 = strTmp.c_str();
Blob blob6(chr1, strlen(chr1));
EXPECT_EQ(blob6.Size(), (size_t)3);
}
/**
* @tc.name: Empty001
* @tc.desc: construct a Blob and check its empty.
* @tc.type: FUNC
* @tc.require: AR000C6GBG
* @tc.author: liqiao
*/
HWTEST_F(BlobTest, Empty001, TestSize.Level0)
{
Blob blob1;
EXPECT_EQ(blob1.Empty(), true);
Blob blob2 = "1234567890";
EXPECT_EQ(blob2.Empty(), false);
Blob blob3("12345");
EXPECT_EQ(blob3.Empty(), false);
std::string strTmp = "123";
const char *chr = strTmp.c_str();
Blob blob4(chr);
EXPECT_EQ(blob4.Empty(), false);
std::vector<uint8_t> vec = {'1', '2', '3', '4'};
Blob blob5(vec);
EXPECT_EQ(blob5.Empty(), false);
const char *chr1 = strTmp.c_str();
Blob blob6(chr1, strlen(chr1));
EXPECT_EQ(blob6.Empty(), false);
}
/**
* @tc.name: Clear001
* @tc.desc: construct a Blob and check it clear function.
* @tc.type: FUNC
* @tc.require: AR000C6GBG
* @tc.author: liqiao
*/
HWTEST_F(BlobTest, Clear001, TestSize.Level0)
{
Blob blob1 = "1234567890";
blob1.Clear();
EXPECT_EQ(blob1.Empty(), true);
Blob blob2("12345");
blob2.Clear();
EXPECT_EQ(blob2.Empty(), true);
std::string strTmp = "123";
const char *chr = strTmp.c_str();
Blob blob3(chr);
blob3.Clear();
EXPECT_EQ(blob3.Empty(), true);
std::vector<uint8_t> vec = {'1', '2', '3', '4'};
Blob blob4(vec);
blob4.Clear();
EXPECT_EQ(blob4.Empty(), true);
}
/**
* @tc.name: StartsWith001
* @tc.desc: construct a Blob and check it StartsWith function.
* @tc.type: FUNC
* @tc.require: AR000C6GBG
* @tc.author: liqiao
*/
HWTEST_F(BlobTest, StartsWith001, TestSize.Level0)
{
Blob blob1 = "1234567890";
Blob blob2("12345");
EXPECT_EQ(blob1.StartsWith(blob2), true);
EXPECT_EQ(blob2.StartsWith(blob1), false);
Blob blob3("234");
EXPECT_EQ(blob1.StartsWith(blob3), false);
EXPECT_EQ(blob2.StartsWith(blob3), false);
}
/**
* @tc.name: Compare001
* @tc.desc: construct a Blob and check it compare function.
* @tc.type: FUNC
* @tc.require: AR000C6GBG
* @tc.author: liqiao
*/
HWTEST_F(BlobTest, Compare001, TestSize.Level0)
{
Blob blob1 = "1234567890";
Blob blob2("12345");
EXPECT_EQ(blob1.Compare(blob2), 1);
EXPECT_EQ(blob2.Compare(blob1), -1);
Blob blob3("12345");
EXPECT_EQ(blob2.Compare(blob3), 0);
}
/**
* @tc.name: Data001
* @tc.desc: construct a Blob and check it Data function.
* @tc.type: FUNC
* @tc.require: AR000C6GBG
* @tc.author: liqiao
*/
HWTEST_F(BlobTest, Data001, TestSize.Level0)
{
std::vector<uint8_t> result = {'1', '2', '3', '4'};
Blob blob1("1234");
EXPECT_EQ(blob1.Data(), result);
std::vector<uint8_t> result2 = {'1', '2', '3', '4', '5'};
Blob blob2("12345");
EXPECT_EQ(blob2.Data(), result2);
}
/**
* @tc.name: ToString001
* @tc.desc: construct a Blob and check it ToString function.
* @tc.type: FUNC
* @tc.require: AR000C6GBG
* @tc.author: liqiao
*/
HWTEST_F(BlobTest, ToString001, TestSize.Level0)
{
Blob blob1("1234");
std::string str = "1234";
EXPECT_EQ(blob1.ToString(), str);
}
/**
* @tc.name: OperatorEqual001
* @tc.desc: construct a Blob and check it operator== function.
* @tc.type: FUNC
* @tc.require: AR000C6GBG
* @tc.author: liqiao
*/
HWTEST_F(BlobTest, OperatorEqual001, TestSize.Level0)
{
Blob blob1("1234");
Blob blob2("1234");
EXPECT_EQ(blob1 == blob2, true);
Blob blob3("12345");
EXPECT_EQ(blob1 == blob3, false);
}
/**
* @tc.name: Operator001
* @tc.desc: construct a Blob and check it operator[] function.
* @tc.type: FUNC
* @tc.require: AR000C6GBG
* @tc.author: liqiao
*/
HWTEST_F(BlobTest, Operator001, TestSize.Level0)
{
Blob blob1("1234");
EXPECT_EQ(blob1[0], '1');
EXPECT_EQ(blob1[1], '2');
EXPECT_EQ(blob1[2], '3');
EXPECT_EQ(blob1[3], '4');
EXPECT_EQ(blob1[4], 0);
}
/**
* @tc.name: Operator002
* @tc.desc: construct a Blob and check it operator= function.
* @tc.type: FUNC
* @tc.require: AR000C6GBG
* @tc.author: liqiao
*/
HWTEST_F(BlobTest, Operator002, TestSize.Level0)
{
Blob blob1("1234");
Blob blob2 = blob1;
EXPECT_EQ(blob1 == blob2, true);
EXPECT_EQ(blob2.ToString(), "1234");
}
/**
* @tc.name: Operator003
* @tc.desc: construct a Blob and check it operator= function.
* @tc.type: FUNC
* @tc.require: AR000C6GBG
* @tc.author: liqiao
*/
HWTEST_F(BlobTest, Operator003, TestSize.Level0)
{
Blob blob1("1234");
Blob blob2 = std::move(blob1);
EXPECT_EQ(blob1 == blob2, false);
EXPECT_EQ(blob1.Empty(), true);
EXPECT_EQ(blob2.ToString(), "1234");
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,130 @@
/*
* 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 "DistributedKvDataManagerEncryptTest"
#include <gtest/gtest.h>
#include "distributed_kv_data_manager.h"
#include "kvstore_death_recipient.h"
#include "log_print.h"
#include "types.h"
using namespace testing::ext;
using namespace OHOS::DistributedKv;
class DistributedKvDataManagerEncryptTest : public testing::Test {
public:
static DistributedKvDataManager manager;
static Options createEnc;
static UserId userId;
static AppId appId;
static StoreId storeId;
static void SetUpTestCase(void);
static void TearDownTestCase(void);
static void RemoveAllStore(DistributedKvDataManager manager);
void SetUp();
void TearDown();
DistributedKvDataManagerEncryptTest();
virtual ~DistributedKvDataManagerEncryptTest();
};
class MyDeathRecipient : public KvStoreDeathRecipient {
public:
MyDeathRecipient() {}
virtual ~MyDeathRecipient() {}
void OnRemoteDied() override {}
};
DistributedKvDataManager DistributedKvDataManagerEncryptTest::manager;
Options DistributedKvDataManagerEncryptTest::createEnc;
UserId DistributedKvDataManagerEncryptTest::userId;
AppId DistributedKvDataManagerEncryptTest::appId;
StoreId DistributedKvDataManagerEncryptTest::storeId;
void DistributedKvDataManagerEncryptTest::RemoveAllStore(DistributedKvDataManager manager)
{
manager.CloseAllKvStore(appId);
manager.DeleteKvStore(appId, storeId, createEnc.baseDir);
manager.DeleteAllKvStore(appId, createEnc.baseDir);
}
void DistributedKvDataManagerEncryptTest::SetUpTestCase(void)
{
createEnc.createIfMissing = true;
createEnc.encrypt = true;
createEnc.autoSync = true;
createEnc.kvStoreType = SINGLE_VERSION;
userId.userId = "account0";
appId.appId = "com.ohos.nb.service";
storeId.storeId = "EncryptStoreId";
createEnc.area = EL1;
createEnc.baseDir = std::string("/data/service/el1/public/database/") + appId.appId;
mkdir(createEnc.baseDir.c_str(), (S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH));
}
void DistributedKvDataManagerEncryptTest::TearDownTestCase(void)
{
RemoveAllStore(manager);
(void)remove((createEnc.baseDir + "/kvdb").c_str());
(void)remove(createEnc.baseDir.c_str());
}
void DistributedKvDataManagerEncryptTest::SetUp(void)
{}
DistributedKvDataManagerEncryptTest::DistributedKvDataManagerEncryptTest(void)
{}
DistributedKvDataManagerEncryptTest::~DistributedKvDataManagerEncryptTest(void)
{}
void DistributedKvDataManagerEncryptTest::TearDown(void)
{}
/**
* @tc.name: kvstore_ddm_createEncryptedStore_001
* @tc.desc: Create an encrypted KvStore.
* @tc.type: FUNC
* @tc.require: SR000D08K4 AR000D08KQ
* @tc.author: liqiao
*/
HWTEST_F(DistributedKvDataManagerEncryptTest, kvstore_ddm_createEncryptedStore_001, TestSize.Level1)
{
ZLOGI("kvstore_ddm_createEncryptedStore_001 begin.");
std::shared_ptr<SingleKvStore> kvStore;
Status status = manager.GetSingleKvStore(createEnc, appId, storeId, kvStore);
ASSERT_EQ(status, Status::SUCCESS);
ASSERT_NE(kvStore, nullptr);
Key key = "age";
Value value = "18";
status = kvStore->Put(key, value);
EXPECT_EQ(Status::SUCCESS, status) << "KvStore put data return wrong status";
// get value from kvstore.
Value valueRet;
Status statusRet = kvStore->Get(key, valueRet);
EXPECT_EQ(Status::SUCCESS, statusRet) << "get data return wrong status";
EXPECT_EQ(value, valueRet) << "value and valueRet are not equal";
}

View File

@ -0,0 +1,718 @@
/*
* 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 "DistributedKvDataManagerTest"
#include "distributed_kv_data_manager.h"
#include <gtest/gtest.h>
#include <vector>
#include "kvstore_death_recipient.h"
#include "log_print.h"
#include "types.h"
using namespace testing::ext;
using namespace OHOS::DistributedKv;
class DistributedKvDataManagerTest : public testing::Test {
public:
static DistributedKvDataManager manager;
static Options create;
static Options noCreate;
static UserId userId;
static AppId appId;
static StoreId storeId64;
static StoreId storeId65;
static StoreId storeIdTest;
static StoreId storeIdEmpty;
static Entry entryA;
static Entry entryB;
static void SetUpTestCase(void);
static void TearDownTestCase(void);
static void RemoveAllStore(DistributedKvDataManager manager);
void SetUp();
void TearDown();
DistributedKvDataManagerTest();
};
class MyDeathRecipient : public KvStoreDeathRecipient {
public:
MyDeathRecipient() {}
virtual ~MyDeathRecipient() {}
void OnRemoteDied() override {}
};
DistributedKvDataManager DistributedKvDataManagerTest::manager;
Options DistributedKvDataManagerTest::create;
Options DistributedKvDataManagerTest::noCreate;
UserId DistributedKvDataManagerTest::userId;
AppId DistributedKvDataManagerTest::appId;
StoreId DistributedKvDataManagerTest::storeId64;
StoreId DistributedKvDataManagerTest::storeId65;
StoreId DistributedKvDataManagerTest::storeIdTest;
StoreId DistributedKvDataManagerTest::storeIdEmpty;
Entry DistributedKvDataManagerTest::entryA;
Entry DistributedKvDataManagerTest::entryB;
void DistributedKvDataManagerTest::RemoveAllStore(DistributedKvDataManager manager)
{
manager.CloseAllKvStore(appId);
manager.DeleteAllKvStore(appId, create.baseDir);
}
void DistributedKvDataManagerTest::SetUpTestCase(void)
{
userId.userId = "account0";
appId.appId = "ohos.kvdatamanager.test";
create.createIfMissing = true;
create.encrypt = false;
create.autoSync = true;
create.kvStoreType = SINGLE_VERSION;
create.area = EL1;
create.baseDir = std::string("/data/service/el1/public/database/") + appId.appId;
mkdir(create.baseDir.c_str(), (S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH));
noCreate.createIfMissing = false;
noCreate.encrypt = false;
noCreate.autoSync = true;
noCreate.kvStoreType = SINGLE_VERSION;
noCreate.area = EL1;
noCreate.baseDir = create.baseDir;
storeId64.storeId = "a000000000b000000000c000000000d000000000e000000000f000000000g000";
storeId65.storeId = "a000000000b000000000c000000000d000000000e000000000f000000000g000"
"a000000000b000000000c000000000d000000000e000000000f000000000g0000";
storeIdTest.storeId = "test";
storeIdEmpty.storeId = "";
entryA.key = "a";
entryA.value = "valueA";
entryB.key = "b";
entryB.value = "valueB";
RemoveAllStore(manager);
}
void DistributedKvDataManagerTest::TearDownTestCase(void)
{
RemoveAllStore(manager);
(void)remove((create.baseDir + "/kvdb").c_str());
(void)remove(create.baseDir.c_str());
}
void DistributedKvDataManagerTest::SetUp(void)
{}
DistributedKvDataManagerTest::DistributedKvDataManagerTest(void)
{}
void DistributedKvDataManagerTest::TearDown(void)
{
RemoveAllStore(manager);
}
/**
* @tc.name: GetKvStore001
* @tc.desc: Get an exist SingleKvStore
* @tc.type: FUNC
* @tc.require: SR000CQDU0 AR000BVTDM
* @tc.author: liqiao
*/
HWTEST_F(DistributedKvDataManagerTest, GetKvStore001, TestSize.Level1)
{
ZLOGI("GetKvStore001 begin.");
std::shared_ptr<SingleKvStore> notExistKvStore;
Status status = manager.GetSingleKvStore(create, appId, storeId64, notExistKvStore);
ASSERT_EQ(status, Status::SUCCESS);
EXPECT_NE(notExistKvStore, nullptr);
std::shared_ptr<SingleKvStore> existKvStore;
status = manager.GetSingleKvStore(noCreate, appId, storeId64, existKvStore);
ASSERT_EQ(status, Status::SUCCESS);
EXPECT_NE(existKvStore, nullptr);
}
/**
* @tc.name: GetKvStore002
* @tc.desc: Create and get a new SingleKvStore
* @tc.type: FUNC
* @tc.require: SR000CQDU0 AR000BVTDM
* @tc.author: liqiao
*/
HWTEST_F(DistributedKvDataManagerTest, GetKvStore002, TestSize.Level1)
{
ZLOGI("GetKvStore002 begin.");
std::shared_ptr<SingleKvStore> notExistKvStore;
Status status = manager.GetSingleKvStore(create, appId, storeId64, notExistKvStore);
ASSERT_EQ(status, Status::SUCCESS);
EXPECT_NE(notExistKvStore, nullptr);
manager.CloseKvStore(appId, storeId64);
manager.DeleteKvStore(appId, storeId64);
}
/**
* @tc.name: GetKvStore003
* @tc.desc: Get a non-existing SingleKvStore, and the callback function should receive STORE_NOT_FOUND and
* get a nullptr.
* @tc.type: FUNC
* @tc.require: SR000CQDU0 AR000BVTDM
* @tc.author: liqiao
*/
HWTEST_F(DistributedKvDataManagerTest, GetKvStore003, TestSize.Level1)
{
ZLOGI("GetKvStore003 begin.");
std::shared_ptr<SingleKvStore> notExistKvStore;
(void)manager.GetSingleKvStore(noCreate, appId, storeId64, notExistKvStore);
EXPECT_EQ(notExistKvStore, nullptr);
}
/**
* @tc.name: GetKvStore004
* @tc.desc: Create a SingleKvStore with an empty storeId, and the callback function should receive
* @tc.type: FUNC
* @tc.require: SR000CQDU0 AR000BVTDM
* @tc.author: liqiao
*/
HWTEST_F(DistributedKvDataManagerTest, GetKvStore004, TestSize.Level1)
{
ZLOGI("GetKvStore004 begin.");
std::shared_ptr<SingleKvStore> notExistKvStore;
Status status = manager.GetSingleKvStore(create, appId, storeIdEmpty, notExistKvStore);
ASSERT_EQ(status, Status::INVALID_ARGUMENT);
EXPECT_EQ(notExistKvStore, nullptr);
}
/**
* @tc.name: GetKvStore005
* @tc.desc: Get a SingleKvStore with an empty storeId, and the callback function should receive INVALID_ARGUMENT
* @tc.type: FUNC
* @tc.require: SR000CQDU0 AR000BVTDM
* @tc.author: liqiao
*/
HWTEST_F(DistributedKvDataManagerTest, GetKvStore005, TestSize.Level1)
{
ZLOGI("GetKvStore005 begin.");
std::shared_ptr<SingleKvStore> notExistKvStore;
Status status = manager.GetSingleKvStore(noCreate, appId, storeIdEmpty, notExistKvStore);
ASSERT_EQ(status, Status::INVALID_ARGUMENT);
EXPECT_EQ(notExistKvStore, nullptr);
}
/**
* @tc.name: GetKvStore006
* @tc.desc: Create a SingleKvStore with a 65-byte storeId, and the callback function should receive INVALID_ARGUMENT
* @tc.type: FUNC
* @tc.require: SR000CQDU0 AR000BVTDM
* @tc.author: liqiao
*/
HWTEST_F(DistributedKvDataManagerTest, GetKvStore006, TestSize.Level1)
{
ZLOGI("GetKvStore006 begin.");
std::shared_ptr<SingleKvStore> notExistKvStore;
Status status = manager.GetSingleKvStore(create, appId, storeId65, notExistKvStore);
ASSERT_EQ(status, Status::INVALID_ARGUMENT);
EXPECT_EQ(notExistKvStore, nullptr);
}
/**
* @tc.name: GetKvStore007
* @tc.desc: Get a SingleKvStore with a 65-byte storeId, the callback function should receive INVALID_ARGUMENT
* @tc.type: FUNC
* @tc.require: SR000CQDU0 AR000BVTDM
* @tc.author: liqiao
*/
HWTEST_F(DistributedKvDataManagerTest, GetKvStore007, TestSize.Level1)
{
ZLOGI("GetKvStore007 begin.");
std::shared_ptr<SingleKvStore> notExistKvStore;
Status status = manager.GetSingleKvStore(noCreate, appId, storeId65, notExistKvStore);
ASSERT_EQ(status, Status::INVALID_ARGUMENT);
EXPECT_EQ(notExistKvStore, nullptr);
}
/**
* @tc.name: GetAllKvStore001
* @tc.desc: Get all KvStore IDs when no KvStore exists, and the callback function should receive a 0-length vector.
* @tc.type: FUNC
* @tc.require: SR000CQDU0 AR000BVTDM
* @tc.author: liqiao
*/
HWTEST_F(DistributedKvDataManagerTest, GetAllKvStore001, TestSize.Level1)
{
ZLOGI("GetAllKvStore001 begin.");
std::vector<StoreId> storeIds;
Status status = manager.GetAllKvStoreId(appId, storeIds);
EXPECT_EQ(status, Status::SUCCESS);
EXPECT_EQ(storeIds.size(), static_cast<size_t>(0));
}
/**
* @tc.name: GetAllKvStore002
* @tc.desc: Get all SingleKvStore IDs when no KvStore exists, and the callback function should receive a empty vector.
* @tc.type: FUNC
* @tc.require: SR000CQDU0 AR000BVTDM
* @tc.author: liqiao
*/
HWTEST_F(DistributedKvDataManagerTest, GetAllKvStore002, TestSize.Level1)
{
ZLOGI("GetAllKvStore002 begin.");
StoreId id1;
id1.storeId = "id1";
StoreId id2;
id2.storeId = "id2";
StoreId id3;
id3.storeId = "id3";
std::shared_ptr<SingleKvStore> kvStore;
Status status = manager.GetSingleKvStore(create, appId, id1, kvStore);
ASSERT_NE(kvStore, nullptr);
ASSERT_EQ(status, Status::SUCCESS);
status = manager.GetSingleKvStore(create, appId, id2, kvStore);
ASSERT_NE(kvStore, nullptr);
ASSERT_EQ(status, Status::SUCCESS);
status = manager.GetSingleKvStore(create, appId, id3, kvStore);
ASSERT_NE(kvStore, nullptr);
ASSERT_EQ(status, Status::SUCCESS);
std::vector<StoreId> storeIds;
status = manager.GetAllKvStoreId(appId, storeIds);
EXPECT_EQ(status, Status::SUCCESS);
bool haveId1 = false;
bool haveId2 = false;
bool haveId3 = false;
for (StoreId &id : storeIds) {
if (id.storeId == "id1") {
haveId1 = true;
} else if (id.storeId == "id2") {
haveId2 = true;
} else if (id.storeId == "id3") {
haveId3 = true;
} else {
ZLOGI("got an unknown storeId.");
EXPECT_TRUE(false);
}
}
EXPECT_TRUE(haveId1);
EXPECT_TRUE(haveId2);
EXPECT_TRUE(haveId3);
EXPECT_EQ(storeIds.size(), static_cast<size_t>(3));
}
/**
* @tc.name: CloseKvStore001
* @tc.desc: Close an opened KVStore, and the callback function should return SUCCESS.
* @tc.type: FUNC
* @tc.require: SR000CQDU0 AR000BVTDM
* @tc.author: liqiao
*/
HWTEST_F(DistributedKvDataManagerTest, CloseKvStore001, TestSize.Level1)
{
ZLOGI("CloseKvStore001 begin.");
std::shared_ptr<SingleKvStore> kvStore;
Status status = manager.GetSingleKvStore(create, appId, storeId64, kvStore);
ASSERT_EQ(status, Status::SUCCESS);
ASSERT_NE(kvStore, nullptr);
Status stat = manager.CloseKvStore(appId, storeId64);
EXPECT_EQ(stat, Status::SUCCESS);
}
/**
* @tc.name: CloseKvStore002
* @tc.desc: Close a closed SingleKvStore, and the callback function should return SUCCESS.
* @tc.type: FUNC
* @tc.require: SR000CQDU0 AR000BVTDM
* @tc.author: liqiao
*/
HWTEST_F(DistributedKvDataManagerTest, CloseKvStore002, TestSize.Level1)
{
ZLOGI("CloseKvStore002 begin.");
std::shared_ptr<SingleKvStore> kvStore;
Status status = manager.GetSingleKvStore(create, appId, storeId64, kvStore);
ASSERT_EQ(status, Status::SUCCESS);
ASSERT_NE(kvStore, nullptr);
manager.CloseKvStore(appId, storeId64);
Status stat = manager.CloseKvStore(appId, storeId64);
EXPECT_EQ(stat, Status::STORE_NOT_OPEN);
}
/**
* @tc.name: CloseKvStore003
* @tc.desc: Close a SingleKvStore with an empty storeId, and the callback function should return INVALID_ARGUMENT.
* @tc.type: FUNC
* @tc.require: SR000CQDU0 AR000BVTDM
* @tc.author: liqiao
*/
HWTEST_F(DistributedKvDataManagerTest, CloseKvStore003, TestSize.Level1)
{
ZLOGI("CloseKvStore003 begin.");
Status stat = manager.CloseKvStore(appId, storeIdEmpty);
EXPECT_EQ(stat, Status::INVALID_ARGUMENT);
}
/**
* @tc.name: CloseKvStore004
* @tc.desc: Close a SingleKvStore with a 65-byte storeId, and the callback function should return INVALID_ARGUMENT.
* @tc.type: FUNC
* @tc.require: SR000CQDU0 AR000BVTDM
* @tc.author: liqiao
*/
HWTEST_F(DistributedKvDataManagerTest, CloseKvStore004, TestSize.Level1)
{
ZLOGI("CloseKvStore004 begin.");
Status stat = manager.CloseKvStore(appId, storeId65);
EXPECT_EQ(stat, Status::INVALID_ARGUMENT);
}
/**
* @tc.name: CloseKvStore005
* @tc.desc: Close a non-existing SingleKvStore, and the callback function should return STORE_NOT_OPEN.
* @tc.type: FUNC
* @tc.require: SR000CQDU0 AR000BVTDM
* @tc.author: liqiao
*/
HWTEST_F(DistributedKvDataManagerTest, CloseKvStore005, TestSize.Level1)
{
ZLOGI("CloseKvStore005 begin.");
Status stat = manager.CloseKvStore(appId, storeId64);
EXPECT_EQ(stat, Status::STORE_NOT_OPEN);
}
/**
* @tc.name: CloseKvStoreMulti001
* @tc.desc: Open a SingleKvStore several times and close them one by one.
* @tc.type: FUNC
* @tc.require: SR000CQDU0 AR000CSKRU
* @tc.author: liqiao
*/
HWTEST_F(DistributedKvDataManagerTest, CloseKvStoreMulti001, TestSize.Level1)
{
ZLOGI("CloseKvStoreMulti001 begin.");
std::shared_ptr<SingleKvStore> notExistKvStore;
Status status = manager.GetSingleKvStore(create, appId, storeId64, notExistKvStore);
ASSERT_EQ(status, Status::SUCCESS);
EXPECT_NE(notExistKvStore, nullptr);
std::shared_ptr<SingleKvStore> existKvStore;
manager.GetSingleKvStore(noCreate, appId, storeId64, existKvStore);
ASSERT_EQ(status, Status::SUCCESS);
EXPECT_NE(existKvStore, nullptr);
Status stat = manager.CloseKvStore(appId, storeId64);
EXPECT_EQ(stat, Status::SUCCESS);
stat = manager.CloseKvStore(appId, storeId64);
EXPECT_EQ(stat, Status::SUCCESS);
}
/**
* @tc.name: CloseKvStoreMulti002
* @tc.desc: Open a SingleKvStore several times and close them one by one.
* @tc.type: FUNC
* @tc.require: SR000CQDU0 AR000CSKRU
* @tc.author: liqiao
*/
HWTEST_F(DistributedKvDataManagerTest, CloseKvStoreMulti002, TestSize.Level1)
{
ZLOGI("CloseKvStoreMulti002 begin.");
std::shared_ptr<SingleKvStore> notExistKvStore;
Status status = manager.GetSingleKvStore(create, appId, storeId64, notExistKvStore);
ASSERT_EQ(status, Status::SUCCESS);
EXPECT_NE(notExistKvStore, nullptr);
std::shared_ptr<SingleKvStore> existKvStore1;
status = manager.GetSingleKvStore(noCreate, appId, storeId64, existKvStore1);
ASSERT_EQ(status, Status::SUCCESS);
EXPECT_NE(existKvStore1, nullptr);
std::shared_ptr<SingleKvStore> existKvStore2;
status = manager.GetSingleKvStore(noCreate, appId, storeId64, existKvStore2);
ASSERT_EQ(status, Status::SUCCESS);
EXPECT_NE(existKvStore2, nullptr);
Status stat = manager.CloseKvStore(appId, storeId64);
EXPECT_EQ(stat, Status::SUCCESS);
stat = manager.CloseKvStore(appId, storeId64);
EXPECT_EQ(stat, Status::SUCCESS);
stat = manager.CloseKvStore(appId, storeId64);
EXPECT_EQ(stat, Status::SUCCESS);
stat = manager.CloseKvStore(appId, storeId64);
EXPECT_NE(stat, Status::SUCCESS);
}
/**
* @tc.name: CloseAllKvStore001
* @tc.desc: Close all opened KvStores, and the callback function should return SUCCESS.
* @tc.type: FUNC
* @tc.require: SR000CQDU0 AR000BVTDM
* @tc.author: liqiao
*/
HWTEST_F(DistributedKvDataManagerTest, CloseAllKvStore001, TestSize.Level1)
{
ZLOGI("CloseAllKvStore001 begin.");
std::shared_ptr<SingleKvStore> kvStore1;
Status status = manager.GetSingleKvStore(create, appId, storeId64, kvStore1);
ASSERT_EQ(status, Status::SUCCESS);
ASSERT_NE(kvStore1, nullptr);
std::shared_ptr<SingleKvStore> kvStore2;
status = manager.GetSingleKvStore(create, appId, storeIdTest, kvStore2);
ASSERT_EQ(status, Status::SUCCESS);
ASSERT_NE(kvStore2, nullptr);
Status stat = manager.CloseAllKvStore(appId);
EXPECT_EQ(stat, Status::SUCCESS);
}
/**
* @tc.name: CloseAllKvStore002
* @tc.desc: Close all KvStores which exist but are not opened, and the callback function should return STORE_NOT_OPEN.
* @tc.type: FUNC
* @tc.require: SR000CQDU0 AR000BVTDM
* @tc.author: liqiao
*/
HWTEST_F(DistributedKvDataManagerTest, CloseAllKvStore002, TestSize.Level1)
{
ZLOGI("CloseAllKvStore002 begin.");
std::shared_ptr<SingleKvStore> kvStore;
Status status = manager.GetSingleKvStore(create, appId, storeId64, kvStore);
ASSERT_EQ(status, Status::SUCCESS);
ASSERT_NE(kvStore, nullptr);
std::shared_ptr<SingleKvStore> kvStore2;
status = manager.GetSingleKvStore(create, appId, storeIdTest, kvStore2);
ASSERT_EQ(status, Status::SUCCESS);
ASSERT_NE(kvStore2, nullptr);
Status stat = manager.CloseKvStore(appId, storeId64);
EXPECT_EQ(stat, Status::SUCCESS);
stat = manager.CloseAllKvStore(appId);
EXPECT_EQ(stat, Status::SUCCESS);
}
/**
* @tc.name: DeleteKvStore001
* @tc.desc: Delete a closed KvStore, and the callback function should return SUCCESS.
* @tc.type: FUNC
* @tc.require: SR000CQDU0 AR000BVTDM
* @tc.author: liqiao
*/
HWTEST_F(DistributedKvDataManagerTest, DeleteKvStore001, TestSize.Level1)
{
ZLOGI("DeleteKvStore001 begin.");
std::shared_ptr<SingleKvStore> kvStore;
Status status = manager.GetSingleKvStore(create, appId, storeId64, kvStore);
ASSERT_EQ(status, Status::SUCCESS);
ASSERT_NE(kvStore, nullptr);
Status stat = manager.CloseKvStore(appId, storeId64);
ASSERT_EQ(stat, Status::SUCCESS);
stat = manager.DeleteKvStore(appId, storeId64, create.baseDir);
EXPECT_EQ(stat, Status::SUCCESS);
}
/**
* @tc.name: DeleteKvStore002
* @tc.desc: Delete an opened SingleKvStore, and the callback function should return SUCCESS.
* @tc.type: FUNC
* @tc.require: SR000CQDU0 AR000BVTDM
* @tc.author: liqiao
*/
HWTEST_F(DistributedKvDataManagerTest, DeleteKvStore002, TestSize.Level1)
{
ZLOGI("DeleteKvStore002 begin.");
std::shared_ptr<SingleKvStore> kvStore;
Status status = manager.GetSingleKvStore(create, appId, storeId64, kvStore);
ASSERT_EQ(status, Status::SUCCESS);
ASSERT_NE(kvStore, nullptr);
// first close it if opened, and then delete it.
Status stat = manager.DeleteKvStore(appId, storeId64, create.baseDir);
EXPECT_EQ(stat, Status::SUCCESS);
}
/**
* @tc.name: DeleteKvStore003
* @tc.desc: Delete a non-existing KvStore, and the callback function should return DB_ERROR.
* @tc.type: FUNC
* @tc.require: SR000CQDU0 AR000BVTDM
* @tc.author: liqiao
*/
HWTEST_F(DistributedKvDataManagerTest, DeleteKvStore003, TestSize.Level1)
{
ZLOGI("DeleteKvStore003 begin.");
Status stat = manager.DeleteKvStore(appId, storeId64, create.baseDir);
EXPECT_EQ(stat, Status::STORE_NOT_FOUND);
}
/**
* @tc.name: DeleteKvStore004
* @tc.desc: Delete a KvStore with an empty storeId, and the callback function should return INVALID_ARGUMENT.
* @tc.type: FUNC
* @tc.require: SR000CQDU0 AR000BVTDM
* @tc.author: liqiao
*/
HWTEST_F(DistributedKvDataManagerTest, DeleteKvStore004, TestSize.Level1)
{
ZLOGI("DeleteKvStore004 begin.");
Status stat = manager.DeleteKvStore(appId, storeIdEmpty);
EXPECT_EQ(stat, Status::INVALID_ARGUMENT);
}
/**
* @tc.name: DeleteKvStore005
* @tc.desc: Delete a KvStore with 65 bytes long storeId (which exceed storeId length limit). Should
* return INVALID_ARGUMENT.
* @tc.type: FUNC
* @tc.require: SR000CQDU0 AR000BVTDM
* @tc.author: liqiao
*/
HWTEST_F(DistributedKvDataManagerTest, DeleteKvStore005, TestSize.Level1)
{
ZLOGI("DeleteKvStore005 begin.");
Status stat = manager.DeleteKvStore(appId, storeId65);
EXPECT_EQ(stat, Status::INVALID_ARGUMENT);
}
/**
* @tc.name: DeleteAllKvStore001
* @tc.desc: Delete all KvStores after closing all of them, and the callback function should return SUCCESS.
* @tc.type: FUNC
* @tc.require: SR000CQDU0 AR000BVTDM
* @tc.author: liqiao
*/
HWTEST_F(DistributedKvDataManagerTest, DeleteAllKvStore001, TestSize.Level1)
{
ZLOGI("DeleteAllKvStore001 begin.");
std::shared_ptr<SingleKvStore> kvStore1;
Status status = manager.GetSingleKvStore(create, appId, storeId64, kvStore1);
ASSERT_EQ(status, Status::SUCCESS);
ASSERT_NE(kvStore1, nullptr);
std::shared_ptr<SingleKvStore> kvStore2;
status = manager.GetSingleKvStore(create, appId, storeIdTest, kvStore2);
ASSERT_EQ(status, Status::SUCCESS);
ASSERT_NE(kvStore2, nullptr);
Status stat = manager.CloseKvStore(appId, storeId64);
EXPECT_EQ(stat, Status::SUCCESS);
stat = manager.CloseKvStore(appId, storeIdTest);
EXPECT_EQ(stat, Status::SUCCESS);
stat = manager.DeleteAllKvStore(appId, create.baseDir);
EXPECT_EQ(stat, Status::SUCCESS);
}
/**
* @tc.name: DeleteAllKvStore002
* @tc.desc: Delete all kvstore fail when any kvstore in the appId is not closed
* @tc.type: FUNC
* @tc.require: SR000CQDU0 AR000BVTDM
* @tc.author: liqiao
*/
HWTEST_F(DistributedKvDataManagerTest, DeleteAllKvStore002, TestSize.Level1)
{
ZLOGI("DeleteAllKvStore002 begin.");
std::shared_ptr<SingleKvStore> kvStore1;
Status status = manager.GetSingleKvStore(create, appId, storeId64, kvStore1);
ASSERT_EQ(status, Status::SUCCESS);
ASSERT_NE(kvStore1, nullptr);
std::shared_ptr<SingleKvStore> kvStore2;
status = manager.GetSingleKvStore(create, appId, storeIdTest, kvStore2);
ASSERT_EQ(status, Status::SUCCESS);
ASSERT_NE(kvStore2, nullptr);
Status stat = manager.CloseKvStore(appId, storeId64);
EXPECT_EQ(stat, Status::SUCCESS);
stat = manager.DeleteAllKvStore(appId, create.baseDir);
EXPECT_EQ(stat, Status::SUCCESS);
}
/**
* @tc.name: DeleteAllKvStore003
* @tc.desc: Delete all KvStores even if no KvStore exists in the appId.
* @tc.type: FUNC
* @tc.require: SR000CQDU0 AR000BVTDM
* @tc.author: liqiao
*/
HWTEST_F(DistributedKvDataManagerTest, DeleteAllKvStore003, TestSize.Level1)
{
ZLOGI("DeleteAllKvStore003 begin.");
Status stat = manager.DeleteAllKvStore(appId, create.baseDir);
EXPECT_EQ(stat, Status::SUCCESS);
}
/**
* @tc.name: DeleteAllKvStore004
* @tc.desc: when delete the last active kvstore, the system will remove the app manager scene
* @tc.type: FUNC
* @tc.require: bugs
* @tc.author: Sven Wang
*/
HWTEST_F(DistributedKvDataManagerTest, DeleteAllKvStore004, TestSize.Level1)
{
ZLOGI("DeleteAllKvStore004 begin.");
std::shared_ptr<SingleKvStore> kvStore1;
Status status = manager.GetSingleKvStore(create, appId, storeId64, kvStore1);
ASSERT_EQ(status, Status::SUCCESS);
ASSERT_NE(kvStore1, nullptr);
std::shared_ptr<SingleKvStore> kvStore2;
status = manager.GetSingleKvStore(create, appId, storeIdTest, kvStore2);
ASSERT_EQ(status, Status::SUCCESS);
ASSERT_NE(kvStore2, nullptr);
Status stat = manager.CloseKvStore(appId, storeId64);
EXPECT_EQ(stat, Status::SUCCESS);
stat = manager.CloseKvStore(appId, storeIdTest);
EXPECT_EQ(stat, Status::SUCCESS);
stat = manager.DeleteKvStore(appId, storeIdTest, create.baseDir);
EXPECT_EQ(stat, Status::SUCCESS);
stat = manager.DeleteAllKvStore(appId, create.baseDir);
EXPECT_EQ(stat, Status::SUCCESS);
}
/**
* @tc.name: RegisterKvStoreServiceDeathRecipient001
* @tc.desc: Register a callback called when the service dies.
* @tc.type: FUNC
* @tc.require: SR000CQDU0 AR000CQDU1
* @tc.author: liqiao
*/
HWTEST_F(DistributedKvDataManagerTest, RegisterKvStoreServiceDeathRecipient001, TestSize.Level1)
{
ZLOGI("RegisterKvStoreServiceDeathRecipient001 begin.");
std::shared_ptr<KvStoreDeathRecipient> kvStoreDeathRecipient = std::make_shared<MyDeathRecipient>();
manager.RegisterKvStoreServiceDeathRecipient(kvStoreDeathRecipient);
kvStoreDeathRecipient->OnRemoteDied();
}
/**
* @tc.name: UnRegisterKvStoreServiceDeathRecipient001
* @tc.desc: Unregister the callback called when the service dies.
* @tc.type: FUNC
* @tc.require: AR000CQDUS AR000CQDU1
* @tc.author: liqiao
*/
HWTEST_F(DistributedKvDataManagerTest, UnRegisterKvStoreServiceDeathRecipient001, TestSize.Level1)
{
ZLOGI("UnRegisterKvStoreServiceDeathRecipient001 begin.");
std::shared_ptr<KvStoreDeathRecipient> kvStoreDeathRecipientPtr = std::make_shared<MyDeathRecipient>();
manager.UnRegisterKvStoreServiceDeathRecipient(kvStoreDeathRecipientPtr);
}

View File

@ -0,0 +1,607 @@
/*
* 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 "SingleKvStoreClientQueryTest"
#include <unistd.h>
#include <cstddef>
#include <cstdint>
#include <vector>
#include "distributed_kv_data_manager.h"
#include "types.h"
#include "log_print.h"
#include "gtest/gtest.h"
using namespace testing::ext;
using namespace OHOS::DistributedKv;
class SingleKvStoreClientQueryTest : public testing::Test {
public:
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
static std::shared_ptr<SingleKvStore> singleKvStorePtr;
static Status statusGetKvStore;
};
const std::string VALID_SCHEMA_STRICT_DEFINE = "{\"SCHEMA_VERSION\":\"1.0\","
"\"SCHEMA_MODE\":\"STRICT\","
"\"SCHEMA_SKIPSIZE\":0,"
"\"SCHEMA_DEFINE\":{"
"\"name\":\"INTEGER, NOT NULL\""
"},"
"\"SCHEMA_INDEXES\":[\"$.name\"]}";
std::shared_ptr<SingleKvStore> SingleKvStoreClientQueryTest::singleKvStorePtr = nullptr;
Status SingleKvStoreClientQueryTest::statusGetKvStore = Status::ERROR;
void SingleKvStoreClientQueryTest::SetUpTestCase(void)
{}
void SingleKvStoreClientQueryTest::TearDownTestCase(void)
{}
void SingleKvStoreClientQueryTest::SetUp(void)
{}
void SingleKvStoreClientQueryTest::TearDown(void)
{}
/**
* @tc.name: TestQueryC001
* @tc.desc: Query reset.
* @tc.type: FUNC
* @tc.require: AR000DPSF5
* @tc.author: YangLeda
*/
HWTEST_F(SingleKvStoreClientQueryTest, TestQueryC001, TestSize.Level1)
{
ZLOGD("TestQueryC001 start");
DataQuery query;
EXPECT_TRUE(query.ToString().length() == 0);
std::string str = "test value";
query.EqualTo("$.test_field_name", str);
EXPECT_TRUE(query.ToString().length() > 0);
query.Reset();
EXPECT_TRUE(query.ToString().length() == 0);
ZLOGD("TestQueryC001 end");
}
/**
* @tc.name: TestQueryC002
* @tc.desc: Query equalTo.
* @tc.type: FUNC
* @tc.require: AR000DPSF5
* @tc.author: YangLeda
*/
HWTEST_F(SingleKvStoreClientQueryTest, TestQueryC002, TestSize.Level1)
{
ZLOGD("TestQueryC002 start");
DataQuery query;
query.EqualTo("$.test_field_name", 100);
EXPECT_TRUE(query.ToString().length() > 0);
query.Reset();
query.EqualTo("$.test_field_name", (int64_t) 100);
EXPECT_TRUE(query.ToString().length() > 0);
query.Reset();
query.EqualTo("$.test_field_name", 1.23);
EXPECT_TRUE(query.ToString().length() > 0);
query.Reset();
query.EqualTo("$.test_field_name", false);
EXPECT_TRUE(query.ToString().length() > 0);
query.Reset();
std::string str = "";
query.EqualTo("$.test_field_name", str);
EXPECT_TRUE(query.ToString().length() > 0);
ZLOGD("TestQueryC002 end");
}
/**
* @tc.name: TestQueryC003
* @tc.desc: Query notEqualTo.
* @tc.type: FUNC
* @tc.require: AR000DPSF5
* @tc.author: YangLeda
*/
HWTEST_F(SingleKvStoreClientQueryTest, TestQueryC003, TestSize.Level1)
{
ZLOGD("TestQueryC003 start");
DataQuery query;
query.NotEqualTo("$.test_field_name", 100);
EXPECT_TRUE(query.ToString().length() > 0);
query.Reset();
query.NotEqualTo("$.test_field_name", (int64_t) 100);
EXPECT_TRUE(query.ToString().length() > 0);
query.Reset();
query.NotEqualTo("$.test_field_name", 1.23);
EXPECT_TRUE(query.ToString().length() > 0);
query.Reset();
query.NotEqualTo("$.test_field_name", false);
EXPECT_TRUE(query.ToString().length() > 0);
query.Reset();
std::string str = "test value";
query.NotEqualTo("$.test_field_name", str);
EXPECT_TRUE(query.ToString().length() > 0);
ZLOGD("TestQueryC003 end");
}
/**
* @tc.name: TestQueryC004
* @tc.desc: Query greaterThan.
* @tc.type: FUNC
* @tc.require: AR000DPSF5
* @tc.author: YangLeda
*/
HWTEST_F(SingleKvStoreClientQueryTest, TestQueryC004, TestSize.Level1)
{
ZLOGD("TestQueryC004 start");
DataQuery query;
query.GreaterThan("$.test_field_name", 100);
EXPECT_TRUE(query.ToString().length() > 0);
query.Reset();
query.GreaterThan("$.test_field_name", (int64_t) 100);
EXPECT_TRUE(query.ToString().length() > 0);
query.Reset();
query.GreaterThan("$.test_field_name", 1.23);
EXPECT_TRUE(query.ToString().length() > 0);
query.Reset();
std::string str = "test value";
query.GreaterThan("$.test_field_name", str);
EXPECT_TRUE(query.ToString().length() > 0);
ZLOGD("TestQueryC004 end");
}
/**
* @tc.name: TestQueryC005
* @tc.desc: Query lessThan.
* @tc.type: FUNC
* @tc.require: AR000DPSF5
* @tc.author: YangLeda
*/
HWTEST_F(SingleKvStoreClientQueryTest, TestQueryC005, TestSize.Level1)
{
ZLOGD("TestQueryC005 start");
DataQuery query;
query.LessThan("$.test_field_name", 100);
EXPECT_TRUE(query.ToString().length() > 0);
query.Reset();
query.LessThan("$.test_field_name", (int64_t) 100);
EXPECT_TRUE(query.ToString().length() > 0);
query.Reset();
query.LessThan("$.test_field_name", 1.23);
EXPECT_TRUE(query.ToString().length() > 0);
query.Reset();
std::string str = "test value";
query.LessThan("$.test_field_name", str);
EXPECT_TRUE(query.ToString().length() > 0);
ZLOGD("TestQueryC005 end");
}
/**
* @tc.name: TestQueryC006
* @tc.desc: Query greaterThanOrEqualTo.
* @tc.type: FUNC
* @tc.require: AR000DPSF5
* @tc.author: YangLeda
*/
HWTEST_F(SingleKvStoreClientQueryTest, TestQueryC006, TestSize.Level1)
{
ZLOGD("TestQueryC006 start");
DataQuery query;
query.GreaterThanOrEqualTo("$.test_field_name", 100);
EXPECT_TRUE(query.ToString().length() > 0);
query.Reset();
query.GreaterThanOrEqualTo("$.test_field_name", (int64_t) 100);
EXPECT_TRUE(query.ToString().length() > 0);
query.Reset();
query.GreaterThanOrEqualTo("$.test_field_name", 1.23);
EXPECT_TRUE(query.ToString().length() > 0);
query.Reset();
std::string str = "test value";
query.GreaterThanOrEqualTo("$.test_field_name", str);
EXPECT_TRUE(query.ToString().length() > 0);
ZLOGD("TestQueryC006 end");
}
/**
* @tc.name: TestQueryC007
* @tc.desc: Query lessThanOrEqualTo.
* @tc.type: FUNC
* @tc.require: AR000DPSF5
* @tc.author: YangLeda
*/
HWTEST_F(SingleKvStoreClientQueryTest, TestQueryC007, TestSize.Level1)
{
ZLOGD("TestQueryC007 start");
DataQuery query;
query.LessThanOrEqualTo("$.test_field_name", 100);
EXPECT_TRUE(query.ToString().length() > 0);
query.Reset();
query.LessThanOrEqualTo("$.test_field_name", (int64_t) 100);
EXPECT_TRUE(query.ToString().length() > 0);
query.Reset();
query.LessThanOrEqualTo("$.test_field_name", 1.23);
EXPECT_TRUE(query.ToString().length() > 0);
query.Reset();
std::string str = "test value";
query.LessThanOrEqualTo("$.test_field_name", str);
EXPECT_TRUE(query.ToString().length() > 0);
ZLOGD("TestQueryC007 end");
}
/**
* @tc.name: TestQueryC008
* @tc.desc: Query isNull.
* @tc.type: FUNC
* @tc.require: AR000DPSF5
* @tc.author: YangLeda
*/
HWTEST_F(SingleKvStoreClientQueryTest, TestQueryC008, TestSize.Level1)
{
ZLOGD("TestQueryC008 start");
DataQuery query;
query.IsNull("$.test_field_name");
EXPECT_TRUE(query.ToString().length() > 0);
ZLOGD("TestQueryC008 end");
}
/**
* @tc.name: TestQueryC009
* @tc.desc: Query in.
* @tc.type: FUNC
* @tc.require: AR000DPSF5
* @tc.author: YangLeda
*/
HWTEST_F(SingleKvStoreClientQueryTest, TestQueryC009, TestSize.Level1)
{
ZLOGD("TestQueryC009 start");
DataQuery query;
std::vector<int> vectInt{ 10, 20, 30 };
query.In("$.test_field_name", vectInt);
EXPECT_TRUE(query.ToString().length() > 0);
query.Reset();
std::vector<int64_t> vectLong{ (int64_t) 100, (int64_t) 200, (int64_t) 300 };
query.In("$.test_field_name", vectLong);
EXPECT_TRUE(query.ToString().length() > 0);
query.Reset();
std::vector<double> vectDouble{1.23, 2.23, 3.23};
query.In("$.test_field_name", vectDouble);
EXPECT_TRUE(query.ToString().length() > 0);
query.Reset();
std::vector<std::string> vectString{ "value 1", "value 2", "value 3" };
query.In("$.test_field_name", vectString);
EXPECT_TRUE(query.ToString().length() > 0);
ZLOGD("TestQueryC009 end");
}
/**
* @tc.name: TestQueryC010
* @tc.desc: Query in.
* @tc.type: FUNC
* @tc.require: AR000DPSF5
* @tc.author: YangLeda
*/
HWTEST_F(SingleKvStoreClientQueryTest, TestQueryC010, TestSize.Level1)
{
ZLOGD("TestQueryC010 start");
DataQuery query;
std::vector<int> vectInt{ 10, 20, 30 };
query.NotIn("$.test_field_name", vectInt);
EXPECT_TRUE(query.ToString().length() > 0);
query.Reset();
std::vector<int64_t> vectLong{ (int64_t) 100, (int64_t) 200, (int64_t) 300 };
query.NotIn("$.test_field_name", vectLong);
EXPECT_TRUE(query.ToString().length() > 0);
query.Reset();
std::vector<double> vectDouble{ 1.23, 2.23, 3.23 };
query.NotIn("$.test_field_name", vectDouble);
EXPECT_TRUE(query.ToString().length() > 0);
query.Reset();
std::vector<std::string> vectString{ "value 1", "value 2", "value 3" };
query.NotIn("$.test_field_name", vectString);
EXPECT_TRUE(query.ToString().length() > 0);
ZLOGD("TestQueryC010 end");
}
/**
* @tc.name: TestQueryC011
* @tc.desc: Query like.
* @tc.type: FUNC
* @tc.require: AR000DPSF5
* @tc.author: YangLeda
*/
HWTEST_F(SingleKvStoreClientQueryTest, TestQueryC011, TestSize.Level1)
{
ZLOGD("TestQueryC011 start");
DataQuery query;
query.Like("$.test_field_name", "test value");
EXPECT_TRUE(query.ToString().length() > 0);
ZLOGD("TestQueryC011 end");
}
/**
* @tc.name: TestQueryC012
* @tc.desc: Query unlike.
* @tc.type: FUNC
* @tc.require: AR000DPSF5
* @tc.author: YangLeda
*/
HWTEST_F(SingleKvStoreClientQueryTest, TestQueryC012, TestSize.Level1)
{
ZLOGD("TestQueryC012 start");
DataQuery query;
query.Unlike("$.test_field_name", "test value");
EXPECT_TRUE(query.ToString().length() > 0);
ZLOGD("TestQueryC012 end");
}
/**
* @tc.name: TestQueryC013
* @tc.desc: Query and.
* @tc.type: FUNC
* @tc.require: AR000DPSF5
* @tc.author: YangLeda
*/
HWTEST_F(SingleKvStoreClientQueryTest, TestQueryC013, TestSize.Level1)
{
ZLOGD("TestQueryC013 start");
DataQuery query;
query.Like("$.test_field_name1", "test value1");
query.And();
query.Like("$.test_field_name2", "test value2");
EXPECT_TRUE(query.ToString().length() > 0);
ZLOGD("TestQueryC013 end");
}
/**
* @tc.name: TestQueryC014
* @tc.desc: Query or.
* @tc.type: FUNC
* @tc.require: AR000DPSF5
* @tc.author: YangLeda
*/
HWTEST_F(SingleKvStoreClientQueryTest, TestQueryC014, TestSize.Level1)
{
ZLOGD("TestQueryC014 start");
DataQuery query;
query.Like("$.test_field_name1", "test value1");
query.Or();
query.Like("$.test_field_name2", "test value2");
EXPECT_TRUE(query.ToString().length() > 0);
ZLOGD("TestQueryC014 end");
}
/**
* @tc.name: TestQueryC015
* @tc.desc: Query orderBy.
* @tc.type: FUNC
* @tc.require: AR000DPSF5
* @tc.author: YangLeda
*/
HWTEST_F(SingleKvStoreClientQueryTest, TestQueryC015, TestSize.Level1)
{
ZLOGD("TestQueryC015 start");
DataQuery query;
query.OrderByAsc("$.test_field_name1");
query.Reset();
query.OrderByDesc("$.test_field_name1");
EXPECT_TRUE(query.ToString().length() > 0);
ZLOGD("TestQueryC015 end");
}
/**
* @tc.name: TestQueryC016
* @tc.desc: Query orderBy.
* @tc.type: FUNC
* @tc.require: AR000DPSF5
* @tc.author: YangLeda
*/
HWTEST_F(SingleKvStoreClientQueryTest, TestQueryC016, TestSize.Level1)
{
ZLOGD("TestQueryC016 start");
DataQuery query;
query.Limit(10, 100);
EXPECT_TRUE(query.ToString().length() > 0);
ZLOGD("TestQueryC016 end");
}
/**
* @tc.name: TestSingleKvStoreQueryC001
* @tc.desc: query single KvStore.
* @tc.type: FUNC
* @tc.require: SR000DPCO9
* @tc.author: YangLeda
*/
HWTEST_F(SingleKvStoreClientQueryTest, TestSingleKvStoreQueryC001, TestSize.Level1)
{
ZLOGD("TestSingleKvStoreQueryC001 start");
DistributedKvDataManager manager;
Options options = { .createIfMissing = true, .encrypt = true, .autoSync = true,
.kvStoreType = KvStoreType::SINGLE_VERSION, .schema = VALID_SCHEMA_STRICT_DEFINE };
AppId appId = { "SingleKvStoreClientQueryTestAppId1" };
StoreId storeId = { "SingleKvStoreClientQueryTestStoreId1" };
statusGetKvStore = manager.GetSingleKvStore(options, appId, storeId, singleKvStorePtr);
EXPECT_NE(singleKvStorePtr, nullptr) << "kvStorePtr is null.";
singleKvStorePtr->Put("test_key_1", "{\"name\":1}");
singleKvStorePtr->Put("test_key_2", "{\"name\":2}");
singleKvStorePtr->Put("test_key_3", "{\"name\":3}");
DataQuery query;
query.NotEqualTo("$.name", 3);
std::vector<Entry> results;
Status status1 = singleKvStorePtr->GetEntries(query, results);
ASSERT_EQ(status1, Status::SUCCESS);
EXPECT_TRUE(results.size() == 2);
results.clear();
Status status2 = singleKvStorePtr->GetEntries(query, results);
ASSERT_EQ(status2, Status::SUCCESS);
EXPECT_TRUE(results.size() == 2);
std::shared_ptr<KvStoreResultSet> resultSet;
Status status3 = singleKvStorePtr->GetResultSet(query, resultSet);
ASSERT_EQ(status3, Status::SUCCESS);
EXPECT_TRUE(resultSet->GetCount() == 2);
auto closeResultSetStatus = singleKvStorePtr->CloseResultSet(resultSet);
ASSERT_EQ(closeResultSetStatus, Status::SUCCESS);
Status status4 = singleKvStorePtr->GetResultSet(query, resultSet);
ASSERT_EQ(status4, Status::SUCCESS);
EXPECT_TRUE(resultSet->GetCount() == 2);
closeResultSetStatus = singleKvStorePtr->CloseResultSet(resultSet);
ASSERT_EQ(closeResultSetStatus, Status::SUCCESS);
int resultSize1;
Status status5 = singleKvStorePtr->GetCount(query, resultSize1);
ASSERT_EQ(status5, Status::SUCCESS);
EXPECT_TRUE(resultSize1 == 2);
int resultSize2;
Status status6 = singleKvStorePtr->GetCount(query, resultSize2);
ASSERT_EQ(status6, Status::SUCCESS);
EXPECT_TRUE(resultSize2 == 2);
singleKvStorePtr->Delete("test_key_1");
singleKvStorePtr->Delete("test_key_2");
singleKvStorePtr->Delete("test_key_3");
Status status = manager.CloseAllKvStore(appId);
EXPECT_EQ(status, Status::SUCCESS);
status = manager.DeleteAllKvStore(appId);
EXPECT_EQ(status, Status::SUCCESS);
ZLOGD("TestSingleKvStoreQueryC001 end");
}
/**
* @tc.name: TestSingleKvStoreQueryC002
* @tc.desc: query single KvStore.
* @tc.type: FUNC
* @tc.require: SR000DPCO9
* @tc.author: YangLeda
*/
HWTEST_F(SingleKvStoreClientQueryTest, TestSingleKvStoreQueryC002, TestSize.Level1)
{
ZLOGD("TestSingleKvStoreQueryC002 start");
DistributedKvDataManager manager;
Options options = { .createIfMissing = true, .encrypt = true, .autoSync = true,
.kvStoreType = KvStoreType::SINGLE_VERSION };
options.schema = VALID_SCHEMA_STRICT_DEFINE;
AppId appId = { "SingleKvStoreClientQueryTestAppId2" };
StoreId storeId = { "SingleKvStoreClientQueryTestStoreId2" };
statusGetKvStore = manager.GetSingleKvStore(options, appId, storeId, singleKvStorePtr);
EXPECT_NE(singleKvStorePtr, nullptr) << "kvStorePtr is null.";
singleKvStorePtr->Put("test_key_1", "{\"name\":1}");
singleKvStorePtr->Put("test_key_2", "{\"name\":2}");
singleKvStorePtr->Put("test_key_3", "{\"name\":3}");
DataQuery query;
query.NotEqualTo("$.name", 3);
query.And();
query.EqualTo("$.name", 1);
std::vector<Entry> results1;
Status status1 = singleKvStorePtr->GetEntries(query, results1);
ASSERT_EQ(status1, Status::SUCCESS);
EXPECT_TRUE(results1.size() == 1);
std::vector<Entry> results2;
Status status2 = singleKvStorePtr->GetEntries(query, results2);
ASSERT_EQ(status2, Status::SUCCESS);
EXPECT_TRUE(results2.size() == 1);
std::shared_ptr<KvStoreResultSet> resultSet;
Status status3 = singleKvStorePtr->GetResultSet(query, resultSet);
ASSERT_EQ(status3, Status::SUCCESS);
EXPECT_TRUE(resultSet->GetCount() == 1);
auto closeResultSetStatus = singleKvStorePtr->CloseResultSet(resultSet);
ASSERT_EQ(closeResultSetStatus, Status::SUCCESS);
Status status4 = singleKvStorePtr->GetResultSet(query, resultSet);
ASSERT_EQ(status4, Status::SUCCESS);
EXPECT_TRUE(resultSet->GetCount() == 1);
closeResultSetStatus = singleKvStorePtr->CloseResultSet(resultSet);
ASSERT_EQ(closeResultSetStatus, Status::SUCCESS);
int resultSize1;
Status status5 = singleKvStorePtr->GetCount(query, resultSize1);
ZLOGD("this is it %ul", status5);
ASSERT_EQ(status5, Status::SUCCESS);
EXPECT_TRUE(resultSize1 == 1);
int resultSize2;
Status status6 = singleKvStorePtr->GetCount(query, resultSize2);
ASSERT_EQ(status6, Status::SUCCESS);
EXPECT_TRUE(resultSize2 == 1);
singleKvStorePtr->Delete("test_key_1");
singleKvStorePtr->Delete("test_key_2");
singleKvStorePtr->Delete("test_key_3");
Status status = manager.CloseAllKvStore(appId);
EXPECT_EQ(status, Status::SUCCESS);
status = manager.DeleteAllKvStore(appId);
EXPECT_EQ(status, Status::SUCCESS);
ZLOGD("TestSingleKvStoreQueryC002 end");
}
/**
* @tc.name: TestQueryC017
* @tc.desc: Query group prefix isNotNull.
* @tc.type: FUNC
* @tc.require: AR000EPAMV
* @tc.author: YangLeda
*/
HWTEST_F(SingleKvStoreClientQueryTest, TestQueryC017, TestSize.Level1)
{
ZLOGD("TestQueryC017 start");
DataQuery query;
query.KeyPrefix("prefix");
query.BeginGroup();
query.IsNotNull("$.name");
query.EndGroup();
EXPECT_TRUE(query.ToString().length() > 0);
ZLOGD("TestQueryC017 end");
}
/**
* @tc.name: TestQueryC018
* @tc.desc: Query SetSuggestIndex.
* @tc.type: FUNC
* @tc.require: AR000F3PBJ
* @tc.author: liuwenhui
*/
HWTEST_F(SingleKvStoreClientQueryTest, TestQueryC018, TestSize.Level1)
{
ZLOGD("TestQueryC018 start");
DataQuery query;
query.SetSuggestIndex("test_field_name");
EXPECT_TRUE(query.ToString().length() > 0);
ZLOGD("TestQueryC018 end");
}
/**
* @tc.name: TestQueryC019
* @tc.desc: Query InKeys.
* @tc.type: FUNC
* @tc.require: AR000GOHO7
* @tc.author: taoyuxin
*/
HWTEST_F(SingleKvStoreClientQueryTest, TestQueryC019, TestSize.Level1)
{
ZLOGD("TestQueryC019 start");
DataQuery query;
query.InKeys({"test_field_name"});
EXPECT_TRUE(query.ToString().length() > 0);
ZLOGD("TestQueryC019 end");
}

View File

@ -0,0 +1,148 @@
/*
* 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 <gtest/gtest.h>
#include <cstdint>
#include <vector>
#include "iremote_object.h"
#include "itypes_util.h"
#include "types.h"
using namespace testing::ext;
using namespace OHOS::DistributedKv;
using namespace OHOS;
class TypesUtilTest : public testing::Test {
public:
class TestRemoteObject : public IRemoteObject {
public:
int32_t GetObjectRefCount() override
{
return 0;
}
int SendRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override
{
return 0;
}
bool AddDeathRecipient(const sptr<DeathRecipient> &recipient) override
{
return false;
}
bool RemoveDeathRecipient(const sptr<DeathRecipient> &recipient) override
{
return false;
}
int Dump(int fd, const vector<std::u16string> &args) override
{
return 0;
}
};
static void SetUpTestCase(void) {};
static void TearDownTestCase(void) {};
void SetUp() {};
void TearDown() {};
};
HWTEST_F(TypesUtilTest, DeviceInfo, TestSize.Level0)
{
MessageParcel parcel;
DeviceInfo clientDev;
clientDev.deviceId = "123";
clientDev.deviceName = "rk3568";
clientDev.deviceType = "phone";
ASSERT_TRUE(ITypesUtil::Marshal(parcel, clientDev));
DeviceInfo serverDev;
ASSERT_TRUE(ITypesUtil::Unmarshal(parcel, serverDev));
ASSERT_EQ(clientDev.deviceId, serverDev.deviceId);
ASSERT_EQ(clientDev.deviceName, serverDev.deviceName);
ASSERT_EQ(clientDev.deviceType, serverDev.deviceType);
}
HWTEST_F(TypesUtilTest, Entry, TestSize.Level0)
{
MessageParcel parcel;
Entry entryIn;
entryIn.key = "student_name_mali";
entryIn.value = "age:20";
ASSERT_TRUE(ITypesUtil::Marshal(parcel, entryIn));
Entry entryOut;
ASSERT_TRUE(ITypesUtil::Unmarshal(parcel, entryOut));
EXPECT_EQ(entryOut.key.ToString(), std::string("student_name_mali"));
EXPECT_EQ(entryOut.value.ToString(), std::string("age:20"));
}
HWTEST_F(TypesUtilTest, ChangeNotification, TestSize.Level1)
{
Entry insert, update, del;
insert.key = "insert";
update.key = "update";
del.key = "delete";
insert.value = "insert_value";
update.value = "update_value";
del.value = "delete_value";
std::vector<Entry> inserts, updates, deleteds;
inserts.push_back(insert);
updates.push_back(update);
deleteds.push_back(del);
ChangeNotification changeIn(std::move(inserts), std::move(updates), std::move(deleteds), std::string(), false);
MessageParcel parcel;
ASSERT_TRUE(ITypesUtil::Marshal(parcel, changeIn));
ChangeNotification changeOut({}, {}, {}, "", false);
ASSERT_TRUE(ITypesUtil::Unmarshal(parcel, changeOut));
ASSERT_EQ(changeOut.GetInsertEntries().size(), 1UL);
EXPECT_EQ(changeOut.GetInsertEntries().front().key.ToString(), std::string("insert"));
EXPECT_EQ(changeOut.GetInsertEntries().front().value.ToString(), std::string("insert_value"));
ASSERT_EQ(changeOut.GetUpdateEntries().size(), 1UL);
EXPECT_EQ(changeOut.GetUpdateEntries().front().key.ToString(), std::string("update"));
EXPECT_EQ(changeOut.GetUpdateEntries().front().value.ToString(), std::string("update_value"));
ASSERT_EQ(changeOut.GetDeleteEntries().size(), 1UL);
EXPECT_EQ(changeOut.GetDeleteEntries().front().key.ToString(), std::string("delete"));
EXPECT_EQ(changeOut.GetDeleteEntries().front().value.ToString(), std::string("delete_value"));
EXPECT_EQ(changeOut.IsClear(), false);
}
HWTEST_F(TypesUtilTest, Multiple, TestSize.Level1)
{
uint32_t input1 = 10;
int32_t input2 = -10;
std::string input3 = "i test";
Blob input4 = "input 4";
Entry input5;
input5.key = "my test";
input5.value = "test value";
DeviceInfo input6 = {.deviceId = "mock deviceId", .deviceName = "mock phone", .deviceType = "0"};
sptr<IRemoteObject> input7 = new TestRemoteObject();
MessageParcel parcel;
ASSERT_TRUE(ITypesUtil::Marshal(parcel, input1, input2, input3, input4, input5, input6, input7));
uint32_t output1 = 0;
int32_t output2 = 0;
std::string output3 = "";
Blob output4;
Entry output5;
DeviceInfo output6;
sptr<IRemoteObject> output7;
ASSERT_TRUE(ITypesUtil::Unmarshal(parcel, output1, output2, output3, output4, output5, output6, output7));
ASSERT_EQ(output1, input1);
ASSERT_EQ(output2, input2);
ASSERT_EQ(output3, input3);
ASSERT_EQ(output4, input4);
ASSERT_EQ(output5.key, input5.key);
ASSERT_EQ(output5.value, input5.value);
ASSERT_EQ(output6.deviceId, input6.deviceId);
ASSERT_EQ(output6.deviceName, input6.deviceName);
ASSERT_EQ(output6.deviceType, input6.deviceType);
ASSERT_EQ(output7, input7);
}

View File

@ -0,0 +1,280 @@
# 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")
config("distrdb_config") {
visibility = [ ":*" ]
include_dirs = [
"include",
"interfaces/include",
"interfaces/src",
"interfaces/src/relational",
"common/include",
"common/include/relational",
"communicator/include",
"storage/include",
"storage/src",
"storage/src/multiver",
"storage/src/operation",
"storage/src/sqlite",
"storage/src/sqlite/relational",
"storage/src/upgrader",
"syncer/include",
"syncer/src",
"//third_party/openssl/include/",
]
defines = [
"_LARGEFILE64_SOURCE",
"_FILE_OFFSET_BITS=64",
"SQLITE_HAS_CODEC",
"SQLITE_ENABLE_JSON1",
"USING_HILOG_LOGGER",
"USE_SQLITE_SYMBOLS",
"USING_DB_JSON_EXTRACT_AUTOMATICALLY",
"JSONCPP_USE_BUILDER",
"OMIT_FLATBUFFER",
"RELATIONAL_STORE",
"SQLITE_DISTRIBUTE_RELATIONAL",
"USE_DFX_ABILITY",
]
if (is_debug) {
defines += [ "TRACE_SQLITE_EXECUTE" ]
}
}
config("distrdb_public_config") {
visibility = [ "*:*" ]
include_dirs = [
"interfaces/include",
"interfaces/include/relational",
"include",
]
}
group("build_module") {
deps = [ ":distributeddb" ]
}
ohos_shared_library("distributeddb") {
sources = [
"common/src/auto_launch.cpp",
"common/src/data_compression.cpp",
"common/src/data_value.cpp",
"common/src/db_common.cpp",
"common/src/db_constant.cpp",
"common/src/db_dfx_adapter.cpp",
"common/src/db_dump_helper.cpp",
"common/src/evloop/src/event_impl.cpp",
"common/src/evloop/src/event_loop_epoll.cpp",
"common/src/evloop/src/event_loop_impl.cpp",
"common/src/evloop/src/event_loop_select.cpp",
"common/src/evloop/src/ievent.cpp",
"common/src/evloop/src/ievent_loop.cpp",
"common/src/flatbuffer_schema.cpp",
"common/src/hash.cpp",
"common/src/json_object.cpp",
"common/src/lock_status_observer.cpp",
"common/src/log_print.cpp",
"common/src/notification_chain.cpp",
"common/src/param_check_utils.cpp",
"common/src/parcel.cpp",
"common/src/performance_analysis.cpp",
"common/src/platform_specific.cpp",
"common/src/query.cpp",
"common/src/query_expression.cpp",
"common/src/ref_object.cpp",
"common/src/relational/relational_schema_object.cpp",
"common/src/runtime_context.cpp",
"common/src/runtime_context_impl.cpp",
"common/src/schema_constant.cpp",
"common/src/schema_negotiate.cpp",
"common/src/schema_object.cpp",
"common/src/schema_utils.cpp",
"common/src/semaphore_utils.cpp",
"common/src/task_pool.cpp",
"common/src/task_pool_impl.cpp",
"common/src/task_queue.cpp",
"common/src/time_tick_monitor.cpp",
"common/src/types_export.cpp",
"common/src/user_change_monitor.cpp",
"common/src/value_object.cpp",
"common/src/zlib_compression.cpp",
"communicator/src/combine_status.cpp",
"communicator/src/communicator.cpp",
"communicator/src/communicator_aggregator.cpp",
"communicator/src/communicator_linker.cpp",
"communicator/src/frame_combiner.cpp",
"communicator/src/frame_retainer.cpp",
"communicator/src/header_converter.cpp",
"communicator/src/message_transform.cpp",
"communicator/src/network_adapter.cpp",
"communicator/src/protocol_proto.cpp",
"communicator/src/send_task_scheduler.cpp",
"communicator/src/serial_buffer.cpp",
"interfaces/src/intercepted_data_impl.cpp",
"interfaces/src/kv_store_changed_data_impl.cpp",
"interfaces/src/kv_store_delegate_impl.cpp",
"interfaces/src/kv_store_delegate_manager.cpp",
"interfaces/src/kv_store_errno.cpp",
"interfaces/src/kv_store_nb_conflict_data_impl.cpp",
"interfaces/src/kv_store_nb_delegate_impl.cpp",
"interfaces/src/kv_store_result_set_impl.cpp",
"interfaces/src/kv_store_snapshot_delegate_impl.cpp",
"interfaces/src/relational/relational_store_changed_data_impl.cpp",
"interfaces/src/relational/relational_store_delegate_impl.cpp",
"interfaces/src/relational/relational_store_manager.cpp",
"interfaces/src/relational/relational_store_sqlite_ext.cpp",
"interfaces/src/relational/runtime_config.cpp",
"storage/src/data_transformer.cpp",
"storage/src/db_properties.cpp",
"storage/src/default_factory.cpp",
"storage/src/generic_kvdb.cpp",
"storage/src/generic_kvdb_connection.cpp",
"storage/src/generic_single_ver_kv_entry.cpp",
"storage/src/iconnection.cpp",
"storage/src/ikvdb_factory.cpp",
"storage/src/kvdb_commit_notify_filterable_data.cpp",
"storage/src/kvdb_manager.cpp",
"storage/src/kvdb_observer_handle.cpp",
"storage/src/kvdb_properties.cpp",
"storage/src/kvdb_utils.cpp",
"storage/src/kvdb_windowed_result_set.cpp",
"storage/src/multiver/generic_multi_ver_kv_entry.cpp",
"storage/src/multiver/multi_ver_commit.cpp",
"storage/src/multiver/multi_ver_kvdata_storage.cpp",
"storage/src/multiver/multi_ver_natural_store.cpp",
"storage/src/multiver/multi_ver_natural_store_commit_notify_data.cpp",
"storage/src/multiver/multi_ver_natural_store_commit_storage.cpp",
"storage/src/multiver/multi_ver_natural_store_connection.cpp",
"storage/src/multiver/multi_ver_natural_store_snapshot.cpp",
"storage/src/multiver/multi_ver_natural_store_transfer_data.cpp",
"storage/src/multiver/multi_ver_storage_engine.cpp",
"storage/src/multiver/multi_ver_storage_executor.cpp",
"storage/src/multiver/multi_ver_vacuum.cpp",
"storage/src/multiver/multi_ver_vacuum_executor_impl.cpp",
"storage/src/multiver/multi_ver_value_object.cpp",
"storage/src/operation/database_oper.cpp",
"storage/src/operation/local_database_oper.cpp",
"storage/src/operation/multi_ver_database_oper.cpp",
"storage/src/operation/single_ver_database_oper.cpp",
"storage/src/package_file.cpp",
"storage/src/relational_store_connection.cpp",
"storage/src/relational_store_instance.cpp",
"storage/src/relational_sync_able_storage.cpp",
"storage/src/relationaldb_properties.cpp",
"storage/src/result_entries_window.cpp",
"storage/src/single_ver_natural_store_commit_notify_data.cpp",
"storage/src/sqlite/query_object.cpp",
"storage/src/sqlite/query_sync_object.cpp",
"storage/src/sqlite/relational/sqlite_relational_store.cpp",
"storage/src/sqlite/relational/sqlite_relational_store_connection.cpp",
"storage/src/sqlite/relational/sqlite_single_relational_storage_engine.cpp",
"storage/src/sqlite/sqlite_local_kvdb.cpp",
"storage/src/sqlite/sqlite_local_kvdb_connection.cpp",
"storage/src/sqlite/sqlite_local_kvdb_snapshot.cpp",
"storage/src/sqlite/sqlite_local_storage_engine.cpp",
"storage/src/sqlite/sqlite_local_storage_executor.cpp",
"storage/src/sqlite/sqlite_multi_ver_data_storage.cpp",
"storage/src/sqlite/sqlite_multi_ver_transaction.cpp",
"storage/src/sqlite/sqlite_query_helper.cpp",
"storage/src/sqlite/sqlite_single_ver_continue_token.cpp",
"storage/src/sqlite/sqlite_single_ver_database_upgrader.cpp",
"storage/src/sqlite/sqlite_single_ver_forward_cursor.cpp",
"storage/src/sqlite/sqlite_single_ver_natural_store.cpp",
"storage/src/sqlite/sqlite_single_ver_natural_store_connection.cpp",
"storage/src/sqlite/sqlite_single_ver_relational_continue_token.cpp",
"storage/src/sqlite/sqlite_single_ver_relational_storage_executor.cpp",
"storage/src/sqlite/sqlite_single_ver_result_set.cpp",
"storage/src/sqlite/sqlite_single_ver_schema_database_upgrader.cpp",
"storage/src/sqlite/sqlite_single_ver_storage_engine.cpp",
"storage/src/sqlite/sqlite_single_ver_storage_executor.cpp",
"storage/src/sqlite/sqlite_single_ver_storage_executor_cache.cpp",
"storage/src/sqlite/sqlite_single_ver_storage_executor_subscribe.cpp",
"storage/src/sqlite/sqlite_storage_engine.cpp",
"storage/src/sqlite/sqlite_storage_executor.cpp",
"storage/src/sqlite/sqlite_utils.cpp",
"storage/src/storage_engine.cpp",
"storage/src/storage_engine_manager.cpp",
"storage/src/storage_executor.cpp",
"storage/src/sync_able_engine.cpp",
"storage/src/sync_able_kvdb.cpp",
"storage/src/sync_able_kvdb_connection.cpp",
"storage/src/upgrader/single_ver_database_upgrader.cpp",
"storage/src/upgrader/single_ver_schema_database_upgrader.cpp",
"syncer/src/ability_sync.cpp",
"syncer/src/commit_history_sync.cpp",
"syncer/src/communicator_proxy.cpp",
"syncer/src/db_ability.cpp",
"syncer/src/device_manager.cpp",
"syncer/src/generic_syncer.cpp",
"syncer/src/meta_data.cpp",
"syncer/src/multi_ver_data_sync.cpp",
"syncer/src/multi_ver_sync_engine.cpp",
"syncer/src/multi_ver_sync_state_machine.cpp",
"syncer/src/multi_ver_sync_task_context.cpp",
"syncer/src/multi_ver_syncer.cpp",
"syncer/src/query_sync_water_mark_helper.cpp",
"syncer/src/single_ver_data_message_schedule.cpp",
"syncer/src/single_ver_data_packet.cpp",
"syncer/src/single_ver_data_sync.cpp",
"syncer/src/single_ver_data_sync_utils.cpp",
"syncer/src/single_ver_kv_sync_task_context.cpp",
"syncer/src/single_ver_kv_syncer.cpp",
"syncer/src/single_ver_relational_sync_task_context.cpp",
"syncer/src/single_ver_relational_syncer.cpp",
"syncer/src/single_ver_serialize_manager.cpp",
"syncer/src/single_ver_sync_engine.cpp",
"syncer/src/single_ver_sync_state_machine.cpp",
"syncer/src/single_ver_sync_target.cpp",
"syncer/src/single_ver_sync_task_context.cpp",
"syncer/src/single_ver_syncer.cpp",
"syncer/src/subscribe_manager.cpp",
"syncer/src/sync_config.cpp",
"syncer/src/sync_engine.cpp",
"syncer/src/sync_operation.cpp",
"syncer/src/sync_state_machine.cpp",
"syncer/src/sync_target.cpp",
"syncer/src/sync_task_context.cpp",
"syncer/src/syncer_factory.cpp",
"syncer/src/syncer_proxy.cpp",
"syncer/src/time_helper.cpp",
"syncer/src/time_sync.cpp",
"syncer/src/value_slice_sync.cpp",
]
configs = [ ":distrdb_config" ]
public_configs = [ ":distrdb_public_config" ]
deps = [
"//third_party/sqlite:sqlite",
"//third_party/zlib:libz",
]
configs += [ "//third_party/jsoncpp:jsoncpp_config" ]
ldflags = [ "-Wl,--exclude-libs,ALL" ]
deps += [
"//third_party/jsoncpp:jsoncpp",
"//third_party/openssl:libcrypto_shared",
]
external_deps = [
"c_utils:utils",
"hisysevent_native:libhisysevent",
"hitrace_native:hitrace_meter",
"hiviewdfx_hilog_native:libhilog",
]
subsystem_name = "distributeddatamgr"
part_name = "kv_store"
}

View File

@ -0,0 +1,130 @@
{
"name": "@ohos/distributeddatamgr_datamgr",
"version": "1.0.0",
"description": "Distributed data manager that provides the capability to store data in the databases of different devices",
"homePage": "https://gitee.com/openharmony",
"license": "Apache V2",
"repository": "https://gitee.com/openharmony/distributeddatamgr_datamgr",
"domain": "os",
"language": "",
"publishAs": "code-segment",
"private": false,
"scripts": {},
"tags": [
"foundation"
],
"keywords": [
"distributeddatamgr",
"datamgr"
],
"envs": [],
"dirs": [],
"author": {
"name": "",
"email": "",
"url": ""
},
"contributors": [
{
"name": "",
"email": "",
"url": ""
}
],
"segment": {
"destPath": "foundation/distributeddatamgr/kv_store"
},
"component": {
"name": "kv_store",
"subsystem": "distributeddatamgr",
"syscap": [
"SystemCapability.DistributedDataManager.KVStore.Core",
"SystemCapability.DistributedDataManager.KVStore.Lite",
"SystemCapability.DistributedDataManager.KVStore.DistributedKVStore"
],
"features": [],
"adapted_system_type": [
"standard"
],
"rom": "",
"ram": "",
"hisysevent_config": [
"//foundation/distributeddatamgr/kv_store/hisysevent.yaml"
],
"deps": {
"components": [
"libuv",
"common_event_service",
"bundle_framework",
"safwk",
"zlib",
"init",
"os_account",
"common",
"samgr_standard",
"dataclassification",
"dsoftbus",
"jsoncpp",
"hitrace_native",
"access_token",
"huks",
"ability_base",
"ability_runtime",
"hiviewdfx_hilog_native",
"hisysevent_native",
"device_auth",
"ipc",
"napi"
],
"third_party": [
"uv_static",
"sqlite",
"libz",
"jsoncpp",
"libcrypto_shared"
]
},
"build": {
"sub_component": [
"//foundation/distributeddatamgr/kv_store/interfaces/innerkits/distributeddata:build_module",
"//foundation/distributeddatamgr/kv_store/interfaces/jskits/distributeddata:build_module",
"//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/app:build_module",
"//foundation/distributeddatamgr/kv_store/frameworks/innerkitsimpl/kvdb/distributeddb:build_module",
"//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/framework:build_module",
"//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/service:build_module",
"//foundation/distributeddatamgr/kv_store/conf:build_module"
],
"inner_kits": [
{
"name": "//foundation/distributeddatamgr/kv_store/interfaces/innerkits/distributeddata:distributeddata_inner",
"header": {
"header_files": [
"blob.h",
"change_notification.h",
"distributed_kv_data_manager.h",
"kvstore.h",
"kvstore_death_recipient.h",
"kvstore_observer.h",
"kvstore_result_set.h",
"kvstore_sync_callback.h",
"single_kvstore.h",
"types.h",
"visibility.h",
"data_query.h",
"device_status_change_listener.h",
"store_errno.h"
],
"header_base": "//foundation/distributeddatamgr/kv_store/interfaces/innerkits/distributeddata/include"
}
}
],
"test": [
"//foundation/distributeddatamgr/kv_store:build_native_test",
"//foundation/distributeddatamgr/kv_store/frameworks/innerkitsimpl/kvdb/distributeddb/test:distributeddatamgr_fuzztest",
"//foundation/distributeddatamgr/kv_store:fuzztest",
"//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/test:fuzztest",
"//foundation/distributeddatamgr/kv_store:distributedtest"
]
}
}
}

View File

@ -0,0 +1,185 @@
/*
* 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 AUTO_LAUNCH_H
#define AUTO_LAUNCH_H
#include <set>
#include <map>
#include <mutex>
#include "auto_launch_export.h"
#include "db_properties.h"
#include "ikvdb_connection.h"
#include "icommunicator_aggregator.h"
#include "kv_store_observer.h"
#include "kvdb_properties.h"
#include "types_export.h"
#include "relational_store_connection.h"
#include "relationaldb_properties.h"
#include "store_observer.h"
namespace DistributedDB {
enum class AutoLaunchItemState {
UN_INITIAL = 0,
IN_ENABLE,
IN_LIFE_CYCLE_CALL_BACK, // in LifeCycleCallback
IN_COMMUNICATOR_CALL_BACK, // in OnConnectCallback or CommunicatorLackCallback
IDLE,
};
enum class DBType {
DB_KV = 0,
DB_RELATION,
DB_INVALID,
};
struct AutoLaunchItem {
std::shared_ptr<DBProperties> propertiesPtr;
AutoLaunchNotifier notifier;
KvStoreObserver *observer = nullptr;
int conflictType = 0;
KvStoreNbConflictNotifier conflictNotifier;
void *conn = nullptr;
KvDBObserverHandle *observerHandle = nullptr;
bool isWriteOpenNotified = false;
AutoLaunchItemState state = AutoLaunchItemState::UN_INITIAL;
bool isDisable = false;
bool inObserver = false;
bool isAutoSync = true;
DBType type = DBType::DB_INVALID;
StoreObserver *storeObserver = nullptr;
};
class AutoLaunch {
public:
static int GetAutoLaunchProperties(const AutoLaunchParam &param, const DBType &openType, bool checkDir,
std::shared_ptr<DBProperties> &propertiesPtr);
AutoLaunch() = default;
virtual ~AutoLaunch();
DISABLE_COPY_ASSIGN_MOVE(AutoLaunch);
void SetCommunicatorAggregator(ICommunicatorAggregator *aggregator);
int EnableKvStoreAutoLaunch(const KvDBProperties &properties, AutoLaunchNotifier notifier,
const AutoLaunchOption &option);
int DisableKvStoreAutoLaunch(const std::string &normalIdentifier, const std::string &dualTupleIdentifier,
const std::string &userId);
void GetAutoLaunchSyncDevices(const std::string &identifier, std::vector<std::string> &devices) const;
void SetAutoLaunchRequestCallback(const AutoLaunchRequestCallback &callback, DBType type);
void Dump(int fd);
protected:
static int OpenOneConnection(AutoLaunchItem &autoLaunchItem);
// we will return errCode, if errCode != E_OK
static int CloseConnectionStrict(AutoLaunchItem &autoLaunchItem);
static void CloseNotifier(const AutoLaunchItem &autoLaunchItem);
static int SetConflictNotifier(AutoLaunchItem &autoLaunchItem);
static int GetAutoLaunchKVProperties(const AutoLaunchParam &param,
const std::shared_ptr<KvDBProperties> &propertiesPtr, bool checkDir);
static int GetAutoLaunchRelationProperties(const AutoLaunchParam &param,
const std::shared_ptr<RelationalDBProperties> &propertiesPtr);
static int OpenKvConnection(AutoLaunchItem &autoLaunchItem);
static int OpenRelationalConnection(AutoLaunchItem &autoLaunchItem);
static int PragmaAutoSync(AutoLaunchItem &autoLaunchItem);
int EnableKvStoreAutoLaunchParmCheck(AutoLaunchItem &autoLaunchItem, const std::string &normalIdentifier,
const std::string &dualTupleIdentifier, bool isDualTupleMode);
int GetKVConnectionInEnable(AutoLaunchItem &autoLaunchItem, const std::string &identifier);
// before ReleaseDatabaseConnection, if errCode != E_OK, we not return, we try close more
virtual void TryCloseConnection(AutoLaunchItem &autoLaunchItem);
int RegisterObserverAndLifeCycleCallback(AutoLaunchItem &autoLaunchItem, const std::string &identifier,
bool isExt);
int RegisterObserver(AutoLaunchItem &autoLaunchItem, const std::string &identifier, bool isExt);
void ObserverFunc(const KvDBCommitNotifyData &notifyData, const std::string &identifier,
const std::string &userId);
void ConnectionLifeCycleCallbackTask(const std::string &identifier, const std::string &userId);
void OnlineCallBackTask();
void GetDoOpenMap(std::map<std::string, std::map<std::string, AutoLaunchItem>> &doOpenMap);
void GetConnInDoOpenMap(std::map<std::string, std::map<std::string, AutoLaunchItem>> &doOpenMap);
void UpdateGlobalMap(std::map<std::string, std::map<std::string, AutoLaunchItem>> &doOpenMap);
void ReceiveUnknownIdentifierCallBackTask(const std::string &identifier, const std::string &userId);
void ConnectionLifeCycleCallback(const std::string &identifier, const std::string &userId);
void OnlineCallBack(const std::string &device, bool isConnect);
int ReceiveUnknownIdentifierCallBack(const LabelType &label, const std::string &originalUserId);
int AutoLaunchExt(const std::string &identifier, const std::string &userId);
void AutoLaunchExtTask(const std::string &identifier, const std::string &userId, AutoLaunchItem &autoLaunchItem);
void ExtObserverFunc(const KvDBCommitNotifyData &notifyData, const std::string &identifier,
const std::string &userId);
void ExtConnectionLifeCycleCallback(const std::string &identifier, const std::string &userId);
void ExtConnectionLifeCycleCallbackTask(const std::string &identifier, const std::string &userId);
int ExtAutoLaunchRequestCallBack(const std::string &identifier, AutoLaunchParam &param, DBType &openType);
int RegisterLifeCycleCallback(AutoLaunchItem &autoLaunchItem, const std::string &identifier, bool isExt);
void TryCloseKvConnection(AutoLaunchItem &autoLaunchItem);
void TryCloseRelationConnection(AutoLaunchItem &autoLaunchItem);
void EraseAutoLauchItem(const std::string &identifier, const std::string &userId);
void NotifyInvalidParam(const AutoLaunchItem &autoLaunchItem);
int CheckAutoLaunchRealPath(const AutoLaunchItem &autoLaunchItem);
mutable std::mutex dataLock_;
mutable std::mutex communicatorLock_;
std::set<std::string> onlineDevices_;
// key: label, value: <userId, AutoLaunchItem>
std::map<std::string, std::map<std::string, AutoLaunchItem>> autoLaunchItemMap_;
ICommunicatorAggregator *communicatorAggregator_ = nullptr;
std::condition_variable cv_;
std::mutex extLock_;
std::map<DBType, AutoLaunchRequestCallback> autoLaunchRequestCallbackMap_;
// key: label, value: <userId, AutoLaunchItem>
std::map<std::string, std::map<std::string, AutoLaunchItem>> extItemMap_;
};
} // namespace DistributedDB
#endif // AUTO_LAUNCH_H

View File

@ -0,0 +1,48 @@
/*
* 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 DATA_COMPRESSION_H
#define DATA_COMPRESSION_H
#include <vector>
#include <set>
#include <map>
#include "types_export.h"
namespace DistributedDB {
class DataCompression {
public:
static DataCompression *GetInstance(CompressAlgorithm algo);
static void GetCompressionAlgo(std::set<CompressAlgorithm> &algorithmSet);
static int TransferCompressionAlgo(uint32_t compressAlgoType, CompressAlgorithm &algoType);
virtual int Compress(const std::vector<uint8_t> &srcData, std::vector<uint8_t> &destData) const = 0;
virtual int Uncompress(const std::vector<uint8_t> &srcData, std::vector<uint8_t> &destData, uint32_t destLen)
const = 0;
protected:
DataCompression() = default;
virtual ~DataCompression() = default;
DataCompression(const DataCompression& compression) = delete;
DataCompression& operator= (const DataCompression& compression) = delete;
static void Register(CompressAlgorithm algo, DataCompression *compression);
private:
static std::map<CompressAlgorithm, DataCompression *> &GetCompressionAlgos();
static std::map<uint32_t, CompressAlgorithm> &GetTransMap();
};
} // namespace DistributedDB
#endif // DATA_COMPRESSION_H

View File

@ -0,0 +1,98 @@
/*
* 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_DB_DATA_VALUE_H
#define DISTRIBUTED_DB_DATA_VALUE_H
#include <cstdint>
#include <macro_utils.h>
#include <map>
#include <string>
namespace DistributedDB {
// field types stored in sqlite
enum class StorageType {
STORAGE_TYPE_NONE = 0,
STORAGE_TYPE_NULL,
STORAGE_TYPE_INTEGER,
STORAGE_TYPE_REAL,
STORAGE_TYPE_TEXT,
STORAGE_TYPE_BLOB
};
class Blob {
public:
Blob();
~Blob();
Blob(Blob &&);
Blob(const Blob &) = delete;
Blob &operator=(Blob &&) noexcept;
Blob &operator=(const Blob &) = delete;
const uint8_t* GetData() const;
uint32_t GetSize() const;
int WriteBlob(const uint8_t *ptrArray, const uint32_t &size);
private:
uint8_t* ptr_;
uint32_t size_;
};
class DataValue {
public:
DataValue();
~DataValue();
// copy constructor
DataValue(const DataValue &dataValue);
DataValue &operator=(const DataValue &dataValue);
// move constructor
DataValue(DataValue &&dataValue) noexcept;
DataValue &operator=(DataValue &&dataValue) noexcept;
DataValue &operator=(int64_t intVal);
DataValue &operator=(double doubleVal);
DataValue &operator=(const Blob &blob);
DataValue &operator=(const std::string &string);
int Set(Blob *&blob);
// equals
bool operator==(const DataValue &dataValue) const;
bool operator!=(const DataValue &dataValue) const;
StorageType GetType() const;
int GetInt64(int64_t &outVal) const;
int GetDouble(double &outVal) const;
int GetBlob(Blob *&outVal) const;
int SetBlob(const Blob &val);
int GetBlob(Blob &outVal) const;
int SetText(const std::string &val);
int SetText(const uint8_t *val, uint32_t length);
int GetText(std::string &outVal) const;
void ResetValue();
int GetBlobLength(uint32_t &length) const;
std::string ToString() const;
private:
StorageType type_ = StorageType::STORAGE_TYPE_NULL;
union {
void* zeroMem;
Blob* blobPtr;
double dValue;
int64_t iValue;
} value_{};
};
}
#endif // DISTRIBUTED_DB_DATA_VALUE_H

View File

@ -0,0 +1,71 @@
/*
* 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 DISTRIBUTEDDB_COMMON_H
#define DISTRIBUTEDDB_COMMON_H
#include <list>
#include <string>
#include "db_types.h"
#include "store_types.h"
#include "kvdb_properties.h"
namespace DistributedDB {
class DBCommon final {
public:
static int CreateDirectory(const std::string &directory);
static void StringToVector(const std::string &src, std::vector<uint8_t> &dst);
static void VectorToString(const std::vector<uint8_t> &src, std::string &dst);
static std::string VectorToHexString(const std::vector<uint8_t> &inVec, const std::string &separator = "");
static void PrintHexVector(const std::vector<uint8_t> &data, int line = 0, const std::string &tag = "");
static std::string TransferStringToHex(const std::string &origStr);
static std::string TransferHashString(const std::string &devName);
static int CalcValueHash(const std::vector<uint8_t> &Value, std::vector<uint8_t> &hashValue);
static int CreateStoreDirectory(const std::string &directory, const std::string &identifierName,
const std::string &subDir, bool isCreate);
static int CopyFile(const std::string &srcFile, const std::string &dstFile);
static int RemoveAllFilesOfDirectory(const std::string &dir, bool isNeedRemoveDir = true);
static std::string GenerateIdentifierId(const std::string &storeId,
const std::string &appId, const std::string &userId);
static std::string GenerateDualTupleIdentifierId(const std::string &storeId, const std::string &appId);
static void SetDatabaseIds(KvDBProperties &properties, const std::string &appId, const std::string &userId,
const std::string &storeId);
static std::string StringMasking(const std::string &oriStr, size_t remain = 3); // remain 3 unmask
static std::string GetDistributedTableName(const std::string &device, const std::string &tableName);
static void GetDeviceFromName(const std::string &deviceTableName, std::string &deviceHash, std::string &tableName);
};
// Define short macro substitute for original long expression for convenience of using
#define VEC_TO_STR(x) DBCommon::VectorToHexString(x).c_str()
#define STR_MASK(x) DBCommon::StringMasking(x).c_str()
#define STR_TO_HEX(x) DBCommon::TransferStringToHex(x).c_str()
} // namespace DistributedDB
#endif // DISTRIBUTEDDB_COMMON_H

View File

@ -0,0 +1,140 @@
/*
* 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 DISTRIBUTEDDB_CONSTANT_H
#define DISTRIBUTEDDB_CONSTANT_H
#include <string>
namespace DistributedDB {
class DBConstant {
public:
static constexpr size_t MAX_KEY_SIZE = 1024;
static constexpr size_t MAX_VALUE_SIZE = 4194304;
static constexpr size_t MAX_BATCH_SIZE = 128;
static constexpr size_t MAX_DEV_LENGTH = 128;
static constexpr size_t MAX_TRANSACTION_ENTRY_SIZE = 128;
static constexpr size_t MAX_DATA_DIR_LENGTH = 512;
static constexpr size_t MAX_INKEYS_SIZE = 128;
static constexpr int DB_TYPE_LOCAL = 1;
static constexpr int DB_TYPE_MULTI_VER = 2;
static constexpr int DB_TYPE_SINGLE_VER = 3;
static constexpr int QUEUED_SYNC_LIMIT_DEFAULT = 32;
static constexpr int QUEUED_SYNC_LIMIT_MIN = 1;
static constexpr int QUEUED_SYNC_LIMIT_MAX = 4096;
static constexpr int MAX_DEVICES_SIZE = 100;
static constexpr int MAX_COMMIT_SIZE = 1000000;
static constexpr int MAX_ENTRIES_SIZE = 1000000;
static constexpr uint32_t MAX_COLUMN = 32767;
// In querySync, when getting query data finished,
// if the block size reach the half of max block size, will get deleted data next;
// if the block size not reach the half of max block size, will not get deleted data.
static constexpr float QUERY_SYNC_THRESHOLD = 0.50;
static constexpr uint64_t MAX_USER_ID_LENGTH = 128;
static constexpr uint64_t MAX_APP_ID_LENGTH = 128;
static constexpr uint64_t MAX_STORE_ID_LENGTH = 128;
static const std::string MULTI_SUB_DIR;
static const std::string SINGLE_SUB_DIR;
static const std::string LOCAL_SUB_DIR;
static const std::string MAINDB_DIR;
static const std::string METADB_DIR;
static const std::string CACHEDB_DIR;
static const std::string LOCAL_DATABASE_NAME;
static const std::string MULTI_VER_DATA_STORE;
static const std::string MULTI_VER_COMMIT_STORE;
static const std::string MULTI_VER_VALUE_STORE;
static const std::string MULTI_VER_META_STORE;
static const std::string SINGLE_VER_DATA_STORE;
static const std::string SINGLE_VER_META_STORE;
static const std::string SINGLE_VER_CACHE_STORE;
static const std::string SQLITE_URL_PRE;
static const std::string SQLITE_DB_EXTENSION;
static const std::string SQLITE_MEMDB_IDENTIFY;
static const std::string SCHEMA_KEY;
static const std::string PATH_POSTFIX_UNPACKED;
static const std::string PATH_POSTFIX_IMPORT_BACKUP;
static const std::string PATH_POSTFIX_IMPORT_ORIGIN;
static const std::string PATH_POSTFIX_IMPORT_DUP;
static const std::string PATH_POSTFIX_EXPORT_BACKUP;
static const std::string PATH_POSTFIX_DB_INCOMPLETE; // use for make sure create datebase and set label complete
static const std::string REKEY_FILENAME_POSTFIX_PRE;
static const std::string REKEY_FILENAME_POSTFIX_OK;
static const std::string UPGRADE_POSTFIX;
static const std::string SET_SECOPT_POSTFIX; // used for make sure meta split upgrade atomically
static const std::string PATH_BACKUP_POSTFIX;
static const std::string ID_CONNECTOR;
static const std::string DELETE_KVSTORE_REMOVING;
static const std::string DB_LOCK_POSTFIX;
static const std::string SUBSCRIBE_QUERY_PREFIX;
static const std::string TRIGGER_REFERENCES_NEW;
static const std::string TRIGGER_REFERENCES_OLD;
static const std::string UPDATE_META_FUNC;
static const std::string SYSTEM_TABLE_PREFIX;
static constexpr uint32_t AUTO_SYNC_TIMEOUT = 5000; // 5s
static constexpr uint32_t MANUAL_SYNC_TIMEOUT = 5000; // 5s
static const size_t MAX_NORMAL_PACK_ITEM_SIZE = 4000;
static const size_t MAX_HPMODE_PACK_ITEM_SIZE = 2000; // slide window mode to reduce last ack transfer time
static constexpr uint32_t MIN_MTU_SIZE = 1024; // 1KB
static constexpr uint32_t MAX_MTU_SIZE = 5242880; // 5MB
static constexpr uint32_t MIN_TIMEOUT = 5000; // 5s
static constexpr uint32_t MAX_TIMEOUT = 60000; // 60s
static constexpr uint8_t DEFAULT_COMPTRESS_RATE = 100;
static constexpr size_t MAX_SYNC_BLOCK_SIZE = 31457280; // 30MB
static constexpr int DOUBLE_PRECISION = 15;
static constexpr int MAX_DISTRIBUTED_TABLE_COUNT = 32;
static constexpr uint64_t MAX_LOG_SIZE_HIGH = 0x400000000ULL; // 16GB
static constexpr uint64_t MAX_LOG_SIZE_LOW = 0x400000ULL; // 4MB
static constexpr uint64_t MAX_LOG_SIZE_DEFAULT = 0x40000000ULL; // 1GB
static constexpr int DEF_LIFE_CYCLE_TIME = 60000; // 60S
static constexpr int RELATIONAL_LOG_TABLE_FIELD_NUM = 7; // field num is relational distributed log table
static constexpr uint64_t IGNORE_CONNECTION_ID = 0;
// For relational
static const std::string RELATIONAL_PREFIX;
static const std::string TIMESTAMP_ALIAS;
};
} // namespace DistributedDB
#endif // DISTRIBUTEDDB_CONSTANT_H

View File

@ -0,0 +1,62 @@
/*
* 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 DB_DFX_ADAPTER_H
#define DB_DFX_ADAPTER_H
#include <string>
#include <vector>
namespace DistributedDB {
enum DBEventType {
FAULT = 1,
STATISTIC = 2,
SECURITY = 3,
BEHAVIOR = 4
};
struct ReportTask {
std::string eventName;
std::string appId;
std::string userId;
std::string storeId;
int errCode = 0;
};
class DBDfxAdapter {
public:
static void Dump(int fd, const std::vector<std::u16string> &args);
static void ReportFault(const ReportTask &reportTask);
static void StartTrace(const std::string &action);
static void FinishTrace();
static void StartTraceSQL();
static void FinishTraceSQL();
static void StartAsyncTrace(const std::string &action, int32_t taskId);
static void FinishAsyncTrace(const std::string &action, int32_t taskId);
static const std::string SYNC_ACTION;
static const std::string EVENT_OPEN_DATABASE_FAILED;
private:
static const std::string EVENT_CODE;
static const std::string APP_ID;
static const std::string USER_ID;
static const std::string STORE_ID;
static const std::string SQLITE_EXECUTE;
};
} // namespace DistributedDB
#endif // DB_DFX_ADAPTER_H

View File

@ -0,0 +1,26 @@
/*
* 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 DB_DUMP_HELPER_H
#define DB_DUMP_HELPER_H
namespace DistributedDB {
class DBDumpHelper {
public:
static void Dump(int fd, const char *format, ...);
};
} // namespace DistributedDB
#endif // DB_DFX_ADAPTER_H

View File

@ -0,0 +1,155 @@
/*
* 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 DISTRIBUTEDDB_ERRNO_H
#define DISTRIBUTEDDB_ERRNO_H
#include <errno.h>
namespace DistributedDB {
constexpr int E_OK = 0;
constexpr int E_BASE = 1000; // different from the other errno.
constexpr int E_NOT_SUPPORT = (E_BASE + 1); // not support currently.
constexpr int E_INVALID_DB = (E_BASE + 2); // invalid db or connection.
constexpr int E_NOT_FOUND = (E_BASE + 3); // not found the resource.
constexpr int E_BUSY = (E_BASE + 4); // the db is busy
constexpr int E_UNEXPECTED_DATA = (E_BASE + 5); // Data does not match expectation.
constexpr int E_STALE = (E_BASE + 6); // Resource has been stopped, killed or destroyed.
constexpr int E_INVALID_ARGS = (E_BASE + 7); // the input args is invalid.
constexpr int E_REGISTER_OBSERVER = (E_BASE + 8); // error in register observer related function.
constexpr int E_TRANSACT_STATE = (E_BASE + 9); // transaction state error.
constexpr int E_SECUREC_ERROR = (E_BASE + 10); // security interface returns error
constexpr int E_OUT_OF_MEMORY = (E_BASE + 11); // out of memory
constexpr int E_NOT_PERMIT = (E_BASE + 12); // operation is not permitted
constexpr int E_ALREADY_REGISTER = (E_BASE + 13); // function or handle already registered and not allowed replace
constexpr int E_ALREADY_ALLOC = (E_BASE + 14); // Object had already been allocated
constexpr int E_ALREADY_RELEASE = (E_BASE + 15); // Object had already been released
constexpr int E_CONTAINER_FULL = (E_BASE + 16); // container full
constexpr int E_CONTAINER_EMPTY = (E_BASE + 17); // container empty
constexpr int E_CONTAINER_FULL_TO_NOTFULL = (E_BASE + 18); // container status changed from full to not full
constexpr int E_CONTAINER_NOTEMPTY_TO_EMPTY = (E_BASE + 19); // container status changed from full to not full
constexpr int E_WAIT_RETRY = (E_BASE + 20); // wait and retry later
constexpr int E_PARSE_FAIL = (E_BASE + 21); // parse packet or frame fail
constexpr int E_TIMEOUT = (E_BASE + 22); // time out
constexpr int E_SERIALIZE_ERROR = (E_BASE + 23); // serialize error
constexpr int E_DESERIALIZE_ERROR = (E_BASE + 24); // deserialize error
constexpr int E_NOT_REGISTER = (E_BASE + 25); // handler or function not registered
constexpr int E_LENGTH_ERROR = (E_BASE + 26); // error relative to length
constexpr int E_UNFINISHED = (E_BASE + 27); // get sync data unfinished.
constexpr int E_FINISHED = (E_BASE + 28); // get sync data finished.
constexpr int E_INVALID_MESSAGE_ID = (E_BASE + 29); // invalid messageId error
constexpr int E_MESSAGE_ID_ERROR = (E_BASE + 30); // messageId is not expected
constexpr int E_MESSAGE_TYPE_ERROR = (E_BASE + 31); // messageType is not expected
constexpr int E_PERIPHERAL_INTERFACE_FAIL = (E_BASE + 32); // peripheral interface fail
constexpr int E_NOT_INIT = (E_BASE + 33); // module may not init
constexpr int E_MAX_LIMITS = (E_BASE + 34); // over max limits.
constexpr int E_INVALID_CONNECTION = (E_BASE + 35); // invalid db connection.
constexpr int E_NO_SUCH_ENTRY = (E_BASE + 36); // invalid db connection.
constexpr int E_INTERNAL_ERROR = (E_BASE + 37); // an error due to code logic that is a bug
constexpr int E_CONTAINER_ONLY_DELAY_TASK = (E_BASE + 38); // only delay task left in the container
constexpr int E_SUM_CALCULATE_FAIL = (E_BASE + 39); // only delay task left in the container
constexpr int E_SUM_MISMATCH = (E_BASE + 40); // check sum mismatch
constexpr int E_OUT_OF_DATE = (E_BASE + 41); // things is out of date
constexpr int E_OBJ_IS_KILLED = (E_BASE + 42); // the refObject has been killed.
constexpr int E_SYSTEM_API_FAIL = (E_BASE + 43); // call the system api failed
constexpr int E_INVALID_DATA = (E_BASE + 44); // invalid data
constexpr int E_OUT_OF_IDS = (E_BASE + 45); // out of ids.
constexpr int E_SEND_DATA = (E_BASE + 46); // need send data
constexpr int E_NEED_TIMER = (E_BASE + 47); // timer is still need
constexpr int E_NO_NEED_TIMER = (E_BASE + 48); // timer no longer need
constexpr int E_COMBINE_FAIL = (E_BASE + 49); // fail in combining a frame
constexpr int E_END_TIMER = (E_BASE + 50); // timer no longer needed
constexpr int E_CALC_HASH = (E_BASE + 51); // calc hash error
constexpr int E_REMOVE_FILE = (E_BASE + 52); // remove file failed
constexpr int E_STATE_MACHINE_ERROR = (E_BASE + 53); // sync state machine error
constexpr int E_NO_DATA_SEND = (E_BASE + 54); // no data to send
constexpr int E_RECV_FINISHED = (E_BASE + 55); // recv finished
constexpr int E_NEED_PULL_REPONSE = (E_BASE + 56); // need to response pull request
constexpr int E_NO_SYNC_TASK = (E_BASE + 57); // no sync task to do
constexpr int E_INVALID_PASSWD_OR_CORRUPTED_DB = (E_BASE + 58); // invalid password or corrupted database.
constexpr int E_RESULT_SET_STATUS_INVALID = (E_BASE + 59); // status of result set is invalid.
constexpr int E_RESULT_SET_EMPTY = (E_BASE + 60); // the result set is empty.
constexpr int E_UPGRADE_FAILED = (E_BASE + 61); // the upgrade failed.
constexpr int E_INVALID_FILE = (E_BASE + 62); // import invalid file.
constexpr int E_INVALID_PATH = (E_BASE + 63); // the path is invalid.
constexpr int E_EMPTY_PATH = (E_BASE + 64); // the path is empty.
constexpr int E_TASK_BREAK_OFF = (E_BASE + 65); // task quit due to normal break off or error happen
constexpr int E_INCORRECT_DATA = (E_BASE + 66); // data in the database is incorrect
constexpr int E_NO_RESOURCE_FOR_USE = (E_BASE + 67); // no resource such as dbhandle for use
constexpr int E_LAST_SYNC_FRAME = (E_BASE + 68); // this frame is the last frame for this sync
constexpr int E_VERSION_NOT_SUPPORT = (E_BASE + 69); // version not support in any layer
constexpr int E_FRAME_TYPE_NOT_SUPPORT = (E_BASE + 70); // frame type not support
constexpr int E_INVALID_TIME = (E_BASE + 71); // the time is invalid
constexpr int E_INVALID_VERSION = (E_BASE + 72); // sqlite storage version is invalid
constexpr int E_SCHEMA_NOTEXIST = (E_BASE + 73); // schema does not exist
constexpr int E_INVALID_SCHEMA = (E_BASE + 74); // the schema is invalid
constexpr int E_SCHEMA_MISMATCH = (E_BASE + 75); // the schema is mismatch
constexpr int E_INVALID_FORMAT = (E_BASE + 76); // the value is invalid json or mismatch with the schema.
constexpr int E_READ_ONLY = (E_BASE + 77); // only have the read permission.
constexpr int E_NEED_ABILITY_SYNC = (E_BASE + 78); // ability sync has not done
constexpr int E_WAIT_NEXT_MESSAGE = (E_BASE + 79); // need remote device send a next message.
constexpr int E_LOCAL_DELETED = (E_BASE + 80); // local data is deleted by the unpublish.
constexpr int E_LOCAL_DEFEAT = (E_BASE + 81); // local data defeat the sync data while unpublish.
constexpr int E_LOCAL_COVERED = (E_BASE + 82); // local data is covered by the sync data while unpublish.
constexpr int E_INVALID_QUERY_FORMAT = (E_BASE + 83); // query format is not valid.
constexpr int E_INVALID_QUERY_FIELD = (E_BASE + 84); // query field is not valid.
constexpr int E_ALREADY_OPENED = (E_BASE + 85); // the database is already opened.
constexpr int E_ALREADY_SET = (E_BASE + 86); // already set.
constexpr int E_SAVE_DATA_NOTIFY = (E_BASE + 87); // notify remote device to keep alive, don't timeout
constexpr int E_RE_SEND_DATA = (E_BASE + 88); // need re send data
constexpr int E_EKEYREVOKED = (E_BASE + 89); // the EKEYREVOKED error
constexpr int E_SECURITY_OPTION_CHECK_ERROR = (E_BASE + 90); // remote device's SecurityOption not equal to local
constexpr int E_SYSTEM_API_ADAPTER_CALL_FAILED = (E_BASE + 91); // Adapter call failed
constexpr int E_NOT_NEED_DELETE_MSG = (E_BASE + 92); // not need delete msg, will be delete by sliding window receiver
constexpr int E_SLIDING_WINDOW_SENDER_ERR = (E_BASE + 93); // sliding window sender err
constexpr int E_SLIDING_WINDOW_RECEIVER_INVALID_MSG = (E_BASE + 94); // sliding window receiver invalid msg
constexpr int E_IGNORE_DATA = (E_BASE + 95); // ignore the data changed by other devices and ignore the same data.
constexpr int E_FORBID_CACHEDB = (E_BASE + 96); // such after rekey can not check passwd due to file control.
constexpr int E_INTERCEPT_DATA_FAIL = (E_BASE + 97); // Intercept push data failed.
constexpr int E_INVALID_COMPRESS_ALGO = (E_BASE + 98); // The algo is defined, but there's no implement for the algo.
constexpr int E_LOG_OVER_LIMITS = (E_BASE + 99); // The log file size is over the limits.
constexpr int E_MODE_MISMATCH = (E_BASE + 100); // dual sync mode mismatch
constexpr int E_NO_NEED_ACTIVE = (E_BASE + 101); // no need to active sync mode
// Num 150+ is reserved for schema related errno, since it may be added regularly
constexpr int E_JSON_PARSE_FAIL = (E_BASE + 150); // Parse json fail in grammatical level
constexpr int E_JSON_INSERT_PATH_EXIST = (E_BASE + 151); // Path already exist before insert
constexpr int E_JSON_INSERT_PATH_CONFLICT = (E_BASE + 152); // Nearest path ends with type not object
constexpr int E_JSON_DELETE_PATH_NOT_FOUND = (E_BASE + 153); // Path to delete not found
constexpr int E_SCHEMA_PARSE_FAIL = (E_BASE + 160); // Parse schema fail in content level
constexpr int E_SCHEMA_EQUAL_EXACTLY = (E_BASE + 161); // Two schemas are exactly the same
constexpr int E_SCHEMA_UNEQUAL_COMPATIBLE = (E_BASE + 162); // New schema contain different index
constexpr int E_SCHEMA_UNEQUAL_COMPATIBLE_UPGRADE = (E_BASE + 163); // New schema contain more field(index may differ)
constexpr int E_SCHEMA_UNEQUAL_INCOMPATIBLE = (E_BASE + 164); // New schema contain more field or index
constexpr int E_SCHEMA_VIOLATE_VALUE = (E_BASE + 165); // New schema violate values already exist in dbFile
constexpr int E_FLATBUFFER_VERIFY_FAIL = (E_BASE + 170); // Verify flatbuffer content(schema or value) fail.
constexpr int E_VALUE_MATCH = (E_BASE + 180); // Value match schema(strict or compatible) without amend
constexpr int E_VALUE_MATCH_AMENDED = (E_BASE + 181); // Value match schema(strict or compatible) with amend
constexpr int E_VALUE_MISMATCH_FEILD_COUNT = (E_BASE + 182); // Value mismatch schema in field count
constexpr int E_VALUE_MISMATCH_FEILD_TYPE = (E_BASE + 183); // Value mismatch schema in field type
constexpr int E_VALUE_MISMATCH_CONSTRAINT = (E_BASE + 184); // Value mismatch schema in constraint
constexpr int E_VALUE_MISMATCH_OTHER_REASON = (E_BASE + 185); // Value mismatch schema in other reason
constexpr int E_RELATIONAL_TABLE_EQUAL = (E_BASE + 186); // In table is same
constexpr int E_RELATIONAL_TABLE_COMPATIBLE = (E_BASE + 187); // In table is compatible
constexpr int E_RELATIONAL_TABLE_COMPATIBLE_UPGRADE = (E_BASE + 188); // In table has more fields with default value
constexpr int E_RELATIONAL_TABLE_INCOMPATIBLE = (E_BASE + 189); // In table is incompatible
// Num 200+ is reserved for fixed value errno, which should not be changed between time
// Message with errorNo of Feedback-type is generated by CommunicatorAggregator without data part(No deserial if exist)
constexpr int E_FEEDBACK_UNKNOWN_MESSAGE = (E_BASE + 200); // Unknown message feedback from remote device
constexpr int E_FEEDBACK_COMMUNICATOR_NOT_FOUND = (E_BASE + 201); // Communicator not found feedback from remote device
constexpr int E_DISTRIBUTED_SCHEMA_NOT_FOUND = (E_BASE + 202); // Schema was not found in relational distributed tables
constexpr int E_DISTRIBUTED_SCHEMA_CHANGED = (E_BASE + 203); // Schema has change when do sync
} // namespace DistributedDB
#endif // DISTRIBUTEDDB_ERRNO_H

View File

@ -0,0 +1,140 @@
/*
* 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 DISTRIBUTEDDB_TYPES_H
#define DISTRIBUTEDDB_TYPES_H
#include <cstdint>
#include <functional>
#include <string>
#include <vector>
#include "types_export.h"
#include "db_constant.h"
namespace DistributedDB {
using Timestamp = uint64_t;
using ContinueToken = void *;
using DeviceID = std::string;
using TimeOffset = int64_t;
using ErrorCode = int;
using SyncId = uint64_t;
using WaterMark = uint64_t;
using DatabaseCorruptHandler = std::function<void()>;
using DatabaseLifeCycleNotifier = std::function<void(const std::string &, const std::string &)>;
const uint32_t MTU_SIZE = 5 * 1024 * 1024; // 5 M, 1024 is scale
struct DataItem {
Key key;
Value value;
Timestamp timestamp = 0;
uint64_t flag = 0;
std::string origDev;
Timestamp writeTimestamp = 0;
std::string dev;
bool neglect = false;
Key hashKey{};
static constexpr uint64_t DELETE_FLAG = 0x01;
static constexpr uint64_t LOCAL_FLAG = 0x02;
static constexpr uint64_t REMOVE_DEVICE_DATA_FLAG = 0x04; // only use for cachedb
static constexpr uint64_t REMOVE_DEVICE_DATA_NOTIFY_FLAG = 0x08; // only use for cachedb
// Only use for query sync and subscribe. ATTENTION!!! this flag should not write into mainDB.
// Mark the changed row data does not match with query sync(or subscribe) condition.
static constexpr uint64_t REMOTE_DEVICE_DATA_MISS_QUERY = 0x10;
static constexpr uint64_t UPDATE_FLAG = 0X20;
};
struct PragmaPublishInfo {
Key key;
bool deleteLocal = false;
bool updateTimestamp = false;
KvStoreNbPublishAction action;
};
struct PragmaUnpublishInfo {
Key key;
bool isDeleteSync = false;
bool isUpdateTime = false;
};
struct IOption {
static constexpr int LOCAL_DATA = 1;
static constexpr int SYNC_DATA = 2;
int dataType = LOCAL_DATA;
};
struct DataSizeSpecInfo {
uint32_t blockSize = MTU_SIZE;
size_t packetSize = DBConstant::MAX_HPMODE_PACK_ITEM_SIZE;
};
enum NotificationEventType {
DATABASE_COMMIT_EVENT = 0
};
// Following are schema related common definition
using FieldName = std::string;
using FieldPath = std::vector<std::string>;
// Normally, LEAF_FIELD_NULL will not appear in valid schema. LEAF_FIELD_LONG contain LEAF_FIELD_INTEGER, both are
// signed type and LEAF_FIELD_DOUBLE contain LEAF_FIELD_LONG. We don't parse into an array, so array are always leaf
// type. We parse into an object, LEAF_FIELD_OBJECT means an empty object, INTERNAL_FIELD_OBJECT however not empty.
enum class FieldType {
LEAF_FIELD_NULL,
LEAF_FIELD_BOOL,
LEAF_FIELD_INTEGER,
LEAF_FIELD_LONG,
LEAF_FIELD_DOUBLE,
LEAF_FIELD_STRING,
LEAF_FIELD_ARRAY,
LEAF_FIELD_OBJECT,
INTERNAL_FIELD_OBJECT,
};
using TypeValue = std::pair<FieldType, FieldValue>; // Define for parameter convenience
// Schema compatibility check behave differently for different value source
enum class ValueSource {
FROM_LOCAL,
FROM_SYNC,
FROM_DBFILE,
};
// Represent raw-value from database to avoid copy. the first is the value start pointer, the second is the length.
using RawValue = std::pair<const uint8_t *, uint32_t>;
using RawString = const std::string::value_type *;
enum class OperatePerm {
NORMAL_PERM,
REKEY_MONOPOLIZE_PERM,
IMPORT_MONOPOLIZE_PERM,
DISABLE_PERM,
};
enum SingleVerConflictResolvePolicy {
DEFAULT_LAST_WIN = 0,
DENY_OTHER_DEV_AMEND_CUR_DEV_DATA = 1,
};
struct SyncTimeRange {
Timestamp beginTime = 0;
Timestamp deleteBeginTime = 0;
Timestamp endTime = static_cast<Timestamp>(INT64_MAX);
Timestamp deleteEndTime = static_cast<Timestamp>(INT64_MAX);
Timestamp lastQueryTime = 0;
bool IsValid() const
{
return (beginTime <= endTime && deleteBeginTime <= deleteEndTime);
}
};
} // namespace DistributedDB
#endif // DISTRIBUTEDDB_TYPES_H

View File

@ -0,0 +1,55 @@
/*
* 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 ENDIAN_CONVERT_H
#define ENDIAN_CONVERT_H
#include <cstdint>
#include <cstddef>
namespace DistributedDB {
inline bool IsBigEndian()
{
uint32_t data = 0x12345678; // 0x12345678 only used here, for endian test
uint8_t *firstByte = reinterpret_cast<uint8_t *>(&data);
if (*firstByte == 0x12) { // 0x12 only used here, for endian test
return true;
}
return false;
}
template<typename T> T HostToNet(const T &from)
{
if (IsBigEndian()) {
return from;
} else {
T to;
size_t typeLen = sizeof(T);
const uint8_t *fromByte = reinterpret_cast<const uint8_t *>(&from);
uint8_t *toByte = reinterpret_cast<uint8_t *>(&to);
for (size_t i = 0; i < typeLen; i++) {
toByte[i] = fromByte[typeLen - i - 1]; // 1 is for index boundary
}
return to;
}
}
template<typename T> T NetToHost(const T &from)
{
return HostToNet(from);
}
}
#endif

View File

@ -0,0 +1,31 @@
/*
* 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 HASH_H
#define HASH_H
#include <cstdint>
#include <string>
namespace DistributedDB {
class Hash {
const static uint64_t PRIME_SEED = 33; // 33 is a prime seed
public:
static uint64_t HashFunc(const std::string &input);
static uint32_t Hash32Func(const std::string &input);
};
}
#endif

View File

@ -0,0 +1,61 @@
/*
* 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 I_SCHEMA_H
#define I_SCHEMA_H
#include <string>
#include "db_types.h"
namespace DistributedDB {
// SchemaType::NONE represent for KV database which do not have schema. Only invalid SchemaObject is NONE type.
// Enum value must not be changed except SchemaType::UNRECOGNIZED.
enum class SchemaType : uint8_t {
NONE = 0,
JSON = 1,
FLATBUFFER = 2,
RELATIVE = 3,
UNRECOGNIZED = 4
};
inline SchemaType ReadSchemaType(uint8_t inType)
{
if (inType >= static_cast<uint8_t>(SchemaType::UNRECOGNIZED)) {
return SchemaType::UNRECOGNIZED;
}
return static_cast<SchemaType>(inType);
}
struct SchemaAttribute {
FieldType type = FieldType::LEAF_FIELD_NULL;
bool isIndexable = false;
bool hasNotNullConstraint = false;
bool hasDefaultValue = false;
FieldValue defaultValue; // Has default value in union part and default construction in string part
std::string customFieldType {}; // Custom field type like BIGINT, DECIMAL, CHARACTER ...
};
class ISchema {
public:
ISchema() = default;
virtual ~ISchema() = default;
virtual int ParseFromSchemaString(const std::string &inSchemaString) = 0;
virtual bool IsSchemaValid() const = 0;
virtual SchemaType GetSchemaType() const = 0;
virtual std::string ToSchemaString() const = 0;
};
}
#endif // I_SCHEMA_H

View File

@ -0,0 +1,131 @@
/*
* 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 JSON_OBJECT_H
#define JSON_OBJECT_H
#include <map>
#include <set>
#include <string>
#include <vector>
#ifndef OMIT_JSON
#include <json/json.h>
#endif
#include "db_types.h"
namespace DistributedDB {
// JsonObject is the abstraction of JsonString, it hides the JsonLib that we use and other messy details.
// JsonObject do not support concurrence inherently, use it locally or under mutex protection.
class JsonObject {
public:
// Set max allowed nest depth and return the value before set.
static uint32_t SetMaxNestDepth(uint32_t nestDepth);
// Calculate nest depth when json string is legal or estimate depth by legal part from illegal json.
static uint32_t CalculateNestDepth(const std::string &inString, int &errCode);
static uint32_t CalculateNestDepth(const uint8_t *dataBegin, const uint8_t *dataEnd, int &errCode);
// Support default constructor, copy constructor and copy assignment
JsonObject() = default;
~JsonObject() = default;
JsonObject(const JsonObject &);
JsonObject& operator=(const JsonObject &);
explicit JsonObject(const Json::Value &value);
// Should be called on an invalid JsonObject, create new JsonObject if need to reparse
// Require the type of the root to be JsonObject, otherwise parse fail
int Parse(const std::string &inString);
int Parse(const std::vector<uint8_t> &inData); // Whether ends with '\0' in vector is OK
// The end refer to the byte after the last valid byte
int Parse(const uint8_t *dataBegin, const uint8_t *dataEnd);
bool IsValid() const;
// Unnecessary spacing will be removed and fieldName resorted by lexicographical order
std::string ToString() const;
bool IsFieldPathExist(const FieldPath &inPath) const;
int GetFieldTypeByFieldPath(const FieldPath &inPath, FieldType &outType) const;
int GetFieldValueByFieldPath(const FieldPath &inPath, FieldValue &outValue) const;
int GetObjectArrayByFieldPath(const FieldPath &inPath, std::vector<JsonObject> &outArray) const;
int GetStringArrayByFieldPath(const FieldPath &inPath, std::vector<std::string> &outArray) const;
int GetObjectByFieldPath(const FieldPath &inPath, JsonObject &outObj) const;
// An empty fieldPath indicate the root, the outSubPath should be empty before call, we will not empty it at first.
// If inPath is of multiple path, then outSubPath is combination of result of each inPath.
int GetSubFieldPath(const FieldPath &inPath, std::set<FieldPath> &outSubPath) const;
int GetSubFieldPath(const std::set<FieldPath> &inPath, std::set<FieldPath> &outSubPath) const;
int GetSubFieldPathAndType(const FieldPath &inPath, std::map<FieldPath, FieldType> &outSubPathType) const;
int GetSubFieldPathAndType(const std::set<FieldPath> &inPath, std::map<FieldPath, FieldType> &outSubPathType) const;
// If inPath not refer to an array, return error.
int GetArraySize(const FieldPath &inPath, uint32_t &outSize) const;
// If inPath not refer to an array, return error. If not all members are string or array type, return error.
// If array-type member is empty, ignore. If not all members of the array-type member are string, return error.
int GetArrayContentOfStringOrStringArray(const FieldPath &inPath,
std::vector<std::vector<std::string>> &outContent) const;
// Can be called no matter JsonObject valid or not. Invalid turn into valid after call(insert on invalid never fail
// if parameter is valid). An empty inPath is not allowed. LEAF_FIELD_ARRAY and INTERNAL_FIELD_OBJECT is not
// supported. infinite double is not support. inValue is ignored for LEAF_FIELD_NULL.
// When inPath already exist, append value if it's an arrayObject, otherwise returns -E_JSON_INSERT_PATH_EXIST
// if nearest path ends with type not object, rets -E_JSON_INSERT_PATH_CONFLICT.
// Otherwise, insert field as well as filling up intermediate field, then returns E_OK;
// isAppend: when it's true, append inValue as path is an arrayObject if path not exist.
int InsertField(const FieldPath &inPath, FieldType inType, const FieldValue &inValue, bool isAppend = false);
// Add json object to an array field. should be called on an valid JsonObject. Never turn into invalid after call.
// If inPath not refer to an array, return error.
int InsertField(const FieldPath &inPath, const JsonObject &inValue, bool isAppend = false);
// Should be called on an valid JsonObject. Never turn into invalid after call. An empty inPath is not allowed.
// If inPath not exist, returns -E_JSON_DELETE_PATH_NOT_FOUND. Otherwise, delete field from its parent returns E_OK;
int DeleteField(const FieldPath &inPath);
private:
#ifndef OMIT_JSON
// Auxiliary Method: If inPath not refer to an array, return error. If not all members are string, return error.
int GetStringArrayContentByJsonValue(const Json::Value &value, std::vector<std::string> &outStringArray) const;
// Common Type Judgement Logic
int GetFieldTypeByJsonValue(const Json::Value &value, FieldType &outType) const;
// Return E_OK if JsonValueNode found at exact the path, otherwise not E_OK
const Json::Value &GetJsonValueByFieldPath(const FieldPath &inPath, int &errCode) const;
// REQUIRE: JsonObject is valid(Root value is object type).
// If inPath empty(means root), set exact and nearest to root value and nearDepth to 0, then ret E_OK;
// If JsonValue exist at exact path, set exact to this JsonValue, set nearest to its parent JsonValue, set nearDepth
// to the depth of this parent JsonValue, then ret E_OK;
// If exact path no exist, set exact to nullptr, set nearest to nearest JsonValue that can be found, set nearDepth
// to the depth of this nearest JsonValue, then ret -E_NOT_FOUND;
int LocateJsonValueByFieldPath(const FieldPath &inPath, Json::Value *&exact,
Json::Value *&nearest, uint32_t &nearDepth);
// create if path not exist
int MoveToPath(const FieldPath &inPath, Json::Value *&exact, Json::Value *&nearest);
static uint32_t maxNestDepth_;
bool isValid_ = false;
Json::Value value_;
#endif
};
} // namespace DistributedDB
#endif // JSON_OBJECT_H

View File

@ -0,0 +1,57 @@
/*
* 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 DISTRIBUTEDDB_LOG_PRINT_H
#define DISTRIBUTEDDB_LOG_PRINT_H
#include <cinttypes>
#include <cstdarg>
#include <cstdio>
#include <string>
namespace DistributedDB {
const std::string LOG_TAG_KV = "DistributedDB";
class Logger {
public:
enum class Level {
LEVEL_DEBUG,
LEVEL_INFO,
LEVEL_WARN,
LEVEL_ERROR,
LEVEL_FATAL
};
virtual ~Logger() {};
static Logger *GetInstance();
static void RegisterLogger(Logger *logger);
static void Log(Level level, const std::string &tag, const char *func, int line, const char *format, ...);
private:
virtual void Print(Level level, const std::string &tag, const std::string &msg) = 0;
static void PreparePrivateLog(const char *format, std::string &outStrFormat);
static Logger *logHandler;
static const std::string PRIVATE_TAG;
};
#define NO_LOG(...) // No log in normal and release. Used for convenience when deep debugging
#define LOGD(...) Logger::Log(Logger::Level::LEVEL_DEBUG, LOG_TAG_KV, __FUNCTION__, __LINE__, __VA_ARGS__)
#define LOGI(...) Logger::Log(Logger::Level::LEVEL_INFO, LOG_TAG_KV, __FUNCTION__, __LINE__, __VA_ARGS__)
#define LOGW(...) Logger::Log(Logger::Level::LEVEL_WARN, LOG_TAG_KV, __FUNCTION__, __LINE__, __VA_ARGS__)
#define LOGE(...) Logger::Log(Logger::Level::LEVEL_ERROR, LOG_TAG_KV, __FUNCTION__, __LINE__, __VA_ARGS__)
#define LOGF(...) Logger::Log(Logger::Level::LEVEL_FATAL, LOG_TAG_KV, __FUNCTION__, __LINE__, __VA_ARGS__)
} // namespace DistributedDB
#endif // DISTRIBUTEDDB_LOG_PRINT_H

View File

@ -0,0 +1,45 @@
/*
* 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 MACRO_UTILS_H
#define MACRO_UTILS_H
namespace DistributedDB {
#define DISABLE_COPY_ASSIGN_MOVE(ClassName) \
ClassName(const ClassName &) = delete; \
ClassName(ClassName &&) = delete; \
ClassName& operator=(const ClassName &) = delete; \
ClassName& operator=(ClassName &&) = delete
#define DECLARE_OBJECT_TAG(ClassName) \
std::string GetObjectTag() const override; \
constexpr static const char * const classTag = "Class-"#ClassName
#define DEFINE_OBJECT_TAG_FACILITIES(ClassName) \
std::string ClassName::GetObjectTag() const \
{ \
return ClassName::classTag; \
}
#define BYTE_8_ALIGN(x) (((x) + (8 - 1)) & ~(8 - 1))
#define BITX(x) (1 << (x))
#define ULL(x) (static_cast<unsigned long long>(x))
// Convert var or enum to variable name for printf
#define VNAME(name) (#name)
}
#endif // MACRO_UTILS_H

View File

@ -0,0 +1,143 @@
/*
* 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 NOTIFICATION_CHAIN_H
#define NOTIFICATION_CHAIN_H
#include <map>
#include <set>
#include <thread>
#include <condition_variable>
#include "ref_object.h"
namespace DistributedDB {
using EventType = unsigned int;
class NotificationChain final : public RefObject {
private:
class ListenerChain;
public:
class Listener final : public RefObject {
public:
using OnEvent = std::function<void(void *)>;
using OnFinalize = std::function<void(void)>;
// Called by ListenerChain.callbackListeners, it will call the OnEvent
void NotifyListener(void *arg);
// Drop this listener. after call this function, the listener will be destroy
int Drop(bool wait = false);
// Enter kill-waiting state if 'onEvent()' is invoking when 'KillObj()'.
void KillWait();
// Set the listener chain we belong to.
void SetOwner(ListenerChain *listenerChain);
Listener(const OnEvent &onEvent, const OnFinalize &onFinalize);
// Delete the copy and assign constructors
DISABLE_COPY_ASSIGN_MOVE(Listener);
protected:
~Listener() override;
private:
// will be call when this listener destroy
void Finalize() const;
bool EnterEventAction();
void LeaveEventAction();
DECLARE_OBJECT_TAG(Listener);
constexpr static int KILL_WAIT_SECONDS = 5; // wait only 5 seconds when killing to avoid dead-lock.
OnEvent onEvent_;
OnFinalize onFinalize_;
ListenerChain *listenerChain_;
std::thread::id eventRunningThread_;
std::condition_variable safeKill_;
};
// Add a listener from the NotificationChain. it will return a Listener handle
// The param type should match the RegisterEventsType
// The param onEvent will be call when events happened.
// The param onFinalize will be call when this listener destroy
Listener *RegisterListener(EventType type, const Listener::OnEvent &onEvent,
const Listener::OnFinalize &onFinalize, int &errCode);
// User to register an events type to the NotificationChain, needs to call at init
int RegisterEventType(EventType type);
// User to unregister an events type.
int UnRegisterEventType(EventType type);
// Should be call when events happened.
void NotifyEvent(EventType type, void *arg);
NotificationChain() = default;
// Delete the copy and assign constructors
DISABLE_COPY_ASSIGN_MOVE(NotificationChain);
protected:
~NotificationChain() override;
private:
class ListenerChain final : public RefObject {
public:
// Add a listener to the ListenerChain
int RegisterListener(Listener *listener);
// Remove a listener to the ListenerChain
int UnRegisterListener(Listener *listener, bool wait = false);
// Callback all the listeners
void NotifyListeners(void *arg);
// Clear all listeners
void ClearListeners();
ListenerChain();
// Delete the copy and assign constructors
DISABLE_COPY_ASSIGN_MOVE(ListenerChain);
protected:
~ListenerChain() override;
private:
// Used to back up listenerSet_, need to lock
void BackupListenerSet(std::set<Listener *> &backupSet) const;
DECLARE_OBJECT_TAG(ListenerChain);
std::set<Listener *> listenerSet_;
};
// Find a ListenerChain from the eventChains_ with given type,
// this function needs to lock.
ListenerChain *FindAndGetListenerChainLocked(EventType type);
// Find a ListenerChain from the eventChains_ with given type,
ListenerChain *FindListenerChain(EventType type) const;
DECLARE_OBJECT_TAG(NotificationChain);
std::map<EventType, ListenerChain *> eventChains_;
};
} // namespace DistributedDB
#endif // NOTIFICATION_CHAIN_H

View File

@ -0,0 +1,58 @@
/*
* 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 PARAM_CHECK_UTILS_H
#define PARAM_CHECK_UTILS_H
#include <string>
#include "db_types.h"
#include "auto_launch_export.h"
#include "schema_object.h"
namespace DistributedDB {
class ParamCheckUtils final {
public:
static bool CheckDataDir(const std::string &dir, std::string &canonicalDir);
// Check if the storeID is a safe arg.
static bool IsStoreIdSafe(const std::string &storeId);
// check appId, userId, storeId.
static bool CheckStoreParameter(const std::string &storeId, const std::string &appId, const std::string &userId,
bool isIgnoreUserIdCheck = false);
// check encrypted args for KvStore.
static bool CheckEncryptedParameter(CipherType cipher, const CipherPassword &passwd);
static bool CheckConflictNotifierType(int conflictType);
static bool CheckSecOption(const SecurityOption &secOption);
static bool CheckObserver(const Key &key, unsigned int mode);
static bool IsS3SECEOpt(const SecurityOption &secOpt);
static int CheckAndTransferAutoLaunchParam(const AutoLaunchParam &param, bool checkDir,
SchemaObject &schemaObject, std::string &canonicalDir);
static uint8_t GetValidCompressionRate(uint8_t compressionRate);
static bool CheckRelationalTableName(const std::string &tableName);
};
} // namespace DistributedDB
#endif // DISTRIBUTEDDB_PARAM_CHECK_UTILS_H

View File

@ -0,0 +1,233 @@
/*
* 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 PARCEL_H
#define PARCEL_H
#include <vector>
#include <cstdint>
#include <string>
#include <type_traits>
#include "endian_convert.h"
#include "securec.h"
#include "macro_utils.h"
#include "db_errno.h"
#include "log_print.h"
#ifndef OMIT_MULTI_VER
#include "multi_ver_def.h"
#endif
namespace DistributedDB {
class Parcel {
public:
Parcel(uint8_t *inBuf, uint32_t length);
~Parcel();
bool IsError() const;
int WriteBool(bool data);
uint32_t ReadBool(bool &data);
int WriteInt(int data);
uint32_t ReadInt(int &val);
int WriteUInt8(uint8_t data);
uint32_t ReadUInt8(uint8_t &val);
int WriteDouble(double data);
uint32_t ReadDouble(double &val);
int WriteInt64(int64_t data);
uint32_t ReadInt64(int64_t &val);
int WriteUInt32(uint32_t data);
uint32_t ReadUInt32(uint32_t &val);
int WriteUInt64(uint64_t data);
uint32_t ReadUInt64(uint64_t &val);
int WriteVectorChar(const std::vector<uint8_t> &data);
uint32_t ReadVectorChar(std::vector<uint8_t> &val);
int WriteString(const std::string &inVal);
uint32_t ReadString(std::string &outVal);
bool IsContinueRead();
#ifndef OMIT_MULTI_VER
int WriteMultiVerCommit(const MultiVerCommitNode &commit);
uint32_t ReadMultiVerCommit(MultiVerCommitNode &commit);
int WriteMultiVerCommits(const std::vector<MultiVerCommitNode> &commits);
uint32_t ReadMultiVerCommits(std::vector<MultiVerCommitNode> &commits);
#endif
template<typename T>
int WriteVector(const std::vector<T> &data)
{
static_assert(std::is_pod<T>::value, "type T is not pod");
if (data.size() > INT32_MAX || sizeof(T) > INT32_MAX) {
LOGE("[WriteVector] invalid vector. vec.size:%zu, sizeof(T):%zu", data.size(), sizeof(T));
isError_ = true;
return -E_PARSE_FAIL;
}
if (IsError()) {
return -E_PARSE_FAIL;
}
uint32_t len = data.size();
uint64_t stepLen = static_cast<uint64_t>(data.size()) * sizeof(T) + sizeof(uint32_t);
len = HostToNet(len);
if (bufPtr_ == nullptr || stepLen > INT32_MAX || parcelLen_ + BYTE_8_ALIGN(stepLen) > totalLen_) {
LOGE("[WriteVector] bufPtr:%d, stepLen:%llu, totalLen:%llu, parcelLen:%llu",
bufPtr_ != nullptr, ULL(stepLen), ULL(totalLen_), ULL(parcelLen_));
isError_ = true;
return -E_PARSE_FAIL;
}
errno_t errCode = memcpy_s(bufPtr_, totalLen_ - parcelLen_, &len, sizeof(uint32_t));
if (errCode != EOK) {
LOGE("[ReadVector] totalLen:%llu, parcelLen:%llu", ULL(totalLen_), ULL(parcelLen_));
isError_ = true;
return -E_SECUREC_ERROR;
}
bufPtr_ += sizeof(uint32_t);
for (auto iter : data) {
*(reinterpret_cast<T *>(bufPtr_)) = HostToNet(iter);
bufPtr_ += sizeof(T);
}
bufPtr_ += BYTE_8_ALIGN(stepLen) - stepLen;
parcelLen_ += BYTE_8_ALIGN(stepLen);
return errCode;
}
template<typename T>
uint32_t ReadVector(std::vector<T> &val)
{
static_assert(std::is_pod<T>::value, "type T is not pod");
if (IsError()) {
return 0;
}
if (bufPtr_ == nullptr || parcelLen_ + sizeof(uint32_t) > totalLen_ || sizeof(T) > INT32_MAX) {
LOGE("[ReadVector] bufPtr:%d, totalLen:%llu, parcelLen:%llu, sizeof(T):%zu",
bufPtr_ != nullptr, ULL(totalLen_), ULL(parcelLen_), sizeof(T));
isError_ = true;
return 0;
}
uint32_t len = *(reinterpret_cast<uint32_t *>(bufPtr_));
len = NetToHost(len);
if (len > INT32_MAX) {
LOGE("[ReadVector] invalid length:%u", len);
isError_ = true;
return 0;
}
uint64_t stepLen = static_cast<uint64_t>(len) * sizeof(T) + sizeof(uint32_t);
if (stepLen > INT32_MAX || parcelLen_ + BYTE_8_ALIGN(stepLen) > totalLen_) {
LOGE("[ReadVector] stepLen:%llu, totalLen:%llu, parcelLen:%llu", ULL(stepLen), ULL(totalLen_),
ULL(parcelLen_));
isError_ = true;
return 0;
}
bufPtr_ += sizeof(uint32_t);
val.resize(len);
for (uint32_t i = 0; i < len; i++) {
val[i] = NetToHost(*(reinterpret_cast<T *>(bufPtr_)));
bufPtr_ += sizeof(T);
}
bufPtr_ += BYTE_8_ALIGN(stepLen) - stepLen;
parcelLen_ += BYTE_8_ALIGN(stepLen);
stepLen = BYTE_8_ALIGN(stepLen);
return static_cast<uint32_t>(stepLen);
}
int WriteBlob(const char *buffer, uint32_t bufLen);
uint32_t ReadBlob(char *buffer, uint32_t bufLen);
void EightByteAlign(); // Avoid reading a single data type across 8 bytes
static uint32_t GetBoolLen();
static uint32_t GetIntLen();
static uint32_t GetUInt8Len();
static uint32_t GetUInt32Len();
static uint32_t GetUInt64Len();
static uint32_t GetInt64Len();
static uint32_t GetDoubleLen();
static uint32_t GetVectorCharLen(const std::vector<uint8_t> &data);
template<typename T>
static uint32_t GetVectorLen(const std::vector<T> &data)
{
if (data.size() > INT32_MAX || sizeof(T) > INT32_MAX) {
return 0;
}
uint64_t len = sizeof(uint32_t) + static_cast<uint64_t>(data.size()) * sizeof(T);
len = BYTE_8_ALIGN(len);
if (len > INT32_MAX) {
return 0;
}
return static_cast<uint32_t>(len);
}
static uint32_t GetEightByteAlign(uint32_t len);
static uint32_t GetStringLen(const std::string &data);
#ifndef OMIT_MULTI_VER
static uint32_t GetMultiVerCommitLen(const MultiVerCommitNode &commit);
static uint32_t GetMultiVerCommitsLen(const std::vector<MultiVerCommitNode> &commits);
#endif
static uint32_t GetAppendedLen();
private:
template<typename T>
int WriteInteger(T integer);
template<typename T>
uint32_t ReadInteger(T &integer);
bool isError_ = false;
uint8_t *buf_ = nullptr;
uint8_t *bufPtr_ = nullptr;
uint64_t parcelLen_ = 0;
uint64_t totalLen_ = 0;
};
template<typename T>
uint32_t Parcel::ReadInteger(T &integer)
{
if (IsError()) {
return 0;
}
if (bufPtr_ == nullptr || parcelLen_ + sizeof(T) > totalLen_) {
LOGE("[ReadInteger] bufPtr:%d, totalLen:%llu, parcelLen:%llu, sizeof(T):%zu",
bufPtr_ != nullptr, ULL(totalLen_), ULL(parcelLen_), sizeof(T));
isError_ = true;
return 0;
}
integer = *(reinterpret_cast<T *>(bufPtr_));
bufPtr_ += sizeof(T);
parcelLen_ += sizeof(T);
integer = NetToHost(integer);
return sizeof(T);
}
template<typename T>
int Parcel::WriteInteger(T integer)
{
if (IsError()) {
return -E_PARSE_FAIL;
}
T inData = HostToNet(integer);
if (parcelLen_ + sizeof(T) > totalLen_) {
LOGE("[WriteInteger] totalLen:%llu, parcelLen:%llu, sizeof(T):%zu", ULL(totalLen_), ULL(parcelLen_), sizeof(T));
isError_ = true;
return -E_PARSE_FAIL;
}
errno_t errCode = memcpy_s(bufPtr_, totalLen_ - parcelLen_, &inData, sizeof(T));
if (errCode != EOK) {
LOGE("[WriteInteger] bufPtr:%d, totalLen:%llu, parcelLen:%llu, sizeof(T):%zu",
bufPtr_ != nullptr, ULL(totalLen_), ULL(parcelLen_), sizeof(T));
isError_ = true;
return -E_SECUREC_ERROR;
}
bufPtr_ += sizeof(T);
parcelLen_ += sizeof(T);
return errCode;
}
} // namespace DistributedDB
#endif // PARCEL_H

View File

@ -0,0 +1,123 @@
/*
* 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 PERFORMANCE_ANALYSIS_H
#define PERFORMANCE_ANALYSIS_H
#include <vector>
#include <fstream>
#include "db_types.h"
namespace DistributedDB {
enum PT_TEST_RECORDS : uint32_t {
RECORD_PUT_DATA = 1,
RECORD_SYNC_TOTAL,
RECORD_WATERMARK_SYNC,
RECORD_READ_DATA,
RECORD_SAVE_DATA,
RECORD_SAVE_LOCAL_WATERMARK,
RECORD_SAVE_PEER_WATERMARK,
RECORD_DATA_SEND_REQUEST_TO_ACK_RECV,
RECORD_DATA_REQUEST_RECV_TO_SEND_ACK,
RECORD_MACHINE_START_TO_PUSH_SEND,
RECORD_ACK_RECV_TO_USER_CALL_BACK,
};
enum MV_TEST_RECORDS : uint32_t {
RECORD_SEND_LOCAL_DATA_CHANGED_TO_COMMIT_REQUEST_RECV = 3,
RECORD_GET_DEVICE_LATEST_COMMIT,
RECORD_COMMIT_SEND_REQUEST_TO_ACK_RECV,
RECORD_GET_COMMIT_TREE,
RECORD_DATA_GET_VALID_COMMIT,
RECORD_DATA_ENTRY_SEND_REQUEST_TO_ACK_RECV,
RECORD_GET_COMMIT_DATA,
RECORD_GET_VALUE_SLICE_NODE,
RECORD_VALUE_SLICE_SEND_REQUEST_TO_ACK_RECV,
RECORD_READ_VALUE_SLICE,
RECORD_SAVE_VALUE_SLICE,
RECORD_PUT_COMMIT_DATA,
RECORD_MERGE,
};
struct TimePair {
Timestamp startTime = 0;
Timestamp endTime = 0;
};
struct StatisticsInfo {
Timestamp max = 0;
Timestamp min = 0;
float average = 0.0;
};
struct SingleStatistics {
std::vector<TimePair> timeInfo;
};
class PerformanceAnalysis {
public:
explicit PerformanceAnalysis(uint32_t step);
~PerformanceAnalysis();
static PerformanceAnalysis *GetInstance(int stepNum = 20);
void TimeRecordStart();
void TimeRecordEnd();
void StepTimeRecordStart(uint32_t step);
void StepTimeRecordEnd(uint32_t step);
std::string GetStatistics();
void OpenPerformanceAnalysis();
void ClosePerformanceAnalysis();
void SetFileNumber(const std::string &FileID);
private:
bool IsStepValid(uint32_t step) const;
bool IsOpen() const;
bool InsertTimeRecord(const TimePair &timePair, uint32_t step);
bool GetTimeRecord(uint32_t step, TimePair &timePair) const;
void OutStatistics();
void Clear();
void Close();
const static int MAX_TIMERECORD_STEP_NUM = 200;
const static std::string STATISTICAL_DATA_FILE_NAME_HEADER;
const static std::string CSV_FILE_EXTENSION;
const static std::string DEFAULT_FILE_NAME;
SingleStatistics timeRecordData_;
std::vector<StatisticsInfo> stepTimeRecordInfo_;
std::vector<uint64_t> counts_;
uint32_t stepNum_;
bool isOpen_;
std::ofstream outFile;
int fileNumber_;
std::string fileID_;
};
} // namespace DistributedDB
#endif

View File

@ -0,0 +1,78 @@
/*
* 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 PLATFORM_SPECIFIC_H
#define PLATFORM_SPECIFIC_H
#include <string>
#include <cstdint>
#include <list>
namespace DistributedDB {
namespace OS {
enum FileType {
FILE = 0,
PATH = 1,
OTHER = 2,
};
struct FileAttr {
std::string fileName;
FileType fileType;
uint64_t fileLen;
};
// Shield the representation method of file handles on different platforms
struct FileHandle {
int handle = -1;
};
int CalFileSize(const std::string &fileUrl, uint64_t &size);
bool CheckPathExistence(const std::string &filePath);
int MakeDBDirectory(const std::string &directory);
int RemoveFile(const std::string &filePath);
// Can only remove empty directory
int RemoveDBDirectory(const std::string &directory);
int GetRealPath(const std::string &inOriPath, std::string &outRealPath);
int GetCurrentSysTimeInMicrosecond(uint64_t &outTime);
int GetMonotonicRelativeTimeInMicrosecond(uint64_t &outTime);
int CreateFileByFileName(const std::string &fileName);
void SplitFilePath(const std::string &filePath, std::string &fileDir, std::string &fileName);
int GetFileAttrFromPath(const std::string &filePath, std::list<FileAttr> &files, bool isNeedAllPath = false);
int GetFilePermissions(const std::string &fileName, uint32_t &permissions);
int SetFilePermissions(const std::string &fileName, uint32_t permissions);
int RenameFilePath(const std::string &oldFilePath, const std::string &newFilePath);
int OpenFile(const std::string &fileName, FileHandle &handle);
int CloseFile(FileHandle &handle);
int FileLock(const FileHandle &handle, bool isBlock); // be careful use block=true, may block process
int FileUnlock(FileHandle &handle);
} // namespace OS
} // namespace DistributedDB
#endif // PLATFORM_SPECIFIC_H

View File

@ -0,0 +1,80 @@
/*
* 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 KV_DB_REF_OBJECT_H
#define KV_DB_REF_OBJECT_H
#include <atomic>
#include <string>
#include <mutex>
#include <functional>
#include <condition_variable>
#include "macro_utils.h"
namespace DistributedDB {
class RefObject {
public:
class AutoLock final {
public:
AutoLock(const RefObject *obj, bool unlocked = true);
~AutoLock();
void Lock();
void Unlock();
private:
DISABLE_COPY_ASSIGN_MOVE(AutoLock);
const RefObject *refObj_;
bool IsLocked_;
};
RefObject();
/* Invoked before this object deleted. */
void OnLastRef(const std::function<void(void)> &callback) const;
/* Invoked when kill object, with lock held. */
void OnKill(const std::function<void(void)> &callback);
bool IsKilled() const;
void KillObj();
void LockObj() const;
void UnlockObj() const;
bool WaitLockedUntil(std::condition_variable &cv,
const std::function<bool(void)> &condition, int seconds = 0);
/* Work as static members, avoid to 'delete this' */
static void IncObjRef(const RefObject *obj);
static void DecObjRef(const RefObject *obj);
static void KillAndDecObjRef(RefObject *obj);
protected:
virtual ~RefObject();
virtual std::string GetObjectTag() const;
private:
constexpr static const char * const classTag = "Class-RefObject";
DISABLE_COPY_ASSIGN_MOVE(RefObject);
/* A const object can also be locked/unlocked/ref()/unref() */
mutable std::atomic<int> refCount_;
mutable std::mutex objLock_;
std::atomic<bool> isKilled_;
mutable std::function<void(void)> onLast_;
std::function<void(void)> onKill_;
};
} // namespace DistributedDB
#endif // KV_DB_REF_OBJECT_H

View File

@ -0,0 +1,151 @@
/*
* 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 RELATIONAL_SCHEMA_OBJECT_H
#define RELATIONAL_SCHEMA_OBJECT_H
#ifdef RELATIONAL_STORE
#include <map>
#include "data_value.h"
#include "json_object.h"
#include "parcel.h"
#include "ischema.h"
namespace DistributedDB {
using CompositeFields = std::vector<FieldName>;
class FieldInfo {
public:
const std::string &GetFieldName() const;
void SetFieldName(const std::string &fileName);
const std::string &GetDataType() const;
void SetDataType(const std::string &dataType);
bool IsNotNull() const;
void SetNotNull(bool isNotNull);
// Use string type to save the default value define in the create table sql.
// No need to use the real value because sqlite will complete them.
bool HasDefaultValue() const;
const std::string &GetDefaultValue() const;
void SetDefaultValue(const std::string &value);
// convert to StorageType according "Determination Of Column Affinity"
StorageType GetStorageType() const;
void SetStorageType(StorageType storageType);
int GetColumnId() const;
void SetColumnId(int cid);
// return field define string like ("fieldName": "MY INT(21), NOT NULL, DEFAULT 123")
std::string ToAttributeString() const;
int CompareWithField(const FieldInfo &inField) const;
private:
std::string fieldName_;
std::string dataType_; // Type may be null
StorageType storageType_ = StorageType::STORAGE_TYPE_NONE;
bool isNotNull_ = false;
bool hasDefaultValue_ = false;
std::string defaultValue_;
int64_t cid_ = -1;
};
class TableInfo {
public:
const std::string &GetTableName() const;
bool GetAutoIncrement() const;
const std::string &GetCreateTableSql() const;
const std::map<FieldName, FieldInfo> &GetFields() const; // <colName, colAttr>
const std::map<std::string, CompositeFields> &GetIndexDefine() const;
const FieldName &GetPrimaryKey() const;
void SetTableName(const std::string &tableName);
void SetAutoIncrement(bool autoInc);
void SetCreateTableSql(std::string sql); // set 'autoInc_' flag when set sql
void AddField(const FieldInfo &field);
void AddIndexDefine(const std::string &indexName, const CompositeFields &indexDefine);
void SetPrimaryKey(const FieldName &fieldName); // not support composite index now
std::string ToTableInfoString() const;
int CompareWithTable(const TableInfo &inTableInfo) const;
std::map<FieldPath, SchemaAttribute> GetSchemaDefine() const;
std::string GetFieldName(uint32_t cid) const; // cid begin with 0
const std::vector<FieldInfo> &GetFieldInfos() const; // Sort by cid
bool IsValid() const;
private:
void AddFieldDefineString(std::string &attrStr) const;
void AddIndexDefineString(std::string &attrStr) const;
int CompareWithTableFields(const std::map<std::string, FieldInfo> &inTableFields) const;
int CompareWithTableIndex(const std::map<std::string, CompositeFields> &inTableIndex) const;
std::string tableName_;
bool autoInc_ = false; // only 'INTEGER PRIMARY KEY' could be defined as 'AUTOINCREMENT'
std::string sql_;
std::map<std::string, FieldInfo> fields_;
FieldName primaryKey_;
std::map<std::string, CompositeFields> indexDefines_;
mutable std::vector<FieldInfo> fieldInfos_;
};
class RelationalSchemaObject : public ISchema {
public:
RelationalSchemaObject() = default;
~RelationalSchemaObject() override = default;
bool IsSchemaValid() const override;
SchemaType GetSchemaType() const override;
std::string ToSchemaString() const override;
// Should be called on an invalid SchemaObject, create new SchemaObject if need to reparse
int ParseFromSchemaString(const std::string &inSchemaString) override;
void AddRelationalTable(const TableInfo& tb);
void RemoveRelationalTable(const std::string &tableName);
const std::map<std::string, TableInfo> &GetTables() const;
std::vector<std::string> GetTableNames() const;
TableInfo GetTable(const std::string& tableName) const;
private:
int CompareAgainstSchemaObject(const std::string &inSchemaString, std::map<std::string, int> &cmpRst) const;
int CompareAgainstSchemaObject(const RelationalSchemaObject &inSchemaObject,
std::map<std::string, int> &cmpRst) const;
int ParseRelationalSchema(const JsonObject &inJsonObject);
int ParseCheckSchemaType(const JsonObject &inJsonObject);
int ParseCheckSchemaVersion(const JsonObject &inJsonObject);
int ParseCheckSchemaTableDefine(const JsonObject &inJsonObject);
int ParseCheckTableInfo(const JsonObject &inJsonObject);
int ParseCheckTableName(const JsonObject &inJsonObject, TableInfo &resultTable);
int ParseCheckTableDefine(const JsonObject &inJsonObject, TableInfo &resultTable);
int ParseCheckTableFieldInfo(const JsonObject &inJsonObject, const FieldPath &path, FieldInfo &table);
int ParseCheckTableAutoInc(const JsonObject &inJsonObject, TableInfo &resultTable);
int ParseCheckTableIndex(const JsonObject &inJsonObject, TableInfo &resultTable);
int ParseCheckTablePrimaryKey(const JsonObject &inJsonObject, TableInfo &resultTable);
void GenerateSchemaString();
bool isValid_ = false; // set to true after parse success from string or add at least one relational table
SchemaType schemaType_ = SchemaType::RELATIVE; // Default RELATIVE
std::string schemaString_; // The minified and valid schemaString
std::string schemaVersion_;
std::map<std::string, TableInfo> tables_;
};
} // namespace DistributedDB
#endif // RELATIONAL_STORE
#endif // RELATIONAL_SCHEMA_OBJECT_H

View File

@ -0,0 +1,41 @@
/*
* 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 RES_FINALIZER_H
#define RES_FINALIZER_H
#include <functional>
#include "macro_utils.h"
namespace DistributedDB {
// RAII style resource finalizer for using in functions where the resource should be finalized before each return after
// the resource had been allocated. Just create an instance as function local stack variable and provide finalizer
// function after where the resource allocated. Suggest using this RAII style instead of using goto statement.
class ResFinalizer {
public:
explicit ResFinalizer(const std::function<void(void)> &inFinalizer) : finalizer_(inFinalizer) {}
~ResFinalizer()
{
if (finalizer_) {
finalizer_();
}
}
DISABLE_COPY_ASSIGN_MOVE(ResFinalizer);
private:
std::function<void(void)> finalizer_;
};
} // namespace DistributedDB
#endif // RES_FINALIZER_H

View File

@ -0,0 +1,137 @@
/*
* 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 RUNTIME_CONTEXT_H
#define RUNTIME_CONTEXT_H
#include <cstdint>
#include <string>
#include <functional>
#include "auto_launch.h"
#include "auto_launch_export.h"
#include "icommunicator_aggregator.h"
#include "iprocess_system_api_adapter.h"
#include "kv_store_observer.h"
#include "kvdb_properties.h"
#include "macro_utils.h"
#include "notification_chain.h"
#include "types_export.h"
namespace DistributedDB {
using TimerId = uint64_t;
using TimerAction = std::function<int(TimerId timerId)>;
using TimerFinalizer = std::function<void(void)>;
using TaskAction = std::function<void(void)>;
using TimeChangedAction = std::function<void(void *)>;
using LockStatusNotifier = std::function<void(void *isLocked)>;
using UserChangedAction = std::function<void(void *)>;
class RuntimeContext {
public:
DISABLE_COPY_ASSIGN_MOVE(RuntimeContext);
// Global setting interfaces.
virtual void SetProcessLabel(const std::string &label) = 0;
virtual std::string GetProcessLabel() const = 0;
// If the pre adapter is not nullptr, set new adapter will release the pre adapter,
// must be called after SetCommunicatorAggregator
virtual int SetCommunicatorAdapter(IAdapter *adapter) = 0;
virtual int GetCommunicatorAggregator(ICommunicatorAggregator *&outAggregator) = 0;
virtual void SetCommunicatorAggregator(ICommunicatorAggregator *inAggregator) = 0;
virtual int GetLocalIdentity(std::string &outTarget) = 0;
// Timer interfaces.
virtual int SetTimer(int milliSeconds, const TimerAction &action,
const TimerFinalizer &finalizer, TimerId &timerId) = 0;
virtual int ModifyTimer(TimerId timerId, int milliSeconds) = 0;
virtual void RemoveTimer(TimerId timerId, bool wait = false) = 0;
// Task interfaces.
virtual int ScheduleTask(const TaskAction &task) = 0;
virtual int ScheduleQueuedTask(const std::string &queueTag,
const TaskAction &task) = 0;
// Shrink as much memory as possible.
virtual void ShrinkMemory(const std::string &description) = 0;
// Register a time changed lister, it will be callback when local time changed.
virtual NotificationChain::Listener *RegisterTimeChangedLister(const TimeChangedAction &action, int &errCode) = 0;
// Get the global context object(singleton), never return nullptr.
static RuntimeContext *GetInstance();
virtual int SetPermissionCheckCallback(const PermissionCheckCallback &callback) = 0;
virtual int SetPermissionCheckCallback(const PermissionCheckCallbackV2 &callback) = 0;
virtual int RunPermissionCheck(const std::string &userId, const std::string &appId, const std::string &storeId,
const std::string &deviceId, uint8_t flag) const = 0;
virtual int EnableKvStoreAutoLaunch(const KvDBProperties &properties, AutoLaunchNotifier notifier,
const AutoLaunchOption &option) = 0;
virtual int DisableKvStoreAutoLaunch(const std::string &normalIdentifier, const std::string &dualTupleIdentifier,
const std::string &userId) = 0;
virtual void GetAutoLaunchSyncDevices(const std::string &identifier, std::vector<std::string> &devices) const = 0;
virtual void SetAutoLaunchRequestCallback(const AutoLaunchRequestCallback &callback, DBType type) = 0;
virtual NotificationChain::Listener *RegisterLockStatusLister(const LockStatusNotifier &action, int &errCode) = 0;
virtual bool IsAccessControlled() const = 0;
virtual int SetSecurityOption(const std::string &filePath, const SecurityOption &option) const = 0;
virtual int GetSecurityOption(const std::string &filePath, SecurityOption &option) const = 0;
virtual bool CheckDeviceSecurityAbility(const std::string &devId, const SecurityOption &option) const = 0;
virtual int SetProcessSystemApiAdapter(const std::shared_ptr<IProcessSystemApiAdapter> &adapter) = 0;
virtual bool IsProcessSystemApiAdapterValid() const = 0;
virtual bool IsCommunicatorAggregatorValid() const = 0;
// Notify TIME_CHANGE_EVENT.
virtual void NotifyTimestampChanged(TimeOffset offset) const = 0;
virtual void SetStoreStatusNotifier(const StoreStatusNotifier &notifier) = 0;
virtual void NotifyDatabaseStatusChange(const std::string &userId, const std::string &appId,
const std::string &storeId, const std::string &deviceId, bool onlineStatus) = 0;
virtual int SetSyncActivationCheckCallback(const SyncActivationCheckCallback &callback) = 0;
virtual bool IsSyncerNeedActive(std::string &userId, std::string &appId, std::string &storeId) const = 0;
virtual NotificationChain::Listener *RegisterUserChangedListerner(const UserChangedAction &action,
EventType event) = 0;
virtual int NotifyUserChanged() const = 0;
// Generate global sessionId in current process
virtual uint32_t GenerateSessionId() = 0;
virtual void DumpCommonInfo(int fd) = 0;
protected:
RuntimeContext() = default;
virtual ~RuntimeContext() {}
};
} // namespace DistributedDB
#endif // RUNTIME_CONTEXT_H

View File

@ -0,0 +1,68 @@
/*
* 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 SCHEMA_CONSTANT_H
#define SCHEMA_CONSTANT_H
#include <string>
// This header is supposed to be included only in source files. Do not include it in any header files.
namespace DistributedDB {
class SchemaConstant final {
public:
static const std::string KEYWORD_SCHEMA_VERSION;
static const std::string KEYWORD_SCHEMA_MODE;
static const std::string KEYWORD_SCHEMA_DEFINE;
static const std::string KEYWORD_SCHEMA_INDEXES;
static const std::string KEYWORD_SCHEMA_SKIPSIZE;
static const std::string KEYWORD_SCHEMA_TYPE;
static const std::string KEYWORD_SCHEMA_TABLE;
static const std::string KEYWORD_INDEX; // For FlatBuffer-Schema
static const std::string KEYWORD_MODE_STRICT;
static const std::string KEYWORD_MODE_COMPATIBLE;
static const std::string KEYWORD_TYPE_BOOL;
static const std::string KEYWORD_TYPE_INTEGER;
static const std::string KEYWORD_TYPE_LONG;
static const std::string KEYWORD_TYPE_DOUBLE;
static const std::string KEYWORD_TYPE_STRING;
static const std::string KEYWORD_ATTR_NOT_NULL;
static const std::string KEYWORD_ATTR_DEFAULT;
static const std::string KEYWORD_ATTR_VALUE_NULL;
static const std::string KEYWORD_ATTR_VALUE_TRUE;
static const std::string KEYWORD_ATTR_VALUE_FALSE;
static const std::string KEYWORD_TYPE_RELATIVE;
static const std::string SCHEMA_SUPPORT_VERSION;
static const std::string SCHEMA_SUPPORT_VERSION_V2;
static const uint32_t SCHEMA_META_FEILD_COUNT_MAX;
static const uint32_t SCHEMA_META_FEILD_COUNT_MIN;
static const uint32_t SCHEMA_FEILD_NAME_LENGTH_MAX;
static const uint32_t SCHEMA_FEILD_NAME_LENGTH_MIN;
static const uint32_t SCHEMA_FEILD_NAME_COUNT_MAX;
static const uint32_t SCHEMA_FEILD_NAME_COUNT_MIN;
static const uint32_t SCHEMA_FEILD_PATH_DEPTH_MAX;
static const uint32_t SCHEMA_INDEX_COUNT_MAX;
static const uint32_t SCHEMA_STRING_SIZE_LIMIT;
static const uint32_t SCHEMA_DEFAULT_STRING_SIZE_LIMIT;
static const uint32_t SCHEMA_SKIPSIZE_MAX;
static const uint32_t SECURE_BYTE_ALIGN;
};
} // namespace DistributedDB
#endif // SCHEMA_CONSTANT_H

View File

@ -0,0 +1,64 @@
/*
* 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 SCHEMA_NEGOTIATE_H
#define SCHEMA_NEGOTIATE_H
#include "schema_object.h"
#include "relational_schema_object.h"
namespace DistributedDB {
struct SyncOpinion {
bool permitSync = false;
bool requirePeerConvert = false;
bool checkOnReceive = false;
};
struct SyncStrategy {
bool permitSync = false;
bool convertOnSend = false;
bool convertOnReceive = false;
bool checkOnReceive = false;
};
using RelationalSyncOpinion = std::map<std::string, SyncOpinion>;
using RelationalSyncStrategy = std::map<std::string, SyncStrategy>;
class SchemaNegotiate {
public:
// The remoteSchemaType may beyond local SchemaType definition
static SyncOpinion MakeLocalSyncOpinion(const SchemaObject &localSchema, const std::string &remoteSchema,
uint8_t remoteSchemaType);
// The remoteOpinion.checkOnReceive is ignored
static SyncStrategy ConcludeSyncStrategy(const SyncOpinion &localOpinion, const SyncOpinion &remoteOpinion);
static RelationalSyncOpinion MakeLocalSyncOpinion(const RelationalSchemaObject &localSchema,
const std::string &remoteSchema, uint8_t remoteSchemaType);
// The remoteOpinion.checkOnReceive is ignored
static RelationalSyncStrategy ConcludeSyncStrategy(const RelationalSyncOpinion &localOpinion,
const RelationalSyncOpinion &remoteOpinion);
static uint32_t CalculateParcelLen(const RelationalSyncOpinion &opinions);
static int SerializeData(const RelationalSyncOpinion &opinions, Parcel &parcel);
static int DeserializeData(Parcel &parcel, RelationalSyncOpinion &opinion);
private:
SchemaNegotiate() = default;
~SchemaNegotiate() = default;
};
}
#endif // SCHEMA_NEGOTIATE_H

View File

@ -0,0 +1,210 @@
/*
* 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 SCHEMA_OBJECT_H
#define SCHEMA_OBJECT_H
#include <set>
#include <map>
#ifndef OMIT_FLATBUFFER
#include <flatbuffers/idl.h>
#endif // OMIT_FLATBUFFER
#include "db_types.h"
#include "macro_utils.h"
#include "relational_schema_object.h"
#include "ischema.h"
#include "value_object.h"
namespace DistributedDB {
using IndexName = FieldPath;
using IndexFieldInfo = std::pair<FieldPath, FieldType>;
using IndexInfo = std::vector<IndexFieldInfo>;
template<typename T> using PairConstPointer = std::pair<const T *, const T *>;
struct IndexDifference {
std::map<IndexName, IndexInfo> change;
std::map<IndexName, IndexInfo> increase;
std::set<IndexName> decrease;
};
class SchemaObject : public ISchema {
public:
static std::string GetExtractFuncName(SchemaType inSchemaType);
static std::string GenerateExtractSQL(SchemaType inSchemaType, const FieldPath &inFieldpath, FieldType inFieldType,
uint32_t skipSize, const std::string &accessStr = "");
// Support default constructor, copy constructor and copy assignment
SchemaObject();
~SchemaObject() = default;
SchemaObject(const SchemaObject &);
SchemaObject& operator=(const SchemaObject &);
#ifdef RELATIONAL_STORE
explicit SchemaObject(const TableInfo &tableInfo); // The construct func can only be used for query.
#endif // RELATIONAL_STORE
// Move constructor and move assignment is not need currently
SchemaObject(SchemaObject &&) = delete;
SchemaObject& operator=(SchemaObject &&) = delete;
// Should be called on an invalid SchemaObject, create new SchemaObject if need to reparse
int ParseFromSchemaString(const std::string &inSchemaString) override;
bool IsSchemaValid() const override;
SchemaType GetSchemaType() const override;
// For Json-Schema : Unnecessary spacing will be removed and fieldname resorted by lexicographical order
// For FlatBuffer-Schema : Original binary schema(Base64 decoded if need)
std::string ToSchemaString() const override;
uint32_t GetSkipSize() const;
std::map<IndexName, IndexInfo> GetIndexInfo() const;
bool IsIndexExist(const IndexName &indexName) const;
// Return E_OK if queryale. outType will be set if path exist no matter binary or not
int CheckQueryableAndGetFieldType(const FieldPath &inPath, FieldType &outType) const;
// Attention: it doesn't return E_OK. instead:
// E_JSON_PARSE_FAIL : the inSchemaString is not an valid json
// E_SCHEMA_PARSE_FAIL : the inSchemaString is not an valid schema
// E_SCHEMA_EQUAL_EXACTLY : the inSchema is exactly equal to this SchemaObject
// E_SCHEMA_UNEQUAL_COMPATIBLE : the inSchema is not equal to but only index differ with this SchemaObject
// E_SCHEMA_UNEQUAL_COMPATIBLE_UPGRADE : the inSchema is not equal to but can upgrade from this SchemaObject
// E_SCHEMA_UNEQUAL_INCOMPATIBLE : the inSchema is not equal to and can not upgrade from this SchemaObject
int CompareAgainstSchemaString(const std::string &inSchemaString) const;
int CompareAgainstSchemaString(const std::string &inSchemaString, IndexDifference &indexDiffer) const;
int CompareAgainstSchemaObject(const SchemaObject &inSchemaObject) const;
int CompareAgainstSchemaObject(const SchemaObject &inSchemaObject, IndexDifference &indexDiffer) const;
// Attention: it doesn't return E_OK. instead:
// E_VALUE_MATCH : Value match schema(no matter strict or compatible mode) without any change
// E_VALUE_MATCH_AMENDED : Value match schema(no matter strict or compatible mode) with some amendment
// E_VALUE_MISMATCH_FEILD_COUNT : Value contain more field then schema when in strict mode
// E_VALUE_MISMATCH_FEILD_TYPE : Type of some fields of value mismatch schema
// E_VALUE_MISMATCH_CONSTRAINT : Some fields of value violate the NotNull constraint against schema
// E_VALUE_MISMATCH_OTHER_REASON : Value mismatch schema because of other reason unmentioned
int CheckValueAndAmendIfNeed(ValueSource sourceType, ValueObject &inValue) const;
// Currently only for flatBuffer-type schema and value.
// Accept the original entry-value, return E_OK or E_FLATBUFFER_VERIFY_FAIL.
int VerifyValue(ValueSource sourceType, const Value &inValue) const;
int VerifyValue(ValueSource sourceType, const RawValue &inValue) const;
// Accept the original value from database. The cache will not be expanded. Return E_OK if nothing error.
// The ExtractValue is with nice performance by carefully not use std-class to avoid memory allocation.
// But currently it can only deal with path with $. prefix and only one depth. However, meet current demand.
int ExtractValue(ValueSource sourceType, RawString inPath, const RawValue &inValue, TypeValue &outExtract,
std::vector<uint8_t> *cache) const;
private:
enum class SchemaMode {
STRICT,
COMPATIBLE,
};
using SchemaDefine = std::map<FieldPath, SchemaAttribute>;
// For Json-Schema : Parsing related methods.
int ParseJsonSchema(const JsonObject &inJsonObject);
int CheckMetaFieldCountAndType(const JsonObject &inJsonObject) const;
int ParseCheckSchemaVersionMode(const JsonObject &inJsonObject);
int ParseCheckSchemaDefine(const JsonObject &inJsonObject);
int CheckSchemaDefineItemDecideAttribute(const JsonObject &inJsonObject, const FieldPath &inPath, FieldType inType,
SchemaAttribute &outAttr) const;
int ParseCheckSchemaIndexes(const JsonObject &inJsonObject);
int ParseCheckSchemaSkipSize(const JsonObject &inJsonObject);
// For both Json-Schema and FlatBuffer-Schema.
int ParseCheckEachIndexFromStringArray(const std::vector<std::string> &inStrArray);
int CheckFieldPathIndexableThenSave(const std::vector<FieldPath> &inPathVec, IndexInfo &infoToSave);
// CompareAgainstSchemaObject related sub methods
int CompareSchemaVersionMode(const SchemaObject &newSchema) const;
int CompareSchemaSkipSize(const SchemaObject &newSchema) const;
int CompareSchemaDefine(const SchemaObject &newSchema) const;
int CompareSchemaDefineByDepth(const SchemaDefine &oldDefine, const SchemaDefine &newDefine) const;
int CompareSchemaAttribute(const SchemaAttribute &oldAttr, const SchemaAttribute &newAttr) const;
int CompareSchemaDefaultValue(const SchemaAttribute &oldAttr, const SchemaAttribute &newAttr) const;
int CompareSchemaIndexes(const SchemaObject &newSchema, IndexDifference &indexDiffer) const;
// CheckValueAndAmendIfNeed related sub methods
int CheckValue(const ValueObject &inValue, std::set<FieldPath> &lackingPaths) const;
int AmendValueIfNeed(ValueObject &inValue, const std::set<FieldPath> &lackingPaths, bool &amended) const;
// It is better using a class to represent flatBuffer-Schema related other than more private method(As well as for
// Json-Schema in the future refactor). Delegation is chosen other than inheritance for accessing SchemaObject.
// Choose inner-class other than friend-class to avoid forward declaration and using pointer.
class FlatBufferSchema {
public:
explicit FlatBufferSchema(SchemaObject &owner) : owner_(owner) {};
~FlatBufferSchema() = default;
DISABLE_COPY_ASSIGN_MOVE(FlatBufferSchema);
// Copy-Constructor can not define due to Const-Ref member. Code standard require copy assignment be deleted.
void CopyFrom(const FlatBufferSchema &other);
std::string GetDescription() const;
// Judge whether it's flatbuffer type schema, no matter whether it is Base64 encoded, provide a decoded one.
static bool IsFlatBufferSchema(const std::string &inOriginal, std::string &outDecoded);
// Accept a decoded and verified flatbuffer-schema, then parse its content
int ParseFlatBufferSchema(const std::string &inDecoded);
// Compare based on self.
// return E_SCHEMA_EQUAL_EXACTLY or E_SCHEMA_UNEQUAL_COMPATIBLE_UPGRADE or E_SCHEMA_UNEQUAL_INCOMPATIBLE
int CompareFlatBufferDefine(const FlatBufferSchema &other) const;
// Accept a no-skipsize(so byte-aligned) value, return E_OK or E_FLATBUFFER_VERIFY_FAIL.
int VerifyFlatBufferValue(const RawValue &inValue, bool tryNoSizePrefix) const;
// Accept a no-skipsize(so byte-aligned) value.
int ExtractFlatBufferValue(RawString inPath, const RawValue &inValue, TypeValue &outExtract,
bool tryNoSizePrefix) const;
private:
#ifndef OMIT_FLATBUFFER
using RawIndexInfos = std::map<std::string, std::string>; // First the fieldName, second the index-attr value.
const reflection::Schema *GetSchema() const;
int ParseCheckRootTableAttribute(const reflection::Object &rootTable);
int ParseCheckRootTableDefine(const reflection::Schema &schema, const reflection::Object &rootTable,
RawIndexInfos &indexCollect);
int ParseCheckFieldInfo(const reflection::Schema &schema, const reflection::Field &field,
const FieldPath &path, RawIndexInfos &indexCollect);
void CollectRawIndexInfos(const reflection::Field &field, RawIndexInfos &indexCollect) const;
int ParseCheckStructDefine(const reflection::Schema &schema, const reflection::Field &field,
const FieldPath &path);
int ParseCheckIndexes(const RawIndexInfos &indexCollect);
int CompareTableOrStructDefine(const PairConstPointer<reflection::Schema> &bothSchema,
const PairConstPointer<reflection::Object> &bothObject, bool isRoot, std::set<std::string> &compared) const;
int CompareStruct(const PairConstPointer<reflection::Schema> &bothSchema,
const PairConstPointer<reflection::Field> &bothField, std::set<std::string> &compared) const;
#endif
SchemaObject &owner_;
std::string description_;
};
bool isValid_ = false;
SchemaType schemaType_ = SchemaType::NONE; // Default NONE
FlatBufferSchema flatbufferSchema_;
std::string schemaString_; // The minified and valid schemaString
std::string schemaVersion_;
SchemaMode schemaMode_ = SchemaMode::STRICT; // Only for Json-Schema, Consider refactor into JsonSchema class
uint32_t schemaSkipSize_ = 0;
std::map<IndexName, IndexInfo> schemaIndexes_;
std::map<uint32_t, SchemaDefine> schemaDefine_; // SchemaDefine classified by the depth of fieldpath
};
} // namespace DistributedDB
#endif // SCHEMA_OBJECT_H

View File

@ -0,0 +1,77 @@
/*
* 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 SCHEMA_UTILS_H
#define SCHEMA_UTILS_H
#include "db_types.h"
#include "schema_object.h"
// This header is supposed to be included only in source files. Do not include it in any header files.
namespace DistributedDB {
class SchemaUtils {
public:
// Check if any invalid exist, parse it into SchemaAttribute if totally valid and return E_OK
// Number don't support format of scientific notation. SchemaAttribute.isIndexable always set true.
// Prefix and postfix spaces or tabs is allowed.
// Customer FieldType will be accepted if useAffinity is true.
static int ParseAndCheckSchemaAttribute(const std::string &inAttrString, SchemaAttribute &outAttr,
bool useAffinity = false);
// Check if any invalid exist, parse it into FieldPath if totally valid and return E_OK
// Each fieldName of the fieldPath will be check valid as well. Path depth will be check.
// Prefix and postfix spaces or tabs is allowed. Prefix $. can be not exist.
// Parameter permitPrefix means whether $. prefix is permited. If not, return E_SCHEMA_PARSE_FAIL.
static int ParseAndCheckFieldPath(const std::string &inPathString, FieldPath &outPath, bool permitPrefix = true);
// Return E_OK if it is totally valid. Prefix and postfix spaces or tabs is not allowed.
static int CheckFieldName(const FieldName &inName);
// Remove prefix and postfix spaces or tabs
static std::string Strip(const std::string &inString);
// Strip the namespace from the full-name, this method mainly for flatbuffer-type schema
static std::string StripNameSpace(const std::string &inFullName);
static std::string FieldTypeString(FieldType inType);
static std::string SchemaTypeString(SchemaType inType);
// Restore to string representation of fieldPath with $. prefix
static std::string FieldPathString(const FieldPath &inPath);
SchemaUtils() = delete;
~SchemaUtils() = delete;
private:
static int SplitSchemaAttribute(const std::string &inAttrString, std::vector<std::string> &outAttrString);
static int MakeTrans(const std::string &oriContent, size_t &pos);
static int ParseSchemaAttribute(std::vector<std::string> &attrContext, SchemaAttribute &outAttr, bool useAffinity);
static int TransformDefaultValue(std::string &defaultContent, SchemaAttribute &outAttr);
static int TransToDouble(const std::string &defaultContent, SchemaAttribute &outAttr);
static int TransToInteger(const std::string &defaultContent, SchemaAttribute &outAttr);
static int TransToLong(const std::string &defaultContent, SchemaAttribute &outAttr);
static int TransToString(const std::string &defaultContent, SchemaAttribute &outAttr);
static int TransToBool(const std::string &defaultContent, SchemaAttribute &outAttr);
};
} // namespace DistributedDB
#endif // SCHEMA_UTILS_H

View File

@ -0,0 +1,48 @@
/*
* 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 SEMAPHORE_UTILS_H
#define SEMAPHORE_UTILS_H
#include <cstdio>
#include <cstdlib>
#include <mutex>
#include <condition_variable>
#include "macro_utils.h"
namespace DistributedDB {
class SemaphoreUtils {
public:
explicit SemaphoreUtils(int count);
~SemaphoreUtils();
// Delete the copy and assign constructors
DISABLE_COPY_ASSIGN_MOVE(SemaphoreUtils);
bool WaitSemaphore(int waitSecond);
void WaitSemaphore();
void SendSemaphore();
private:
bool CompareCount() const;
std::mutex lockMutex_;
std::condition_variable cv_;
int count_;
};
}
#endif

View File

@ -0,0 +1,54 @@
/*
* 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 TASK_POOL_H
#define TASK_POOL_H
#include <string>
#include <functional>
#include "macro_utils.h"
namespace DistributedDB {
using Task = std::function<void(void)>;
class TaskPool {
public:
// Start the task pool.
virtual int Start() = 0;
// Stop the task pool.
virtual void Stop() = 0;
// Schedule a task, the task can be ran in any thread.
virtual int Schedule(const Task &task) = 0;
// Schedule tasks using FIFO policy(tasks with the same 'tag').
virtual int Schedule(const std::string &tag, const Task &task) = 0;
// Shrink memory associated with the given tag if possible.
virtual void ShrinkMemory(const std::string &tag) = 0;
// Create/Destroy a task pool.
static TaskPool *Create(int maxThreads, int minThreads, int &errCode);
static void Release(TaskPool *&taskPool);
protected:
TaskPool() = default;
virtual ~TaskPool() {}
DISABLE_COPY_ASSIGN_MOVE(TaskPool);
};
} // namespace DistributedDB
#endif // TASK_POOL_H

View File

@ -0,0 +1,58 @@
/*
* 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 USER_CHANGE_MONITOR_H
#define USER_CHANGE_MONITOR_H
#include <shared_mutex>
#include "platform_specific.h"
#include "macro_utils.h"
#include "notification_chain.h"
#include "runtime_context.h"
namespace DistributedDB {
class UserChangeMonitor final {
public:
UserChangeMonitor();
~UserChangeMonitor();
DISABLE_COPY_ASSIGN_MOVE(UserChangeMonitor);
// Start the UserChangeMonitor
int Start();
// Stop the UserChangeMonitor
void Stop();
// Register a user changed lister, it will be callback when user changed.
NotificationChain::Listener *RegisterUserChangedListerner(const UserChangedAction &action, EventType event,
int &errCode);
// Notify USER_CHANGE_EVENT.
void NotifyUserChanged() const;
static constexpr EventType USER_ACTIVE_EVENT = 3;
static constexpr EventType USER_NON_ACTIVE_EVENT = 4;
static constexpr EventType USER_ACTIVE_TO_NON_ACTIVE_EVENT = 5;
private:
// prepare notifier chain
int PrepareNotifierChain();
mutable std::shared_mutex userChangeMonitorLock_;
NotificationChain *userNotifier_;
bool isStarted_ = false;
};
} // namespace DistributedDB
#endif // USER_CHANGE_MONITOR_H

View File

@ -0,0 +1,88 @@
/*
* 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 VALUE_HASH_CALC_H
#define VALUE_HASH_CALC_H
#include <vector>
#include <openssl/sha.h>
#include "db_types.h"
#include "db_errno.h"
#include "log_print.h"
namespace DistributedDB {
class ValueHashCalc {
public:
ValueHashCalc() {};
~ValueHashCalc()
{
if (context_ != nullptr) {
delete context_;
context_ = nullptr;
}
}
int Initialize()
{
context_ = new (std::nothrow) SHA256_CTX;
if (context_ == nullptr) {
return -E_OUT_OF_MEMORY;
}
int errCode = SHA256_Init(context_);
if (errCode == 0) {
LOGE("sha init failed:%d", errCode);
return -E_CALC_HASH;
}
return E_OK;
}
int Update(const std::vector<uint8_t> &value)
{
if (context_ == nullptr) {
return -E_CALC_HASH;
}
int errCode = SHA256_Update(context_, value.data(), value.size());
if (errCode == 0) {
LOGE("sha update failed:%d", errCode);
return -E_CALC_HASH;
}
return E_OK;
}
int GetResult(std::vector<uint8_t> &value)
{
if (context_ == nullptr) {
return -E_CALC_HASH;
}
value.resize(SHA256_DIGEST_LENGTH);
int errCode = SHA256_Final(value.data(), context_);
if (errCode == 0) {
LOGE("sha get result failed:%d", errCode);
return -E_CALC_HASH;
}
return E_OK;
}
private:
SHA256_CTX *context_ = nullptr;
};
}
#endif // VALUE_HASH_CALC_H

View File

@ -0,0 +1,75 @@
/*
* 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 VALUE_OBJECT_H
#define VALUE_OBJECT_H
#include "json_object.h"
namespace DistributedDB {
// ValueObject is the abstraction of value of KvEntry, a value is not always an json in different solutions.
// Thus, ValueObject can't just inherit JsonObject, although their methods are nearly the same.
class ValueObject {
public:
// Support default constructor, copy constructor and copy assignment
ValueObject() = default;
~ValueObject() = default;
ValueObject(const ValueObject &);
ValueObject& operator=(const ValueObject &);
// Move constructor and move assignment is not need currently
ValueObject(ValueObject &&) = delete;
ValueObject& operator=(ValueObject &&) = delete;
// Should be called on an invalid ValueObject, create new ValueObject if need to reparse
int Parse(const std::string &inString);
int Parse(const std::vector<uint8_t> &inData); // Whether ends with '\0' in vector is OK
// The end refer to the byte after the last valid byte
int Parse(const uint8_t *dataBegin, const uint8_t *dataEnd, uint32_t offset = 0);
bool IsValid() const;
// Unnecessary spacing will be removed and fieldname resorted by lexicographical order
std::string ToString() const;
void WriteIntoVector(std::vector<uint8_t> &outData) const; // An vector version ToString
bool IsFieldPathExist(const FieldPath &inPath) const;
int GetFieldTypeByFieldPath(const FieldPath &inPath, FieldType &outType) const;
int GetFieldValueByFieldPath(const FieldPath &inPath, FieldValue &outValue) const;
// An empty fieldpath indicate the root, the outSubPath should be empty before call, we will not empty it at first.
// If inPath is of multiple path, then outSubPath is combination of result of each inPath.
int GetSubFieldPath(const FieldPath &inPath, std::set<FieldPath> &outSubPath) const;
int GetSubFieldPath(const std::set<FieldPath> &inPath, std::set<FieldPath> &outSubPath) const;
int GetSubFieldPathAndType(const FieldPath &inPath, std::map<FieldPath, FieldType> &outSubPathType) const;
int GetSubFieldPathAndType(const std::set<FieldPath> &inPath, std::map<FieldPath, FieldType> &outSubPathType) const;
// Can be called no matter ValueObject valid or not. Invalid turn into valid after successful call. An empty inPath
// is not allowed. LEAF_FIELD_ARRAY and INTERNAL_FIELD_OBJECT is not supported. infinite double is not support.
// inValue is ignored for LEAF_FIELD_NULL. If inPath already exist or nearest path ends with type not object,
// returns not E_OK. Otherwise insert field as well as filling up intermediate field, then returns E_OK;
int InsertField(const FieldPath &inPath, FieldType inType, const FieldValue &inValue);
// Should be called on an valid ValueObject. Never turn into invalid after call. An empty inPath is not allowed.
// If inPath not exist, returns not E_OK. Otherwise delete field from its parent returns E_OK;
int DeleteField(const FieldPath &inPath);
private:
bool isValid_ = false;
JsonObject value_;
std::vector<uint8_t> dataBeforeOffset_;
};
} // namespace DistributedDB
#endif // VALUE_OBJECT_H

View File

@ -0,0 +1,72 @@
/*
* 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 VERSION_H
#define VERSION_H
#include <string>
#include <cstdint>
namespace DistributedDB {
// Version Regulation:
// Module version is always equal to the max version of its submodule.
// If a module or submodule upgrade to higher version, DO NOT simply increase current version by 1.
// First: you have to preserve current version by renaming it as a historical version.
// Second: Update the current version to the version to be release.
// Finally: Update its parent module's version if exist.
// Why we update the current version to the version to be release? For example, if module A has submodule B and C,
// if now version of B is 105, and C is 101, thus version of A is 105; if now release version is 106 and we upgrade
// submodule C, if we simply change version of C to 102 then version of A is still 105, but if we change version of C
// to 106 then version of A is now 106, so we can know that something had changed for module A.
const std::string SOFTWARE_VERSION_STRING = "1.1.5"; // DistributedDB current version string.
constexpr uint32_t SOFTWARE_VERSION_BASE = 100; // Software version base value, do not change it
constexpr uint32_t SOFTWARE_VERSION_RELEASE_1_0 = SOFTWARE_VERSION_BASE + 1; // 1 for first released version
constexpr uint32_t SOFTWARE_VERSION_RELEASE_2_0 = SOFTWARE_VERSION_BASE + 2; // 2 for second released version
constexpr uint32_t SOFTWARE_VERSION_RELEASE_3_0 = SOFTWARE_VERSION_BASE + 3; // 3 for third released version
constexpr uint32_t SOFTWARE_VERSION_RELEASE_4_0 = SOFTWARE_VERSION_BASE + 4; // 4 for fourth released version
constexpr uint32_t SOFTWARE_VERSION_RELEASE_5_0 = SOFTWARE_VERSION_BASE + 5; // 5 for fifth released version
constexpr uint32_t SOFTWARE_VERSION_RELEASE_6_0 = SOFTWARE_VERSION_BASE + 6; // 6 for sixth released version
constexpr uint32_t SOFTWARE_VERSION_EARLIEST = SOFTWARE_VERSION_RELEASE_1_0;
#ifdef RELATIONAL_STORE
constexpr uint32_t SOFTWARE_VERSION_CURRENT = SOFTWARE_VERSION_RELEASE_6_0;
#else
constexpr uint32_t SOFTWARE_VERSION_CURRENT = SOFTWARE_VERSION_RELEASE_5_0;
#endif
constexpr int VERSION_INVALID = INT32_MAX;
// Storage Related Version
// LocalNaturalStore Related Version
constexpr int LOCAL_STORE_VERSION_CURRENT = SOFTWARE_VERSION_RELEASE_1_0;
// SingleVerNaturalStore Related Version
constexpr int SINGLE_VER_STORE_VERSION_V1 = SOFTWARE_VERSION_RELEASE_1_0;
constexpr int SINGLE_VER_STORE_VERSION_V2 = SOFTWARE_VERSION_RELEASE_2_0;
constexpr int SINGLE_VER_STORE_VERSION_CURRENT = SOFTWARE_VERSION_RELEASE_3_0;
// MultiVerNaturalStore Related Version
constexpr uint32_t VERSION_FILE_VERSION_CURRENT = 1;
constexpr uint32_t MULTI_VER_STORE_VERSION_CURRENT = SOFTWARE_VERSION_RELEASE_1_0;
constexpr int MULTI_VER_COMMIT_STORAGE_VERSION_CURRENT = SOFTWARE_VERSION_RELEASE_1_0;
constexpr int MULTI_VER_DATA_STORAGE_VERSION_CURRENT = SOFTWARE_VERSION_RELEASE_1_0;
constexpr int MULTI_VER_METADATA_STORAGE_VERSION_CURRENT = SOFTWARE_VERSION_RELEASE_1_0;
constexpr int MULTI_VER_VALUESLICE_STORAGE_VERSION_CURRENT = SOFTWARE_VERSION_RELEASE_1_0;
// Syncer Related Version
constexpr int TIME_SYNC_VERSION_V1 = SOFTWARE_VERSION_RELEASE_1_0; // time sync proctol added in version 101.
constexpr int ABILITY_SYNC_VERSION_V1 = SOFTWARE_VERSION_RELEASE_2_0; // Ability sync proctol added in version 102.
constexpr uint32_t SINGLE_VER_SYNC_PROCTOL_V1 = SOFTWARE_VERSION_RELEASE_1_0; // The 1st version num
constexpr uint32_t SINGLE_VER_SYNC_PROCTOL_V2 = SOFTWARE_VERSION_RELEASE_2_0; // The 2nd version num
constexpr uint32_t SINGLE_VER_SYNC_PROCTOL_V3 = SOFTWARE_VERSION_RELEASE_3_0; // The third version num
} // namespace DistributedDB
#endif // VERSION_H

View File

@ -0,0 +1,37 @@
/*
* 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 ZLIB_COMPRESSION_H
#define ZLIB_COMPRESSION_H
#ifndef OMIT_ZLIB
#include <vector>
#include "data_compression.h"
namespace DistributedDB {
class ZlibCompression final : public DataCompression {
public:
ZlibCompression();
~ZlibCompression() = default;
int Compress(const std::vector<uint8_t> &srcData, std::vector<uint8_t> &destData) const override;
int Uncompress(const std::vector<uint8_t> &srcData, std::vector<uint8_t> &destData, uint32_t destLen) const
override;
protected:
ZlibCompression(const ZlibCompression& compression) = delete;
ZlibCompression& operator= (const ZlibCompression& compression) = delete;
};
} // namespace DistributedDB
#endif // OMIT_ZLIB
#endif // ZLIB_COMPRESSION_H

File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More