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 #include "uv_queue.h"
16
17 #include <memory>
18
19 #include "js_logger.h"
20
21 namespace OHOS::PreferencesJsKit {
22 constexpr size_t MAX_CALLBACK_ARG_NUM = 6;
UvQueue(napi_env env)23 UvQueue::UvQueue(napi_env env)
24 : env_(env)
25 {
26 if (env != nullptr) {
27 napi_get_uv_event_loop(env, &loop_);
28 }
29 }
30
~UvQueue()31 UvQueue::~UvQueue()
32 {
33 LOG_DEBUG("no memory leak for queue-callback");
34 env_ = nullptr;
35 }
36
AsyncCall(NapiCallbackGetter getter,NapiArgsGenerator genArgs)37 void UvQueue::AsyncCall(NapiCallbackGetter getter, NapiArgsGenerator genArgs)
38 {
39 if (loop_ == nullptr || !getter) {
40 LOG_ERROR("loop_ or callback is nullptr");
41 return;
42 }
43
44 uv_work_t* work = new (std::nothrow) uv_work_t;
45 if (work == nullptr) {
46 LOG_ERROR("no memory for uv_work_t");
47 return;
48 }
49 work->data = new UvEntry{ env_, getter, std::move(genArgs) };
50 uv_queue_work(
51 loop_, work, [](uv_work_t* work) {},
52 [](uv_work_t* work, int uvstatus) {
53 std::shared_ptr<UvEntry> entry(static_cast<UvEntry *>(work->data), [work](UvEntry *data) {
54 delete data;
55 delete work;
56 });
57 napi_handle_scope scope = nullptr;
58 napi_open_handle_scope(entry->env, &scope);
59 if (scope == nullptr) {
60 return;
61 }
62 napi_value method = entry->callback(entry->env);
63 if (method == nullptr) {
64 LOG_ERROR("the callback is invalid, maybe is cleared!");
65 napi_close_handle_scope(entry->env, scope);
66 return ;
67 }
68 int argc = 0;
69 napi_value argv[MAX_CALLBACK_ARG_NUM] = { nullptr };
70 if (entry->args) {
71 argc = MAX_CALLBACK_ARG_NUM;
72 entry->args(entry->env, argc, argv);
73 }
74 LOG_DEBUG("queue uv_after_work_cb");
75 napi_value global = nullptr;
76 napi_get_global(entry->env, &global);
77 napi_value result;
78 napi_status status = napi_call_function(entry->env, global, method, argc, argv, &result);
79 if (status != napi_ok) {
80 LOG_ERROR("notify data change failed status:%{public}d.", status);
81 }
82 napi_close_handle_scope(entry->env, scope);
83 });
84 }
85
GetEnv()86 napi_env UvQueue::GetEnv()
87 {
88 return env_;
89 }
90 } // namespace OHOS::DistributedKVStore
91