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 
16 #ifndef COMMUNICATOR_PROXY_H
17 #define COMMUNICATOR_PROXY_H
18 
19 #include <cstdint>
20 #include <functional>
21 #include <map>
22 #include <mutex>
23 #include <string>
24 #include <vector>
25 #include "icommunicator.h"
26 #include "message.h"
27 
28 namespace DistributedDB {
29 class CommunicatorProxy : public ICommunicator {
30 public:
31     CommunicatorProxy();
32     ~CommunicatorProxy();
33 
34     int RegOnMessageCallback(const OnMessageCallback &onMessage, const Finalizer &inOper) override;
35     int RegOnConnectCallback(const OnConnectCallback &onConnect, const Finalizer &inOper) override;
36     int RegOnSendableCallback(const std::function<void(void)> &onSendable, const Finalizer &inOper) override;
37     void Activate() override;
38     uint32_t GetCommunicatorMtuSize() const override;
39     uint32_t GetCommunicatorMtuSize(const std::string &target) const override;
40     uint32_t GetTimeout() const override;
41     uint32_t GetTimeout(const std::string &target) const override;
42     bool IsDeviceOnline(const std::string &device) const override;
43     int GetLocalIdentity(std::string &outTarget) const override;
44     int GetRemoteCommunicatorVersion(const std::string &target, uint16_t &outVersion) const override;
45     int SendMessage(const std::string &dstTarget, const Message *inMsg, const SendConfig &config) override;
46     int SendMessage(const std::string &dstTarget, const Message *inMsg, const SendConfig &config,
47         const OnSendEnd &onEnd) override;
48 
49     // Set an Main communicator for this database, used userid & appId & storeId
50     void SetMainCommunicator(ICommunicator *communicator);
51 
52     // Set an equal communicator for this database, After this called, send msg to the target will use this communicator
53     void SetEqualCommunicator(ICommunicator *communicator, const std::string &identifier,
54         const std::vector<std::string> &targets);
55 
56     void Dump(int fd);
57 
58 private:
59     ICommunicator *mainComm_;
60     mutable std::mutex devCommMapLock_;
61     // key: device value: <identifier, ICommunicator *>
62     std::map<std::string, std::pair<std::string, ICommunicator *>> devCommMap_;
63 };
64 } // namespace DistributedDB
65 #endif // COMMUNICATOR_PROXY_H
66