lichao
2021-04-02 0bc72d004b08b6cac005931787f43c68dace7685
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_center.cpp
 *
 *    Description:  pub/sub center/manager
 *
 *        Version:  1.0
 *        Created:  2021年04月01日 09时29分04秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Li Chao (), 
 *   Organization:  
 *
 * =====================================================================================
 */
#include "pubsub_center.h"
#include "bh_util.h"
using namespace bhome_shm;
namespace
{
class BusCenter
{
    typedef std::set<MQId> Clients;
    std::unordered_map<Topic, Clients> records_;
    // todo cache data if send fail.
 
public:
    template <class Iter>
    void SubScribe(const MQId &client, Iter topic_begin, Iter topic_end)
    {
        for (auto it = topic_begin; it != topic_end; ++it) {
            records_[*it].insert(client);
        }
    }
    template <class Iter>
    void UnsubScribe(const MQId &client, Iter topic_begin, Iter topic_end)
    {
        for (auto it = topic_begin; it != topic_end; ++it) {
            auto pos = records_.find(*it);
            if (pos != records_.end()) {
                if (pos->second.erase(client) && pos->second.empty()) {
                    records_.erase(pos);
                }
            }
        }
    };
    Clients FindClients(const std::string &topic)
    {
        Clients dests;
        auto Find1 = [&](const std::string &t) {
            auto pos = records_.find(topic);
            if (pos != records_.end() && !pos->second.empty()) {
                auto &clients = pos->second;
                for (auto &cli : clients) {
                    dests.insert(cli);
                }
            }
        };
        Find1(topic);
 
        //TODO check and adjust topic on client side sub/pub.
        size_t pos = 0;
        while (true) {
            pos = topic.find(kTopicSep, pos);
            if (pos == topic.npos || ++pos == topic.size()) {
                // Find1(std::string()); // sub all.
                break;
            } else {
                Find1(topic.substr(0, pos));
            }
        }
        return dests;
    }
};
 
} // namespace
 
bool PubSubCenter::Start(const int nworker)
{
    auto bus_ptr = std::make_shared<Synced<BusCenter>>();
 
    auto onRecv = [bus_ptr, this](MsgI &imsg) {
#ifndef NDEBUG
        static std::atomic<time_t> last(0);
        time_t now = 0;
        time(&now);
        if (last.exchange(now) < now) {
            printf("bus queue size: %ld\n", socket_.Pending());
        }
#endif
        auto &bus = *bus_ptr;
 
        BHMsg msg;
        if (!imsg.Unpack(msg)) {
            return;
        }
 
        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));
                update(client, sub.topics());
            }
        };
 
        auto Sub = [&](const MQId &id, auto &topics) { bus->SubScribe(id, topics.begin(), topics.end()); };
        auto Unsub = [&](const MQId &id, auto &topics) { bus->UnsubScribe(id, topics.begin(), topics.end()); };
 
        auto OnPublish = [&]() {
            DataPub pub;
            if (!pub.ParseFromString(msg.body())) {
                return;
            }
            auto Dispatch = [&](auto &&send1) {
                const auto &clients(bus->FindClients(pub.topic()));
                for (auto &cli : clients) {
                    send1(cli);
                }
            };
 
            if (imsg.IsCounted()) {
                Dispatch([&](const MQId &cli) { ShmMsgQueue::Send(shm(), cli, imsg, 10); });
            } else {
                MsgI pubmsg;
                if (!pubmsg.MakeRC(shm(), msg)) { return; }
                DEFER1(pubmsg.Release(shm()));
 
                Dispatch([&](const MQId &cli) { ShmMsgQueue::Send(shm(), cli, pubmsg, 10); });
            }
        };
 
        switch (msg.type()) {
        case kMsgTypeSubscribe: OnSubChange(Sub); break;
        case kMsgTypeUnsubscribe: OnSubChange(Unsub); break;
        case kMsgTypePublish: OnPublish(); break;
        default: break;
        }
    };
 
    const int kMaxWorker = 16;
    return socket_.StartRaw(onRecv, std::min((nworker > 0 ? nworker : 2), kMaxWorker));
}