1 /*
2  * Copyright (c) 2023 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 "NapiQueue"
16 #include "napi_queue.h"
17 
18 namespace OHOS {
19 namespace UDMF {
~ContextBase()20 ContextBase::~ContextBase()
21 {
22     LOG_DEBUG(UDMF_KITS_NAPI, "no memory leak after callback or promise[resolved/rejected]");
23     if (env != nullptr) {
24         napi_delete_reference(env, selfRef);
25         env = nullptr;
26     }
27 }
28 
GetCbInfo(napi_env envi,napi_callback_info info,NapiCbInfoParser parse,bool sync)29 void ContextBase::GetCbInfo(napi_env envi, napi_callback_info info, NapiCbInfoParser parse, bool sync)
30 {
31     env = envi;
32     size_t argc = ARGC_MAX;
33     napi_value argv[ARGC_MAX] = { nullptr };
34     status = napi_get_cb_info(env, info, &argc, argv, &self, nullptr);
35     ASSERT_STATUS(this, "napi_get_cb_info failed!");
36     ASSERT_ARGS(this, argc <= ARGC_MAX, "too many arguments!");
37     ASSERT_ARGS(this, self != nullptr, "no JavaScript this argument!");
38     if (!sync) {
39         napi_create_reference(env, self, 1, &selfRef);
40     }
41     status = napi_unwrap(env, self, &native);
42     ASSERT_STATUS(this, "self unwrap failed!");
43 
44     if (!sync && (argc > 0)) {
45         // get the last arguments :: <callback>
46         size_t index = argc - 1;
47         napi_valuetype type = napi_undefined;
48         napi_status tyst = napi_typeof(env, argv[index], &type);
49         if ((tyst == napi_ok) && (type == napi_function)) {
50             status = napi_create_reference(env, argv[index], 1, &callbackRef);
51             ASSERT_STATUS(this, "ref callback failed!");
52             argc = index;
53             LOG_DEBUG(UDMF_KITS_NAPI, "async callback, no promise");
54         } else {
55             LOG_DEBUG(UDMF_KITS_NAPI, "no callback, async pormose");
56         }
57     }
58 
59     if (parse) {
60         parse(argc, argv);
61     } else {
62         ASSERT_ARGS(this, argc == 0, "required no arguments!");
63     }
64 }
65 
AsyncWork(napi_env env,std::shared_ptr<ContextBase> contextBase,const std::string & name,NapiAsyncExecute execute,NapiAsyncComplete complete)66 napi_value NapiQueue::AsyncWork(napi_env env, std::shared_ptr<ContextBase> contextBase, const std::string &name,
67     NapiAsyncExecute execute, NapiAsyncComplete complete)
68 {
69     LOG_DEBUG(UDMF_KITS_NAPI, "NapiQueue::AsyncWork name = %{public}s", name.c_str());
70     AsyncContext *aCtx = new AsyncContext;
71     aCtx->ctxt = std::move(contextBase);
72     aCtx->execute = std::move(execute);
73     aCtx->complete = std::move(complete);
74     LOG_DEBUG(UDMF_KITS_NAPI, "NapiQueue::AsyncWork move func finish");
75     auto ctxt = aCtx->ctxt;
76     napi_value promise = nullptr;
77     if (ctxt->callbackRef == nullptr) {
78         LOG_DEBUG(UDMF_KITS_NAPI, "NapiQueue::AsyncWork has promise");
79         napi_create_promise(ctxt->env, &ctxt->deferred, &promise);
80         LOG_DEBUG(UDMF_KITS_NAPI, "create deferred promise");
81     } else {
82         LOG_DEBUG(UDMF_KITS_NAPI, "NapiQueue::AsyncWork no promise");
83         napi_get_undefined(ctxt->env, &promise);
84     }
85     napi_value resource = nullptr;
86     LOG_DEBUG(UDMF_KITS_NAPI, "NapiQueue::AsyncWork create string start");
87     napi_create_string_utf8(ctxt->env, name.c_str(), NAPI_AUTO_LENGTH, &resource);
88     LOG_DEBUG(UDMF_KITS_NAPI, "NapiQueue::AsyncWork create string finish");
89     napi_create_async_work(ctxt->env, nullptr, resource, onExecute, onComplete, reinterpret_cast<void *>(aCtx),
90         &aCtx->work);
91     auto status = napi_queue_async_work(ctxt->env, aCtx->work);
92     if (status != napi_ok) {
93         LOG_ERROR(UDMF_KITS_NAPI, "async work failed: %{public}d", status);
94         napi_get_undefined(env, &promise);
95         delete aCtx;
96     }
97     return promise;
98 }
99 
GenerateOutput(ContextBase * ctxt)100 void NapiQueue::GenerateOutput(ContextBase *ctxt)
101 {
102     LOG_DEBUG(UDMF_KITS_NAPI, "GenerateOutput start");
103     napi_value result[RESULT_ALL] = { nullptr };
104     LOG_DEBUG(UDMF_KITS_NAPI, "GenerateOutput ctxt->status = %{public}d", ctxt->status);
105     if (ctxt->status == napi_ok) {
106         napi_get_undefined(ctxt->env, &result[RESULT_ERROR]);
107         if (ctxt->output == nullptr) {
108             napi_get_undefined(ctxt->env, &ctxt->output);
109         }
110         result[RESULT_DATA] = ctxt->output;
111     } else {
112         napi_value code = nullptr;
113         napi_value message = nullptr;
114         if (ctxt->jsCode != 0 && ctxt->jsCode != -1) {
115             napi_create_string_utf8(ctxt->env, std::to_string(ctxt->jsCode).c_str(), NAPI_AUTO_LENGTH, &code);
116         }
117         if (ctxt->jsCode == -1) {
118             std::string jsCode;
119             napi_create_string_utf8(ctxt->env, jsCode.c_str(), NAPI_AUTO_LENGTH, &code);
120         }
121         napi_create_string_utf8(ctxt->env, ctxt->error.c_str(), NAPI_AUTO_LENGTH, &message);
122         napi_create_error(ctxt->env, code, message, &result[RESULT_ERROR]);
123         napi_get_undefined(ctxt->env, &result[RESULT_DATA]);
124     }
125     if (ctxt->deferred != nullptr) {
126         LOG_DEBUG(UDMF_KITS_NAPI, "GenerateOutput deferred branch");
127         if (ctxt->status == napi_ok) {
128             LOG_DEBUG(UDMF_KITS_NAPI, "deferred promise resolved");
129             napi_resolve_deferred(ctxt->env, ctxt->deferred, result[RESULT_DATA]);
130         } else {
131             LOG_DEBUG(UDMF_KITS_NAPI, "deferred promise rejected");
132             napi_reject_deferred(ctxt->env, ctxt->deferred, result[RESULT_ERROR]);
133         }
134     } else {
135         napi_value callback = nullptr;
136         napi_get_reference_value(ctxt->env, ctxt->callbackRef, &callback);
137         napi_value callbackResult = nullptr;
138         LOG_INFO(UDMF_KITS_NAPI, "GenerateOutput call callback function");
139         LOG_DEBUG(UDMF_KITS_NAPI, "call callback function");
140         napi_call_function(ctxt->env, nullptr, callback, RESULT_ALL, result, &callbackResult);
141     }
142     LOG_DEBUG(UDMF_KITS_NAPI, "GenerateOutput stop");
143 }
144 
onExecute(napi_env env,void * data)145 void NapiQueue::onExecute(napi_env env, void *data)
146 {
147     LOG_DEBUG(UDMF_KITS_NAPI, "NapiQueue::AsyncWork start execute");
148     ASSERT_VOID(data != nullptr, "no data");
149     auto actxt = reinterpret_cast<AsyncContext *>(data);
150     LOG_DEBUG(UDMF_KITS_NAPI, "napi_async_execute_callback ctxt->status = %{public}d", actxt->ctxt->status);
151     if (actxt->execute && actxt->ctxt->status == napi_ok) {
152         LOG_DEBUG(UDMF_KITS_NAPI, "NapiQueue::AsyncWork do user design execute");
153         actxt->execute();
154     }
155     LOG_DEBUG(UDMF_KITS_NAPI, "NapiQueue::AsyncWork finish execute");
156 }
157 
onComplete(napi_env env,napi_status status,void * data)158 void NapiQueue::onComplete(napi_env env, napi_status status, void *data)
159 {
160     LOG_DEBUG(UDMF_KITS_NAPI, "NapiQueue::AsyncWork start output");
161     ASSERT_VOID(data != nullptr, "no data");
162     auto actxt = reinterpret_cast<AsyncContext *>(data);
163     LOG_DEBUG(UDMF_KITS_NAPI, "napi_async_complete_callback status = %{public}d, ctxt->status = %{public}d", status,
164         actxt->ctxt->status);
165     if ((status != napi_ok) && (actxt->ctxt->status == napi_ok)) {
166         LOG_DEBUG(UDMF_KITS_NAPI, "NapiQueue::AsyncWork check status");
167         actxt->ctxt->status = status;
168     }
169     if ((actxt->complete) && (status == napi_ok) && (actxt->ctxt->status == napi_ok)) {
170         LOG_DEBUG(UDMF_KITS_NAPI, "NapiQueue::AsyncWork do user design output");
171         actxt->complete(actxt->ctxt->output);
172     }
173     GenerateOutput(actxt->ctxt.get());
174     LOG_DEBUG(UDMF_KITS_NAPI, "NapiQueue::AsyncWork finish output");
175     napi_delete_reference(env, actxt->ctxt->callbackRef);
176     napi_delete_async_work(env, actxt->work);
177     delete actxt;
178 }
179 } // namespace UDMF
180 } // namespace OHOS
181