• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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     CHECK_STATUS_RETURN_VOID(this, "napi_get_cb_info failed!");
44     CHECK_ARGS_RETURN_VOID(this, argc <= ARGC_MAX, "too many arguments!", std::make_shared<InnerError>());
45     CHECK_ARGS_RETURN_VOID(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     CHECK_STATUS_RETURN_VOID(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             CHECK_STATUS_RETURN_VOID(this, "ref callback failed!");
58             argc = index;
59             LOG_DEBUG("async callback, no promise");
60         } else {
61             CHECK_ARGS_RETURN_VOID(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         CHECK_ARGS_RETURN_VOID(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             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     ctxt->execute = std::move(execute);
113     ctxt->complete = std::move(complete);
114     ctxt->hold = ctxt; // save crossing-thread ctxt.
115     napi_queue_async_work(ctxt->env, ctxt->work);
116     return promise;
117 }
118 
SetBusinessError(napi_env env,napi_value * businessError,std::shared_ptr<Error> error)119 void NapiQueue::SetBusinessError(napi_env env, napi_value *businessError, std::shared_ptr<Error> error)
120 {
121     napi_create_object(env, businessError);
122     if (error != nullptr && error->GetCode() != EXCEPTION_INNER) {
123         napi_value code = nullptr;
124         napi_value msg = nullptr;
125         napi_create_int32(env, error->GetCode(), &code);
126         napi_create_string_utf8(env, error->GetMessage().c_str(), NAPI_AUTO_LENGTH, &msg);
127         napi_set_named_property(env, *businessError, "code", code);
128         napi_set_named_property(env, *businessError, "message", msg);
129     }
130 }
131 
GenerateOutput(ContextBase * ctxt)132 void NapiQueue::GenerateOutput(ContextBase *ctxt)
133 {
134     napi_value result[RESULT_ALL] = { nullptr };
135     if (ctxt->status == napi_ok) {
136         napi_get_undefined(ctxt->env, &result[RESULT_ERROR]);
137         if (ctxt->output == nullptr) {
138             napi_get_undefined(ctxt->env, &ctxt->output);
139         }
140         result[RESULT_DATA] = ctxt->output;
141     } else {
142         napi_value businessError = nullptr;
143         SetBusinessError(ctxt->env, &businessError, ctxt->error);
144         result[RESULT_ERROR] = businessError;
145         napi_get_undefined(ctxt->env, &result[RESULT_DATA]);
146     }
147     if (ctxt->deferred != nullptr) {
148         if (ctxt->status == napi_ok) {
149             LOG_DEBUG("deferred promise resolved");
150             napi_resolve_deferred(ctxt->env, ctxt->deferred, result[RESULT_DATA]);
151         } else {
152             LOG_DEBUG("deferred promise rejected");
153             napi_reject_deferred(ctxt->env, ctxt->deferred, result[RESULT_ERROR]);
154         }
155     } else {
156         napi_value callback = nullptr;
157         napi_get_reference_value(ctxt->env, ctxt->callbackRef, &callback);
158         napi_value callbackResult = nullptr;
159         LOG_DEBUG("call callback function");
160         napi_call_function(ctxt->env, nullptr, callback, RESULT_ALL, result, &callbackResult);
161     }
162     ctxt->execute = nullptr;
163     ctxt->complete = nullptr;
164     ctxt->hold.reset(); // release ctxt.
165 }
166 } // namespace OHOS::DistributedData
167