lichao
2021-04-16 94a455aba299af5ffe476560d859dfd007cd5467
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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
/*
 * =====================================================================================
 *
 *       Filename:  topic_node.cpp
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  2021年04月07日 09时01分48秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Li Chao (), 
 *   Organization:  
 *
 * =====================================================================================
 */
#include "topic_node.h"
#include "bh_util.h"
#include <chrono>
#include <list>
 
using namespace std::chrono;
using namespace std::chrono_literals;
 
namespace
{
inline void AddRoute(BHMsgHead &head, const MQId &id) { head.add_route()->set_mq_id(&id, sizeof(id)); }
 
struct SrcInfo {
    std::vector<BHAddress> route;
    std::string msg_id;
};
 
} // namespace
 
TopicNode::TopicNode(SharedMemory &shm) :
    shm_(shm), sock_node_(shm), sock_request_(shm), sock_reply_(shm), sock_sub_(shm), registered_(false)
{
    // recv msgs to avoid memory leak.
    auto default_ignore_msg = [](ShmSocket &sock, MsgI &imsg, BHMsgHead &head) { return true; };
    SockNode().Start(default_ignore_msg);
}
 
TopicNode::~TopicNode()
{
    Stop();
    SockNode().Stop();
}
 
void TopicNode::Start(ServerCB const &server_cb, SubDataCB const &sub_cb, RequestResultCB &client_cb, int nworker)
{
    if (nworker < 1) {
        nworker = 1;
    } else if (nworker > 16) {
        nworker = 16;
    }
 
    ServerStart(server_cb, nworker);
    SubscribeStartWorker(sub_cb, nworker);
    ClientStartWorker(client_cb, nworker);
}
void TopicNode::Stop()
{
    SockSub().Stop();
    SockServer().Stop();
    SockClient().Stop();
}
 
bool TopicNode::Register(ProcInfo &proc, MsgCommonReply &reply_body, const int timeout_ms)
{
    info_ = proc;
 
    auto &sock = SockNode();
    MsgRegister body;
    body.mutable_proc()->Swap(&proc);
    auto AddId = [&](const MQId &id) { body.add_addrs()->set_mq_id(&id, sizeof(id)); };
    AddId(SockNode().id());
    AddId(SockServer().id());
    AddId(SockClient().id());
    AddId(SockSub().id());
    AddId(SockPub().id());
 
    auto head(InitMsgHead(GetType(body), body.proc().proc_id()));
    AddRoute(head, sock.id());
 
    auto CheckResult = [this](MsgI &msg, BHMsgHead &head, MsgCommonReply &rbody) {
        bool ok = head.type() == kMsgTypeCommonReply &&
                  msg.ParseBody(rbody) &&
                  IsSuccess(rbody.errmsg().errcode());
        printf("async regisered %s\n", ok ? "ok" : "failed");
        registered_.store(ok);
    };
 
    if (timeout_ms == 0) {
        auto onResult = [this, CheckResult](ShmSocket &socket, MsgI &imsg, BHMsgHead &head) {
            MsgCommonReply body;
            CheckResult(imsg, head, body);
        };
        return sock.Send(&BHTopicCenterAddress(), head, body, onResult);
    } else {
        MsgI reply;
        DEFER1(reply.Release(shm_););
        BHMsgHead reply_head;
        bool r = sock.SendAndRecv(&BHTopicCenterAddress(), head, body, reply, reply_head, timeout_ms);
        if (r) {
            CheckResult(reply, reply_head, reply_body);
        }
        return IsRegistered();
    }
}
 
