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 #ifndef OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_COMMUNICATION_CONNECT_MANAGER_H
17 #define OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_COMMUNICATION_CONNECT_MANAGER_H
18 
19 #include <functional>
20 #include <map>
21 #include <memory>
22 #include <mutex>
23 
24 #include "concurrent_map.h"
25 #include "visibility.h"
26 namespace OHOS {
27 namespace AppDistributedKv {
28 class API_EXPORT ConnectManager {
29 public:
30     using ConnectTask = std::function<void(void)>;
31     using CloseSessionTask = std::function<bool(const std::string &networkId)>;
32     using SessionCloseListener = std::function<void(const std::string &networkId)>;
33     using SessionOpenListener = std::function<void(const std::string &networkId)>;
34 
35     API_EXPORT static std::shared_ptr<ConnectManager> GetInstance();
36     API_EXPORT static bool RegisterInstance(std::shared_ptr<ConnectManager> instance);
37 
38     API_EXPORT static bool CloseSession(const std::string &networkId);
39     API_EXPORT static bool RegisterCloseSessionTask(CloseSessionTask task);
40 
41     API_EXPORT static bool RegisterSessionCloseListener(const std::string &name, SessionCloseListener listener);
42     API_EXPORT static void UnRegisterSessionCloseListener(const std::string &name);
43     API_EXPORT static void OnSessionClose(const std::string &networkId);
44 
45     API_EXPORT static bool RegisterSessionOpenListener(const std::string &name, SessionOpenListener listener);
46     API_EXPORT static void UnRegisterSessionOpenListener(const std::string &name);
47     API_EXPORT static void OnSessionOpen(const std::string &networkId);
48 
49     ConnectManager() = default;
50     virtual ~ConnectManager() = default;
51 
52     virtual void OnStart();
53     virtual void OnDestory();
54     virtual int32_t ApplyConnect(const std::string &networkId, ConnectTask task);
55 
56 private:
57     static std::mutex mtx_;
58     static std::shared_ptr<ConnectManager> instance_;
59     static CloseSessionTask closeSessionTask_;
60     static ConcurrentMap<std::string, SessionCloseListener> sessionCloseListener_;
61     static ConcurrentMap<std::string, SessionOpenListener> sessionOpenListener_;
62 };
63 } // namespace AppDistributedKv
64 } // namespace OHOS
65 #endif // OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_COMMUNICATION_CONNECT_MANAGER_H