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 "napi_queue.h"
16 #include "logger.h"
17 #include "js_common.h"
18
19 namespace OHOS::ObjectStore {
~ContextBase()20 ContextBase::~ContextBase()
21 {
22 LOG_DEBUG("no memory leak after callback or promise[resolved/rejected]");
23 if (env != nullptr) {
24 if (work != nullptr) {
25 napi_delete_async_work(env, work);
26 }
27 if (callbackRef != nullptr) {
28 napi_delete_reference(env, callbackRef);
29 }
30 napi_delete_reference(env, selfRef);
31 env = nullptr;
32 }
33 }
34
GetCbInfo(napi_env envi,napi_callback_info info,NapiCbInfoParser parse,bool sync)35 void ContextBase::GetCbInfo(napi_env envi, napi_callback_info info, NapiCbInfoParser parse, bool sync)
36 {
37 env = envi;
38 size_t argc = ARGC_MAX;
39 napi_value argv[ARGC_MAX] = { nullptr };
40 status = napi_get_cb_info(env, info, &argc, argv, &self, nullptr);
41 CHECK_STATUS_RETURN_VOID(this, "napi_get_cb_info failed!");
42 CHECK_ARGS_RETURN_VOID(this, argc <= ARGC_MAX, "too many arguments!", std::make_shared<InnerError>());
43 CHECK_ARGS_RETURN_VOID(this, self != nullptr, "no JavaScript this argument!", std::make_shared<InnerError>());
44 napi_create_reference(env, self, 1, &selfRef);
45 status = napi_unwrap(env, self, &native);
46 CHECK_STATUS_RETURN_VOID(this, "self unwrap failed!");
47
48 if (!sync && (argc > 0)) {
49 // get the last arguments :: <callback>
50 size_t index = argc - 1;
51 napi_valuetype type = napi_undefined;
52 napi_status tyst = napi_typeof(env, argv[index], &type);
53 if ((tyst == napi_ok) && (type == napi_function)) {
54 status = napi_create_reference(env, argv[index], 1, &callbackRef);
55 CHECK_STATUS_RETURN_VOID(this, "ref callback failed!");
56 argc = index;
57 LOG_DEBUG("async callback, no promise");
58 } else {
59 CHECK_ARGS_RETURN_VOID(this, type == napi_undefined, "arguments error!",
60 std::make_shared<ParametersType>("callback", "function"));
61 LOG_DEBUG("no callback, async promise");
62 }
63 }
64
65 if (parse) {
66 parse(argc, argv);
67 } else {
68 CHECK_ARGS_RETURN_VOID(this, argc == 0, "required no arguments!", std::make_shared<InnerError>());
69 }
70 }
71
AsyncWork(napi_env env,std::shared_ptr<ContextBase> ctxt,const std::string & name,NapiAsyncExecute execute,NapiAsyncComplete complete)72 napi_value NapiQueue::AsyncWork(napi_env env, std::shared_ptr<ContextBase> ctxt, const std::string& name,
73 NapiAsyncExecute execute, NapiAsyncComplete complete)
74 {
75 LOG_DEBUG("name=%{public}s", name.c_str());
76 ctxt->execute = std::move(execute);
77 ctxt->complete = std::move(complete);
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 ASSERT_MATCH_ELSE_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 ASSERT_MATCH_ELSE_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 napi_queue_async_work(ctxt->env, ctxt->work);
113 ctxt->hold = ctxt; // save crossing-thread ctxt.
114 return promise;
115 }
116
SetBusinessError(napi_env env,napi_value * businessError,std::shared_ptr<Error> error)117 void NapiQueue::SetBusinessError(napi_env env, napi_value *businessError, std::shared_ptr<Error> error)
118 {
119 napi_create_object(env, businessError);
120 if (error != nullptr && error->GetCode() != EXCEPTION_INNER) {
121 napi_value code = nullptr;
122 napi_value msg = nullptr;
123 napi_create_int32(env, error->GetCode(), &code);
124 napi_create_string_utf8(env, error->GetMessage().c_str(), NAPI_AUTO_LENGTH, &msg);
125 napi_set_named_property(env, *businessError, "code", code);
126 napi_set_named_property(env, *businessError, "message", msg);
127 }
128 }
129
GenerateOutput(ContextBase * ctxt)130 void NapiQueue::GenerateOutput(ContextBase *ctxt)
131 {
132 napi_value result[RESULT_ALL] = { nullptr };
133 if (ctxt->status == napi_ok) {
134 napi_get_undefined(ctxt->env, &result[RESULT_ERROR]);
135 if (ctxt->output == nullptr) {
136 napi_get_undefined(ctxt->env, &ctxt->output);
137 }
138 result[RESULT_DATA] = ctxt->output;
139 } else {
140 napi_value businessError = nullptr;
141 SetBusinessError(ctxt->env, &businessError, ctxt->error);
142 result[RESULT_ERROR] = businessError;
143 napi_get_undefined(ctxt->env, &result[RESULT_DATA]);
144 }
145 if (ctxt->deferred != nullptr) {
146 if (ctxt->status == napi_ok) {
147 LOG_DEBUG("deferred promise resolved");
148 napi_resolve_deferred(ctxt->env, ctxt->deferred, result[RESULT_DATA]);
149 } else {
150 LOG_DEBUG("deferred promise rejected");
151 napi_reject_deferred(ctxt->env, ctxt->deferred, result[RESULT_ERROR]);
152 }
153 } else {
154 napi_value callback = nullptr;
155 napi_get_reference_value(ctxt->env, ctxt->callbackRef, &callback);
156 napi_value callbackResult = nullptr;
157 LOG_DEBUG("call callback function");
158 napi_call_function(ctxt->env, nullptr, callback, RESULT_ALL, result, &callbackResult);
159 }
160 ctxt->hold.reset(); // release ctxt.
161 }
162 } // namespace OHOS::DistributedData
163