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
16 #include "napi_queue.h"
17
18 #include "js_common.h"
19 #include "logger.h"
20
21 namespace OHOS::ObjectStore {
~ContextBase()22 ContextBase::~ContextBase()
23 {
24 LOG_DEBUG("no memory leak after callback or promise[resolved/rejected]");
25 if (env != nullptr) {
26 if (work != nullptr) {
27 napi_delete_async_work(env, work);
28 }
29 if (callbackRef != nullptr) {
30 napi_delete_reference(env, callbackRef);
31 }
32 napi_delete_reference(env, selfRef);
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 INVALID_STATUS_RETURN_ERROR(this, "napi_get_cb_info failed!");
44 INVALID_ARGS_RETURN_ERROR(this, argc <= ARGC_MAX, "too many arguments!", std::make_shared<InnerError>());
45 INVALID_ARGS_RETURN_ERROR(this, self != nullptr, "no JavaScript this argument!", std::make_shared<InnerError>());
46 napi_create_reference(env, self, 1, &selfRef);
47 status = napi_unwrap(env, self, &native);
48 INVALID_STATUS_RETURN_ERROR(this, "self unwrap failed!");
49
50 if (!sync && (argc > 0)) {
51 // get the last arguments :: <callback>
52 size_t index = argc - 1;
53 napi_valuetype type = napi_undefined;
54 napi_status tyst = napi_typeof(env, argv[index], &type);
55 if ((tyst == napi_ok) && (type == napi_function)) {
56 status = napi_create_reference(env, argv[index], 1, &callbackRef);
57 INVALID_STATUS_RETURN_ERROR(this, "ref callback failed!");
58 argc = index;
59 LOG_DEBUG("async callback, no promise");
60 } else {
61 INVALID_ARGS_RETURN_ERROR(this, type == napi_undefined, "arguments error!",
62 std::make_shared<ParametersType>("callback", "function"));
63 LOG_DEBUG("no callback, async promise");
64 }
65 }
66
67 if (parse) {
68 parse(argc, argv);
69 } else {
70 INVALID_ARGS_RETURN_ERROR(this, argc == 0, "required no arguments!", std::make_shared<InnerError>());
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 LOG_DEBUG("name=%{public}s", name.c_str());
78
79 napi_value promise = nullptr;
80 if (ctxt->callbackRef == nullptr) {
81 napi_create_promise(ctxt->env, &ctxt->deferred, &promise);
82 LOG_DEBUG("create deferred promise");
83 } else {
84 napi_get_undefined(ctxt->env, &promise);
85 }
86
87 napi_value resource = nullptr;
88 napi_create_string_utf8(ctxt->env, name.c_str(), NAPI_AUTO_LENGTH, &resource);
89 napi_create_async_work(
90 ctxt->env, nullptr, resource,
91 [](napi_env env, void* data) {
92 NOT_MATCH_RETURN_VOID(data != nullptr);
93 auto ctxt = reinterpret_cast<ContextBase*>(data);
94 LOG_DEBUG("napi_async_execute_callback ctxt->status=%{public}d", ctxt->status);
95 if (ctxt->execute && ctxt->status == napi_ok) {
96 ctxt->execute();
97 }
98 },
99 [](napi_env env, napi_status status, void* data) {
100 NOT_MATCH_RETURN_VOID(data != nullptr);
101 auto ctxt = reinterpret_cast<ContextBase*>(data);
102 LOG_DEBUG("napi_async_complete_callback status=%{public}d, ctxt->status=%{public}d", status, ctxt->status);
103 if ((status != napi_ok) && (ctxt->status == napi_ok)) {
104 ctxt->status = status;
105 }
106 if ((ctxt->complete) && (status == napi_ok) && (ctxt->status == napi_ok)) {
107 ctxt->complete(ctxt->output);
108 }
109 GenerateOutput(ctxt);
110 },
111 reinterpret_cast<void*>(ctxt.get()), &ctxt->work);
112 ctxt->execute = std::move(execute);
113 ctxt->complete = std::move(complete);
114 ctxt->hold = ctxt; // save crossing-thread ctxt.
115 auto status = napi_queue_async_work_with_qos(ctxt->env, ctxt->work, napi_qos_user_initiated);
116 if (status != napi_ok) {
117 napi_get_undefined(ctxt->env, &promise);
118 }
119 return promise;
120 }
121
SetBusinessError(napi_env env, napi_value *businessError, std::shared_ptr<Error> error)122 void NapiQueue::SetBusinessError(napi_env env, napi_value *businessError, std::shared_ptr<Error> error)
123 {
124 napi_create_object(env, businessError);
125 if (error != nullptr && error->GetCode() != EXCEPTION_INNER) {
126 napi_value code = nullptr;
127 napi_value msg = nullptr;
128 napi_create_int32(env, error->GetCode(), &code);
129 napi_create_string_utf8(env, error->GetMessage().c_str(), NAPI_AUTO_LENGTH, &msg);
130 napi_set_named_property(env, *businessError, "code", code);
131 napi_set_named_property(env, *businessError, "message", msg);
132 }
133 }
134
GenerateOutput(ContextBase *ctxt)135 void NapiQueue::GenerateOutput(ContextBase *ctxt)
136 {
137 napi_value result[RESULT_ALL] = { nullptr };
138 if (ctxt->status == napi_ok) {
139 napi_get_undefined(ctxt->env, &result[RESULT_ERROR]);
140 if (ctxt->output == nullptr) {
141 napi_get_undefined(ctxt->env, &ctxt->output);
142 }
143 result[RESULT_DATA] = ctxt->output;
144 } else {
145 napi_value businessError = nullptr;
146 SetBusinessError(ctxt->env, &businessError, ctxt->error);
147 result[RESULT_ERROR] = businessError;
148 napi_get_undefined(ctxt->env, &result[RESULT_DATA]);
149 }
150 if (ctxt->deferred != nullptr) {
151 if (ctxt->status == napi_ok) {
152 LOG_DEBUG("deferred promise resolved");
153 napi_resolve_deferred(ctxt->env, ctxt->deferred, result[RESULT_DATA]);
154 } else {
155 LOG_DEBUG("deferred promise rejected");
156 napi_reject_deferred(ctxt->env, ctxt->deferred, result[RESULT_ERROR]);
157 }
158 } else {
159 napi_value callback = nullptr;
160 napi_get_reference_value(ctxt->env, ctxt->callbackRef, &callback);
161 napi_value callbackResult = nullptr;
162 LOG_DEBUG("call callback function");
163 napi_call_function(ctxt->env, nullptr, callback, RESULT_ALL, result, &callbackResult);
164 }
165 ctxt->execute = nullptr;
166 ctxt->complete = nullptr;
167 ctxt->hold.reset(); // release ctxt.
168 }
169 } // namespace OHOS::DistributedData
170