mirror of
https://gitee.com/openharmony/distributeddatamgr_datamgr_service
synced 2024-11-23 06:50:35 +00:00
update OpenHarmony 2.0 Canary
This commit is contained in:
parent
20ae51a33f
commit
c283a7e148
15
.gitattributes
vendored
Normal file
15
.gitattributes
vendored
Normal file
@ -0,0 +1,15 @@
|
||||
*.tgz filter=lfs diff=lfs merge=lfs -text
|
||||
*.trp filter=lfs diff=lfs merge=lfs -text
|
||||
*.apk filter=lfs diff=lfs merge=lfs -text
|
||||
*.jar filter=lfs diff=lfs merge=lfs -text
|
||||
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
||||
*.zip filter=lfs diff=lfs merge=lfs -text
|
||||
*.asm filter=lfs diff=lfs merge=lfs -text
|
||||
*.8svn filter=lfs diff=lfs merge=lfs -text
|
||||
*.9svn filter=lfs diff=lfs merge=lfs -text
|
||||
*.dylib filter=lfs diff=lfs merge=lfs -text
|
||||
*.exe filter=lfs diff=lfs merge=lfs -text
|
||||
*.a filter=lfs diff=lfs merge=lfs -text
|
||||
*.so filter=lfs diff=lfs merge=lfs -text
|
||||
*.bin filter=lfs diff=lfs merge=lfs -text
|
||||
*.dll filter=lfs diff=lfs merge=lfs -text
|
24
BUILD.gn
Executable file
24
BUILD.gn
Executable 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.
|
||||
import("//build/ohos.gni")
|
||||
|
||||
group("build_native_test") {
|
||||
testonly = true
|
||||
deps = [
|
||||
"frameworks/innerkitsimpl/distributeddatafwk/test:unittest",
|
||||
"services/distributeddataservice/adapter/test:unittest",
|
||||
"services/distributeddataservice/app/test:unittest",
|
||||
"services/distributeddataservice/libs/distributeddb/test:unittest",
|
||||
"services/distributeddataservice/test:moduletest",
|
||||
]
|
||||
}
|
177
LICENSE
Normal file
177
LICENSE
Normal file
@ -0,0 +1,177 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
36
README.en.md
36
README.en.md
@ -1,36 +0,0 @@
|
||||
# distributeddatamgr_datamgr
|
||||
|
||||
#### Description
|
||||
Distributed data manager that provides the capability to store data in the databases of different devices | 分布式数据管理服务模块,提供多设备数据分布式存储能力
|
||||
|
||||
#### Software Architecture
|
||||
Software architecture description
|
||||
|
||||
#### Installation
|
||||
|
||||
1. xxxx
|
||||
2. xxxx
|
||||
3. xxxx
|
||||
|
||||
#### Instructions
|
||||
|
||||
1. xxxx
|
||||
2. xxxx
|
||||
3. xxxx
|
||||
|
||||
#### Contribution
|
||||
|
||||
1. Fork the repository
|
||||
2. Create Feat_xxx branch
|
||||
3. Commit your code
|
||||
4. Create Pull Request
|
||||
|
||||
|
||||
#### Gitee Feature
|
||||
|
||||
1. You can use Readme\_XXX.md to support different languages, such as Readme\_en.md, Readme\_zh.md
|
||||
2. Gitee blog [blog.gitee.com](https://blog.gitee.com)
|
||||
3. Explore open source project [https://gitee.com/explore](https://gitee.com/explore)
|
||||
4. The most valuable open source project [GVP](https://gitee.com/gvp)
|
||||
5. The manual of Gitee [https://gitee.com/help](https://gitee.com/help)
|
||||
6. The most popular members [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/)
|
148
README.md
148
README.md
@ -1,37 +1,127 @@
|
||||
# distributeddatamgr_datamgr
|
||||
# distributeddatamgr\_distributeddatamgr<a name="EN-US_TOPIC_0000001124232845"></a>
|
||||
|
||||
#### 介绍
|
||||
Distributed data manager that provides the capability to store data in the databases of different devices | 分布式数据管理服务模块,提供多设备数据分布式存储能力
|
||||
- [Introduction](#section11660541593)
|
||||
- [Directory Structure](#section161941989596)
|
||||
- [Constraints](#section119744591305)
|
||||
- [Description](#section1312121216216)
|
||||
- [Repositories Involved](#section1371113476307)
|
||||
|
||||
#### 软件架构
|
||||
软件架构说明
|
||||
## Introduction<a name="section11660541593"></a>
|
||||
|
||||
Distributed Data Service \(DDS\) provides the capability to store data in the databases of different devices. DDS isolates data based on a triplet of the account, app, and database. DDS synchronizes data between trusted devices to provide users with consistent data access experience on different devices.
|
||||
|
||||
DDS manages data of OpenHarmony in a distributed manner. It consists of the following parts:
|
||||
|
||||
- **Service interfaces**
|
||||
|
||||
DDS provides APIs for other modules to create databases, access data, and subscribe to data. Supporting the KV data model and common data types, the APIs are highly compatible and easy to use, and can be released.
|
||||
|
||||
- **Service component**
|
||||
|
||||
The service component manages metadata, permissions, backup and restoration, and multiple users. It also initializes the storage and synchronization components and communication adaptation layer of the distributed database.
|
||||
|
||||
- **Storage component**
|
||||
|
||||
The storage component provides data access, data reduction, transactions, snapshots, data combination, and conflict resolution.
|
||||
|
||||
- **Synchronization component**
|
||||
|
||||
The synchronization component connects the storage and communication components. It maintains data consistency between online devices by synchronizing data generated on the local device to other devices and merging data received from other devices into the local device.
|
||||
|
||||
- **Communication adaptation layer**
|
||||
|
||||
The communication adaptation layer invokes interfaces of the public communication layer to create and connect to communication channels, receive device online and offline messages, maintain metadata of the connected and disconnected devices, send device online and offline messages to the synchronization component, synchronize the list of devices connected to and maintained by components, and invoke interfaces to encapsulate and send data to the connected devices.
|
||||
|
||||
|
||||
#### 安装教程
|
||||
You call APIs of DDS to create, access, and subscribe to distributed databases. The service interfaces store data to the storage component based on the capabilities provided by the service component. The storage component invokes the synchronization component to synchronize data. The synchronization component uses the communication adaptation layer to synchronize data to remote devices, which update the data in the storage component.
|
||||
|
||||
1. xxxx
|
||||
2. xxxx
|
||||
3. xxxx
|
||||
|
||||
#### 使用说明
|
||||
|
||||
1. xxxx
|
||||
2. xxxx
|
||||
3. xxxx
|
||||
|
||||
#### 参与贡献
|
||||
|
||||
1. Fork 本仓库
|
||||
2. 新建 Feat_xxx 分支
|
||||
3. 提交代码
|
||||
4. 新建 Pull Request
|
||||
**Figure 1** How DDS works<a name="fig371116145419"></a>
|
||||
|
||||
|
||||
#### 特技
|
||||
![](figures/en-us_image_0000001162536643.png)
|
||||
|
||||
## Directory Structure<a name="section161941989596"></a>
|
||||
|
||||
```
|
||||
/foundation/distributeddatamgr/distributeddatamgr
|
||||
├── interfaces # APIs
|
||||
│ └── innerkits # Native APIs
|
||||
├── services # Service code
|
||||
│ └── distributeddataservice # DDS implementation
|
||||
└── test # Test case resources
|
||||
```
|
||||
|
||||
## Constraints<a name="section119744591305"></a>
|
||||
|
||||
- To use all functions of DDS, you need to obtain the **ohos.permission.DISTRIBUTED\_DATASYNC** permission.
|
||||
- DDS supports the KV data model, but not foreign keys or triggers of the relational database.
|
||||
- DDS supports the following KV data model specifications:
|
||||
- For the device KV store, the maximum size of a key is 896 bytes, and that of a value is 4 MB.
|
||||
- For the single KV store, the maximum size of a key is 1 KB, and that of a value is 4 MB.
|
||||
- Each app can open a maximum of 16 databases simultaneously.
|
||||
|
||||
- DDS cannot completely replace the database in the service sandbox for storing data, because the storage types supported by them are not completely the same. You need to determine the data to be synchronized in distributed mode and store the data in DDS.
|
||||
- Currently, DDS does not allow customization of conflict resolution policies.
|
||||
- DDS supports a maximum of 1000 **KvStore** API calls per second, and 10,000 per minute. It supports a maximum of 50 **KvManager** API calls per second, and 500 per minute.
|
||||
|
||||
## Description<a name="section1312121216216"></a>
|
||||
|
||||
Some basic concepts related to the DDS are as follows:
|
||||
|
||||
- **KV data model**
|
||||
|
||||
KV is short for key-value. The KV database is a type of NoSQL database. Data in this type of database is organized, indexed, and stored in the form of key-value pairs.
|
||||
|
||||
The KV data model is suitable for storing service data that does not involve too many data or service relationships. It provides better read and write performance than the SQL database. The KV data model is widely used in distributed scenarios because it handles conflict more easily in database version compatibility and data synchronization. The distributed database is based on the KV data model and provides KV-based access interfaces.
|
||||
|
||||
- **Distributed database transactions**
|
||||
|
||||
Distributed database transactions include local transactions \(same as the transactions of traditional databases\) and synchronization transactions. Synchronization transactions refer to data synchronization between devices in the unit of local transaction. Synchronization of a local transaction modification either succeeds or fails on multiple devices.
|
||||
|
||||
- **Distributed database consistency**
|
||||
|
||||
In a distributed scenario where multiple devices are used in the same network, distributed database consistency means that data is consistent on these devices. This consistency can be classified into strong, weak, and eventual consistency.
|
||||
|
||||
- **Strong consistency**: After data is inserted, deleted, or updated on a device, other devices in the same network will obtain the updated data.
|
||||
- **Weak consistency**: After data is inserted, deleted, or updated on a device, other devices in the same network may or may not obtain the updated data. The time when all devices have the same data is uncertain.
|
||||
- **Eventual consistency**: After data is inserted, deleted, or updated on a device, other devices in the same network may not obtain the updated data immediately. However, data on all the devices will become consistent after some time.
|
||||
|
||||
Strong consistency has high requirements on distributed data management and may be used in distributed server scenarios. DDS supports only ultimate consistency because mobile devices are not always online and there is no center.
|
||||
|
||||
- **Distributed database synchronization**
|
||||
|
||||
After discovering and authenticating a device, the bottom-layer communication component notifies the DDS that the device goes online. After receiving the notification, DDS establishes an encrypted transmission channel to synchronize data between the two devices.
|
||||
|
||||
DDS provides both manual and automatic synchronization. In manual synchronization, you can specify the list of target devices and the synchronization mode \(PULL, PUSH, or PULL\_PUSH\). In automatic synchronization, the distributed database synchronizes data \(when devices go online or data is modified\), and you are unaware of the synchronization.
|
||||
|
||||
- **Single KV store**
|
||||
|
||||
Data is saved locally in the unit of a single KV entry. Only one entry is saved for each key. When users modify data locally, the corresponding KV entry is modified, regardless of whether the data has been synchronized. As for synchronization, the latest modification is synchronized to remote devices.
|
||||
|
||||
- **Device KV store**
|
||||
|
||||
The device KV store is based on the single KV store and adds device IDs before the keys of key-value pairs. This ensures that the data generated by each device is isolated from each other and is centrally managed by the system. With the device KV store, you can query data of a specified device, but cannot modify the data synchronized from remote devices.
|
||||
|
||||
- **Conflict resolution policy for the distributed database**
|
||||
|
||||
A data conflict occurs when multiple devices modify the same data and commit the modification to the database. In this case, the default conflict resolution policy is used, that is, the data modification committed later takes effect. Currently, the conflict resolution policy cannot be customized.
|
||||
|
||||
- **Schema-based database management and data query based on predicates**
|
||||
|
||||
When creating or opening a single KV store, you can specify a schema. The database detects the value format of key-value pairs based on the schema and checks the value structure. In addition, the database provides index creation and predicate-based query functions based on the fields in the values.
|
||||
|
||||
- **Distributed database backup capability**
|
||||
|
||||
DDS provides the database backup capability. By setting **backup** to **true**, you can trigger daily database backup. If a distributed database is damaged, DDS deletes the database and restores the most recent data from the backup database. If no backup database is available, DDS creates one. DDS can also back up encrypted databases.
|
||||
|
||||
|
||||
## Repositories Involved<a name="section1371113476307"></a>
|
||||
|
||||
Distributed Data Management subsystem
|
||||
|
||||
distributeddatamgr\_distributeddatamgr
|
||||
|
||||
third\_party\_sqlite
|
||||
|
||||
third\_party\_flatbuffers
|
||||
|
||||
1. 使用 Readme\_XXX.md 来支持不同的语言,例如 Readme\_en.md, Readme\_zh.md
|
||||
2. Gitee 官方博客 [blog.gitee.com](https://blog.gitee.com)
|
||||
3. 你可以 [https://gitee.com/explore](https://gitee.com/explore) 这个地址来了解 Gitee 上的优秀开源项目
|
||||
4. [GVP](https://gitee.com/gvp) 全称是 Gitee 最有价值开源项目,是综合评定出的优秀开源项目
|
||||
5. Gitee 官方提供的使用手册 [https://gitee.com/help](https://gitee.com/help)
|
||||
6. Gitee 封面人物是一档用来展示 Gitee 会员风采的栏目 [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/)
|
||||
|
127
README_zh.md
Normal file
127
README_zh.md
Normal file
@ -0,0 +1,127 @@
|
||||
# 分布式数据服务组件<a name="ZH-CN_TOPIC_0000001124232845"></a>
|
||||
|
||||
- [简介](#section11660541593)
|
||||
- [目录](#section161941989596)
|
||||
- [约束](#section119744591305)
|
||||
- [说明](#section1312121216216)
|
||||
- [相关仓](#section1371113476307)
|
||||
|
||||
## 简介<a name="section11660541593"></a>
|
||||
|
||||
分布式数据服务(Distributed Data Service,DDS) 提供不同设备间数据库数据分布式的能力。通过结合帐号、应用和数据库三元组,分布式数据服务对数据进行隔离。在通过可信认证的设备间,分布式数据服务支持数据相互同步,为用户提供在多种终端设备上一致的数据访问体验。
|
||||
|
||||
分布式数据服务支撑OpenHarmony系统上分布式管理数据,包含五部分:
|
||||
|
||||
- **服务接口**
|
||||
|
||||
分布式数据服务提供专门的数据库创建、数据访问、数据订阅等接口给内部其他部件调用,接口支持KV数据模型,支持常用的数据类型,同时确保接口的兼容性、易用性和可发布性。
|
||||
|
||||
- **服务组件**
|
||||
|
||||
服务组件负责服务内元数据管理、权限管理、备份和恢复管理以及多用户管理等、同时负责初始化底层分布式DB的存储组件、同步组件和通信适配层。
|
||||
|
||||
- **存储组件**
|
||||
|
||||
存储组件负责数据的访问、数据的缩减、事务、快照,以及数据合并和冲突解决等特性。
|
||||
|
||||
- **同步组件**
|
||||
|
||||
同步组件连结了存储组件与通信组件,其目标是保持在线设备间的数据库数据一致性,包括将本地产生的未同步数据同步给其他设备,接收来自其他设备发送过来的数据,并合并到本地设备中。
|
||||
|
||||
- **通信适配层**
|
||||
|
||||
通信适配层负责调用底层公共通信层的接口完成通信管道的创建、连接,接收设备上下线消息,维护已连接和断开设备列表的元数据,同时将设备上下线信息发送给上层同步组件,同步组件维护连接的设备列表,同步数据时根据该列表,调用通信适配层的接口将数据封装并发送给连接的设备。
|
||||
|
||||
|
||||
通过调用分布式数据服务接口实现分布式数据库创建、访问、订阅功能,服务接口通过操作服务组件提供的能力,将数据存储至存储组件,存储组件调用同步组件实现将数据同步,同步组件使用通信适配层将数据同步至远端设备,远端设备通过同步组件接收数据,并更新至本端存储组件。
|
||||
|
||||
**图 1** 数据分布式运作示意图<a name="fig371116145419"></a>
|
||||
|
||||
|
||||
![](figures/zh-cn_image_0000001162536643.png)
|
||||
|
||||
## 目录<a name="section161941989596"></a>
|
||||
|
||||
```
|
||||
/foundation/distributeddatamgr/distributeddatamgr
|
||||
├── interfaces # 接口层代码
|
||||
│ └── innerkits # Native接口
|
||||
├── services # 服务层代码
|
||||
│ └── distributeddataservice # 分布式数据服务实现
|
||||
└── test # 测试用例资源
|
||||
```
|
||||
|
||||
## 约束<a name="section119744591305"></a>
|
||||
|
||||
- 如需使用分布式数据服务完整功能,需要申请ohos.permission.DISTRIBUTED\_DATASYNC权限。
|
||||
- 分布式数据服务的数据模型仅支持KV数据模型,不支持外键、触发器等关系型数据库中的技术点。
|
||||
- 分布式数据服务支持的KV数据模型规格:
|
||||
- 设备协同数据库,Key最大支持896Byte,Value最大支持4MB。
|
||||
- 单版本数据库,Key最大支持1KB,Value最大支持4MB。
|
||||
- 每个程序最多支持同时打开16个DB。
|
||||
|
||||
- 由于支持的存储类型不完全相同等原因,分布式数据服务无法完全代替业务沙箱内数据库数据的存储功能,开发人员需要确定要做分布式同步的数据,把这些数据保存到分布式数据服务中。
|
||||
- 分布式数据服务当前不支持自定义冲突解决策略。
|
||||
- 分布式数据服务当前流控机制针对KvStore的接口1秒最大访问1000次,1分钟最大访问10000次。KvManager的接口1秒最大访问50次,1分钟最大访问500次。
|
||||
|
||||
## 说明<a name="section1312121216216"></a>
|
||||
|
||||
分布式数据服务几个基本概念:
|
||||
|
||||
- **KV数据模型**
|
||||
|
||||
“KV数据模型”是“Key-Value数据模型”的简称,“Key-Value”即“键-值”。它是一种NoSQL类型数据库,其数据以键值对的形式进行组织、索引和存储。
|
||||
|
||||
KV数据模型适合不涉及过多数据关系和业务关系的业务数据存储,比SQL数据库存储拥有更好的读写性能,同时因在分布式场景中降低了数据库版本兼容和数据同步过程中冲突解决的复杂度而被广泛使用。分布式数据库也是基于KV数据模型,对外提供KV类型的访问接口。
|
||||
|
||||
- **分布式数据库事务性**
|
||||
|
||||
分布式数据库事务支持本地事务(和传统数据库的事务概念一致)和同步事务,同步事务是指在设备之间同步数据时,是以本地事务为单位进行同步,一次本地事务的修改要么都同步成功,要么都同步失败。
|
||||
|
||||
- **分布式数据库一致性**
|
||||
|
||||
在分布式场景中一般会涉及多个设备,组网内设备之间看到的数据是否一致称为分布式数据库的一致性。分布式数据库一致性可以分为**强一致性**、**弱一致性**和**最终一致性**。
|
||||
|
||||
- **强一致性**:是指某一设备成功增、删、改数据后,组网内设备对该数据的读取操作都将得到更新后的值。
|
||||
- **弱一致性**:是指某一设备成功增、删、改数据后,组网内设备可能能读取到本次更新数据,也可能读取不到,不能保证在多长时间后每个设备的数据一定是一致的。
|
||||
- **最终一致性**:是指某一设备成功增、删、改数据后,组网内设备可能读取不到本次更新数据,但在某个时间窗口之后组网内设备的数据能够达到一致状态。
|
||||
|
||||
强一致性对分布式数据的管理要求非常高,在服务器的分布式场景可能会遇到。因为移动终端设备的不常在线、以及无中心的特性,分布式数据服务不支持强一致,只支持最终一致性。
|
||||
|
||||
- **分布式数据库同步**
|
||||
|
||||
底层通信组件完成设备发现和认证,会通知分布式数据服务设备上线。收到设备上线的消息后分布式数据服务可以在两个设备之间建立加密的数据传输通道,利用该通道在两个设备之间进行数据同步。
|
||||
|
||||
分布式数据服务提供了两种同步模式:**手动同步**和**自动同步模式**。**手动同步模式**支持指定同步的设备列表和同步模式(PULL、PUSH和PULL\_PUSH三种同步模式)。**自动同步模式**由分布式数据库来完成数据同步(同步时机包括设备上线、修改数据等),业务不感知同步操作。
|
||||
|
||||
- **单版本分布式数据库**
|
||||
|
||||
单版本是指数据在本地保存是以单个KV条目为单位的方式保存,对每个Key最多只保存一个条目项,当数据在本地被用户修改时,不管它是否已经被同步出去,均直接在这个条目上进行修改。同步也以此为基础,按照它在本地被写入或更改的顺序将当前最新一次修改逐条同步至远端设备。
|
||||
|
||||
- **设备协同分布式数据库**
|
||||
|
||||
设备协同分布式数据库建立在单版本分布式数据库之上,对于存入的KV数据中的Key前面拼接了本设备的DeviceID标识符,这样能保证每个设备产生的数据严格隔离,底层按照设备的维度管理这些数据,设备协同分布式数据库支持以设备的维度查询分布式数据,但是不支持修改远端设备同步过来的数据。
|
||||
|
||||
- **分布式数据库冲突解决策略**
|
||||
|
||||
分布式数据库多设备提交冲突场景,在给提交冲突做合并的过程中,如果多个设备同时修改了同一数据,则称这种场景为数据冲突。数据冲突采用默认冲突解决策略,基于提交时间戳,取时间戳较大的提交数据,当前不支持定制冲突解决策略。
|
||||
|
||||
- **数据库Schema化管理与谓词查询**
|
||||
|
||||
单版本数据库支持在创建和打开数据库时指定Schema,数据库根据Schema定义感知KV记录的Value格式,以实现对Value值结构的检查,并基于Value中的字段实现索引建立和支持谓词查询。
|
||||
|
||||
- **分布式数据库备份能力**
|
||||
|
||||
提供分布式数据库备份能力,业务通过设置backup属性为true,可以触发分布式数据服务每日备份。当分布式数据库发生损坏,分布式数据服务会删除损坏数据库,并且从备份数据库中恢复上次备份的数据。如果不存在备份数据库,则创建一个新的数据库。同时支持加密数据库的备份能力。
|
||||
|
||||
|
||||
## 相关仓<a name="section1371113476307"></a>
|
||||
|
||||
分布式数据管理子系统
|
||||
|
||||
distributeddatamgr\_distributeddatamgr
|
||||
|
||||
third\_party\_sqlite
|
||||
|
||||
third\_party\_flatbuffers
|
||||
|
BIN
figures/en-us_image_0000001162536643.png
Normal file
BIN
figures/en-us_image_0000001162536643.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 78 KiB |
BIN
figures/zh-cn_image_0000001162536643.png
Normal file
BIN
figures/zh-cn_image_0000001162536643.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 138 KiB |
@ -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:
|
||||
virtual 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
|
100
frameworks/innerkitsimpl/distributeddatafwk/include/ikvstore.h
Normal file
100
frameworks/innerkitsimpl/distributeddatafwk/include/ikvstore.h
Normal file
@ -0,0 +1,100 @@
|
||||
/*
|
||||
* 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_H
|
||||
#define I_KVSTORE_H
|
||||
|
||||
#include "message_parcel.h"
|
||||
#include "iremote_broker.h"
|
||||
#include "ikvstore_observer.h"
|
||||
#include "ikvstore_snapshot.h"
|
||||
#include "iremote_proxy.h"
|
||||
#include "iremote_stub.h"
|
||||
#include "types.h"
|
||||
|
||||
namespace OHOS {
|
||||
namespace DistributedKv {
|
||||
|
||||
class IKvStoreImpl : public IRemoteBroker {
|
||||
public:
|
||||
DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.DistributedKv.IKvStoreImpl")
|
||||
|
||||
virtual void GetKvStoreSnapshot(sptr<IKvStoreObserver> observer,
|
||||
std::function<void(Status, sptr<IKvStoreSnapshotImpl>)> callback) = 0;
|
||||
|
||||
virtual Status ReleaseKvStoreSnapshot(sptr<IKvStoreSnapshotImpl> iKvStoreSnapshot) = 0;
|
||||
|
||||
virtual Status Put(const Key &key, const Value &value) = 0;
|
||||
|
||||
virtual Status PutBatch(const std::vector<Entry> &entries) = 0;
|
||||
|
||||
virtual Status Delete(const Key &key) = 0;
|
||||
|
||||
virtual Status DeleteBatch(const std::vector<Key> &keys) = 0;
|
||||
|
||||
virtual Status Clear() = 0;
|
||||
|
||||
virtual Status StartTransaction() = 0;
|
||||
|
||||
virtual Status Commit() = 0;
|
||||
|
||||
virtual Status Rollback() = 0;
|
||||
|
||||
virtual Status SubscribeKvStore(const SubscribeType subscribeType, sptr<IKvStoreObserver> observer) = 0;
|
||||
|
||||
virtual Status UnSubscribeKvStore(const SubscribeType subscribeType, sptr<IKvStoreObserver> observer) = 0;
|
||||
};
|
||||
|
||||
class KvStoreImplStub : public IRemoteStub<IKvStoreImpl> {
|
||||
public:
|
||||
virtual int OnRemoteRequest(uint32_t code, MessageParcel &data,
|
||||
MessageParcel &reply, MessageOption &option) override;
|
||||
|
||||
private:
|
||||
int32_t GetKvStoreSnapshotOnRemote(MessageParcel &data, MessageParcel &reply);
|
||||
int32_t ReleaseKvStoreSnapshotOnRemote(MessageParcel &data, MessageParcel &reply);
|
||||
int32_t PutOnRemoteRequest(MessageParcel &data, MessageParcel &reply);
|
||||
int32_t PutBatchOnRemoteRequest(MessageParcel &data, MessageParcel &reply);
|
||||
int32_t DeleteOnRemoteRequest(MessageParcel &data, MessageParcel &reply);
|
||||
int32_t DeleteBatchOnRemoteRequest(MessageParcel &data, MessageParcel &reply);
|
||||
int32_t SubscribeKvStoreOnRemote(MessageParcel &data, MessageParcel &reply);
|
||||
int32_t UnSubscribeKvStoreOnRemote(MessageParcel &data, MessageParcel &reply);
|
||||
};
|
||||
|
||||
class KvStoreImplProxy : public IRemoteProxy<IKvStoreImpl> {
|
||||
public:
|
||||
explicit KvStoreImplProxy(const sptr<IRemoteObject> &impl);
|
||||
~KvStoreImplProxy() = default;
|
||||
virtual void GetKvStoreSnapshot(sptr<IKvStoreObserver> observer,
|
||||
std::function<void(Status, sptr<IKvStoreSnapshotImpl>)> callback);
|
||||
virtual Status ReleaseKvStoreSnapshot(sptr<IKvStoreSnapshotImpl> iKvStoreSnapshot);
|
||||
virtual Status Put(const Key &key, const Value &value);
|
||||
virtual Status PutBatch(const std::vector<Entry> &entries);
|
||||
virtual Status Delete(const Key &key);
|
||||
virtual Status DeleteBatch(const std::vector<Key> &keys);
|
||||
virtual Status Clear();
|
||||
virtual Status StartTransaction();
|
||||
virtual Status Commit();
|
||||
virtual Status Rollback();
|
||||
virtual Status SubscribeKvStore(const SubscribeType subscribeType, sptr<IKvStoreObserver> observer);
|
||||
virtual Status UnSubscribeKvStore(const SubscribeType subscribeType, sptr<IKvStoreObserver> observer);
|
||||
private:
|
||||
static inline BrokerDelegator<KvStoreImplProxy> delegator_;
|
||||
};
|
||||
|
||||
} // namespace DistributedKv
|
||||
} // namespace OHOS
|
||||
|
||||
#endif // I_KVSTORE_H
|
@ -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 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:
|
||||
virtual int OnRemoteRequest(uint32_t code, MessageParcel &data,
|
||||
MessageParcel &reply, MessageOption &option) override;
|
||||
};
|
||||
|
||||
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
|
176
frameworks/innerkitsimpl/distributeddatafwk/include/ikvstore_data_service.h
Executable file
176
frameworks/innerkitsimpl/distributeddatafwk/include/ikvstore_data_service.h
Executable file
@ -0,0 +1,176 @@
|
||||
/*
|
||||
* 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.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 {
|
||||
namespace 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 persistant;
|
||||
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 {
|
||||
GETKVSTORE,
|
||||
GETALLKVSTOREID,
|
||||
CLOSEKVSTORE,
|
||||
CLOSEALLKVSTORE,
|
||||
DELETEKVSTORE,
|
||||
DELETEALLKVSTORE,
|
||||
REGISTERCLIENTDEATHOBSERVER,
|
||||
GETSINGLEKVSTORE,
|
||||
GETLOCALDEVICE,
|
||||
GETDEVICELIST,
|
||||
STARTWATCHDEVICECHANGE,
|
||||
STOPWATCHDEVICECHANGE,
|
||||
SERVICE_CMD_LAST,
|
||||
DATAUSAGESTART = 20,
|
||||
DATAUSAGEEND = 40,
|
||||
};
|
||||
|
||||
DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.DistributedKv.IKvStoreDataService");
|
||||
/* create and open kv store instance. */
|
||||
virtual Status GetKvStore(const Options &options, const AppId &appId, const StoreId &storeId,
|
||||
std::function<void(sptr<IKvStoreImpl>)> callback) = 0;
|
||||
|
||||
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 GetDeviceList(std::vector<DeviceInfo> &deviceInfoList, DeviceFilterStrategy strategy) = 0;
|
||||
virtual Status StartWatchDeviceChange(sptr<IDeviceStatusChangeListener> observer,
|
||||
DeviceFilterStrategy strategy) = 0;
|
||||
virtual Status StopWatchDeviceChange(sptr<IDeviceStatusChangeListener> observer) = 0;
|
||||
};
|
||||
|
||||
class KvStoreDataServiceStub : public IRemoteStub<IKvStoreDataService> {
|
||||
public:
|
||||
virtual int OnRemoteRequest(uint32_t code, MessageParcel &data,
|
||||
MessageParcel &reply, MessageOption &option) override;
|
||||
private:
|
||||
int32_t GetKvStoreOnRemote(MessageParcel &data, MessageParcel &reply);
|
||||
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 GetDeviceListOnRemote(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);
|
||||
|
||||
using RequestHandler = int32_t(KvStoreDataServiceStub::*)(MessageParcel&, MessageParcel&);
|
||||
static constexpr RequestHandler HANDLERS[SERVICE_CMD_LAST] = {
|
||||
[GETKVSTORE] = &KvStoreDataServiceStub::GetKvStoreOnRemote,
|
||||
[GETALLKVSTOREID] = &KvStoreDataServiceStub::GetAllKvStoreIdOnRemote,
|
||||
[CLOSEKVSTORE] = &KvStoreDataServiceStub::CloseKvStoreOnRemote,
|
||||
[CLOSEALLKVSTORE] = &KvStoreDataServiceStub::CloseAllKvStoreOnRemote,
|
||||
[DELETEKVSTORE] = &KvStoreDataServiceStub::DeleteKvStoreOnRemote,
|
||||
[DELETEALLKVSTORE] = &KvStoreDataServiceStub::DeleteAllKvStoreOnRemote,
|
||||
[REGISTERCLIENTDEATHOBSERVER] = &KvStoreDataServiceStub::RegisterClientDeathObserverOnRemote,
|
||||
[GETSINGLEKVSTORE] = &KvStoreDataServiceStub::GetSingleKvStoreOnRemote,
|
||||
[GETLOCALDEVICE] = &KvStoreDataServiceStub::GetLocalDeviceOnRemote,
|
||||
[GETDEVICELIST] = &KvStoreDataServiceStub::GetDeviceListOnRemote,
|
||||
[STARTWATCHDEVICECHANGE] = &KvStoreDataServiceStub::StartWatchDeviceChangeOnRemote,
|
||||
[STOPWATCHDEVICECHANGE] = &KvStoreDataServiceStub::StopWatchDeviceChangeOnRemote,
|
||||
};
|
||||
};
|
||||
|
||||
class KvStoreDataServiceProxy : public IRemoteProxy<IKvStoreDataService> {
|
||||
public:
|
||||
explicit KvStoreDataServiceProxy(const sptr<IRemoteObject> &impl);
|
||||
~KvStoreDataServiceProxy() = default;
|
||||
|
||||
/* create and open kv store instance. */
|
||||
virtual Status GetKvStore(const Options &options, const AppId &appId, const StoreId &storeId,
|
||||
std::function<void(sptr<IKvStoreImpl>)> callback);
|
||||
|
||||
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 GetDeviceList(std::vector<DeviceInfo> &deviceInfoList, DeviceFilterStrategy strategy);
|
||||
virtual Status StartWatchDeviceChange(sptr<IDeviceStatusChangeListener> observer, DeviceFilterStrategy strategy);
|
||||
virtual Status StopWatchDeviceChange(sptr<IDeviceStatusChangeListener> observer);
|
||||
private:
|
||||
static inline BrokerDelegator<KvStoreDataServiceProxy> delegator_;
|
||||
};
|
||||
} // namespace DistributedKv
|
||||
} // namespace OHOS
|
||||
|
||||
#endif // I_KV_STORE_DATA_SERVICE_H
|
@ -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 I_KVSTORE_OBSERVER_H
|
||||
#define I_KVSTORE_OBSERVER_H
|
||||
|
||||
#include "change_notification.h"
|
||||
#include "iremote_broker.h"
|
||||
#include "ikvstore_observer.h"
|
||||
#include "ikvstore_snapshot.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, sptr<IKvStoreSnapshotImpl> snapshot) = 0;
|
||||
};
|
||||
|
||||
class KvStoreObserverStub : public IRemoteStub<IKvStoreObserver> {
|
||||
public:
|
||||
virtual 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, sptr<IKvStoreSnapshotImpl> snapshot) override;
|
||||
private:
|
||||
static inline BrokerDelegator<KvStoreObserverProxy> delegator_;
|
||||
};
|
||||
|
||||
} // namespace DistributedKv
|
||||
} // namespace OHOS
|
||||
|
||||
#endif // I_KVSTORE_OBSERVER_H
|
@ -0,0 +1,101 @@
|
||||
/*
|
||||
* 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:
|
||||
virtual 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
|
191
frameworks/innerkitsimpl/distributeddatafwk/include/ikvstore_single.h
Executable file
191
frameworks/innerkitsimpl/distributeddatafwk/include/ikvstore_single.h
Executable file
@ -0,0 +1,191 @@
|
||||
/*
|
||||
* 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,
|
||||
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> &deviceIdList, const SyncMode &mode,
|
||||
uint32_t allowedDelayMs) = 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;
|
||||
};
|
||||
|
||||
class SingleKvStoreStub : public IRemoteStub<ISingleKvStore> {
|
||||
public:
|
||||
virtual 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 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,
|
||||
};
|
||||
};
|
||||
|
||||
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> &deviceIdList, const SyncMode &mode, uint32_t allowedDelayMs);
|
||||
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);
|
||||
private:
|
||||
static inline BrokerDelegator<SingleKvStoreProxy> delegator_;
|
||||
};
|
||||
|
||||
} // namespace DistributedKv
|
||||
} // namespace OHOS
|
||||
|
||||
#endif // I_SINGLE_KVSTORE_H
|
@ -0,0 +1,81 @@
|
||||
/*
|
||||
* 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_SNAPSHOT_H
|
||||
#define I_KVSTORE_SNAPSHOT_H
|
||||
|
||||
#include "message_parcel.h"
|
||||
#include "iremote_broker.h"
|
||||
#include "iremote_proxy.h"
|
||||
#include "iremote_stub.h"
|
||||
#include "types.h"
|
||||
|
||||
namespace OHOS {
|
||||
namespace DistributedKv {
|
||||
|
||||
class IKvStoreSnapshotImpl : public IRemoteBroker {
|
||||
public:
|
||||
DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.DistributedKv.IKvStoreSnapshotImpl")
|
||||
virtual void GetEntries(
|
||||
const Key &prefixKey, const Key &nextKey,
|
||||
std::function<void(OHOS::DistributedKv::Status, std::vector<OHOS::DistributedKv::Entry> &,
|
||||
const OHOS::DistributedKv::Key &)>
|
||||
callback) = 0;
|
||||
|
||||
virtual void GetKeys(const Key &prefixKey, const Key &nextKey,
|
||||
std::function<void(Status, std::vector<Key> &, const Key &)> callback) = 0;
|
||||
|
||||
virtual Status Get(const Key &key, Value &value) = 0;
|
||||
};
|
||||
|
||||
class KvStoreSnapshotImplStub : public IRemoteStub<IKvStoreSnapshotImpl> {
|
||||
public:
|
||||
virtual int OnRemoteRequest(uint32_t code, MessageParcel &data,
|
||||
MessageParcel &reply, MessageOption &option) override;
|
||||
|
||||
private:
|
||||
int32_t GetEntriesOnRemote(MessageParcel &data, MessageParcel &reply);
|
||||
int32_t GetKeysRemote(MessageParcel &data, MessageParcel &reply);
|
||||
int32_t GetRemote(MessageParcel &data, MessageParcel &reply);
|
||||
int32_t GetTotalEntriesSize(std::vector<Entry> entryList);
|
||||
int32_t WriteEntriesParcelable(MessageParcel &reply, Status statusTmp,
|
||||
std::vector<Entry> entryList, int bufferSize, Key nxtKey);
|
||||
int32_t GetTotalkeysSize(std::vector<Key> keyList);
|
||||
int32_t WritekeysParcelable(MessageParcel &reply, Status statusTmp,
|
||||
std::vector<Key> keyList, int bufferSize, Key nxtKey);
|
||||
};
|
||||
|
||||
class KvStoreSnapshotImplProxy : public IRemoteProxy<IKvStoreSnapshotImpl> {
|
||||
public:
|
||||
explicit KvStoreSnapshotImplProxy(const sptr<IRemoteObject> &impl);
|
||||
virtual void GetEntries(
|
||||
const Key &prefixKey, const Key &nextKey,
|
||||
std::function<void(OHOS::DistributedKv::Status, std::vector<OHOS::DistributedKv::Entry> &,
|
||||
const OHOS::DistributedKv::Key &)>
|
||||
callback);
|
||||
|
||||
virtual void GetKeys(const Key &prefixKey, const Key &nextKey,
|
||||
std::function<void(Status, std::vector<Key> &, const Key &)> callback);
|
||||
|
||||
virtual Status Get(const Key &key, Value &value);
|
||||
|
||||
virtual ~KvStoreSnapshotImplProxy();
|
||||
private:
|
||||
static inline BrokerDelegator<KvStoreSnapshotImplProxy> delegator_;
|
||||
};
|
||||
} // namespace DistributedKv
|
||||
} // namespace OHOS
|
||||
|
||||
#endif // I_KVSTORE_SNAPSHOT_H
|
@ -0,0 +1,52 @@
|
||||
/*
|
||||
* 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) = 0;
|
||||
};
|
||||
|
||||
class KvStoreSyncCallbackStub : public IRemoteStub<IKvStoreSyncCallback> {
|
||||
public:
|
||||
virtual 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) override;
|
||||
private:
|
||||
static inline BrokerDelegator<KvStoreSyncCallbackProxy> delegator_;
|
||||
};
|
||||
|
||||
} // namespace DistributedKv
|
||||
} // namespace OHOS
|
||||
|
||||
#endif // I_KVSTORE_SYNC_CALLBACK_H
|
@ -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.
|
||||
*/
|
||||
|
||||
#ifndef INNER_TYPES_H
|
||||
#define INNER_TYPES_H
|
||||
|
||||
namespace OHOS {
|
||||
namespace DistributedKv {
|
||||
|
||||
enum class InnerStatus {
|
||||
SUCCESS = 0,
|
||||
DECREASE_REFCOUNT,
|
||||
ERROR,
|
||||
};
|
||||
|
||||
}
|
||||
}
|
||||
#endif
|
116
frameworks/innerkitsimpl/distributeddatafwk/src/app_blob.cpp
Executable file
116
frameworks/innerkitsimpl/distributeddatafwk/src/app_blob.cpp
Executable file
@ -0,0 +1,116 @@
|
||||
/*
|
||||
* Copyright (c) 2021 Huawei Device Co., Ltd.
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include "app_blob.h"
|
||||
#include <securec.h>
|
||||
namespace OHOS {
|
||||
namespace AppDistributedKv {
|
||||
AppBlob::AppBlob(const AppBlob &blob)
|
||||
{
|
||||
blob_ = blob.Data();
|
||||
}
|
||||
|
||||
AppBlob::AppBlob(AppBlob &&blob) noexcept
|
||||
{
|
||||
blob_.swap(blob.blob_);
|
||||
}
|
||||
|
||||
AppBlob &AppBlob::operator=(const AppBlob &blob)
|
||||
{
|
||||
// Self-assignment detection
|
||||
if (&blob == this) {
|
||||
return *this;
|
||||
}
|
||||
|
||||
blob_ = blob.Data();
|
||||
return *this;
|
||||
}
|
||||
|
||||
AppBlob &AppBlob::operator=(AppBlob &&blob) noexcept
|
||||
{
|
||||
// Self-assignment detection
|
||||
if (&blob == this) {
|
||||
return *this;
|
||||
}
|
||||
|
||||
blob_.swap(blob.blob_);
|
||||
|
||||
return *this;
|
||||
}
|
||||
|
||||
AppBlob::AppBlob(const char *str, size_t n)
|
||||
: blob_()
|
||||
{
|
||||
if (str != nullptr) {
|
||||
blob_ = std::vector<uint8_t>(str, str + n);
|
||||
}
|
||||
}
|
||||
|
||||
AppBlob::AppBlob(const std::string &str)
|
||||
: blob_(str.begin(), str.end())
|
||||
{
|
||||
}
|
||||
|
||||
AppBlob::AppBlob(const char *str)
|
||||
: blob_()
|
||||
{
|
||||
if (str != nullptr) {
|
||||
blob_ = std::vector<uint8_t>(str, str + strlen(str));
|
||||
}
|
||||
}
|
||||
|
||||
AppBlob::AppBlob(const std::vector<uint8_t> &bytes)
|
||||
: blob_(bytes)
|
||||
{
|
||||
}
|
||||
|
||||
const std::vector<uint8_t> &AppBlob::Data() const
|
||||
{
|
||||
return blob_;
|
||||
}
|
||||
|
||||
size_t AppBlob::Size() const
|
||||
{
|
||||
return blob_.size();
|
||||
}
|
||||
|
||||
bool AppBlob::Empty() const
|
||||
{
|
||||
return (blob_.empty());
|
||||
}
|
||||
|
||||
bool AppBlob::operator==(const AppBlob &blob) const
|
||||
{
|
||||
return blob_ == blob.blob_;
|
||||
}
|
||||
|
||||
std::string AppBlob::ToString() const
|
||||
{
|
||||
std::string str(blob_.begin(), blob_.end());
|
||||
return str;
|
||||
}
|
||||
|
||||
int AppBlob::Compare(const AppBlob &blob) const
|
||||
{
|
||||
if (blob_ < blob.blob_) {
|
||||
return -1;
|
||||
}
|
||||
if (blob_ == blob.blob_) {
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
} // namespace AppDistributedKv
|
||||
} // namespace OHOS
|
60
frameworks/innerkitsimpl/distributeddatafwk/src/app_change_notification.cpp
Executable file
60
frameworks/innerkitsimpl/distributeddatafwk/src/app_change_notification.cpp
Executable 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.
|
||||
*/
|
||||
|
||||
#include "app_change_notification.h"
|
||||
|
||||
namespace OHOS {
|
||||
namespace AppDistributedKv {
|
||||
AppChangeNotification::AppChangeNotification()
|
||||
{}
|
||||
|
||||
AppChangeNotification::AppChangeNotification(const std::list<Entry> &insertEntries,
|
||||
const std::list<Entry> &updateEntries,
|
||||
const std::list<Entry> &deleteEntries,
|
||||
const std::string &deviceId,
|
||||
const bool isClear)
|
||||
: insertEntries_(insertEntries), updateEntries_(updateEntries), deleteEntries_(deleteEntries),
|
||||
deviceId_(deviceId), isClear_(isClear)
|
||||
{}
|
||||
|
||||
AppChangeNotification::~AppChangeNotification()
|
||||
{}
|
||||
|
||||
const std::list<Entry> &AppChangeNotification::GetInsertEntries() const
|
||||
{
|
||||
return this->insertEntries_;
|
||||
}
|
||||
|
||||
const std::list<Entry> &AppChangeNotification::GetUpdateEntries() const
|
||||
{
|
||||
return this->updateEntries_;
|
||||
}
|
||||
|
||||
const std::list<Entry> &AppChangeNotification::GetDeleteEntries() const
|
||||
{
|
||||
return this->deleteEntries_;
|
||||
}
|
||||
|
||||
const std::string &AppChangeNotification::GetDeviceId() const
|
||||
{
|
||||
return this->deviceId_;
|
||||
}
|
||||
|
||||
bool AppChangeNotification::IsClear() const
|
||||
{
|
||||
return this->isClear_;
|
||||
}
|
||||
} // namespace AppDistributedKv
|
||||
} // namespace OHOS
|
@ -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.
|
||||
*/
|
||||
|
||||
#include "app_distributed_kv_data_manager.h"
|
||||
#include "app_distributed_kv_data_manager_impl.h"
|
||||
|
||||
namespace OHOS {
|
||||
namespace AppDistributedKv {
|
||||
std::shared_ptr<AppDistributedKvDataManager> AppDistributedKvDataManager::GetInstance(const std::string &bundleName,
|
||||
const std::string &dataDir,
|
||||
const std::string &userId)
|
||||
{
|
||||
return AppDistributedKvDataManagerImpl::GetInstance(bundleName, dataDir, userId);
|
||||
}
|
||||
} // namespace AppDistributedKv
|
||||
} // namespace OHOS
|
@ -0,0 +1,263 @@
|
||||
/*
|
||||
* Copyright (c) 2021 Huawei Device Co., Ltd.
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#define LOG_TAG "AppDistributedKvDataManagerImpl"
|
||||
|
||||
#include "app_distributed_kv_data_manager_impl.h"
|
||||
#include <directory_ex.h>
|
||||
#include <unistd.h>
|
||||
#include <memory>
|
||||
#include <cinttypes>
|
||||
#include "app_kvstore_impl.h"
|
||||
#include "communication_provider.h"
|
||||
#include "constant.h"
|
||||
#include "types.h"
|
||||
#include "log_print.h"
|
||||
#include "reporter.h"
|
||||
#include "account_delegate.h"
|
||||
#include "delegate_mgr_callback.h"
|
||||
#include "process_communicator_impl.h"
|
||||
#include "kvstore_utils.h"
|
||||
namespace OHOS {
|
||||
namespace AppDistributedKv {
|
||||
using namespace OHOS::DistributedKv;
|
||||
const std::string DATABASE_DIR = "distributeddb";
|
||||
const std::string DEVICE_COLLABORATION_ABBRE = "_DDC";
|
||||
|
||||
std::mutex AppDistributedKvDataManagerImpl::storeMutex_;
|
||||
std::map<std::string, std::shared_ptr<AppDistributedKvDataManager>> AppDistributedKvDataManagerImpl::managers_;
|
||||
|
||||
std::shared_ptr<AppDistributedKvDataManager> AppDistributedKvDataManagerImpl::GetInstance(const std::string &bundleName,
|
||||
const std::string &dataDir,
|
||||
const std::string &userId)
|
||||
{
|
||||
ZLOGI("start");
|
||||
std::lock_guard<std::mutex> lck(storeMutex_);
|
||||
auto it = managers_.find(bundleName + userId);
|
||||
if (it != managers_.end()) {
|
||||
return it->second;
|
||||
}
|
||||
|
||||
std::string tempDataDir = dataDir;
|
||||
ZLOGD("tempDataDir : %s", tempDataDir.c_str());
|
||||
if (!ForceCreateDirectory(tempDataDir)) {
|
||||
ZLOGE("create directories %s failed", tempDataDir.c_str());
|
||||
FaultMsg msg = {FaultType::SERVICE_FAULT, "device", "GetInstance", Fault::SF_CREATE_DIR};
|
||||
Reporter::GetInstance()->ServiceFault()->Report(msg);
|
||||
return nullptr;
|
||||
}
|
||||
// default mode is 0755
|
||||
if (!ChangeModeDirectory(tempDataDir, DistributedKv::Constant::DEFAULT_MODE)) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
std::string appId = KvStoreUtils::GetAppIdByBundleName(bundleName);
|
||||
if (appId.empty()) {
|
||||
appId = bundleName;
|
||||
}
|
||||
auto status = DistributedDB::KvStoreDelegateManager::SetProcessLabel(appId + DEVICE_COLLABORATION_ABBRE, userId);
|
||||
if (status != DistributedDB::DBStatus::OK) {
|
||||
ZLOGE("delegate SetProcessLabel failed: %d.", static_cast<int>(status));
|
||||
FaultMsg msg = {FaultType::SERVICE_FAULT, "device", "GetInstance", Fault::SF_PROCESS_LABEL};
|
||||
Reporter::GetInstance()->ServiceFault()->Report(msg);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
auto communicator = std::make_shared<ProcessCommunicatorImpl>();
|
||||
auto commStatus = DistributedDB::KvStoreDelegateManager::SetProcessCommunicator(communicator);
|
||||
if (commStatus != DistributedDB::DBStatus::OK) {
|
||||
ZLOGW("set distributed db communicator failed.");
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
auto *delegateManager = new(std::nothrow) DistributedDB::KvStoreDelegateManager(appId, userId);
|
||||
if (delegateManager == nullptr) {
|
||||
ZLOGW("new kvStoredelegateManager failed");
|
||||
return nullptr;
|
||||
}
|
||||
DistributedDB::KvStoreConfig kvStoreConfig { tempDataDir };
|
||||
status = delegateManager->SetKvStoreConfig(kvStoreConfig);
|
||||
if (status != DistributedDB::DBStatus::OK) {
|
||||
ZLOGE("delegate SetKvStoreConfig failed: %d.", static_cast<int>(status));
|
||||
FaultMsg msg = {FaultType::SERVICE_FAULT, "device", "GetInstance", Fault::SF_DATABASE_CONFIG};
|
||||
Reporter::GetInstance()->ServiceFault()->Report(msg);
|
||||
delete delegateManager;
|
||||
delegateManager = nullptr;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
auto temp = std::make_shared<AppDistributedKvDataManagerImpl>(delegateManager, appId);
|
||||
if (temp == nullptr) {
|
||||
delete delegateManager;
|
||||
delegateManager = nullptr;
|
||||
ZLOGW("new AppDistributedKvDataManagerImpl failed");
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
managers_.insert({bundleName + userId, temp});
|
||||
ZLOGD("return a new managerSingleton_.");
|
||||
return temp;
|
||||
}
|
||||
|
||||
AppDistributedKvDataManagerImpl::AppDistributedKvDataManagerImpl(
|
||||
DistributedDB::KvStoreDelegateManager *delegateManager, const std::string &appId)
|
||||
: kvStoreDelegateManager_(delegateManager), appId_(appId)
|
||||
{
|
||||
ZLOGI("construct");
|
||||
}
|
||||
|
||||
AppDistributedKvDataManagerImpl::~AppDistributedKvDataManagerImpl()
|
||||
{
|
||||
ZLOGI("destruct");
|
||||
delete kvStoreDelegateManager_;
|
||||
}
|
||||
|
||||
Status AppDistributedKvDataManagerImpl::GetKvStore(
|
||||
const Options &options, const std::string &storeId,
|
||||
const std::function<void(std::unique_ptr<AppKvStore> appKvStore)> &callback)
|
||||
{
|
||||
ZLOGI("start.");
|
||||
std::string trimmedStoreId = DistributedKv::Constant::TrimCopy<std::string>(storeId);
|
||||
if (trimmedStoreId.size() == 0 || trimmedStoreId.size() > DistributedKv::Constant::MAX_STORE_ID_LENGTH) {
|
||||
ZLOGE("storeId is invalid.");
|
||||
return Status::INVALID_ARGUMENT;
|
||||
}
|
||||
if (kvStoreDelegateManager_ == nullptr) {
|
||||
ZLOGE("kvStoreDelegateManager_ is nullptr.");
|
||||
return Status::ILLEGAL_STATE;
|
||||
}
|
||||
Status status = Status::ERROR;
|
||||
DistributedDB::KvStoreNbDelegate::Option dbOption;
|
||||
dbOption.createIfNecessary = options.createIfMissing;
|
||||
dbOption.isMemoryDb = !options.persistant;
|
||||
dbOption.secOption = ConvertSecurityLevel(options.securityLevel);
|
||||
kvStoreDelegateManager_->GetKvStore(
|
||||
trimmedStoreId, dbOption,
|
||||
[&](DistributedDB::DBStatus dbStatus, DistributedDB::KvStoreNbDelegate *kvStoreNbDelegate) {
|
||||
if (dbStatus == DistributedDB::DBStatus::OK && kvStoreNbDelegate != nullptr) {
|
||||
status = Status::SUCCESS;
|
||||
callback(std::make_unique<AppKvStoreImpl>(trimmedStoreId, kvStoreNbDelegate));
|
||||
ZLOGI("succeed.");
|
||||
auto statDelegateMgr = std::make_shared<DelegateMgrCallback>(kvStoreDelegateManager_);
|
||||
auto statDelegate = std::static_pointer_cast<DbMetaCallbackDelegate>(statDelegateMgr);
|
||||
Reporter::GetInstance()->DatabaseStatistic()->Report(
|
||||
{AccountDelegate::GetInstance()->GetCurrentHarmonyAccountId(), appId_, storeId, 0, statDelegate});
|
||||
return;
|
||||
}
|
||||
|
||||
status = AppKvStoreImpl::ConvertErrorCode(dbStatus);
|
||||
if (kvStoreNbDelegate == nullptr) {
|
||||
status = Status::STORE_NOT_FOUND;
|
||||
}
|
||||
ZLOGW("appKvStore return nullptr.");
|
||||
callback(nullptr);
|
||||
FaultMsg msg = {FaultType::RUNTIME_FAULT, ModuleName::DEVICE, "GetKvStore", Fault::RF_GET_DB};
|
||||
Reporter::GetInstance()->ServiceFault()->Report(msg);
|
||||
});
|
||||
|
||||
ZLOGI("get status: %d.", static_cast<int>(status));
|
||||
return status;
|
||||
}
|
||||
|
||||
Status AppDistributedKvDataManagerImpl::CloseKvStore(std::unique_ptr<AppKvStore> appKvStore)
|
||||
{
|
||||
ZLOGI("start.");
|
||||
if (appKvStore == nullptr) {
|
||||
ZLOGE("appKvStore is nullptr.");
|
||||
return Status::INVALID_ARGUMENT;
|
||||
}
|
||||
if (kvStoreDelegateManager_ == nullptr) {
|
||||
ZLOGE("kvStoreDelegateManager_ is nullptr.");
|
||||
return Status::ILLEGAL_STATE;
|
||||
}
|
||||
return reinterpret_cast<AppKvStoreImpl *>(appKvStore.get())->Close(kvStoreDelegateManager_);
|
||||
}
|
||||
|
||||
Status AppDistributedKvDataManagerImpl::DeleteKvStore(const std::string &storeId)
|
||||
{
|
||||
ZLOGI("start.");
|
||||
if (kvStoreDelegateManager_ == nullptr) {
|
||||
ZLOGE("kvStoreDelegateManager_ is nullptr.");
|
||||
return Status::ILLEGAL_STATE;
|
||||
}
|
||||
std::string trimmedStoreId = DistributedKv::Constant::TrimCopy<std::string>(storeId);
|
||||
if (trimmedStoreId.empty() || trimmedStoreId.size() > DistributedKv::Constant::MAX_STORE_ID_LENGTH) {
|
||||
ZLOGW("invalid storeId.");
|
||||
return Status::INVALID_ARGUMENT;
|
||||
}
|
||||
DistributedDB::DBStatus status = kvStoreDelegateManager_->DeleteKvStore(trimmedStoreId);
|
||||
if (status == DistributedDB::DBStatus::OK) {
|
||||
ZLOGI("delete KVStore succeed.");
|
||||
return Status::SUCCESS;
|
||||
}
|
||||
ZLOGE("delete KVStore failed.");
|
||||
return Status::ERROR;
|
||||
}
|
||||
|
||||
Status AppDistributedKvDataManagerImpl::GetKvStoreDiskSize(const std::string &storeId, uint64_t &size)
|
||||
{
|
||||
ZLOGI("start");
|
||||
if (kvStoreDelegateManager_ == nullptr) {
|
||||
ZLOGE("kvStoreDelegateManager_ is nullptr.");
|
||||
return Status::ILLEGAL_STATE;
|
||||
}
|
||||
DistributedDB::DBStatus status = kvStoreDelegateManager_->GetKvStoreDiskSize(storeId, size);
|
||||
if (status != DistributedDB::DBStatus::OK) {
|
||||
ZLOGE("Failed to getStoreDiskSize, storeID: %s", storeId.c_str());
|
||||
return Status::ERROR;
|
||||
}
|
||||
ZLOGI("end, size:%" PRIu64, size);
|
||||
return Status::SUCCESS;
|
||||
}
|
||||
|
||||
Status AppDistributedKvDataManagerImpl::RegisterKvStoreCorruptionObserver(
|
||||
const std::shared_ptr<AppKvStoreCorruptionObserver> observer)
|
||||
{
|
||||
ZLOGI("start");
|
||||
if (observer == nullptr) {
|
||||
ZLOGE("observer is nullptr.");
|
||||
return Status::INVALID_ARGUMENT;
|
||||
}
|
||||
if (corruptionObserver_ != nullptr) {
|
||||
return Status::REPEATED_REGISTER;
|
||||
}
|
||||
if (kvStoreDelegateManager_ == nullptr) {
|
||||
return Status::ERROR;
|
||||
}
|
||||
corruptionObserver_ = observer;
|
||||
kvStoreDelegateManager_->SetKvStoreCorruptionHandler([&](const std::string& appId, const std::string& userId,
|
||||
const std::string& storeId) {
|
||||
corruptionObserver_->OnCorruption(appId, userId, storeId);
|
||||
});
|
||||
ZLOGD("end");
|
||||
return Status::SUCCESS;
|
||||
}
|
||||
|
||||
DistributedDB::SecurityOption AppDistributedKvDataManagerImpl::ConvertSecurityLevel(int securityLevel)
|
||||
{
|
||||
if (securityLevel < SecurityLevel::NO_LABEL || securityLevel > SecurityLevel::S4) {
|
||||
return {SecurityLevel::NO_LABEL, DistributedDB::ECE};
|
||||
}
|
||||
switch (securityLevel) {
|
||||
case SecurityLevel::S3:
|
||||
return {DistributedDB::S3, DistributedDB::SECE};
|
||||
case SecurityLevel::S4:
|
||||
return {DistributedDB::S4, DistributedDB::ECE};
|
||||
default:
|
||||
return {securityLevel, DistributedDB::ECE};
|
||||
}
|
||||
}
|
||||
} // namespace AppDistributedKv
|
||||
} // namespace OHOS
|
@ -0,0 +1,65 @@
|
||||
/*
|
||||
* Copyright (c) 2021 Huawei Device Co., Ltd.
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#ifndef APP_DISTRIBUTED_KV_DATA_MANAGER_IMPL_H
|
||||
#define APP_DISTRIBUTED_KV_DATA_MANAGER_IMPL_H
|
||||
|
||||
#include <mutex>
|
||||
#include "app_device_status_change_listener.h"
|
||||
#include "app_distributed_kv_data_manager.h"
|
||||
#include "app_kvstore.h"
|
||||
#include "app_types.h"
|
||||
#include "kv_store_delegate_manager.h"
|
||||
#include "process_communicator_impl.h"
|
||||
|
||||
namespace OHOS {
|
||||
namespace AppDistributedKv {
|
||||
// This is the overall manager of all kvstore.
|
||||
// This class provides open, close, delete AppKvStore and manage remote device functions.
|
||||
class AppDistributedKvDataManagerImpl final : public AppDistributedKvDataManager {
|
||||
public:
|
||||
AppDistributedKvDataManagerImpl(DistributedDB::KvStoreDelegateManager *delegateManager, const std::string &appId);
|
||||
|
||||
static std::shared_ptr<AppDistributedKvDataManager> GetInstance(const std::string &bundleName,
|
||||
const std::string &dataDir,
|
||||
const std::string &userId);
|
||||
|
||||
virtual ~AppDistributedKvDataManagerImpl();
|
||||
|
||||
Status GetKvStore(const Options &options, const std::string &storeId,
|
||||
const std::function<void(std::unique_ptr<AppKvStore> appKvStore)> &callback) override;
|
||||
|
||||
Status CloseKvStore(std::unique_ptr<AppKvStore> appKvStore) override;
|
||||
|
||||
Status DeleteKvStore(const std::string &storeId) override;
|
||||
|
||||
Status GetKvStoreDiskSize(const std::string &storeId, uint64_t &size) override;
|
||||
|
||||
Status RegisterKvStoreCorruptionObserver(const std::shared_ptr<AppKvStoreCorruptionObserver> observer) override;
|
||||
private:
|
||||
static DistributedDB::SecurityOption ConvertSecurityLevel(int securityLevel);
|
||||
|
||||
static std::mutex storeMutex_;
|
||||
|
||||
static std::map<std::string, std::shared_ptr<AppDistributedKvDataManager>> managers_;
|
||||
// pointer of class DistributedDB::KvStoreDelegateManager. defined as void* to avoid exposing inside implementions.
|
||||
DistributedDB::KvStoreDelegateManager *kvStoreDelegateManager_;
|
||||
std::string appId_;
|
||||
|
||||
std::shared_ptr<AppKvStoreCorruptionObserver> corruptionObserver_;
|
||||
}; // class AppDistributedKvDataManagerImpl
|
||||
} // namespace AppDistributedKv
|
||||
} // namespace OHOS
|
||||
#endif // APP_DISTRIBUTED_KV_DATA_MANAGER_IMPL_H
|
@ -0,0 +1,76 @@
|
||||
/*
|
||||
* Copyright (c) 2021 Huawei Device Co., Ltd.
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#define LOG_TAG "AppKvStoreConflictDataImpl"
|
||||
|
||||
#include "app_kvstore_conflict_data_impl.h"
|
||||
#include "log_print.h"
|
||||
|
||||
namespace OHOS {
|
||||
namespace AppDistributedKv {
|
||||
AppKvStoreConflictDataImpl::AppKvStoreConflictDataImpl(const KvStoreConflictEntry &kvStoreConflictEntry)
|
||||
: kvStoreConflictEntry_(kvStoreConflictEntry)
|
||||
{
|
||||
ZLOGI("constructor");
|
||||
}
|
||||
|
||||
AppKvStoreConflictDataImpl::~AppKvStoreConflictDataImpl()
|
||||
{
|
||||
ZLOGI("destructor");
|
||||
}
|
||||
|
||||
AppKvStoreConflictPolicyType AppKvStoreConflictDataImpl::GetType() const
|
||||
{
|
||||
return static_cast<AppKvStoreConflictPolicyType>(kvStoreConflictEntry_.type);
|
||||
}
|
||||
|
||||
void AppKvStoreConflictDataImpl::GetKey(Key &key) const
|
||||
{
|
||||
key = kvStoreConflictEntry_.key;
|
||||
}
|
||||
|
||||
Status AppKvStoreConflictDataImpl::GetValue(ConflictValueType type, Value &value) const
|
||||
{
|
||||
if (type == ConflictValueType::OLD_VALUE) {
|
||||
if (!kvStoreConflictEntry_.oldData.isDeleted) {
|
||||
value = kvStoreConflictEntry_.oldData.value;
|
||||
}
|
||||
return kvStoreConflictEntry_.oldData.status;
|
||||
} else {
|
||||
if (!kvStoreConflictEntry_.newData.isDeleted) {
|
||||
value = kvStoreConflictEntry_.newData.value;
|
||||
}
|
||||
return kvStoreConflictEntry_.newData.status;
|
||||
}
|
||||
}
|
||||
|
||||
bool AppKvStoreConflictDataImpl::IsDeleted(ConflictValueType type) const
|
||||
{
|
||||
if (type == ConflictValueType::OLD_VALUE) {
|
||||
return kvStoreConflictEntry_.oldData.isDeleted;
|
||||
}
|
||||
return kvStoreConflictEntry_.newData.isDeleted;
|
||||
}
|
||||
|
||||
bool AppKvStoreConflictDataImpl::IsNative(ConflictValueType type) const
|
||||
{
|
||||
if (type == ConflictValueType::OLD_VALUE) {
|
||||
return kvStoreConflictEntry_.oldData.isLocal;
|
||||
} else {
|
||||
return kvStoreConflictEntry_.newData.isLocal;
|
||||
}
|
||||
}
|
||||
} // namespace AppDistributedKv
|
||||
} // namespace OHOS
|
@ -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 APP_KVSTORE_CONFLICT_DATA_IMPL_H
|
||||
#define APP_KVSTORE_CONFLICT_DATA_IMPL_H
|
||||
|
||||
#include "app_kvstore_conflict_data.h"
|
||||
#include "app_types.h"
|
||||
#include "kv_store_nb_conflict_data.h"
|
||||
|
||||
namespace OHOS {
|
||||
namespace AppDistributedKv {
|
||||
struct KvStoreConflictData {
|
||||
Value value {};
|
||||
bool isDeleted = false;
|
||||
bool isLocal = false;
|
||||
Status status {};
|
||||
};
|
||||
|
||||
struct KvStoreConflictEntry {
|
||||
int type = 1;
|
||||
Key key {};
|
||||
KvStoreConflictData oldData {};
|
||||
KvStoreConflictData newData {};
|
||||
};
|
||||
|
||||
class AppKvStoreConflictDataImpl final : public AppKvStoreConflictData {
|
||||
public:
|
||||
explicit AppKvStoreConflictDataImpl(const KvStoreConflictEntry &kvStoreConflictEntry);
|
||||
|
||||
~AppKvStoreConflictDataImpl();
|
||||
|
||||
AppKvStoreConflictPolicyType GetType() const override;
|
||||
|
||||
void GetKey(Key &key) const override;
|
||||
|
||||
Status GetValue(ConflictValueType type, Value &value) const override;
|
||||
|
||||
bool IsDeleted(ConflictValueType type) const override;
|
||||
|
||||
bool IsNative(ConflictValueType type) const override;
|
||||
|
||||
private:
|
||||
const KvStoreConflictEntry kvStoreConflictEntry_;
|
||||
};
|
||||
} // namespace AppDistributedKv
|
||||
} // namespace OHOS
|
||||
|
||||
#endif // APP_KVSTORE_CONFLICT_DATA_IMPL_H
|
562
frameworks/innerkitsimpl/distributeddatafwk/src/app_kvstore_impl.cpp
Executable file
562
frameworks/innerkitsimpl/distributeddatafwk/src/app_kvstore_impl.cpp
Executable file
@ -0,0 +1,562 @@
|
||||
/*
|
||||
* Copyright (c) 2021 Huawei Device Co., Ltd.
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#define LOG_TAG "AppKvStoreImpl"
|
||||
|
||||
#include "app_kvstore_impl.h"
|
||||
#include <chrono>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
#include "app_kvstore_result_set_impl.h"
|
||||
#include "app_types.h"
|
||||
#include "log_print.h"
|
||||
#include "types.h"
|
||||
#include "reporter.h"
|
||||
|
||||
namespace OHOS {
|
||||
namespace AppDistributedKv {
|
||||
using namespace std::chrono_literals;
|
||||
using namespace OHOS::DistributedKv;
|
||||
AppKvStoreImpl::AppKvStoreImpl(const std::string &storeId, DistributedDB::KvStoreNbDelegate *kvStoreNbDelegate)
|
||||
: storeId_(storeId), kvStoreNbDelegate_(kvStoreNbDelegate)
|
||||
{
|
||||
ZLOGI("constructor appkvstore");
|
||||
}
|
||||
|
||||
AppKvStoreImpl::~AppKvStoreImpl()
|
||||
{
|
||||
ZLOGI("destructor appKvStore.");
|
||||
// This function will be called after DB close, so every Subscribe/Unsubscribe call will fail and no more element
|
||||
// will be added to observer maps.
|
||||
{
|
||||
std::lock_guard<std::mutex> localLock(localObserverMapMutex_);
|
||||
for (auto const &iter : localObserverMap_) {
|
||||
delete iter.second;
|
||||
}
|
||||
localObserverMap_.clear();
|
||||
}
|
||||
{
|
||||
std::lock_guard<std::mutex> syncLock(syncedObserverMapMutex_);
|
||||
for (auto const &iter : syncedObserverMap_) {
|
||||
delete iter.second;
|
||||
}
|
||||
syncedObserverMap_.clear();
|
||||
}
|
||||
}
|
||||
|
||||
// Get id of this AppKvStore.
|
||||
const std::string &AppKvStoreImpl::GetStoreId()
|
||||
{
|
||||
return storeId_;
|
||||
}
|
||||
|
||||
// options: Mark this is a local entry or not.
|
||||
Status AppKvStoreImpl::Put(const WriteOptions &options, const Key &key, const Value &value)
|
||||
{
|
||||
ZLOGD("start");
|
||||
auto trimmedKey = DistributedKv::Constant::TrimCopy<std::vector<uint8_t>>(key.Data());
|
||||
// Restrict key and value size to interface specification.
|
||||
if (trimmedKey.size() == 0 || trimmedKey.size() > DistributedKv::Constant::MAX_KEY_LENGTH ||
|
||||
value.Data().size() > DistributedKv::Constant::MAX_VALUE_LENGTH) {
|
||||
ZLOGW("invalid_argument.");
|
||||
return Status::INVALID_ARGUMENT;
|
||||
}
|
||||
DistributedDB::Key tmpKey = trimmedKey;
|
||||
DistributedDB::Value tmpValue = value.Data();
|
||||
DistributedDB::DBStatus status;
|
||||
if (options.local) {
|
||||
status = kvStoreNbDelegate_->PutLocal(tmpKey, tmpValue);
|
||||
} else {
|
||||
status = kvStoreNbDelegate_->Put(tmpKey, tmpValue);
|
||||
}
|
||||
if (status == DistributedDB::DBStatus::OK) {
|
||||
ZLOGD("put succeed.");
|
||||
Reporter::GetInstance()->VisitStatistic()->Report({appId_, __FUNCTION__});
|
||||
return Status::SUCCESS;
|
||||
}
|
||||
ZLOGW("put failed. status: %d.", static_cast<int>(status));
|
||||
return ConvertErrorCode(status);
|
||||
}
|
||||
|
||||
// options: mark this delete is a local change or not.
|
||||
Status AppKvStoreImpl::Delete(const WriteOptions &options, const Key &key)
|
||||
{
|
||||
ZLOGD("start.");
|
||||
auto trimmedKey = DistributedKv::Constant::TrimCopy<std::vector<uint8_t>>(key.Data());
|
||||
if (trimmedKey.size() == 0 || trimmedKey.size() > DistributedKv::Constant::MAX_KEY_LENGTH) {
|
||||
ZLOGW("invalid argument.");
|
||||
return Status::INVALID_ARGUMENT;
|
||||
}
|
||||
DistributedDB::Key tmpKey = trimmedKey;
|
||||
DistributedDB::DBStatus status;
|
||||
if (options.local) {
|
||||
status = kvStoreNbDelegate_->DeleteLocal(tmpKey);
|
||||
} else {
|
||||
status = kvStoreNbDelegate_->Delete(tmpKey);
|
||||
}
|
||||
if (status == DistributedDB::DBStatus::OK) {
|
||||
ZLOGD("succeed.");
|
||||
Reporter::GetInstance()->VisitStatistic()->Report({appId_, __FUNCTION__});
|
||||
return Status::SUCCESS;
|
||||
}
|
||||
ZLOGW("failed status: %d.", static_cast<int>(status));
|
||||
return ConvertErrorCode(status);
|
||||
}
|
||||
|
||||
// Get value from AppKvStore by its key. Set options->local to true if you want to get from local kvstore.
|
||||
// Parameters:
|
||||
// options: mark we get from local store or remote store. options->batch is a reserved parameter and should
|
||||
// always be false.
|
||||
Status AppKvStoreImpl::Get(const ReadOptions &options, const Key &key, Value &value)
|
||||
{
|
||||
ZLOGD("start");
|
||||
auto trimmedKey = DistributedKv::Constant::TrimCopy<std::vector<uint8_t>>(key.Data());
|
||||
if (trimmedKey.size() == 0 || trimmedKey.size() > DistributedKv::Constant::MAX_KEY_LENGTH) {
|
||||
return Status::INVALID_ARGUMENT;
|
||||
}
|
||||
DistributedDB::Key tmpKey = trimmedKey;
|
||||
DistributedDB::Value tmpValue;
|
||||
DistributedDB::DBStatus status;
|
||||
if (options.local) {
|
||||
status = kvStoreNbDelegate_->GetLocal(tmpKey, tmpValue);
|
||||
} else {
|
||||
status = kvStoreNbDelegate_->Get(tmpKey, tmpValue);
|
||||
}
|
||||
ZLOGD("status: %d.", static_cast<int>(status));
|
||||
// Value don't have other write method.
|
||||
Value tmpValueForCopy(tmpValue);
|
||||
value = tmpValueForCopy;
|
||||
if (status == DistributedDB::DBStatus::OK) {
|
||||
Reporter::GetInstance()->VisitStatistic()->Report({appId_, __FUNCTION__});
|
||||
return Status::SUCCESS;
|
||||
}
|
||||
return ConvertErrorCode(status);
|
||||
}
|
||||
|
||||
// Get all entries in this store which key start with prefixKey.
|
||||
// Parameters:
|
||||
// options: mark we get from local store or remote store. options->batch is a reserved parameter and should
|
||||
// always be false.
|
||||
Status AppKvStoreImpl::GetEntries(const Key &prefixKey, std::vector<Entry> &entries)
|
||||
{
|
||||
ZLOGD("start.");
|
||||
auto trimmedPrefix = DistributedKv::Constant::TrimCopy<std::vector<uint8_t>>(prefixKey.Data());
|
||||
if (trimmedPrefix.size() > DistributedKv::Constant::MAX_KEY_LENGTH) {
|
||||
return Status::INVALID_ARGUMENT;
|
||||
}
|
||||
DistributedDB::Key tmpKeyPrefix = trimmedPrefix;
|
||||
std::vector<DistributedDB::Entry> dbEntries;
|
||||
DistributedDB::DBStatus status = kvStoreNbDelegate_->GetEntries(tmpKeyPrefix, dbEntries);
|
||||
if (status == DistributedDB::DBStatus::OK) {
|
||||
entries.reserve(dbEntries.size());
|
||||
ZLOGD("vector size: %zu status: %d.", dbEntries.size(), static_cast<int>(status));
|
||||
for (auto const &dbEntry : dbEntries) {
|
||||
Key tmpKey(dbEntry.key);
|
||||
Value tmpValue(dbEntry.value);
|
||||
entries.push_back({.key = tmpKey, .value = tmpValue});
|
||||
}
|
||||
return Status::SUCCESS;
|
||||
}
|
||||
return ConvertErrorCode(status);
|
||||
}
|
||||
|
||||
// Get all entries in this store which key start with prefixKey.
|
||||
Status AppKvStoreImpl::GetEntries(const Key &prefixKey, AppKvStoreResultSet *&resultSet)
|
||||
{
|
||||
ZLOGD("start.");
|
||||
auto trimmedPrefix = DistributedKv::Constant::TrimCopy<std::vector<uint8_t>>(prefixKey.Data());
|
||||
if (trimmedPrefix.size() > DistributedKv::Constant::MAX_KEY_LENGTH) {
|
||||
return Status::INVALID_ARGUMENT;
|
||||
}
|
||||
DistributedDB::Key tmpKeyPrefix = trimmedPrefix;
|
||||
DistributedDB::KvStoreResultSet *dbResultSet = nullptr;
|
||||
DistributedDB::DBStatus status = kvStoreNbDelegate_->GetEntries(tmpKeyPrefix, dbResultSet);
|
||||
if (status == DistributedDB::DBStatus::OK) {
|
||||
resultSet = new (std::nothrow) AppKvStoreResultSetImpl(dbResultSet, kvStoreNbDelegate_);
|
||||
if (resultSet == nullptr) {
|
||||
ZLOGW("new resultSet failed.");
|
||||
return Status::ERROR;
|
||||
}
|
||||
return Status::SUCCESS;
|
||||
}
|
||||
return ConvertErrorCode(status);
|
||||
}
|
||||
|
||||
// Close the result set returned by GetEntries().
|
||||
Status AppKvStoreImpl::CloseResultSet(AppKvStoreResultSet *&resultSet)
|
||||
{
|
||||
if (resultSet == nullptr) {
|
||||
return Status::INVALID_ARGUMENT;
|
||||
}
|
||||
if (resultSet->Close() == Status::SUCCESS) {
|
||||
delete resultSet;
|
||||
resultSet = nullptr;
|
||||
return Status::SUCCESS;
|
||||
}
|
||||
return Status::ERROR;
|
||||
}
|
||||
|
||||
// Close this kvstore in KvStoreDelegateManager. This method is called before this store object destruct.
|
||||
Status AppKvStoreImpl::Close(DistributedDB::KvStoreDelegateManager *kvStoreDelegateManager)
|
||||
{
|
||||
if (kvStoreDelegateManager == nullptr) {
|
||||
return Status::INVALID_ARGUMENT;
|
||||
}
|
||||
|
||||
DistributedDB::DBStatus status = kvStoreDelegateManager->CloseKvStore(kvStoreNbDelegate_);
|
||||
if (status == DistributedDB::DBStatus::OK) {
|
||||
VisitStat vs { appId_, __FUNCTION__ };
|
||||
Reporter::GetInstance()->VisitStatistic()->Report(vs);
|
||||
return Status::SUCCESS;
|
||||
}
|
||||
return Status::ERROR;
|
||||
}
|
||||
|
||||
// Sync store with other devices. This is an asynchronous method,
|
||||
// sync will fail if there is a syncing operation in progress.
|
||||
// Parameters:
|
||||
// deviceIdList: device list to sync.
|
||||
// mode: mode can be set to SyncMode::PUSH, SyncMode::PULL and SyncMode::PUTH_PULL. PUSH_PULL will firstly
|
||||
// push all not-local store to listed devices, then pull these stores back.
|
||||
// callback: return <device-id, sync-result> map to caller.
|
||||
// Return:
|
||||
// Status of this Sync operation.
|
||||
Status AppKvStoreImpl::Sync(const std::vector<std::string> &deviceIdList, const SyncMode &mode,
|
||||
const std::function<void(const std::map<std::string, Status> &)> &callback)
|
||||
{
|
||||
ZLOGD("start.");
|
||||
DistributedDB::DBStatus status;
|
||||
DistributedDB::SyncMode dbMode;
|
||||
if (mode == SyncMode::PUSH) {
|
||||
dbMode = DistributedDB::SyncMode::SYNC_MODE_PUSH_ONLY;
|
||||
} else if (mode == SyncMode::PULL) {
|
||||
dbMode = DistributedDB::SyncMode::SYNC_MODE_PULL_ONLY;
|
||||
} else {
|
||||
dbMode = DistributedDB::SyncMode::SYNC_MODE_PUSH_PULL;
|
||||
}
|
||||
|
||||
bool syncStatus = syncStatus_.try_lock();
|
||||
if (!syncStatus) {
|
||||
ZLOGW("Another sync operation still in progress, still call sync right now.");
|
||||
}
|
||||
status = kvStoreNbDelegate_->Sync(deviceIdList, dbMode,
|
||||
[&, callback](const std::map<std::string, DistributedDB::DBStatus> &devices) {
|
||||
syncStatus_.unlock();
|
||||
std::map<std::string, Status> resultMap;
|
||||
for (auto device : devices) {
|
||||
if (device.second == DistributedDB::DBStatus::OK) {
|
||||
resultMap[device.first] = Status::SUCCESS;
|
||||
} else if (device.second == DistributedDB::DBStatus::NOT_FOUND) {
|
||||
resultMap[device.first] = Status::DEVICE_NOT_FOUND;
|
||||
} else if (device.second == DistributedDB::DBStatus::TIME_OUT) {
|
||||
resultMap[device.first] = Status::TIME_OUT;
|
||||
} else {
|
||||
resultMap[device.first] = Status::ERROR;
|
||||
}
|
||||
}
|
||||
ZLOGD("callback.");
|
||||
callback(resultMap);
|
||||
});
|
||||
|
||||
ZLOGD("end: %d", static_cast<int>(status));
|
||||
Reporter::GetInstance()->VisitStatistic()->Report({appId_, __FUNCTION__});
|
||||
if (status == DistributedDB::DBStatus::OK) {
|
||||
return Status::SUCCESS;
|
||||
}
|
||||
return ConvertErrorCode(status);
|
||||
}
|
||||
|
||||
// Register change of this kvstore to a client-defined observer. observer->OnChange method will be called when store
|
||||
// changes. One observer can subscribe more than one AppKvStore.
|
||||
// Parameters:
|
||||
// options: mark this is a local entry or not.
|
||||
// subscribeType: OBSERVER_CHANGES_NATIVE means native changes of syncable kv store,
|
||||
// : OBSERVER_CHANGES_FOREIGN means synced data changes from remote devices,
|
||||
// : OBSERVER_CHANGES_ALL means both native changes and synced data changes.
|
||||
// observer: observer to subscribe changes.
|
||||
// Return:
|
||||
// Status of this subscribe operation.
|
||||
Status AppKvStoreImpl::SubscribeKvStore(const ReadOptions &options, const SubscribeType &subscribeType,
|
||||
AppKvStoreObserver *observer)
|
||||
{
|
||||
ZLOGD("start.");
|
||||
if (observer == nullptr) {
|
||||
return Status::INVALID_ARGUMENT;
|
||||
}
|
||||
DistributedDB::DBStatus dbStatus;
|
||||
KvStoreObserverNbImpl *nbObserver = new (std::nothrow) KvStoreObserverNbImpl(observer, subscribeType);
|
||||
if (nbObserver == nullptr) {
|
||||
ZLOGW("new KvStoreObserverNbImpl failed");
|
||||
return Status::ERROR;
|
||||
}
|
||||
DistributedDB::Key emptyKey;
|
||||
if (options.local) {
|
||||
std::lock_guard<std::mutex> lock(localObserverMapMutex_);
|
||||
bool alreadySubscribed = (localObserverMap_.find(observer) != localObserverMap_.end());
|
||||
if (alreadySubscribed) {
|
||||
delete nbObserver;
|
||||
return Status::STORE_ALREADY_SUBSCRIBE;
|
||||
}
|
||||
|
||||
dbStatus = kvStoreNbDelegate_->RegisterObserver(
|
||||
emptyKey, DistributedDB::ObserverMode::OBSERVER_CHANGES_LOCAL_ONLY, nbObserver);
|
||||
if (dbStatus == DistributedDB::DBStatus::OK) {
|
||||
localObserverMap_.insert(std::pair<AppKvStoreObserver *, KvStoreObserverNbImpl *>(observer, nbObserver));
|
||||
}
|
||||
} else {
|
||||
std::lock_guard<std::mutex> lock(syncedObserverMapMutex_);
|
||||
bool alreadySubscribed = (syncedObserverMap_.find(observer) != syncedObserverMap_.end());
|
||||
if (alreadySubscribed) {
|
||||
delete nbObserver;
|
||||
return Status::STORE_ALREADY_SUBSCRIBE;
|
||||
}
|
||||
int dbObserverMode;
|
||||
if (subscribeType == SubscribeType::OBSERVER_CHANGES_NATIVE) {
|
||||
dbObserverMode = DistributedDB::ObserverMode::OBSERVER_CHANGES_NATIVE;
|
||||
} else if (subscribeType == SubscribeType::OBSERVER_CHANGES_FOREIGN) {
|
||||
dbObserverMode = DistributedDB::ObserverMode::OBSERVER_CHANGES_FOREIGN;
|
||||
} else {
|
||||
dbObserverMode = DistributedDB::ObserverMode::OBSERVER_CHANGES_FOREIGN |
|
||||
DistributedDB::ObserverMode::OBSERVER_CHANGES_NATIVE;
|
||||
}
|
||||
dbStatus = kvStoreNbDelegate_->RegisterObserver(emptyKey, dbObserverMode, nbObserver);
|
||||
if (dbStatus == DistributedDB::DBStatus::OK) {
|
||||
syncedObserverMap_.insert(std::pair<AppKvStoreObserver *, KvStoreObserverNbImpl *>(observer, nbObserver));
|
||||
}
|
||||
}
|
||||
Reporter::GetInstance()->VisitStatistic()->Report({appId_, __FUNCTION__});
|
||||
if (dbStatus == DistributedDB::DBStatus::OK) {
|
||||
return Status::SUCCESS;
|
||||
}
|
||||
|
||||
delete nbObserver;
|
||||
if (dbStatus == DistributedDB::DBStatus::INVALID_ARGS) {
|
||||
return Status::INVALID_ARGUMENT;
|
||||
}
|
||||
if (dbStatus == DistributedDB::DBStatus::DB_ERROR) {
|
||||
return Status::DB_ERROR;
|
||||
}
|
||||
return Status::ERROR;
|
||||
}
|
||||
|
||||
// Unregister a kvstore to an observer.
|
||||
// Parameters:
|
||||
// options: mark this is a local entry or not.
|
||||
// subscribeType: OBSERVER_CHANGES_NATIVE means native changes of syncable kv store,
|
||||
// : OBSERVER_CHANGES_FOREIGN means synced data changes from remote devices,
|
||||
// : OBSERVER_CHANGES_ALL means both native changes and synced data changes.
|
||||
// observer: observer to unsubscribe this store.
|
||||
// Return:
|
||||
// Status of this unsubscribe operation.
|
||||
Status AppKvStoreImpl::UnSubscribeKvStore(const ReadOptions &options, const SubscribeType &subscribeType,
|
||||
AppKvStoreObserver *observer)
|
||||
{
|
||||
ZLOGD("start.");
|
||||
if (observer == nullptr) {
|
||||
return Status::INVALID_ARGUMENT;
|
||||
}
|
||||
DistributedDB::DBStatus dbStatus;
|
||||
if (options.local) {
|
||||
std::lock_guard<std::mutex> lock(localObserverMapMutex_);
|
||||
auto nbObserver = localObserverMap_.find(observer);
|
||||
if (nbObserver == localObserverMap_.end()) {
|
||||
return Status::STORE_NOT_SUBSCRIBE;
|
||||
}
|
||||
dbStatus = kvStoreNbDelegate_->UnRegisterObserver(nbObserver->second);
|
||||
if (dbStatus == DistributedDB::DBStatus::OK) {
|
||||
delete nbObserver->second;
|
||||
localObserverMap_.erase(nbObserver);
|
||||
}
|
||||
} else {
|
||||
std::lock_guard<std::mutex> lock(syncedObserverMapMutex_);
|
||||
auto nbObserver = syncedObserverMap_.find(observer);
|
||||
if (nbObserver == syncedObserverMap_.end()) {
|
||||
return Status::STORE_NOT_SUBSCRIBE;
|
||||
}
|
||||
dbStatus = kvStoreNbDelegate_->UnRegisterObserver(nbObserver->second);
|
||||
if (dbStatus == DistributedDB::DBStatus::OK) {
|
||||
delete nbObserver->second;
|
||||
syncedObserverMap_.erase(nbObserver);
|
||||
}
|
||||
}
|
||||
Reporter::GetInstance()->VisitStatistic()->Report({appId_, __FUNCTION__});
|
||||
if (dbStatus == DistributedDB::DBStatus::OK) {
|
||||
return Status::SUCCESS;
|
||||
}
|
||||
if (dbStatus == DistributedDB::DBStatus::NOT_FOUND) {
|
||||
return Status::STORE_NOT_SUBSCRIBE;
|
||||
}
|
||||
if (dbStatus == DistributedDB::DBStatus::INVALID_ARGS) {
|
||||
return Status::INVALID_ARGUMENT;
|
||||
}
|
||||
return Status::ERROR;
|
||||
}
|
||||
|
||||
Status AppKvStoreImpl::RemoveDeviceData(const std::string &device)
|
||||
{
|
||||
ZLOGD("start");
|
||||
DistributedDB::DBStatus status = kvStoreNbDelegate_->RemoveDeviceData(device);
|
||||
if (status == DistributedDB::DBStatus::OK) {
|
||||
return Status::SUCCESS;
|
||||
}
|
||||
return Status::ERROR;
|
||||
}
|
||||
|
||||
Status AppKvStoreImpl::SetConflictResolutionPolicy(
|
||||
AppKvStoreConflictPolicyType appConflictPolicyType,
|
||||
std::function<void(const AppKvStoreConflictData &appConflictData)> callback)
|
||||
{
|
||||
ZLOGD("start.");
|
||||
int conflictType = static_cast<int>(appConflictPolicyType);
|
||||
DistributedDB::DBStatus dbStatus = kvStoreNbDelegate_->SetConflictNotifier(
|
||||
conflictType, [callback, this](const DistributedDB::KvStoreNbConflictData &kvStoreNbConflictData) {
|
||||
ZLOGD("callback ");
|
||||
KvStoreConflictEntry kvstoreConflictEntry;
|
||||
FormKvStoreConflictEntry(kvStoreNbConflictData, kvstoreConflictEntry);
|
||||
AppKvStoreConflictDataImpl appConflictDataImpl(kvstoreConflictEntry);
|
||||
callback(appConflictDataImpl);
|
||||
});
|
||||
if (dbStatus != DistributedDB::DBStatus::OK) {
|
||||
return Status::DB_ERROR;
|
||||
}
|
||||
return Status::SUCCESS;
|
||||
}
|
||||
|
||||
void AppKvStoreImpl::FormKvStoreConflictEntry(const DistributedDB::KvStoreNbConflictData &data,
|
||||
KvStoreConflictEntry &kvstoreConflictEntry)
|
||||
{
|
||||
kvstoreConflictEntry.type = data.GetType();
|
||||
DistributedDB::Key dbKey;
|
||||
data.GetKey(dbKey);
|
||||
Key tmpKey(dbKey);
|
||||
kvstoreConflictEntry.key = tmpKey;
|
||||
FormKvStoreConflictData(data, DistributedDB::KvStoreNbConflictData::ValueType::OLD_VALUE,
|
||||
kvstoreConflictEntry.oldData);
|
||||
FormKvStoreConflictData(data, DistributedDB::KvStoreNbConflictData::ValueType::NEW_VALUE,
|
||||
kvstoreConflictEntry.newData);
|
||||
}
|
||||
|
||||
void AppKvStoreImpl::FormKvStoreConflictData(const DistributedDB::KvStoreNbConflictData &data,
|
||||
DistributedDB::KvStoreNbConflictData::ValueType type,
|
||||
KvStoreConflictData &kvStoreConflictData)
|
||||
{
|
||||
DistributedDB::DBStatus dbStatus;
|
||||
kvStoreConflictData.isLocal = data.IsNative(type);
|
||||
kvStoreConflictData.isDeleted = data.IsDeleted(type);
|
||||
if (!kvStoreConflictData.isDeleted) {
|
||||
DistributedDB::Value dbValue;
|
||||
dbStatus = data.GetValue(type, dbValue);
|
||||
if (dbStatus != DistributedDB::DBStatus::OK) {
|
||||
ZLOGE("Failed to handle conflict, error: bad conflict data");
|
||||
kvStoreConflictData.status = Status::DB_ERROR;
|
||||
return;
|
||||
}
|
||||
Value tmpValue(dbValue);
|
||||
kvStoreConflictData.status = Status::SUCCESS;
|
||||
kvStoreConflictData.value = tmpValue;
|
||||
}
|
||||
}
|
||||
|
||||
Status AppKvStoreImpl::Export(const std::string &filePath, const std::vector<uint8_t> &passwd)
|
||||
{
|
||||
ZLOGD("export start");
|
||||
if (filePath.empty()) {
|
||||
return Status::INVALID_ARGUMENT;
|
||||
}
|
||||
DistributedDB::CipherPassword password;
|
||||
auto status = password.SetValue(passwd.data(), passwd.size());
|
||||
if (status != DistributedDB::CipherPassword::ErrorCode::OK) {
|
||||
ZLOGE("Failed to set the passwd.");
|
||||
return Status::DB_ERROR;
|
||||
}
|
||||
DistributedDB::DBStatus dbStatus = kvStoreNbDelegate_->Export(filePath, password);
|
||||
if (dbStatus != DistributedDB::DBStatus::OK) {
|
||||
ZLOGE("Failed to export, path:%s", filePath.c_str());
|
||||
return Status::DB_ERROR;
|
||||
}
|
||||
ZLOGD("export end");
|
||||
return Status::SUCCESS;
|
||||
}
|
||||
|
||||
Status AppKvStoreImpl::Import(const std::string &filePath, const std::vector<uint8_t> &passwd)
|
||||
{
|
||||
ZLOGD("Import start");
|
||||
if (filePath.empty()) {
|
||||
return Status::INVALID_ARGUMENT;
|
||||
}
|
||||
DistributedDB::CipherPassword password;
|
||||
auto status = password.SetValue(passwd.data(), passwd.size());
|
||||
if (status != DistributedDB::CipherPassword::ErrorCode::OK) {
|
||||
ZLOGE("Failed to set the passwd.");
|
||||
return Status::DB_ERROR;
|
||||
}
|
||||
DistributedDB::DBStatus dbStatus = kvStoreNbDelegate_->Import(filePath, password);
|
||||
if (dbStatus != DistributedDB::DBStatus::OK) {
|
||||
ZLOGE("Failed to export, path:%s", filePath.c_str());
|
||||
return Status::DB_ERROR;
|
||||
}
|
||||
ZLOGD("Import end");
|
||||
return Status::SUCCESS;
|
||||
}
|
||||
|
||||
Status AppKvStoreImpl::GetSecurityLevel(SecurityLevel &securityLevel) const
|
||||
{
|
||||
ZLOGD("start");
|
||||
DistributedDB::SecurityOption option;
|
||||
DistributedDB::DBStatus dbStatus = kvStoreNbDelegate_->GetSecurityOption(option);
|
||||
if (dbStatus != DistributedDB::DBStatus::OK) {
|
||||
ZLOGE("Failed to get security level");
|
||||
return Status::DB_ERROR;
|
||||
}
|
||||
switch (option.securityLabel) {
|
||||
case DistributedDB::NOT_SET:
|
||||
case DistributedDB::S0:
|
||||
case DistributedDB::S1:
|
||||
case DistributedDB::S2:
|
||||
securityLevel = static_cast<SecurityLevel>(option.securityLabel);
|
||||
break;
|
||||
case DistributedDB::S3:
|
||||
securityLevel = option.securityFlag ? S3 : S3_EX;
|
||||
break;
|
||||
case DistributedDB::S4:
|
||||
securityLevel = S4;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
ZLOGD("end");
|
||||
return Status::SUCCESS;
|
||||
}
|
||||
|
||||
Status AppKvStoreImpl::ConvertErrorCode(DistributedDB::DBStatus status)
|
||||
{
|
||||
switch (status) {
|
||||
case DistributedDB::DBStatus::BUSY:
|
||||
case DistributedDB::DBStatus::DB_ERROR:
|
||||
return Status::DB_ERROR;
|
||||
case DistributedDB::DBStatus::NOT_FOUND:
|
||||
return Status::KEY_NOT_FOUND;
|
||||
case DistributedDB::DBStatus::INVALID_ARGS:
|
||||
return Status::INVALID_ARGUMENT;
|
||||
case DistributedDB::DBStatus::EKEYREVOKED_ERROR:
|
||||
case DistributedDB::DBStatus::SECURITY_OPTION_CHECK_ERROR:
|
||||
return Status::SECURITY_LEVEL_ERROR;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return Status::ERROR;
|
||||
}
|
||||
} // namespace AppDistributedKv
|
||||
} // namespace OHOS
|
189
frameworks/innerkitsimpl/distributeddatafwk/src/app_kvstore_impl.h
Executable file
189
frameworks/innerkitsimpl/distributeddatafwk/src/app_kvstore_impl.h
Executable file
@ -0,0 +1,189 @@
|
||||
/*
|
||||
* Copyright (c) 2021 Huawei Device Co., Ltd.
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#ifndef APP_KV_STORE_IMPL_H
|
||||
#define APP_KV_STORE_IMPL_H
|
||||
|
||||
#include <mutex>
|
||||
#include <set>
|
||||
#include "app_kvstore.h"
|
||||
#include "app_kvstore_conflict_data_impl.h"
|
||||
#include "app_kvstore_observer.h"
|
||||
#include "app_kvstore_result_set.h"
|
||||
#include "app_types.h"
|
||||
#include "constant.h"
|
||||
#include "kv_store_delegate_manager.h"
|
||||
#include "kv_store_nb_delegate.h"
|
||||
#include "kvstore_observer_nb_impl.h"
|
||||
|
||||
namespace OHOS {
|
||||
namespace AppDistributedKv {
|
||||
class AppKvStoreImpl : public AppKvStore {
|
||||
public:
|
||||
AppKvStoreImpl(const std::string &storeId, DistributedDB::KvStoreNbDelegate *kvStoreNbDelegate);
|
||||
|
||||
AppKvStoreImpl(AppKvStoreImpl &&) = delete;
|
||||
AppKvStoreImpl &operator=(AppKvStoreImpl &&) = delete;
|
||||
|
||||
// forbidden copy constructor.
|
||||
AppKvStoreImpl(const AppKvStoreImpl &) = delete;
|
||||
AppKvStoreImpl &operator=(const AppKvStoreImpl &) = delete;
|
||||
|
||||
virtual ~AppKvStoreImpl();
|
||||
|
||||
// Get id of this AppKvStore.
|
||||
const std::string &GetStoreId() override;
|
||||
|
||||
// Write a pair of key and value to this store. Set write option to local if you do not this entry sync to other
|
||||
// devices.
|
||||
// Parameters:
|
||||
// options: mark this is a local entry or not.
|
||||
// key: key of this entry. Should be less than 256 bytes. key will be trimmed before store.
|
||||
// value: value of this entry. Should be less than (1024 * 1024) bytes.
|
||||
// Return:
|
||||
// Status of this put operation.
|
||||
Status Put(const WriteOptions &options, const Key &key, const Value &value) override;
|
||||
|
||||
// Delete an entry by its key. Set write option to local if you want this delete to be a local change.
|
||||
// Parameters:
|
||||
// options: mark this delete is a local change or not.
|
||||
// key: key of the entry to be deleted.
|
||||
// Return:
|
||||
// Status of this delete operation.
|
||||
Status Delete(const WriteOptions &options, const Key &key) override;
|
||||
|
||||
// Get value from AppKvStore by its key. Set options->local to true if you want to get from local kvstore.
|
||||
// Parameters:
|
||||
// options: mark we get from local store or remote store. options->batch is a reserved parameter and should
|
||||
// always be false.
|
||||
// key: key of this entry.
|
||||
// value: value will be returned in this parameter.
|
||||
// Return:
|
||||
// Status of this get operation.
|
||||
Status Get(const ReadOptions &options, const Key &key, Value &value) override;
|
||||
|
||||
// Get all entries in this store which key start with prefixKey. This function will always get from synced store.
|
||||
// Parameters:
|
||||
// prefixkey: the prefix to be searched.
|
||||
// entries: entries will be returned in this parameter.
|
||||
// Return:
|
||||
// Status of this GetEntries operation.
|
||||
Status GetEntries(const Key &prefixKey, std::vector<Entry> &entries) override;
|
||||
|
||||
// Get all entries in this store which key start with prefixKey. This function will always get from synced store.
|
||||
// Parameters:
|
||||
// prefixkey: the prefix to be searched.
|
||||
// resultSet: resultSet will be returned in this parameter.
|
||||
// Return:
|
||||
// Status of this GetEntries operation.
|
||||
Status GetEntries(const Key &prefixKey, AppKvStoreResultSet *&resultSet) override;
|
||||
|
||||
// Close the result set returned by GetEntries().
|
||||
// Parameters:
|
||||
// resultSet: resultSet will be returned in this parameter.
|
||||
// Return:
|
||||
// Status of this GetEntries operation.
|
||||
Status CloseResultSet(AppKvStoreResultSet *&resultSet) override;
|
||||
|
||||
// Sync store with other devices. This is an asynchronous method,
|
||||
// sync will fail if there is a syncing operation in progress.
|
||||
// Parameters:
|
||||
// deviceIdList: device list to sync.
|
||||
// mode: mode can be set to SyncMode::PUSH, SyncMode::PULL and SyncMode::PUTH_PULL. PUSH_PULL will firstly
|
||||
// push all not-local store to listed devices, then pull these stores back.
|
||||
// callback: return <device-id, sync-result> map to caller.
|
||||
// Return:
|
||||
// Status of this Sync operation.
|
||||
Status Sync(const std::vector<std::string> &deviceIdList, const SyncMode &mode,
|
||||
const std::function<void(const std::map<std::string, Status> &)> &callback) override;
|
||||
|
||||
// Register change of this kvstore to a client-defined observer. observer->OnChange method will be called when store
|
||||
// changes. One observer can subscribe more than one AppKvStore.
|
||||
// Parameters:
|
||||
// options: mark this is a local entry or not.
|
||||
// subscribeType: OBSERVER_CHANGES_NATIVE means native changes of syncable kv store,
|
||||
// : OBSERVER_CHANGES_FOREIGN means synced data changes from remote devices,
|
||||
// : OBSERVER_CHANGES_ALL means both native changes and synced data changes.
|
||||
// observer: observer to subscribe changes.
|
||||
// Return:
|
||||
// Status of this subscribe operation.
|
||||
Status SubscribeKvStore(const ReadOptions &options, const SubscribeType &subscribeType,
|
||||
AppKvStoreObserver *observer) override;
|
||||
|
||||
// Unregister a kvstore to an observer.
|
||||
// Parameters:
|
||||
// options: mark this is a local entry or not.
|
||||
// subscribeType: OBSERVER_CHANGES_NATIVE means native changes of syncable kv store,
|
||||
// : OBSERVER_CHANGES_FOREIGN means synced data changes from remote devices,
|
||||
// : OBSERVER_CHANGES_LOCAL_ONLY means local changes of local kv store.
|
||||
// observer: observer to unsubscribe this store.
|
||||
// Return:
|
||||
// Status of this unsubscribe operation.
|
||||
Status UnSubscribeKvStore(const ReadOptions &options, const SubscribeType &subscribeType,
|
||||
AppKvStoreObserver *observer) override;
|
||||
|
||||
// Close this kvstore in KvStoreDelegateManager. This method is called before this store object destruct.
|
||||
Status Close(DistributedDB::KvStoreDelegateManager *kvStoreDelegateManager);
|
||||
|
||||
// Remove Devvice data when device offline.
|
||||
// Parameters:
|
||||
// device: device id.
|
||||
// Return:
|
||||
// Status of this remove operation.
|
||||
Status RemoveDeviceData(const std::string &device) override;
|
||||
|
||||
// Set policy of conflict resolution.
|
||||
// Parameters:
|
||||
// appConflictPolicyType: include CONFLICT_FOREIGN_KEY_ONLY CONFLICT_FOREIGN_KEY_ORIG CONFLICT_NATIVE_ALL.
|
||||
// callback: conflict resolution callback.
|
||||
// Return:
|
||||
// Status of Setting policy operation.
|
||||
Status SetConflictResolutionPolicy(AppKvStoreConflictPolicyType appConflictPolicyType,
|
||||
std::function<void(const AppKvStoreConflictData &data)> callback) override;
|
||||
|
||||
Status Export(const std::string &filePath, const std::vector<uint8_t> &passwd) override;
|
||||
|
||||
Status Import(const std::string &filePath, const std::vector<uint8_t> &passwd) override;
|
||||
|
||||
Status GetSecurityLevel(SecurityLevel &securityLevel) const override;
|
||||
|
||||
static Status ConvertErrorCode(DistributedDB::DBStatus status);
|
||||
private:
|
||||
void FormKvStoreConflictEntry(const DistributedDB::KvStoreNbConflictData &data,
|
||||
KvStoreConflictEntry &kvstoreConflictEntry);
|
||||
void FormKvStoreConflictData(const DistributedDB::KvStoreNbConflictData &data,
|
||||
DistributedDB::KvStoreNbConflictData::ValueType type,
|
||||
KvStoreConflictData &kvStoreConflictData);
|
||||
// user account get from User Account System.
|
||||
std::string userId_;
|
||||
// appId get from PMS.
|
||||
std::string appId_;
|
||||
// kvstore name.
|
||||
std::string storeId_;
|
||||
std::mutex syncStatus_ {};
|
||||
|
||||
// distributeddb is responsible for free kvStoreNbDelegate_,
|
||||
// (destruct will be done while calling CloseKvStore in KvStoreDelegateManager)
|
||||
// so DO NOT free it in AppKvStoreImpl's destructor.
|
||||
DistributedDB::KvStoreNbDelegate *kvStoreNbDelegate_ = nullptr;
|
||||
|
||||
std::map<AppKvStoreObserver *, KvStoreObserverNbImpl *> syncedObserverMap_ {};
|
||||
std::mutex syncedObserverMapMutex_ {};
|
||||
std::map<AppKvStoreObserver *, KvStoreObserverNbImpl *> localObserverMap_ {};
|
||||
std::mutex localObserverMapMutex_ {};
|
||||
};
|
||||
} // namespace AppDistributedKv
|
||||
} // namespace OHOS
|
||||
#endif // APP_KV_STORE_IMPL_H
|
148
frameworks/innerkitsimpl/distributeddatafwk/src/app_kvstore_result_set_impl.cpp
Executable file
148
frameworks/innerkitsimpl/distributeddatafwk/src/app_kvstore_result_set_impl.cpp
Executable file
@ -0,0 +1,148 @@
|
||||
/*
|
||||
* Copyright (c) 2021 Huawei Device Co., Ltd.
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#define LOG_TAG "AppKvStoreResultSetImpl"
|
||||
|
||||
#include "app_kvstore_result_set_impl.h"
|
||||
#include "app_types.h"
|
||||
|
||||
namespace OHOS {
|
||||
namespace AppDistributedKv {
|
||||
const int AppKvStoreResultSetImpl::INIT_POSTION = -1;
|
||||
|
||||
AppKvStoreResultSetImpl::AppKvStoreResultSetImpl(DistributedDB::KvStoreResultSet *resultSet,
|
||||
DistributedDB::KvStoreNbDelegate *delegate)
|
||||
: kvStoreResultSet_(resultSet), nbDelegate_(delegate)
|
||||
{
|
||||
}
|
||||
|
||||
AppKvStoreResultSetImpl::~AppKvStoreResultSetImpl()
|
||||
{
|
||||
}
|
||||
|
||||
// Returns the count of rows in the result set.
|
||||
int AppKvStoreResultSetImpl::GetCount() const
|
||||
{
|
||||
return (kvStoreResultSet_ == nullptr) ? 0 : kvStoreResultSet_->GetCount();
|
||||
}
|
||||
|
||||
// Returns the current read position of the result set.
|
||||
int AppKvStoreResultSetImpl::GetPosition() const
|
||||
{
|
||||
return (kvStoreResultSet_ == nullptr) ? INIT_POSTION : kvStoreResultSet_->GetPosition();
|
||||
}
|
||||
|
||||
// Move the read position to the first row, return false if the result set is empty.
|
||||
bool AppKvStoreResultSetImpl::MoveToFirst()
|
||||
{
|
||||
return (kvStoreResultSet_ == nullptr) ? false : kvStoreResultSet_->MoveToFirst();
|
||||
}
|
||||
|
||||
// Move the read position to the last row, return false if the result set is empty.
|
||||
bool AppKvStoreResultSetImpl::MoveToLast()
|
||||
{
|
||||
return (kvStoreResultSet_ == nullptr) ? false : kvStoreResultSet_->MoveToLast();
|
||||
}
|
||||
|
||||
// Move the read position to the next row,
|
||||
// return false if the result set is empty or the read position is already past the last entry in the result set.
|
||||
bool AppKvStoreResultSetImpl::MoveToNext()
|
||||
{
|
||||
return (kvStoreResultSet_ == nullptr) ? false : kvStoreResultSet_->MoveToNext();
|
||||
}
|
||||
|
||||
// Move the read position to the previous row,
|
||||
// return false if the result set is empty or the read position is already before the first entry in the result set.
|
||||
bool AppKvStoreResultSetImpl::MoveToPrevious()
|
||||
{
|
||||
return (kvStoreResultSet_ == nullptr) ? false : kvStoreResultSet_->MoveToPrevious();
|
||||
}
|
||||
|
||||
// Move the read position by a relative amount from the current position.
|
||||
bool AppKvStoreResultSetImpl::Move(int offset)
|
||||
{
|
||||
return (kvStoreResultSet_ == nullptr) ? false : kvStoreResultSet_->Move(offset);
|
||||
}
|
||||
|
||||
// Move the read position to an absolute position value.
|
||||
bool AppKvStoreResultSetImpl::MoveToPosition(int position)
|
||||
{
|
||||
return (kvStoreResultSet_ == nullptr) ? false : kvStoreResultSet_->MoveToPosition(position);
|
||||
}
|
||||
|
||||
// Returns whether the read position is pointing to the first row.
|
||||
bool AppKvStoreResultSetImpl::IsFirst() const
|
||||
{
|
||||
return (kvStoreResultSet_ == nullptr) ? false : kvStoreResultSet_->IsFirst();
|
||||
}
|
||||
|
||||
// Returns whether the read position is pointing to the last row.
|
||||
bool AppKvStoreResultSetImpl::IsLast() const
|
||||
{
|
||||
return (kvStoreResultSet_ == nullptr) ? false : kvStoreResultSet_->IsLast();
|
||||
}
|
||||
|
||||
// Returns whether the read position is before the first row.
|
||||
bool AppKvStoreResultSetImpl::IsBeforeFirst() const
|
||||
{
|
||||
return (kvStoreResultSet_ == nullptr) ? false : kvStoreResultSet_->IsBeforeFirst();
|
||||
}
|
||||
|
||||
// Returns whether the read position is after the last row
|
||||
bool AppKvStoreResultSetImpl::IsAfterLast() const
|
||||
{
|
||||
return (kvStoreResultSet_ == nullptr) ? false : kvStoreResultSet_->IsAfterLast();
|
||||
}
|
||||
|
||||
// Get a key-value entry.
|
||||
Status AppKvStoreResultSetImpl::GetEntry(Entry &entry) const
|
||||
{
|
||||
if (kvStoreResultSet_ == nullptr) {
|
||||
return Status::ERROR;
|
||||
}
|
||||
if (GetCount() == 0) {
|
||||
return Status::KEY_NOT_FOUND;
|
||||
}
|
||||
DistributedDB::Entry dbEntry;
|
||||
DistributedDB::DBStatus dbStatus = kvStoreResultSet_->GetEntry(dbEntry);
|
||||
if (dbStatus == DistributedDB::DBStatus::OK) {
|
||||
Key tmpKey(dbEntry.key);
|
||||
Value tmpValue(dbEntry.value);
|
||||
entry.key = tmpKey;
|
||||
entry.value = tmpValue;
|
||||
return Status::SUCCESS;
|
||||
}
|
||||
return Status::KEY_NOT_FOUND;
|
||||
}
|
||||
|
||||
Status AppKvStoreResultSetImpl::Close()
|
||||
{
|
||||
if (kvStoreResultSet_ == nullptr) {
|
||||
return Status::SUCCESS;
|
||||
}
|
||||
|
||||
if (nbDelegate_ == nullptr) {
|
||||
return Status::INVALID_ARGUMENT;
|
||||
}
|
||||
|
||||
auto result = nbDelegate_->CloseResultSet(kvStoreResultSet_);
|
||||
if (result == DistributedDB::DBStatus::OK) {
|
||||
return Status::SUCCESS;
|
||||
}
|
||||
kvStoreResultSet_ = nullptr;
|
||||
return Status::ERROR;
|
||||
}
|
||||
} // namespace AppDistributedKv
|
||||
} // namespace OHOS
|
@ -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 APP_KV_STORE_RESULT_SET_IMPL_H
|
||||
#define APP_KV_STORE_RESULT_SET_IMPL_H
|
||||
|
||||
#include "app_kvstore_result_set.h"
|
||||
#include "kv_store_nb_delegate.h"
|
||||
#include "kv_store_result_set.h"
|
||||
|
||||
namespace OHOS {
|
||||
namespace AppDistributedKv {
|
||||
class AppKvStoreResultSetImpl : public AppKvStoreResultSet {
|
||||
public:
|
||||
AppKvStoreResultSetImpl(DistributedDB::KvStoreResultSet *resultSet, DistributedDB::KvStoreNbDelegate *delegate);
|
||||
|
||||
~AppKvStoreResultSetImpl();
|
||||
|
||||
// Returns the count of rows in the result set.
|
||||
int GetCount() const override;
|
||||
|
||||
// Returns the current read position of the result set.
|
||||
int GetPosition() const override;
|
||||
|
||||
// Move the read position to the first row, return false if the result set is empty.
|
||||
bool MoveToFirst() override;
|
||||
|
||||
// Move the read position to the last row, return false if the result set is empty.
|
||||
bool MoveToLast() override;
|
||||
|
||||
// Move the read position to the next row,
|
||||
// return false if the result set is empty or the read position is already past the last entry in the result set.
|
||||
bool MoveToNext() override;
|
||||
|
||||
// Move the read position to the previous row,
|
||||
// return false if result set is empty or the read position is already before the first entry in the result set.
|
||||
bool MoveToPrevious() override;
|
||||
|
||||
// Move the read position by a relative amount from the current position.
|
||||
bool Move(int offset) override;
|
||||
|
||||
// Move the read position to an absolute position value.
|
||||
bool MoveToPosition(int position) override;
|
||||
|
||||
// Returns whether the read position is pointing to the first row.
|
||||
bool IsFirst() const override;
|
||||
|
||||
// Returns whether the read position is pointing to the last row.
|
||||
bool IsLast() const override;
|
||||
|
||||
// Returns whether the read position is before the first row.
|
||||
bool IsBeforeFirst() const override;
|
||||
|
||||
// Returns whether the read position is after the last row
|
||||
bool IsAfterLast() const override;
|
||||
|
||||
// Get a key-value entry.
|
||||
Status GetEntry(Entry &entry) const override;
|
||||
|
||||
Status Close() override;
|
||||
private:
|
||||
DistributedDB::KvStoreResultSet *kvStoreResultSet_ = nullptr;
|
||||
DistributedDB::KvStoreNbDelegate *nbDelegate_ = nullptr;
|
||||
static const int INIT_POSTION;
|
||||
};
|
||||
} // namespace AppDistributedKv
|
||||
} // namespace OHOS
|
||||
#endif // APP_KV_STORE_RESULT_SET_IMPL_H
|
211
frameworks/innerkitsimpl/distributeddatafwk/src/blob.cpp
Executable file
211
frameworks/innerkitsimpl/distributeddatafwk/src/blob.cpp
Executable file
@ -0,0 +1,211 @@
|
||||
/*
|
||||
* 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(const char *str)
|
||||
: blob_()
|
||||
{
|
||||
if (str != nullptr) {
|
||||
blob_ = std::vector<uint8_t>(str, str + strlen(str));
|
||||
}
|
||||
}
|
||||
|
||||
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_;
|
||||
}
|
||||
|
||||
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
|
@ -0,0 +1,159 @@
|
||||
/*
|
||||
* 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(const std::list<Entry> &insertEntries, const std::list<Entry> &updateEntries,
|
||||
const std::list<Entry> &deleteEntries, const std::string &deviceId,
|
||||
const bool isClear)
|
||||
: insertEntries_(insertEntries), updateEntries_(updateEntries), deleteEntries_(deleteEntries),
|
||||
deviceId_(deviceId), isClear_(isClear)
|
||||
{}
|
||||
|
||||
ChangeNotification::~ChangeNotification()
|
||||
{}
|
||||
|
||||
const std::list<Entry> &ChangeNotification::GetInsertEntries() const
|
||||
{
|
||||
return this->insertEntries_;
|
||||
}
|
||||
|
||||
const std::list<Entry> &ChangeNotification::GetUpdateEntries() const
|
||||
{
|
||||
return this->updateEntries_;
|
||||
}
|
||||
|
||||
const std::list<Entry> &ChangeNotification::GetDeleteEntries() const
|
||||
{
|
||||
return this->deleteEntries_;
|
||||
}
|
||||
|
||||
const std::string &ChangeNotification::GetDeviceId() const
|
||||
{
|
||||
return this->deviceId_;
|
||||
}
|
||||
|
||||
bool ChangeNotification::IsClear() const
|
||||
{
|
||||
return this->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::list<Entry> insertEntries;
|
||||
std::list<Entry> updateEntries;
|
||||
std::list<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();
|
||||
ChangeNotification *changeNotification =
|
||||
new ChangeNotification(insertEntries, updateEntries, deleteEntries, deviceId, isClear);
|
||||
return changeNotification;
|
||||
}
|
||||
} // namespace DistributedKv
|
||||
} // namespace OHOS
|
679
frameworks/innerkitsimpl/distributeddatafwk/src/data_query.cpp
Executable file
679
frameworks/innerkitsimpl/distributeddatafwk/src/data_query.cpp
Executable file
@ -0,0 +1,679 @@
|
||||
/*
|
||||
* 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"
|
||||
|
||||
namespace OHOS {
|
||||
namespace DistributedKv {
|
||||
const std::string DataQuery::EQUAL_TO = "^EQUAL";
|
||||
const std::string DataQuery::NOT_EQUAL_TO = "^NOT_EQUAL";
|
||||
const std::string DataQuery::GREATER_THAN = "^GREATER";
|
||||
const std::string DataQuery::LESS_THAN = "^LESS";
|
||||
const std::string DataQuery::GREATER_THAN_OR_EQUAL_TO = "^GREATER_EQUAL";
|
||||
const std::string DataQuery::LESS_THAN_OR_EQUAL_TO = "^LESS_EQUAL";
|
||||
const std::string DataQuery::IS_NULL = "^IS_NULL";
|
||||
const std::string DataQuery::IN = "^IN";
|
||||
const std::string DataQuery::NOT_IN = "^NOT_IN";
|
||||
const std::string DataQuery::LIKE = "^LIKE";
|
||||
const std::string DataQuery::NOT_LIKE = "^NOT_LIKE";
|
||||
const std::string DataQuery::AND = "^AND";
|
||||
const std::string DataQuery::OR = "^OR";
|
||||
const std::string DataQuery::ORDER_BY_ASC = "^ASC";
|
||||
const std::string DataQuery::ORDER_BY_DESC = "^DESC";
|
||||
const std::string DataQuery::LIMIT = "^LIMIT";
|
||||
const std::string DataQuery::SPACE = " ";
|
||||
const std::string DataQuery::SPECIAL = "^";
|
||||
const std::string DataQuery::SPECIAL_ESCAPE = "(^)";
|
||||
const std::string DataQuery::SPACE_ESCAPE = "^^";
|
||||
const std::string DataQuery::EMPTY_STRING = "^EMPTY_STRING";
|
||||
const std::string DataQuery::START_IN = "^START";
|
||||
const std::string DataQuery::END_IN = "^END";
|
||||
const std::string DataQuery::BEGIN_GROUP = "^BEGIN_GROUP";
|
||||
const std::string DataQuery::END_GROUP = "^END_GROUP";
|
||||
const std::string DataQuery::KEY_PREFIX = "^KEY_PREFIX";
|
||||
const std::string DataQuery::DEVICE_ID = "^DEVICE_ID";
|
||||
const std::string DataQuery::IS_NOT_NULL = "^IS_NOT_NULL";
|
||||
const std::string DataQuery::TYPE_STRING = "STRING";
|
||||
const std::string DataQuery::TYPE_INTEGER = "INTEGER";
|
||||
const std::string DataQuery::TYPE_LONG = "LONG";
|
||||
const std::string DataQuery::TYPE_DOUBLE = "DOUBLE";
|
||||
const std::string DataQuery::TYPE_BOOLEAN = "BOOL";
|
||||
const std::string DataQuery::VALUE_TRUE = "true";
|
||||
const std::string DataQuery::VALUE_FALSE = "false";
|
||||
const std::string DataQuery::SUGGEST_INDEX = "^SUGGEST_INDEX";
|
||||
constexpr int MAX_QUERY_LENGTH = 5 * 1024; // Max query string length 5k
|
||||
|
||||
DataQuery::DataQuery()
|
||||
{}
|
||||
|
||||
DataQuery& DataQuery::Reset()
|
||||
{
|
||||
str_ = "";
|
||||
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);
|
||||
}
|
||||
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);
|
||||
}
|
||||
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);
|
||||
}
|
||||
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);
|
||||
}
|
||||
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);
|
||||
}
|
||||
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);
|
||||
}
|
||||
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);
|
||||
}
|
||||
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);
|
||||
}
|
||||
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);
|
||||
}
|
||||
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);
|
||||
}
|
||||
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);
|
||||
}
|
||||
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);
|
||||
}
|
||||
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);
|
||||
}
|
||||
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);
|
||||
}
|
||||
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);
|
||||
}
|
||||
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);
|
||||
}
|
||||
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);
|
||||
}
|
||||
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);
|
||||
}
|
||||
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);
|
||||
}
|
||||
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);
|
||||
}
|
||||
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);
|
||||
}
|
||||
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);
|
||||
}
|
||||
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);
|
||||
}
|
||||
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);
|
||||
}
|
||||
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);
|
||||
}
|
||||
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);
|
||||
}
|
||||
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);
|
||||
}
|
||||
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);
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
DataQuery& DataQuery::InInt(const std::string &field, const std::vector<int> &valueList)
|
||||
{
|
||||
std::string myField = field;
|
||||
if (ValidateField(myField)) {
|
||||
AppendCommonList(IN, TYPE_INTEGER, myField, valueList);
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
DataQuery& DataQuery::InLong(const std::string &field, const std::vector<int64_t> &valueList)
|
||||
{
|
||||
std::string myField = field;
|
||||
if (ValidateField(myField)) {
|
||||
AppendCommonList(IN, TYPE_LONG, myField, valueList);
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
DataQuery& DataQuery::InDouble(const std::string &field, const std::vector<double> &valueList)
|
||||
{
|
||||
std::string myField = field;
|
||||
if (ValidateField(myField)) {
|
||||
AppendCommonList(IN, TYPE_DOUBLE, myField, valueList);
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
DataQuery& DataQuery::InString(const std::string &field, const std::vector<std::string> &valueList)
|
||||
{
|
||||
std::string myField = field;
|
||||
std::vector<std::string> myValueList(valueList);
|
||||
if (ValidateField(myField)) {
|
||||
AppendCommonListString(IN, TYPE_STRING, myField, myValueList);
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
DataQuery& DataQuery::NotInInt(const std::string &field, const std::vector<int> &valueList)
|
||||
{
|
||||
std::string myField = field;
|
||||
if (ValidateField(myField)) {
|
||||
AppendCommonList(NOT_IN, TYPE_INTEGER, myField, valueList);
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
DataQuery& DataQuery::NotInLong(const std::string &field, const std::vector<int64_t> &valueList)
|
||||
{
|
||||
std::string myField = field;
|
||||
if (ValidateField(myField)) {
|
||||
AppendCommonList(NOT_IN, TYPE_LONG, myField, valueList);
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
DataQuery& DataQuery::NotInDouble(const std::string &field, const std::vector<double> &valueList)
|
||||
{
|
||||
std::string myField = field;
|
||||
if (ValidateField(myField)) {
|
||||
AppendCommonList(NOT_IN, TYPE_DOUBLE, myField, valueList);
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
DataQuery& DataQuery::NotInString(const std::string &field, const std::vector<std::string> &valueList)
|
||||
{
|
||||
std::string myField = field;
|
||||
std::vector<std::string> myValueList(valueList);
|
||||
if (ValidateField(myField)) {
|
||||
AppendCommonListString(NOT_IN, TYPE_STRING, myField, myValueList);
|
||||
}
|
||||
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);
|
||||
}
|
||||
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);
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
DataQuery& DataQuery::And()
|
||||
{
|
||||
str_.append(SPACE);
|
||||
str_.append(AND);
|
||||
return *this;
|
||||
}
|
||||
|
||||
DataQuery& DataQuery::Or()
|
||||
{
|
||||
str_.append(SPACE);
|
||||
str_.append(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);
|
||||
}
|
||||
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);
|
||||
}
|
||||
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));
|
||||
return *this;
|
||||
}
|
||||
|
||||
DataQuery& DataQuery::BeginGroup()
|
||||
{
|
||||
str_.append(SPACE);
|
||||
str_.append(BEGIN_GROUP);
|
||||
return *this;
|
||||
}
|
||||
|
||||
DataQuery& DataQuery::EndGroup()
|
||||
{
|
||||
str_.append(SPACE);
|
||||
str_.append(END_GROUP);
|
||||
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);
|
||||
}
|
||||
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);
|
||||
}
|
||||
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
|
@ -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 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;
|
||||
}
|
||||
DistributedDB::DBStatus ret = delegate_->GetKvStoreDiskSize(storeId, size);
|
||||
if (ret != DistributedDB::DBStatus::OK) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void GetKvStoreKeys(std::vector<DistributedKv::StoreInfo> &entries) override
|
||||
{
|
||||
}
|
||||
|
||||
bool IsDestruct()
|
||||
{
|
||||
return delegate_ == nullptr;
|
||||
}
|
||||
private:
|
||||
DistributedDB::KvStoreDelegateManager *delegate_ {};
|
||||
};
|
||||
} // namespace AppDistributedKv
|
||||
} // namespace OHOS
|
||||
#endif // DISTRIBUTEDDATAMGR_DELEGATE_MGR_CALLBACK_H
|
@ -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);
|
||||
}
|
||||
}
|
||||
}
|
@ -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
|
@ -0,0 +1,333 @@
|
||||
/*
|
||||
* 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 "constant.h"
|
||||
#include "ikvstore_data_service.h"
|
||||
#include "kvstore_client.h"
|
||||
#include "kvstore_service_death_notifier.h"
|
||||
#include "log_print.h"
|
||||
#include "refbase.h"
|
||||
#include "single_kvstore_client.h"
|
||||
#include "dds_trace.h"
|
||||
#include "communication_provider.h"
|
||||
#include "device_status_change_listener_client.h"
|
||||
|
||||
namespace OHOS {
|
||||
namespace DistributedKv {
|
||||
DistributedKvDataManager::DistributedKvDataManager()
|
||||
{}
|
||||
|
||||
DistributedKvDataManager::~DistributedKvDataManager()
|
||||
{}
|
||||
|
||||
void DistributedKvDataManager::GetKvStore(const Options &options, const AppId &appId, const StoreId &storeId,
|
||||
std::function<void(Status, std::unique_ptr<KvStore>)> callback)
|
||||
{
|
||||
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__), true);
|
||||
|
||||
std::string storeIdTmp = Constant::TrimCopy<std::string>(storeId.storeId);
|
||||
if (storeIdTmp.size() == 0 || storeIdTmp.size() > Constant::MAX_STORE_ID_LENGTH) {
|
||||
callback(Status::INVALID_ARGUMENT, nullptr);
|
||||
ZLOGE("invalid storeId.");
|
||||
return;
|
||||
}
|
||||
|
||||
KvStoreServiceDeathNotifier::SetAppId(appId);
|
||||
sptr<IKvStoreDataService> kvDataServiceProxy = KvStoreServiceDeathNotifier::GetDistributedKvDataService();
|
||||
Status status = Status::SERVER_UNAVAILABLE;
|
||||
if (kvDataServiceProxy == nullptr) {
|
||||
ZLOGE("proxy is nullptr.");
|
||||
callback(status, nullptr);
|
||||
return;
|
||||
}
|
||||
|
||||
ZLOGD("call proxy.");
|
||||
sptr<IKvStoreImpl> proxyTmp;
|
||||
status = kvDataServiceProxy->GetKvStore(options, appId, storeId,
|
||||
[&](sptr<IKvStoreImpl> proxy) { proxyTmp = std::move(proxy); });
|
||||
if (status == Status::RECOVER_SUCCESS) {
|
||||
ZLOGE("proxy recover success: %d", static_cast<int>(status));
|
||||
callback(status, std::make_unique<KvStoreClient>(std::move(proxyTmp), storeIdTmp));
|
||||
return;
|
||||
}
|
||||
|
||||
if (status != Status::SUCCESS) {
|
||||
ZLOGE("proxy return error: %d", static_cast<int>(status));
|
||||
callback(status, nullptr);
|
||||
return;
|
||||
}
|
||||
|
||||
if (proxyTmp == nullptr) {
|
||||
ZLOGE("proxy return nullptr.");
|
||||
callback(status, nullptr);
|
||||
return;
|
||||
}
|
||||
|
||||
callback(status, std::make_unique<KvStoreClient>(std::move(proxyTmp), storeIdTmp));
|
||||
}
|
||||
|
||||
void DistributedKvDataManager::GetSingleKvStore(const Options &options, const AppId &appId, const StoreId &storeId,
|
||||
std::function<void(Status, std::unique_ptr<SingleKvStore>)> callback)
|
||||
{
|
||||
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__), true);
|
||||
|
||||
std::string storeIdTmp = Constant::TrimCopy<std::string>(storeId.storeId);
|
||||
if (storeIdTmp.size() == 0 || storeIdTmp.size() > Constant::MAX_STORE_ID_LENGTH) {
|
||||
callback(Status::INVALID_ARGUMENT, nullptr);
|
||||
ZLOGE("invalid storeId.");
|
||||
return;
|
||||
}
|
||||
|
||||
KvStoreServiceDeathNotifier::SetAppId(appId);
|
||||
sptr<IKvStoreDataService> kvDataServiceProxy = KvStoreServiceDeathNotifier::GetDistributedKvDataService();
|
||||
Status status = Status::SERVER_UNAVAILABLE;
|
||||
if (kvDataServiceProxy == nullptr) {
|
||||
ZLOGE("proxy is nullptr.");
|
||||
callback(status, nullptr);
|
||||
return;
|
||||
}
|
||||
|
||||
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));
|
||||
callback(status, std::make_unique<SingleKvStoreClient>(std::move(proxyTmp), storeIdTmp));
|
||||
return;
|
||||
}
|
||||
|
||||
if (status != Status::SUCCESS) {
|
||||
ZLOGE("proxy return error: %d", static_cast<int>(status));
|
||||
callback(status, nullptr);
|
||||
return;
|
||||
}
|
||||
|
||||
if (proxyTmp == nullptr) {
|
||||
ZLOGE("proxy return nullptr.");
|
||||
callback(status, nullptr);
|
||||
return;
|
||||
}
|
||||
|
||||
callback(status, std::make_unique<SingleKvStoreClient>(std::move(proxyTmp), storeIdTmp));
|
||||
}
|
||||
|
||||
void DistributedKvDataManager::GetAllKvStoreId(const AppId &appId,
|
||||
std::function<void(Status, std::vector<StoreId> &)> callback)
|
||||
{
|
||||
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
|
||||
|
||||
KvStoreServiceDeathNotifier::SetAppId(appId);
|
||||
sptr<IKvStoreDataService> kvDataServiceProxy = KvStoreServiceDeathNotifier::GetDistributedKvDataService();
|
||||
if (kvDataServiceProxy == nullptr) {
|
||||
ZLOGE("proxy is nullptr.");
|
||||
std::vector<StoreId> storeIds;
|
||||
callback(Status::SERVER_UNAVAILABLE, storeIds);
|
||||
return;
|
||||
}
|
||||
|
||||
kvDataServiceProxy->GetAllKvStoreId(appId, callback);
|
||||
}
|
||||
|
||||
Status DistributedKvDataManager::CloseKvStore(const AppId &appId, const StoreId &storeId,
|
||||
std::unique_ptr<KvStore> kvStorePtr)
|
||||
{
|
||||
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
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::unique_ptr<SingleKvStore> kvStorePtr)
|
||||
{
|
||||
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
|
||||
|
||||
if (kvStorePtr == nullptr) {
|
||||
ZLOGE("kvStorePtr is nullptr.");
|
||||
return Status::INVALID_ARGUMENT;
|
||||
}
|
||||
KvStoreServiceDeathNotifier::SetAppId(appId);
|
||||
sptr<IKvStoreDataService> kvDataServiceProxy = KvStoreServiceDeathNotifier::GetDistributedKvDataService();
|
||||
if (kvDataServiceProxy != nullptr) {
|
||||
return kvDataServiceProxy->CloseKvStore(appId, kvStorePtr->GetStoreId());
|
||||
}
|
||||
ZLOGE("proxy is nullptr.");
|
||||
return Status::SERVER_UNAVAILABLE;
|
||||
}
|
||||
|
||||
Status DistributedKvDataManager::CloseAllKvStore(const AppId &appId)
|
||||
{
|
||||
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
|
||||
|
||||
KvStoreServiceDeathNotifier::SetAppId(appId);
|
||||
sptr<IKvStoreDataService> kvDataServiceProxy = KvStoreServiceDeathNotifier::GetDistributedKvDataService();
|
||||
if (kvDataServiceProxy != nullptr) {
|
||||
return kvDataServiceProxy->CloseAllKvStore(appId);
|
||||
}
|
||||
ZLOGE("proxy is nullptr.");
|
||||
return Status::SERVER_UNAVAILABLE;
|
||||
}
|
||||
|
||||
Status DistributedKvDataManager::DeleteKvStore(const AppId &appId, const StoreId &storeId)
|
||||
{
|
||||
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
|
||||
|
||||
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);
|
||||
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)
|
||||
{
|
||||
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
|
||||
|
||||
KvStoreServiceDeathNotifier::SetAppId(appId);
|
||||
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;
|
||||
}
|
||||
std::shared_ptr<KvStoreDeathRecipientImpl> kvStoreDeathRecipientImpl =
|
||||
std::make_shared<KvStoreDeathRecipientImpl>(kvStoreDeathRecipient);
|
||||
if (kvStoreDeathRecipientImpl != nullptr) {
|
||||
KvStoreServiceDeathNotifier::AddServiceDeathWatcher(kvStoreDeathRecipientImpl);
|
||||
} else {
|
||||
ZLOGW("Register KvStoreService Death Recipient failed.");
|
||||
}
|
||||
}
|
||||
|
||||
void DistributedKvDataManager::UnRegisterKvStoreServiceDeathRecipient(
|
||||
std::shared_ptr<KvStoreDeathRecipient> kvStoreDeathRecipient)
|
||||
{
|
||||
ZLOGD("begin");
|
||||
if (kvStoreDeathRecipient == nullptr) {
|
||||
ZLOGW("UnRegister KvStoreService Death Recipient input is null.");
|
||||
return;
|
||||
}
|
||||
std::shared_ptr<KvStoreDeathRecipientImpl> kvStoreDeathRecipientImpl =
|
||||
std::make_shared<KvStoreDeathRecipientImpl>(kvStoreDeathRecipient);
|
||||
if (kvStoreDeathRecipientImpl != nullptr) {
|
||||
KvStoreServiceDeathNotifier::RemoveServiceDeathWatcher(kvStoreDeathRecipientImpl);
|
||||
} else {
|
||||
ZLOGW("UnRegister KvStoreService Death Recipient failed.");
|
||||
}
|
||||
}
|
||||
|
||||
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->GetDeviceList(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
|
@ -0,0 +1,76 @@
|
||||
/*
|
||||
* 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 "log_print.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)) || !results.Marshalling(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("%d", code);
|
||||
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 *deviceInfoPtr = DeviceInfo::UnMarshalling(data);
|
||||
if (deviceInfoPtr != nullptr) {
|
||||
OnChange(*deviceInfoPtr, type);
|
||||
delete deviceInfoPtr;
|
||||
} else {
|
||||
ZLOGW("device info is null");
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
default:
|
||||
return IPCObjectStub::OnRemoteRequest(code, data, reply, option);
|
||||
}
|
||||
}
|
||||
} // namespace DistributedKv
|
||||
} // namespace OHOS
|
749
frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore.cpp
Executable file
749
frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore.cpp
Executable file
@ -0,0 +1,749 @@
|
||||
/*
|
||||
* 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 "KvStoreImplProxy"
|
||||
|
||||
#include "ikvstore.h"
|
||||
#include <cinttypes>
|
||||
#include "message_parcel.h"
|
||||
#include "constant.h"
|
||||
#include "log_print.h"
|
||||
|
||||
namespace OHOS {
|
||||
namespace DistributedKv {
|
||||
enum {
|
||||
GETKVSTORESNAPSHOT,
|
||||
RELEASEKVSTORESNAPSHOT,
|
||||
PUT,
|
||||
PUTBATCH,
|
||||
DELETE,
|
||||
DELETEBATCH,
|
||||
CLEAR,
|
||||
STARTTRANSACTION,
|
||||
COMMIT,
|
||||
ROLLBACK,
|
||||
SUBSCRIBEKVSTORE,
|
||||
UNSUBSCRIBEKVSTORE,
|
||||
};
|
||||
|
||||
KvStoreImplProxy::KvStoreImplProxy(const sptr<IRemoteObject> &impl) : IRemoteProxy<IKvStoreImpl>(impl)
|
||||
{}
|
||||
|
||||
void KvStoreImplProxy::GetKvStoreSnapshot(sptr<IKvStoreObserver> observer,
|
||||
std::function<void(Status, sptr<IKvStoreSnapshotImpl>)> callback)
|
||||
{
|
||||
if (observer == nullptr) {
|
||||
callback(Status::INVALID_ARGUMENT, nullptr);
|
||||
return;
|
||||
}
|
||||
MessageParcel data;
|
||||
MessageParcel reply;
|
||||
if (!data.WriteInterfaceToken(KvStoreImplProxy::GetDescriptor())) {
|
||||
ZLOGE("write descriptor failed");
|
||||
return;
|
||||
}
|
||||
if (!data.WriteRemoteObject(observer->AsObject().GetRefPtr())) {
|
||||
ZLOGW("get snapshot fail.");
|
||||
callback(Status::IPC_ERROR, nullptr);
|
||||
return;
|
||||
}
|
||||
MessageOption mo { MessageOption::TF_SYNC };
|
||||
int32_t error = Remote()->SendRequest(GETKVSTORESNAPSHOT, data, reply, mo);
|
||||
if (error != 0) {
|
||||
ZLOGW("SendRequest returned %d", error);
|
||||
callback(Status::IPC_ERROR, nullptr);
|
||||
return;
|
||||
}
|
||||
Status status = static_cast<Status>(reply.ReadInt32());
|
||||
if (status == Status::SUCCESS) {
|
||||
sptr<IRemoteObject> remote = reply.ReadRemoteObject();
|
||||
if (remote == nullptr) {
|
||||
callback(status, nullptr);
|
||||
return;
|
||||
}
|
||||
sptr<IKvStoreSnapshotImpl> kvstoreImplProxy = iface_cast<IKvStoreSnapshotImpl>(remote);
|
||||
callback(status, std::move(kvstoreImplProxy));
|
||||
} else {
|
||||
callback(status, nullptr);
|
||||
}
|
||||
}
|
||||
|
||||
Status KvStoreImplProxy::ReleaseKvStoreSnapshot(sptr<IKvStoreSnapshotImpl> kvStoreSnapshotPtr)
|
||||
{
|
||||
if (kvStoreSnapshotPtr == nullptr) {
|
||||
ZLOGW("input snapshot ptr is null");
|
||||
return Status::INVALID_ARGUMENT;
|
||||
}
|
||||
MessageParcel data;
|
||||
MessageParcel reply;
|
||||
if (!data.WriteInterfaceToken(KvStoreImplProxy::GetDescriptor())) {
|
||||
ZLOGE("write descriptor failed");
|
||||
return Status::IPC_ERROR;
|
||||
}
|
||||
if (!data.WriteRemoteObject(kvStoreSnapshotPtr->AsObject().GetRefPtr())) {
|
||||
ZLOGW("write input snapshot ptr failed.");
|
||||
return Status::IPC_ERROR;
|
||||
}
|
||||
|
||||
MessageOption mo { MessageOption::TF_SYNC };
|
||||
int32_t error = Remote()->SendRequest(RELEASEKVSTORESNAPSHOT, data, reply, mo);
|
||||
if (error != 0) {
|
||||
ZLOGW("SendRequest returned %d", error);
|
||||
return Status::IPC_ERROR;
|
||||
}
|
||||
return static_cast<Status>(reply.ReadInt32());
|
||||
}
|
||||
|
||||
Status KvStoreImplProxy::Put(const Key &key, const Value &value)
|
||||
{
|
||||
ZLOGD("proxy put");
|
||||
MessageParcel data, reply;
|
||||
if (!data.WriteInterfaceToken(KvStoreImplProxy::GetDescriptor())) {
|
||||
ZLOGE("write descriptor failed");
|
||||
return Status::IPC_ERROR;
|
||||
}
|
||||
if (!data.SetMaxCapacity(Constant::MAX_IPC_CAPACITY)) {
|
||||
ZLOGW("write capacity failed.");
|
||||
return Status::IPC_ERROR;
|
||||
}
|
||||
|
||||
int bufferSize = key.RawSize() + value.RawSize();
|
||||
if (!data.WriteInt32(bufferSize)) {
|
||||
ZLOGW("write size failed.");
|
||||
return Status::IPC_ERROR;
|
||||
}
|
||||
if (bufferSize < Constant::SWITCH_RAW_DATA_SIZE) {
|
||||
if (!data.WriteParcelable(&key) || !data.WriteParcelable(&value)) {
|
||||
ZLOGW("write key or value failed.");
|
||||
return Status::IPC_ERROR;
|
||||
}
|
||||
|
||||
MessageOption mo { MessageOption::TF_SYNC };
|
||||
int error = Remote()->SendRequest(PUT, data, reply, mo);
|
||||
if (error != 0) {
|
||||
ZLOGW("SendRequest failed with error code %d", error);
|
||||
return Status::IPC_ERROR;
|
||||
}
|
||||
return static_cast<Status>(reply.ReadInt32());
|
||||
}
|
||||
ZLOGI("putting large data.");
|
||||
std::unique_ptr<uint8_t, void(*)(uint8_t *)> buffer(new uint8_t[bufferSize], [](uint8_t *ptr) { delete[] ptr; });
|
||||
if (buffer == nullptr) {
|
||||
ZLOGW("buffer is null");
|
||||
return Status::ERROR;
|
||||
}
|
||||
int bufferLeftSize = bufferSize;
|
||||
uint8_t *cursor = buffer.get();
|
||||
if (!key.WriteToBuffer(cursor, bufferLeftSize) ||
|
||||
!value.WriteToBuffer(cursor, bufferLeftSize) ||
|
||||
!data.WriteRawData(buffer.get(), bufferSize)) {
|
||||
ZLOGW("write failed");
|
||||
return Status::ERROR;
|
||||
}
|
||||
// Parcel before IPC:
|
||||
// buffer: options | bufferSize
|
||||
// rawdata: keySize | key | ValueSize | value
|
||||
MessageOption mo { MessageOption::TF_SYNC };
|
||||
int32_t error = Remote()->SendRequest(PUT, data, reply, mo);
|
||||
if (error != 0) {
|
||||
ZLOGW("SendRequest returned %d", error);
|
||||
return Status::IPC_ERROR;
|
||||
}
|
||||
return static_cast<Status>(reply.ReadInt32());
|
||||
}
|
||||
|
||||
Status KvStoreImplProxy::PutBatch(const std::vector<Entry> &entries)
|
||||
{
|
||||
MessageParcel data, reply;
|
||||
if (!data.WriteInterfaceToken(KvStoreImplProxy::GetDescriptor())) {
|
||||
ZLOGE("write descriptor failed");
|
||||
return Status::IPC_ERROR;
|
||||
}
|
||||
if (!data.SetMaxCapacity(Constant::MAX_IPC_CAPACITY)) {
|
||||
ZLOGW("set capacity failed.");
|
||||
return Status::IPC_ERROR;
|
||||
}
|
||||
if (!data.WriteInt32(entries.size())) {
|
||||
ZLOGW("write entries size failed.");
|
||||
return Status::IPC_ERROR;
|
||||
}
|
||||
|
||||
int64_t bufferSize = 0;
|
||||
for (const auto &item : entries) {
|
||||
if (item.key.Size() > Constant::MAX_KEY_LENGTH || item.value.Size() > Constant::MAX_VALUE_LENGTH) {
|
||||
return Status::INVALID_ARGUMENT;
|
||||
}
|
||||
bufferSize += item.key.RawSize() + item.value.RawSize();
|
||||
}
|
||||
if (!data.WriteInt32(bufferSize)) {
|
||||
ZLOGW("write buffer size failed.");
|
||||
return Status::IPC_ERROR;
|
||||
}
|
||||
if (bufferSize < Constant::SWITCH_RAW_DATA_SIZE) {
|
||||
for (const auto &item : entries) {
|
||||
if (!data.WriteParcelable(&item)) {
|
||||
ZLOGW("write parcel failed.");
|
||||
return Status::IPC_ERROR;
|
||||
}
|
||||
}
|
||||
MessageOption mo { MessageOption::TF_SYNC };
|
||||
if (Remote()->SendRequest(PUTBATCH, data, reply, mo) != 0) {
|
||||
return Status::IPC_ERROR;
|
||||
}
|
||||
return static_cast<Status>(reply.ReadInt32());
|
||||
}
|
||||
ZLOGI("putting large data.");
|
||||
if (bufferSize > static_cast<int64_t>(reply.GetRawDataCapacity())) {
|
||||
ZLOGW("batch size larger than Messageparcel limit.(%" PRIu64")", bufferSize);
|
||||
return Status::INVALID_ARGUMENT;
|
||||
}
|
||||
std::unique_ptr<uint8_t, void(*)(uint8_t *)> buffer(new uint8_t[bufferSize], [](uint8_t *ptr) { delete[] ptr; });
|
||||
if (buffer == nullptr) {
|
||||
ZLOGW("buffer is null");
|
||||
return Status::ERROR;
|
||||
}
|
||||
int bufferLeftSize = bufferSize;
|
||||
uint8_t *cursor = buffer.get();
|
||||
for (const auto &item : entries) {
|
||||
if (!item.key.WriteToBuffer(cursor, bufferLeftSize) ||
|
||||
!item.value.WriteToBuffer(cursor, bufferLeftSize)) {
|
||||
ZLOGW("write item failed.");
|
||||
}
|
||||
}
|
||||
if (!data.WriteRawData(buffer.get(), bufferSize)) {
|
||||
ZLOGW("write failed");
|
||||
return Status::ERROR;
|
||||
}
|
||||
MessageOption mo { MessageOption::TF_SYNC };
|
||||
int32_t error = Remote()->SendRequest(PUTBATCH, data, reply, mo);
|
||||
if (error != 0) {
|
||||
ZLOGW("SendRequest returned %d", error);
|
||||
return Status::IPC_ERROR;
|
||||
}
|
||||
return static_cast<Status>(reply.ReadInt32());
|
||||
}
|
||||
|
||||
Status KvStoreImplProxy::Delete(const Key &key)
|
||||
{
|
||||
MessageParcel data, reply;
|
||||
if (!data.WriteInterfaceToken(KvStoreImplProxy::GetDescriptor())) {
|
||||
ZLOGE("write descriptor failed");
|
||||
return Status::IPC_ERROR;
|
||||
}
|
||||
if (!data.WriteParcelable(&key)) {
|
||||
ZLOGW("write key failed.");
|
||||
return Status::IPC_ERROR;
|
||||
}
|
||||
MessageOption mo { MessageOption::TF_SYNC };
|
||||
int32_t error = Remote()->SendRequest(DELETE, data, reply, mo);
|
||||
if (error != 0) {
|
||||
ZLOGW("SendRequest returned %d", error);
|
||||
return Status::IPC_ERROR;
|
||||
}
|
||||
return static_cast<Status>(reply.ReadInt32());
|
||||
}
|
||||
|
||||
Status KvStoreImplProxy::DeleteBatch(const std::vector<Key> &keys)
|
||||
{
|
||||
MessageParcel data, reply;
|
||||
if (!data.WriteInterfaceToken(KvStoreImplProxy::GetDescriptor())) {
|
||||
ZLOGE("write descriptor failed");
|
||||
return Status::IPC_ERROR;
|
||||
}
|
||||
if (!data.SetMaxCapacity(Constant::MAX_IPC_CAPACITY)) {
|
||||
ZLOGW("set capacity failed.");
|
||||
return Status::IPC_ERROR;
|
||||
}
|
||||
if (!data.WriteInt32(keys.size())) {
|
||||
ZLOGW("write keys size failed.");
|
||||
return Status::IPC_ERROR;
|
||||
}
|
||||
for (const auto &item : keys) {
|
||||
if (item.Size() > Constant::MAX_KEY_LENGTH) {
|
||||
ZLOGW("Delete key size larger than key size limit");
|
||||
return Status::INVALID_ARGUMENT;
|
||||
}
|
||||
if (!data.WriteParcelable(&item)) {
|
||||
ZLOGW("write parcel failed");
|
||||
return Status::IPC_ERROR;
|
||||
}
|
||||
}
|
||||
MessageOption mo { MessageOption::TF_SYNC };
|
||||
int32_t error = Remote()->SendRequest(DELETEBATCH, data, reply, mo);
|
||||
if (error != 0) {
|
||||
ZLOGW("SendRequest returned %d", error);
|
||||
return Status::IPC_ERROR;
|
||||
}
|
||||
return static_cast<Status>(reply.ReadInt32());
|
||||
}
|
||||
|
||||
Status KvStoreImplProxy::Clear()
|
||||
{
|
||||
MessageParcel data, reply;
|
||||
if (!data.WriteInterfaceToken(KvStoreImplProxy::GetDescriptor())) {
|
||||
ZLOGE("write descriptor failed");
|
||||
return Status::IPC_ERROR;
|
||||
}
|
||||
MessageOption mo { MessageOption::TF_SYNC };
|
||||
int32_t error = Remote()->SendRequest(CLEAR, data, reply, mo);
|
||||
if (error != 0) {
|
||||
ZLOGW("SendRequest returned %d", error);
|
||||
return Status::IPC_ERROR;
|
||||
}
|
||||
return static_cast<Status>(reply.ReadInt32());
|
||||
}
|
||||
|
||||
Status KvStoreImplProxy::StartTransaction()
|
||||
{
|
||||
MessageParcel data, reply;
|
||||
if (!data.WriteInterfaceToken(KvStoreImplProxy::GetDescriptor())) {
|
||||
ZLOGE("write descriptor failed");
|
||||
return Status::IPC_ERROR;
|
||||
}
|
||||
MessageOption mo { MessageOption::TF_SYNC };
|
||||
int32_t error = Remote()->SendRequest(STARTTRANSACTION, data, reply, mo);
|
||||
if (error != 0) {
|
||||
ZLOGW("SendRequest returned %d", error);
|
||||
return Status::IPC_ERROR;
|
||||
}
|
||||
return static_cast<Status>(reply.ReadInt32());
|
||||
}
|
||||
|
||||
Status KvStoreImplProxy::Commit()
|
||||
{
|
||||
MessageParcel data, reply;
|
||||
if (!data.WriteInterfaceToken(KvStoreImplProxy::GetDescriptor())) {
|
||||
ZLOGE("write descriptor failed");
|
||||
return Status::IPC_ERROR;
|
||||
}
|
||||
MessageOption mo { MessageOption::TF_SYNC };
|
||||
int32_t error = Remote()->SendRequest(COMMIT, data, reply, mo);
|
||||
if (error != 0) {
|
||||
ZLOGW("SendRequest returned %d", error);
|
||||
return Status::IPC_ERROR;
|
||||
}
|
||||
return static_cast<Status>(reply.ReadInt32());
|
||||
}
|
||||
|
||||
Status KvStoreImplProxy::Rollback()
|
||||
{
|
||||
MessageParcel data, reply;
|
||||
if (!data.WriteInterfaceToken(KvStoreImplProxy::GetDescriptor())) {
|
||||
ZLOGE("write descriptor failed");
|
||||
return Status::IPC_ERROR;
|
||||
}
|
||||
MessageOption mo { MessageOption::TF_SYNC };
|
||||
int32_t error = Remote()->SendRequest(ROLLBACK, data, reply, mo);
|
||||
if (error != 0) {
|
||||
ZLOGW("SendRequest returned %d", error);
|
||||
return Status::IPC_ERROR;
|
||||
}
|
||||
return static_cast<Status>(reply.ReadInt32());
|
||||
}
|
||||
|
||||
Status KvStoreImplProxy::SubscribeKvStore(const SubscribeType subscribeType, sptr<IKvStoreObserver> observer)
|
||||
{
|
||||
if (observer == nullptr) {
|
||||
ZLOGW("observer is invalid.");
|
||||
return Status::INVALID_ARGUMENT;
|
||||
}
|
||||
MessageParcel data;
|
||||
MessageParcel reply;
|
||||
if (!data.WriteInterfaceToken(KvStoreImplProxy::GetDescriptor())) {
|
||||
ZLOGE("write descriptor failed");
|
||||
return Status::IPC_ERROR;
|
||||
}
|
||||
if (!data.WriteInt32(static_cast<int>(subscribeType)) ||
|
||||
!data.WriteRemoteObject(observer->AsObject().GetRefPtr())) {
|
||||
ZLOGW("subscribe type failed.");
|
||||
return Status::IPC_ERROR;
|
||||
}
|
||||
|
||||
MessageOption mo { MessageOption::TF_SYNC };
|
||||
int32_t error = Remote()->SendRequest(SUBSCRIBEKVSTORE, data, reply, mo);
|
||||
if (error != 0) {
|
||||
ZLOGW("SendRequest returned %d", error);
|
||||
return Status::IPC_ERROR;
|
||||
}
|
||||
return static_cast<Status>(reply.ReadInt32());
|
||||
}
|
||||
|
||||
Status KvStoreImplProxy::UnSubscribeKvStore(const SubscribeType subscribeType, sptr<IKvStoreObserver> observer)
|
||||
{
|
||||
if (observer == nullptr) {
|
||||
return Status::INVALID_ARGUMENT;
|
||||
}
|
||||
|
||||
MessageParcel data;
|
||||
MessageParcel reply;
|
||||
if (!data.WriteInterfaceToken(KvStoreImplProxy::GetDescriptor())) {
|
||||
ZLOGE("write descriptor failed");
|
||||
return Status::IPC_ERROR;
|
||||
}
|
||||
if (!data.WriteInt32(static_cast<int>(subscribeType)) ||
|
||||
!data.WriteRemoteObject(observer->AsObject().GetRefPtr())) {
|
||||
ZLOGW("unsubscribe type failed.");
|
||||
return Status::IPC_ERROR;
|
||||
}
|
||||
MessageOption mo { MessageOption::TF_SYNC };
|
||||
int32_t error = Remote()->SendRequest(UNSUBSCRIBEKVSTORE, data, reply, mo);
|
||||
if (error != 0) {
|
||||
ZLOGW("SendRequest returned %d", error);
|
||||
return Status::IPC_ERROR;
|
||||
}
|
||||
return static_cast<Status>(reply.ReadInt32());
|
||||
}
|
||||
|
||||
int32_t KvStoreImplStub::GetKvStoreSnapshotOnRemote(MessageParcel &data, MessageParcel &reply)
|
||||
{
|
||||
sptr<IRemoteObject> remote = data.ReadRemoteObject();
|
||||
if (remote == nullptr) {
|
||||
if (!reply.WriteInt32(static_cast<int>(Status::INVALID_ARGUMENT))) {
|
||||
ZLOGW("write obj failed.");
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
sptr<IKvStoreObserver> kvStoreObserverProxy = iface_cast<IKvStoreObserver>(remote);
|
||||
sptr<IKvStoreSnapshotImpl> proxyTmp;
|
||||
Status statusTmp;
|
||||
GetKvStoreSnapshot(kvStoreObserverProxy, [&](Status status, sptr<IKvStoreSnapshotImpl> proxy) {
|
||||
statusTmp = status;
|
||||
proxyTmp = std::move(proxy);
|
||||
});
|
||||
if (!reply.WriteInt32(static_cast<int>(statusTmp))) {
|
||||
ZLOGW("write get snapshot result failed.");
|
||||
return -1;
|
||||
}
|
||||
if (statusTmp == Status::SUCCESS && proxyTmp != nullptr) {
|
||||
if (!reply.WriteRemoteObject(proxyTmp->AsObject().GetRefPtr())) {
|
||||
ZLOGW("write strong failed.");
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
int32_t KvStoreImplStub::ReleaseKvStoreSnapshotOnRemote(MessageParcel &data, MessageParcel &reply)
|
||||
{
|
||||
sptr<IRemoteObject> remote = data.ReadRemoteObject();
|
||||
if (remote == nullptr) {
|
||||
ZLOGW("kvstoreSnapshotProxy nullptr after ipc");
|
||||
if (!reply.WriteInt32(static_cast<int>(Status::IPC_ERROR))) {
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
sptr<IKvStoreSnapshotImpl> kvStoreSnapshotProxy = iface_cast<IKvStoreSnapshotImpl>(remote);
|
||||
Status status = ReleaseKvStoreSnapshot(kvStoreSnapshotProxy);
|
||||
if (!reply.WriteInt32(static_cast<int>(status))) {
|
||||
ZLOGW("write release snapshot failed.");
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
int32_t KvStoreImplStub::PutOnRemoteRequest(MessageParcel &data, MessageParcel &reply)
|
||||
{
|
||||
if (!data.SetMaxCapacity(Constant::MAX_IPC_CAPACITY)) {
|
||||
ZLOGW("write capacity failed");
|
||||
return -1;
|
||||
}
|
||||
const int bufferSize = data.ReadInt32();
|
||||
ZLOGD("bufferSize %d", bufferSize);
|
||||
if (bufferSize < Constant::SWITCH_RAW_DATA_SIZE) {
|
||||
sptr<Key> key = data.ReadParcelable<Key>();
|
||||
sptr<Value> value = data.ReadParcelable<Value>();
|
||||
if (key == nullptr || value == nullptr) {
|
||||
if (!reply.WriteInt32(static_cast<int>(Status::INVALID_ARGUMENT))) {
|
||||
ZLOGW("write key or val status failed.");
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
Status status = Put(*key, *value);
|
||||
if (!reply.WriteInt32(static_cast<int>(status))) {
|
||||
ZLOGW("write ret status failed.");
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
// this memory is managed by MassageParcel, DO NOT free here
|
||||
const uint8_t *buffer = reinterpret_cast<const uint8_t *>(data.ReadRawData(bufferSize));
|
||||
if (buffer == nullptr) {
|
||||
ZLOGW("buffer is null");
|
||||
if (!reply.WriteInt32(static_cast<int>(Status::IPC_ERROR))) {
|
||||
ZLOGW("write buffer status failed.");
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
int bufferLeftSize = bufferSize;
|
||||
const uint8_t *cursor = buffer;
|
||||
Key key;
|
||||
Value value;
|
||||
if (!key.ReadFromBuffer(cursor, bufferLeftSize) || !value.ReadFromBuffer(cursor, bufferLeftSize)) {
|
||||
if (!reply.WriteInt32(static_cast<int>(Status::IPC_ERROR))) {
|
||||
ZLOGW("read key or value error.");
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
Status status = Put(key, value);
|
||||
if (!reply.WriteInt32(static_cast<int>(status))) {
|
||||
ZLOGW("write ret status failed.");
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
int32_t KvStoreImplStub::PutBatchOnRemoteRequest(MessageParcel &data, MessageParcel &reply)
|
||||
{
|
||||
if (!data.SetMaxCapacity(Constant::MAX_IPC_CAPACITY)) {
|
||||
ZLOGW("set batch size failed.");
|
||||
return -1;
|
||||
}
|
||||
int len = data.ReadInt32();
|
||||
if (len < 0) {
|
||||
ZLOGW("invalid status. len %d", len);
|
||||
if (!reply.WriteInt32(static_cast<int>(Status::INVALID_ARGUMENT))) {
|
||||
ZLOGW("write putbatch failed.");
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
const int bufferSize = data.ReadInt32();
|
||||
if (bufferSize < Constant::SWITCH_RAW_DATA_SIZE) {
|
||||
std::vector<Entry> entries;
|
||||
for (int i = 0; i < len; i++) {
|
||||
sptr<Entry> entry = data.ReadParcelable<Entry>();
|
||||
if (entry == nullptr) {
|
||||
ZLOGW("putbatch got null entry pointer");
|
||||
if (!reply.WriteInt32(static_cast<int>(Status::IPC_ERROR))) {
|
||||
ZLOGW("write putbatch failed.");
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
entries.push_back(*entry);
|
||||
}
|
||||
Status status = PutBatch(entries);
|
||||
if (!reply.WriteInt32(static_cast<int>(status))) {
|
||||
ZLOGW("write putbatch failed.");
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
// this memory is managed by MassageParcel, DO NOT free here
|
||||
const uint8_t *buffer = reinterpret_cast<const uint8_t *>(data.ReadRawData(bufferSize));
|
||||
if (buffer == nullptr) {
|
||||
ZLOGW("buffer is null");
|
||||
if (!reply.WriteInt32(static_cast<int>(Status::IPC_ERROR))) {
|
||||
ZLOGW("write putbatch big failed.");
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
int bufferLeftSize = bufferSize;
|
||||
const uint8_t *cursor = buffer;
|
||||
std::vector<Entry> entries;
|
||||
Entry entry;
|
||||
for (int i = 0; i < len; i++) {
|
||||
bool success = entry.key.ReadFromBuffer(cursor, bufferLeftSize);
|
||||
success = success && entry.value.ReadFromBuffer(cursor, bufferLeftSize);
|
||||
entries.push_back(std::move(entry));
|
||||
if (!success) {
|
||||
ZLOGW("get key or value failed");
|
||||
if (!reply.WriteInt32(static_cast<int>(Status::IPC_ERROR))) {
|
||||
ZLOGW("write putbatch big failed.");
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
Status status = PutBatch(entries);
|
||||
if (!reply.WriteInt32(static_cast<int>(status))) {
|
||||
ZLOGW("write putbatch big failed.");
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
int32_t KvStoreImplStub::DeleteOnRemoteRequest(MessageParcel &data, MessageParcel &reply)
|
||||
{
|
||||
sptr<Key> key = data.ReadParcelable<Key>();
|
||||
if (key == nullptr) {
|
||||
ZLOGW("key nullptr after ipc");
|
||||
if (!reply.WriteInt32(static_cast<int>(Status::INVALID_ARGUMENT))) {
|
||||
ZLOGW("write delete failed.");
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
Status status = Delete(*key);
|
||||
if (!reply.WriteInt32(static_cast<int>(status))) {
|
||||
ZLOGW("write delete failed.");
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
int32_t KvStoreImplStub::DeleteBatchOnRemoteRequest(MessageParcel &data, MessageParcel &reply)
|
||||
{
|
||||
int len = data.ReadInt32();
|
||||
if (len < 0) {
|
||||
ZLOGW("len %d invalid after ipc", len);
|
||||
if (!reply.WriteInt32(static_cast<int>(Status::INVALID_ARGUMENT))) {
|
||||
ZLOGW("write delete failed.");
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
std::vector<Key> keys;
|
||||
for (int i = 0; i < len; i++) {
|
||||
sptr<Key> key = data.ReadParcelable<Key>();
|
||||
if (key == nullptr) {
|
||||
ZLOGW("key nullptr");
|
||||
if (!reply.WriteInt32(static_cast<int>(Status::INVALID_ARGUMENT))) {
|
||||
ZLOGW("write delete failed.");
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
keys.push_back(*key);
|
||||
}
|
||||
Status status = DeleteBatch(keys);
|
||||
if (!reply.WriteInt32(static_cast<int>(status))) {
|
||||
ZLOGW("write delete failed.");
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
int32_t KvStoreImplStub::SubscribeKvStoreOnRemote(MessageParcel &data, MessageParcel &reply)
|
||||
{
|
||||
int32_t type = data.ReadInt32();
|
||||
if (type < 0) {
|
||||
return -1;
|
||||
}
|
||||
SubscribeType subscribeType = static_cast<SubscribeType>(type);
|
||||
sptr<IRemoteObject> remote = data.ReadRemoteObject();
|
||||
if (remote == nullptr) {
|
||||
ZLOGW("kvStoreObserverProxy is null");
|
||||
if (!reply.WriteInt32(static_cast<int>(Status::IPC_ERROR))) {
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
sptr<IKvStoreObserver> kvStoreObserverProxy = iface_cast<IKvStoreObserver>(remote);
|
||||
Status status = SubscribeKvStore(subscribeType, std::move(kvStoreObserverProxy));
|
||||
if (!reply.WriteInt32(static_cast<int>(status))) {
|
||||
ZLOGW("write subscribe status failed.");
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
int32_t KvStoreImplStub::UnSubscribeKvStoreOnRemote(MessageParcel &data, MessageParcel &reply)
|
||||
{
|
||||
int32_t type = data.ReadInt32();
|
||||
if (type < 0) {
|
||||
return -1;
|
||||
}
|
||||
SubscribeType subscribeType = static_cast<SubscribeType>(type);
|
||||
sptr<IRemoteObject> remote = data.ReadRemoteObject();
|
||||
if (remote == nullptr) {
|
||||
ZLOGW("unsubscribe Proxy is null");
|
||||
if (!reply.WriteInt32(static_cast<int>(Status::IPC_ERROR))) {
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
sptr<IKvStoreObserver> kvStoreObserverProxy = iface_cast<IKvStoreObserver>(remote);
|
||||
Status status = UnSubscribeKvStore(subscribeType, std::move(kvStoreObserverProxy));
|
||||
if (!reply.WriteInt32(static_cast<int>(status))) {
|
||||
ZLOGW("write unsubscribe status failed.");
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int32_t KvStoreImplStub::OnRemoteRequest(uint32_t code, MessageParcel &data,
|
||||
MessageParcel &reply, MessageOption &option)
|
||||
{
|
||||
ZLOGD("%d", code);
|
||||
std::u16string descriptor = KvStoreImplStub::GetDescriptor();
|
||||
std::u16string remoteDescriptor = data.ReadInterfaceToken();
|
||||
if (descriptor != remoteDescriptor) {
|
||||
ZLOGE("local descriptor is not equal to remote");
|
||||
return -1;
|
||||
}
|
||||
switch (code) {
|
||||
case GETKVSTORESNAPSHOT: {
|
||||
return GetKvStoreSnapshotOnRemote(data, reply);
|
||||
}
|
||||
case RELEASEKVSTORESNAPSHOT: {
|
||||
return ReleaseKvStoreSnapshotOnRemote(data, reply);
|
||||
}
|
||||
case PUT: {
|
||||
return PutOnRemoteRequest(data, reply);
|
||||
}
|
||||
case PUTBATCH: {
|
||||
return PutBatchOnRemoteRequest(data, reply);
|
||||
}
|
||||
case DELETE: {
|
||||
return DeleteOnRemoteRequest(data, reply);
|
||||
}
|
||||
case DELETEBATCH: {
|
||||
return DeleteBatchOnRemoteRequest(data, reply);
|
||||
}
|
||||
case CLEAR: {
|
||||
Status status = Clear();
|
||||
if (!reply.WriteInt32(static_cast<int>(status))) {
|
||||
ZLOGW("write clear failed.");
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
case STARTTRANSACTION: {
|
||||
Status status = StartTransaction();
|
||||
if (!reply.WriteInt32(static_cast<int>(status))) {
|
||||
ZLOGW("write transaction failed.");
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
case COMMIT: {
|
||||
Status status = Commit();
|
||||
if (!reply.WriteInt32(static_cast<int>(status))) {
|
||||
ZLOGW("write commit failed.");
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
case ROLLBACK: {
|
||||
Status status = Rollback();
|
||||
if (!reply.WriteInt32(static_cast<int>(status))) {
|
||||
ZLOGW("write rollback failed.");
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
case SUBSCRIBEKVSTORE: {
|
||||
return SubscribeKvStoreOnRemote(data, reply);
|
||||
}
|
||||
case UNSUBSCRIBEKVSTORE: {
|
||||
return UnSubscribeKvStoreOnRemote(data, reply);
|
||||
}
|
||||
default: {
|
||||
MessageOption mo { MessageOption::TF_SYNC };
|
||||
return IPCObjectStub::OnRemoteRequest(code, data, reply, mo);
|
||||
}
|
||||
}
|
||||
}
|
||||
} // namespace DistributedKv
|
||||
} // namespace OHOS
|
@ -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 "ikvstore_client_death_observer.h"
|
||||
|
||||
namespace OHOS {
|
||||
namespace DistributedKv {
|
||||
KvStoreClientDeathObserverProxy::KvStoreClientDeathObserverProxy(const sptr<IRemoteObject> &impl)
|
||||
: IRemoteProxy<IKvStoreClientDeathObserver>(impl)
|
||||
{}
|
||||
|
||||
int32_t KvStoreClientDeathObserverStub::OnRemoteRequest(uint32_t code, MessageParcel &data,
|
||||
MessageParcel &reply, MessageOption &option)
|
||||
{
|
||||
return IPCObjectStub::OnRemoteRequest(code, data, reply, option);
|
||||
}
|
||||
} // namespace DistributedKv
|
||||
} // namespace OHOS
|
648
frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_data_service.cpp
Executable file
648
frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_data_service.cpp
Executable file
@ -0,0 +1,648 @@
|
||||
/*
|
||||
* 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 "constant.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::GetKvStore(const Options &options, const AppId &appId, const StoreId &storeId,
|
||||
std::function<void(sptr<IKvStoreImpl>)> 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;
|
||||
}
|
||||
|
||||
// Passing a struct with an std::string field is a potential security exploit.
|
||||
OptionsIpc optionsIpc;
|
||||
optionsIpc.createIfMissing = options.createIfMissing;
|
||||
optionsIpc.encrypt = options.encrypt;
|
||||
optionsIpc.persistant = options.persistant;
|
||||
optionsIpc.backup = options.backup;
|
||||
optionsIpc.autoSync = options.autoSync;
|
||||
optionsIpc.securityLevel = options.securityLevel;
|
||||
optionsIpc.syncPolicy = options.syncPolicy;
|
||||
optionsIpc.kvStoreType = options.kvStoreType;
|
||||
optionsIpc.syncable = options.syncable;
|
||||
optionsIpc.dataOwnership = true; // set default value
|
||||
|
||||
if (!data.WriteBuffer(&optionsIpc, sizeof(optionsIpc)) ||
|
||||
!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(GETKVSTORE, data, reply, mo);
|
||||
if (error != 0) {
|
||||
ZLOGW("failed to write parcel.");
|
||||
return Status::IPC_ERROR;
|
||||
}
|
||||
Status ret = static_cast<Status>(reply.ReadInt32());
|
||||
if (ret == Status::SUCCESS) {
|
||||
sptr<IRemoteObject> remote = reply.ReadRemoteObject();
|
||||
if (remote != nullptr) {
|
||||
sptr<IKvStoreImpl> kvstoreImplProxy = iface_cast<IKvStoreImpl>(remote);
|
||||
callback(std::move(kvstoreImplProxy));
|
||||
}
|
||||
} else {
|
||||
callback(nullptr);
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
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.persistant = options.persistant;
|
||||
optionsIpc.backup = options.backup;
|
||||
optionsIpc.autoSync = options.autoSync;
|
||||
optionsIpc.securityLevel = options.securityLevel;
|
||||
optionsIpc.syncPolicy = options.syncPolicy;
|
||||
optionsIpc.kvStoreType = options.kvStoreType;
|
||||
optionsIpc.syncable = options.syncable;
|
||||
optionsIpc.dataOwnership = true; // set default value
|
||||
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::GetDeviceList(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(GETDEVICELIST, 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());
|
||||
}
|
||||
|
||||
int32_t KvStoreDataServiceStub::GetKvStoreOnRemote(MessageParcel &data, MessageParcel &reply)
|
||||
{
|
||||
OptionsIpc optionsIpc;
|
||||
AppId appId;
|
||||
StoreId storeId;
|
||||
|
||||
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 = *optionIpcPtr;
|
||||
Options options;
|
||||
options.createIfMissing = optionsIpc.createIfMissing;
|
||||
options.encrypt = optionsIpc.encrypt;
|
||||
options.persistant = optionsIpc.persistant;
|
||||
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.dataOwnership = optionsIpc.dataOwnership;
|
||||
appId.appId = data.ReadString();
|
||||
storeId.storeId = data.ReadString();
|
||||
sptr<IKvStoreImpl> proxyTmp;
|
||||
Status status = GetKvStore(options, appId, storeId,
|
||||
[&proxyTmp](sptr<IKvStoreImpl> proxy) { proxyTmp = std::move(proxy); });
|
||||
if (!reply.WriteInt32(static_cast<int>(status))) {
|
||||
return -1;
|
||||
}
|
||||
if (proxyTmp == nullptr) {
|
||||
ZLOGW("proxy is null.");
|
||||
return 0;
|
||||
}
|
||||
if (status == Status::SUCCESS && !reply.WriteRemoteObject(proxyTmp->AsObject().GetRefPtr())) {
|
||||
ZLOGW("write ipc failed.");
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
int32_t KvStoreDataServiceStub::GetAllKvStoreIdOnRemote(MessageParcel &data, MessageParcel &reply)
|
||||
{
|
||||
AppId appId;
|
||||
appId.appId = 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::GetDeviceListOnRemote(MessageParcel &data, MessageParcel &reply)
|
||||
{
|
||||
std::vector<DeviceInfo> infos;
|
||||
DeviceFilterStrategy strategy = static_cast<DeviceFilterStrategy>(data.ReadInt32());
|
||||
Status status = GetDeviceList(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)
|
||||
{
|
||||
OptionsIpc optionsIpc;
|
||||
AppId appId;
|
||||
StoreId storeId;
|
||||
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 = *optionIpcPtr;
|
||||
appId.appId = data.ReadString();
|
||||
storeId.storeId = data.ReadString();
|
||||
Options options;
|
||||
options.createIfMissing = optionsIpc.createIfMissing;
|
||||
options.encrypt = optionsIpc.encrypt;
|
||||
options.persistant = optionsIpc.persistant;
|
||||
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.dataOwnership = optionsIpc.dataOwnership;
|
||||
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;
|
||||
StoreId storeId;
|
||||
appId.appId = data.ReadString();
|
||||
storeId.storeId = 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;
|
||||
appId.appId = 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;
|
||||
StoreId storeId;
|
||||
appId.appId = data.ReadString();
|
||||
storeId.storeId = 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;
|
||||
appId.appId = 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;
|
||||
appId.appId = 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::OnRemoteRequest(uint32_t code, MessageParcel &data,
|
||||
MessageParcel &reply, MessageOption &option)
|
||||
{
|
||||
ZLOGD("%d", code);
|
||||
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
|
@ -0,0 +1,239 @@
|
||||
/*
|
||||
* 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 "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::list<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::list<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::list<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, sptr<IKvStoreSnapshotImpl> snapshot)
|
||||
{
|
||||
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(%lld) U(%lld) D(%lld) T(%lld)", static_cast<long long>(insertBufferSize),
|
||||
static_cast<long long>(updateBufferSize), static_cast<long long>(deleteBufferSize),
|
||||
static_cast<long long>(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;
|
||||
}
|
||||
}
|
||||
|
||||
if (snapshot != nullptr && !data.WriteRemoteObject(snapshot->AsObject().GetRefPtr())) {
|
||||
ZLOGE("write strong parcel 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::list<Entry> &entries)
|
||||
{
|
||||
const uint8_t *buffer = reinterpret_cast<const uint8_t *>(data.ReadRawData(bufferSize));
|
||||
if (buffer == nullptr) {
|
||||
ZLOGE("new buffer filed");
|
||||
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::list<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("%d", code);
|
||||
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;
|
||||
}
|
||||
sptr<IRemoteObject> remote = data.ReadRemoteObject();
|
||||
if (remote != nullptr) {
|
||||
sptr<IKvStoreSnapshotImpl> kvStoreSnapshotProxy = iface_cast<IKvStoreSnapshotImpl>(remote);
|
||||
OnChange(*changeNotification, std::move(kvStoreSnapshotProxy));
|
||||
} else {
|
||||
OnChange(*changeNotification, nullptr);
|
||||
}
|
||||
} else {
|
||||
std::list<Entry> insertEntries;
|
||||
bool result = ReadListFromBuf(data, insertEntries);
|
||||
if (!result) {
|
||||
ZLOGE("read insertList from buff filed");
|
||||
return errorResult;
|
||||
}
|
||||
|
||||
std::list<Entry> updateEntries;
|
||||
result = ReadListFromBuf(data, updateEntries);
|
||||
if (!result) {
|
||||
ZLOGE("read updateList from buff filed");
|
||||
return errorResult;
|
||||
}
|
||||
|
||||
std::list<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 changeNotification(insertEntries, updateEntries, deleteEntries, deviceId, isClear);
|
||||
sptr<IRemoteObject> remote = data.ReadRemoteObject();
|
||||
if (remote != nullptr) {
|
||||
sptr<IKvStoreSnapshotImpl> kvStoreSnapshotProxy = iface_cast<IKvStoreSnapshotImpl>(remote);
|
||||
OnChange(changeNotification, std::move(kvStoreSnapshotProxy));
|
||||
} else {
|
||||
ZLOGD("read kvstoreSnapshot is nullptr.");
|
||||
OnChange(changeNotification, nullptr);
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
default:
|
||||
return IPCObjectStub::OnRemoteRequest(code, data, reply, option);
|
||||
}
|
||||
}
|
||||
} // namespace DistributedKv
|
||||
} // namespace OHOS
|
326
frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_resultset.cpp
Executable file
326
frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_resultset.cpp
Executable file
@ -0,0 +1,326 @@
|
||||
/*
|
||||
* 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 "constant.h"
|
||||
#include "message_parcel.h"
|
||||
#include "log_print.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) {
|
||||
ZLOGW("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) {
|
||||
ZLOGW("SendRequest failed, error is %d", error);
|
||||
return Status::IPC_ERROR;
|
||||
}
|
||||
|
||||
Status status = static_cast<Status>(reply.ReadInt32());
|
||||
if (status != Status::SUCCESS) {
|
||||
ZLOGW("status not success(%d)", static_cast<int>(status));
|
||||
return status;
|
||||
}
|
||||
sptr<Entry> valueTmp = reply.ReadParcelable<Entry>();
|
||||
if (valueTmp != nullptr) {
|
||||
entry = *valueTmp;
|
||||
}
|
||||
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)
|
||||
{
|
||||
Entry entry;
|
||||
Status ret = GetEntry(entry);
|
||||
if (!reply.WriteInt32(static_cast<int>(ret)) ||
|
||||
!reply.WriteParcelable(&entry)) {
|
||||
ZLOGW("ResultSet service side GetEntry fail.");
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
int KvStoreResultSetStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply,
|
||||
MessageOption &option)
|
||||
{
|
||||
ZLOGD("%u", code);
|
||||
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 %d", code);
|
||||
MessageOption mo { MessageOption::TF_SYNC };
|
||||
return IPCObjectStub::OnRemoteRequest(code, data, reply, mo);
|
||||
}
|
||||
}
|
||||
}
|
||||
} // namespace OHOS::DistributedKv
|
1525
frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_single.cpp
Executable file
1525
frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_single.cpp
Executable file
File diff suppressed because it is too large
Load Diff
544
frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_snapshot.cpp
Executable file
544
frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_snapshot.cpp
Executable file
@ -0,0 +1,544 @@
|
||||
/*
|
||||
* 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 "KvStoreSnapshotImplProxy"
|
||||
|
||||
#include "ikvstore_snapshot.h"
|
||||
#include "constant.h"
|
||||
#include "log_print.h"
|
||||
#include "message_parcel.h"
|
||||
|
||||
namespace OHOS {
|
||||
namespace DistributedKv {
|
||||
enum {
|
||||
GETENTRIES,
|
||||
GETKEYS,
|
||||
GET,
|
||||
};
|
||||
|
||||
KvStoreSnapshotImplProxy::KvStoreSnapshotImplProxy(const sptr<IRemoteObject> &impl)
|
||||
: IRemoteProxy<IKvStoreSnapshotImpl>(impl)
|
||||
{}
|
||||
|
||||
KvStoreSnapshotImplProxy::~KvStoreSnapshotImplProxy()
|
||||
{}
|
||||
|
||||
void KvStoreSnapshotImplProxy::GetEntries(const Key &prefixKey, const Key &nextKey,
|
||||
std::function<void(Status status, std::vector<Entry> &entries, const Key &key)> callback)
|
||||
{
|
||||
MessageParcel data, reply;
|
||||
if (!data.WriteInterfaceToken(KvStoreSnapshotImplProxy::GetDescriptor())) {
|
||||
ZLOGE("write descriptor failed");
|
||||
return;
|
||||
}
|
||||
std::vector<Entry> entries;
|
||||
if (!reply.SetMaxCapacity(Constant::MAX_IPC_CAPACITY)) {
|
||||
ZLOGW("set max capacity failed");
|
||||
callback(Status::IPC_ERROR, entries, Key());
|
||||
return;
|
||||
}
|
||||
if (!data.WriteParcelable(&prefixKey)) {
|
||||
ZLOGW("write prefix failed");
|
||||
callback(Status::IPC_ERROR, entries, Key());
|
||||
return;
|
||||
}
|
||||
if (!data.WriteParcelable(&nextKey)) {
|
||||
ZLOGW("write nextkey failed");
|
||||
callback(Status::IPC_ERROR, entries, Key());
|
||||
return;
|
||||
}
|
||||
MessageOption mo { MessageOption::TF_SYNC };
|
||||
// struct of returned reply:
|
||||
// buffer: | status | entryLength | rawdatasize | (sptr<Key>)nextkey |
|
||||
// rawData: ( | keyLen | key | valueLen | value | ){entryLength}
|
||||
int32_t error = Remote()->SendRequest(GETENTRIES, data, reply, mo);
|
||||
|
||||
if (error != 0) {
|
||||
ZLOGW("Transact failed");
|
||||
callback(Status::IPC_ERROR, entries, Key());
|
||||
return;
|
||||
}
|
||||
|
||||
Status status = static_cast<Status>(reply.ReadInt32());
|
||||
if (status != Status::SUCCESS) {
|
||||
ZLOGW("status not success, which is %d", static_cast<int>(status));
|
||||
callback(status, entries, Key());
|
||||
return;
|
||||
}
|
||||
int replyEntryCount = reply.ReadInt32();
|
||||
int bufferSize = reply.ReadInt32();
|
||||
sptr<Key> keyTmp = reply.ReadParcelable<Key>();
|
||||
if (bufferSize < Constant::SWITCH_RAW_DATA_SIZE) {
|
||||
for (int i = 0; i < replyEntryCount; i++) {
|
||||
sptr<Entry> entry = reply.ReadParcelable<Entry>();
|
||||
if (entry == nullptr) {
|
||||
ZLOGW("entry is nullptr");
|
||||
callback(Status::IPC_ERROR, entries, Key());
|
||||
return;
|
||||
}
|
||||
entries.push_back(*entry);
|
||||
}
|
||||
} else {
|
||||
ZLOGI("getting large entry set");
|
||||
// this memory is managed by MassageParcel, DO NOT free here
|
||||
const uint8_t *buffer = reinterpret_cast<const uint8_t *>(reply.ReadRawData(bufferSize));
|
||||
if (replyEntryCount < 0 || bufferSize < 0 || buffer == nullptr) {
|
||||
ZLOGW("replyEntryCount(%d) or bufferSize(%d) less than 0, or buffer is nullptr", replyEntryCount,
|
||||
bufferSize);
|
||||
callback(Status::IPC_ERROR, entries, Key());
|
||||
return;
|
||||
}
|
||||
const uint8_t *rawDataCursor = buffer;
|
||||
int bufferLeftSize = bufferSize;
|
||||
entries = std::vector<Entry>(replyEntryCount);
|
||||
for (auto &entry : entries) {
|
||||
if (!entry.key.ReadFromBuffer(rawDataCursor, bufferLeftSize) ||
|
||||
!entry.value.ReadFromBuffer(rawDataCursor, bufferLeftSize)) {
|
||||
ZLOGW("read key or value from buffer failed");
|
||||
callback(Status::IPC_ERROR, entries, Key());
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (keyTmp != nullptr) {
|
||||
callback(status, entries, *keyTmp);
|
||||
} else {
|
||||
callback(status, entries, Key());
|
||||
}
|
||||
}
|
||||
|
||||
void KvStoreSnapshotImplProxy::GetKeys(const Key &prefixKey, const Key &nextKey,
|
||||
std::function<void(Status, std::vector<Key> &keys, const Key &key)> callback)
|
||||
{
|
||||
MessageParcel data, reply;
|
||||
if (!data.WriteInterfaceToken(KvStoreSnapshotImplProxy::GetDescriptor())) {
|
||||
ZLOGE("write descriptor failed");
|
||||
return;
|
||||
}
|
||||
std::vector<Key> keyList;
|
||||
if (!reply.SetMaxCapacity(Constant::MAX_IPC_CAPACITY)) {
|
||||
callback(Status::IPC_ERROR, keyList, Key());
|
||||
return;
|
||||
}
|
||||
if (!data.WriteParcelable(&prefixKey)) {
|
||||
callback(Status::IPC_ERROR, keyList, Key());
|
||||
return;
|
||||
}
|
||||
if (!data.WriteParcelable(&nextKey)) {
|
||||
callback(Status::IPC_ERROR, keyList, Key());
|
||||
return;
|
||||
}
|
||||
MessageOption mo { MessageOption::TF_SYNC };
|
||||
int32_t error = Remote()->SendRequest(GETKEYS, data, reply, mo);
|
||||
if (error != 0) {
|
||||
ZLOGW("Transact failed");
|
||||
callback(Status::IPC_ERROR, keyList, Key());
|
||||
return;
|
||||
}
|
||||
|
||||
Status status = static_cast<Status>(reply.ReadInt32());
|
||||
if (status != Status::SUCCESS) {
|
||||
ZLOGW("status not success, which is %d", static_cast<int>(status));
|
||||
callback(status, keyList, Key());
|
||||
return;
|
||||
}
|
||||
int replyKeyCount = reply.ReadInt32();
|
||||
int bufferSize = reply.ReadInt32();
|
||||
sptr<Key> keyTmp = reply.ReadParcelable<Key>();
|
||||
if (bufferSize < Constant::SWITCH_RAW_DATA_SIZE) {
|
||||
for (int i = 0; i < replyKeyCount; i++) {
|
||||
sptr<Key> keyInner = reply.ReadParcelable<Key>();
|
||||
if (keyInner == nullptr) {
|
||||
ZLOGW("keyInner is nullptr");
|
||||
callback(Status::IPC_ERROR, keyList, Key());
|
||||
return;
|
||||
}
|
||||
keyList.push_back(*keyInner);
|
||||
}
|
||||
} else {
|
||||
ZLOGI("getting large key set");
|
||||
// this memory is managed by MassageParcel, DO NOT free here
|
||||
const uint8_t *buffer = reinterpret_cast<const uint8_t *>(reply.ReadRawData(bufferSize));
|
||||
if (replyKeyCount < 0 || bufferSize < 0 || buffer == nullptr) {
|
||||
ZLOGW("replyKeyCount(%d) or bufferSize(%d) less than 0, or buffer is nullptr", replyKeyCount, bufferSize);
|
||||
callback(Status::IPC_ERROR, keyList, Key());
|
||||
return;
|
||||
}
|
||||
const uint8_t *rawDataCursor = buffer;
|
||||
int bufferLeftSize = bufferSize;
|
||||
keyList = std::vector<Key>(replyKeyCount);
|
||||
for (auto &key : keyList) {
|
||||
if (!key.ReadFromBuffer(rawDataCursor, bufferLeftSize)) {
|
||||
ZLOGW("read key from buffer failed");
|
||||
callback(Status::IPC_ERROR, keyList, Key());
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (keyTmp != nullptr) {
|
||||
callback(status, keyList, *keyTmp);
|
||||
} else {
|
||||
callback(status, keyList, Key());
|
||||
}
|
||||
}
|
||||
|
||||
Status KvStoreSnapshotImplProxy::Get(const Key &key, Value &value)
|
||||
{
|
||||
MessageParcel data, reply;
|
||||
if (!data.WriteInterfaceToken(KvStoreSnapshotImplProxy::GetDescriptor())) {
|
||||
ZLOGE("write descriptor failed");
|
||||
return Status::IPC_ERROR;
|
||||
}
|
||||
if (!reply.SetMaxCapacity(Constant::MAX_IPC_CAPACITY)) {
|
||||
return Status::IPC_ERROR;
|
||||
}
|
||||
if (!data.WriteParcelable(&key)) {
|
||||
return Status::IPC_ERROR;
|
||||
}
|
||||
|
||||
MessageOption mo { MessageOption::TF_SYNC };
|
||||
ZLOGI("start");
|
||||
int32_t error = Remote()->SendRequest(GET, data, reply, mo);
|
||||
if (error != 0) {
|
||||
ZLOGW("SendRequest failed, error is %d", error);
|
||||
return Status::IPC_ERROR;
|
||||
}
|
||||
Status status = static_cast<Status>(reply.ReadInt32());
|
||||
if (status != Status::SUCCESS) {
|
||||
ZLOGW("status not success(%d)", static_cast<int>(status));
|
||||
return status;
|
||||
}
|
||||
|
||||
int bufferSize = reply.ReadInt32();
|
||||
if (bufferSize < 0) {
|
||||
ZLOGW("bufferSize < 0(%d)", bufferSize);
|
||||
return Status::ERROR;
|
||||
}
|
||||
if (bufferSize < Constant::SWITCH_RAW_DATA_SIZE) {
|
||||
sptr<Value> valueTmp = reply.ReadParcelable<Value>();
|
||||
if (valueTmp != nullptr) {
|
||||
value = *valueTmp;
|
||||
}
|
||||
return status;
|
||||
}
|
||||
ZLOGI("getting big data");
|
||||
// this memory is managed by MassageParcel, DO NOT free here
|
||||
const uint8_t *buffer = reinterpret_cast<const uint8_t *>(reply.ReadRawData(bufferSize));
|
||||
if (buffer == nullptr) {
|
||||
ZLOGW("buffer is null");
|
||||
return Status::IPC_ERROR;
|
||||
}
|
||||
if (!value.ReadFromBuffer(buffer, bufferSize)) {
|
||||
ZLOGW("read value from buffer failed");
|
||||
return Status::IPC_ERROR;
|
||||
}
|
||||
return Status::SUCCESS;
|
||||
}
|
||||
|
||||
int32_t KvStoreSnapshotImplStub::GetTotalEntriesSize(std::vector<Entry> entryList)
|
||||
{
|
||||
int bufferSize = 0;
|
||||
for (const auto &item : entryList) {
|
||||
bufferSize += item.key.RawSize() + item.value.RawSize();
|
||||
}
|
||||
return bufferSize;
|
||||
}
|
||||
int32_t KvStoreSnapshotImplStub::WriteEntriesParcelable(MessageParcel &reply, Status statusTmp,
|
||||
std::vector<Entry> entryList, int bufferSize, Key nxtKey)
|
||||
{
|
||||
if (!reply.WriteInt32(static_cast<int>(statusTmp)) ||
|
||||
!reply.WriteInt32(entryList.size()) ||
|
||||
!reply.WriteInt32(bufferSize) ||
|
||||
!reply.WriteParcelable(&nxtKey)) {
|
||||
ZLOGW("write entry to parcel failed.");
|
||||
return -1;
|
||||
}
|
||||
for (const auto &item : entryList) {
|
||||
if (!reply.WriteParcelable(&item)) {
|
||||
ZLOGW("write item to parcel failed.");
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
int32_t KvStoreSnapshotImplStub::GetTotalkeysSize(std::vector<Key> keyList)
|
||||
{
|
||||
int bufferSize = 0;
|
||||
for (const auto &key : keyList) {
|
||||
bufferSize += key.RawSize();
|
||||
}
|
||||
return bufferSize;
|
||||
}
|
||||
int32_t KvStoreSnapshotImplStub::WritekeysParcelable(MessageParcel &reply, Status statusTmp,
|
||||
std::vector<Key> keyList, int bufferSize, Key nxtKey)
|
||||
{
|
||||
if (!reply.WriteInt32(static_cast<int>(statusTmp)) ||
|
||||
!reply.WriteInt32(keyList.size()) ||
|
||||
!reply.WriteInt32(bufferSize) ||
|
||||
!reply.WriteParcelable(&nxtKey)) {
|
||||
ZLOGW("write buffer size failed.");
|
||||
return -1;
|
||||
}
|
||||
for (const auto &item : keyList) {
|
||||
if (!reply.WriteParcelable(&item)) {
|
||||
ZLOGW("write item failed.");
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int32_t KvStoreSnapshotImplStub::GetEntriesOnRemote(MessageParcel &data, MessageParcel &reply)
|
||||
{
|
||||
// struct of returned reply:
|
||||
// buffer: | status | entryLength | rawdatasize | (sptr<Key>)nextkey |
|
||||
// rawData: ( | keyLen | key | valueLen | value | ){entryLength}
|
||||
sptr<Key> keyPrefix = data.ReadParcelable<Key>();
|
||||
sptr<Key> nextKey = data.ReadParcelable<Key>();
|
||||
if (keyPrefix == nullptr) {
|
||||
ZLOGW("keyPrefix is null. return.");
|
||||
if (!reply.WriteInt32(static_cast<int>(Status::INVALID_ARGUMENT))) {
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
if (nextKey == nullptr) {
|
||||
ZLOGW("nextKey is null. return.");
|
||||
if (!reply.WriteInt32(static_cast<int>(Status::INVALID_ARGUMENT))) {
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
std::vector<Entry> entryList;
|
||||
Key nxtKey;
|
||||
Status statusTmp;
|
||||
GetEntries(*keyPrefix, *nextKey, [&](Status status, const std::vector<Entry> &entries, const Key &key) {
|
||||
statusTmp = status;
|
||||
entryList = std::move(entries);
|
||||
nxtKey = key;
|
||||
});
|
||||
int bufferSize = GetTotalEntriesSize(entryList);
|
||||
if (bufferSize < Constant::SWITCH_RAW_DATA_SIZE) {
|
||||
return WriteEntriesParcelable(reply, statusTmp, entryList, bufferSize, nxtKey);
|
||||
}
|
||||
ZLOGI("getting large entry set");
|
||||
if (bufferSize > static_cast<int64_t>(reply.GetRawDataCapacity())) {
|
||||
ZLOGW("bufferSize %d larger than message parcel limit", bufferSize);
|
||||
if (!reply.WriteInt32(static_cast<int>(Status::ERROR))) {
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
std::unique_ptr<uint8_t, void(*)(uint8_t *)> buffer(
|
||||
new uint8_t[bufferSize], [](uint8_t *ptr) { delete[] ptr; });
|
||||
if (buffer == nullptr) {
|
||||
ZLOGW("buffer is null");
|
||||
if (!reply.WriteInt32(static_cast<int>(Status::ERROR))) {
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (!reply.WriteInt32(static_cast<int>(statusTmp)) ||
|
||||
!reply.WriteInt32(entryList.size()) ||
|
||||
!reply.WriteInt32(bufferSize) ||
|
||||
!reply.WriteParcelable(&nxtKey)) {
|
||||
ZLOGW("write entries failed.");
|
||||
return -1;
|
||||
}
|
||||
int bufferLeftSize = bufferSize;
|
||||
uint8_t *cursor = buffer.get();
|
||||
for (const auto &item : entryList) {
|
||||
if (!item.key.WriteToBuffer(cursor, bufferLeftSize) ||
|
||||
!item.value.WriteToBuffer(cursor, bufferLeftSize)) {
|
||||
ZLOGW("write to buffer failed");
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
if (!reply.WriteRawData(buffer.get(), bufferSize)) {
|
||||
ZLOGW("write rawData failed");
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
int32_t KvStoreSnapshotImplStub::GetKeysRemote(MessageParcel &data, MessageParcel &reply)
|
||||
{
|
||||
// struct of returned reply:
|
||||
// buffer: | status | keyListLength | rawdatasize | (sptr<Key>)nextkey |
|
||||
// rawData: ( | keyLen | key | ){keyListLength}
|
||||
sptr<Key> keyPrefix = data.ReadParcelable<Key>();
|
||||
sptr<Key> nextKey = data.ReadParcelable<Key>();
|
||||
if (keyPrefix == nullptr) {
|
||||
ZLOGW("keyPrefix is null");
|
||||
if (!reply.WriteInt32(static_cast<int>(Status::INVALID_ARGUMENT))) {
|
||||
return -1;
|
||||
}
|
||||
if (!reply.WriteParcelable(nullptr)) {
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
if (nextKey == nullptr) {
|
||||
ZLOGW("nextKey is null. return.");
|
||||
if (!reply.WriteInt32(static_cast<int>(Status::INVALID_ARGUMENT))) {
|
||||
return -1;
|
||||
}
|
||||
if (!reply.WriteParcelable(nullptr)) {
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
std::vector<Key> keyList;
|
||||
Key nxtKey;
|
||||
Status statusTmp;
|
||||
GetKeys(*keyPrefix, *nextKey, [&](Status status, const std::vector<Key> &keys, const Key &key) {
|
||||
statusTmp = status;
|
||||
keyList = std::move(keys);
|
||||
nxtKey = key;
|
||||
});
|
||||
int bufferSize = GetTotalkeysSize(keyList);
|
||||
|
||||
if (bufferSize < Constant::SWITCH_RAW_DATA_SIZE) {
|
||||
return WritekeysParcelable(reply, statusTmp, keyList, bufferSize, nxtKey);
|
||||
}
|
||||
ZLOGI("getting large key set");
|
||||
if (bufferSize > static_cast<int>(reply.GetRawDataCapacity())) {
|
||||
ZLOGW("bufferSize %d larger than message parcel limit", bufferSize);
|
||||
if (!reply.WriteInt32(static_cast<int>(Status::ERROR)) ||
|
||||
!reply.WriteParcelable(&nxtKey)) {
|
||||
ZLOGW("write status failed.");
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
std::unique_ptr<uint8_t, void(*)(uint8_t *)> buffer(
|
||||
new uint8_t[bufferSize], [](uint8_t *ptr) { delete[] ptr; });
|
||||
if (buffer == nullptr) {
|
||||
ZLOGW("alloc memory failed(buffer is null). perhaps low on memory.");
|
||||
if (!reply.WriteInt32(static_cast<int>(Status::ERROR)) ||
|
||||
!reply.WriteParcelable(&nxtKey)) {
|
||||
ZLOGW("write nxtkey failed.");
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
if (!reply.WriteInt32(static_cast<int>(statusTmp)) ||
|
||||
!reply.WriteInt32(keyList.size()) ||
|
||||
!reply.WriteInt32(bufferSize) ||
|
||||
!reply.WriteParcelable(&nxtKey)) {
|
||||
ZLOGW("write meta failed.");
|
||||
return -1;
|
||||
}
|
||||
|
||||
int bufferLeftSize = bufferSize;
|
||||
uint8_t *cursor = buffer.get();
|
||||
for (const auto &key : keyList) {
|
||||
if (!key.WriteToBuffer(cursor, bufferLeftSize)) {
|
||||
ZLOGW("write to buffer failed.");
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
if (!reply.WriteRawData(buffer.get(), bufferSize)) {
|
||||
ZLOGW("write rawData failed");
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
int32_t KvStoreSnapshotImplStub::GetRemote(MessageParcel &data, MessageParcel &reply)
|
||||
{
|
||||
sptr<Key> key = data.ReadParcelable<Key>();
|
||||
if (key == nullptr) {
|
||||
ZLOGW("key is null");
|
||||
if (!reply.WriteInt32(static_cast<int>(Status::INVALID_ARGUMENT))) {
|
||||
return -1;
|
||||
}
|
||||
if (!reply.WriteInt32(0)) {
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
Value value;
|
||||
Status status = Get(*key, value);
|
||||
|
||||
int bufferSize = value.RawSize();
|
||||
if (bufferSize < Constant::SWITCH_RAW_DATA_SIZE) {
|
||||
if (!reply.WriteInt32(static_cast<int>(status)) ||
|
||||
!reply.WriteInt32(bufferSize) ||
|
||||
!reply.WriteParcelable(&value)) {
|
||||
ZLOGW("write meta failed.");
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
ZLOGI("getting large entry");
|
||||
std::unique_ptr<uint8_t, void(*)(uint8_t *)> buffer(
|
||||
new uint8_t[bufferSize], [](uint8_t *ptr) { delete[] ptr; });
|
||||
if (buffer == nullptr) {
|
||||
ZLOGW("buffer is null");
|
||||
if (!reply.WriteInt32(static_cast<int>(Status::ILLEGAL_STATE)) ||
|
||||
!reply.WriteInt32(0)) {
|
||||
ZLOGW("write state failed.");
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
int bufferLeftSize = bufferSize;
|
||||
if (!reply.WriteInt32(static_cast<int>(status)) ||
|
||||
!reply.WriteInt32(bufferSize)) {
|
||||
ZLOGW("write bufferSize failed.");
|
||||
return -1;
|
||||
}
|
||||
|
||||
uint8_t *cursor = buffer.get();
|
||||
if (!value.WriteToBuffer(cursor, bufferLeftSize) ||
|
||||
!reply.WriteRawData(buffer.get(), bufferSize)) {
|
||||
ZLOGW("write rawData failed.");
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int32_t KvStoreSnapshotImplStub::OnRemoteRequest(uint32_t code, MessageParcel &data,
|
||||
MessageParcel &reply, MessageOption &option)
|
||||
{
|
||||
ZLOGD("%d", code);
|
||||
std::u16string descriptor = KvStoreSnapshotImplStub::GetDescriptor();
|
||||
std::u16string remoteDescriptor = data.ReadInterfaceToken();
|
||||
if (descriptor != remoteDescriptor) {
|
||||
ZLOGE("local descriptor is not equal to remote");
|
||||
return -1;
|
||||
}
|
||||
if (!reply.SetMaxCapacity(Constant::MAX_IPC_CAPACITY)) {
|
||||
return -1;
|
||||
}
|
||||
switch (code) {
|
||||
case GETENTRIES: {
|
||||
return GetEntriesOnRemote(data, reply);
|
||||
}
|
||||
case GETKEYS: {
|
||||
return GetKeysRemote(data, reply);
|
||||
}
|
||||
case GET: {
|
||||
return GetRemote(data, reply);
|
||||
}
|
||||
default:
|
||||
if (!reply.WriteInt32((int32_t)Status::ERROR)) {
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
} // namespace DistributedKv
|
||||
} // namespace OHOS
|
@ -0,0 +1,89 @@
|
||||
/*
|
||||
* 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 "log_print.h"
|
||||
#include "message_parcel.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)
|
||||
{
|
||||
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;
|
||||
}
|
||||
}
|
||||
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)
|
||||
{
|
||||
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())));
|
||||
}
|
||||
SyncCompleted(results);
|
||||
return 0;
|
||||
}
|
||||
default:
|
||||
return IPCObjectStub::OnRemoteRequest(code, data, reply, option);
|
||||
}
|
||||
}
|
||||
} // namespace DistributedKv
|
||||
} // namespace OHOS
|
267
frameworks/innerkitsimpl/distributeddatafwk/src/kvstore_client.cpp
Executable file
267
frameworks/innerkitsimpl/distributeddatafwk/src/kvstore_client.cpp
Executable file
@ -0,0 +1,267 @@
|
||||
/*
|
||||
* 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 "KvStoreClient"
|
||||
|
||||
#include "constant.h"
|
||||
#include "dds_trace.h"
|
||||
#include "kvstore_client.h"
|
||||
#include "kvstore_observer_client.h"
|
||||
#include "kvstore_snapshot_client.h"
|
||||
#include "log_print.h"
|
||||
|
||||
namespace OHOS {
|
||||
namespace DistributedKv {
|
||||
KvStoreClient::KvStoreClient(sptr<IKvStoreImpl> kvStoreProxy, const std::string &storeId)
|
||||
: kvStoreProxy_(std::move(kvStoreProxy)), storeId_(storeId)
|
||||
{
|
||||
ZLOGI("construct");
|
||||
}
|
||||
|
||||
KvStoreClient::~KvStoreClient()
|
||||
{
|
||||
ZLOGI("destruct");
|
||||
}
|
||||
|
||||
StoreId KvStoreClient::GetStoreId() const
|
||||
{
|
||||
StoreId storeId;
|
||||
storeId.storeId = storeId_;
|
||||
return storeId;
|
||||
}
|
||||
|
||||
void KvStoreClient::GetKvStoreSnapshot(std::shared_ptr<KvStoreObserver> observer,
|
||||
std::function<void(Status, std::unique_ptr<KvStoreSnapshot>)> callback) const
|
||||
{
|
||||
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__), true);
|
||||
|
||||
Status statusTmp = Status::SERVER_UNAVAILABLE;
|
||||
if (kvStoreProxy_ == nullptr) {
|
||||
ZLOGE("kvstore proxy is nullptr.");
|
||||
callback(statusTmp, nullptr);
|
||||
return;
|
||||
}
|
||||
|
||||
sptr<KvStoreObserverClient> kvStoreObserverClient = new KvStoreObserverClient(GetStoreId(),
|
||||
SubscribeType::SUBSCRIBE_TYPE_ALL, observer, KvStoreType::MULTI_VERSION);
|
||||
|
||||
sptr<IKvStoreSnapshotImpl> snapshotProxyTmp;
|
||||
auto snapshotCallbackFunction = [&](Status status, sptr<IKvStoreSnapshotImpl> snapshotProxy) {
|
||||
statusTmp = status;
|
||||
snapshotProxyTmp = snapshotProxy;
|
||||
};
|
||||
kvStoreProxy_->GetKvStoreSnapshot(kvStoreObserverClient, snapshotCallbackFunction);
|
||||
if (statusTmp != Status::SUCCESS) {
|
||||
ZLOGE("return error: %d.", static_cast<int>(statusTmp));
|
||||
callback(statusTmp, nullptr);
|
||||
return;
|
||||
}
|
||||
|
||||
if (snapshotProxyTmp == nullptr) {
|
||||
ZLOGE("snapshotProxyTmp is nullptr.");
|
||||
callback(statusTmp, nullptr);
|
||||
return;
|
||||
}
|
||||
|
||||
ZLOGD("success.");
|
||||
callback(statusTmp, std::make_unique<KvStoreSnapshotClient>(std::move(snapshotProxyTmp)));
|
||||
}
|
||||
|
||||
Status KvStoreClient::ReleaseKvStoreSnapshot(std::unique_ptr<KvStoreSnapshot> kvStoreSnapshotPtr)
|
||||
{
|
||||
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
|
||||
|
||||
if (kvStoreProxy_ == nullptr) {
|
||||
ZLOGE("kvstore proxy is nullptr.");
|
||||
return Status::SERVER_UNAVAILABLE;
|
||||
}
|
||||
if (kvStoreSnapshotPtr == nullptr) {
|
||||
ZLOGE("kvstoresnapshot is nullptr.");
|
||||
return Status::INVALID_ARGUMENT;
|
||||
}
|
||||
|
||||
KvStoreSnapshotClient *kvStoreSnapshotClient =
|
||||
reinterpret_cast<KvStoreSnapshotClient *>(kvStoreSnapshotPtr.release());
|
||||
sptr<IKvStoreSnapshotImpl> snapshotProxyTmp = kvStoreSnapshotClient->GetkvStoreSnapshotProxy();
|
||||
Status status = kvStoreProxy_->ReleaseKvStoreSnapshot(std::move(snapshotProxyTmp));
|
||||
delete kvStoreSnapshotClient;
|
||||
kvStoreSnapshotClient = nullptr;
|
||||
ZLOGI("return: %d.", static_cast<int>(status));
|
||||
return status;
|
||||
}
|
||||
|
||||
Status KvStoreClient::Put(const Key &key, const Value &value)
|
||||
{
|
||||
ZLOGD("key: %zu value: %zu.", key.Size(), value.Size());
|
||||
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__), true);
|
||||
|
||||
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) {
|
||||
return kvStoreProxy_->Put(key, value);
|
||||
}
|
||||
ZLOGE("kvstore proxy is nullptr.");
|
||||
return Status::SERVER_UNAVAILABLE;
|
||||
}
|
||||
|
||||
Status KvStoreClient::PutBatch(const std::vector<Entry> &entries)
|
||||
{
|
||||
ZLOGI("entry size: %zu", entries.size());
|
||||
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__), true);
|
||||
|
||||
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("kvstore proxy is nullptr.");
|
||||
return Status::SERVER_UNAVAILABLE;
|
||||
}
|
||||
|
||||
Status KvStoreClient::Delete(const Key &key)
|
||||
{
|
||||
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__), true);
|
||||
|
||||
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) {
|
||||
return kvStoreProxy_->Delete(key);
|
||||
}
|
||||
ZLOGE("kvstore proxy is nullptr.");
|
||||
return Status::SERVER_UNAVAILABLE;
|
||||
}
|
||||
|
||||
Status KvStoreClient::DeleteBatch(const std::vector<Key> &keys)
|
||||
{
|
||||
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__), true);
|
||||
|
||||
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("kvstore proxy is nullptr.");
|
||||
return Status::SERVER_UNAVAILABLE;
|
||||
}
|
||||
|
||||
Status KvStoreClient::Clear()
|
||||
{
|
||||
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
|
||||
|
||||
if (kvStoreProxy_ != nullptr) {
|
||||
return kvStoreProxy_->Clear();
|
||||
}
|
||||
ZLOGE("kvstore proxy is nullptr.");
|
||||
return Status::SERVER_UNAVAILABLE;
|
||||
}
|
||||
|
||||
Status KvStoreClient::StartTransaction()
|
||||
{
|
||||
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
|
||||
|
||||
if (kvStoreProxy_ != nullptr) {
|
||||
return kvStoreProxy_->StartTransaction();
|
||||
}
|
||||
ZLOGE("kvstore proxy is nullptr.");
|
||||
return Status::SERVER_UNAVAILABLE;
|
||||
}
|
||||
|
||||
Status KvStoreClient::Commit()
|
||||
{
|
||||
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__), true);
|
||||
|
||||
if (kvStoreProxy_ != nullptr) {
|
||||
return kvStoreProxy_->Commit();
|
||||
}
|
||||
ZLOGE("kvstore proxy is nullptr.");
|
||||
return Status::SERVER_UNAVAILABLE;
|
||||
}
|
||||
|
||||
Status KvStoreClient::Rollback()
|
||||
{
|
||||
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__), true);
|
||||
|
||||
if (kvStoreProxy_ != nullptr) {
|
||||
return kvStoreProxy_->Rollback();
|
||||
}
|
||||
ZLOGE("kvstore proxy is nullptr.");
|
||||
return Status::SERVER_UNAVAILABLE;
|
||||
}
|
||||
|
||||
Status KvStoreClient::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(GetStoreId(), subscribeType, observer, KvStoreType::MULTI_VERSION);
|
||||
if (ipcObserver == nullptr) {
|
||||
ZLOGW("new KvStoreObserverClient failed");
|
||||
return Status::ERROR;
|
||||
}
|
||||
Status status = kvStoreProxy_->SubscribeKvStore(subscribeType, ipcObserver);
|
||||
if (status == Status::SUCCESS) {
|
||||
registeredObservers_.emplace(observer.get(), ipcObserver);
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
Status KvStoreClient::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("return STORE_NOT_SUBSCRIBE.");
|
||||
return Status::STORE_NOT_SUBSCRIBE;
|
||||
}
|
||||
Status status = kvStoreProxy_->UnSubscribeKvStore(subscribeType, it->second);
|
||||
if (status == Status::SUCCESS) {
|
||||
registeredObservers_.erase(it);
|
||||
}
|
||||
return status;
|
||||
}
|
||||
} // namespace DistributedKv
|
||||
} // namespace OHOS
|
@ -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 KVSTORE_CLIENT_H
|
||||
#define KVSTORE_CLIENT_H
|
||||
|
||||
#include <map>
|
||||
#include "ikvstore.h"
|
||||
#include "kvstore.h"
|
||||
#include "kvstore_service_death_notifier.h"
|
||||
#include "kvstore_snapshot.h"
|
||||
#include "types.h"
|
||||
|
||||
namespace OHOS {
|
||||
namespace DistributedKv {
|
||||
|
||||
class KvStoreClient final : public KvStore {
|
||||
public:
|
||||
explicit KvStoreClient(sptr<IKvStoreImpl> kvStoreProxy, const std::string &storeId);
|
||||
|
||||
~KvStoreClient();
|
||||
|
||||
StoreId GetStoreId() const override;
|
||||
|
||||
void GetKvStoreSnapshot(std::shared_ptr<KvStoreObserver> observer,
|
||||
std::function<void(Status, std::unique_ptr<KvStoreSnapshot>)> callback) const override;
|
||||
|
||||
Status ReleaseKvStoreSnapshot(std::unique_ptr<KvStoreSnapshot> kvStoreSnapshotPtr) override;
|
||||
|
||||
Status Put(const Key &key, const Value &value) override;
|
||||
|
||||
Status PutBatch(const std::vector<Entry> &entries) override;
|
||||
|
||||
Status Delete(const Key &key) override;
|
||||
|
||||
Status DeleteBatch(const std::vector<Key> &keys) override;
|
||||
|
||||
Status Clear() override;
|
||||
|
||||
Status StartTransaction() override;
|
||||
|
||||
Status Commit() override;
|
||||
|
||||
Status Rollback() override;
|
||||
|
||||
Status SubscribeKvStore(SubscribeType subscribeType, std::shared_ptr<KvStoreObserver> observer) override;
|
||||
|
||||
Status UnSubscribeKvStore(SubscribeType subscribeType, std::shared_ptr<KvStoreObserver> observer) override;
|
||||
|
||||
private:
|
||||
sptr<IKvStoreImpl> kvStoreProxy_;
|
||||
std::map<KvStoreObserver *, sptr<IKvStoreObserver>> registeredObservers_;
|
||||
std::mutex observerMapMutex_;
|
||||
std::string storeId_;
|
||||
};
|
||||
|
||||
} // namespace DistributedKv
|
||||
} // namespace OHOS
|
||||
|
||||
#endif // KVSTORE_CLIENT_H
|
@ -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
|
@ -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
|
@ -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.
|
||||
*/
|
||||
|
||||
#define LOG_TAG "KvStoreDeathRecipientImpl"
|
||||
|
||||
#include "kvstore_death_recipient_impl.h"
|
||||
|
||||
#include <utility>
|
||||
#include "log_print.h"
|
||||
|
||||
namespace OHOS {
|
||||
namespace DistributedKv {
|
||||
KvStoreDeathRecipientImpl::KvStoreDeathRecipientImpl(std::shared_ptr<KvStoreDeathRecipient> kvStoreDeathRecipient)
|
||||
: kvStoreDeathRecipient_(std::move(kvStoreDeathRecipient))
|
||||
{
|
||||
ZLOGI("constructor");
|
||||
}
|
||||
|
||||
KvStoreDeathRecipientImpl::~KvStoreDeathRecipientImpl()
|
||||
{
|
||||
ZLOGI("destructor");
|
||||
}
|
||||
|
||||
void KvStoreDeathRecipientImpl::OnRemoteDied()
|
||||
{
|
||||
ZLOGI("OnRemoteDied");
|
||||
if (kvStoreDeathRecipient_ != nullptr) {
|
||||
ZLOGI("call client");
|
||||
kvStoreDeathRecipient_->OnRemoteDied();
|
||||
}
|
||||
}
|
||||
} // namespace DistributedKv
|
||||
} // namespace OHOS
|
@ -0,0 +1,38 @@
|
||||
/*
|
||||
* 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_DEATH_RECIPIENT_IMPL_H
|
||||
#define KVSTORE_DEATH_RECIPIENT_IMPL_H
|
||||
|
||||
#include <memory>
|
||||
#include "kvstore_death_recipient.h"
|
||||
|
||||
namespace OHOS {
|
||||
namespace DistributedKv {
|
||||
|
||||
class KvStoreDeathRecipientImpl {
|
||||
public:
|
||||
explicit KvStoreDeathRecipientImpl(std::shared_ptr<KvStoreDeathRecipient> kvStoreDeathRecipient);
|
||||
~KvStoreDeathRecipientImpl();
|
||||
void OnRemoteDied();
|
||||
private:
|
||||
std::shared_ptr<KvStoreDeathRecipient> kvStoreDeathRecipient_;
|
||||
friend struct KvStoreDeathRecipientImplCompare;
|
||||
};
|
||||
|
||||
} // namespace DistributedKv
|
||||
} // namespace OHOS
|
||||
|
||||
#endif // KVSTORE_DEATH_RECIPIENT_IMPL_H
|
66
frameworks/innerkitsimpl/distributeddatafwk/src/kvstore_observer_client.cpp
Executable file
66
frameworks/innerkitsimpl/distributeddatafwk/src/kvstore_observer_client.cpp
Executable file
@ -0,0 +1,66 @@
|
||||
/*
|
||||
* 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 "kvstore_snapshot_client.h"
|
||||
#include "log_print.h"
|
||||
|
||||
namespace OHOS {
|
||||
namespace DistributedKv {
|
||||
KvStoreObserverClient::KvStoreObserverClient(const StoreId &storeId, SubscribeType subscribeType,
|
||||
std::shared_ptr<KvStoreObserver> kvStoreObserver, KvStoreType type)
|
||||
: storeId_(storeId), subscribeType_(subscribeType), kvStoreObserver_(kvStoreObserver), type_(type)
|
||||
{
|
||||
ZLOGI("start");
|
||||
}
|
||||
|
||||
KvStoreObserverClient::~KvStoreObserverClient()
|
||||
{
|
||||
ZLOGI("start");
|
||||
}
|
||||
|
||||
void KvStoreObserverClient::OnChange(const ChangeNotification &changeNotification, sptr<IKvStoreSnapshotImpl> snapshot)
|
||||
{
|
||||
ZLOGI("start");
|
||||
if (kvStoreObserver_ != nullptr) {
|
||||
if (type_ == KvStoreType::SINGLE_VERSION) {
|
||||
ZLOGI("SINGLE_VERSION start");
|
||||
kvStoreObserver_->OnChange(changeNotification);
|
||||
} else {
|
||||
ZLOGI("MULTI_VERSION start");
|
||||
kvStoreObserver_->OnChange(changeNotification,
|
||||
std::make_unique<KvStoreSnapshotClient>(std::move(snapshot)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const StoreId &KvStoreObserverClient::GetStoreId() const
|
||||
{
|
||||
return storeId_;
|
||||
}
|
||||
|
||||
const SubscribeType &KvStoreObserverClient::GetSubscribeType() const
|
||||
{
|
||||
return subscribeType_;
|
||||
}
|
||||
|
||||
const std::shared_ptr<KvStoreObserver> KvStoreObserverClient::GetKvStoreObserver() const
|
||||
{
|
||||
return kvStoreObserver_;
|
||||
}
|
||||
} // namespace DistributedKv
|
||||
} // namespace OHOS
|
@ -0,0 +1,56 @@
|
||||
/*
|
||||
* 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 "ikvstore_snapshot.h"
|
||||
#include "kvstore_observer.h"
|
||||
#include "refbase.h"
|
||||
|
||||
namespace OHOS {
|
||||
namespace DistributedKv {
|
||||
|
||||
class KvStoreObserverClient : public KvStoreObserverStub {
|
||||
public:
|
||||
KvStoreObserverClient(const StoreId &storeId, SubscribeType subscribeType,
|
||||
std::shared_ptr<KvStoreObserver> kvStoreObserver, KvStoreType type);
|
||||
|
||||
~KvStoreObserverClient();
|
||||
|
||||
void OnChange(const ChangeNotification &changeNotification, sptr<IKvStoreSnapshotImpl> snapshot) override;
|
||||
|
||||
const StoreId &GetStoreId() const;
|
||||
|
||||
const SubscribeType &GetSubscribeType() const;
|
||||
|
||||
const std::shared_ptr<KvStoreObserver> GetKvStoreObserver() const;
|
||||
private:
|
||||
static const int MAX_TRY_COUNT = 10;
|
||||
|
||||
StoreId storeId_;
|
||||
|
||||
SubscribeType subscribeType_;
|
||||
|
||||
// client is responsible for free it when call UnSubscribeKvStore.
|
||||
std::shared_ptr<KvStoreObserver> kvStoreObserver_;
|
||||
KvStoreType type_;
|
||||
};
|
||||
} // namespace DistributedKv
|
||||
} // namespace OHOS
|
||||
#endif // KVSTORE_OBSERVER_CLIENT_H
|
@ -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
|
113
frameworks/innerkitsimpl/distributeddatafwk/src/kvstore_resultset_client.cpp
Executable file
113
frameworks/innerkitsimpl/distributeddatafwk/src/kvstore_resultset_client.cpp
Executable file
@ -0,0 +1,113 @@
|
||||
/*
|
||||
* 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 "kvstore_resultset_client.h"
|
||||
#include "dds_trace.h"
|
||||
|
||||
namespace OHOS::DistributedKv {
|
||||
KvStoreResultSetClient::KvStoreResultSetClient(sptr<IKvStoreResultSet> kvStoreProxy)
|
||||
:kvStoreResultSetProxy_(kvStoreProxy)
|
||||
{}
|
||||
|
||||
int KvStoreResultSetClient::GetCount() const
|
||||
{
|
||||
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__), true);
|
||||
|
||||
return kvStoreResultSetProxy_->GetCount();
|
||||
}
|
||||
|
||||
int KvStoreResultSetClient::GetPosition() const
|
||||
{
|
||||
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
|
||||
|
||||
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__), true);
|
||||
|
||||
return kvStoreResultSetProxy_->GetEntry(entry);
|
||||
}
|
||||
|
||||
sptr<IKvStoreResultSet> KvStoreResultSetClient::GetKvStoreResultSetProxy() const
|
||||
{
|
||||
return kvStoreResultSetProxy_;
|
||||
}
|
||||
} // namespace OHOS::DistributedKv
|
@ -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 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;
|
||||
|
||||
sptr<IKvStoreResultSet> GetKvStoreResultSetProxy() const;
|
||||
private:
|
||||
sptr<IKvStoreResultSet> kvStoreResultSetProxy_;
|
||||
};
|
||||
} // namespace OHOS::DistributedKv
|
||||
#endif // DISTRIBUTEDDATAMGR_KVSTORE_RESULTSET_CLIENT_H
|
@ -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.
|
||||
*/
|
||||
|
||||
#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::watchMutex_;
|
||||
sptr<IKvStoreDataService> KvStoreServiceDeathNotifier::kvDataServiceProxy_;
|
||||
sptr<KvStoreServiceDeathNotifier::KvStoreDeathRecipient> KvStoreServiceDeathNotifier::deathRecipientPtr_;
|
||||
sptr<IRemoteObject> KvStoreServiceDeathNotifier::clientDeathObserverPtr_;
|
||||
std::set<std::shared_ptr<KvStoreDeathRecipientImpl>, KvStoreDeathRecipientImplCompare>
|
||||
KvStoreServiceDeathNotifier::serviceDeathWatchers_;
|
||||
|
||||
void KvStoreServiceDeathNotifier::SetAppId(const AppId &appId)
|
||||
{
|
||||
appId_ = 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) KvStoreDeathRecipient();
|
||||
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(appId_, clientDeathObserverPtr_);
|
||||
}
|
||||
|
||||
void KvStoreServiceDeathNotifier::AddServiceDeathWatcher(std::shared_ptr<KvStoreDeathRecipientImpl> watcher)
|
||||
{
|
||||
std::lock_guard<std::mutex> lg(watchMutex_);
|
||||
auto ret = serviceDeathWatchers_.insert(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<KvStoreDeathRecipientImpl> watcher)
|
||||
{
|
||||
std::lock_guard<std::mutex> lg(watchMutex_);
|
||||
auto it = serviceDeathWatchers_.find(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::KvStoreDeathRecipient::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_) {
|
||||
std::thread th = std::thread([watcher]() {
|
||||
watcher->OnRemoteDied();
|
||||
});
|
||||
th.detach();
|
||||
}
|
||||
}
|
||||
|
||||
KvStoreServiceDeathNotifier::KvStoreDeathRecipient::KvStoreDeathRecipient()
|
||||
{
|
||||
ZLOGI("constructor.");
|
||||
}
|
||||
|
||||
KvStoreServiceDeathNotifier::KvStoreDeathRecipient::~KvStoreDeathRecipient()
|
||||
{
|
||||
ZLOGI("destructor.");
|
||||
}
|
||||
} // namespace DistributedKv
|
||||
} // namespace OHOS
|
@ -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 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_impl.h"
|
||||
#include "refbase.h"
|
||||
|
||||
namespace OHOS {
|
||||
namespace DistributedKv {
|
||||
struct KvStoreDeathRecipientImplCompare {
|
||||
bool operator()(const std::shared_ptr<KvStoreDeathRecipientImpl> lhs,
|
||||
const std::shared_ptr<KvStoreDeathRecipientImpl> rhs) const
|
||||
{
|
||||
return lhs->kvStoreDeathRecipient_ < rhs->kvStoreDeathRecipient_;
|
||||
}
|
||||
};
|
||||
|
||||
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);
|
||||
// add watcher for server die msg.
|
||||
static void AddServiceDeathWatcher(std::shared_ptr<KvStoreDeathRecipientImpl> watcher);
|
||||
// remove watcher for server die msg.
|
||||
static void RemoveServiceDeathWatcher(std::shared_ptr<KvStoreDeathRecipientImpl> watcher);
|
||||
private:
|
||||
class KvStoreDeathRecipient : public IRemoteObject::DeathRecipient {
|
||||
public:
|
||||
KvStoreDeathRecipient();
|
||||
|
||||
virtual ~KvStoreDeathRecipient();
|
||||
|
||||
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 sptr<IKvStoreDataService> kvDataServiceProxy_;
|
||||
static sptr<KvStoreDeathRecipient> deathRecipientPtr_;
|
||||
static sptr<IRemoteObject> clientDeathObserverPtr_;
|
||||
// set of watchers for server die msg.
|
||||
static std::set<std::shared_ptr<KvStoreDeathRecipientImpl>, KvStoreDeathRecipientImplCompare> serviceDeathWatchers_;
|
||||
};
|
||||
} // namespace DistributedKv
|
||||
} // namespace OHOS
|
||||
#endif // KVSTORE_SERVICE_DEATH_NOTIFIER_H
|
@ -0,0 +1,194 @@
|
||||
/*
|
||||
* 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 "KvStoreSnapshotClient"
|
||||
|
||||
#include "constant.h"
|
||||
#include "dds_trace.h"
|
||||
#include "kvstore_snapshot_client.h"
|
||||
#include "log_print.h"
|
||||
|
||||
namespace OHOS {
|
||||
namespace DistributedKv {
|
||||
KvStoreSnapshotClient::KvStoreSnapshotClient() : kvStoreSnapshotProxy_(nullptr)
|
||||
{}
|
||||
|
||||
KvStoreSnapshotClient::KvStoreSnapshotClient(sptr<IKvStoreSnapshotImpl> kvStoreSnapshotProxy)
|
||||
: kvStoreSnapshotProxy_(std::move(kvStoreSnapshotProxy))
|
||||
{
|
||||
ZLOGI("construct");
|
||||
}
|
||||
|
||||
KvStoreSnapshotClient::~KvStoreSnapshotClient()
|
||||
{
|
||||
ZLOGI("destruct");
|
||||
}
|
||||
|
||||
void KvStoreSnapshotClient::GetEntries(const Key &prefixKey, const Key &nextKey,
|
||||
std::function<void(Status, std::vector<Entry> &, const Key &)> callback)
|
||||
{
|
||||
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__), true);
|
||||
|
||||
std::vector<Entry> entries;
|
||||
std::vector<uint8_t> keyData = Constant::TrimCopy<std::vector<uint8_t>>(prefixKey.Data());
|
||||
if (keyData.size() > Constant::MAX_KEY_LENGTH) {
|
||||
ZLOGE("invalid prefixKey.");
|
||||
callback(Status::INVALID_ARGUMENT, entries, nextKey);
|
||||
return;
|
||||
}
|
||||
keyData = Constant::TrimCopy<std::vector<uint8_t>>(nextKey.Data());
|
||||
if (keyData.size() > Constant::MAX_KEY_LENGTH) {
|
||||
ZLOGE("invalid nextKey.");
|
||||
callback(Status::INVALID_ARGUMENT, entries, nextKey);
|
||||
return;
|
||||
}
|
||||
if (kvStoreSnapshotProxy_ != nullptr) {
|
||||
kvStoreSnapshotProxy_->GetEntries(prefixKey, nextKey, callback);
|
||||
return;
|
||||
}
|
||||
|
||||
ZLOGE("snapshot proxy is nullptr.");
|
||||
callback(Status::SERVER_UNAVAILABLE, entries, nextKey);
|
||||
}
|
||||
|
||||
void KvStoreSnapshotClient::GetEntries(const Key &prefixKey, std::function<void(Status, std::vector<Entry> &)> callback)
|
||||
{
|
||||
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__), true);
|
||||
|
||||
std::vector<Entry> allEntries;
|
||||
std::vector<uint8_t> keyData = Constant::TrimCopy<std::vector<uint8_t>>(prefixKey.Data());
|
||||
if (keyData.size() > Constant::MAX_KEY_LENGTH) {
|
||||
ZLOGE("invalid prefixKey.");
|
||||
callback(Status::INVALID_ARGUMENT, allEntries);
|
||||
return;
|
||||
}
|
||||
if (kvStoreSnapshotProxy_ == nullptr) {
|
||||
ZLOGE("snapshot proxy is nullptr.");
|
||||
callback(Status::SERVER_UNAVAILABLE, allEntries);
|
||||
return;
|
||||
}
|
||||
Key startKey = "";
|
||||
Status allStatus = Status::ERROR;
|
||||
do {
|
||||
kvStoreSnapshotProxy_->GetEntries(prefixKey, startKey,
|
||||
[&allStatus, &allEntries, &startKey](Status stat, std::vector<Entry> &entries, Key next) {
|
||||
allStatus = stat;
|
||||
if (stat != Status::SUCCESS) {
|
||||
return;
|
||||
}
|
||||
for (const auto &entry : entries) {
|
||||
allEntries.push_back(entry);
|
||||
}
|
||||
startKey = next;
|
||||
if (entries.empty()) {
|
||||
startKey = "";
|
||||
}
|
||||
});
|
||||
} while (allStatus == Status::SUCCESS && startKey.ToString() != "");
|
||||
if (allStatus != Status::SUCCESS) {
|
||||
ZLOGW("Error occurs during GetEntries.");
|
||||
allEntries.clear();
|
||||
}
|
||||
callback(allStatus, allEntries);
|
||||
}
|
||||
|
||||
void KvStoreSnapshotClient::GetKeys(const Key &prefixKey, const Key &nextKey,
|
||||
std::function<void(Status, std::vector<Key> &, const Key &)> callback)
|
||||
{
|
||||
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
|
||||
|
||||
std::vector<Key> keys;
|
||||
std::vector<uint8_t> keyData = Constant::TrimCopy<std::vector<uint8_t>>(prefixKey.Data());
|
||||
if (keyData.size() > Constant::MAX_KEY_LENGTH) {
|
||||
ZLOGE("invalid prefixKey.");
|
||||
callback(Status::INVALID_ARGUMENT, keys, nextKey);
|
||||
return;
|
||||
}
|
||||
keyData = Constant::TrimCopy<std::vector<uint8_t>>(nextKey.Data());
|
||||
if (keyData.size() > Constant::MAX_KEY_LENGTH) {
|
||||
ZLOGE("invalid nextKey.");
|
||||
callback(Status::INVALID_ARGUMENT, keys, nextKey);
|
||||
return;
|
||||
}
|
||||
if (kvStoreSnapshotProxy_ != nullptr) {
|
||||
kvStoreSnapshotProxy_->GetKeys(prefixKey, nextKey, callback);
|
||||
return;
|
||||
}
|
||||
ZLOGE("snapshot proxy is nullptr.");
|
||||
callback(Status::SERVER_UNAVAILABLE, keys, nextKey);
|
||||
}
|
||||
|
||||
void KvStoreSnapshotClient::GetKeys(const Key &prefixKey, std::function<void(Status, std::vector<Key> &)> callback)
|
||||
{
|
||||
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
|
||||
|
||||
std::vector<Key> allKeys;
|
||||
std::vector<uint8_t> keyData = Constant::TrimCopy<std::vector<uint8_t>>(prefixKey.Data());
|
||||
if (keyData.size() > Constant::MAX_KEY_LENGTH) {
|
||||
ZLOGE("invalid prefixKey.");
|
||||
callback(Status::INVALID_ARGUMENT, allKeys);
|
||||
return;
|
||||
}
|
||||
if (kvStoreSnapshotProxy_ == nullptr) {
|
||||
ZLOGE("snapshot proxy is nullptr.");
|
||||
callback(Status::SERVER_UNAVAILABLE, allKeys);
|
||||
return;
|
||||
}
|
||||
Key startKey = "";
|
||||
Status allStatus = Status::ERROR;
|
||||
do {
|
||||
kvStoreSnapshotProxy_->GetKeys(prefixKey, startKey, [&](Status stat, std::vector<Key> &keys, Key next) {
|
||||
allStatus = stat;
|
||||
if (stat != Status::SUCCESS) {
|
||||
return;
|
||||
}
|
||||
for (const auto &key : keys) {
|
||||
allKeys.push_back(key);
|
||||
}
|
||||
startKey = next;
|
||||
if (keys.empty()) {
|
||||
startKey = "";
|
||||
}
|
||||
});
|
||||
} while (allStatus == Status::SUCCESS && startKey.ToString() != "");
|
||||
if (allStatus != Status::SUCCESS) {
|
||||
ZLOGW("Error occurs during GetKeys.");
|
||||
allKeys.clear();
|
||||
}
|
||||
callback(allStatus, allKeys);
|
||||
}
|
||||
|
||||
Status KvStoreSnapshotClient::Get(const Key &key, Value &value)
|
||||
{
|
||||
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__), true);
|
||||
|
||||
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 (kvStoreSnapshotProxy_ != nullptr) {
|
||||
return kvStoreSnapshotProxy_->Get(key, value);
|
||||
}
|
||||
ZLOGE("snapshot proxy is nullptr.");
|
||||
return Status::SERVER_UNAVAILABLE;
|
||||
}
|
||||
|
||||
sptr<IKvStoreSnapshotImpl> KvStoreSnapshotClient::GetkvStoreSnapshotProxy()
|
||||
{
|
||||
return kvStoreSnapshotProxy_;
|
||||
}
|
||||
} // namespace DistributedKv
|
||||
} // namespace OHOS
|
@ -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 KVSTORE_SNAPSHOT_CLIENT_H
|
||||
#define KVSTORE_SNAPSHOT_CLIENT_H
|
||||
|
||||
#include "ikvstore_snapshot.h"
|
||||
#include "kvstore_service_death_notifier.h"
|
||||
#include "kvstore_snapshot.h"
|
||||
#include "types.h"
|
||||
|
||||
namespace OHOS {
|
||||
namespace DistributedKv {
|
||||
class KvStoreSnapshotClient final : public KvStoreSnapshot {
|
||||
public:
|
||||
KvStoreSnapshotClient();
|
||||
|
||||
explicit KvStoreSnapshotClient(sptr<IKvStoreSnapshotImpl> kvStoreSnapshotProxy);
|
||||
|
||||
~KvStoreSnapshotClient();
|
||||
|
||||
void GetEntries(const Key &prefixKey, const Key &nextKey,
|
||||
std::function<void(Status, std::vector<Entry> &, const Key &)> callback) override;
|
||||
|
||||
void GetEntries(const Key &prefixKey, std::function<void(Status, std::vector<Entry> &)> callback) override;
|
||||
|
||||
void GetKeys(const Key &prefixKey, const Key &nextKey,
|
||||
std::function<void(Status, std::vector<Key> &, const Key &)> callback) override;
|
||||
|
||||
void GetKeys(const Key &prefixKey, std::function<void(Status, std::vector<Key> &)> callback) override;
|
||||
|
||||
Status Get(const Key &key, Value &value) override;
|
||||
|
||||
sptr<IKvStoreSnapshotImpl> GetkvStoreSnapshotProxy();
|
||||
private:
|
||||
// use shared_ptr here to free pointer when reference count is 0.
|
||||
sptr<IKvStoreSnapshotImpl> kvStoreSnapshotProxy_;
|
||||
};
|
||||
} // namespace DistributedKv
|
||||
} // namespace OHOS
|
||||
#endif // KVSTORE_SNAPSHOT_CLIENT_H
|
@ -0,0 +1,36 @@
|
||||
/*
|
||||
* 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"
|
||||
|
||||
namespace OHOS {
|
||||
namespace DistributedKv {
|
||||
KvStoreSyncCallbackClient::KvStoreSyncCallbackClient(std::shared_ptr<KvStoreSyncCallback> kvStoreSyncCallback)
|
||||
: kvStoreSyncCallback_(kvStoreSyncCallback)
|
||||
{}
|
||||
|
||||
KvStoreSyncCallbackClient::~KvStoreSyncCallbackClient()
|
||||
{}
|
||||
|
||||
void KvStoreSyncCallbackClient::SyncCompleted(const std::map<std::string, Status> &results)
|
||||
{
|
||||
if (kvStoreSyncCallback_ != nullptr) {
|
||||
kvStoreSyncCallback_->SyncCompleted(results);
|
||||
}
|
||||
}
|
||||
} // namespace DistributedKv
|
||||
} // namespace OHOS
|
@ -0,0 +1,40 @@
|
||||
/*
|
||||
* 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 "ikvstore_sync_callback.h"
|
||||
#include "kvstore_sync_callback.h"
|
||||
|
||||
namespace OHOS {
|
||||
namespace DistributedKv {
|
||||
|
||||
class KvStoreSyncCallbackClient : public KvStoreSyncCallbackStub {
|
||||
public:
|
||||
explicit KvStoreSyncCallbackClient(std::shared_ptr<KvStoreSyncCallback> kvStoreSyncCallback);
|
||||
|
||||
virtual ~KvStoreSyncCallbackClient();
|
||||
|
||||
void SyncCompleted(const std::map<std::string, Status> &results) override;
|
||||
|
||||
private:
|
||||
std::shared_ptr<KvStoreSyncCallback> kvStoreSyncCallback_;
|
||||
};
|
||||
|
||||
} // namespace DistributedKv
|
||||
} // namespace OHOS
|
||||
|
||||
#endif // KVSTORE_SYNC_CALLBACK_CLIENT_H
|
451
frameworks/innerkitsimpl/distributeddatafwk/src/single_kvstore_client.cpp
Executable file
451
frameworks/innerkitsimpl/distributeddatafwk/src/single_kvstore_client.cpp
Executable file
@ -0,0 +1,451 @@
|
||||
/*
|
||||
* 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"
|
||||
|
||||
namespace OHOS::DistributedKv {
|
||||
SingleKvStoreClient::SingleKvStoreClient(sptr<ISingleKvStore> kvStoreProxy, const std::string &storeId)
|
||||
: kvStoreProxy_(kvStoreProxy), storeId_(storeId)
|
||||
{}
|
||||
|
||||
StoreId SingleKvStoreClient::GetStoreId() const
|
||||
{
|
||||
StoreId storeId;
|
||||
storeId.storeId = storeId_;
|
||||
return storeId;
|
||||
}
|
||||
|
||||
Status SingleKvStoreClient::GetEntries(const Key &prefixKey, std::vector<Entry> &entries) const
|
||||
{
|
||||
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__), true);
|
||||
|
||||
if (kvStoreProxy_ == nullptr) {
|
||||
ZLOGE("kvstore proxy is nullptr.");
|
||||
return Status::SERVER_UNAVAILABLE;
|
||||
}
|
||||
|
||||
return kvStoreProxy_->GetEntries(prefixKey, entries);
|
||||
}
|
||||
|
||||
Status SingleKvStoreClient::GetEntriesWithQuery(const std::string &query, std::vector<Entry> &entries) const
|
||||
{
|
||||
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__), true);
|
||||
|
||||
if (kvStoreProxy_ == nullptr) {
|
||||
ZLOGE("kvstore proxy is nullptr.");
|
||||
return Status::SERVER_UNAVAILABLE;
|
||||
}
|
||||
ZLOGD("Cpp client GetEntriesWithQuery");
|
||||
return kvStoreProxy_->GetEntriesWithQuery(query, entries);
|
||||
}
|
||||
|
||||
Status SingleKvStoreClient::GetEntriesWithQuery(const DataQuery &query, std::vector<Entry> &entries) const
|
||||
{
|
||||
return GetEntriesWithQuery(query.ToString(), entries);
|
||||
}
|
||||
|
||||
void SingleKvStoreClient::GetResultSet(const Key &prefixKey,
|
||||
std::function<void(Status, std::unique_ptr<KvStoreResultSet>)> callback) const
|
||||
{
|
||||
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__), true);
|
||||
|
||||
Status statusTmp = Status::SERVER_UNAVAILABLE;
|
||||
if (kvStoreProxy_ == nullptr) {
|
||||
ZLOGE("kvstore proxy is nullptr.");
|
||||
callback(statusTmp, nullptr);
|
||||
return;
|
||||
}
|
||||
sptr<IKvStoreResultSet> resultSetTmp;
|
||||
auto callFun = [&](Status status, sptr<IKvStoreResultSet> proxy) {
|
||||
statusTmp = status;
|
||||
resultSetTmp = proxy;
|
||||
};
|
||||
kvStoreProxy_->GetResultSet(prefixKey, callFun);
|
||||
if (statusTmp != Status::SUCCESS) {
|
||||
ZLOGE("return error: %d.", static_cast<int>(statusTmp));
|
||||
callback(statusTmp, nullptr);
|
||||
return;
|
||||
}
|
||||
|
||||
if (resultSetTmp == nullptr) {
|
||||
ZLOGE("resultSetTmp is nullptr.");
|
||||
callback(statusTmp, nullptr);
|
||||
return;
|
||||
}
|
||||
callback(statusTmp, std::make_unique<KvStoreResultSetClient>(std::move(resultSetTmp)));
|
||||
}
|
||||
|
||||
void SingleKvStoreClient::GetResultSetWithQuery(const std::string &query,
|
||||
std::function<void(Status, std::unique_ptr<KvStoreResultSet>)> callback) const
|
||||
{
|
||||
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__), true);
|
||||
|
||||
Status statusTmp = Status::SERVER_UNAVAILABLE;
|
||||
if (kvStoreProxy_ == nullptr) {
|
||||
ZLOGE("kvstore proxy is nullptr.");
|
||||
callback(statusTmp, nullptr);
|
||||
return;
|
||||
}
|
||||
|
||||
ZLOGD("Cpp client GetResultSetWithQuery");
|
||||
sptr<IKvStoreResultSet> resultSetTmp;
|
||||
auto callFun = [&](Status status, sptr<IKvStoreResultSet> proxy) {
|
||||
statusTmp = status;
|
||||
resultSetTmp = proxy;
|
||||
};
|
||||
kvStoreProxy_->GetResultSetWithQuery(query, callFun);
|
||||
if (statusTmp != Status::SUCCESS) {
|
||||
ZLOGE("return error: %d.", static_cast<int>(statusTmp));
|
||||
callback(statusTmp, nullptr);
|
||||
return;
|
||||
}
|
||||
|
||||
if (resultSetTmp == nullptr) {
|
||||
ZLOGE("resultSetTmp is nullptr.");
|
||||
callback(statusTmp, nullptr);
|
||||
return;
|
||||
}
|
||||
callback(statusTmp, std::make_unique<KvStoreResultSetClient>(std::move(resultSetTmp)));
|
||||
ZLOGE("GetResultSetWithQuery");
|
||||
}
|
||||
|
||||
void SingleKvStoreClient::GetResultSetWithQuery(const DataQuery &query,
|
||||
std::function<void(Status, std::unique_ptr<KvStoreResultSet>)> callback) const
|
||||
{
|
||||
GetResultSetWithQuery(query.ToString(), callback);
|
||||
}
|
||||
|
||||
Status SingleKvStoreClient::CloseResultSet(std::unique_ptr<KvStoreResultSet> resultSet)
|
||||
{
|
||||
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
|
||||
|
||||
if (resultSet == 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 *>(resultSet.release());
|
||||
return kvStoreProxy_->CloseResultSet(resultSetClient->GetKvStoreResultSetProxy());
|
||||
}
|
||||
|
||||
Status SingleKvStoreClient::GetCountWithQuery(const std::string &query, int &result) const
|
||||
{
|
||||
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__), true);
|
||||
|
||||
if (kvStoreProxy_ == nullptr) {
|
||||
ZLOGE("kvstore proxy is nullptr.");
|
||||
return Status::SERVER_UNAVAILABLE;
|
||||
}
|
||||
ZLOGD("Cpp client GetCountWithQuery");
|
||||
return kvStoreProxy_->GetCountWithQuery(query, result);
|
||||
}
|
||||
|
||||
Status SingleKvStoreClient::GetCountWithQuery(const DataQuery &query, int &result) const
|
||||
{
|
||||
return GetCountWithQuery(query.ToString(), result);
|
||||
}
|
||||
|
||||
Status SingleKvStoreClient::Sync(const std::vector<std::string> &deviceIdList, const SyncMode &mode,
|
||||
uint32_t allowedDelayMs)
|
||||
{
|
||||
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__), true);
|
||||
|
||||
if (kvStoreProxy_ == nullptr) {
|
||||
ZLOGE("kvstore proxy is nullptr.");
|
||||
return Status::SERVER_UNAVAILABLE;
|
||||
}
|
||||
if (deviceIdList.empty()) {
|
||||
ZLOGW("deviceIdList is empty.");
|
||||
return Status::INVALID_ARGUMENT;
|
||||
}
|
||||
return kvStoreProxy_->Sync(deviceIdList, mode, allowedDelayMs);
|
||||
}
|
||||
|
||||
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__), true);
|
||||
|
||||
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__), true);
|
||||
|
||||
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(GetStoreId(), subscribeType, observer,
|
||||
KvStoreType::SINGLE_VERSION);
|
||||
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)
|
||||
{
|
||||
ZLOGI("begin.");
|
||||
if (callback == nullptr) {
|
||||
ZLOGW("return INVALID_ARGUMENT.");
|
||||
return Status::INVALID_ARGUMENT;
|
||||
}
|
||||
// remove storeId after remove SubscribeKvStore function in manager. currently reserve for convenience.
|
||||
sptr<KvStoreSyncCallbackClient> ipcCallback =
|
||||
new (std::nothrow) KvStoreSyncCallbackClient(callback);
|
||||
if (ipcCallback == nullptr) {
|
||||
ZLOGW("new KvStoreSyncCallbackClient failed");
|
||||
return Status::ERROR;
|
||||
}
|
||||
return kvStoreProxy_->RegisterSyncCallback(ipcCallback);
|
||||
}
|
||||
|
||||
Status SingleKvStoreClient::UnRegisterSyncCallback()
|
||||
{
|
||||
ZLOGI("begin.");
|
||||
return kvStoreProxy_->UnRegisterSyncCallback();
|
||||
}
|
||||
|
||||
Status SingleKvStoreClient::PutBatch(const std::vector<Entry> &entries)
|
||||
{
|
||||
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__), true);
|
||||
|
||||
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__), true);
|
||||
|
||||
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__), true);
|
||||
|
||||
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__), true);
|
||||
|
||||
if (kvStoreProxy_ != nullptr) {
|
||||
return kvStoreProxy_->Rollback();
|
||||
}
|
||||
ZLOGE("singleKvstore proxy is nullptr.");
|
||||
return Status::SERVER_UNAVAILABLE;
|
||||
}
|
||||
|
||||
Status SingleKvStoreClient::SetSyncParam(const KvSyncParam &syncParam)
|
||||
{
|
||||
KvParam input(TransferTypeToByteArray<KvSyncParam>(syncParam));
|
||||
sptr<KvParam> output = nullptr;
|
||||
return Control(KvControlCmd::SET_SYNC_PARAM, input, output);
|
||||
}
|
||||
|
||||
Status SingleKvStoreClient::GetSyncParam(KvSyncParam &syncParam)
|
||||
{
|
||||
KvParam inputEmpty;
|
||||
sptr<KvParam> output = nullptr;
|
||||
Status ret = Control(KvControlCmd::GET_SYNC_PARAM, inputEmpty, output);
|
||||
if (ret != Status::SUCCESS) {
|
||||
return ret;
|
||||
}
|
||||
if ((output != nullptr) && (output->Size() == sizeof(syncParam))) {
|
||||
syncParam = TransferByteArrayToType<KvSyncParam>(output->Data());
|
||||
return Status::SUCCESS;
|
||||
}
|
||||
return Status::ERROR;
|
||||
}
|
||||
|
||||
Status SingleKvStoreClient::Control(KvControlCmd cmd, const KvParam &inputParam, sptr<KvParam> &output)
|
||||
{
|
||||
ZLOGI("begin.");
|
||||
if (kvStoreProxy_ != nullptr) {
|
||||
return kvStoreProxy_->Control(cmd, inputParam, output);
|
||||
}
|
||||
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> &remoteSupportLabels) const
|
||||
{
|
||||
if (kvStoreProxy_ != nullptr) {
|
||||
return kvStoreProxy_->SetCapabilityRange(localLabels, remoteSupportLabels);
|
||||
}
|
||||
ZLOGE("singleKvstore proxy is nullptr.");
|
||||
return Status::SERVER_UNAVAILABLE;
|
||||
}
|
||||
|
||||
Status SingleKvStoreClient::GetSecurityLevel(SecurityLevel &securityLevel) const
|
||||
{
|
||||
if (kvStoreProxy_ != nullptr) {
|
||||
return kvStoreProxy_->GetSecurityLevel(securityLevel);
|
||||
}
|
||||
ZLOGE("singleKvstore proxy is nullptr.");
|
||||
return Status::SERVER_UNAVAILABLE;
|
||||
}
|
||||
} // namespace OHOS::DistributedKv
|
100
frameworks/innerkitsimpl/distributeddatafwk/src/single_kvstore_client.h
Executable file
100
frameworks/innerkitsimpl/distributeddatafwk/src/single_kvstore_client.h
Executable file
@ -0,0 +1,100 @@
|
||||
/*
|
||||
* 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 "data_query.h"
|
||||
#include "ikvstore_single.h"
|
||||
#include "single_kvstore.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 &prefixKey, std::vector<Entry> &entries) const override;
|
||||
|
||||
Status GetEntriesWithQuery(const std::string &query, std::vector<Entry> &entries) const override;
|
||||
|
||||
Status GetEntriesWithQuery(const DataQuery &query, std::vector<Entry> &entries) const override;
|
||||
|
||||
void GetResultSet(const Key &prefixKey,
|
||||
std::function<void(Status, std::unique_ptr<KvStoreResultSet>)> callback) const override;
|
||||
|
||||
void GetResultSetWithQuery(const std::string &query,
|
||||
std::function<void(Status, std::unique_ptr<KvStoreResultSet>)> callback) const override;
|
||||
|
||||
void GetResultSetWithQuery(const DataQuery &query,
|
||||
std::function<void(Status, std::unique_ptr<KvStoreResultSet>)> callback) const override;
|
||||
|
||||
Status CloseResultSet(std::unique_ptr<KvStoreResultSet> resultSet) override;
|
||||
|
||||
Status GetCountWithQuery(const std::string &query, int &result) const override;
|
||||
|
||||
Status GetCountWithQuery(const DataQuery &query, int &result) const override;
|
||||
|
||||
Status Sync(const std::vector<std::string> &deviceIdList, const SyncMode &mode, uint32_t allowedDelayMs) 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 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> &remoteSupportLabels) const override;
|
||||
|
||||
Status GetSecurityLevel(SecurityLevel &securityLevel) const override;
|
||||
protected:
|
||||
Status Control(KvControlCmd cmd, const KvParam &inputParam, sptr<KvParam> &outputParam) override;
|
||||
|
||||
private:
|
||||
sptr<ISingleKvStore> kvStoreProxy_;
|
||||
std::map<KvStoreObserver *, sptr<IKvStoreObserver>> registeredObservers_;
|
||||
std::mutex observerMapMutex_;
|
||||
std::string storeId_;
|
||||
};
|
||||
} // namespace OHOS::DistributedKv
|
||||
#endif // DISTRIBUTEDDATAMGR2_SINGLE_KVSTORE_CLIENT_H
|
252
frameworks/innerkitsimpl/distributeddatafwk/test/BUILD.gn
Executable file
252
frameworks/innerkitsimpl/distributeddatafwk/test/BUILD.gn
Executable file
@ -0,0 +1,252 @@
|
||||
# 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.
|
||||
"//utils/native/base/include",
|
||||
"//foundation/distributeddatamgr/distributeddatamgr/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 = [
|
||||
"hiviewdfx_hilog_native:libhilog",
|
||||
"ipc:ipc_core",
|
||||
"samgr_L2:samgr_proxy",
|
||||
]
|
||||
|
||||
deps = [
|
||||
"//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata",
|
||||
"//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter:distributeddata_adapter",
|
||||
"//third_party/googletest:gtest_main",
|
||||
"//utils/native/base:utils",
|
||||
]
|
||||
}
|
||||
|
||||
ohos_unittest("DistributedKvDataManagerEncryptTest") {
|
||||
module_out_path = module_output_path
|
||||
|
||||
sources = [ "unittest/distributed_kv_data_manager_encrypt_test.cpp" ]
|
||||
|
||||
configs = [ ":module_private_config" ]
|
||||
|
||||
external_deps = [
|
||||
"hiviewdfx_hilog_native:libhilog",
|
||||
"ipc:ipc_core",
|
||||
"samgr_L2:samgr_proxy",
|
||||
]
|
||||
|
||||
deps = [
|
||||
"//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata",
|
||||
"//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter:distributeddata_adapter",
|
||||
"//third_party/googletest:gtest_main",
|
||||
"//utils/native/base:utils",
|
||||
]
|
||||
}
|
||||
|
||||
ohos_unittest("KvStoreClientTest") {
|
||||
module_out_path = module_output_path
|
||||
|
||||
sources = [
|
||||
"unittest/kvstore_client_test.cpp",
|
||||
"unittest/single_kvstore_client_query_test.cpp",
|
||||
"unittest/single_kvstore_client_test.cpp",
|
||||
]
|
||||
|
||||
configs = [ ":module_private_config" ]
|
||||
|
||||
external_deps = [
|
||||
"hiviewdfx_hilog_native:libhilog",
|
||||
"ipc:ipc_core",
|
||||
"samgr_L2:samgr_proxy",
|
||||
]
|
||||
|
||||
deps = [
|
||||
"//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata/:distributeddata",
|
||||
"//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter:distributeddata_adapter",
|
||||
"//third_party/googletest:gtest_main",
|
||||
"//utils/native/base:utils",
|
||||
]
|
||||
}
|
||||
|
||||
ohos_unittest("KvStoreSnapshotClientTest") {
|
||||
module_out_path = module_output_path
|
||||
|
||||
sources = [ "unittest/kvstore_snapshot_client_test.cpp" ]
|
||||
|
||||
configs = [ ":module_private_config" ]
|
||||
|
||||
external_deps = [
|
||||
"hiviewdfx_hilog_native:libhilog",
|
||||
"ipc:ipc_core",
|
||||
"samgr_L2:samgr_proxy",
|
||||
]
|
||||
|
||||
deps = [
|
||||
"//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata/:distributeddata",
|
||||
"//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter:distributeddata_adapter",
|
||||
"//third_party/googletest:gtest_main",
|
||||
"//utils/native/base:utils",
|
||||
]
|
||||
}
|
||||
|
||||
ohos_unittest("LocalSubscribeStoreTest") {
|
||||
module_out_path = module_output_path
|
||||
|
||||
sources = [ "unittest/local_subscribe_store_test.cpp" ]
|
||||
|
||||
configs = [ ":module_private_config" ]
|
||||
|
||||
external_deps = [
|
||||
"hiviewdfx_hilog_native:libhilog",
|
||||
"ipc:ipc_core",
|
||||
"samgr_L2:samgr_proxy",
|
||||
]
|
||||
|
||||
deps = [
|
||||
"//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata/:distributeddata",
|
||||
"//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter:distributeddata_adapter",
|
||||
"//third_party/googletest:gtest_main",
|
||||
"//utils/native/base:utils",
|
||||
]
|
||||
}
|
||||
|
||||
ohos_unittest("BlobTest") {
|
||||
module_out_path = module_output_path
|
||||
|
||||
sources = [ "unittest/blob_test.cpp" ]
|
||||
|
||||
configs = [ ":module_private_config" ]
|
||||
|
||||
deps = [
|
||||
"//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata/:distributeddata",
|
||||
"//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter:distributeddata_adapter",
|
||||
"//third_party/googletest:gtest_main",
|
||||
"//utils/native/base:utils",
|
||||
]
|
||||
}
|
||||
|
||||
###############################################################################
|
||||
config("app_test_config") {
|
||||
visibility = [ ":*" ]
|
||||
|
||||
include_dirs = [
|
||||
"../include/",
|
||||
"../../../../interfaces/innerkits/app_distributeddata/include",
|
||||
"//utils/native/base/include",
|
||||
"//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata/include",
|
||||
]
|
||||
}
|
||||
|
||||
ohos_unittest("AppDistributedKvStoreTest") {
|
||||
module_out_path = module_output_path
|
||||
|
||||
sources = [ "unittest/app_distributed_kv_store_test.cpp" ]
|
||||
|
||||
configs = [ ":app_test_config" ]
|
||||
|
||||
external_deps = [ "hiviewdfx_hilog_native:libhilog" ]
|
||||
|
||||
deps = [
|
||||
"//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/app_distributeddata/:app_distributeddata",
|
||||
"//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter:distributeddata_adapter",
|
||||
"//third_party/googletest:gtest_main",
|
||||
]
|
||||
}
|
||||
|
||||
ohos_unittest("AppDistributedKvDataManagerTest") {
|
||||
module_out_path = module_output_path
|
||||
|
||||
sources = [ "unittest/app_distributed_kv_data_manager_test.cpp" ]
|
||||
|
||||
configs = [ ":app_test_config" ]
|
||||
|
||||
external_deps = [ "hiviewdfx_hilog_native:libhilog" ]
|
||||
|
||||
deps = [
|
||||
"//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/app_distributeddata/:app_distributeddata",
|
||||
"//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter:distributeddata_adapter",
|
||||
"//third_party/googletest:gtest_main",
|
||||
]
|
||||
}
|
||||
|
||||
ohos_unittest("AppBlobTest") {
|
||||
module_out_path = module_output_path
|
||||
|
||||
sources = [ "unittest/app_blob_test.cpp" ]
|
||||
|
||||
configs = [ ":app_test_config" ]
|
||||
|
||||
external_deps = [ "hiviewdfx_hilog_native:libhilog" ]
|
||||
|
||||
deps = [
|
||||
"//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/app_distributeddata/:app_distributeddata",
|
||||
"//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter:distributeddata_adapter",
|
||||
"//third_party/googletest:gtest_main",
|
||||
]
|
||||
}
|
||||
|
||||
ohos_unittest("AppConflictTest") {
|
||||
module_out_path = module_output_path
|
||||
|
||||
sources = [ "unittest/app_conflict_test.cpp" ]
|
||||
|
||||
configs = [ ":app_test_config" ]
|
||||
|
||||
external_deps = [ "hiviewdfx_hilog_native:libhilog" ]
|
||||
|
||||
deps = [
|
||||
"//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/app_distributeddata/:app_distributeddata",
|
||||
"//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter:distributeddata_adapter",
|
||||
"//third_party/googletest:gtest_main",
|
||||
]
|
||||
}
|
||||
|
||||
group("unittest") {
|
||||
testonly = true
|
||||
|
||||
deps = []
|
||||
|
||||
deps += [
|
||||
":AppBlobTest",
|
||||
":AppConflictTest",
|
||||
":AppDistributedKvDataManagerTest",
|
||||
":AppDistributedKvStoreTest",
|
||||
":BlobTest",
|
||||
":DistributedKvDataManagerEncryptTest",
|
||||
":DistributedKvDataManagerTest",
|
||||
":KvStoreClientTest",
|
||||
":KvStoreSnapshotClientTest",
|
||||
":LocalSubscribeStoreTest",
|
||||
]
|
||||
}
|
||||
###############################################################################
|
196
frameworks/innerkitsimpl/distributeddatafwk/test/unittest/app_blob_test.cpp
Executable file
196
frameworks/innerkitsimpl/distributeddatafwk/test/unittest/app_blob_test.cpp
Executable file
@ -0,0 +1,196 @@
|
||||
/*
|
||||
* 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 "app_types.h"
|
||||
using namespace testing::ext;
|
||||
using namespace OHOS::AppDistributedKv;
|
||||
|
||||
class AppBlobTest : public testing::Test {
|
||||
public:
|
||||
static void SetUpTestCase(void);
|
||||
static void TearDownTestCase(void);
|
||||
void SetUp();
|
||||
void TearDown();
|
||||
};
|
||||
|
||||
void AppBlobTest::SetUpTestCase(void)
|
||||
{}
|
||||
|
||||
void AppBlobTest::TearDownTestCase(void)
|
||||
{}
|
||||
|
||||
void AppBlobTest::SetUp(void)
|
||||
{}
|
||||
|
||||
void AppBlobTest::TearDown(void)
|
||||
{}
|
||||
|
||||
/**
|
||||
* @tc.name: AppBlobSize001
|
||||
* @tc.desc: Construct a Blob and check its size.
|
||||
* @tc.type: FUNC
|
||||
* @tc.require: AR000CCPOL
|
||||
* @tc.author: liqiao
|
||||
*/
|
||||
HWTEST_F(AppBlobTest, AppBlobSize001, TestSize.Level0)
|
||||
{
|
||||
AppBlob blob1;
|
||||
EXPECT_EQ(blob1.Size(), (size_t)0);
|
||||
AppBlob blob2 = "1234567890";
|
||||
EXPECT_EQ(blob2.Size(), (size_t)10);
|
||||
AppBlob blob3("12345");
|
||||
EXPECT_EQ(blob3.Size(), (size_t)5);
|
||||
std::string strTmp = "123";
|
||||
const char *chr = strTmp.c_str();
|
||||
AppBlob blob4(chr);
|
||||
EXPECT_EQ(blob4.Size(), (size_t)3);
|
||||
std::vector<uint8_t> vec = {'1', '2', '3', '4'};
|
||||
AppBlob blob5(vec);
|
||||
EXPECT_EQ(blob5.Size(), (size_t)4);
|
||||
const char *chr1 = strTmp.c_str();
|
||||
AppBlob blob6(chr1, strlen(chr1));
|
||||
EXPECT_EQ(blob6.Size(), (size_t)3);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: AppBlobEmpty001
|
||||
* @tc.desc: Construct a Blob and check its empty.
|
||||
* @tc.type: FUNC
|
||||
* @tc.require: AR000CCPOL
|
||||
* @tc.author: liqiao
|
||||
*/
|
||||
HWTEST_F(AppBlobTest, AppBlobEmpty001, TestSize.Level0)
|
||||
{
|
||||
AppBlob blob1;
|
||||
EXPECT_EQ(blob1.Empty(), true);
|
||||
AppBlob blob2 = "1234567890";
|
||||
EXPECT_EQ(blob2.Empty(), false);
|
||||
AppBlob blob3("12345");
|
||||
EXPECT_EQ(blob3.Empty(), false);
|
||||
std::string strTmp = "123";
|
||||
const char *chr = strTmp.c_str();
|
||||
AppBlob blob4(chr);
|
||||
EXPECT_EQ(blob4.Empty(), false);
|
||||
std::vector<uint8_t> vec = {'1', '2', '3', '4'};
|
||||
AppBlob blob5(vec);
|
||||
EXPECT_EQ(blob5.Empty(), false);
|
||||
const char *chr1 = strTmp.c_str();
|
||||
AppBlob blob6(chr1, strlen(chr1));
|
||||
EXPECT_EQ(blob6.Empty(), false);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: AppBlobCompare001
|
||||
* @tc.desc: Construct a Blob and check its StartsWith function.
|
||||
* @tc.type: FUNC
|
||||
* @tc.require: AR000CCPOL
|
||||
* @tc.author: liqiao
|
||||
*/
|
||||
HWTEST_F(AppBlobTest, AppBlobCompare001, TestSize.Level0)
|
||||
{
|
||||
AppBlob blob1 = "1234567890";
|
||||
AppBlob blob2("12345");
|
||||
EXPECT_EQ(blob1.Compare(blob2), 1);
|
||||
EXPECT_EQ(blob2.Compare(blob1), -1);
|
||||
AppBlob blob3("12345");
|
||||
EXPECT_EQ(blob2.Compare(blob3), 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: AppBlobData001
|
||||
* @tc.desc: Construct a Blob and check its Data function.
|
||||
* @tc.type: FUNC
|
||||
* @tc.require: AR000CCPOL
|
||||
* @tc.author: liqiao
|
||||
*/
|
||||
HWTEST_F(AppBlobTest, AppBlobData001, TestSize.Level0)
|
||||
{
|
||||
std::vector<uint8_t> result = {'1', '2', '3', '4'};
|
||||
AppBlob blob1("1234");
|
||||
EXPECT_EQ(blob1.Data(), result);
|
||||
std::vector<uint8_t> result2 = {'1', '2', '3', '4', '5'};
|
||||
AppBlob blob2("12345");
|
||||
EXPECT_EQ(blob2.Data(), result2);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: AppBlobToString001
|
||||
* @tc.desc: Construct a Blob and check its ToString function.
|
||||
* @tc.type: FUNC
|
||||
* @tc.require: AR000CCPOL
|
||||
* @tc.author: liqiao
|
||||
*/
|
||||
HWTEST_F(AppBlobTest, AppBlobToString001, TestSize.Level0)
|
||||
{
|
||||
AppBlob blob1("1234");
|
||||
std::string str = "1234";
|
||||
EXPECT_EQ(blob1.ToString(), str);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: AppBlobOperatorEqual001
|
||||
* @tc.desc: Construct a Blob and check its operator== function.
|
||||
* @tc.type: FUNC
|
||||
* @tc.require: AR000CCPOL
|
||||
* @tc.author: liqiao
|
||||
*/
|
||||
HWTEST_F(AppBlobTest, AppBlobOperatorEqual001, TestSize.Level0)
|
||||
{
|
||||
AppBlob blob1("1234");
|
||||
AppBlob blob2("1234");
|
||||
EXPECT_EQ(blob1 == blob2, true);
|
||||
AppBlob blob3("12345");
|
||||
EXPECT_EQ(blob1 == blob3, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: AppBlobOperator002
|
||||
* @tc.desc: Construct a Blob and check its operator= function.
|
||||
* @tc.type: FUNC
|
||||
* @tc.require: AR000CCPOL
|
||||
* @tc.author: liqiao
|
||||
*/
|
||||
HWTEST_F(AppBlobTest, AppBlobOperator002, TestSize.Level0)
|
||||
{
|
||||
AppBlob blob1("1234");
|
||||
AppBlob blob2 = blob1;
|
||||
EXPECT_EQ(blob1 == blob2, true);
|
||||
EXPECT_EQ(blob2.ToString(), "1234");
|
||||
blob2 = blob1;
|
||||
EXPECT_EQ(blob1 == blob2, true);
|
||||
EXPECT_EQ(blob2.ToString(), "1234");
|
||||
blob2 = std::move(blob1);
|
||||
EXPECT_EQ(blob1 == blob2, true);
|
||||
EXPECT_EQ(blob2.ToString(), "1234");
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: AppBlobOperator003
|
||||
* @tc.desc: Construct a Blob and check its operator= function.
|
||||
* @tc.type: FUNC
|
||||
* @tc.require: AR000CCPOL
|
||||
* @tc.author: liqiao
|
||||
*/
|
||||
HWTEST_F(AppBlobTest, AppBlobOperator003, TestSize.Level0)
|
||||
{
|
||||
AppBlob blob1("1234");
|
||||
AppBlob blob2 = std::move(blob1);
|
||||
EXPECT_EQ(blob1 == blob2, false);
|
||||
EXPECT_EQ(blob1.Empty(), true);
|
||||
EXPECT_EQ(blob2.ToString(), "1234");
|
||||
}
|
224
frameworks/innerkitsimpl/distributeddatafwk/test/unittest/app_conflict_test.cpp
Executable file
224
frameworks/innerkitsimpl/distributeddatafwk/test/unittest/app_conflict_test.cpp
Executable file
@ -0,0 +1,224 @@
|
||||
/*
|
||||
* Copyright (c) 2021 Huawei Device Co., Ltd.
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#define LOG_TAG "AppConflictTest"
|
||||
|
||||
#include "app_distributed_kv_data_manager.h"
|
||||
#include <gtest/gtest.h>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <unistd.h>
|
||||
#include "app_kvstore.h"
|
||||
#include "app_types.h"
|
||||
#include "log_print.h"
|
||||
|
||||
using namespace testing::ext;
|
||||
using namespace OHOS::AppDistributedKv;
|
||||
|
||||
class AppConflictTest : public testing::Test {
|
||||
public:
|
||||
static void SetUpTestCase(void);
|
||||
static void TearDownTestCase(void);
|
||||
void SetUp();
|
||||
void TearDown();
|
||||
|
||||
static std::shared_ptr<AppDistributedKvDataManager> manager;
|
||||
static std::unique_ptr<AppKvStore> appKvStorePtr; // declare kvstore instance.
|
||||
static Status statusGetKvStore;
|
||||
};
|
||||
|
||||
std::shared_ptr<AppDistributedKvDataManager> AppConflictTest::manager;
|
||||
std::unique_ptr<AppKvStore> AppConflictTest::appKvStorePtr = nullptr;
|
||||
Status AppConflictTest::statusGetKvStore = Status::ERROR;
|
||||
static const auto OLD_VALUE_TYPE = AppKvStoreConflictData::ConflictValueType::OLD_VALUE;
|
||||
static const auto NEW_VALUE_TYPE = AppKvStoreConflictData::ConflictValueType::NEW_VALUE;
|
||||
static const int TIME_SLEEP = 100000;
|
||||
|
||||
struct ConflictDataTest {
|
||||
AppKvStoreConflictPolicyType type = AppKvStoreConflictPolicyType::CONFLICT_NATIVE_ALL;
|
||||
Key key;
|
||||
Value oldValue;
|
||||
Value newValue;
|
||||
bool oldIsDeleted = false;
|
||||
bool newIsDeleted = false;
|
||||
bool oldIsNative = false;
|
||||
bool newIsNative = false;
|
||||
bool operator==(const ConflictDataTest &comparedConflictDataTest) const
|
||||
{
|
||||
if (this->type == comparedConflictDataTest.type &&
|
||||
this->key == comparedConflictDataTest.key &&
|
||||
this->oldValue == comparedConflictDataTest.oldValue &&
|
||||
this->newValue == comparedConflictDataTest.newValue &&
|
||||
this->oldIsDeleted == comparedConflictDataTest.oldIsDeleted &&
|
||||
this->newIsDeleted == comparedConflictDataTest.newIsDeleted &&
|
||||
this->oldIsNative == comparedConflictDataTest.oldIsNative &&
|
||||
this->newIsNative == comparedConflictDataTest.newIsNative) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
};
|
||||
static std::vector<ConflictDataTest> g_conflictData;
|
||||
|
||||
static void ConflictCallback(const AppKvStoreConflictData &data)
|
||||
{
|
||||
ZLOGD("start.");
|
||||
Key key;
|
||||
Value oldValue;
|
||||
Value newValue;
|
||||
|
||||
data.GetKey(key);
|
||||
data.GetValue(OLD_VALUE_TYPE, oldValue);
|
||||
data.GetValue(NEW_VALUE_TYPE, newValue);
|
||||
bool oldIsDeleted = data.IsDeleted(OLD_VALUE_TYPE);
|
||||
bool newIsDeleted = data.IsDeleted(NEW_VALUE_TYPE);
|
||||
bool oldIsNative = data.IsNative(OLD_VALUE_TYPE);
|
||||
bool newIsNative = data.IsNative(NEW_VALUE_TYPE);
|
||||
g_conflictData.push_back({data.GetType(), key, oldValue, newValue, oldIsDeleted, newIsDeleted,
|
||||
oldIsNative, newIsNative});
|
||||
|
||||
ZLOGD("Get key: %s", key.ToString().c_str());
|
||||
ZLOGD("Get old value: %s", oldValue.ToString().c_str());
|
||||
ZLOGD("Get oldIsDeleted: %d", oldIsDeleted);
|
||||
ZLOGD("Get newIsDeleted: %d", newIsDeleted);
|
||||
ZLOGD("Get oldIsNative: %d", oldIsNative);
|
||||
ZLOGD("Get newIsNative: %d", newIsNative);
|
||||
}
|
||||
|
||||
void AppConflictTest::SetUpTestCase(void)
|
||||
{
|
||||
}
|
||||
|
||||
void AppConflictTest::TearDownTestCase(void)
|
||||
{
|
||||
}
|
||||
|
||||
void AppConflictTest::SetUp(void)
|
||||
{
|
||||
Options options;
|
||||
options.createIfMissing = true;
|
||||
options.encrypt = false; // not supported yet.
|
||||
options.persistant = true; // not supported yet.
|
||||
|
||||
std::string appId = "odmf"; // define app name.
|
||||
std::string storeId = "conflictdb"; // define kvstore(database) name.
|
||||
std::string dataDir = "data/misc_ce/0/odmf_test";
|
||||
|
||||
manager = AppDistributedKvDataManager::GetInstance(appId, dataDir);
|
||||
// [create and] open and initialize kvstore instance.
|
||||
statusGetKvStore = manager->GetKvStore(options, storeId, [&](std::unique_ptr<AppKvStore> appKvStore) {
|
||||
appKvStorePtr = std::move(appKvStore);
|
||||
});
|
||||
|
||||
g_conflictData.clear();
|
||||
}
|
||||
|
||||
void AppConflictTest::TearDown(void)
|
||||
{
|
||||
Status statusRet = manager->CloseKvStore(std::move(appKvStorePtr));
|
||||
EXPECT_EQ(statusRet, Status::SUCCESS);
|
||||
statusRet = manager->DeleteKvStore("conflictdb");
|
||||
EXPECT_EQ(statusRet, Status::SUCCESS);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: AppConflict001
|
||||
* @tc.desc: set conflict resolution policy and no conflict
|
||||
* @tc.type: FUNC
|
||||
* @tc.require: AR000CQDUG
|
||||
* @tc.author: liuyuhui
|
||||
*/
|
||||
HWTEST_F(AppConflictTest, AppConflict001, TestSize.Level0)
|
||||
{
|
||||
ZLOGD("AppConflict001");
|
||||
EXPECT_EQ(Status::SUCCESS, statusGetKvStore) << "statusGetKvStore return wrong status";
|
||||
EXPECT_NE(nullptr, appKvStorePtr) << "appKvStorePtr is nullptr";
|
||||
|
||||
Status status = appKvStorePtr->SetConflictResolutionPolicy(AppKvStoreConflictPolicyType::CONFLICT_NATIVE_ALL,
|
||||
ConflictCallback);
|
||||
EXPECT_EQ(Status::SUCCESS, status) << "SetConflictResolutionPolicy return wrong status";
|
||||
WriteOptions localWrite;
|
||||
localWrite.local = false;
|
||||
status = appKvStorePtr->Put(localWrite, "Id1", "conflict");
|
||||
EXPECT_EQ(Status::SUCCESS, status) << "Put return wrong status";
|
||||
usleep(TIME_SLEEP);
|
||||
EXPECT_EQ(g_conflictData.empty(), true);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: AppConflict002
|
||||
* @tc.desc: set conflict resolution policy and exist conflict -put the same key
|
||||
* @tc.type: FUNC
|
||||
* @tc.require: AR000CQDUG
|
||||
* @tc.author: liuyuhui
|
||||
*/
|
||||
HWTEST_F(AppConflictTest, AppConflict002, TestSize.Level0)
|
||||
{
|
||||
ZLOGD("AppConflict002");
|
||||
EXPECT_EQ(Status::SUCCESS, statusGetKvStore) << "statusGetKvStore return wrong status";
|
||||
EXPECT_NE(nullptr, appKvStorePtr) << "appKvStorePtr is nullptr";
|
||||
|
||||
WriteOptions localWrite;
|
||||
localWrite.local = false;
|
||||
Status status = appKvStorePtr->Put(localWrite, "Id2", "conflict");
|
||||
EXPECT_EQ(Status::SUCCESS, status) << "Put return wrong status";
|
||||
usleep(TIME_SLEEP);
|
||||
|
||||
status = appKvStorePtr->SetConflictResolutionPolicy(AppKvStoreConflictPolicyType::CONFLICT_NATIVE_ALL,
|
||||
ConflictCallback);
|
||||
EXPECT_EQ(Status::SUCCESS, status) << "SetConflictResolutionPolicy return wrong status";
|
||||
status = appKvStorePtr->Put(localWrite, "Id2", "conflict_modify");
|
||||
EXPECT_EQ(Status::SUCCESS, status) << "Put return wrong status";
|
||||
usleep(TIME_SLEEP);
|
||||
EXPECT_EQ(g_conflictData.empty(), false);
|
||||
ConflictDataTest expectData = {AppKvStoreConflictPolicyType::CONFLICT_NATIVE_ALL,
|
||||
"Id2", "conflict", "conflict_modify", false, false, true, true};
|
||||
EXPECT_EQ(g_conflictData.front() == expectData, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: AppConflict003
|
||||
* @tc.desc: set conflict resolution policy and exist conflict -put and delete the same key
|
||||
* @tc.type: FUNC
|
||||
* @tc.require: AR000CQDUG
|
||||
* @tc.author: liuyuhui
|
||||
*/
|
||||
HWTEST_F(AppConflictTest, AppConflict003, TestSize.Level0)
|
||||
{
|
||||
ZLOGD("app_conflict_003 start");
|
||||
EXPECT_EQ(Status::SUCCESS, statusGetKvStore) << "statusGetKvStore return wrong status";
|
||||
EXPECT_NE(nullptr, appKvStorePtr) << "appKvStorePtr is nullptr";
|
||||
|
||||
WriteOptions localWrite;
|
||||
localWrite.local = false;
|
||||
Status status = appKvStorePtr->Put(localWrite, "Id3", "conflict");
|
||||
EXPECT_EQ(Status::SUCCESS, status) << "Put return wrong status";
|
||||
usleep(TIME_SLEEP);
|
||||
|
||||
status = appKvStorePtr->SetConflictResolutionPolicy(AppKvStoreConflictPolicyType::CONFLICT_NATIVE_ALL,
|
||||
ConflictCallback);
|
||||
EXPECT_EQ(Status::SUCCESS, status) << "SetConflictResolutionPolicy return wrong status";
|
||||
status = appKvStorePtr->Delete(localWrite, "Id3");
|
||||
EXPECT_EQ(Status::SUCCESS, status) << "Delete return wrong status";
|
||||
usleep(TIME_SLEEP);
|
||||
EXPECT_EQ(g_conflictData.empty(), false);
|
||||
Value newValue;
|
||||
ConflictDataTest expectData = {AppKvStoreConflictPolicyType::CONFLICT_NATIVE_ALL,
|
||||
"Id3", "conflict", newValue, false, true, true, true};
|
||||
EXPECT_EQ(g_conflictData.front() == expectData, true);
|
||||
ZLOGD("app_conflict_003 end");
|
||||
}
|
@ -0,0 +1,426 @@
|
||||
/*
|
||||
* Copyright (c) 2021 Huawei Device Co., Ltd.
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include "app_distributed_kv_data_manager.h"
|
||||
#include <gtest/gtest.h>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include "app_kvstore.h"
|
||||
#include "app_types.h"
|
||||
#include "app_kvstore_corruption_observer.h"
|
||||
|
||||
#ifdef LOG_TAG
|
||||
#undef LOG_TAG
|
||||
#endif
|
||||
#define LOG_TAG "AppDistributedKvDataManagerTest"
|
||||
|
||||
using namespace testing::ext;
|
||||
using namespace OHOS::AppDistributedKv;
|
||||
|
||||
class AppDistributedKvDataManagerTest : public testing::Test {
|
||||
public:
|
||||
static std::shared_ptr<AppDistributedKvDataManager> manager;
|
||||
static Options create;
|
||||
static Options noCreate;
|
||||
|
||||
static std::string appId;
|
||||
static std::string storeId64;
|
||||
static std::string storeId65;
|
||||
static std::string storeIdEmpty;
|
||||
|
||||
static void SetUpTestCase(void);
|
||||
static void TearDownTestCase(void);
|
||||
|
||||
static void RemoveAllStore(AppDistributedKvDataManager &manager);
|
||||
|
||||
void SetUp();
|
||||
void TearDown();
|
||||
AppDistributedKvDataManagerTest();
|
||||
};
|
||||
|
||||
std::shared_ptr<AppDistributedKvDataManager> AppDistributedKvDataManagerTest::manager;
|
||||
Options AppDistributedKvDataManagerTest::create;
|
||||
Options AppDistributedKvDataManagerTest::noCreate;
|
||||
|
||||
std::string AppDistributedKvDataManagerTest::appId;
|
||||
std::string AppDistributedKvDataManagerTest::storeId64;
|
||||
std::string AppDistributedKvDataManagerTest::storeId65;
|
||||
std::string AppDistributedKvDataManagerTest::storeIdEmpty;
|
||||
|
||||
void AppDistributedKvDataManagerTest::SetUpTestCase(void)
|
||||
{
|
||||
create.createIfMissing = true;
|
||||
create.encrypt = false;
|
||||
create.persistant = true;
|
||||
|
||||
noCreate.createIfMissing = false;
|
||||
noCreate.encrypt = false;
|
||||
noCreate.persistant = true;
|
||||
|
||||
appId = "com.ohos.nb.service";
|
||||
std::string dataDir = "data/misc_ce/0/com.ohos.nb.service";
|
||||
storeId64 = "a000000000b000000000c000000000d000000000e000000000f000000000g000";
|
||||
storeId65 = "a000000000b000000000c000000000d000000000e000000000f000000000g0000"
|
||||
"a000000000b000000000c000000000d000000000e000000000f000000000g000";
|
||||
storeIdEmpty = "";
|
||||
std::string userId = "ohosAnonymousUid";
|
||||
|
||||
manager = AppDistributedKvDataManager::GetInstance(appId, dataDir, userId);
|
||||
}
|
||||
|
||||
void AppDistributedKvDataManagerTest::TearDownTestCase(void)
|
||||
{
|
||||
manager->DeleteKvStore(storeId64);
|
||||
}
|
||||
|
||||
void AppDistributedKvDataManagerTest::SetUp(void)
|
||||
{
|
||||
manager->DeleteKvStore(storeId64);
|
||||
}
|
||||
|
||||
AppDistributedKvDataManagerTest::AppDistributedKvDataManagerTest(void)
|
||||
{}
|
||||
|
||||
void AppDistributedKvDataManagerTest::TearDown(void)
|
||||
{
|
||||
manager->DeleteKvStore(storeId64);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: AppManagerGetKvstore001
|
||||
* @tc.desc: Get an exist KvStore
|
||||
* @tc.type: FUNC
|
||||
* @tc.require: AR000CCPOJ
|
||||
* @tc.author: liqiao
|
||||
*/
|
||||
HWTEST_F(AppDistributedKvDataManagerTest, AppManagerGetKvstore001, TestSize.Level0)
|
||||
{
|
||||
std::unique_ptr<AppKvStore> notExistKvStorePtr;
|
||||
Status status;
|
||||
status = manager->GetKvStore(create, storeId64, [&](std::unique_ptr<AppKvStore> kvStore) {
|
||||
notExistKvStorePtr = std::move(kvStore);
|
||||
});
|
||||
EXPECT_NE(notExistKvStorePtr, nullptr);
|
||||
EXPECT_EQ(status, Status::SUCCESS);
|
||||
|
||||
std::unique_ptr<AppKvStore> existKvStorePtr;
|
||||
status = manager->GetKvStore(noCreate, storeId64, [&](std::unique_ptr<AppKvStore> kvStore) {
|
||||
existKvStorePtr = std::move(kvStore);
|
||||
});
|
||||
EXPECT_NE(existKvStorePtr, nullptr);
|
||||
EXPECT_EQ(status, Status::SUCCESS);
|
||||
status = manager->CloseKvStore(std::move(notExistKvStorePtr));
|
||||
EXPECT_EQ(status, Status::SUCCESS);
|
||||
status = manager->CloseKvStore(std::move(existKvStorePtr));
|
||||
EXPECT_EQ(status, Status::SUCCESS);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: AppManagerGetKvstore002
|
||||
* @tc.desc: Create and get a new KvStore.
|
||||
* @tc.type: FUNC
|
||||
* @tc.require: AR000CCPOJ
|
||||
* @tc.author: liqiao
|
||||
*/
|
||||
HWTEST_F(AppDistributedKvDataManagerTest, AppManagerGetKvstore002, TestSize.Level0)
|
||||
{
|
||||
std::unique_ptr<AppKvStore> notExistKvStorePtr;
|
||||
Status status;
|
||||
status = manager->GetKvStore(create, storeId64, [&](std::unique_ptr<AppKvStore> kvStore) {
|
||||
notExistKvStorePtr = std::move(kvStore);
|
||||
});
|
||||
EXPECT_NE(notExistKvStorePtr, nullptr);
|
||||
EXPECT_EQ(status, Status::SUCCESS);
|
||||
status = manager->CloseKvStore(std::move(notExistKvStorePtr));
|
||||
EXPECT_EQ(status, Status::SUCCESS);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: AppManagerGetKvstore003
|
||||
* @tc.desc: Get a non-existing KvStore, and the callback function should receive STORE_NOT_FOUND and
|
||||
* get a nullptr.
|
||||
* @tc.type: FUNC
|
||||
* @tc.require: AR000CCPOJ
|
||||
* @tc.author: liqiao
|
||||
*/
|
||||
HWTEST_F(AppDistributedKvDataManagerTest, AppManagerGetKvstore003, TestSize.Level0)
|
||||
{
|
||||
std::unique_ptr<AppKvStore> notExistKvStorePtr;
|
||||
Status status;
|
||||
status = manager->GetKvStore(noCreate, storeId64, [&](std::unique_ptr<AppKvStore> kvStore) {
|
||||
notExistKvStorePtr = std::move(kvStore);
|
||||
});
|
||||
EXPECT_EQ(notExistKvStorePtr, nullptr);
|
||||
EXPECT_EQ(status, Status::STORE_NOT_FOUND);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: AppManagerGetKvstore004
|
||||
* @tc.desc: Create a KvStore with an empty storeId, and the callback function should receive
|
||||
* INVALID_ARGUMENT and got a nullptr.
|
||||
* @tc.type: FUNC
|
||||
* @tc.require: AR000CCPOJ
|
||||
* @tc.author: liqiao
|
||||
*/
|
||||
HWTEST_F(AppDistributedKvDataManagerTest, AppManagerGetKvstore004, TestSize.Level0)
|
||||
{
|
||||
std::unique_ptr<AppKvStore> notExistKvStorePtr;
|
||||
Status status;
|
||||
status = manager->GetKvStore(create, storeIdEmpty, [&](std::unique_ptr<AppKvStore> kvStore) {
|
||||
notExistKvStorePtr = std::move(kvStore);
|
||||
});
|
||||
EXPECT_EQ(notExistKvStorePtr, nullptr);
|
||||
EXPECT_EQ(status, Status::INVALID_ARGUMENT);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: AppManagerGetKvstore005
|
||||
* @tc.desc: Get a KvStore with an empty storeId, the callback function should receive INVALID_ARGUMENT
|
||||
* and got a nullptr.
|
||||
* @tc.type: FUNC
|
||||
* @tc.require: AR000CCPOJ
|
||||
* @tc.author: liqiao
|
||||
*/
|
||||
HWTEST_F(AppDistributedKvDataManagerTest, AppManagerGetKvstore005, TestSize.Level0)
|
||||
{
|
||||
std::unique_ptr<AppKvStore> notExistKvStorePtr;
|
||||
Status status;
|
||||
status = manager->GetKvStore(noCreate, storeIdEmpty, [&](std::unique_ptr<AppKvStore> kvStore) {
|
||||
notExistKvStorePtr = std::move(kvStore);
|
||||
});
|
||||
EXPECT_EQ(notExistKvStorePtr, nullptr);
|
||||
EXPECT_EQ(status, Status::INVALID_ARGUMENT);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: AppManagerGetKvstore006
|
||||
* @tc.desc: Create a KvStore with 65-byte storeId, and the callback function should receive
|
||||
* INVALID_ARGUMENT and got a nullptr.
|
||||
* @tc.type: FUNC
|
||||
* @tc.require: AR000CCPOJ
|
||||
* @tc.author: liqiao
|
||||
*/
|
||||
HWTEST_F(AppDistributedKvDataManagerTest, AppManagerGetKvstore006, TestSize.Level0)
|
||||
{
|
||||
std::unique_ptr<AppKvStore> notExistKvStorePtr;
|
||||
Status status;
|
||||
status = manager->GetKvStore(create, storeId65, [&](std::unique_ptr<AppKvStore> kvStore) {
|
||||
notExistKvStorePtr = std::move(kvStore);
|
||||
});
|
||||
EXPECT_EQ(notExistKvStorePtr, nullptr);
|
||||
EXPECT_EQ(status, Status::INVALID_ARGUMENT);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: AppManagerGetKvstore007
|
||||
* @tc.desc: Get a KvStore with 65-byte storeId, and the callback function should receive
|
||||
* INVALID_ARGUMENT and got a nullptr.
|
||||
* @tc.type: FUNC
|
||||
* @tc.require: AR000CCPOJ
|
||||
* @tc.author: liqiao
|
||||
*/
|
||||
HWTEST_F(AppDistributedKvDataManagerTest, AppManagerGetKvstore007, TestSize.Level0)
|
||||
{
|
||||
std::unique_ptr<AppKvStore> notExistKvStorePtr;
|
||||
Status status;
|
||||
status = manager->GetKvStore(noCreate, storeId65, [&](std::unique_ptr<AppKvStore> kvStore) {
|
||||
notExistKvStorePtr = std::move(kvStore);
|
||||
});
|
||||
EXPECT_EQ(notExistKvStorePtr, nullptr);
|
||||
EXPECT_EQ(status, Status::INVALID_ARGUMENT);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: AppManagerCloseKvstore001
|
||||
* @tc.desc: Close an opened KVStore, and the callback should return SUCCESS.
|
||||
* @tc.type: FUNC
|
||||
* @tc.require: AR000CCPOJ
|
||||
* @tc.author: liqiao
|
||||
*/
|
||||
HWTEST_F(AppDistributedKvDataManagerTest, AppManagerCloseKvstore001, TestSize.Level0)
|
||||
{
|
||||
std::unique_ptr<AppKvStore> kvStorePtr;
|
||||
Status status;
|
||||
status = manager->GetKvStore(create, storeId64, [&](std::unique_ptr<AppKvStore> kvStore) {
|
||||
kvStorePtr = std::move(kvStore);
|
||||
});
|
||||
ASSERT_NE(kvStorePtr, nullptr);
|
||||
ASSERT_EQ(status, Status::SUCCESS);
|
||||
|
||||
Status stat = manager->CloseKvStore(std::move(kvStorePtr));
|
||||
EXPECT_EQ(stat, Status::SUCCESS);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: AppManagerCloseKvstore002
|
||||
* @tc.desc: Close a closed KvStore, and the callback should return INVALID_ARGUMENT.
|
||||
* @tc.type: FUNC
|
||||
* @tc.require: AR000CCPOJ
|
||||
* @tc.author: liqiao
|
||||
*/
|
||||
HWTEST_F(AppDistributedKvDataManagerTest, AppManagerCloseKvstore002, TestSize.Level0)
|
||||
{
|
||||
std::unique_ptr<AppKvStore> kvStorePtr;
|
||||
Status status;
|
||||
status = manager->GetKvStore(create, storeId64, [&](std::unique_ptr<AppKvStore> kvStore) {
|
||||
kvStorePtr = std::move(kvStore);
|
||||
});
|
||||
ASSERT_NE(kvStorePtr, nullptr);
|
||||
ASSERT_EQ(status, Status::SUCCESS);
|
||||
|
||||
manager->CloseKvStore(std::move(kvStorePtr));
|
||||
Status stat = manager->CloseKvStore(std::move(kvStorePtr));
|
||||
EXPECT_EQ(stat, Status::INVALID_ARGUMENT);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: AppManagerCloseKvstore003
|
||||
* @tc.desc: Close a KvStore with empty storeId, and the callback should return INVALID_ARGUMENT.
|
||||
* @tc.type: FUNC
|
||||
* @tc.require: AR000CCPOJ
|
||||
* @tc.author: liqiao
|
||||
*/
|
||||
HWTEST_F(AppDistributedKvDataManagerTest, AppManagerCloseKvstore003, TestSize.Level0)
|
||||
{
|
||||
std::unique_ptr<AppKvStore> kvStorePtr = nullptr;
|
||||
Status stat = manager->CloseKvStore(nullptr);
|
||||
EXPECT_EQ(stat, Status::INVALID_ARGUMENT);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: AppManagerDeleteKvStore001
|
||||
* @tc.desc: Delete a closed KvStore, and the callback should return SUCCESS.
|
||||
* @tc.type: FUNC
|
||||
* @tc.require: AR000CCPOJ
|
||||
* @tc.author: liqiao
|
||||
*/
|
||||
HWTEST_F(AppDistributedKvDataManagerTest, AppManagerDeleteKvStore001, TestSize.Level0)
|
||||
{
|
||||
std::unique_ptr<AppKvStore> kvStorePtr;
|
||||
Status status;
|
||||
status = manager->GetKvStore(create, storeId64, [&](std::unique_ptr<AppKvStore> kvStore) {
|
||||
kvStorePtr = std::move(kvStore);
|
||||
});
|
||||
ASSERT_NE(kvStorePtr, nullptr);
|
||||
ASSERT_EQ(status, Status::SUCCESS);
|
||||
|
||||
Status stat = manager->CloseKvStore(std::move(kvStorePtr));
|
||||
ASSERT_EQ(stat, Status::SUCCESS);
|
||||
|
||||
stat = manager->DeleteKvStore(storeId64);
|
||||
EXPECT_EQ(stat, Status::SUCCESS);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: AppManagerDeleteKvStore002
|
||||
* @tc.desc: Delete a opened KvStore, and the callback should return ILLEGAL_STATE.
|
||||
* @tc.type: FUNC
|
||||
* @tc.require: AR000CCPOJ
|
||||
* @tc.author: liqiao
|
||||
*/
|
||||
HWTEST_F(AppDistributedKvDataManagerTest, AppManagerDeleteKvStore002, TestSize.Level0)
|
||||
{
|
||||
std::unique_ptr<AppKvStore> kvStorePtr;
|
||||
Status status;
|
||||
status = manager->GetKvStore(create, storeId64, [&](std::unique_ptr<AppKvStore> kvStore) {
|
||||
kvStorePtr = std::move(kvStore);
|
||||
});
|
||||
ASSERT_NE(kvStorePtr, nullptr);
|
||||
ASSERT_EQ(status, Status::SUCCESS);
|
||||
|
||||
// first close it if opened, and then delete it.
|
||||
status = manager->DeleteKvStore(storeId64);
|
||||
EXPECT_EQ(status, Status::ERROR);
|
||||
manager->CloseKvStore(std::move(kvStorePtr));
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: AppManagerDeleteKvStore003
|
||||
* @tc.desc: Delete a non-existing KvStore, and the callback should return ERROR.
|
||||
* @tc.type: FUNC
|
||||
* @tc.require: AR000CCPOJ
|
||||
* @tc.author: liqiao
|
||||
*/
|
||||
HWTEST_F(AppDistributedKvDataManagerTest, AppManagerDeleteKvStore003, TestSize.Level0)
|
||||
{
|
||||
Status stat = manager->DeleteKvStore(storeId64);
|
||||
EXPECT_EQ(stat, Status::ERROR);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: AppManagerDeleteKvStore004
|
||||
* @tc.desc: Delete a KvStore with an empty storeId, and the callback should return INVALID_ARGUMENT.
|
||||
* @tc.type: FUNC
|
||||
* @tc.require: AR000CCPOJ
|
||||
* @tc.author: liqiao
|
||||
*/
|
||||
HWTEST_F(AppDistributedKvDataManagerTest, AppManagerDeleteKvStore004, TestSize.Level0)
|
||||
{
|
||||
Status stat = manager->DeleteKvStore(storeIdEmpty);
|
||||
EXPECT_EQ(stat, Status::INVALID_ARGUMENT);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: AppManagerDeleteKvStore005
|
||||
* @tc.desc: Delete a KvStore with a 65-byte storeId (which exceeds storeId length limit), and the calback should
|
||||
* return INVALID_ARGUMENT.
|
||||
* @tc.type: FUNC
|
||||
* @tc.require: AR000CCPOJ
|
||||
* @tc.author: liqiao
|
||||
*/
|
||||
HWTEST_F(AppDistributedKvDataManagerTest, AppManagerDeleteKvStore005, TestSize.Level0)
|
||||
{
|
||||
Status stat = manager->DeleteKvStore(storeId65);
|
||||
EXPECT_EQ(stat, Status::INVALID_ARGUMENT);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: GetKvStoreDiskSize001
|
||||
* @tc.desc: Get the kvStore disk size.
|
||||
* @tc.type: FUNC
|
||||
* @tc.require: AR000CQDTD
|
||||
* @tc.author: hongbo
|
||||
*/
|
||||
HWTEST_F(AppDistributedKvDataManagerTest, GetKvStoreDiskSize001, TestSize.Level0)
|
||||
{
|
||||
uint64_t size;
|
||||
Status stat = manager->GetKvStoreDiskSize(storeId65, size);
|
||||
if (stat == Status::SUCCESS) {
|
||||
uint64_t expect = 0;
|
||||
EXPECT_GE(size, expect);
|
||||
}
|
||||
}
|
||||
|
||||
class CorruptionObserverImpl : public AppKvStoreCorruptionObserver {
|
||||
public:
|
||||
~CorruptionObserverImpl() {}
|
||||
void OnCorruption(const std::string &appId, const std::string &userId, const std::string &storeId) override;
|
||||
};
|
||||
|
||||
void CorruptionObserverImpl::OnCorruption(const std::string &appId, const std::string &userId,
|
||||
const std::string &storeId) {}
|
||||
/**
|
||||
* @tc.name: RegisterKvStoreCorruptionObserver
|
||||
* @tc.desc: Register the database corruption observer.
|
||||
* @tc.type: FUNC
|
||||
* @tc.require: AR000D487D
|
||||
* @tc.author: hongbo
|
||||
*/
|
||||
HWTEST_F(AppDistributedKvDataManagerTest, RegisterKvStoreCorruptionObserver001, TestSize.Level0)
|
||||
{
|
||||
auto observer = std::make_shared<CorruptionObserverImpl>();
|
||||
Status stat = manager->RegisterKvStoreCorruptionObserver(observer);
|
||||
EXPECT_EQ(stat, Status::SUCCESS);
|
||||
}
|
File diff suppressed because it is too large
Load Diff
251
frameworks/innerkitsimpl/distributeddatafwk/test/unittest/blob_test.cpp
Executable file
251
frameworks/innerkitsimpl/distributeddatafwk/test/unittest/blob_test.cpp
Executable 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");
|
||||
}
|
@ -0,0 +1,136 @@
|
||||
/*
|
||||
* 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 "distributed_kv_data_manager.h"
|
||||
#include "kvstore_death_recipient.h"
|
||||
#include <gtest/gtest.h>
|
||||
#include <cstdint>
|
||||
#include <vector>
|
||||
#include "types.h"
|
||||
#include "log_print.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);
|
||||
manager.DeleteAllKvStore(appId);
|
||||
}
|
||||
void DistributedKvDataManagerEncryptTest::SetUpTestCase(void)
|
||||
{
|
||||
createEnc.createIfMissing = true;
|
||||
createEnc.encrypt = true;
|
||||
createEnc.autoSync = true;
|
||||
|
||||
userId.userId = "account0";
|
||||
appId.appId = "com.ohos.nb.service";
|
||||
|
||||
storeId.storeId = "EncryptStoreId";
|
||||
}
|
||||
|
||||
void DistributedKvDataManagerEncryptTest::TearDownTestCase(void)
|
||||
{
|
||||
RemoveAllStore(manager);
|
||||
}
|
||||
|
||||
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.Level0)
|
||||
{
|
||||
ZLOGI("kvstore_ddm_createEncryptedStore_001 begin.");
|
||||
std::unique_ptr<KvStore> kvStorePtr;
|
||||
manager.GetKvStore(createEnc, appId, storeId, [&](Status status, std::unique_ptr<KvStore> kvStore) {
|
||||
kvStorePtr = std::move(kvStore);
|
||||
ASSERT_EQ(status, Status::SUCCESS);
|
||||
});
|
||||
ASSERT_NE(kvStorePtr, nullptr);
|
||||
|
||||
Key key = "age";
|
||||
Value value = "18";
|
||||
Status status = kvStorePtr->Put(key, value);
|
||||
EXPECT_EQ(Status::SUCCESS, status) << "KvStore put data return wrong status";
|
||||
|
||||
std::unique_ptr<KvStoreSnapshot> kvStoreSnapshotPtr;
|
||||
// [create and] open and initialize kvstore snapshot instance.
|
||||
kvStorePtr->GetKvStoreSnapshot(nullptr,
|
||||
[&](Status status, std::unique_ptr<KvStoreSnapshot> kvStoreSnapshot) {
|
||||
kvStoreSnapshotPtr = std::move(kvStoreSnapshot);
|
||||
});
|
||||
|
||||
ASSERT_NE(nullptr, kvStoreSnapshotPtr) << "kvStoreSnapshotPtr is nullptr";
|
||||
// get value from kvstore.
|
||||
Value valueRet;
|
||||
Status statusRet = kvStoreSnapshotPtr->Get(key, valueRet);
|
||||
EXPECT_EQ(Status::SUCCESS, statusRet) << "KvStoreSnapshot get data return wrong status";
|
||||
|
||||
EXPECT_EQ(value, valueRet) << "value and valueRet are not equal";
|
||||
kvStorePtr->ReleaseKvStoreSnapshot(std::move(kvStoreSnapshotPtr));
|
||||
}
|
@ -0,0 +1,846 @@
|
||||
/*
|
||||
* 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 <cstdint>
|
||||
#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() {}
|
||||
virtual 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);
|
||||
}
|
||||
void DistributedKvDataManagerTest::SetUpTestCase(void)
|
||||
{
|
||||
create.createIfMissing = true;
|
||||
create.encrypt = false;
|
||||
create.autoSync = true;
|
||||
|
||||
noCreate.createIfMissing = false;
|
||||
noCreate.encrypt = false;
|
||||
noCreate.autoSync = true;
|
||||
noCreate.dataOwnership = true;
|
||||
|
||||
userId.userId = "account0";
|
||||
appId.appId = "com.ohos.kvdatamanager.test";
|
||||
|
||||
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 DistributedKvDataManagerTest::SetUp(void)
|
||||
{}
|
||||
|
||||
DistributedKvDataManagerTest::DistributedKvDataManagerTest(void)
|
||||
{}
|
||||
|
||||
void DistributedKvDataManagerTest::TearDown(void)
|
||||
{
|
||||
RemoveAllStore(manager);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: GetKvStore001
|
||||
* @tc.desc: Get an exist KvStore
|
||||
* @tc.type: FUNC
|
||||
* @tc.require: SR000CQDU0 AR000BVTDM
|
||||
* @tc.author: liqiao
|
||||
*/
|
||||
HWTEST_F(DistributedKvDataManagerTest, GetKvStore001, TestSize.Level0)
|
||||
{
|
||||
ZLOGI("GetKvStore001 begin.");
|
||||
std::unique_ptr<KvStore> notExistKvStorePtr;
|
||||
manager.GetKvStore(create, appId, storeId64, [&](Status status, std::unique_ptr<KvStore> kvStore) {
|
||||
notExistKvStorePtr = std::move(kvStore);
|
||||
ASSERT_EQ(status, Status::SUCCESS);
|
||||
});
|
||||
EXPECT_NE(notExistKvStorePtr, nullptr);
|
||||
|
||||
std::unique_ptr<KvStore> existKvStorePtr;
|
||||
manager.GetKvStore(noCreate, appId, storeId64, [&](Status status, std::unique_ptr<KvStore> kvStore) {
|
||||
existKvStorePtr = std::move(kvStore);
|
||||
ASSERT_EQ(status, Status::SUCCESS);
|
||||
});
|
||||
EXPECT_NE(existKvStorePtr, nullptr);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: GetKvStore002
|
||||
* @tc.desc: Create and get a new KvStore
|
||||
* @tc.type: FUNC
|
||||
* @tc.require: SR000CQDU0 AR000BVTDM
|
||||
* @tc.author: liqiao
|
||||
*/
|
||||
HWTEST_F(DistributedKvDataManagerTest, GetKvStore002, TestSize.Level0)
|
||||
{
|
||||
ZLOGI("GetKvStore002 begin.");
|
||||
std::unique_ptr<KvStore> notExistKvStorePtr;
|
||||
manager.GetKvStore(create, appId, storeId64, [&](Status status, std::unique_ptr<KvStore> kvStore) {
|
||||
notExistKvStorePtr = std::move(kvStore);
|
||||
ASSERT_EQ(status, Status::SUCCESS);
|
||||
});
|
||||
EXPECT_NE(notExistKvStorePtr, nullptr);
|
||||
manager.CloseKvStore(appId, storeId64);
|
||||
manager.DeleteKvStore(appId, storeId64);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: GetKvStore003
|
||||
* @tc.desc: Get a non-existing KvStore, and the callback function should receive STORE_NOT_FOUND and
|
||||
* get a nullptr.
|
||||
* @tc.type: FUNC
|
||||
* @tc.require: SR000CQDU0 AR000BVTDM
|
||||
* @tc.author: liqiao
|
||||
*/
|
||||
HWTEST_F(DistributedKvDataManagerTest, GetKvStore003, TestSize.Level0)
|
||||
{
|
||||
ZLOGI("GetKvStore003 begin.");
|
||||
std::unique_ptr<KvStore> notExistKvStorePtr;
|
||||
manager.GetKvStore(noCreate, appId, storeId64, [&](Status status, std::unique_ptr<KvStore> kvStore) {
|
||||
notExistKvStorePtr = std::move(kvStore);
|
||||
EXPECT_EQ(status, Status::STORE_NOT_FOUND);
|
||||
});
|
||||
EXPECT_EQ(notExistKvStorePtr, nullptr);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: GetKvStore004
|
||||
* @tc.desc: Create a KvStore 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.Level0)
|
||||
{
|
||||
ZLOGI("GetKvStore004 begin.");
|
||||
std::unique_ptr<KvStore> notExistKvStorePtr;
|
||||
manager.GetKvStore(create, appId, storeIdEmpty, [&](Status status, std::unique_ptr<KvStore> kvStore) {
|
||||
notExistKvStorePtr = std::move(kvStore);
|
||||
ASSERT_EQ(status, Status::INVALID_ARGUMENT);
|
||||
});
|
||||
EXPECT_EQ(notExistKvStorePtr, nullptr);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: GetKvStore005
|
||||
* @tc.desc: Get a KvStore 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.Level0)
|
||||
{
|
||||
ZLOGI("GetKvStore005 begin.");
|
||||
std::unique_ptr<KvStore> notExistKvStorePtr;
|
||||
manager.GetKvStore(noCreate, appId, storeIdEmpty, [&](Status status, std::unique_ptr<KvStore> kvStore) {
|
||||
notExistKvStorePtr = std::move(kvStore);
|
||||
ASSERT_EQ(status, Status::INVALID_ARGUMENT);
|
||||
});
|
||||
EXPECT_EQ(notExistKvStorePtr, nullptr);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: GetKvStore006
|
||||
* @tc.desc: Create a KvStore 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.Level0)
|
||||
{
|
||||
ZLOGI("GetKvStore006 begin.");
|
||||
std::unique_ptr<KvStore> notExistKvStorePtr;
|
||||
manager.GetKvStore(create, appId, storeId65, [&](Status status, std::unique_ptr<KvStore> kvStore) {
|
||||
notExistKvStorePtr = std::move(kvStore);
|
||||
ASSERT_EQ(status, Status::INVALID_ARGUMENT);
|
||||
});
|
||||
EXPECT_EQ(notExistKvStorePtr, nullptr);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: GetKvStore007
|
||||
* @tc.desc: Get a KvStore 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.Level0)
|
||||
{
|
||||
ZLOGI("GetKvStore007 begin.");
|
||||
std::unique_ptr<KvStore> notExistKvStorePtr;
|
||||
manager.GetKvStore(noCreate, appId, storeId65, [&](Status status, std::unique_ptr<KvStore> kvStore) {
|
||||
notExistKvStorePtr = std::move(kvStore);
|
||||
ASSERT_EQ(status, Status::INVALID_ARGUMENT);
|
||||
});
|
||||
EXPECT_EQ(notExistKvStorePtr, 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.Level0)
|
||||
{
|
||||
ZLOGI("GetAllKvStore001 begin.");
|
||||
std::vector<StoreId> idList;
|
||||
manager.GetAllKvStoreId(appId, [&](Status status, std::vector<StoreId> &idList) {
|
||||
EXPECT_EQ(status, Status::SUCCESS);
|
||||
EXPECT_EQ(idList.size(), (unsigned long)0);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: GetAllKvStore002
|
||||
* @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, GetAllKvStore002, TestSize.Level0)
|
||||
{
|
||||
ZLOGI("GetAllKvStore002 begin.");
|
||||
StoreId id1;
|
||||
id1.storeId = "id1";
|
||||
StoreId id2;
|
||||
id2.storeId = "id2";
|
||||
StoreId id3;
|
||||
id3.storeId = "id3";
|
||||
manager.GetKvStore(create, appId, id1, [&](Status status, std::unique_ptr<KvStore> kvStore) {
|
||||
ASSERT_NE(kvStore, nullptr);
|
||||
ASSERT_EQ(status, Status::SUCCESS);
|
||||
});
|
||||
manager.GetKvStore(create, appId, id2, [&](Status status, std::unique_ptr<KvStore> kvStore) {
|
||||
ASSERT_NE(kvStore, nullptr);
|
||||
ASSERT_EQ(status, Status::SUCCESS);
|
||||
});
|
||||
manager.GetKvStore(create, appId, id3, [&](Status status, std::unique_ptr<KvStore> kvStore) {
|
||||
ASSERT_NE(kvStore, nullptr);
|
||||
ASSERT_EQ(status, Status::SUCCESS);
|
||||
});
|
||||
|
||||
std::vector<StoreId> idList;
|
||||
manager.GetAllKvStoreId(appId, [&](Status status, std::vector<StoreId> &idList) {
|
||||
EXPECT_EQ(status, Status::SUCCESS);
|
||||
bool haveId1 = false;
|
||||
bool haveId2 = false;
|
||||
bool haveId3 = false;
|
||||
for (StoreId id : idList) {
|
||||
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(idList.size(), (unsigned long)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.Level0)
|
||||
{
|
||||
ZLOGI("CloseKvStore001 begin.");
|
||||
std::unique_ptr<KvStore> kvStorePtr;
|
||||
manager.GetKvStore(create, appId, storeId64, [&](Status status, std::unique_ptr<KvStore> kvStore) {
|
||||
kvStorePtr = std::move(kvStore);
|
||||
ASSERT_EQ(status, Status::SUCCESS);
|
||||
});
|
||||
ASSERT_NE(kvStorePtr, nullptr);
|
||||
|
||||
Status stat = manager.CloseKvStore(appId, storeId64);
|
||||
EXPECT_EQ(stat, Status::SUCCESS);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: CloseKvStore002
|
||||
* @tc.desc: Close a closed KvStore, and the callback function should return SUCCESS.
|
||||
* @tc.type: FUNC
|
||||
* @tc.require: SR000CQDU0 AR000BVTDM
|
||||
* @tc.author: liqiao
|
||||
*/
|
||||
HWTEST_F(DistributedKvDataManagerTest, CloseKvStore002, TestSize.Level0)
|
||||
{
|
||||
ZLOGI("CloseKvStore002 begin.");
|
||||
std::unique_ptr<KvStore> kvStorePtr;
|
||||
manager.GetKvStore(create, appId, storeId64, [&](Status status, std::unique_ptr<KvStore> kvStore) {
|
||||
kvStorePtr = std::move(kvStore);
|
||||
ASSERT_EQ(status, Status::SUCCESS);
|
||||
});
|
||||
ASSERT_NE(kvStorePtr, 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 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, CloseKvStore003, TestSize.Level0)
|
||||
{
|
||||
ZLOGI("CloseKvStore003 begin.");
|
||||
Status stat = manager.CloseKvStore(appId, storeIdEmpty);
|
||||
EXPECT_EQ(stat, Status::INVALID_ARGUMENT);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: CloseKvStore004
|
||||
* @tc.desc: Close a KvStore 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.Level0)
|
||||
{
|
||||
ZLOGI("CloseKvStore004 begin.");
|
||||
Status stat = manager.CloseKvStore(appId, storeId65);
|
||||
EXPECT_EQ(stat, Status::INVALID_ARGUMENT);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: CloseKvStore005
|
||||
* @tc.desc: Close a non-existing KvStore, and the callback function should return STORE_NOT_OPEN.
|
||||
* @tc.type: FUNC
|
||||
* @tc.require: SR000CQDU0 AR000BVTDM
|
||||
* @tc.author: liqiao
|
||||
*/
|
||||
HWTEST_F(DistributedKvDataManagerTest, CloseKvStore005, TestSize.Level0)
|
||||
{
|
||||
ZLOGI("CloseKvStore005 begin.");
|
||||
Status stat = manager.CloseKvStore(appId, storeId64);
|
||||
EXPECT_EQ(stat, Status::STORE_NOT_OPEN);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: CloseKvStoreMulti001
|
||||
* @tc.desc: Open a KvStore several times and close them one by one, and the callback function should return SUCCESS.
|
||||
* @tc.type: FUNC
|
||||
* @tc.require: SR000CQDU0 AR000CSKRU
|
||||
* @tc.author: liqiao
|
||||
*/
|
||||
HWTEST_F(DistributedKvDataManagerTest, CloseKvStoreMulti001, TestSize.Level0)
|
||||
{
|
||||
ZLOGI("CloseKvStoreMulti001 begin.");
|
||||
std::unique_ptr<KvStore> notExistKvStorePtr;
|
||||
manager.GetKvStore(create, appId, storeId64, [&](Status status, std::unique_ptr<KvStore> kvStore) {
|
||||
notExistKvStorePtr = std::move(kvStore);
|
||||
ASSERT_EQ(status, Status::SUCCESS);
|
||||
});
|
||||
EXPECT_NE(notExistKvStorePtr, nullptr);
|
||||
|
||||
std::unique_ptr<KvStore> existKvStorePtr;
|
||||
manager.GetKvStore(noCreate, appId, storeId64, [&](Status status, std::unique_ptr<KvStore> kvStore) {
|
||||
existKvStorePtr = std::move(kvStore);
|
||||
ASSERT_EQ(status, Status::SUCCESS);
|
||||
});
|
||||
EXPECT_NE(existKvStorePtr, 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 KvStore several times and close them one by one, and the callback function should return SUCCESS.
|
||||
* @tc.type: FUNC
|
||||
* @tc.require: SR000CQDU0 AR000CSKRU
|
||||
* @tc.author: liqiao
|
||||
*/
|
||||
HWTEST_F(DistributedKvDataManagerTest, CloseKvStoreMulti002, TestSize.Level0)
|
||||
{
|
||||
ZLOGI("CloseKvStoreMulti002 begin.");
|
||||
std::unique_ptr<KvStore> notExistKvStorePtr;
|
||||
manager.GetKvStore(create, appId, storeId64, [&](Status status, std::unique_ptr<KvStore> kvStore) {
|
||||
notExistKvStorePtr = std::move(kvStore);
|
||||
ASSERT_EQ(status, Status::SUCCESS);
|
||||
});
|
||||
EXPECT_NE(notExistKvStorePtr, nullptr);
|
||||
|
||||
std::unique_ptr<KvStore> existKvStorePtr1;
|
||||
manager.GetKvStore(noCreate, appId, storeId64, [&](Status status, std::unique_ptr<KvStore> kvStore) {
|
||||
existKvStorePtr1 = std::move(kvStore);
|
||||
ASSERT_EQ(status, Status::SUCCESS);
|
||||
});
|
||||
EXPECT_NE(existKvStorePtr1, nullptr);
|
||||
|
||||
std::unique_ptr<KvStore> existKvStorePtr2;
|
||||
manager.GetKvStore(noCreate, appId, storeId64, [&](Status status, std::unique_ptr<KvStore> kvStore) {
|
||||
existKvStorePtr2 = std::move(kvStore);
|
||||
ASSERT_EQ(status, Status::SUCCESS);
|
||||
});
|
||||
EXPECT_NE(existKvStorePtr2, 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: CloseKvStoreMulti003
|
||||
* @tc.desc: Open a KvStore several times and close them one by one, and the callback function should return SUCCESS.
|
||||
* @tc.type: FUNC
|
||||
* @tc.require: SR000CQDU0 AR000CSKRU
|
||||
* @tc.author: liqiao
|
||||
*/
|
||||
HWTEST_F(DistributedKvDataManagerTest, CloseKvStoreMulti003, TestSize.Level0)
|
||||
{
|
||||
ZLOGI("CloseKvStoreMulti003 begin.");
|
||||
std::unique_ptr<KvStore> notExistKvStorePtr;
|
||||
manager.GetKvStore(create, appId, storeId64, [&](Status status, std::unique_ptr<KvStore> kvStore) {
|
||||
notExistKvStorePtr = std::move(kvStore);
|
||||
ASSERT_EQ(status, Status::SUCCESS);
|
||||
});
|
||||
EXPECT_NE(notExistKvStorePtr, nullptr);
|
||||
|
||||
std::unique_ptr<KvStore> existKvStorePtr1;
|
||||
manager.GetKvStore(noCreate, appId, storeId64, [&](Status status, std::unique_ptr<KvStore> kvStore) {
|
||||
existKvStorePtr1 = std::move(kvStore);
|
||||
ASSERT_EQ(status, Status::SUCCESS);
|
||||
});
|
||||
EXPECT_NE(existKvStorePtr1, nullptr);
|
||||
|
||||
std::unique_ptr<KvStore> existKvStorePtr2;
|
||||
manager.GetKvStore(noCreate, appId, storeId64, [&](Status status, std::unique_ptr<KvStore> kvStore) {
|
||||
existKvStorePtr2 = std::move(kvStore);
|
||||
ASSERT_EQ(status, Status::SUCCESS);
|
||||
});
|
||||
EXPECT_NE(existKvStorePtr2, nullptr);
|
||||
|
||||
Status stat = manager.CloseKvStore(appId, storeId64);
|
||||
EXPECT_EQ(stat, Status::SUCCESS);
|
||||
|
||||
stat = manager.CloseKvStore(appId, storeId64);
|
||||
EXPECT_EQ(stat, Status::SUCCESS);
|
||||
|
||||
Key keyInt = "math_score_int";
|
||||
Value valueInt = Value(TransferTypeToByteArray<int>(-100));
|
||||
Status status = existKvStorePtr2->Put(keyInt, valueInt);
|
||||
EXPECT_EQ(Status::SUCCESS, status) << "KvStore put data return wrong status";
|
||||
std::unique_ptr<KvStoreSnapshot> kvStoreSnapshotPtr;
|
||||
existKvStorePtr2->GetKvStoreSnapshot(nullptr,
|
||||
[&](Status status, std::unique_ptr<KvStoreSnapshot> kvStoreSnapshot) {
|
||||
kvStoreSnapshotPtr = std::move(kvStoreSnapshot);
|
||||
});
|
||||
|
||||
EXPECT_NE(nullptr, kvStoreSnapshotPtr) << "kvStoreSnapshotPtr is nullptr";
|
||||
|
||||
std::unique_ptr<KvStore> existKvStorePtr3;
|
||||
manager.GetKvStore(noCreate, appId, storeId64, [&](Status status, std::unique_ptr<KvStore> kvStore) {
|
||||
existKvStorePtr3 = std::move(kvStore);
|
||||
ASSERT_EQ(status, Status::SUCCESS);
|
||||
});
|
||||
EXPECT_NE(existKvStorePtr3, nullptr);
|
||||
|
||||
stat = manager.CloseKvStore(appId, storeId64);
|
||||
EXPECT_EQ(stat, Status::SUCCESS);
|
||||
|
||||
Value valueRetInt;
|
||||
Status statusTmp = kvStoreSnapshotPtr->Get(keyInt, valueRetInt);
|
||||
EXPECT_EQ(Status::SUCCESS, statusTmp) << "KvStoreSnapshot get data return wrong status";
|
||||
EXPECT_EQ(valueInt, valueRetInt) << "valueInt and valueRetInt are not equal";
|
||||
|
||||
stat = manager.CloseKvStore(appId, storeId64);
|
||||
EXPECT_EQ(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.Level0)
|
||||
{
|
||||
ZLOGI("CloseAllKvStore001 begin.");
|
||||
std::unique_ptr<KvStore> kvStorePtr1;
|
||||
manager.GetKvStore(create, appId, storeId64, [&](Status status, std::unique_ptr<KvStore> kvStore) {
|
||||
kvStorePtr1 = std::move(kvStore);
|
||||
ASSERT_EQ(status, Status::SUCCESS);
|
||||
});
|
||||
ASSERT_NE(kvStorePtr1, nullptr);
|
||||
|
||||
std::unique_ptr<KvStore> kvStorePtr2;
|
||||
manager.GetKvStore(create, appId, storeIdTest, [&](Status status, std::unique_ptr<KvStore> kvStore) {
|
||||
kvStorePtr2 = std::move(kvStore);
|
||||
ASSERT_EQ(status, Status::SUCCESS);
|
||||
});
|
||||
ASSERT_NE(kvStorePtr2, 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.Level0)
|
||||
{
|
||||
ZLOGI("CloseAllKvStore002 begin.");
|
||||
std::unique_ptr<KvStore> kvStorePtr1;
|
||||
manager.GetKvStore(create, appId, storeId64, [&](Status status, std::unique_ptr<KvStore> kvStore) {
|
||||
kvStorePtr1 = std::move(kvStore);
|
||||
ASSERT_EQ(status, Status::SUCCESS);
|
||||
});
|
||||
ASSERT_NE(kvStorePtr1, nullptr);
|
||||
|
||||
std::unique_ptr<KvStore> kvStorePtr2;
|
||||
manager.GetKvStore(create, appId, storeIdTest, [&](Status status, std::unique_ptr<KvStore> kvStore) {
|
||||
kvStorePtr2 = std::move(kvStore);
|
||||
ASSERT_EQ(status, Status::SUCCESS);
|
||||
});
|
||||
ASSERT_NE(kvStorePtr2, 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.Level0)
|
||||
{
|
||||
ZLOGI("DeleteKvStore001 begin.");
|
||||
std::unique_ptr<KvStore> kvStorePtr;
|
||||
manager.GetKvStore(create, appId, storeId64, [&](Status status, std::unique_ptr<KvStore> kvStore) {
|
||||
kvStorePtr = std::move(kvStore);
|
||||
ASSERT_EQ(status, Status::SUCCESS);
|
||||
});
|
||||
ASSERT_NE(kvStorePtr, nullptr);
|
||||
|
||||
Status stat = manager.CloseKvStore(appId, storeId64);
|
||||
ASSERT_EQ(stat, Status::SUCCESS);
|
||||
|
||||
stat = manager.DeleteKvStore(appId, storeId64);
|
||||
EXPECT_EQ(stat, Status::SUCCESS);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: DeleteKvStore002
|
||||
* @tc.desc: Delete an opened KvStore, and the callback function should return SUCCESS.
|
||||
* @tc.type: FUNC
|
||||
* @tc.require: SR000CQDU0 AR000BVTDM
|
||||
* @tc.author: liqiao
|
||||
*/
|
||||
HWTEST_F(DistributedKvDataManagerTest, DeleteKvStore002, TestSize.Level0)
|
||||
{
|
||||
ZLOGI("DeleteKvStore002 begin.");
|
||||
std::unique_ptr<KvStore> kvStorePtr;
|
||||
manager.GetKvStore(create, appId, storeId64, [&](Status status, std::unique_ptr<KvStore> kvStore) {
|
||||
kvStorePtr = std::move(kvStore);
|
||||
ASSERT_EQ(status, Status::SUCCESS);
|
||||
});
|
||||
ASSERT_NE(kvStorePtr, nullptr);
|
||||
|
||||
// first close it if opened, and then delete it.
|
||||
Status stat = manager.DeleteKvStore(appId, storeId64);
|
||||
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.Level0)
|
||||
{
|
||||
ZLOGI("DeleteKvStore003 begin.");
|
||||
Status stat = manager.DeleteKvStore(appId, storeId64);
|
||||
EXPECT_EQ(stat, Status::DB_ERROR);
|
||||
}
|
||||
|
||||
/**
|
||||
* @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.Level0)
|
||||
{
|
||||
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.Level0)
|
||||
{
|
||||
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.Level0)
|
||||
{
|
||||
ZLOGI("DeleteAllKvStore001 begin.");
|
||||
std::unique_ptr<KvStore> kvStorePtr1;
|
||||
manager.GetKvStore(create, appId, storeId64, [&](Status status, std::unique_ptr<KvStore> kvStore) {
|
||||
kvStorePtr1 = std::move(kvStore);
|
||||
ASSERT_EQ(status, Status::SUCCESS);
|
||||
});
|
||||
ASSERT_NE(kvStorePtr1, nullptr);
|
||||
std::unique_ptr<KvStore> kvStorePtr2;
|
||||
manager.GetKvStore(create, appId, storeIdTest, [&](Status status, std::unique_ptr<KvStore> kvStore) {
|
||||
kvStorePtr2 = std::move(kvStore);
|
||||
ASSERT_EQ(status, Status::SUCCESS);
|
||||
});
|
||||
ASSERT_NE(kvStorePtr2, 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);
|
||||
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.Level0)
|
||||
{
|
||||
ZLOGI("DeleteAllKvStore002 begin.");
|
||||
std::unique_ptr<KvStore> kvStorePtr1;
|
||||
manager.GetKvStore(create, appId, storeId64, [&](Status status, std::unique_ptr<KvStore> kvStore) {
|
||||
kvStorePtr1 = std::move(kvStore);
|
||||
ASSERT_EQ(status, Status::SUCCESS);
|
||||
});
|
||||
ASSERT_NE(kvStorePtr1, nullptr);
|
||||
std::unique_ptr<KvStore> kvStorePtr2;
|
||||
manager.GetKvStore(create, appId, storeIdTest, [&](Status status, std::unique_ptr<KvStore> kvStore) {
|
||||
kvStorePtr2 = std::move(kvStore);
|
||||
ASSERT_EQ(status, Status::SUCCESS);
|
||||
});
|
||||
ASSERT_NE(kvStorePtr2, nullptr);
|
||||
Status stat = manager.CloseKvStore(appId, storeId64);
|
||||
EXPECT_EQ(stat, Status::SUCCESS);
|
||||
|
||||
stat = manager.DeleteAllKvStore(appId);
|
||||
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.Level0)
|
||||
{
|
||||
ZLOGI("DeleteAllKvStore003 begin.");
|
||||
Status stat = manager.DeleteAllKvStore(appId);
|
||||
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.Level0)
|
||||
{
|
||||
ZLOGI("RegisterKvStoreServiceDeathRecipient001 begin.");
|
||||
std::shared_ptr<KvStoreDeathRecipient> kvStoreDeathRecipientPtr = std::make_shared<MyDeathRecipient>();
|
||||
manager.RegisterKvStoreServiceDeathRecipient(kvStoreDeathRecipientPtr);
|
||||
kvStoreDeathRecipientPtr->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.Level0)
|
||||
{
|
||||
ZLOGI("UnRegisterKvStoreServiceDeathRecipient001 begin.");
|
||||
std::shared_ptr<KvStoreDeathRecipient> kvStoreDeathRecipientPtr = std::make_shared<MyDeathRecipient>();
|
||||
manager.UnRegisterKvStoreServiceDeathRecipient(kvStoreDeathRecipientPtr);
|
||||
}
|
||||
|
||||
class DeviceListenerImpl : public DeviceStatusChangeListener {
|
||||
public:
|
||||
void OnDeviceChanged(const DeviceInfo &info, const DeviceChangeType &type) const override
|
||||
{
|
||||
}
|
||||
DeviceFilterStrategy GetFilterStrategy() const override
|
||||
{
|
||||
return DeviceFilterStrategy::NO_FILTER;
|
||||
}
|
||||
};
|
||||
/**
|
||||
* @tc.name: GetDevice001
|
||||
* @tc.desc: Get device id.
|
||||
* @tc.type: FUNC
|
||||
* @tc.require: SR000DOH1R AR000DPSGU
|
||||
* @tc.author: hongbo
|
||||
*/
|
||||
HWTEST_F(DistributedKvDataManagerTest, GetDevice001, TestSize.Level0)
|
||||
{
|
||||
ZLOGI("GetDevice001 begin.");
|
||||
DeviceInfo info;
|
||||
Status status = manager.GetLocalDevice(info);
|
||||
EXPECT_EQ(Status::SUCCESS, status) << "expected getLocalDevice true";
|
||||
EXPECT_TRUE(info.deviceId.size() > 0) << "expected deviceId exist";
|
||||
|
||||
std::vector<DeviceInfo> infos;
|
||||
status = manager.GetDeviceList(infos, DeviceFilterStrategy::FILTER);
|
||||
// EXPECT_EQ(Status::SUCCESS, status) << "expected GetDeviceList true";
|
||||
// EXPECT_TRUE(infos.size() == 0) << "expected GetDeviceList exist";
|
||||
|
||||
auto listener = std::make_shared<DeviceListenerImpl>();
|
||||
status = manager.StartWatchDeviceChange(listener);
|
||||
EXPECT_EQ(Status::SUCCESS, status) << "expected StartWatchDeviceChange true";
|
||||
status = manager.StopWatchDeviceChange(listener);
|
||||
EXPECT_EQ(Status::SUCCESS, status) << "expected StopWatchDeviceChange true";
|
||||
}
|
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,486 @@
|
||||
/*
|
||||
* 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 "KvStoreSnapshotClientTest"
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <gtest/gtest.h>
|
||||
#include <unistd.h>
|
||||
#include <vector>
|
||||
#include "distributed_kv_data_manager.h"
|
||||
#include "log_print.h"
|
||||
#include "types.h"
|
||||
|
||||
using namespace testing::ext;
|
||||
using namespace OHOS::DistributedKv;
|
||||
|
||||
class KvStoreSnapshotClientTest : public testing::Test {
|
||||
public:
|
||||
static void SetUpTestCase(void);
|
||||
static void TearDownTestCase(void);
|
||||
void SetUp();
|
||||
void TearDown();
|
||||
|
||||
static std::unique_ptr<KvStore> kvStorePtr; // declare kv store instance.
|
||||
static Status statusGetKvStore;
|
||||
static DistributedKvDataManager manager;
|
||||
};
|
||||
|
||||
DistributedKvDataManager KvStoreSnapshotClientTest::manager;
|
||||
std::unique_ptr<KvStore> KvStoreSnapshotClientTest::kvStorePtr = nullptr;
|
||||
Status KvStoreSnapshotClientTest::statusGetKvStore = Status::ERROR;
|
||||
|
||||
void KvStoreSnapshotClientTest::SetUpTestCase(void)
|
||||
{
|
||||
ZLOGI("KvStoreSnapshotClientTest::SetUpTestCase");
|
||||
Options options;
|
||||
options.createIfMissing = true;
|
||||
options.encrypt = false; // not supported yet.
|
||||
options.autoSync = true; // not supported yet.
|
||||
options.kvStoreType = KvStoreType::MULTI_VERSION;
|
||||
|
||||
AppId appId;
|
||||
appId.appId = "odmf"; // define app name.
|
||||
StoreId storeId;
|
||||
storeId.storeId = "student"; // define kvstore(database) name.
|
||||
|
||||
manager.CloseAllKvStore(appId);
|
||||
manager.DeleteAllKvStore(appId);
|
||||
// [create and] open and initialize kvstore instance.
|
||||
manager.GetKvStore(options, appId, storeId, [&](Status status, std::unique_ptr<KvStore> kvStore) {
|
||||
statusGetKvStore = status;
|
||||
kvStorePtr = std::move(kvStore);
|
||||
});
|
||||
}
|
||||
|
||||
void KvStoreSnapshotClientTest::TearDownTestCase(void)
|
||||
{
|
||||
ZLOGI("KvStoreSnapshotClientTest::TearDownTestCase");
|
||||
if (kvStorePtr != nullptr) {
|
||||
AppId appId;
|
||||
appId.appId = "odmf"; // define app name.
|
||||
StoreId storeId;
|
||||
storeId.storeId = "student"; // define kvstore(database) name.
|
||||
manager.CloseKvStore(appId, storeId);
|
||||
}
|
||||
}
|
||||
|
||||
void KvStoreSnapshotClientTest::SetUp(void)
|
||||
{}
|
||||
|
||||
void KvStoreSnapshotClientTest::TearDown(void)
|
||||
{}
|
||||
|
||||
/**
|
||||
* @tc.name: KvStoreSnapshotDdmGet001
|
||||
* @tc.desc: Get values of keys in KvStore.
|
||||
* @tc.type: FUNC
|
||||
* @tc.require: AR000C6GBG
|
||||
* @tc.author: liuyuhui
|
||||
*/
|
||||
HWTEST_F(KvStoreSnapshotClientTest, KvStoreSnapshotDdmGet001, TestSize.Level0)
|
||||
{
|
||||
ZLOGI("KvStoreSnapshotDdmGet001 begin.");
|
||||
EXPECT_EQ(Status::SUCCESS, statusGetKvStore) << "statusGetKvStore return wrong status";
|
||||
EXPECT_NE(nullptr, kvStorePtr) << "kvStorePtr is nullptr";
|
||||
|
||||
Key key = "age";
|
||||
Value value = "18";
|
||||
Status status = kvStorePtr->Put(key, value); // insert or update key-value
|
||||
EXPECT_EQ(Status::SUCCESS, status) << "KvStore put data return wrong status";
|
||||
|
||||
std::unique_ptr<KvStoreSnapshot> kvStoreSnapshotPtr;
|
||||
// [create and] open and initialize kvstore snapshot instance.
|
||||
kvStorePtr->GetKvStoreSnapshot(nullptr, /* (KvStoreObserver ) */
|
||||
[&](Status status, std::unique_ptr<KvStoreSnapshot> kvStoreSnapshot) {
|
||||
kvStoreSnapshotPtr = std::move(kvStoreSnapshot);
|
||||
});
|
||||
|
||||
EXPECT_NE(nullptr, kvStoreSnapshotPtr) << "kvStoreSnapshotPtr is nullptr";
|
||||
// get value from kvstore.
|
||||
Value valueRet;
|
||||
Status statusRet = kvStoreSnapshotPtr->Get(key, valueRet);
|
||||
EXPECT_EQ(Status::SUCCESS, statusRet) << "KvStoreSnapshot get data return wrong status";
|
||||
|
||||
EXPECT_EQ(value, valueRet) << "value and valueRet are not equal";
|
||||
kvStorePtr->ReleaseKvStoreSnapshot(std::move(kvStoreSnapshotPtr));
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: KvStoreSnapshotDdmGet002
|
||||
* @tc.desc: Get key values in KvStore when keys do not exist.
|
||||
* @tc.type: FUNC
|
||||
* @tc.require: AR000C6GBG
|
||||
* @tc.author: liuyuhui
|
||||
*/
|
||||
HWTEST_F(KvStoreSnapshotClientTest, KvStoreSnapshotDdmGet002, TestSize.Level0)
|
||||
{
|
||||
ZLOGI("KvStoreSnapshotDdmGet002 begin.");
|
||||
EXPECT_EQ(Status::SUCCESS, statusGetKvStore) << "statusGetKvStore return wrong status";
|
||||
EXPECT_NE(nullptr, kvStorePtr) << "kvStorePtr is nullptr";
|
||||
|
||||
Key key = "age";
|
||||
Value value = "18";
|
||||
Status status1 = kvStorePtr->Put(key, value); // insert or update key-value
|
||||
EXPECT_EQ(Status::SUCCESS, status1) << "KvStore put data return wrong status";
|
||||
|
||||
Status status2 = kvStorePtr->Delete(key); // delete data
|
||||
EXPECT_EQ(Status::SUCCESS, status2) << "KvStore delete data return wrong status";
|
||||
|
||||
std::unique_ptr<KvStoreSnapshot> kvStoreSnapshotPtr;
|
||||
// [create and] open and initialize kvstore snapshot instance.
|
||||
kvStorePtr->GetKvStoreSnapshot(nullptr, /* (KvStoreObserver ) */
|
||||
[&](Status status, std::unique_ptr<KvStoreSnapshot> kvStoreSnapshot) {
|
||||
kvStoreSnapshotPtr = std::move(kvStoreSnapshot);
|
||||
});
|
||||
|
||||
EXPECT_NE(nullptr, kvStoreSnapshotPtr) << "kvStoreSnapshotPtr is nullptr";
|
||||
// get value from kvstore.
|
||||
Value valueRet;
|
||||
Status statusRet = kvStoreSnapshotPtr->Get(key, valueRet);
|
||||
EXPECT_EQ(Status::KEY_NOT_FOUND, statusRet);
|
||||
EXPECT_EQ(Status::KEY_NOT_FOUND, statusRet) << "KvStoreSnapshot get data return wrong status";
|
||||
EXPECT_EQ("", valueRet.ToString()) << "value and valueRet are not equal";
|
||||
kvStorePtr->ReleaseKvStoreSnapshot(std::move(kvStoreSnapshotPtr));
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: KvStoreSnapshotDdmGet003
|
||||
* @tc.desc: Get key values in KvStore when keys are invalid.
|
||||
* @tc.type: FUNC
|
||||
* @tc.require: AR000C6GBG
|
||||
* @tc.author: liuyuhui
|
||||
*/
|
||||
HWTEST_F(KvStoreSnapshotClientTest, KvStoreSnapshotDdmGet003, TestSize.Level0)
|
||||
{
|
||||
ZLOGI("KvStoreSnapshotDdmGet003 begin.");
|
||||
EXPECT_EQ(Status::SUCCESS, statusGetKvStore) << "statusGetKvStore return wrong status";
|
||||
EXPECT_NE(nullptr, kvStorePtr) << "kvStorePtr is nullptr";
|
||||
std::unique_ptr<KvStoreSnapshot> kvStoreSnapshotPtr;
|
||||
// [create and] open and initialize kvstore snapshot instance.
|
||||
kvStorePtr->GetKvStoreSnapshot(nullptr, /* (KvStoreObserver ) */
|
||||
[&](Status status, std::unique_ptr<KvStoreSnapshot> kvStoreSnapshot) {
|
||||
kvStoreSnapshotPtr = std::move(kvStoreSnapshot);
|
||||
});
|
||||
|
||||
EXPECT_NE(nullptr, kvStoreSnapshotPtr) << "kvStoreSnapshotPtr is nullptr";
|
||||
|
||||
// get value from kvstore.
|
||||
Key key;
|
||||
Value valueRet;
|
||||
Status statusRet = kvStoreSnapshotPtr->Get(key, valueRet);
|
||||
EXPECT_EQ(Status::INVALID_ARGUMENT, statusRet);
|
||||
EXPECT_EQ(Status::INVALID_ARGUMENT, statusRet) << "KvStoreSnapshot get data return wrong status";
|
||||
EXPECT_EQ("", valueRet.ToString()) << "value and valueRet are not equal";
|
||||
kvStorePtr->ReleaseKvStoreSnapshot(std::move(kvStoreSnapshotPtr));
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: KvStoreSnapshotDdmGetEntries001
|
||||
* @tc.desc: Get key entries from KvStore.
|
||||
* @tc.type: FUNC
|
||||
* @tc.require: AR000C6GBG
|
||||
* @tc.author: liuyuhui
|
||||
*/
|
||||
HWTEST_F(KvStoreSnapshotClientTest, KvStoreSnapshotDdmGetEntries001, TestSize.Level0)
|
||||
{
|
||||
ZLOGI("KvStoreSnapshotDdmGetEntries001 begin.");
|
||||
EXPECT_EQ(Status::SUCCESS, statusGetKvStore) << "statusGetKvStore return wrong status";
|
||||
EXPECT_NE(nullptr, kvStorePtr) << "kvStorePtr is nullptr";
|
||||
kvStorePtr->Clear();
|
||||
|
||||
// store entries to kvstore.
|
||||
std::vector<Entry> entries;
|
||||
Entry entry1, entry2, entry3;
|
||||
entry1.key = "student_name_mali";
|
||||
entry1.value = "age:20";
|
||||
entry2.key = "student_name_caixu";
|
||||
entry2.value = "age:19";
|
||||
entry3.key = "student_name_liuyue";
|
||||
entry3.value = "age:23";
|
||||
entries.push_back(entry1);
|
||||
entries.push_back(entry2);
|
||||
entries.push_back(entry3);
|
||||
|
||||
Status status = kvStorePtr->PutBatch(entries);
|
||||
EXPECT_EQ(Status::SUCCESS, status) << "KvStore putbatch data return wrong status";
|
||||
|
||||
// get entries
|
||||
Key keyPrefixStudent = "student_name_";
|
||||
std::vector<Entry> students;
|
||||
Key token;
|
||||
Status statusTmp = Status::ERROR;
|
||||
std::unique_ptr<KvStoreSnapshot> kvStoreSnapshotPtr;
|
||||
// [create and] open and initialize kvstore snapshot instance.
|
||||
kvStorePtr->GetKvStoreSnapshot(nullptr, /* (KvStoreObserver ) */
|
||||
[&](Status status, std::unique_ptr<KvStoreSnapshot> kvStoreSnapshot) {
|
||||
kvStoreSnapshotPtr = std::move(kvStoreSnapshot);
|
||||
});
|
||||
|
||||
EXPECT_NE(nullptr, kvStoreSnapshotPtr) << "kvStoreSnapshotPtr is nullptr";
|
||||
kvStoreSnapshotPtr->GetEntries(keyPrefixStudent,
|
||||
[&](Status status, std::vector<Entry> &entries) {
|
||||
statusTmp = std::move(status);
|
||||
students = std::move(entries);
|
||||
});
|
||||
EXPECT_EQ(3, static_cast<int>(students.size())) << "GetEntries failed";
|
||||
EXPECT_EQ(Status::SUCCESS, statusTmp) << "KvStore GetEntries data return wrong status";
|
||||
kvStorePtr->ReleaseKvStoreSnapshot(std::move(kvStoreSnapshotPtr));
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: KvStoreSnapshotDdmGetEntries002
|
||||
* @tc.desc: Get key entries from KvStore when the keyPrefix does not exist.
|
||||
* @tc.type: FUNC
|
||||
* @tc.require: AR000C6GBG
|
||||
* @tc.author: liuyuhui
|
||||
*/
|
||||
HWTEST_F(KvStoreSnapshotClientTest, KvStoreSnapshotDdmGetEntries002, TestSize.Level0)
|
||||
{
|
||||
ZLOGI("KvStoreSnapshotDdmGetEntries002 begin.");
|
||||
EXPECT_EQ(Status::SUCCESS, statusGetKvStore) << "statusGetKvStore return wrong status";
|
||||
EXPECT_NE(nullptr, kvStorePtr) << "kvStorePtr is nullptr";
|
||||
kvStorePtr->Clear();
|
||||
|
||||
// store entries to kvstore.
|
||||
std::vector<Entry> entries;
|
||||
Entry entry1, entry2, entry3;
|
||||
entry1.key = "student_name_mali";
|
||||
entry1.value = "age:20";
|
||||
entry2.key = "student_name_caixu";
|
||||
entry2.value = "age:19";
|
||||
entry3.key = "student_name_liuyue";
|
||||
entry3.value = "age:23";
|
||||
entries.push_back(entry1);
|
||||
entries.push_back(entry2);
|
||||
entries.push_back(entry3);
|
||||
|
||||
Status status = kvStorePtr->PutBatch(entries);
|
||||
EXPECT_EQ(Status::SUCCESS, status) << "KvStore putbatch data return wrong status";
|
||||
|
||||
// get entries
|
||||
Key keyPrefixStudent = "teacher_name_";
|
||||
std::vector<Entry> students;
|
||||
Key token;
|
||||
Status statusTmp = Status::ERROR;
|
||||
std::unique_ptr<KvStoreSnapshot> kvStoreSnapshotPtr;
|
||||
// [create and] open and initialize kvstore snapshot instance.
|
||||
kvStorePtr->GetKvStoreSnapshot(nullptr, /* (KvStoreObserver ) */
|
||||
[&](Status status, std::unique_ptr<KvStoreSnapshot> kvStoreSnapshot) {
|
||||
kvStoreSnapshotPtr = std::move(kvStoreSnapshot);
|
||||
});
|
||||
|
||||
EXPECT_NE(nullptr, kvStoreSnapshotPtr) << "kvStoreSnapshotPtr is nullptr";
|
||||
kvStoreSnapshotPtr->GetEntries(keyPrefixStudent,
|
||||
[&](Status status, std::vector<Entry> &entries) {
|
||||
statusTmp = std::move(status);
|
||||
students = std::move(entries);
|
||||
});
|
||||
EXPECT_EQ(0, static_cast<int>(students.size())) << "GetEntries fail";
|
||||
EXPECT_EQ(Status::KEY_NOT_FOUND, statusTmp) << "KvStore GetEntries data return wrong status";
|
||||
kvStorePtr->ReleaseKvStoreSnapshot(std::move(kvStoreSnapshotPtr));
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: KvStoreSnapshotDdmGetEntries003
|
||||
* @tc.desc: Get all key entries from KvStore when the keys are empty.
|
||||
* @tc.type: FUNC
|
||||
* @tc.require: AR000C6GBG
|
||||
* @tc.author: liuyuhui
|
||||
*/
|
||||
HWTEST_F(KvStoreSnapshotClientTest, KvStoreSnapshotDdmGetEntries003, TestSize.Level0)
|
||||
{
|
||||
ZLOGI("KvStoreSnapshotDdmGetEntries003 begin.");
|
||||
EXPECT_EQ(Status::SUCCESS, statusGetKvStore) << "statusGetKvStore return wrong status";
|
||||
EXPECT_NE(nullptr, kvStorePtr) << "kvStorePtr is nullptr";
|
||||
kvStorePtr->Clear();
|
||||
|
||||
// store entries to kvstore.
|
||||
std::vector<Entry> entries;
|
||||
Entry entry1, entry2, entry3;
|
||||
entry1.key = "student_name_mali";
|
||||
entry1.value = "age:20";
|
||||
entry2.key = "student_name_caixu";
|
||||
entry2.value = "age:19";
|
||||
entry3.key = "student_name_liuyue";
|
||||
entry3.value = "age:23";
|
||||
entries.push_back(entry1);
|
||||
entries.push_back(entry2);
|
||||
entries.push_back(entry3);
|
||||
|
||||
Status status = kvStorePtr->PutBatch(entries);
|
||||
EXPECT_EQ(Status::SUCCESS, status) << "KvStore putbatch data return wrong status";
|
||||
|
||||
// get entries
|
||||
Key keyPrefixStudent = "";
|
||||
std::vector<Entry> students;
|
||||
Key token;
|
||||
Status statusTmp = Status::ERROR;
|
||||
std::unique_ptr<KvStoreSnapshot> kvStoreSnapshotPtr;
|
||||
// [create and] open and initialize kvstore snapshot instance.
|
||||
kvStorePtr->GetKvStoreSnapshot(nullptr, /* (KvStoreObserver ) */
|
||||
[&](Status status, std::unique_ptr<KvStoreSnapshot> kvStoreSnapshot) {
|
||||
kvStoreSnapshotPtr = std::move(kvStoreSnapshot);
|
||||
});
|
||||
|
||||
EXPECT_NE(nullptr, kvStoreSnapshotPtr) << "kvStoreSnapshotPtr is nullptr";
|
||||
kvStoreSnapshotPtr->GetEntries(keyPrefixStudent,
|
||||
[&](Status status, std::vector<Entry> &entries) {
|
||||
statusTmp = std::move(status);
|
||||
students = std::move(entries);
|
||||
});
|
||||
EXPECT_EQ(3, static_cast<int>(students.size())) << "GetEntries fail";
|
||||
EXPECT_EQ(Status::SUCCESS, statusTmp) << "KvStore GetEntries data return wrong status";
|
||||
kvStorePtr->ReleaseKvStoreSnapshot(std::move(kvStoreSnapshotPtr));
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: KvStoreSnapshotDdmGetEntries004
|
||||
* @tc.desc: Get all key entries from KvStore when the keys contain only space blank.
|
||||
* @tc.type: FUNC
|
||||
* @tc.require: AR000C6GBG
|
||||
* @tc.author: liuyuhui
|
||||
*/
|
||||
HWTEST_F(KvStoreSnapshotClientTest, KvStoreSnapshotDdmGetEntries004, TestSize.Level0)
|
||||
{
|
||||
ZLOGI("KvStoreSnapshotDdmGetEntries004 begin.");
|
||||
EXPECT_EQ(Status::SUCCESS, statusGetKvStore) << "statusGetKvStore return wrong status";
|
||||
EXPECT_NE(nullptr, kvStorePtr) << "kvStorePtr is nullptr";
|
||||
kvStorePtr->Clear();
|
||||
|
||||
// store entries to kvstore.
|
||||
std::vector<Entry> entries;
|
||||
Entry entry1, entry2, entry3;
|
||||
entry1.key = "student_name_mali";
|
||||
entry1.value = "age:20";
|
||||
entry2.key = "student_name_caixu";
|
||||
entry2.value = "age:19";
|
||||
entry3.key = "student_name_liuyue";
|
||||
entry3.value = "age:23";
|
||||
entries.push_back(entry1);
|
||||
entries.push_back(entry2);
|
||||
entries.push_back(entry3);
|
||||
|
||||
Status status = kvStorePtr->PutBatch(entries);
|
||||
EXPECT_EQ(Status::SUCCESS, status) << "KvStore putbatch data return wrong status";
|
||||
|
||||
// get entries
|
||||
Key keyPrefixStudent = " ";
|
||||
std::vector<Entry> students;
|
||||
Key token;
|
||||
Status statusTmp = Status::ERROR;
|
||||
std::unique_ptr<KvStoreSnapshot> kvStoreSnapshotPtr;
|
||||
// [create and] open and initialize kvstore snapshot instance.
|
||||
kvStorePtr->GetKvStoreSnapshot(nullptr, /* (KvStoreObserver ) */
|
||||
[&](Status status, std::unique_ptr<KvStoreSnapshot> kvStoreSnapshot) {
|
||||
kvStoreSnapshotPtr = std::move(kvStoreSnapshot);
|
||||
});
|
||||
|
||||
EXPECT_NE(nullptr, kvStoreSnapshotPtr) << "kvStoreSnapshotPtr is nullptr";
|
||||
kvStoreSnapshotPtr->GetEntries(keyPrefixStudent,
|
||||
[&](Status status, std::vector<Entry> &entries) {
|
||||
statusTmp = std::move(status);
|
||||
students = std::move(entries);
|
||||
});
|
||||
EXPECT_EQ(3, static_cast<int>(students.size())) << "GetEntries fail";
|
||||
EXPECT_EQ(Status::SUCCESS, statusTmp) << "KvStore GetEntries data return wrong status";
|
||||
kvStorePtr->ReleaseKvStoreSnapshot(std::move(kvStoreSnapshotPtr));
|
||||
}
|
||||
|
||||
std::string Generate1025KeyLen()
|
||||
{
|
||||
// Generate key and the length is more than 1024;
|
||||
std::string str("prefix");
|
||||
for (int i = 0; i < 1024; i++) {
|
||||
str += "a";
|
||||
}
|
||||
return str;
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: KvStoreSnapshotDdmGetEntries005
|
||||
* @tc.desc: Get key entries from KvStore when the keyPrefix is invalid.
|
||||
* @tc.type: FUNC
|
||||
* @tc.require: AR000C6GBG
|
||||
* @tc.author: liuyuhui
|
||||
*/
|
||||
HWTEST_F(KvStoreSnapshotClientTest, KvStoreSnapshotDdmGetEntries005, TestSize.Level0)
|
||||
{
|
||||
ZLOGI("KvStoreSnapshotDdmGetEntries005 begin.");
|
||||
EXPECT_EQ(Status::SUCCESS, statusGetKvStore) << "statusGetKvStore return wrong status";
|
||||
EXPECT_NE(nullptr, kvStorePtr) << "kvStorePtr is nullptr";
|
||||
kvStorePtr->Clear();
|
||||
|
||||
// store entries to kvstore.
|
||||
std::vector<Entry> entries;
|
||||
Entry entry1, entry2, entry3;
|
||||
entry1.key = "student_name_mali";
|
||||
entry1.value = "age:20";
|
||||
entry2.key = "student_name_caixu";
|
||||
entry2.value = "age:19";
|
||||
entry3.key = "student_name_liuyue";
|
||||
entry3.value = "age:23";
|
||||
entries.push_back(entry1);
|
||||
entries.push_back(entry2);
|
||||
entries.push_back(entry3);
|
||||
|
||||
Status status = kvStorePtr->PutBatch(entries);
|
||||
EXPECT_EQ(Status::SUCCESS, status) << "KvStore putbatch data return wrong status";
|
||||
|
||||
// get entries
|
||||
Key keyPrefixStudent = Generate1025KeyLen();
|
||||
std::vector<Entry> students;
|
||||
Key token;
|
||||
Status statusTmp = Status::ERROR;
|
||||
std::unique_ptr<KvStoreSnapshot> kvStoreSnapshotPtr;
|
||||
// [create and] open and initialize kvstore snapshot instance.
|
||||
kvStorePtr->GetKvStoreSnapshot(nullptr, /* (KvStoreObserver ) */
|
||||
[&](Status status, std::unique_ptr<KvStoreSnapshot> kvStoreSnapshot) {
|
||||
kvStoreSnapshotPtr = std::move(kvStoreSnapshot);
|
||||
});
|
||||
|
||||
EXPECT_NE(nullptr, kvStoreSnapshotPtr) << "kvStoreSnapshotPtr is nullptr";
|
||||
kvStoreSnapshotPtr->GetEntries(keyPrefixStudent,
|
||||
[&](Status status, std::vector<Entry> &entries) {
|
||||
statusTmp = std::move(status);
|
||||
students = std::move(entries);
|
||||
});
|
||||
EXPECT_EQ(0, static_cast<int>(students.size())) << "invalid argument, GetEntries fail";
|
||||
EXPECT_EQ(Status::INVALID_ARGUMENT, statusTmp) << "KvStore GetEntries data return wrong status";
|
||||
kvStorePtr->ReleaseKvStoreSnapshot(std::move(kvStoreSnapshotPtr));
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: EntryIpcInterfaceTest001
|
||||
* @tc.desc: Marshal and unmarshall key entries.
|
||||
* @tc.type: FUNC
|
||||
* @tc.require: AR000C6GBG
|
||||
* @tc.author: liuyuhui
|
||||
*/
|
||||
HWTEST_F(KvStoreSnapshotClientTest, EntryIpcInterfaceTest001, TestSize.Level0)
|
||||
{
|
||||
ZLOGI("EntryIpcInterfaceTest001 begin.");
|
||||
Entry entryIn, *entryOut;
|
||||
entryIn.key = "student_name_mali";
|
||||
entryIn.value = "age:20";
|
||||
OHOS::Parcel parcel;
|
||||
entryIn.Marshalling(parcel);
|
||||
entryOut = Entry::Unmarshalling(parcel);
|
||||
EXPECT_NE(entryOut, nullptr);
|
||||
EXPECT_EQ(entryOut->key.ToString(), std::string("student_name_mali"));
|
||||
EXPECT_EQ(entryOut->value.ToString(), std::string("age:20"));
|
||||
delete entryOut;
|
||||
}
|
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,609 @@
|
||||
/*
|
||||
* 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 <gtest/gtest.h>
|
||||
#include <unistd.h>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <vector>
|
||||
#include "distributed_kv_data_manager.h"
|
||||
#include "types.h"
|
||||
#include "log_print.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::unique_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::unique_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.Level0)
|
||||
{
|
||||
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.Level0)
|
||||
{
|
||||
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.Level0)
|
||||
{
|
||||
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.Level0)
|
||||
{
|
||||
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.Level0)
|
||||
{
|
||||
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.Level0)
|
||||
{
|
||||
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.Level0)
|
||||
{
|
||||
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.Level0)
|
||||
{
|
||||
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.Level0)
|
||||
{
|
||||
ZLOGD("TestQueryC009 start");
|
||||
DataQuery query;
|
||||
std::vector<int> vectInt{ 10, 20, 30 };
|
||||
query.InInt("$.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.InLong("$.test_field_name", vectLong);
|
||||
EXPECT_TRUE(query.ToString().length() > 0);
|
||||
query.Reset();
|
||||
std::vector<double> vectDouble{ 1.23, 2.23, 3.23 };
|
||||
query.InDouble("$.test_field_name", vectDouble);
|
||||
EXPECT_TRUE(query.ToString().length() > 0);
|
||||
query.Reset();
|
||||
std::vector<std::string> vectString{ "value 1", "value 2", "value 3" };
|
||||
query.InString("$.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.Level0)
|
||||
{
|
||||
ZLOGD("TestQueryC010 start");
|
||||
DataQuery query;
|
||||
std::vector<int> vectInt{ 10, 20, 30 };
|
||||
query.NotInInt("$.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.NotInLong("$.test_field_name", vectLong);
|
||||
EXPECT_TRUE(query.ToString().length() > 0);
|
||||
query.Reset();
|
||||
std::vector<double> vectDouble{ 1.23, 2.23, 3.23 };
|
||||
query.NotInDouble("$.test_field_name", vectDouble);
|
||||
EXPECT_TRUE(query.ToString().length() > 0);
|
||||
query.Reset();
|
||||
std::vector<std::string> vectString{ "value 1", "value 2", "value 3" };
|
||||
query.NotInString("$.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.Level0)
|
||||
{
|
||||
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.Level0)
|
||||
{
|
||||
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.Level0)
|
||||
{
|
||||
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.Level0)
|
||||
{
|
||||
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.Level0)
|
||||
{
|
||||
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.Level0)
|
||||
{
|
||||
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.Level0)
|
||||
{
|
||||
ZLOGD("TestSingleKvStoreQueryC001 start");
|
||||
|
||||
DistributedKvDataManager manager;
|
||||
Options options = { .createIfMissing = true, .encrypt = true, .autoSync = true,
|
||||
.kvStoreType = KvStoreType::SINGLE_VERSION };
|
||||
options.schema = VALID_SCHEMA_STRICT_DEFINE;
|
||||
AppId appId = { "SingleKvStoreClientQueryTestAppId1" };
|
||||
StoreId storeId = { "SingleKvStoreClientQueryTestStoreId1" };
|
||||
manager.GetSingleKvStore(options, appId, storeId, [&](Status status, std::unique_ptr<SingleKvStore> kvStore) {
|
||||
statusGetKvStore = status;
|
||||
singleKvStorePtr = std::move(kvStore);
|
||||
});
|
||||
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> results1;
|
||||
Status status1 = singleKvStorePtr->GetEntriesWithQuery(query.ToString(), results1);
|
||||
ASSERT_EQ(status1, Status::SUCCESS);
|
||||
EXPECT_TRUE(results1.size() == 2);
|
||||
std::vector<Entry> results2;
|
||||
Status status2 = singleKvStorePtr->GetEntriesWithQuery(query, results2);
|
||||
ASSERT_EQ(status2, Status::SUCCESS);
|
||||
EXPECT_TRUE(results2.size() == 2);
|
||||
|
||||
std::unique_ptr<KvStoreResultSet> callback1;
|
||||
singleKvStorePtr->GetResultSetWithQuery(query.ToString(), [&](Status status3, std::unique_ptr<KvStoreResultSet> call) {
|
||||
ASSERT_EQ(status3, Status::SUCCESS);
|
||||
callback1 = std::move(call);
|
||||
EXPECT_TRUE(callback1->GetCount() == 2);
|
||||
});
|
||||
auto closeResultSetStatus = singleKvStorePtr->CloseResultSet(std::move(callback1));
|
||||
ASSERT_EQ(closeResultSetStatus, Status::SUCCESS);
|
||||
std::unique_ptr<KvStoreResultSet> callback2;
|
||||
singleKvStorePtr->GetResultSetWithQuery(query, [&](Status status4, std::unique_ptr<KvStoreResultSet> call) {
|
||||
ASSERT_EQ(status4, Status::SUCCESS);
|
||||
callback2 = std::move(call);
|
||||
EXPECT_TRUE(callback2->GetCount() == 2);
|
||||
});
|
||||
closeResultSetStatus = singleKvStorePtr->CloseResultSet(std::move(callback2));
|
||||
ASSERT_EQ(closeResultSetStatus, Status::SUCCESS);
|
||||
|
||||
int resultSize1;
|
||||
Status status5 = singleKvStorePtr->GetCountWithQuery(query.ToString(), resultSize1);
|
||||
ASSERT_EQ(status5, Status::SUCCESS);
|
||||
EXPECT_TRUE(resultSize1 == 2);
|
||||
int resultSize2;
|
||||
Status status6 = singleKvStorePtr->GetCountWithQuery(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.Level0)
|
||||
{
|
||||
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" };
|
||||
manager.GetSingleKvStore(options, appId, storeId, [&](Status status, std::unique_ptr<SingleKvStore> kvStore) {
|
||||
statusGetKvStore = status;
|
||||
singleKvStorePtr = std::move(kvStore);
|
||||
});
|
||||
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->GetEntriesWithQuery(query.ToString(), results1);
|
||||
ASSERT_EQ(status1, Status::SUCCESS);
|
||||
EXPECT_TRUE(results1.size() == 1);
|
||||
std::vector<Entry> results2;
|
||||
Status status2 = singleKvStorePtr->GetEntriesWithQuery(query, results2);
|
||||
ASSERT_EQ(status2, Status::SUCCESS);
|
||||
EXPECT_TRUE(results2.size() == 1);
|
||||
|
||||
std::unique_ptr<KvStoreResultSet> callback1;
|
||||
singleKvStorePtr->GetResultSetWithQuery(query.ToString(), [&](Status status3, std::unique_ptr<KvStoreResultSet> call) {
|
||||
ASSERT_EQ(status3, Status::SUCCESS);
|
||||
callback1 = std::move(call);
|
||||
EXPECT_TRUE(callback1->GetCount() == 1);
|
||||
});
|
||||
auto closeResultSetStatus = singleKvStorePtr->CloseResultSet(std::move(callback1));
|
||||
ASSERT_EQ(closeResultSetStatus, Status::SUCCESS);
|
||||
std::unique_ptr<KvStoreResultSet> callback2;
|
||||
singleKvStorePtr->GetResultSetWithQuery(query, [&](Status status4, std::unique_ptr<KvStoreResultSet> call) {
|
||||
ASSERT_EQ(status4, Status::SUCCESS);
|
||||
callback2 = std::move(call);
|
||||
EXPECT_TRUE(callback2->GetCount() == 1);
|
||||
});
|
||||
closeResultSetStatus = singleKvStorePtr->CloseResultSet(std::move(callback2));
|
||||
ASSERT_EQ(closeResultSetStatus, Status::SUCCESS);
|
||||
|
||||
int resultSize1;
|
||||
Status status5 = singleKvStorePtr->GetCountWithQuery(query.ToString(), resultSize1);
|
||||
ZLOGD("this is it %ul", status5);
|
||||
ASSERT_EQ(status5, Status::SUCCESS);
|
||||
EXPECT_TRUE(resultSize1 == 1);
|
||||
int resultSize2;
|
||||
Status status6 = singleKvStorePtr->GetCountWithQuery(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.Level0)
|
||||
{
|
||||
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.Level0)
|
||||
{
|
||||
ZLOGD("TestQueryC018 start");
|
||||
DataQuery query;
|
||||
query.SetSuggestIndex("test_field_name");
|
||||
EXPECT_TRUE(query.ToString().length() > 0);
|
||||
ZLOGD("TestQueryC018 end");
|
||||
}
|
File diff suppressed because it is too large
Load Diff
99
interfaces/innerkits/app_distributeddata/BUILD.gn
Executable file
99
interfaces/innerkits/app_distributeddata/BUILD.gn
Executable 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.
|
||||
import("//build/ohos.gni")
|
||||
|
||||
group("build_module") {
|
||||
deps = [ ":app_distributeddata" ]
|
||||
}
|
||||
|
||||
config("distributeddata_test_config") {
|
||||
visibility = [ ":*" ]
|
||||
|
||||
include_dirs = [ "include" ]
|
||||
}
|
||||
|
||||
config("distributeddatafwk_config") {
|
||||
visibility = [ ":*" ]
|
||||
|
||||
cflags = [ "-Wno-multichar" ]
|
||||
|
||||
cflags_cc = [ "-fvisibility=hidden" ]
|
||||
|
||||
include_dirs = [
|
||||
"include",
|
||||
"../../../frameworks/innerkitsimpl/distributeddatafwk/src",
|
||||
"../../../frameworks/innerkitsimpl/distributeddatafwk/include",
|
||||
"//utils/native/base/include",
|
||||
]
|
||||
}
|
||||
|
||||
config("distributeddatafwk_public_config") {
|
||||
visibility = [ "//foundation/distributeddatamgr/distributeddatamgr:*" ]
|
||||
|
||||
include_dirs = [
|
||||
"include",
|
||||
"//utils/native/base/include",
|
||||
"//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/include/permission",
|
||||
"//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/include/account",
|
||||
"//foundation/distributeddatamgr/distributeddatamgr/frameworks/innerkitsimpl/distributeddatafwk/include",
|
||||
"//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata/include",
|
||||
"//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/include/utils",
|
||||
]
|
||||
}
|
||||
|
||||
ohos_shared_library("app_distributeddata") {
|
||||
part_name = "distributeddatamgr"
|
||||
sources = [
|
||||
"../../../frameworks/innerkitsimpl/distributeddatafwk/src/app_blob.cpp",
|
||||
"../../../frameworks/innerkitsimpl/distributeddatafwk/src/app_change_notification.cpp",
|
||||
"../../../frameworks/innerkitsimpl/distributeddatafwk/src/app_distributed_kv_data_manager.cpp",
|
||||
"../../../frameworks/innerkitsimpl/distributeddatafwk/src/app_distributed_kv_data_manager_impl.cpp",
|
||||
"../../../frameworks/innerkitsimpl/distributeddatafwk/src/app_distributed_kv_data_manager_impl.h",
|
||||
"../../../frameworks/innerkitsimpl/distributeddatafwk/src/app_kvstore_conflict_data_impl.cpp",
|
||||
"../../../frameworks/innerkitsimpl/distributeddatafwk/src/app_kvstore_impl.cpp",
|
||||
"../../../frameworks/innerkitsimpl/distributeddatafwk/src/app_kvstore_impl.h",
|
||||
"../../../frameworks/innerkitsimpl/distributeddatafwk/src/app_kvstore_result_set_impl.cpp",
|
||||
"include/app_types.h",
|
||||
]
|
||||
|
||||
configs = [ ":distributeddatafwk_config" ]
|
||||
|
||||
deps = [
|
||||
"//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/account:distributeddata_account_static",
|
||||
"//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/permission:distributeddata_permission_static",
|
||||
"//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/utils:distributeddata_utils_static",
|
||||
"//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter:distributeddata_adapter",
|
||||
"//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/libs/distributeddb:distributeddb",
|
||||
"//utils/native/base:utils",
|
||||
]
|
||||
|
||||
external_deps = [
|
||||
"hiviewdfx_hilog_native:libhilog",
|
||||
"ipc:ipc_core",
|
||||
]
|
||||
|
||||
public_configs = [ ":distributeddatafwk_public_config" ]
|
||||
|
||||
subsystem_name = "distributeddatamgr"
|
||||
}
|
||||
|
||||
config("distributeddatafwk_communication_config") {
|
||||
visibility = [ ":*" ]
|
||||
|
||||
cflags = [ "-Wno-multichar" ]
|
||||
|
||||
include_dirs = [
|
||||
"include",
|
||||
"//utils/native/base/include",
|
||||
]
|
||||
}
|
76
interfaces/innerkits/app_distributeddata/include/app_blob.h
Executable file
76
interfaces/innerkits/app_distributeddata/include/app_blob.h
Executable file
@ -0,0 +1,76 @@
|
||||
/*
|
||||
* Copyright (c) 2021 Huawei Device Co., Ltd.
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#ifndef DISTRIBUTED_KV_APP_BLOB_H
|
||||
#define DISTRIBUTED_KV_APP_BLOB_H
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include "visibility.h"
|
||||
|
||||
namespace OHOS {
|
||||
namespace AppDistributedKv {
|
||||
class AppBlob {
|
||||
public:
|
||||
KVSTORE_API AppBlob() = default;
|
||||
KVSTORE_API ~AppBlob() = default;
|
||||
|
||||
// Copy constructor for Blob.
|
||||
KVSTORE_API AppBlob(const AppBlob &blob);
|
||||
KVSTORE_API AppBlob &operator=(const AppBlob &blob);
|
||||
|
||||
// Move constructor for Blob.
|
||||
KVSTORE_API AppBlob(AppBlob &&blob) noexcept;
|
||||
KVSTORE_API AppBlob &operator=(AppBlob &&blob) noexcept;
|
||||
|
||||
// Construct a Blob using std::string.
|
||||
KVSTORE_API AppBlob(const std::string &str);
|
||||
|
||||
// Construct a Blob using char pointer and len.
|
||||
KVSTORE_API AppBlob(const char *str, size_t n);
|
||||
|
||||
// Construct a Blob using char pointer.
|
||||
KVSTORE_API AppBlob(const char *str);
|
||||
|
||||
// Construct a Blob using std::vector<uint8_t>.
|
||||
KVSTORE_API AppBlob(const std::vector<uint8_t> &str);
|
||||
|
||||
// Return a reference to the data of the blob.
|
||||
KVSTORE_API const std::vector<uint8_t> &Data() const;
|
||||
|
||||
// Return the length (in bytes) of the referenced data.
|
||||
KVSTORE_API size_t Size() const;
|
||||
|
||||
// Return true if the length of the referenced data is zero.
|
||||
KVSTORE_API bool Empty() const;
|
||||
|
||||
KVSTORE_API bool operator==(const AppBlob &) const;
|
||||
|
||||
// Change vector<uint8_t> to std::string.
|
||||
KVSTORE_API std::string ToString() const;
|
||||
|
||||
// comparison. Returns value:
|
||||
// < 0 if "*this" < "blob",
|
||||
// == 0 if "*this" == "blob",
|
||||
// > 0 if "*this" > "blob"
|
||||
KVSTORE_API int Compare(const AppBlob &blob) const;
|
||||
|
||||
private:
|
||||
std::vector<uint8_t> blob_;
|
||||
};
|
||||
} // namespace AppDistributedKv
|
||||
} // namespace OHOS
|
||||
|
||||
#endif // DISTRIBUTED_KV_APP_BLOB_H
|
@ -0,0 +1,64 @@
|
||||
/*
|
||||
* Copyright (c) 2021 Huawei Device Co., Ltd.
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#ifndef APP_CHANGE_NOTIFICATION_H
|
||||
#define APP_CHANGE_NOTIFICATION_H
|
||||
|
||||
#include <time.h>
|
||||
#include <list>
|
||||
#include "app_types.h"
|
||||
|
||||
namespace OHOS {
|
||||
namespace AppDistributedKv {
|
||||
class AppChangeNotification final {
|
||||
public:
|
||||
AppChangeNotification();
|
||||
|
||||
// constructor using changing data.
|
||||
AppChangeNotification(const std::list<Entry> &insertEntries, const std::list<Entry> &updateEntries,
|
||||
const std::list<Entry> &deleteEntries, const std::string &deviceId, const bool isClear);
|
||||
|
||||
KVSTORE_API ~AppChangeNotification();
|
||||
|
||||
// Function to get all inserted entries for this changing.
|
||||
KVSTORE_API const std::list<Entry> &GetInsertEntries() const;
|
||||
|
||||
// Function to get all updated entries for this changing.
|
||||
KVSTORE_API const std::list<Entry> &GetUpdateEntries() const;
|
||||
|
||||
// Function to get all deleted entries for this changing.
|
||||
KVSTORE_API const std::list<Entry> &GetDeleteEntries() const;
|
||||
|
||||
// Function to get from device id.
|
||||
KVSTORE_API const std::string &GetDeviceId() const;
|
||||
|
||||
// Function to check if this change is made by calling clear function.
|
||||
KVSTORE_API bool IsClear() const;
|
||||
|
||||
private:
|
||||
std::list<Entry> insertEntries_;
|
||||
|
||||
std::list<Entry> updateEntries_;
|
||||
|
||||
std::list<Entry> deleteEntries_;
|
||||
|
||||
std::string deviceId_;
|
||||
|
||||
bool isClear_ = false;
|
||||
};
|
||||
} // namespace AppDistributedKv
|
||||
} // namespace OHOS
|
||||
|
||||
#endif // APP_CHANGE_NOTIFICATION_H
|
@ -0,0 +1,40 @@
|
||||
/*
|
||||
* Copyright (c) 2021 Huawei Device Co., Ltd.
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#ifndef APP_DEVICE_STATUS_CHANGE_LISTENER_H
|
||||
#define APP_DEVICE_STATUS_CHANGE_LISTENER_H
|
||||
|
||||
#include "app_types.h"
|
||||
|
||||
namespace OHOS {
|
||||
namespace AppDistributedKv {
|
||||
enum class ChangeLevelType {
|
||||
HIGH,
|
||||
LOW,
|
||||
MIN,
|
||||
};
|
||||
class AppDeviceStatusChangeListener {
|
||||
public:
|
||||
KVSTORE_API virtual ~AppDeviceStatusChangeListener() {};
|
||||
KVSTORE_API virtual void OnDeviceChanged(const DeviceInfo &info, const DeviceChangeType &type) const = 0;
|
||||
KVSTORE_API virtual ChangeLevelType GetChangeLevelType() const
|
||||
{
|
||||
return ChangeLevelType::LOW;
|
||||
}
|
||||
};
|
||||
} // namespace AppDistributedKv
|
||||
} // namespace OHOS
|
||||
|
||||
#endif // APP_DEVICE_STATUS_CHANGE_LISTENER_H
|
@ -0,0 +1,107 @@
|
||||
/*
|
||||
* Copyright (c) 2021 Huawei Device Co., Ltd.
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#ifndef APP_DISTRIBUTED_KV_DATA_MANAGER_H
|
||||
#define APP_DISTRIBUTED_KV_DATA_MANAGER_H
|
||||
|
||||
#include <memory>
|
||||
#include "app_device_status_change_listener.h"
|
||||
#include "app_kvstore.h"
|
||||
#include "app_types.h"
|
||||
#include "app_kvstore_corruption_observer.h"
|
||||
|
||||
namespace OHOS {
|
||||
namespace AppDistributedKv {
|
||||
// This is the overall manager of all kvstore.
|
||||
// This class provides open, close, delete AppKvStore and manage remote device functions.
|
||||
class AppDistributedKvDataManager {
|
||||
public:
|
||||
// Get AppDistributedKvDataManager singleton for APP process (for jni and dynamic library depended by jni).
|
||||
// Parameters:
|
||||
// bundleName: bundleName of your app
|
||||
// dataDir: the directory to save your db file. Please choose a directory you can visit before phone unlock.
|
||||
// this parameter will not be checked or used after first successful call.
|
||||
// userId: name of your user. this stands for multiuser, not for huawei account or linux user.
|
||||
// Return:
|
||||
// singleton of AppDistributedKvDataManager, or nullptr on error.
|
||||
KVSTORE_API static std::shared_ptr<AppDistributedKvDataManager> GetInstance(const std::string &bundleName,
|
||||
const std::string &dataDir,
|
||||
const std::string &userId = "account0");
|
||||
|
||||
KVSTORE_API AppDistributedKvDataManager()
|
||||
{}
|
||||
|
||||
KVSTORE_API virtual ~AppDistributedKvDataManager()
|
||||
{}
|
||||
|
||||
// Open kvstore instance with the given storeId, creating it if needed.
|
||||
// It is allowed to open the same kvstore concurrently
|
||||
// multiple times, but only one database instance will be created.
|
||||
// Parameters:
|
||||
// options: the config of the kvstore, including encrypt, create if needed and whether need sync between
|
||||
// devices.
|
||||
// storeId: the name of the kvstore.
|
||||
// callback: KvStore instance returned by this call.
|
||||
// callback will return:
|
||||
// if Options.createIfMissing is false and kvstore has not been created before, nullptr and Status is
|
||||
// STORE_NOT_FOUND,
|
||||
// if storeId is not valid, nullptr and Status is INVALID_ARGUMENT
|
||||
// otherwise, SUCCESS and the unipue_ptr of AppKvStore, which client can use to operate kvstore, will be
|
||||
// returned.
|
||||
// Return:
|
||||
// Status of this get operation.
|
||||
KVSTORE_API
|
||||
virtual Status GetKvStore(const Options &options, const std::string &storeId,
|
||||
const std::function<void(std::unique_ptr<AppKvStore> appKvStore)> &callback) = 0;
|
||||
|
||||
// WARNING: try to close a KvStore while other thread(s) still using it may cause process crash.
|
||||
// Disconnect kvstore connection from database instance with the given storeId,
|
||||
// only if all connections to the same database instance are closed, database instance will be freed.
|
||||
// after this call, kvstore becomes invalid.
|
||||
// call to it will return nullptr exception.
|
||||
// Parameters:
|
||||
// appKvStore: kvstore instance created by GetKvStore.
|
||||
// Return:
|
||||
// Status of this close operation.
|
||||
KVSTORE_API virtual Status CloseKvStore(std::unique_ptr<AppKvStore> appKvStore) = 0;
|
||||
|
||||
// Delete database file with the given storeId.
|
||||
// Client should first close all connections to it and then delete it, otherwise delete will return error.
|
||||
// Parameters:
|
||||
// storeId: the name of the kvstore.
|
||||
// Return:
|
||||
// Status of this delete operation.
|
||||
KVSTORE_API virtual Status DeleteKvStore(const std::string &storeId) = 0;
|
||||
|
||||
// Get the database size.
|
||||
KVSTORE_API virtual Status GetKvStoreDiskSize(const std::string &storeId, uint64_t &size) = 0;
|
||||
|
||||
// observe
|
||||
// Parameters:
|
||||
// observer: observer which will be callback when corrupted.
|
||||
// Return:
|
||||
// Status of this operation.
|
||||
KVSTORE_API
|
||||
virtual Status RegisterKvStoreCorruptionObserver(const std::shared_ptr<AppKvStoreCorruptionObserver> observer) = 0;
|
||||
protected:
|
||||
AppDistributedKvDataManager(const AppDistributedKvDataManager &) = delete;
|
||||
AppDistributedKvDataManager& operator=(const AppDistributedKvDataManager&) = delete;
|
||||
AppDistributedKvDataManager(AppDistributedKvDataManager &&) = delete;
|
||||
AppDistributedKvDataManager& operator=(AppDistributedKvDataManager &&) = delete;
|
||||
}; // class AppDistributedKvDataManager
|
||||
} // namespace AppDistributedKv
|
||||
} // namespace OHOS
|
||||
|
||||
#endif // APP_DISTRIBUTED_KV_DATA_MANAGER_H
|
167
interfaces/innerkits/app_distributeddata/include/app_kvstore.h
Executable file
167
interfaces/innerkits/app_distributeddata/include/app_kvstore.h
Executable file
@ -0,0 +1,167 @@
|
||||
/*
|
||||
* Copyright (c) 2021 Huawei Device Co., Ltd.
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#ifndef APP_KV_STORE_H
|
||||
#define APP_KV_STORE_H
|
||||
|
||||
#include <map>
|
||||
#include <functional>
|
||||
#include "app_kvstore_conflict_data.h"
|
||||
#include "app_kvstore_observer.h"
|
||||
#include "app_types.h"
|
||||
#include "app_kvstore_result_set.h"
|
||||
|
||||
namespace OHOS {
|
||||
namespace AppDistributedKv {
|
||||
// This is a public interface. Implementation of this class is in AppKvStoreImpl.
|
||||
// This class provides put, delete, search, sync and subscribe functions of a key-value store.
|
||||
class AppKvStore {
|
||||
public:
|
||||
KVSTORE_API virtual ~AppKvStore()
|
||||
{}
|
||||
|
||||
// Get id of this AppKvStore.
|
||||
KVSTORE_API virtual const std::string &GetStoreId() = 0;
|
||||
|
||||
// Write a pair of key and value to this store. Set write option to local if you do not this entry sync to other
|
||||
// devices.
|
||||
// Parameters:
|
||||
// options: mark this is a local entry or not.
|
||||
// key: key of this entry. Should be less than 256 bytes. key will be trimmed before store.
|
||||
// value: value of this entry. Should be less than (1024 * 1024) bytes.
|
||||
// Return:
|
||||
// Status of this put operation.
|
||||
KVSTORE_API virtual Status Put(const WriteOptions &options, const Key &key, const Value &value) = 0;
|
||||
|
||||
// Delete an entry by its key. Set write option to local if you want this delete to be a local change.
|
||||
// Parameters:
|
||||
// options: mark this delete is a local change or not.
|
||||
// key: key of the entry to be deleted.
|
||||
// Return:
|
||||
// Status of this delete operation.
|
||||
KVSTORE_API virtual Status Delete(const WriteOptions &options, const Key &key) = 0;
|
||||
|
||||
// Get value from AppKvStore by its key. Set options->local to true if you want to get from local kvstore.
|
||||
// Parameters:
|
||||
// options: mark we get from local store or remote store. options->batch is a reserved parameter and should
|
||||
// always be false.
|
||||
// key: key of this entry.
|
||||
// value: value will be returned in this parameter.
|
||||
// Return:
|
||||
// Status of this get operation.
|
||||
KVSTORE_API virtual Status Get(const ReadOptions &options, const Key &key, Value &value) = 0;
|
||||
|
||||
// Get all entries in this store which key start with prefixKey. This function will always get from synced store.
|
||||
// Parameters:
|
||||
// prefixkey: the prefix to be searched.
|
||||
// entries: entries will be returned in this parameter.
|
||||
// Return:
|
||||
// Status of this GetEntries operation.
|
||||
KVSTORE_API virtual Status GetEntries(const Key &prefixKey, std::vector<Entry> &entries) = 0;
|
||||
|
||||
// Get all entries in this store which key start with prefixKey. This function will always get from synced store.
|
||||
// Parameters:
|
||||
// prefixkey: the prefix to be searched.
|
||||
// resultSet: resultSet will be returned in this parameter.
|
||||
// Return:
|
||||
// Status of this GetEntries operation.
|
||||
KVSTORE_API virtual Status GetEntries(const Key &prefixKey, AppKvStoreResultSet *&resultSet) = 0;
|
||||
|
||||
// Close the result set returned by GetEntries().
|
||||
// Parameters:
|
||||
// resultSet: resultSet will be returned in this parameter.
|
||||
// Return:
|
||||
// Status of this GetEntries operation.
|
||||
KVSTORE_API virtual Status CloseResultSet(AppKvStoreResultSet *&resultSet) = 0;
|
||||
|
||||
// Sync store with other devices. This is an asynchronous method,
|
||||
// sync will fail if there is a syncing operation in progress.
|
||||
// Parameters:
|
||||
// deviceIdList: device list to sync.
|
||||
// mode: mode can be set to SyncMode::PUSH, SyncMode::PULL and SyncMode::PUTH_PULL. PUSH_PULL will firstly
|
||||
// push all not-local store to listed devices, then pull these stores back.
|
||||
// callback: return <device-id, sync-result> map to caller.
|
||||
// Return:
|
||||
// Status of this Sync operation.
|
||||
KVSTORE_API virtual Status Sync(const std::vector<std::string> &deviceIdList, const SyncMode &mode,
|
||||
const std::function<void(const std::map<std::string, Status> &)> &callback) = 0;
|
||||
|
||||
// Register change of this kvstore to a client-defined observer. observer->OnChange method will be called when store
|
||||
// changes. One observer can subscribe more than one AppKvStore.
|
||||
// Parameters:
|
||||
// options: mark this is a local entry or not.
|
||||
// subscribeType: OBSERVER_CHANGES_NATIVE means native changes of syncable kv store,
|
||||
// : OBSERVER_CHANGES_FOREIGN means synced data changes from remote devices,
|
||||
// : OBSERVER_CHANGES_ALL means both native changes and synced data changes.
|
||||
// observer: observer to subscribe changes.
|
||||
// Return:
|
||||
// Status of this subscribe operation.
|
||||
KVSTORE_API virtual Status SubscribeKvStore(const ReadOptions &options, const SubscribeType &subscribeType,
|
||||
AppKvStoreObserver *observer) = 0;
|
||||
|
||||
// Unregister a kvstore to an observer.
|
||||
// Parameters:
|
||||
// options: mark this is a local entry or not.
|
||||
// subscribeType: reserved parameter. Current is always SubscribeType::DEFAULT.
|
||||
// observer: observer to unsubscribe this store.
|
||||
// Return:
|
||||
// Status of this unsubscribe operation.
|
||||
KVSTORE_API virtual Status UnSubscribeKvStore(const ReadOptions &options, const SubscribeType &subscribeType,
|
||||
AppKvStoreObserver *observer) = 0;
|
||||
|
||||
// Remove the device data synced from remote.
|
||||
// Parameters:
|
||||
// device: device id.
|
||||
// Return:
|
||||
// Status of this remove operation.
|
||||
KVSTORE_API virtual Status RemoveDeviceData(const std::string &device) = 0;
|
||||
|
||||
// Set policy of conflict resolution.
|
||||
// Parameters:
|
||||
// conflictType: include CONFLICT_FOREIGN_KEY_ONLY CONFLICT_FOREIGN_KEY_ORIG CONFLICT_NATIVE_ALL.
|
||||
// callback: conflict resolution callback.
|
||||
// Return:
|
||||
// Status of Setting policy operation.
|
||||
KVSTORE_API
|
||||
virtual Status SetConflictResolutionPolicy(AppKvStoreConflictPolicyType conflictType,
|
||||
std::function<void(const AppKvStoreConflictData &data)> callback) = 0;
|
||||
|
||||
// Export current data store to ${filePath} using ${passwd}
|
||||
// Parameters:
|
||||
// filePath: directory which store will be saved.
|
||||
// passwd: can be null, which means dont cipher.
|
||||
// Return:
|
||||
// Status of this operation.
|
||||
KVSTORE_API virtual Status Export(const std::string &filePath, const std::vector<uint8_t> &passwd) = 0;
|
||||
|
||||
// Import current data store to ${filePath} using ${passwd}
|
||||
// Parameters:
|
||||
// filePath: directory from which will recovery.
|
||||
// passwd: can be null, which means dont cipher.
|
||||
// Return:
|
||||
// Status of this operation.
|
||||
KVSTORE_API virtual Status Import(const std::string &filePath, const std::vector<uint8_t> &passwd) = 0;
|
||||
|
||||
// get security level.
|
||||
// Parameters:
|
||||
// securityLevel: the security level.
|
||||
// Return:
|
||||
// Status of this operation.
|
||||
KVSTORE_API virtual Status GetSecurityLevel(SecurityLevel &securityLevel) const = 0;
|
||||
};
|
||||
} // namespace AppDistributedKv
|
||||
} // namespace OHOS
|
||||
|
||||
#endif // APP_KV_STORE_H
|
@ -0,0 +1,47 @@
|
||||
/*
|
||||
* Copyright (c) 2021 Huawei Device Co., Ltd.
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#ifndef APP_KVSTOR_CONFLICT_DATA_H
|
||||
#define APP_KVSTOR_CONFLICT_DATA_H
|
||||
|
||||
#include <time.h>
|
||||
#include <list>
|
||||
#include "app_types.h"
|
||||
|
||||
namespace OHOS {
|
||||
namespace AppDistributedKv {
|
||||
class AppKvStoreConflictData {
|
||||
public:
|
||||
enum class ConflictValueType {
|
||||
OLD_VALUE = 0,
|
||||
NEW_VALUE,
|
||||
};
|
||||
|
||||
KVSTORE_API virtual ~AppKvStoreConflictData() = default;
|
||||
|
||||
KVSTORE_API virtual AppKvStoreConflictPolicyType GetType() const = 0;
|
||||
|
||||
KVSTORE_API virtual void GetKey(Key &key) const = 0;
|
||||
|
||||
KVSTORE_API virtual Status GetValue(ConflictValueType type, Value &value) const = 0;
|
||||
|
||||
KVSTORE_API virtual bool IsDeleted(ConflictValueType type) const = 0;
|
||||
|
||||
KVSTORE_API virtual bool IsNative(ConflictValueType type) const = 0;
|
||||
};
|
||||
} // namespace AppDistributedKv
|
||||
} // namespace OHOS
|
||||
|
||||
#endif // APP_KVSTOR_CONFLICT_DATA_H
|
@ -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 DISTRIBUTEDDATAMGR_APP_KVSTORE_CORRUPTION_OBSERVER_H
|
||||
#define DISTRIBUTEDDATAMGR_APP_KVSTORE_CORRUPTION_OBSERVER_H
|
||||
namespace OHOS {
|
||||
namespace AppDistributedKv {
|
||||
class AppKvStoreCorruptionObserver {
|
||||
public:
|
||||
KVSTORE_API virtual ~AppKvStoreCorruptionObserver() {};
|
||||
KVSTORE_API
|
||||
virtual void OnCorruption(const std::string &appId, const std::string &userId, const std::string &storeId) = 0;
|
||||
};
|
||||
} // namespace AppDistributedKv
|
||||
} // namespace OHOS
|
||||
#endif // DISTRIBUTEDDATAMGR_APP_KVSTORE_CORRUPTION_OBSERVER_H
|
@ -0,0 +1,39 @@
|
||||
/*
|
||||
* Copyright (c) 2021 Huawei Device Co., Ltd.
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#ifndef APP_KVSTORE_OBSERVER_H
|
||||
#define APP_KVSTORE_OBSERVER_H
|
||||
|
||||
#include "app_change_notification.h"
|
||||
|
||||
namespace OHOS {
|
||||
namespace AppDistributedKv {
|
||||
// This is a abstract classes. Client needs to implement this class by self.
|
||||
class AppKvStoreObserver {
|
||||
public:
|
||||
KVSTORE_API AppKvStoreObserver() = default;
|
||||
|
||||
KVSTORE_API virtual ~AppKvStoreObserver()
|
||||
{}
|
||||
// This virtual function will be called on store change.
|
||||
// Client needs to override this function to receive change notification.
|
||||
// Parameters:
|
||||
// ChangeNotification: all changes from other devices.
|
||||
KVSTORE_API virtual void OnChange(const AppChangeNotification &appChangeNotification) = 0;
|
||||
};
|
||||
} // namespace AppDistributedKv
|
||||
} // namespace OHOS
|
||||
|
||||
#endif // APP_KV_STORE_OBSERVER_H
|
76
interfaces/innerkits/app_distributeddata/include/app_kvstore_result_set.h
Executable file
76
interfaces/innerkits/app_distributeddata/include/app_kvstore_result_set.h
Executable file
@ -0,0 +1,76 @@
|
||||
/*
|
||||
* Copyright (c) 2021 Huawei Device Co., Ltd.
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#ifndef APP_KV_STORE_RESULT_SET_H
|
||||
#define APP_KV_STORE_RESULT_SET_H
|
||||
|
||||
#include "app_types.h"
|
||||
|
||||
namespace OHOS {
|
||||
namespace AppDistributedKv {
|
||||
class AppKvStoreResultSet {
|
||||
public:
|
||||
KVSTORE_API virtual ~AppKvStoreResultSet()
|
||||
{}
|
||||
|
||||
// Returns the count of rows in the result set.
|
||||
KVSTORE_API virtual int GetCount() const = 0;
|
||||
|
||||
// Returns the current read position of the result set.
|
||||
KVSTORE_API virtual int GetPosition() const = 0;
|
||||
|
||||
// Move the read position to the first row, return false if the result set is empty.
|
||||
KVSTORE_API virtual bool MoveToFirst() = 0;
|
||||
|
||||
// Move the read position to the last row, return false if the result set is empty.
|
||||
KVSTORE_API virtual bool MoveToLast() = 0;
|
||||
|
||||
// Move the read position to the next row,
|
||||
// and returns false if the result set is empty or the read position is already
|
||||
// past the last entry in the result set.
|
||||
KVSTORE_API virtual bool MoveToNext() = 0;
|
||||
|
||||
// Move the read position to the previous row,
|
||||
// and returns false if result set is empty or the read position is already
|
||||
// before the first entry in the result set.
|
||||
KVSTORE_API virtual bool MoveToPrevious() = 0;
|
||||
|
||||
// Move the read position by a relative amount from the current position.
|
||||
KVSTORE_API virtual bool Move(int offset) = 0;
|
||||
|
||||
// Move the read position to an absolute position value.
|
||||
KVSTORE_API virtual bool MoveToPosition(int position) = 0;
|
||||
|
||||
// Returns whether the read position is pointing to the first row.
|
||||
KVSTORE_API virtual bool IsFirst() const = 0;
|
||||
|
||||
// Returns whether the read position is pointing to the last row.
|
||||
KVSTORE_API virtual bool IsLast() const = 0;
|
||||
|
||||
// Returns whether the read position is before the first row.
|
||||
KVSTORE_API virtual bool IsBeforeFirst() const = 0;
|
||||
|
||||
// Returns whether the read position is after the last row.
|
||||
KVSTORE_API virtual bool IsAfterLast() const = 0;
|
||||
|
||||
// Get a key-value entry.
|
||||
KVSTORE_API virtual Status GetEntry(Entry &entry) const = 0;
|
||||
|
||||
KVSTORE_API virtual Status Close() = 0;
|
||||
};
|
||||
} // namespace AppDistributedKv
|
||||
} // namespace OHOS
|
||||
|
||||
#endif // APP_KV_STORE_RESULT_SET_H
|
173
interfaces/innerkits/app_distributeddata/include/app_types.h
Executable file
173
interfaces/innerkits/app_distributeddata/include/app_types.h
Executable file
@ -0,0 +1,173 @@
|
||||
/*
|
||||
* Copyright (c) 2021 Huawei Device Co., Ltd.
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#ifndef APP_DISTRIBUTED_KVSTORE_APP_TYPES_H
|
||||
#define APP_DISTRIBUTED_KVSTORE_APP_TYPES_H
|
||||
|
||||
#include <errors.h>
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include "app_blob.h"
|
||||
#include "visibility.h"
|
||||
|
||||
namespace OHOS {
|
||||
namespace AppDistributedKv {
|
||||
// Key set by the client, which can be any non-empty byte array with a length of less than 256 bytes.
|
||||
using Key = OHOS::AppDistributedKv::AppBlob;
|
||||
|
||||
// Value set by client, which can be any byte array.
|
||||
using Value = OHOS::AppDistributedKv::AppBlob;
|
||||
|
||||
// User ID from the user account
|
||||
struct UserId {
|
||||
std::string userId;
|
||||
};
|
||||
|
||||
// App ID from the BMS
|
||||
struct AppId {
|
||||
std::string appId;
|
||||
};
|
||||
|
||||
struct PipeInfo {
|
||||
std::string pipeId;
|
||||
std::string userId;
|
||||
};
|
||||
|
||||
struct DeviceInfo {
|
||||
std::string deviceId;
|
||||
std::string deviceName;
|
||||
std::string deviceType;
|
||||
};
|
||||
|
||||
enum class MessageType {
|
||||
DEFAULT = 0,
|
||||
FILE = 1,
|
||||
};
|
||||
|
||||
struct MessageInfo {
|
||||
MessageType msgType;
|
||||
};
|
||||
|
||||
enum class DeviceChangeType {
|
||||
DEVICE_OFFLINE = 0,
|
||||
DEVICE_ONLINE = 1,
|
||||
};
|
||||
|
||||
struct DeviceId {
|
||||
std::string deviceId;
|
||||
};
|
||||
|
||||
// app_distributed_data_manager using sub error code 0
|
||||
constexpr ErrCode APP_DISTRIBUTEDDATAMGR_ERR_OFFSET = ErrCodeOffset(SUBSYS_DISTRIBUTEDDATAMNG, 0);
|
||||
|
||||
enum class Status {
|
||||
SUCCESS = ERR_OK,
|
||||
ERROR = APP_DISTRIBUTEDDATAMGR_ERR_OFFSET,
|
||||
INVALID_ARGUMENT = APP_DISTRIBUTEDDATAMGR_ERR_OFFSET + 1,
|
||||
ILLEGAL_STATE = APP_DISTRIBUTEDDATAMGR_ERR_OFFSET + 2,
|
||||
STORE_NOT_OPEN = APP_DISTRIBUTEDDATAMGR_ERR_OFFSET + 3,
|
||||
STORE_NOT_FOUND = APP_DISTRIBUTEDDATAMGR_ERR_OFFSET + 4,
|
||||
STORE_ALREADY_SUBSCRIBE = APP_DISTRIBUTEDDATAMGR_ERR_OFFSET + 5,
|
||||
STORE_NOT_SUBSCRIBE = APP_DISTRIBUTEDDATAMGR_ERR_OFFSET + 6,
|
||||
KEY_NOT_FOUND = APP_DISTRIBUTEDDATAMGR_ERR_OFFSET + 7,
|
||||
DB_ERROR = APP_DISTRIBUTEDDATAMGR_ERR_OFFSET + 8,
|
||||
DEVICE_NOT_FOUND = APP_DISTRIBUTEDDATAMGR_ERR_OFFSET + 9,
|
||||
NETWORK_ERROR = APP_DISTRIBUTEDDATAMGR_ERR_OFFSET + 10,
|
||||
NO_DEVICE_CONNECTED = APP_DISTRIBUTEDDATAMGR_ERR_OFFSET + 11,
|
||||
PERMISSION_DENIED = APP_DISTRIBUTEDDATAMGR_ERR_OFFSET + 12,
|
||||
TIME_OUT = APP_DISTRIBUTEDDATAMGR_ERR_OFFSET + 13,
|
||||
REPEATED_REGISTER = APP_DISTRIBUTEDDATAMGR_ERR_OFFSET + 14,
|
||||
CREATE_SESSION_ERROR = APP_DISTRIBUTEDDATAMGR_ERR_OFFSET + 15,
|
||||
SECURITY_LEVEL_ERROR = APP_DISTRIBUTEDDATAMGR_ERR_OFFSET + 32,
|
||||
};
|
||||
|
||||
enum class SubscribeType {
|
||||
DEFAULT = 0, // reserved value, to be deleted
|
||||
OBSERVER_CHANGES_NATIVE = 1, // native changes of syncable KvStore
|
||||
OBSERVER_CHANGES_FOREIGN = 2, // synced data changes from remote devices
|
||||
OBSERVER_CHANGES_ALL = 3, // both native changes and synced data changes
|
||||
};
|
||||
|
||||
struct Entry {
|
||||
Key key;
|
||||
Value value;
|
||||
};
|
||||
|
||||
enum class SyncMode {
|
||||
PULL,
|
||||
PUSH,
|
||||
PUSH_PULL,
|
||||
};
|
||||
|
||||
enum ConflictResolvePolicy {
|
||||
LAST_WIN = 0,
|
||||
DEVICE_COLLABORATION,
|
||||
};
|
||||
|
||||
enum SecurityLevel : int {
|
||||
NO_LABEL,
|
||||
S0,
|
||||
S1,
|
||||
S2,
|
||||
S3_EX,
|
||||
S3,
|
||||
S4,
|
||||
};
|
||||
|
||||
struct Options {
|
||||
bool createIfMissing = false;
|
||||
bool encrypt = false;
|
||||
bool persistant = false;
|
||||
int conflictResolvePolicy = LAST_WIN;
|
||||
int securityLevel = SecurityLevel::NO_LABEL;
|
||||
};
|
||||
|
||||
struct WriteOptions {
|
||||
bool local;
|
||||
};
|
||||
|
||||
struct ReadOptions {
|
||||
bool local;
|
||||
};
|
||||
|
||||
template<typename T>
|
||||
std::vector<uint8_t> TransferTypeToByteArray(const T &t)
|
||||
{
|
||||
return std::vector<uint8_t>(reinterpret_cast<uint8_t *>(const_cast<T *>(&t)),
|
||||
reinterpret_cast<uint8_t *>(const_cast<T *>(&t)) + sizeof(T));
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
T TransferByteArrayToType(const std::vector<uint8_t> &blob)
|
||||
{
|
||||
// replace assert to HILOG_FATAL when HILOG_FATAL is ok.
|
||||
if (blob.size() != sizeof(T) || blob.size() == 0) {
|
||||
constexpr int tSize = sizeof(T);
|
||||
uint8_t tContent[tSize] = { 0 };
|
||||
return *reinterpret_cast<T *>(tContent);
|
||||
}
|
||||
return *reinterpret_cast<T *>(const_cast<uint8_t *>(&blob[0]));
|
||||
}
|
||||
|
||||
enum class AppKvStoreConflictPolicyType {
|
||||
CONFIICT_FOREIGN_KEY_ONLY = 0x01,
|
||||
CONFLICT_FOREIGN_KEY_ORIG = 0x02,
|
||||
CONFLICT_NATIVE_ALL = 0x0c,
|
||||
};
|
||||
} // namespace AppDistributedKv
|
||||
} // namespace OHOS
|
||||
|
||||
#endif // APP_DISTRIBUTED_KVSTORE_TYPES_H
|
@ -0,0 +1,27 @@
|
||||
/*
|
||||
* 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_API
|
||||
#ifdef _WIN32
|
||||
#ifdef DB_DLL_EXPORT
|
||||
#define KVSTORE_API __declspec(dllexport)
|
||||
#else
|
||||
#define KVSTORE_API
|
||||
#endif
|
||||
#else
|
||||
#define KVSTORE_API __attribute__ ((visibility ("default")))
|
||||
#endif
|
||||
#endif
|
||||
|
87
interfaces/innerkits/distributeddata/BUILD.gn
Executable file
87
interfaces/innerkits/distributeddata/BUILD.gn
Executable 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.
|
||||
import("//build/ohos.gni")
|
||||
|
||||
group("build_module") {
|
||||
deps = [ ":distributeddata" ]
|
||||
}
|
||||
|
||||
config("distributeddatafwk_config") {
|
||||
visibility = [ ":*" ]
|
||||
|
||||
cflags = [ "-Wno-multichar" ]
|
||||
|
||||
include_dirs = [
|
||||
"include",
|
||||
"../../../frameworks/innerkitsimpl/distributeddatafwk/include",
|
||||
"../../../frameworks/innerkitsimpl/distributeddatafwk/src",
|
||||
"//utils/system/safwk/native/include",
|
||||
"//utils/native/base/include",
|
||||
"//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/app_distributeddata/include",
|
||||
]
|
||||
}
|
||||
|
||||
config("distributeddatafwk_public_config") {
|
||||
visibility = [ "//foundation/distributeddatamgr/distributeddatamgr:*" ]
|
||||
|
||||
include_dirs = [
|
||||
"include",
|
||||
"//utils/native/base/include",
|
||||
]
|
||||
}
|
||||
|
||||
ohos_shared_library("distributeddata") {
|
||||
part_name = "distributeddatamgr"
|
||||
sources = [
|
||||
"../../../frameworks/innerkitsimpl/distributeddatafwk/src/blob.cpp",
|
||||
"../../../frameworks/innerkitsimpl/distributeddatafwk/src/change_notification.cpp",
|
||||
"../../../frameworks/innerkitsimpl/distributeddatafwk/src/data_query.cpp",
|
||||
"../../../frameworks/innerkitsimpl/distributeddatafwk/src/device_status_change_listener_client.cpp",
|
||||
"../../../frameworks/innerkitsimpl/distributeddatafwk/src/distributed_kv_data_manager.cpp",
|
||||
"../../../frameworks/innerkitsimpl/distributeddatafwk/src/idevice_status_change_listener_impl.cpp",
|
||||
"../../../frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore.cpp",
|
||||
"../../../frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_client_death_observer.cpp",
|
||||
"../../../frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_data_service.cpp",
|
||||
"../../../frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_observer.cpp",
|
||||
"../../../frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_resultset.cpp",
|
||||
"../../../frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_single.cpp",
|
||||
"../../../frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_snapshot.cpp",
|
||||
"../../../frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_sync_callback.cpp",
|
||||
"../../../frameworks/innerkitsimpl/distributeddatafwk/src/kvstore_client.cpp",
|
||||
"../../../frameworks/innerkitsimpl/distributeddatafwk/src/kvstore_client_death_observer.cpp",
|
||||
"../../../frameworks/innerkitsimpl/distributeddatafwk/src/kvstore_death_recipient_impl.cpp",
|
||||
"../../../frameworks/innerkitsimpl/distributeddatafwk/src/kvstore_observer_client.cpp",
|
||||
"../../../frameworks/innerkitsimpl/distributeddatafwk/src/kvstore_resultset_client.cpp",
|
||||
"../../../frameworks/innerkitsimpl/distributeddatafwk/src/kvstore_service_death_notifier.cpp",
|
||||
"../../../frameworks/innerkitsimpl/distributeddatafwk/src/kvstore_snapshot_client.cpp",
|
||||
"../../../frameworks/innerkitsimpl/distributeddatafwk/src/kvstore_sync_callback_client.cpp",
|
||||
"../../../frameworks/innerkitsimpl/distributeddatafwk/src/single_kvstore_client.cpp",
|
||||
"include/types.h",
|
||||
]
|
||||
|
||||
configs = [ ":distributeddatafwk_config" ]
|
||||
|
||||
deps = [
|
||||
"//utils/native/base:utils",
|
||||
"//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter:distributeddata_adapter",
|
||||
]
|
||||
external_deps = [
|
||||
"hiviewdfx_hilog_native:libhilog",
|
||||
"ipc:ipc_core",
|
||||
"samgr_L2:samgr_proxy",
|
||||
]
|
||||
|
||||
public_configs = [ ":distributeddatafwk_public_config" ]
|
||||
|
||||
subsystem_name = "distributeddatamgr"
|
||||
}
|
111
interfaces/innerkits/distributeddata/include/blob.h
Normal file
111
interfaces/innerkits/distributeddata/include/blob.h
Normal file
@ -0,0 +1,111 @@
|
||||
/*
|
||||
* Copyright (c) 2021 Huawei Device Co., Ltd.
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#ifndef DISTRIBUTED_KV_BLOB_H
|
||||
#define DISTRIBUTED_KV_BLOB_H
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include "parcel.h"
|
||||
#include "visibility.h"
|
||||
|
||||
namespace OHOS {
|
||||
namespace DistributedKv {
|
||||
// note: Blob derives from Parcelable, so hiding inner a interface using blob is not possible unless Parcelable
|
||||
// declared its interface as visible.
|
||||
class Blob : public virtual Parcelable {
|
||||
public:
|
||||
KVSTORE_API Blob();
|
||||
|
||||
KVSTORE_API ~Blob() = default;
|
||||
|
||||
// copy constructor for Blob.
|
||||
KVSTORE_API Blob(const Blob &blob);
|
||||
KVSTORE_API Blob &operator=(const Blob &blob);
|
||||
|
||||
// move constructor for Blob.
|
||||
KVSTORE_API Blob(Blob &&blob);
|
||||
KVSTORE_API Blob &operator=(Blob &&blob);
|
||||
|
||||
// construct a Blob use std::string.
|
||||
KVSTORE_API Blob(const std::string &str);
|
||||
|
||||
// construct a Blob use char pointer and len.
|
||||
KVSTORE_API Blob(const char *str, size_t n);
|
||||
|
||||
// construct a Blob use char pointer.
|
||||
KVSTORE_API Blob(const char *str);
|
||||
|
||||
// construct a Blob use std::vector<uint8_t>
|
||||
KVSTORE_API Blob(const std::vector<uint8_t> &bytes);
|
||||
|
||||
// construct a Blob use std::vector<uint8_t>
|
||||
KVSTORE_API Blob(std::vector<uint8_t> &&bytes);
|
||||
|
||||
// Return a reference to the data of the blob.
|
||||
KVSTORE_API const std::vector<uint8_t> &Data() const;
|
||||
|
||||
// Return the length (in bytes) of the referenced data
|
||||
KVSTORE_API size_t Size() const;
|
||||
|
||||
// Return the occupied length when write this blob to rawdata
|
||||
int RawSize() const;
|
||||
|
||||
// Return true if the length of the referenced data is zero
|
||||
KVSTORE_API bool Empty() const;
|
||||
|
||||
// Return the the byte in the referenced data.
|
||||
// REQUIRES: n < size()
|
||||
KVSTORE_API uint8_t operator[](size_t n) const;
|
||||
|
||||
KVSTORE_API bool operator==(const Blob &) const;
|
||||
|
||||
// Change this blob to refer to an empty array
|
||||
KVSTORE_API void Clear();
|
||||
|
||||
// change vector<uint8_t> to std::string
|
||||
KVSTORE_API std::string ToString() const;
|
||||
|
||||
// comparison. Returns value:
|
||||
// < 0 if "*this" < "blob",
|
||||
// == 0 if "*this" == "blob",
|
||||
// > 0 if "*this" > "blob"
|
||||
KVSTORE_API int Compare(const Blob &blob) const;
|
||||
|
||||
// Return true if "blob" is a prefix of "*this"
|
||||
KVSTORE_API bool StartsWith(const Blob &blob) const;
|
||||
|
||||
// Write a parcelable object to the given parcel.
|
||||
// The object position is saved into Parcel if set asRemote_ to
|
||||
// true, and this intends to use in kernel data transaction.
|
||||
// Returns true being written on success or false if any error occur.
|
||||
KVSTORE_API bool Marshalling(Parcel &parcel) const override;
|
||||
|
||||
// get data from the given parcel into this parcelable object.
|
||||
KVSTORE_API static Blob *Unmarshalling(Parcel &parcel);
|
||||
|
||||
/* write blob size and data to memory buffer. return error when bufferLeftSize not enough. */
|
||||
bool WriteToBuffer(uint8_t *&cursorPtr, int &bufferLeftSize) const;
|
||||
|
||||
/* read a blob from memory buffer. */
|
||||
bool ReadFromBuffer(const uint8_t *&cursorPtr, int &bufferLeftSize);
|
||||
private:
|
||||
std::vector<uint8_t> blob_;
|
||||
};
|
||||
|
||||
} // namespace DistributedKv
|
||||
} // namespace OHOS
|
||||
|
||||
#endif // DISTRIBUTED_KV_BLOB_H
|
@ -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 CHANGE_NOTIFICATION_H
|
||||
#define CHANGE_NOTIFICATION_H
|
||||
|
||||
#include <list>
|
||||
#include "types.h"
|
||||
#include "parcel.h"
|
||||
|
||||
namespace OHOS {
|
||||
namespace DistributedKv {
|
||||
class ChangeNotification final : public virtual Parcelable {
|
||||
public:
|
||||
// Constructor of ChangeNotification.
|
||||
ChangeNotification(const std::list<Entry> &insertEntries,
|
||||
const std::list<Entry> &updateEntries,
|
||||
const std::list<Entry> &deleteEntries,
|
||||
const std::string &deviceId,
|
||||
const bool isClear);
|
||||
|
||||
KVSTORE_API ~ChangeNotification();
|
||||
|
||||
// Get all inserted entries in this change.
|
||||
KVSTORE_API const std::list<Entry> &GetInsertEntries() const;
|
||||
|
||||
// Get all updated entries in this changing.
|
||||
KVSTORE_API const std::list<Entry> &GetUpdateEntries() const;
|
||||
|
||||
// Get all deleted entries in this changing.
|
||||
KVSTORE_API const std::list<Entry> &GetDeleteEntries() const;
|
||||
|
||||
// Get the device ID.
|
||||
KVSTORE_API const std::string &GetDeviceId() const;
|
||||
|
||||
// Check if this change is made by calling the Clear function.
|
||||
KVSTORE_API bool IsClear() const;
|
||||
|
||||
// Write a parcelable object to the given parcel.
|
||||
// The object position is saved into Parcel if asRemote_ is set to
|
||||
// true, and this intends to use in kernel data transaction.
|
||||
// Returns true if the writing is successful; returns false otherwise.
|
||||
KVSTORE_API bool Marshalling(Parcel &parcel) const override;
|
||||
|
||||
// Unmarshall the given parcel from this parcelable object.
|
||||
KVSTORE_API static ChangeNotification *Unmarshalling(Parcel &parcel);
|
||||
private:
|
||||
std::list<Entry> insertEntries_;
|
||||
|
||||
std::list<Entry> updateEntries_;
|
||||
|
||||
std::list<Entry> deleteEntries_;
|
||||
|
||||
std::string deviceId_;
|
||||
|
||||
bool isClear_ = false;
|
||||
};
|
||||
} // namespace DistributedKv
|
||||
} // namespace OHOS
|
||||
#endif // CHANGE_NOTIFICATION_H
|
542
interfaces/innerkits/distributeddata/include/data_query.h
Executable file
542
interfaces/innerkits/distributeddata/include/data_query.h
Executable file
@ -0,0 +1,542 @@
|
||||
/*
|
||||
* 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_DATA_QUERY_H
|
||||
#define DISTRIBUTED_DATA_QUERY_H
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <sstream>
|
||||
#include "visibility.h"
|
||||
|
||||
namespace OHOS {
|
||||
namespace DistributedKv {
|
||||
class DataQuery {
|
||||
public:
|
||||
KVSTORE_API DataQuery();
|
||||
|
||||
KVSTORE_API ~DataQuery() = default;
|
||||
|
||||
// Reset the query.
|
||||
// Return:
|
||||
// This Query.
|
||||
KVSTORE_API DataQuery& Reset();
|
||||
|
||||
// Equal to int value.
|
||||
// Parameters:
|
||||
// field: the field name.
|
||||
// value: the field value.
|
||||
// Return:
|
||||
// This Query.
|
||||
KVSTORE_API DataQuery& EqualTo(const std::string &field, const int value);
|
||||
|
||||
// Equal to long value.
|
||||
// Parameters:
|
||||
// field: the field name.
|
||||
// value: the field value.
|
||||
// Return:
|
||||
// This Query.
|
||||
KVSTORE_API DataQuery& EqualTo(const std::string &field, const int64_t value);
|
||||
|
||||
// Equal to double value.
|
||||
// Parameters:
|
||||
// field: the field name.
|
||||
// value: the field value.
|
||||
// Return:
|
||||
// This Query.
|
||||
KVSTORE_API DataQuery& EqualTo(const std::string &field, const double value);
|
||||
|
||||
// Equal to String value.
|
||||
// Parameters:
|
||||
// field: the field name.
|
||||
// value: the field value.
|
||||
// Return:
|
||||
// This Query.
|
||||
KVSTORE_API DataQuery& EqualTo(const std::string &field, const std::string &value);
|
||||
|
||||
// Equal to boolean value.
|
||||
// Parameters:
|
||||
// field: the field name.
|
||||
// value: the field value.
|
||||
// Return:
|
||||
// This Query.
|
||||
KVSTORE_API DataQuery& EqualTo(const std::string &field, const bool value);
|
||||
|
||||
// Not equal to int value.
|
||||
// Parameters:
|
||||
// field: the field name.
|
||||
// value: the field value.
|
||||
// Return:
|
||||
// This Query.
|
||||
KVSTORE_API DataQuery& NotEqualTo(const std::string &field, const int value);
|
||||
|
||||
// Not equal to long value.
|
||||
// Parameters:
|
||||
// field: the field name.
|
||||
// value: the field value.
|
||||
// Return:
|
||||
// This Query.
|
||||
KVSTORE_API DataQuery& NotEqualTo(const std::string &field, const int64_t value);
|
||||
|
||||
// Not equal to double value.
|
||||
// Parameters:
|
||||
// field: the field name.
|
||||
// value: the field value.
|
||||
// Return:
|
||||
// This Query.
|
||||
KVSTORE_API DataQuery& NotEqualTo(const std::string &field, const double value);
|
||||
|
||||
// Not equal to String value.
|
||||
// Parameters:
|
||||
// field: the field name.
|
||||
// value: the field value.
|
||||
// Return:
|
||||
// This Query.
|
||||
KVSTORE_API DataQuery& NotEqualTo(const std::string &field, const std::string &value);
|
||||
|
||||
// Not equal to boolean value.
|
||||
// Parameters:
|
||||
// field: the field name.
|
||||
// value: the field value.
|
||||
// Return:
|
||||
// This Query.
|
||||
KVSTORE_API DataQuery& NotEqualTo(const std::string &field, const bool value);
|
||||
|
||||
// Greater than int value.
|
||||
// Parameters:
|
||||
// field: the field name.
|
||||
// value: the field value.
|
||||
// Return:
|
||||
// This Query.
|
||||
KVSTORE_API DataQuery& GreaterThan(const std::string &field, const int value);
|
||||
|
||||
// Greater than long value.
|
||||
// Parameters:
|
||||
// field: the field name.
|
||||
// value: the field value.
|
||||
// Return:
|
||||
// This Query.
|
||||
KVSTORE_API DataQuery& GreaterThan(const std::string &field, const int64_t value);
|
||||
|
||||
// Greater than double value.
|
||||
// Parameters:
|
||||
// field: the field name.
|
||||
// value: the field value.
|
||||
// Return:
|
||||
// This Query.
|
||||
KVSTORE_API DataQuery& GreaterThan(const std::string &field, const double value);
|
||||
|
||||
// Greater than String value.
|
||||
// Parameters:
|
||||
// field: the field name.
|
||||
// value: the field value.
|
||||
// Return:
|
||||
// This Query.
|
||||
KVSTORE_API DataQuery& GreaterThan(const std::string &field, const std::string &value);
|
||||
|
||||
// Less than int value.
|
||||
// Parameters:
|
||||
// field: the field name.
|
||||
// value: the field value.
|
||||
// Return:
|
||||
// This Query.
|
||||
KVSTORE_API DataQuery& LessThan(const std::string &field, const int value);
|
||||
|
||||
// Less than long value.
|
||||
// Parameters:
|
||||
// field: the field name.
|
||||
// value: the field value.
|
||||
// Return:
|
||||
// This Query.
|
||||
KVSTORE_API DataQuery& LessThan(const std::string &field, const int64_t value);
|
||||
|
||||
// Less than double value.
|
||||
// Parameters:
|
||||
// field: the field name.
|
||||
// value: the field value.
|
||||
// Return:
|
||||
// This Query.
|
||||
KVSTORE_API DataQuery& LessThan(const std::string &field, const double value);
|
||||
|
||||
// Less than String value.
|
||||
// Parameters:
|
||||
// field: the field name.
|
||||
// value: the field value.
|
||||
// Return:
|
||||
// This Query.
|
||||
KVSTORE_API DataQuery& LessThan(const std::string &field, const std::string &value);
|
||||
|
||||
// Greater than or equal to int value.
|
||||
// Parameters:
|
||||
// field: the field name.
|
||||
// value: the field value.
|
||||
// Return:
|
||||
// This Query.
|
||||
KVSTORE_API DataQuery& GreaterThanOrEqualTo(const std::string &field, const int value);
|
||||
|
||||
// Greater than or equal to long value.
|
||||
// Parameters:
|
||||
// field: the field name.
|
||||
// value: the field value.
|
||||
// Return:
|
||||
// This Query.
|
||||
KVSTORE_API DataQuery& GreaterThanOrEqualTo(const std::string &field, const int64_t value);
|
||||
|
||||
// Greater than or equal to double value.
|
||||
// Parameters:
|
||||
// field: the field name.
|
||||
// value: the field value.
|
||||
// Return:
|
||||
// This Query.
|
||||
KVSTORE_API DataQuery& GreaterThanOrEqualTo(const std::string &field, const double value);
|
||||
|
||||
// Greater than or equal to String value.
|
||||
// Parameters:
|
||||
// field: the field name.
|
||||
// value: the field value.
|
||||
// Return:
|
||||
// This Query.
|
||||
KVSTORE_API DataQuery& GreaterThanOrEqualTo(const std::string &field, const std::string &value);
|
||||
|
||||
// Less than or equal to int value.
|
||||
// Parameters:
|
||||
// field: the field name.
|
||||
// value: the field value.
|
||||
// Return:
|
||||
// This Query.
|
||||
KVSTORE_API DataQuery& LessThanOrEqualTo(const std::string &field, const int value);
|
||||
|
||||
// Less than or equal to long value.
|
||||
// Parameters:
|
||||
// field: the field name.
|
||||
// value: the field value.
|
||||
// Return:
|
||||
// This Query.
|
||||
KVSTORE_API DataQuery& LessThanOrEqualTo(const std::string &field, const int64_t value);
|
||||
|
||||
// Less than or equal to double value.
|
||||
// Parameters:
|
||||
// field: the field name.
|
||||
// value: the field value.
|
||||
// Return:
|
||||
// This Query.
|
||||
KVSTORE_API DataQuery& LessThanOrEqualTo(const std::string &field, const double value);
|
||||
|
||||
// Less than or equal to String value.
|
||||
// Parameters:
|
||||
// field: the field name.
|
||||
// value: the field value.
|
||||
// Return:
|
||||
// This Query.
|
||||
KVSTORE_API DataQuery& LessThanOrEqualTo(const std::string &field, const std::string &value);
|
||||
|
||||
// Is null field value.
|
||||
// Parameters:
|
||||
// field: the field name.
|
||||
// Return:
|
||||
// This Query.
|
||||
KVSTORE_API DataQuery& IsNull(const std::string &field);
|
||||
|
||||
// Is not null field value.
|
||||
// Parameters:
|
||||
// field: the field name.
|
||||
// Return:
|
||||
// This Query.
|
||||
KVSTORE_API DataQuery& IsNotNull(const std::string &field);
|
||||
|
||||
// In int value list.
|
||||
// Parameters:
|
||||
// field: the field name.
|
||||
// value: the field value list.
|
||||
// Return:
|
||||
// This Query.
|
||||
KVSTORE_API DataQuery& InInt(const std::string &field, const std::vector<int> &valueList);
|
||||
|
||||
// In long value list.
|
||||
// Parameters:
|
||||
// field: the field name.
|
||||
// value: the field value list.
|
||||
// Return:
|
||||
// This Query.
|
||||
KVSTORE_API DataQuery& InLong(const std::string &field, const std::vector<int64_t> &valueList);
|
||||
|
||||
// In Double value list.
|
||||
// Parameters:
|
||||
// field: the field name.
|
||||
// value: the field value list.
|
||||
// Return:
|
||||
// This Query.
|
||||
KVSTORE_API DataQuery& InDouble(const std::string &field, const std::vector<double> &valueList);
|
||||
|
||||
// In String value list.
|
||||
// Parameters:
|
||||
// field: the field name.
|
||||
// value: the field value list.
|
||||
// Return:
|
||||
// This Query.
|
||||
KVSTORE_API DataQuery& InString(const std::string &field, const std::vector<std::string> &valueList);
|
||||
|
||||
// Not in int value list.
|
||||
// Parameters:
|
||||
// field: the field name.
|
||||
// value: the field value list.
|
||||
// Return:
|
||||
// This Query.
|
||||
KVSTORE_API DataQuery& NotInInt(const std::string &field, const std::vector<int> &valueList);
|
||||
|
||||
// Not in long value list.
|
||||
// Parameters:
|
||||
// field: the field name.
|
||||
// value: the field value list.
|
||||
// Return:
|
||||
// This Query.
|
||||
KVSTORE_API DataQuery& NotInLong(const std::string &field, const std::vector<int64_t> &valueList);
|
||||
|
||||
// Not in Double value list.
|
||||
// Parameters:
|
||||
// field: the field name.
|
||||
// value: the field value list.
|
||||
// Return:
|
||||
// This Query.
|
||||
KVSTORE_API DataQuery& NotInDouble(const std::string &field, const std::vector<double> &valueList);
|
||||
|
||||
// Not in String value list.
|
||||
// Parameters:
|
||||
// field: the field name.
|
||||
// value: the field value list.
|
||||
// Return:
|
||||
// This Query.
|
||||
KVSTORE_API DataQuery& NotInString(const std::string &field, const std::vector<std::string> &valueList);
|
||||
|
||||
// Like String value.
|
||||
// Parameters:
|
||||
// field: the field name.
|
||||
// value: the field value list.
|
||||
// Return:
|
||||
// This Query.
|
||||
KVSTORE_API DataQuery& Like(const std::string &field, const std::string &value);
|
||||
|
||||
// Unlike String value.
|
||||
// Parameters:
|
||||
// field: the field name.
|
||||
// value: the field value list.
|
||||
// Return:
|
||||
// This Query.
|
||||
KVSTORE_API DataQuery& Unlike(const std::string &field, const std::string &value);
|
||||
|
||||
// And operator.
|
||||
// Return:
|
||||
// This Query.
|
||||
KVSTORE_API DataQuery& And();
|
||||
|
||||
// Or operator.
|
||||
// Return:
|
||||
// This Query.
|
||||
KVSTORE_API DataQuery& Or();
|
||||
|
||||
// Order by ascent.
|
||||
// Parameters:
|
||||
// field: the field name.
|
||||
// Return:
|
||||
// This Query.
|
||||
KVSTORE_API DataQuery& OrderByAsc(const std::string &field);
|
||||
|
||||
// Order by descent.
|
||||
// Parameters:
|
||||
// field: the field name.
|
||||
// Return:
|
||||
// This Query.
|
||||
KVSTORE_API DataQuery& OrderByDesc(const std::string &field);
|
||||
|
||||
// Limit result size.
|
||||
// Parameters:
|
||||
// number: the number of results.
|
||||
// offset: the start position.
|
||||
// Return:
|
||||
// This Query.
|
||||
KVSTORE_API DataQuery& Limit(const int number, const int offset);
|
||||
|
||||
// Begin group.
|
||||
// Return:
|
||||
// This Query.
|
||||
KVSTORE_API DataQuery& BeginGroup();
|
||||
|
||||
// End group.
|
||||
// Return:
|
||||
// This Query.
|
||||
KVSTORE_API DataQuery& EndGroup();
|
||||
|
||||
// Select results with specified key prefix.
|
||||
// Parameters:
|
||||
// prefix: key prefix.
|
||||
// Return:
|
||||
// This Query.
|
||||
KVSTORE_API DataQuery& KeyPrefix(const std::string &prefix);
|
||||
|
||||
// Select results with suggested index.
|
||||
// Parameters:
|
||||
// index: suggested index.
|
||||
// Return:
|
||||
// This Query.
|
||||
KVSTORE_API DataQuery& SetSuggestIndex(const std::string &index);
|
||||
|
||||
// Get string representation
|
||||
// Return:
|
||||
// String representation of this query.
|
||||
KVSTORE_API std::string ToString() const;
|
||||
|
||||
// equal to
|
||||
static const std::string EQUAL_TO;
|
||||
|
||||
// not equal to
|
||||
static const std::string NOT_EQUAL_TO;
|
||||
|
||||
// greater than
|
||||
static const std::string GREATER_THAN;
|
||||
|
||||
// less than
|
||||
static const std::string LESS_THAN;
|
||||
|
||||
// greater than or equal to
|
||||
static const std::string GREATER_THAN_OR_EQUAL_TO;
|
||||
|
||||
// less than or equal to
|
||||
static const std::string LESS_THAN_OR_EQUAL_TO;
|
||||
|
||||
// is null
|
||||
static const std::string IS_NULL;
|
||||
|
||||
// in
|
||||
static const std::string IN;
|
||||
|
||||
// not in
|
||||
static const std::string NOT_IN;
|
||||
|
||||
// like
|
||||
static const std::string LIKE;
|
||||
|
||||
// not like
|
||||
static const std::string NOT_LIKE;
|
||||
|
||||
// and
|
||||
static const std::string AND;
|
||||
|
||||
// or
|
||||
static const std::string OR;
|
||||
|
||||
// order by asc
|
||||
static const std::string ORDER_BY_ASC;
|
||||
|
||||
// order by desc
|
||||
static const std::string ORDER_BY_DESC;
|
||||
|
||||
// limit
|
||||
static const std::string LIMIT;
|
||||
|
||||
// space
|
||||
static const std::string SPACE;
|
||||
|
||||
// '^'
|
||||
static const std::string SPECIAL;
|
||||
|
||||
// '^' escape
|
||||
static const std::string SPECIAL_ESCAPE;
|
||||
|
||||
// space escape
|
||||
static const std::string SPACE_ESCAPE;
|
||||
|
||||
// empty string
|
||||
static const std::string EMPTY_STRING;
|
||||
|
||||
// start in
|
||||
static const std::string START_IN;
|
||||
|
||||
// end in
|
||||
static const std::string END_IN;
|
||||
|
||||
// begin group
|
||||
static const std::string BEGIN_GROUP;
|
||||
|
||||
// end group
|
||||
static const std::string END_GROUP;
|
||||
|
||||
// key prefix
|
||||
static const std::string KEY_PREFIX;
|
||||
|
||||
// device id
|
||||
static const std::string DEVICE_ID;
|
||||
|
||||
// is not null
|
||||
static const std::string IS_NOT_NULL;
|
||||
|
||||
// type string
|
||||
static const std::string TYPE_STRING;
|
||||
|
||||
// type integer
|
||||
static const std::string TYPE_INTEGER;
|
||||
|
||||
// type long
|
||||
static const std::string TYPE_LONG;
|
||||
|
||||
// type double
|
||||
static const std::string TYPE_DOUBLE;
|
||||
|
||||
// type boolean
|
||||
static const std::string TYPE_BOOLEAN;
|
||||
|
||||
// value true
|
||||
static const std::string VALUE_TRUE;
|
||||
|
||||
// value false
|
||||
static const std::string VALUE_FALSE;
|
||||
|
||||
// suggested index
|
||||
static const std::string SUGGEST_INDEX;
|
||||
private:
|
||||
std::string str_;
|
||||
|
||||
template<typename T>
|
||||
void AppendCommon(const std::string &keyword, const std::string &fieldType, std::string &field, const T &value);
|
||||
|
||||
void AppendCommonString(const std::string &keyword, const std::string &fieldType,
|
||||
std::string &field, std::string &value);
|
||||
|
||||
void AppendCommonBoolean(const std::string &keyword, const std::string &fieldType,
|
||||
std::string &field, const bool &value);
|
||||
|
||||
void AppendCommonString(const std::string &keyword, std::string &field, std::string &value);
|
||||
|
||||
template<typename T>
|
||||
void AppendCommonList(const std::string &keyword, const std::string &fieldType,
|
||||
std::string &field, const std::vector<T> &valueList);
|
||||
|
||||
void AppendCommonListString(const std::string &keyword, const std::string &fieldType,
|
||||
std::string &field, std::vector<std::string> &valueList);
|
||||
|
||||
void EscapeSpace(std::string &input);
|
||||
|
||||
bool ValidateField(const std::string &field);
|
||||
|
||||
bool ValidateValue(const std::string &value);
|
||||
|
||||
bool ValidateStringValueList(const std::vector<std::string> &valueList);
|
||||
|
||||
template<typename T>
|
||||
std::string BasicToString(const T &value);
|
||||
};
|
||||
} // namespace DistributedKv
|
||||
} // namespace OHOS
|
||||
|
||||
#endif // DISTRIBUTED_DATA_QUERY_H
|
@ -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 DEVICE_STATUS_CHANGE_LISTENER_H
|
||||
#define DEVICE_STATUS_CHANGE_LISTENER_H
|
||||
|
||||
#include "types.h"
|
||||
|
||||
namespace OHOS {
|
||||
namespace DistributedKv {
|
||||
class DeviceStatusChangeListener {
|
||||
public:
|
||||
KVSTORE_API virtual ~DeviceStatusChangeListener() {};
|
||||
KVSTORE_API virtual void OnDeviceChanged(const DeviceInfo &info, const DeviceChangeType &type) const = 0;
|
||||
KVSTORE_API virtual DeviceFilterStrategy GetFilterStrategy() const = 0;
|
||||
};
|
||||
} // namespace DistributedKv
|
||||
} // namespace OHOS
|
||||
|
||||
#endif // DEVICE_STATUS_CHANGE_LISTENER_H
|
@ -0,0 +1,161 @@
|
||||
/*
|
||||
* Copyright (c) 2021 Huawei Device Co., Ltd.
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#ifndef DISTRIBUTED_KV_DATA_MANAGER_H
|
||||
#define DISTRIBUTED_KV_DATA_MANAGER_H
|
||||
|
||||
#include "kvstore.h"
|
||||
#include "kvstore_death_recipient.h"
|
||||
#include "kvstore_observer.h"
|
||||
#include "single_kvstore.h"
|
||||
#include "types.h"
|
||||
#include "device_status_change_listener.h"
|
||||
|
||||
namespace OHOS {
|
||||
namespace DistributedKv {
|
||||
class DistributedKvDataManager final {
|
||||
public:
|
||||
KVSTORE_API
|
||||
DistributedKvDataManager();
|
||||
|
||||
KVSTORE_API
|
||||
~DistributedKvDataManager();
|
||||
|
||||
// Open kvstore instance with the given storeId, creating it if needed.
|
||||
// It is allowed to open the same kvstore concurrently
|
||||
// multiple times, but only one KvStoreImpl will be created.
|
||||
// Parameters:
|
||||
// options: the config of the kvstore, including encrypt,
|
||||
// create if needed and whether need sync between devices.
|
||||
// appId: the name of the application.
|
||||
// :storeId: the name of the kvstore.
|
||||
// callback: including status and KvStore instance returned by this call.
|
||||
// callback will return:
|
||||
// if Options.createIfMissing is false and kvstore has not been created before,
|
||||
// STORE_NOT_FOUND and nullptr,
|
||||
// if storeId is not valid, INVALID_ARGUMENT and nullptr,
|
||||
// if appId has no permission, PERMISSION_DENIED and nullptr,
|
||||
// otherwise, SUCCESS and the unipue_ptr of kvstore, which client can use to operate kvstore, will be returned.
|
||||
KVSTORE_API void GetKvStore(const Options &options, const AppId &appId, const StoreId &storeId,
|
||||
std::function<void(Status, std::unique_ptr<KvStore>)> callback);
|
||||
|
||||
// Open kvstore instance with the given storeId, creating it if needed.
|
||||
// It is allowed to open the same kvstore concurrently
|
||||
// multiple times, but only one KvStoreImpl will be created.
|
||||
// Parameters:
|
||||
// options: the config of the kvstore, including encrypt,
|
||||
// create if needed and whether need sync between devices.
|
||||
// appId: the name of the application.
|
||||
// :storeId: the name of the kvstore.
|
||||
// callback: including status and KvStore instance returned by this call.
|
||||
// callback will return:
|
||||
// if Options.createIfMissing is false and kvstore has not been created before,
|
||||
// STORE_NOT_FOUND and nullptr,
|
||||
// if storeId is not valid, INVALID_ARGUMENT and nullptr,
|
||||
// if appId has no permission, PERMISSION_DENIED and nullptr,
|
||||
// otherwise, SUCCESS and the unipue_ptr of kvstore, which client can use to operate kvstore, will be returned.
|
||||
KVSTORE_API void GetSingleKvStore(const Options &options, const AppId &appId, const StoreId &storeId,
|
||||
std::function<void(Status, std::unique_ptr<SingleKvStore>)> callback);
|
||||
|
||||
// get all existed kvstore names.
|
||||
KVSTORE_API void GetAllKvStoreId(const AppId &appId, std::function<void(Status, std::vector<StoreId> &)> callback);
|
||||
|
||||
// WARNING: try to close a KvStore while other thread(s) still using it may cause process crash.
|
||||
// Disconnect kvstore instance from kvstoreimpl with the given storeId,
|
||||
// if all kvstore created for a single kvsotreimpl, kvstoreimpl and resource below will be freed.
|
||||
// before this call, all KvStoreSnapshot must be released firstly,
|
||||
// otherwise this call will fail.
|
||||
// after this call, kvstore and kvstoresnapshot become invalid.
|
||||
// call to it will return nullptr exception.
|
||||
// Parameters:
|
||||
// appId: the name of the application.
|
||||
// storeId: the name of the kvstore.
|
||||
KVSTORE_API
|
||||
Status CloseKvStore(const AppId &appId, const StoreId &storeId, std::unique_ptr<KvStore> kvStorePtr = nullptr);
|
||||
|
||||
// WARNING: try to close a KvStore while other thread(s) still using it may cause process crash.
|
||||
//
|
||||
// Disconnect kvstore instance from kvstoreimpl.
|
||||
// if all kvstore created for a single kvsotreimpl, kvstoreimpl and resource below will be freed.
|
||||
// before this call, all KvStoreResultSet must be released firstly,
|
||||
// otherwise this call will fail.
|
||||
// after this call, kvstore and KvStoreResultSet become invalid.
|
||||
// call to it will return nullptr exception.
|
||||
// Parameters:
|
||||
// appId: the name of the application.
|
||||
// kvStorePtr: the pointer of the kvstore.
|
||||
KVSTORE_API
|
||||
Status CloseKvStore(const AppId &appId, std::unique_ptr<SingleKvStore> kvStorePtr);
|
||||
|
||||
// WARNING: try to close a KvStore while other thread(s) still using it may cause process crash.
|
||||
// close all opened kvstores for this appId.
|
||||
KVSTORE_API Status CloseAllKvStore(const AppId &appId);
|
||||
|
||||
// delete kvstore file with the given storeId.
|
||||
// client should first close all connections to it and then delete it,
|
||||
// otherwise delete may return error.
|
||||
// after this call, kvstore and kvstoresnapshot become invalid.
|
||||
// call to it will return error.
|
||||
// Parameters:
|
||||
// appId: the name of the application.
|
||||
// storeId: the name of the kvstore.
|
||||
KVSTORE_API Status DeleteKvStore(const AppId &appId, const StoreId &storeId);
|
||||
|
||||
// delete all kvstore.
|
||||
KVSTORE_API Status DeleteAllKvStore(const AppId &appId);
|
||||
|
||||
KVSTORE_API void RegisterKvStoreServiceDeathRecipient(std::shared_ptr<KvStoreDeathRecipient> kvStoreDeathRecipient);
|
||||
|
||||
KVSTORE_API
|
||||
void UnRegisterKvStoreServiceDeathRecipient(std::shared_ptr<KvStoreDeathRecipient> kvStoreDeathRecipient);
|
||||
|
||||
// Subscribe device status change, like online or offline.
|
||||
// Client should override AppDeviceStatusChangeListener and register it by this function, observer->OnDeviceChanged
|
||||
// will be called on remote device status change.
|
||||
// Parameters:
|
||||
// observer: callback for device status change event.
|
||||
// Return:
|
||||
// Status of this subscribe operation.
|
||||
KVSTORE_API Status StartWatchDeviceChange(std::shared_ptr<DeviceStatusChangeListener> observer);
|
||||
|
||||
// Unsubscribe device status change, like online or offline.
|
||||
// client should override AppDeviceStatusChangeListener and register it by calling this function, then
|
||||
// observer->OnDeviceChanged will no longer be called on remote device status change.
|
||||
// Parameters:
|
||||
// observer: callback for device status change event.
|
||||
// Return:
|
||||
// Status of this unsubscribe operation.
|
||||
KVSTORE_API Status StopWatchDeviceChange(std::shared_ptr<DeviceStatusChangeListener> observer);
|
||||
|
||||
// Get all connected devices.
|
||||
// Client can use this method to retrieve all devices that have already connected,
|
||||
// and then call StartWatchDeviceChange to watch device status change later.
|
||||
// Parameters:
|
||||
// deviceInfoList: list of all connected device will be returned by this parameter.
|
||||
// Return:
|
||||
// Status of this get device list operation.
|
||||
KVSTORE_API Status GetDeviceList(std::vector<DeviceInfo> &deviceInfoList, DeviceFilterStrategy strategy);
|
||||
|
||||
// Get device.
|
||||
// Client can use this method to retrieve local device,
|
||||
// Parameters:
|
||||
// localDevice: DeviceInfo will be returned by this parameter.
|
||||
// Return:
|
||||
// Status of this get device operation.
|
||||
KVSTORE_API Status GetLocalDevice(DeviceInfo &localDevice);
|
||||
};
|
||||
} // namespace DistributedKv
|
||||
} // namespace OHOS
|
||||
#endif // DISTRIBUTED_KV_DATA_MANAGER_H
|
124
interfaces/innerkits/distributeddata/include/kvstore.h
Normal file
124
interfaces/innerkits/distributeddata/include/kvstore.h
Normal file
@ -0,0 +1,124 @@
|
||||
/*
|
||||
* 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_H
|
||||
#define KVSTORE_H
|
||||
|
||||
#include "kvstore_observer.h"
|
||||
#include "kvstore_snapshot.h"
|
||||
#include "types.h"
|
||||
|
||||
namespace OHOS {
|
||||
namespace DistributedKv {
|
||||
class KvStore {
|
||||
public:
|
||||
KVSTORE_API KvStore() = default;
|
||||
|
||||
// forbidden copy constructor.
|
||||
KvStore(const KvStore &) = delete;
|
||||
KvStore &operator=(const KvStore &) = delete;
|
||||
|
||||
KVSTORE_API virtual ~KvStore()
|
||||
{}
|
||||
|
||||
// Get kvstore name of this kvstore instance.
|
||||
KVSTORE_API virtual StoreId GetStoreId() const = 0;
|
||||
|
||||
// Creates a snapshot of the kvstore, allowing the client app to read a
|
||||
// consistent data of the content of the kvstore.
|
||||
//
|
||||
// If observer is provided, it will receive notifications for changes of the
|
||||
// kvstore newer than the resulting snapshot.
|
||||
// Parameters:
|
||||
// observer: observer for subscribe.
|
||||
// callback: including status and KvStoreSnapshot instance returned by this call.
|
||||
KVSTORE_API
|
||||
virtual void GetKvStoreSnapshot(std::shared_ptr<KvStoreObserver> observer,
|
||||
std::function<void(Status, std::unique_ptr<KvStoreSnapshot>)> callback) const = 0;
|
||||
|
||||
// Release snapshot created by calling GetKvStoreSnapshot.
|
||||
KVSTORE_API virtual Status ReleaseKvStoreSnapshot(std::unique_ptr<KvStoreSnapshot> kvStoreSnapshotPtr) = 0;
|
||||
|
||||
// Mutation operations.
|
||||
// Key level operations.
|
||||
// Mutations are bundled together into atomic commits. If a transaction is in
|
||||
// progress, the list of mutations bundled together is tied to the current
|
||||
// transaction. If no transaction is in progress, mutations will be a unique transaction.
|
||||
// Put one entry with key-value into kvstore,
|
||||
// key length should not be greater than 256, and can not be empty.
|
||||
// value size should be less than IPC transport limit, and can not be empty.
|
||||
KVSTORE_API virtual Status Put(const Key &key, const Value &value) = 0;
|
||||
|
||||
// see Put, PutBatch put a list of entries to kvstore,
|
||||
// all entries will be put in a transaction,
|
||||
// if entries contains invalid entry, PutBatch will all fail.
|
||||
// entries's size should be less than 128 and memory size must be less than IPC transport limit.
|
||||
KVSTORE_API virtual Status PutBatch(const std::vector<Entry> &entries) = 0;
|
||||
|
||||
// delete one entry in the kvstore,
|
||||
// delete non-exist key still return KEY NOT FOUND error,
|
||||
// key length should not be greater than 256, and can not be empty.
|
||||
KVSTORE_API virtual Status Delete(const Key &key) = 0;
|
||||
|
||||
// delete a list of entries in the kvstore,
|
||||
// delete key not exist still return success,
|
||||
// key length should not be greater than 256, and can not be empty.
|
||||
// if keys contains invaid key, all delete will fail.
|
||||
// keys memory size should not be greater than IPC transport limit, and can not be empty.
|
||||
KVSTORE_API virtual Status DeleteBatch(const std::vector<Key> &keys) = 0;
|
||||
|
||||
// clear all entries in the kvstore.
|
||||
// after this call, IsClear function in ChangeNotification in subscription return true.
|
||||
KVSTORE_API virtual Status Clear() = 0;
|
||||
|
||||
// start transaction.
|
||||
// all changes to this kvstore will be in a same transaction and will not change the store until Commit() or
|
||||
// Rollback() is called.
|
||||
// before this transaction is committed or rollbacked, all attemption to close this store will fail.
|
||||
KVSTORE_API virtual Status StartTransaction() = 0;
|
||||
|
||||
// commit current transaction. all changes to this store will be done after calling this method.
|
||||
// any calling of this method outside a transaction will fail.
|
||||
KVSTORE_API virtual Status Commit() = 0;
|
||||
|
||||
// rollback current transaction.
|
||||
// all changes to this store during this transaction will be rollback after calling this method.
|
||||
// any calling of this method outside a transaction will fail.
|
||||
KVSTORE_API virtual Status Rollback() = 0;
|
||||
|
||||
// subscribe kvstore to watch data change in the kvstore,
|
||||
// OnChange in he observer will be called when data changed, with all the changed contents.
|
||||
// client is responsible for free observer after and only after call UnSubscribeKvStore.
|
||||
// otherwise, codes in sdk may use a freed memory and cause unexpected result.
|
||||
// Parameters:
|
||||
// subscribeType: strategy for this subscribe, default right now.
|
||||
// observer: callback client provided, client must implement KvStoreObserver and override OnChange function, when
|
||||
// data changed in store, OnChange will called in Observer.
|
||||
KVSTORE_API
|
||||
virtual Status SubscribeKvStore(SubscribeType subscribeType, std::shared_ptr<KvStoreObserver> observer) = 0;
|
||||
|
||||
// unSubscribe kvstore to un-watch data change in the kvstore,
|
||||
// after this call, no message will be received even data change in the kvstore.
|
||||
// client is responsible for free observer after and only after call UnSubscribeKvStore.
|
||||
// otherwise, codes in sdk may use a freed memory and cause unexpected result.
|
||||
// Parameters:
|
||||
// subscribeType: strategy for this subscribe, default right now.
|
||||
// observer: callback client provided in SubscribeKvStore.
|
||||
KVSTORE_API
|
||||
virtual Status UnSubscribeKvStore(SubscribeType subscribeType, std::shared_ptr<KvStoreObserver> observer) = 0;
|
||||
};
|
||||
} // namespace DistributedKv
|
||||
} // namespace OHOS
|
||||
#endif // KVSTORE_H
|
@ -0,0 +1,29 @@
|
||||
/*
|
||||
* 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_DEATH_RECIPIENT_H
|
||||
#define KVSTORE_DEATH_RECIPIENT_H
|
||||
|
||||
#include "visibility.h"
|
||||
|
||||
namespace OHOS {
|
||||
namespace DistributedKv {
|
||||
class KvStoreDeathRecipient {
|
||||
public:
|
||||
KVSTORE_API virtual void OnRemoteDied() = 0;
|
||||
};
|
||||
} // namespace DistributedKv
|
||||
} // namespace OHOS
|
||||
#endif // KVSTORE_DEATH_RECIPIENT_H
|
@ -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 KVSTORE_OBSERVER_H
|
||||
#define KVSTORE_OBSERVER_H
|
||||
|
||||
#include <memory>
|
||||
#include "change_notification.h"
|
||||
#include "kvstore_snapshot.h"
|
||||
|
||||
namespace OHOS {
|
||||
namespace DistributedKv {
|
||||
// client implement this class to watch kvstore change.
|
||||
class KvStoreObserver {
|
||||
public:
|
||||
KVSTORE_API KvStoreObserver() = default;
|
||||
|
||||
KVSTORE_API virtual ~KvStoreObserver()
|
||||
{}
|
||||
|
||||
// client override this function to receive change notification.
|
||||
KVSTORE_API
|
||||
virtual void OnChange(const ChangeNotification &changeNotification, std::unique_ptr<KvStoreSnapshot> snapshot) = 0;
|
||||
|
||||
// client override this function to receive change notification.
|
||||
KVSTORE_API
|
||||
virtual void OnChange(const ChangeNotification &changeNotification)
|
||||
{}
|
||||
};
|
||||
} // namespace DistributedKv
|
||||
} // namespace OHOS
|
||||
#endif // KVSTORE_OBSERVER_H
|
@ -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 KVSTORE_RESULT_SET_H
|
||||
#define KVSTORE_RESULT_SET_H
|
||||
|
||||
#include "types.h"
|
||||
|
||||
namespace OHOS {
|
||||
namespace DistributedKv {
|
||||
class KvStoreResultSet {
|
||||
public:
|
||||
KVSTORE_API virtual ~KvStoreResultSet()
|
||||
{}
|
||||
|
||||
// Returns the count of rows in the result set.
|
||||
KVSTORE_API virtual int GetCount() const = 0;
|
||||
|
||||
// Returns the current read position of the result set.
|
||||
KVSTORE_API virtual int GetPosition() const = 0;
|
||||
|
||||
// Move the read position to the first row, return false if the result set is empty.
|
||||
KVSTORE_API virtual bool MoveToFirst() = 0;
|
||||
|
||||
// Move the read position to the last row, return false if the result set is empty.
|
||||
KVSTORE_API virtual bool MoveToLast() = 0;
|
||||
|
||||
// Move the read position to the next row,
|
||||
// return false if the result set is empty or the read position is already past the last entry in the result set.
|
||||
KVSTORE_API virtual bool MoveToNext() = 0;
|
||||
|
||||
// Move the read position to the previous row,
|
||||
// return false if result set is empty or the read position is already before the first entry in the result set.
|
||||
KVSTORE_API virtual bool MoveToPrevious() = 0;
|
||||
|
||||
// Move the read position by a relative amount from the current position.
|
||||
KVSTORE_API virtual bool Move(int offset) = 0;
|
||||
|
||||
// Move the read position to an absolute position value.
|
||||
KVSTORE_API virtual bool MoveToPosition(int position) = 0;
|
||||
|
||||
// Returns whether the read position is pointing to the first row.
|
||||
KVSTORE_API virtual bool IsFirst() const = 0;
|
||||
|
||||
// Returns whether the read position is pointing to the last row.
|
||||
KVSTORE_API virtual bool IsLast() const = 0;
|
||||
|
||||
// Returns whether the read position is before the first row.
|
||||
KVSTORE_API virtual bool IsBeforeFirst() const = 0;
|
||||
|
||||
// Returns whether the read position is after the last row.
|
||||
KVSTORE_API virtual bool IsAfterLast() const = 0;
|
||||
|
||||
// Get a key-value entry.
|
||||
KVSTORE_API virtual Status GetEntry(Entry &entry) const = 0;
|
||||
};
|
||||
} // namespace DistributedKv
|
||||
} // namespace OHOS
|
||||
#endif // KVSTORE_RESULT_SET_H
|
94
interfaces/innerkits/distributeddata/include/kvstore_snapshot.h
Executable file
94
interfaces/innerkits/distributeddata/include/kvstore_snapshot.h
Executable file
@ -0,0 +1,94 @@
|
||||
/*
|
||||
* 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_SNAPSHOT_H
|
||||
#define KVSTORE_SNAPSHOT_H
|
||||
|
||||
#include "types.h"
|
||||
|
||||
namespace OHOS {
|
||||
namespace DistributedKv {
|
||||
class KvStoreSnapshot {
|
||||
public:
|
||||
KVSTORE_API KvStoreSnapshot() = default;
|
||||
|
||||
KVSTORE_API virtual ~KvStoreSnapshot()
|
||||
{}
|
||||
|
||||
// Deprecated. use the GetEntries interface without nextKey as parameter instead.
|
||||
// Get a list of entries from kvstore by keyPrefix,
|
||||
// key length must be less than 1024,
|
||||
// GetEntries will return all entries whose Key.StartsWith(keyPrefix) is true,
|
||||
// if keyPrefix is empty, all entries in the kvstore will be returned.
|
||||
// if data size is larger than 800k, data may be transported by several times. each time callback will give you the
|
||||
// first key of the not-transported part. You can use this key as nextKey to get next part of data. When you get an
|
||||
// empty nextKey, It means all data has been transported.
|
||||
// parameters:
|
||||
// prefixKey: perfix key to search
|
||||
// nextKey: The first key to start in this search.
|
||||
// callback: all entries satisfied perfixKey, status of this call and the first key of the next part of data.
|
||||
[[deprecated]]
|
||||
KVSTORE_API virtual void GetEntries(const Key &prefixKey, const Key &nextKey,
|
||||
std::function<void(Status, std::vector<Entry> &, const Key &)> callback) = 0;
|
||||
|
||||
// Get a list of entries from kvstore by keyPrefix,
|
||||
// key length must be less than 1024,
|
||||
// GetEntries will return all entries whose Key.StartsWith(keyPrefix) is true,
|
||||
// if keyPrefix is empty, all entries in the kvstore will be returned.
|
||||
// if some entry in the return set large then 750k, GetEntries may only return entries before this entry. you need
|
||||
// to use GetKeys interface to get all keys, then use Get interface to get each entry.
|
||||
// parameters:
|
||||
// prefixKey: perfix key to search
|
||||
// callback: all entries satisfies perfixKey, and Stauts for this call.
|
||||
KVSTORE_API
|
||||
virtual void GetEntries(const Key &prefixKey, std::function<void(Status, std::vector<Entry> &)> callback) = 0;
|
||||
|
||||
// Deprecated. use the GetKeys interface without nextKey as parameter instead.
|
||||
// Get a list of keys from kvstore by keyPrefix,
|
||||
// key length must be less than 1024,
|
||||
// GetKeys will return all keys whose Key.StartsWith(keyPrefix) is true,
|
||||
// if keyPrefix is empty, all keys in the kvstore will be returned.
|
||||
// if data size is larger than 800k, data may be transported by several times. each time callback will give you the
|
||||
// first key of the not-transported part. You can use this key as nextKey to get next part of data. When you get an
|
||||
// empty nextKey, It means all data has been transported.
|
||||
// parameters:
|
||||
// prefixKey: perfix key to search
|
||||
// nextKey: The first key to start in this search.
|
||||
// callback: all keys satisfies perfixKey, status of this call and the first key of the next part of data.
|
||||
[[deprecated]]
|
||||
KVSTORE_API virtual void GetKeys(const Key &prefixKey, const Key &nextKey,
|
||||
std::function<void(Status, std::vector<Key> &, const Key &)> callback) = 0;
|
||||
|
||||
// Get a list of keys from kvstore by keyPrefix,
|
||||
// key length must be less than 1024,
|
||||
// GetKeys will return all keys whose Key.StartsWith(keyPrefix) is true,
|
||||
// if keyPrefix is empty, all keys in the kvstore will be returned.
|
||||
// parameters:
|
||||
// prefixKey: perfix key to search
|
||||
// callback: all keys satisfies perfixKey, and Stauts for this call.
|
||||
KVSTORE_API
|
||||
virtual void GetKeys(const Key &prefixKey, std::function<void(Status, std::vector<Key> &)> callback) = 0;
|
||||
|
||||
// Get value by key from kvstore, key length must be less than 256 and can not be empty.
|
||||
// if key not found in kvstore, KEY_NOT_FOUND will be returned.
|
||||
// otherwise, SUCCESS will be returned and value can be retrieved from the second parameter.
|
||||
// parameters:
|
||||
// key: key specified by client,
|
||||
// value: value stored in kvstore, or empty and KEY_NOT_FOUND returned.
|
||||
KVSTORE_API virtual Status Get(const Key &key, Value &value) = 0;
|
||||
};
|
||||
} // namespace DistributedKv
|
||||
} // namespace OHOS
|
||||
#endif // KVSTORE_SNAPSHOT_H
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user