1/*
2 * Copyright (c) 2021-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#ifndef FOUNDATION_ACE_NAPI_NATIVE_ENGINE_NATIVE_ASYNC_WORK_H
17#define FOUNDATION_ACE_NAPI_NATIVE_ENGINE_NATIVE_ASYNC_WORK_H
18
19#include "interfaces/kits/napi/common.h"
20#include "native_value.h"
21#ifdef ENABLE_HITRACE
22#include "hitrace/trace.h"
23#endif
24#include <mutex>
25#include <queue>
26#include <uv.h>
27
28struct NativeAsyncWorkDataPointer {
29    NativeAsyncWorkDataPointer()
30    {
31        data_ = nullptr;
32    }
33
34    explicit NativeAsyncWorkDataPointer(void* data)
35    {
36        data_ = data;
37    }
38    void* data_ { nullptr };
39};
40
41#ifdef ENABLE_HITRACE
42namespace OHOS {
43namespace HiviewDFX {
44class HiTraceId;
45}
46} // namespace OHOS
47#endif
48
49class NativeAsyncWork {
50public:
51    NativeAsyncWork(NativeEngine* engine,
52                    NativeAsyncExecuteCallback execute,
53                    NativeAsyncCompleteCallback complete,
54                    const std::string &asyncResourceName,
55                    void* data);
56
57    virtual ~NativeAsyncWork();
58    virtual bool Queue();
59    virtual bool QueueWithQos(napi_qos_t qos);
60    virtual bool Cancel();
61    virtual std::string GetTraceDescription();
62    template<typename Inner, typename Outer>
63    static Outer* DereferenceOf(const Inner Outer::*field, const Inner* pointer)
64    {
65        if (field != nullptr && pointer != nullptr) {
66            auto fieldOffset = reinterpret_cast<uintptr_t>(&(static_cast<Outer*>(0)->*field));
67            auto outPointer = reinterpret_cast<Outer*>(reinterpret_cast<uintptr_t>(pointer) - fieldOffset);
68            return outPointer;
69        }
70        return nullptr;
71    }
72
73private:
74    static void AsyncWorkCallback(uv_work_t* req);
75    static void AsyncAfterWorkCallback(uv_work_t* req, int status);
76
77    uv_work_t work_;
78    NativeEngine* engine_;
79    uint64_t engineId_;
80    NativeAsyncExecuteCallback execute_;
81    NativeAsyncCompleteCallback complete_;
82    void* data_;
83    std::mutex workAsyncMutex_;
84    std::queue<NativeAsyncWorkDataPointer> asyncWorkRecvData_;
85    std::string traceDescription_;
86#ifdef ENABLE_CONTAINER_SCOPE
87    int32_t containerScopeId_;
88#endif
89#ifdef ENABLE_HITRACE
90    OHOS::HiviewDFX::HiTraceId taskTraceId_;
91#endif
92};
93
94#endif /* FOUNDATION_ACE_NAPI_NATIVE_ENGINE_NATIVE_ASYNC_WORK_H */
95