lichao
2021-05-21 b2484c8bd77a9d21bcf1827f554444535196953d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
/*
 * =====================================================================================
 *
 *       Filename:  center.cpp
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  2021年03月30日 16时19分37秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Li Chao (), 
 *   Organization:  
 *
 * =====================================================================================
 */
#include "center.h"
#include "center_topic_node.h"
#include "node_center.h"
#include <chrono>
 
using namespace std::chrono;
using namespace std::chrono_literals;
 
using namespace bhome_shm;
using namespace bhome_msg;
typedef BHCenter::MsgHandler Handler;
 
namespace
{
 
//TODO check proc_id
 
template <class Body, class OnMsg, class Replyer>
inline void Dispatch(MsgI &msg, BHMsgHead &head, OnMsg const &onmsg, Replyer const &replyer)
{
    if (head.route_size() != 1) { return; }
    Body body;
    if (msg.ParseBody(body)) {
        replyer(onmsg(body));
    }
}
 
Handler Combine(const Handler &h1, const Handler &h2)
{
    return [h1, h2](ShmSocket &socket, bhome_msg::MsgI &msg, bhome_msg::BHMsgHead &head) {
        return h1(socket, msg, head) || h2(socket, msg, head);
    };
}
template <class... H>
Handler Combine(const Handler &h0, const Handler &h1, const Handler &h2, const H &...rest)
{
    return Combine(Combine(h0, h1), h2, rest...);
}
 
#define CASE_ON_MSG_TYPE(MsgTag)                                                         \
    case kMsgType##MsgTag:                                                               \
        Dispatch<Msg##MsgTag>(                                                           \
            msg, head, [&](auto &body) { return center->MsgTag(head, body); }, replyer); \
        return true;
 
auto MakeReplyer(ShmSocket &socket, BHMsgHead &head, Synced<NodeCenter> &center)
{
    return [&](auto &&rep_body) {
        auto reply_head(InitMsgHead(GetType(rep_body), center->id(), head.ssn_id(), head.msg_id()));
        MQInfo remote = {head.route(0).mq_id(), head.route(0).abs_addr()};
        MsgI msg;
        if (msg.Make(reply_head, rep_body)) {
            DEFER1(msg.Release(););
            center->SendAllocMsg(socket, remote, msg);
        }
    };
}
 
bool AddCenter(std::shared_ptr<Synced<NodeCenter>> center_ptr)
{
    // command
    auto OnCommand = [center_ptr](ShmSocket &socket, ShmMsgQueue::RawData &cmd) -> bool {
        auto &center = *center_ptr;
        return IsCmd(cmd) && center->OnCommand(socket, cmd);
    };
 
    // now we can talk.
    auto OnCenterIdle = [center_ptr](ShmSocket &socket) {
        auto &center = *center_ptr;
        auto onInit = [&](const int64_t request) {
            return center->OnNodeInit(socket, request);
        };
        BHCenterHandleInit(onInit);
        center->OnTimer();
    };
 
    auto OnCenter = [=](ShmSocket &socket, MsgI &msg, BHMsgHead &head) -> bool {
        auto &center = *center_ptr;
        auto replyer = MakeReplyer(socket, head, center);
        switch (head.type()) {
            CASE_ON_MSG_TYPE(ProcInit);
            CASE_ON_MSG_TYPE(Register);
            CASE_ON_MSG_TYPE(Heartbeat);
            CASE_ON_MSG_TYPE(Unregister);
 
            CASE_ON_MSG_TYPE(RegisterRPC);
            CASE_ON_MSG_TYPE(QueryTopic);
            CASE_ON_MSG_TYPE(QueryProc);
        default: return false;
        }
    };
    BHCenter::Install("#center.main", OnCenter, OnCommand, OnCenterIdle, BHTopicCenterAddress(), 1000);
 
    auto OnBusIdle = [=](ShmSocket &socket) {};
    auto OnBusCmd = [=](ShmSocket &socket, ShmMsgQueue::RawData &val) { return false; };
    auto OnPubSub = [=](ShmSocket &socket, MsgI &msg, BHMsgHead &head) -> bool {
        auto &center = *center_ptr;
        auto replyer = MakeReplyer(socket, head, center);
        auto OnPublish = [&]() {
            MsgPublish pub;
            NodeCenter::Clients clients;
            MsgCommonReply reply;
            if (head.route_size() != 1 || !msg.ParseBody(pub)) {
                return;
            } else if (!center->FindClients(head, pub, clients, reply)) {
                replyer(reply);
            } else {
                replyer(MakeReply(eSuccess));
                if (clients.empty()) { return; }
                for (auto &cli : clients) {
                    auto node = cli.weak_node_.lock();
                    if (node) {
                        // should also make sure that mq is not killed before msg expires.
                        // it would be ok if (kill_time - offline_time) is longer than expire time.
                        socket.Send({cli.mq_id_, cli.mq_abs_addr_}, msg);
                    }
                }
            }
        };
        switch (head.type()) {
            CASE_ON_MSG_TYPE(Subscribe);
            CASE_ON_MSG_TYPE(Unsubscribe);
        case kMsgTypePublish: OnPublish(); return true;
        default: return false;
        }
    };
 
    BHCenter::Install("#center.bus", OnPubSub, OnBusCmd, OnBusIdle, BHTopicBusAddress(), 1000);
 
    return true;
}
 
#undef CASE_ON_MSG_TYPE
 
} // namespace
 
BHCenter::CenterRecords &BHCenter::Centers()
{
    static CenterRecords rec;
    return rec;
}
 
bool BHCenter::Install(const std::string &name, MsgHandler handler, RawHandler raw_handler, IdleHandler idle, const MQInfo &mq, const int mq_len)
{
    Centers()[name] = CenterInfo{name, handler, raw_handler, idle, mq, mq_len};
    return true;
}
 
BHCenter::BHCenter(Socket::Shm &shm)
{
    auto nsec = NodeTimeoutSec();
    auto center_ptr = std::make_shared<Synced<NodeCenter>>("#bhome_center", nsec, nsec * 3); // *3 to allow other clients to finish sending msgs.
    AddCenter(center_ptr);
 
    for (auto &kv : Centers()) {
        auto &info = kv.second;
        sockets_[info.name_] = std::make_shared<ShmSocket>(info.mq_.offset_, shm, info.mq_.id_);
    }
 
    topic_node_.reset(new CenterTopicNode(center_ptr, shm));
}
BHCenter::~BHCenter() { Stop(); }
 
bool BHCenter::Start()
{
    for (auto &kv : Centers()) {
        auto &info = kv.second;
        sockets_[info.name_]->Start(1, info.handler_, info.raw_handler_, info.idle_);
    }
    topic_node_->Start();
    return true;
}
 
bool BHCenter::Stop()
{
    topic_node_->Stop();
    for (auto &kv : sockets_) {
        kv.second->Stop();
    }
    return true;
}