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 "NapiQueue"
16 #include "napi_queue.h"
17
18 using namespace OHOS::DistributedKv;
19
20 namespace OHOS::DistributedData {
~ContextBase()21 ContextBase::~ContextBase()
22 {
23 ZLOGD("No memory leak after callback or promise[resolved/rejected]");
24 if (env != nullptr) {
25 if (callbackRef != nullptr) {
26 auto status = napi_delete_reference(env, callbackRef);
27 ZLOGD("status:%{public}d", status);
28 }
29 if (selfRef != nullptr) {
30 auto status = napi_delete_reference(env, selfRef);
31 ZLOGD("status:%{public}d", status);
32 }
33 env = nullptr;
34 }
35 }
36
GetCbInfo(napi_env envi,napi_callback_info info,NapiCbInfoParser parse,bool sync)37 void ContextBase::GetCbInfo(napi_env envi, napi_callback_info info, NapiCbInfoParser parse, bool sync)
38 {
39 env = envi;
40 size_t argc = ARGC_MAX;
41 napi_value argv[ARGC_MAX] = { nullptr };
42 status = napi_get_cb_info(env, info, &argc, argv, &self, nullptr);
43 CHECK_STATUS_RETURN_VOID(this, "napi_get_cb_info failed!");
44 CHECK_ARGS_RETURN_VOID(this, argc <= ARGC_MAX, "too many arguments!");
45 CHECK_ARGS_RETURN_VOID(this, self != nullptr, "no JavaScript this argument!");
46 if (!sync) {
47 napi_create_reference(env, self, 1, &selfRef);
48 }
49 status = napi_unwrap(env, self, &native);
50 CHECK_STATUS_RETURN_VOID(this, "self unwrap failed!");
51
52 if (!sync && (argc > 0)) {
53 // get the last arguments :: <callback>
54 size_t index = argc - 1;
55 napi_valuetype type = napi_undefined;
56 napi_status tyst = napi_typeof(env, argv[index], &type);
57 if ((tyst == napi_ok) && (type == napi_function)) {
58 status = napi_create_reference(env, argv[index], 1, &callbackRef);
59 CHECK_STATUS_RETURN_VOID(this, "ref callback failed!");
60 argc = index;
61 ZLOGD("Async callback, no promise");
62 } else {
63 ZLOGD("No callback, async pormose");
64 }
65 }
66
67 if (parse) {
68 parse(argc, argv);
69 } else {
70 CHECK_ARGS_RETURN_VOID(this, argc == 0, "required no arguments!");
71 }
72 }
73
AsyncWork(napi_env env,std::shared_ptr<ContextBase> ctxt,const std::string & name,NapiAsyncExecute execute,NapiAsyncComplete complete)74 napi_value NapiQueue::AsyncWork(napi_env env, std::shared_ptr<ContextBase> ctxt, const std::string& name,
75 NapiAsyncExecute execute, NapiAsyncComplete complete)
76 {
77 ZLOGD("name=%{public}s", name.c_str());
78 AsyncContext *aCtx = new AsyncContext;
79 aCtx->env = env;
80 aCtx->ctx = std::move(ctxt);
81 aCtx->execute = std::move(execute);
82 aCtx->complete = std::move(complete);
83 napi_value promise = nullptr;
84 if (aCtx->ctx->callbackRef == nullptr) {
85 if (napi_create_promise(env, &aCtx->deferred, &promise) != napi_ok) {
86 ZLOGE("Create deferred promise fail");
87 delete aCtx;
88 return nullptr;
89 }
90 } else {
91 napi_get_undefined(env, &promise);
92 }
93
94 napi_value resource = nullptr;
95 napi_create_string_utf8(env, name.c_str(), NAPI_AUTO_LENGTH, &resource);
96 napi_create_async_work(env, nullptr, resource, [](napi_env env, void* data) {
97 CHECK_RETURN_VOID(data != nullptr, "napi_async_execute_callback nullptr");
98 auto actx = reinterpret_cast<AsyncContext*>(data);
99 ZLOGD("napi_async_execute_callback ctxt->status=%{public}d", actx->ctx->status);
100 if (actx->execute && actx->ctx->status == napi_ok) {
101 actx->execute();
102 }
103 },
104 [](napi_env env, napi_status status, void* data) {
105 CHECK_RETURN_VOID(data != nullptr, "napi_async_complete_callback nullptr");
106 auto actx = reinterpret_cast<AsyncContext*>(data);
107 ZLOGD("napi_async_complete_callback status=%{public}d, ctxt->status=%{public}d", status, actx->ctx->status);
108 if ((status != napi_ok) && (actx->ctx->status == napi_ok)) {
109 actx->ctx->status = status;
110 }
111 napi_value output = nullptr;
112 if ((actx->complete) && (status == napi_ok) && (actx->ctx->status == napi_ok)) {
113 actx->complete(output);
114 }
115 GenerateOutput(*actx, output);
116 delete actx;
117 },
118 reinterpret_cast<void*>(aCtx), &aCtx->work);
119 auto status = napi_queue_async_work_with_qos(env, aCtx->work, napi_qos_user_initiated);
120 if (status != napi_ok) {
121 napi_get_undefined(env, &promise);
122 delete aCtx;
123 }
124 return promise;
125 }
126
GenerateOutput(AsyncContext & ctx,napi_value output)127 void NapiQueue::GenerateOutput(AsyncContext &ctx, napi_value output)
128 {
129 napi_value result[RESULT_ALL] = { nullptr };
130 if (ctx.ctx->status == napi_ok) {
131 napi_get_undefined(ctx.env, &result[RESULT_ERROR]);
132 if (output == nullptr) {
133 napi_get_undefined(ctx.env, &output);
134 }
135 result[RESULT_DATA] = output;
136 } else {
137 napi_value message = nullptr;
138 napi_create_string_utf8(ctx.env, ctx.ctx->error.c_str(), NAPI_AUTO_LENGTH, &message);
139 napi_create_error(ctx.env, nullptr, message, &result[RESULT_ERROR]);
140 napi_get_undefined(ctx.env, &result[RESULT_DATA]);
141 }
142 if (ctx.deferred != nullptr) {
143 if (ctx.ctx->status == napi_ok) {
144 ZLOGD("deferred promise resolved");
145 napi_resolve_deferred(ctx.env, ctx.deferred, result[RESULT_DATA]);
146 } else {
147 ZLOGD("deferred promise rejected");
148 napi_reject_deferred(ctx.env, ctx.deferred, result[RESULT_ERROR]);
149 }
150 } else {
151 napi_value callback = nullptr;
152 napi_get_reference_value(ctx.env, ctx.ctx->callbackRef, &callback);
153 napi_value callbackResult = nullptr;
154 ZLOGD("Call callback function");
155 napi_call_function(ctx.env, nullptr, callback, RESULT_ALL, result, &callbackResult);
156 }
157 }
158 } // namespace OHOS::DistributedData