1 /*
2 * Copyright (c) 2021 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 "uv_queue.h"
16 #include "logger.h"
17
18 namespace OHOS::ObjectStore {
UvQueue(napi_env env)19 UvQueue::UvQueue(napi_env env) : env_(env)
20 {
21 napi_get_uv_event_loop(env, &loop_);
22 }
23
~UvQueue()24 UvQueue::~UvQueue()
25 {
26 LOG_DEBUG("no memory leak for queue-callback");
27 }
28
ExecUvWork(UvEntry * entry)29 void UvQueue::ExecUvWork(UvEntry *entry)
30 {
31 if (entry == nullptr) {
32 LOG_ERROR("entry is nullptr");
33 return;
34 }
35 auto queue = entry->uvQueue_.lock();
36 if (queue != nullptr) {
37 std::unique_lock<std::shared_mutex> cacheLock(queue->mutex_);
38 for (auto &item : queue->args_) {
39 item.first(queue->env_, item.second);
40 }
41 queue->args_.clear();
42 }
43 delete entry;
44 entry = nullptr;
45 }
46
CallFunction(Process process,void * argv)47 bool UvQueue::CallFunction(Process process, void *argv)
48 {
49 if (process == nullptr || argv == nullptr) {
50 LOG_ERROR("nullptr");
51 return false;
52 }
53 auto *uvEntry = new (std::nothrow) UvEntry{ weak_from_this() };
54 if (uvEntry == nullptr) {
55 LOG_ERROR("no memory for UvEntry");
56 return false;
57 }
58 auto rollbackAddition = [this, process, argv]() {
59 std::unique_lock<std::shared_mutex> lock(mutex_);
60 auto it = args_.find(process);
61 if (it != args_.end() && !it->second.empty()) {
62 it->second.pop_back();
63 if (it->second.empty()) {
64 args_.erase(it);
65 }
66 }
67 };
68 {
69 std::unique_lock<std::shared_mutex> cacheLock(mutex_);
70 auto &processList = args_[process];
71 processList.push_back(argv);
72 }
73
74 auto task = [uvEntry]() { UvQueue::ExecUvWork(uvEntry); };
75 auto ret = napi_send_event(env_, task, napi_eprio_high);
76 if (ret != 0) {
77 LOG_ERROR("napi_send_event failed, ret: %{public}d.", ret);
78 rollbackAddition();
79 delete uvEntry;
80 return false;
81 }
82 return true;
83 }
84 } // namespace OHOS::ObjectStore
85