bool TopicNode::Heartbeat(ProcInfo &proc, MsgCommonReply &reply_body, const int timeout_ms)
{
    if (!IsRegistered()) { return false; }
 
    auto &sock = SockNode();
    MsgHeartbeat body;
    body.mutable_proc()->Swap(&proc);
 
    auto head(InitMsgHead(GetType(body), body.proc().proc_id()));
    AddRoute(head, sock.id());
 
    if (timeout_ms == 0) {
        return sock.Send(&BHTopicCenterAddress(), head, body);
    } else {
        MsgI reply;
        DEFER1(reply.Release(shm_););
        BHMsgHead reply_head;
        bool r = sock.SendAndRecv(&BHTopicCenterAddress(), head, body, reply, reply_head, timeout_ms);
        r = r && reply_head.type() == kMsgTypeCommonReply && reply.ParseBody(reply_body);
        return (r && IsSuccess(reply_body.errmsg().errcode()));
    }
}
bool TopicNode::Heartbeat(const int timeout_ms)
{
    ProcInfo proc;
    proc.set_proc_id(proc_id());
    MsgCommonReply reply_body;
    return Heartbeat(proc, reply_body, timeout_ms);
}
 
bool TopicNode::ServerRegisterRPC(MsgTopicList &topics, MsgCommonReply &reply_body, const int timeout_ms)
{
    if (!IsRegistered()) { return false; }
 
    auto &sock = SockServer();
    MsgRegisterRPC body;
    body.mutable_topics()->Swap(&topics);
 
    auto head(InitMsgHead(GetType(body), proc_id()));
    AddRoute(head, sock.id());
 
    if (timeout_ms == 0) {
        return sock.Send(&BHTopicCenterAddress(), head, body);
    } else {
        MsgI reply;
        DEFER1(reply.Release(shm_););
        BHMsgHead reply_head;
        bool r = sock.SendAndRecv(&BHTopicCenterAddress(), head, body, reply, reply_head, timeout_ms);
        r = r && reply_head.type() == kMsgTypeCommonReply;
        r = r && reply.ParseBody(reply_body);
        return r;
    }
}
 
bool TopicNode::ServerStart(const ServerCB &rcb, int nworker)
{
    auto onRecv = [this, rcb](ShmSocket &sock, MsgI &imsg, BHMsgHead &head) {
        if (head.type() != kMsgTypeRequestTopic || head.route_size() == 0) { return; }
        MsgRequestTopic req;
        if (!imsg.ParseBody(req)) { return; }
 
        MsgRequestTopicReply reply_body;
        if (rcb(head.proc_id(), req, reply_body)) {
            BHMsgHead reply_head(InitMsgHead(GetType(reply_body), proc_id(), head.msg_id()));
 
            for (int i = 0; i < head.route_size() - 1; ++i) {
                reply_head.add_route()->Swap(head.mutable_route(i));
            }
            auto &remote = head.route().rbegin()->mq_id();
            sock.Send(remote.data(), reply_head, reply_body);
        }
    };
 
    auto &sock = SockServer();
    return rcb && sock.Start(onRecv, nworker);
}
 
bool TopicNode::ServerRecvRequest(void *&src_info, std::string &proc_id, MsgRequestTopic &request, const int timeout_ms)
{
    if (!IsRegistered()) { return false; }
 
    auto &sock = SockServer();
 
    MsgI imsg;
    BHMsgHead head;
    if (sock.SyncRecv(imsg, head, timeout_ms) && head.type() == kMsgTypeRequestTopic) {
        if (imsg.ParseBody(request)) {
            head.mutable_proc_id()->swap(proc_id);
            SrcInfo *p = new SrcInfo;
            p->route.assign(head.route().begin(), head.route().end());
            p->msg_id = head.msg_id();
            src_info = p;
            return true;
        }
    }
    return false;
}
 
bool TopicNode::ServerSendReply(void *src_info, const MsgRequestTopicReply &body)
{
    if (!IsRegistered()) { return false; }
 
    auto &sock = SockServer();
 
    SrcInfo *p = static_cast<SrcInfo *>(src_info);
    DEFER1(delete p);
    if (!p || p->route.empty()) {
        return false;
    }
    BHMsgHead head(InitMsgHead(GetType(body), proc_id(), p->msg_id));
    for (unsigned i = 0; i < p->route.size() - 1; ++i) {
        head.add_route()->Swap(&p->route[i]);
    }
    return sock.Send(p->route.back().mq_id().data(), head, body);
}
 
