1 /*
2 * Copyright (c) 2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 #define LOG_TAG "JsDeviceKVStore"
16 #include "js_device_kv_store.h"
17 #include <iomanip>
18 #include "js_kv_store_resultset.h"
19 #include "js_query.h"
20 #include "js_util.h"
21 #include "log_print.h"
22 #include "napi_queue.h"
23 #include "uv_queue.h"
24 #include "distributed_kv_data_manager.h"
25
26 using namespace OHOS::DistributedKv;
27 using namespace OHOS::DataShare;
28 namespace OHOS::DistributedKVStore {
29 constexpr int DEVICEID_WIDTH = 4;
GetDeviceKey(const std::string & deviceId,const std::string & key)30 static std::string GetDeviceKey(const std::string& deviceId, const std::string& key)
31 {
32 std::ostringstream oss;
33 if (!deviceId.empty()) {
34 oss << std::setfill('0') << std::setw(DEVICEID_WIDTH) << deviceId.length() << deviceId;
35 }
36 oss << key;
37 return oss.str();
38 }
39
JsDeviceKVStore(const std::string & storeId)40 JsDeviceKVStore::JsDeviceKVStore(const std::string& storeId)
41 : JsSingleKVStore(storeId)
42 {
43 }
44
Constructor(napi_env env)45 napi_value JsDeviceKVStore::Constructor(napi_env env)
46 {
47 auto lambda = []() -> std::vector<napi_property_descriptor>{
48 std::vector<napi_property_descriptor> properties = {
49 DECLARE_NAPI_FUNCTION("put", JsSingleKVStore::Put),
50 DECLARE_NAPI_FUNCTION("delete", JsSingleKVStore::Delete),
51 DECLARE_NAPI_FUNCTION("putBatch", JsSingleKVStore::PutBatch),
52 DECLARE_NAPI_FUNCTION("deleteBatch", JsSingleKVStore::DeleteBatch),
53 DECLARE_NAPI_FUNCTION("startTransaction", JsSingleKVStore::StartTransaction),
54 DECLARE_NAPI_FUNCTION("commit", JsSingleKVStore::Commit),
55 DECLARE_NAPI_FUNCTION("rollback", JsSingleKVStore::Rollback),
56 DECLARE_NAPI_FUNCTION("enableSync", JsSingleKVStore::EnableSync),
57 DECLARE_NAPI_FUNCTION("setSyncRange", JsSingleKVStore::SetSyncRange),
58 DECLARE_NAPI_FUNCTION("backup", JsSingleKVStore::Backup),
59 DECLARE_NAPI_FUNCTION("restore", JsSingleKVStore::Restore),
60 /* JsDeviceKVStore externs JsSingleKVStore */
61 DECLARE_NAPI_FUNCTION("get", JsDeviceKVStore::Get),
62 DECLARE_NAPI_FUNCTION("getEntries", JsDeviceKVStore::GetEntries),
63 DECLARE_NAPI_FUNCTION("getResultSet", JsDeviceKVStore::GetResultSet),
64 DECLARE_NAPI_FUNCTION("getResultSize", JsDeviceKVStore::GetResultSize),
65 DECLARE_NAPI_FUNCTION("closeResultSet", JsSingleKVStore::CloseResultSet),
66 DECLARE_NAPI_FUNCTION("removeDeviceData", JsSingleKVStore::RemoveDeviceData),
67 DECLARE_NAPI_FUNCTION("sync", JsSingleKVStore::Sync),
68 DECLARE_NAPI_FUNCTION("on", JsSingleKVStore::OnEvent), /* same to JsSingleKVStore */
69 DECLARE_NAPI_FUNCTION("off", JsSingleKVStore::OffEvent) /* same to JsSingleKVStore */
70 };
71 return properties;
72 };
73 return JSUtil::DefineClass(env, "ohos.data.distributedKVStore", "DeviceKVStore", lambda, JsDeviceKVStore::New);
74 }
75
76 /*
77 * [JS API Prototype]
78 * [AsyncCallback]
79 * get(deviceId:string, key:string, callback:AsyncCallback<boolean|string|number|Uint8Array>):void;
80 * [Promise]
81 * get(deviceId:string, key:string):Promise<boolean|string|number|Uint8Array>;
82 */
Get(napi_env env,napi_callback_info info)83 napi_value JsDeviceKVStore::Get(napi_env env, napi_callback_info info)
84 {
85 struct GetContext : public ContextBase {
86 std::string deviceId;
87 std::string key;
88 JSUtil::KvStoreVariant value;
89 };
90 auto ctxt = std::make_shared<GetContext>();
91 auto input = [env, ctxt](size_t argc, napi_value* argv) {
92 // number 2 means: required 2 arguments, <deviceId> + <key>
93 ASSERT_BUSINESS_ERR(ctxt, argc >= 1, Status::INVALID_ARGUMENT, "The number of parameters is incorrect.");
94 if (argc > 1) {
95 ctxt->status = JSUtil::GetValue(env, argv[0], ctxt->deviceId);
96 ASSERT_BUSINESS_ERR(ctxt, ctxt->status == napi_ok, Status::INVALID_ARGUMENT,
97 "The parameter deviceId is incorrect.");
98 }
99 int32_t pos = (argc == 1) ? 0 : 1;
100 ctxt->status = JSUtil::GetValue(env, argv[pos], ctxt->key);
101 ASSERT_BUSINESS_ERR(ctxt, ctxt->status == napi_ok, Status::INVALID_ARGUMENT, "The type of key must be string.");
102 };
103 ctxt->GetCbInfo(env, info, input);
104 ASSERT_NULL(!ctxt->isThrowError, "DeviceGet exits");
105
106 auto execute = [ctxt]() {
107 std::string deviceKey = GetDeviceKey(ctxt->deviceId, ctxt->key);
108 OHOS::DistributedKv::Key key(deviceKey);
109 OHOS::DistributedKv::Value value;
110 auto kvStore = reinterpret_cast<JsDeviceKVStore*>(ctxt->native)->GetKvStorePtr();
111 ASSERT_STATUS(ctxt, "kvStore->result() failed!");
112 bool isSchemaStore = reinterpret_cast<JsDeviceKVStore*>(ctxt->native)->IsSchemaStore();
113 Status status = kvStore->Get(key, value);
114 ZLOGD("kvStore->Get return %{public}d", status);
115 ctxt->value = isSchemaStore ? value.ToString() : JSUtil::Blob2VariantValue(value);
116 ctxt->status = (GenerateNapiError(status, ctxt->jsCode, ctxt->error) == Status::SUCCESS) ?
117 napi_ok : napi_generic_failure;
118 };
119 auto output = [env, ctxt](napi_value& result) {
120 ctxt->status = JSUtil::SetValue(env, ctxt->value, result);
121 ASSERT_STATUS(ctxt, "output failed");
122 };
123 return NapiQueue::AsyncWork(env, ctxt, std::string(__FUNCTION__), execute, output);
124 }
125
126 struct VariantArgs {
127 /* input arguments' combinations */
128 DataQuery dataQuery;
129 std::string errMsg = "";
130 };
131
GetVariantArgs(napi_env env,size_t argc,napi_value * argv,VariantArgs & va)132 static JSUtil::StatusMsg GetVariantArgs(napi_env env, size_t argc, napi_value* argv, VariantArgs& va)
133 {
134 int32_t pos = (argc == 1) ? 0 : 1;
135 napi_valuetype type = napi_undefined;
136 JSUtil::StatusMsg statusMsg = napi_typeof(env, argv[pos], &type);
137 if (statusMsg != napi_ok || (type != napi_string && type != napi_object)) {
138 va.errMsg = "The type of parameters keyPrefix/query is incorrect.";
139 return statusMsg != napi_ok ? statusMsg.status : napi_invalid_arg;
140 }
141 if (type == napi_string) {
142 std::string keyPrefix;
143 statusMsg = JSUtil::GetValue(env, argv[pos], keyPrefix);
144 if (keyPrefix.empty()) {
145 va.errMsg = "The type of parameters keyPrefix is incorrect.";
146 return napi_invalid_arg;
147 }
148 va.dataQuery.KeyPrefix(keyPrefix);
149 } else {
150 bool result = false;
151 statusMsg = napi_instanceof(env, argv[pos], JsQuery::Constructor(env), &result);
152 if ((statusMsg.status == napi_ok) && (result != false)) {
153 JsQuery *jsQuery = nullptr;
154 statusMsg = JSUtil::Unwrap(env, argv[pos], reinterpret_cast<void **>(&jsQuery), JsQuery::Constructor(env));
155 if (jsQuery == nullptr) {
156 va.errMsg = "The parameters query is incorrect.";
157 return napi_invalid_arg;
158 }
159 va.dataQuery = jsQuery->GetDataQuery();
160 } else {
161 statusMsg = JSUtil::GetValue(env, argv[pos], va.dataQuery);
162 ZLOGD("kvStoreDataShare->GetResultSet return %{public}d", statusMsg.status);
163 statusMsg.jsApiType = JSUtil::DATASHARE;
164 }
165 }
166 std::string deviceId;
167 if (argc > 1) {
168 JSUtil::GetValue(env, argv[0], deviceId);
169 va.dataQuery.DeviceId(deviceId);
170 }
171 return statusMsg;
172 };
173
174 /*
175 * [JS API Prototype]
176 * getEntries(deviceId:string, keyPrefix:string, callback:AsyncCallback<Entry[]>):void
177 * getEntries(deviceId:string, keyPrefix:string):Promise<Entry[]>
178 *
179 * getEntries(query:Query, callback:AsyncCallback<Entry[]>):void
180 * getEntries(query:Query) : Promise<Entry[]>
181 *
182 * getEntries(deviceId:string, query:Query):callback:AsyncCallback<Entry[]>):void
183 * getEntries(deviceId:string, query:Query):Promise<Entry[]>
184 */
GetEntries(napi_env env,napi_callback_info info)185 napi_value JsDeviceKVStore::GetEntries(napi_env env, napi_callback_info info)
186 {
187 struct GetEntriesContext : public ContextBase {
188 VariantArgs va;
189 std::vector<Entry> entries;
190 };
191 auto ctxt = std::make_shared<GetEntriesContext>();
192 auto input = [env, ctxt](size_t argc, napi_value* argv) {
193 ASSERT_BUSINESS_ERR(ctxt, argc >= 1, Status::INVALID_ARGUMENT, "The number of parameters is incorrect.");
194 ctxt->status = GetVariantArgs(env, argc, argv, ctxt->va);
195 ASSERT_BUSINESS_ERR(ctxt, ctxt->status == napi_ok, Status::INVALID_ARGUMENT, ctxt->va.errMsg);
196 };
197 ctxt->GetCbInfo(env, info, input);
198 ASSERT_NULL(!ctxt->isThrowError, "GetEntries exit");
199
200 auto execute = [ctxt]() {
201 auto kvStore = reinterpret_cast<JsDeviceKVStore*>(ctxt->native)->GetKvStorePtr();
202 Status status = kvStore->GetEntries(ctxt->va.dataQuery, ctxt->entries);
203 ZLOGD("kvStore->GetEntries() return %{public}d", status);
204 ctxt->status = (GenerateNapiError(status, ctxt->jsCode, ctxt->error) == Status::SUCCESS) ?
205 napi_ok : napi_generic_failure;
206 };
207 auto output = [env, ctxt](napi_value& result) {
208 auto isSchemaStore = reinterpret_cast<JsDeviceKVStore*>(ctxt->native)->IsSchemaStore();
209 ctxt->status = JSUtil::SetValue(env, ctxt->entries, result, isSchemaStore);
210 ASSERT_STATUS(ctxt, "output failed!");
211 };
212 return NapiQueue::AsyncWork(env, ctxt, std::string(__FUNCTION__), execute, output);
213 }
214
215 /*
216 * [JS API Prototype]
217 * getResultSet(deviceId:string, keyPrefix:string, callback:AsyncCallback<KvStoreResultSet>):void
218 * getResultSet(deviceId:string, keyPrefix:string):Promise<KvStoreResultSet>
219 *
220 * getResultSet(query:Query, callback:AsyncCallback<KvStoreResultSet>):void
221 * getResultSet(query:Query):Promise<KvStoreResultSet>
222 *
223 * getResultSet(deviceId:string, query:Query, callback:AsyncCallback<KvStoreResultSet>):void
224 * getResultSet(deviceId:string, query:Query):Promise<KvStoreResultSet>
225 */
GetResultSet(napi_env env,napi_callback_info info)226 napi_value JsDeviceKVStore::GetResultSet(napi_env env, napi_callback_info info)
227 {
228 struct GetResultSetContext : public ContextBase {
229 VariantArgs va;
230 JsKVStoreResultSet* resultSet = nullptr;
231 napi_ref ref = nullptr;
232 };
233 auto ctxt = std::make_shared<GetResultSetContext>();
234 auto input = [env, ctxt](size_t argc, napi_value* argv) {
235 ASSERT_BUSINESS_ERR(ctxt, argc >= 1, Status::INVALID_ARGUMENT, "The number of parameters is incorrect.");
236 JSUtil::StatusMsg statusMsg = GetVariantArgs(env, argc, argv, ctxt->va);
237 ctxt->status = statusMsg.status;
238 ASSERT_BUSINESS_ERR(ctxt, ctxt->status == napi_ok, Status::INVALID_ARGUMENT, ctxt->va.errMsg);
239 ASSERT_PERMISSION_ERR(ctxt,
240 !JSUtil::IsSystemApi(statusMsg.jsApiType) ||
241 reinterpret_cast<JsSingleKVStore *>(ctxt->native)->IsSystemApp(), Status::PERMISSION_DENIED, "");
242 ctxt->ref = JSUtil::NewWithRef(env, 0, nullptr, reinterpret_cast<void **>(&ctxt->resultSet),
243 JsKVStoreResultSet::Constructor(env));
244 ASSERT_BUSINESS_ERR(ctxt, ctxt->resultSet != nullptr, Status::INVALID_ARGUMENT,
245 "KVStoreResultSet::New failed!");
246 };
247 ctxt->GetCbInfo(env, info, input);
248 ASSERT_NULL(!ctxt->isThrowError, "GetResultSet exit");
249
250 auto execute = [ctxt]() {
251 std::shared_ptr<KvStoreResultSet> kvResultSet;
252 auto kvStore = reinterpret_cast<JsDeviceKVStore*>(ctxt->native)->GetKvStorePtr();
253 Status status = kvStore->GetResultSet(ctxt->va.dataQuery, kvResultSet);
254 ZLOGD("kvStore->GetResultSet() return %{public}d", status);
255 ctxt->status = (GenerateNapiError(status, ctxt->jsCode, ctxt->error) == Status::SUCCESS) ?
256 napi_ok : napi_generic_failure;
257 ctxt->resultSet->SetKvStoreResultSetPtr(kvResultSet);
258 bool isSchema = reinterpret_cast<JsDeviceKVStore*>(ctxt->native)->IsSchemaStore();
259 ctxt->resultSet->SetSchema(isSchema);
260 };
261 auto output = [env, ctxt](napi_value& result) {
262 ctxt->status = napi_get_reference_value(env, ctxt->ref, &result);
263 napi_delete_reference(env, ctxt->ref);
264 ASSERT_STATUS(ctxt, "output KvResultSet failed");
265 };
266 return NapiQueue::AsyncWork(env, ctxt, std::string(__FUNCTION__), execute, output);
267 }
268
269 /*
270 * [JS API Prototype]
271 * getResultSize(query:Query, callback: AsyncCallback<number>):void
272 * getResultSize(query:Query):Promise<number>
273 *
274 * getResultSize(deviceId:string, query:Query, callback: AsyncCallback<number>):void
275 * getResultSize(deviceId:string, query:Query):Promise<number>
276 */
GetResultSize(napi_env env,napi_callback_info info)277 napi_value JsDeviceKVStore::GetResultSize(napi_env env, napi_callback_info info)
278 {
279 struct ResultSizeContext : public ContextBase {
280 VariantArgs va;
281 int resultSize = 0;
282 };
283 auto ctxt = std::make_shared<ResultSizeContext>();
284 auto input = [env, ctxt](size_t argc, napi_value* argv) {
285 ASSERT_BUSINESS_ERR(ctxt, argc >= 1, Status::INVALID_ARGUMENT, "The number of parameters is incorrect.");
286 ctxt->status = GetVariantArgs(env, argc, argv, ctxt->va);
287 ASSERT_BUSINESS_ERR(ctxt, ctxt->status != napi_invalid_arg, Status::INVALID_ARGUMENT, ctxt->va.errMsg);
288 };
289
290 ctxt->GetCbInfo(env, info, input);
291 ASSERT_NULL(!ctxt->isThrowError, "GetResultSize exit");
292
293 auto execute = [ctxt]() {
294 auto kvStore = reinterpret_cast<JsDeviceKVStore*>(ctxt->native)->GetKvStorePtr();
295 Status status = kvStore->GetCount(ctxt->va.dataQuery, ctxt->resultSize);
296 ZLOGD("kvStore->GetCount() return %{public}d", status);
297 ctxt->status = (GenerateNapiError(status, ctxt->jsCode, ctxt->error) == Status::SUCCESS) ?
298 napi_ok : napi_generic_failure;
299 };
300 auto output = [env, ctxt](napi_value& result) {
301 ctxt->status = JSUtil::SetValue(env, static_cast<int32_t>(ctxt->resultSize), result);
302 ASSERT_STATUS(ctxt, "output resultSize failed!");
303 };
304 return NapiQueue::AsyncWork(env, ctxt, std::string(__FUNCTION__), execute, output);
305 }
306
New(napi_env env,napi_callback_info info)307 napi_value JsDeviceKVStore::New(napi_env env, napi_callback_info info)
308 {
309 ZLOGD("Constructor single kv store!");
310 std::string storeId;
311 auto ctxt = std::make_shared<ContextBase>();
312 auto input = [env, ctxt, &storeId](size_t argc, napi_value* argv) {
313 // required 2 arguments :: <storeId> <options>
314 ASSERT_BUSINESS_ERR(ctxt, argc >= 2, Status::INVALID_ARGUMENT, "The number of parameters is incorrect.");
315 ctxt->status = JSUtil::GetValue(env, argv[0], storeId);
316 ASSERT_BUSINESS_ERR(ctxt, (ctxt->status == napi_ok) && !storeId.empty(), Status::INVALID_ARGUMENT,
317 "The type of storeId must be string.");
318 };
319 ctxt->GetCbInfoSync(env, info, input);
320 ASSERT_NULL(!ctxt->isThrowError, "New JsDeviceKVStore exit");
321
322 JsDeviceKVStore* kvStore = new (std::nothrow) JsDeviceKVStore(storeId);
323 ASSERT_ERR(env, kvStore != nullptr, Status::INVALID_ARGUMENT, "no memory for kvStore");
324
325 auto finalize = [](napi_env env, void* data, void* hint) {
326 ZLOGI("deviceKvStore finalize.");
327 auto* kvStore = reinterpret_cast<JsDeviceKVStore*>(data);
328 ASSERT_VOID(kvStore != nullptr, "kvStore is null!");
329 delete kvStore;
330 };
331 ASSERT_CALL(env, napi_wrap(env, ctxt->self, kvStore, finalize, nullptr, nullptr), kvStore);
332 return ctxt->self;
333 }
334 } // namespace OHOS::DistributedKVStore
335