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