bool TopicNode::ClientStartWorker(RequestResultCB const &cb, const int nworker)
{
    if (!cb) {
        return false;
    }
    auto onData = [this, cb](ShmSocket &socket, MsgI &imsg, BHMsgHead &head) {
        if (head.type() == kMsgTypeRequestTopicReply) {
            MsgRequestTopicReply reply;
            if (imsg.ParseBody(reply)) {
                cb(head, reply);
            }
        }
    };
 
    return SockRequest().Start(onData, nworker);
}
 
bool TopicNode::ClientAsyncRequest(const MsgRequestTopic &req, std::string &out_msg_id, const RequestResultCB &cb)
{
    if (!IsRegistered()) {
        SetLastError(eNotRegistered, "Not Registered.");
        return false;
    }
 
    const std::string &msg_id(NewMsgId());
 
    out_msg_id = msg_id;
 
    auto SendTo = [this, msg_id](const BHAddress &addr, const MsgRequestTopic &req, const RequestResultCB &cb) {
        auto &sock = SockClient();
        BHMsgHead head(InitMsgHead(GetType(req), proc_id(), msg_id));
        AddRoute(head, sock.id());
        head.set_topic(req.topic());
 
        if (cb) {
            auto onRecv = [cb](ShmSocket &sock, MsgI &imsg, BHMsgHead &head) {
                if (head.type() == kMsgTypeRequestTopicReply) {
                    MsgRequestTopicReply reply;
                    if (imsg.ParseBody(reply)) {
                        cb(head, reply);
                    }
                }
            };
            return sock.Send(addr.mq_id().data(), head, req, onRecv);
        } else {
            return sock.Send(addr.mq_id().data(), head, req);
        }
    };
 
    try {
        auto &sock = SockClient();
        BHAddress addr;
 
        if (topic_query_cache_.Find(req.topic(), addr)) {
            return SendTo(addr, req, cb);
        }
 
        MsgQueryTopic query;
        query.set_topic(req.topic());
        BHMsgHead head(InitMsgHead(GetType(query), proc_id()));
        AddRoute(head, sock.id());
 
        auto onQueryResult = [this, SendTo, req, cb](ShmSocket &sock, MsgI &imsg, BHMsgHead &head) {
            MsgQueryTopicReply rep;
            if (head.type() == kMsgTypeQueryTopicReply && imsg.ParseBody(rep)) {
                auto &addr = rep.address();
                if (!addr.mq_id().empty()) {
                    topic_query_cache_.Update(req.topic(), addr);
                    SendTo(addr, req, cb);
                }
            }
        };
        return sock.Send(&BHTopicCenterAddress(), head, query, onQueryResult);
 
    } catch (...) {
        SetLastError(eError, "internal error.");
        return false;
    }
}
 
bool TopicNode::ClientSyncRequest(const MsgRequestTopic &request, std::string &out_proc_id, MsgRequestTopicReply &out_reply, const int timeout_ms)
{
    if (!IsRegistered()) { return false; }
 
    try {
        auto &sock = SockRequest();
 
        BHAddress addr;
        if (ClientQueryRPCTopic(request.topic(), addr, timeout_ms)) {
            BHMsgHead head(InitMsgHead(GetType(request), proc_id()));
            AddRoute(head, sock.id());
            head.set_topic(request.topic());
 
            MsgI reply_msg;
            DEFER1(reply_msg.Release(shm_););
            BHMsgHead reply_head;
 
            if (sock.SendAndRecv(addr.mq_id().data(), head, request, reply_msg, reply_head, timeout_ms) && reply_head.type() == kMsgTypeRequestTopicReply) {
                if (reply_msg.ParseBody(out_reply)) {
                    reply_head.mutable_proc_id()->swap(out_proc_id);
                    return true;
                } else {
                    printf("error parse reply.\n");
                }
            }
        } else {
            SetLastError(eNotFound, "remote not found.");
        }
    } catch (...) {
        printf("error recv data. line: %d\n", __LINE__);
    }
    return false;
}
 
