1 /*
2  * Copyright (c) 2024 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_session.h"
17 
18 #include "node_api.h"
19 
20 #include "base_client.h"
21 #include "napi_common_define.h"
22 #include "napi_common_utils.h"
23 
24 using namespace std;
25 
26 namespace OHOS::UpdateEngine {
27 uint32_t g_sessionId = 0;
28 
NapiSession(BaseClient * client,SessionParams & sessionParams,size_t argc,size_t callbackNumber)29 NapiSession::NapiSession(BaseClient *client, SessionParams &sessionParams, size_t argc, size_t callbackNumber)
30     : sessionId(++g_sessionId), client_(client), sessionParams_(sessionParams), totalArgc_(argc),
31     callbackNumber_(callbackNumber) {}
32 
CreateWorkerName(napi_env env) const33 napi_value NapiSession::CreateWorkerName(napi_env env) const
34 {
35     napi_value workName;
36     std::string name = "Async Work" + std::to_string(sessionId);
37     napi_status status = napi_create_string_utf8(env, name.c_str(), NAPI_AUTO_LENGTH, &workName);
38     PARAM_CHECK_NAPI_CALL(env, status == napi_ok, return nullptr, "Failed to worker name");
39     return workName;
40 }
41 
StartWork(napi_env env,const napi_value * args,DoWorkFunction worker,void * context)42 napi_value NapiSession::StartWork(napi_env env, const napi_value *args, DoWorkFunction worker, void *context)
43 {
44     ENGINE_LOGI("StartWork type: %{public}d", CAST_INT(sessionParams_.type));
45     doWorker_ = worker;
46     context_ = context;
47     return StartWork(env, sessionParams_.callbackStartIndex, args);
48 }
49 
ExecuteWork(napi_env env)50 void NapiSession::ExecuteWork(napi_env env)
51 {
52     if (doWorker_ != nullptr) {
53 #ifndef UPDATER_UT
54         if (sessionParams_.isNeedBusinessError) {
55             workResult_ = doWorker_(&businessError_);
56         } else {
57             workResult_ = doWorker_(context_);
58         }
59         if (workResult_ != 0) {
60             ENGINE_LOGI("UpdateSession::ExecuteWork workResult : %{public}d", workResult_);
61         }
62         if (sessionParams_.isAsyncCompleteWork && IsWorkExecuteSuccess()) {
63             // 异步搜包完成,需要把businessError设置进来或者超时,才能结束等待
64             std::unique_lock<std::mutex> lock(conditionVariableMutex_);
65             auto now = std::chrono::system_clock::now();
66             conditionVariable_.wait_until(lock, now + 40000ms, [this] { return asyncExecuteComplete_; });
67             ENGINE_LOGI("UpdateSession::ExecuteWork asyncExcuteComplete : %{public}s",
68                 asyncExecuteComplete_ ? "true" : "false");
69             if (!asyncExecuteComplete_) {
70                 businessError_.errorNum = CallResult::TIME_OUT;
71             }
72         }
73 #else
74         doWorker_(context_);
75 #endif
76     }
77 }
78 
79 // JS thread, which is used to notify the JS page upon completion of the operation.
CompleteWork(napi_env env,napi_status status,void * data)80 void NapiSession::CompleteWork(napi_env env, napi_status status, void *data)
81 {
82     auto sess = reinterpret_cast<NapiSession *>(data);
83     PARAM_CHECK(sess != nullptr && sess->GetNapiClient() != nullptr, return, "Session is null pointer");
84     sess->CompleteWork(env, status);
85     // If the share ptr is used, you can directly remove the share ptr.
86     BaseClient *client = sess->GetNapiClient();
87     if (client != nullptr) {
88         client->RemoveSession(sess->GetSessionId());
89     }
90 }
91 
92 // The C++ thread executes the synchronization operation. After the synchronization is complete,
93 // the CompleteWork is called to notify the JS page of the completion of the operation.
ExecuteWork(napi_env env,void * data)94 void NapiSession::ExecuteWork(napi_env env, void *data)
95 {
96     auto sess = reinterpret_cast<NapiSession *>(data);
97     PARAM_CHECK(sess != nullptr, return, "sess is null");
98     sess->ExecuteWork(env);
99 }
100 
GetSessionFuncParameter(std::string & funcName,std::string & permissionName)101 void NapiSession::GetSessionFuncParameter(std::string &funcName, std::string &permissionName)
102 {
103     funcName = GetFunctionName();
104     permissionName = GetFunctionPermissionName();
105 }
106 } // namespace OHOS::UpdateEngine