1 /*
2  * Copyright (c) 2023 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 NAPI_REMOTE_PROXY_HOLDER_H
17 #define NAPI_REMOTE_PROXY_HOLDER_H
18 
19 #include <mutex>
20 #include <refbase.h>
21 #include <set>
22 #include <uv.h>
23 
24 #include "napi_remote_object_internal.h"
25 
26 #include "napi/native_api.h"
27 
28 namespace OHOS {
29 class NAPIDeathRecipient : public IRemoteObject::DeathRecipient {
30 public:
31     explicit NAPIDeathRecipient(napi_env env, napi_value jsDeathRecipient);
32 
33     void OnRemoteDied(const wptr<IRemoteObject> &object) override;
34 
35     bool Matches(napi_value object);
36 
37 protected:
38     virtual ~NAPIDeathRecipient() = default;
39 
40 private:
41     static void AfterWorkCallback(uv_work_t *work, int status);
42 
43     struct OnRemoteDiedParam {
44         napi_env env;
45         napi_ref deathRecipientRef;
46     };
47     napi_env env_ = nullptr;
48     napi_ref deathRecipientRef_ = nullptr;
49 };
50 
51 class NAPIDeathRecipientList : public RefBase {
52 public:
53     NAPIDeathRecipientList();
54 
55     ~NAPIDeathRecipientList();
56 
57     bool Add(const sptr<NAPIDeathRecipient> &recipient);
58 
59     bool Remove(const sptr<NAPIDeathRecipient> &recipient);
60 
61     sptr<NAPIDeathRecipient> Find(napi_value jsRecipient);
62 
63 private:
64     std::mutex mutex_;
65     std::set<sptr<NAPIDeathRecipient>> set_;
66 };
67 
68 class NAPIRemoteProxyHolder {
69 public:
70     NAPIRemoteProxyHolder();
71     ~NAPIRemoteProxyHolder();
72     sptr<NAPIDeathRecipientList> list_;
73     sptr<IRemoteObject> object_;
74 };
75 
76 NAPIRemoteProxyHolder *NAPI_ohos_rpc_getRemoteProxyHolder(napi_env env, napi_value jsRemoteProxy);
77 } // namespace OHOS
78 #endif // NAPI_REMOTE_PROXY_HOLDER_H