bool TopicNode::ClientQueryRPCTopic(const Topic &topic, bhome::msg::BHAddress &addr, const int timeout_ms)
{
    if (!IsRegistered()) { return false; }
 
    auto &sock = SockRequest();
 
    if (topic_query_cache_.Find(topic, addr)) {
        return true;
    }
 
    MsgQueryTopic query;
    query.set_topic(topic);
    BHMsgHead head(InitMsgHead(GetType(query), proc_id()));
    AddRoute(head, sock.id());
 
    MsgI reply;
    DEFER1(reply.Release(shm_));
    BHMsgHead reply_head;
 
    if (sock.SendAndRecv(&BHTopicCenterAddress(), head, query, reply, reply_head, timeout_ms)) {
        if (reply_head.type() == kMsgTypeQueryTopicReply) {
            MsgQueryTopicReply rep;
            if (reply.ParseBody(rep)) {
                addr = rep.address();
                if (addr.mq_id().empty()) {
                    return false;
                } else {
                    topic_query_cache_.Update(topic, addr);
                    return true;
                }
            }
        }
    } else {
    }
    return false;
}
 
// publish
 
bool TopicNode::Publish(const MsgPublish &pub, const int timeout_ms)
{
    if (!IsRegistered()) { return false; }
 
    try {
        auto &sock = SockPub();
        BHMsgHead head(InitMsgHead(GetType(pub), proc_id()));
        AddRoute(head, sock.id());
 
        if (timeout_ms == 0) {
            return sock.Send(&BHTopicBusAddress(), head, pub);
        } else {
            MsgI reply;
            DEFER1(reply.Release(shm()););
            BHMsgHead reply_head;
            MsgCommonReply reply_body;
            return sock.SendAndRecv(&BHTopicBusAddress(), head, pub, reply, reply_head, timeout_ms) &&
                   reply_head.type() == kMsgTypeCommonReply &&
                   reply.ParseBody(reply_body) &&
                   IsSuccess(reply_body.errmsg().errcode());
        }
    } catch (...) {
    }
    return false;
}
 
// subscribe
 
bool TopicNode::Subscribe(MsgTopicList &topics, MsgCommonReply &reply_body, const int timeout_ms)
{
    if (!IsRegistered()) { return false; }
 
    try {
        auto &sock = SockSub();
        MsgSubscribe sub;
        sub.mutable_topics()->Swap(&topics);
 
        BHMsgHead head(InitMsgHead(GetType(sub), proc_id()));
        AddRoute(head, sock.id());
        if (timeout_ms == 0) {
            return sock.Send(&BHTopicBusAddress(), head, sub);
        } else {
            MsgI reply;
            DEFER1(reply.Release(shm()););
            BHMsgHead reply_head;
            return sock.SendAndRecv(&BHTopicBusAddress(), head, sub, reply, reply_head, timeout_ms) &&
                   reply_head.type() == kMsgTypeCommonReply &&
                   reply.ParseBody(reply_body) &&
                   IsSuccess(reply_body.errmsg().errcode());
        }
        // TODO wait for result?
    } catch (...) {
        return false;
    }
}
 
bool TopicNode::SubscribeStartWorker(const SubDataCB &tdcb, int nworker)
{
    auto &sock = SockSub();
 
    auto AsyncRecvProc = [this, tdcb](ShmSocket &, MsgI &imsg, BHMsgHead &head) {
        if (head.type() == kMsgTypePublish) {
            MsgPublish pub;
            if (imsg.ParseBody(pub)) {
                tdcb(head.proc_id(), pub);
            }
        } else {
            // ignored, or dropped
        }
    };
 
    return tdcb && sock.Start(AsyncRecvProc, nworker);
}
 
bool TopicNode::RecvSub(std::string &proc_id, MsgPublish &pub, const int timeout_ms)
{
    if (!IsRegistered()) { return false; }
 
    auto &sock = SockSub();
    MsgI msg;
    DEFER1(msg.Release(shm()););
    BHMsgHead head;
    //TODO error msg.
    if (sock.SyncRecv(msg, head, timeout_ms) && head.type() == kMsgTypePublish) {
        if (msg.ParseBody(pub)) {
            head.mutable_proc_id()->swap(proc_id);
            return true;
        }
    }
    return false;
}