lichao
2021-03-29 6aa7e4c37a70709e7348bd16407c5983a563ed76
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
/*
 * =====================================================================================
 *
 *       Filename:  pubsub.cpp
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  2021年03月24日 18时44分13秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Li Chao (), 
 *   Organization:  
 *
 * =====================================================================================
 */
#include "pubsub.h"
#include <chrono>
#include "bh_util.h"
 
namespace bhome_shm {
 
using namespace std::chrono_literals;
const MQId kBusQueueId = boost::uuids::string_generator()("01234567-89ab-cdef-8349-1234567890ff");
const int kMaxWorker = 16;
using namespace bhome_msg;
 
BusManager::BusManager(SharedMemory &shm):
shm_(shm),
busq_(kBusQueueId, shm, 1000),
run_(false)
{
}
    
BusManager::~BusManager()
{
    Stop();
}
 
bool BusManager::Start(const int nworker)
{
    std::lock_guard<std::mutex> guard(mutex_);
    StopNoLock();
    // start
    auto Worker = [&](){
        while (this->run_) {
            BusManager &self = *this;
            BHMsg msg;
            const int timeout_ms = 100;
            if (self.busq_.Recv(msg, timeout_ms)) {
                self.OnMsg(msg);
            }
        }
    };
 
    run_.store(true);
    const int n = std::min(nworker, kMaxWorker);
    for (int i = 0; i < n; ++i) {
        workers_.emplace_back(Worker);
    }
    return true;
}
 
bool BusManager::Stop()
{
    std::lock_guard<std::mutex> guard(mutex_);
    return StopNoLock();
}
 
bool BusManager::StopNoLock()
{
    if (run_.exchange(false)) {
        for (auto &w: workers_) {
            if (w.joinable()) {
                w.join();
            }
        }
        return true;
    }    
    return false;
}
 
void BusManager::OnMsg(const BHMsg &msg)
{
    auto OnSubChange = [&](auto &&update) {
        DataSub sub;
        if (!msg.route().empty() && sub.ParseFromString(msg.body()) && !sub.topics().empty()) {
            assert(sizeof(MQId) == msg.route(0).mq_id().size());
            MQId client;
            memcpy(&client, msg.route(0).mq_id().data(), sizeof(client));
 
            std::lock_guard<std::mutex> guard(mutex_);
            auto &topics = sub.topics();
            for (auto &topic : topics) {
                try {
                    update(topic, client);
                } catch(...) {
                    //TODO log error
                }
            }
        }
    };
 
    auto Sub1 = [this](const std::string &topic, const MQId &id) {
        records_[topic].insert(id);
    };
 
    auto Unsub1 = [this](const std::string &topic, const MQId &id) {
        auto pos = records_.find(topic);
        if (pos != records_.end()) {
            if (pos->second.erase(id) && pos->second.empty()) {
                records_.erase(pos);
            }
        }
    };
 
    auto OnPublish = [&]() {
        DataPub pub;
        MsgI pubmsg;
        if (!pub.ParseFromString(msg.body()) || !pubmsg.MakeRC(shm_, msg)) {
            return;
        }
        DEFER1(pubmsg.Release(shm_));
 
        std::lock_guard<std::mutex> guard(mutex_);
        auto pos = records_.find(pub.topic());
        if (pos != records_.end() && !pos->second.empty()) {
            auto &clients = pos->second;
            for (auto &cli : clients) {
                busq_.Send(cli, pubmsg, 100);
            }
        } else {
            // printf("invalid topic: %s\n", pub.topic().c_str());
        }
    };
 
    switch (msg.type()) {
        case kMsgTypeSubscribe: OnSubChange(Sub1); break;
        case kMsgTypeUnsubscribe: OnSubChange(Unsub1); break;
        case kMsgTypePublish : OnPublish(); break;
        default: break;
    }
}
 
} // namespace bhome_shm