lichao
2021-04-06 4deeafbd502dc3c57dab8ad6ca601a38a9e7f074
src/pubsub.cpp
@@ -18,168 +18,59 @@
#include "pubsub.h"
#include "bh_util.h"
#include "defs.h"
#include <chrono>
namespace bhome_shm
{
using namespace std::chrono_literals;
const int kMaxWorker = 16;
using namespace bhome_msg;
BusManager::BusManager(SharedMemory &shm) :
    shm_(shm),
    busq_(kBHBusQueueId, shm, 16),
    run_(false)
bool SocketPublish::Publish(const Topic &topic, const void *data, const size_t size, const int timeout_ms)
{
   try {
      MsgI imsg;
      if (!imsg.MakeRC(shm(), MakePub(topic, data, size))) {
         return false;
      }
      DEFER1(imsg.Release(shm()));
      return ShmMsgQueue::Send(shm(), kBHTopicBus, imsg, timeout_ms);
   } catch (...) {
      return false;
   }
}
BusManager::~BusManager()
bool SocketSubscribe::Subscribe(const std::vector<Topic> &topics, const int timeout_ms)
{
   Stop();
   try {
      return mq().Send(kBHTopicBus, MakeSub(mq().Id(), topics), timeout_ms);
   } catch (...) {
      return false;
   }
}
bool BusManager::Start(const int nworker)
bool SocketSubscribe::StartRecv(const TopicDataCB &tdcb, int nworker)
{
   std::lock_guard<std::mutex> guard(mutex_);
   StopNoLock();
   // start
   auto Worker = [&]() {
      while (this->run_) {
         BusManager &self = *this;
         MsgI msg;
         const int timeout_ms = 100;
         if (self.busq_.Recv(msg, timeout_ms)) {
            self.OnMsg(msg);
   auto AsyncRecvProc = [this, tdcb](BHMsg &msg) {
      if (msg.type() == kMsgTypePublish) {
         MsgPub d;
         if (d.ParseFromString(msg.body())) {
            tdcb(d.topic(), d.data());
         }
      } else {
         // ignored, or dropped
      }
   };
   run_.store(true);
   const int n = std::min(nworker, kMaxWorker);
   for (int i = 0; i < n; ++i) {
      workers_.emplace_back(Worker);
   }
   return true;
   return tdcb && Start(AsyncRecvProc, nworker);
}
bool BusManager::Stop()
bool SocketSubscribe::RecvSub(Topic &topic, std::string &data, const int timeout_ms)
{
   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();
         }
   BHMsg msg;
   if (SyncRecv(msg, timeout_ms) && msg.type() == kMsgTypePublish) {
      MsgPub d;
      if (d.ParseFromString(msg.body())) {
         d.mutable_topic()->swap(topic);
         d.mutable_data()->swap(data);
         return true;
      }
      return true;
   }
   return false;
}
void BusManager::OnMsg(MsgI &imsg)
{
   DEFER1(imsg.Release(shm_));
   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));
         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;
      if (!pub.ParseFromString(msg.body())) {
         return;
      }
      auto FindClients = [&](const std::string &topic) {
         Clients dests;
         std::lock_guard<std::mutex> guard(mutex_);
         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;
      };
      auto Dispatch = [&](auto &&send1) {
         const Clients &clients(FindClients(pub.topic()));
         for (auto &cli : clients) {
            send1(cli);
         }
      };
      if (imsg.IsCounted()) {
         Dispatch([&](const MQId &cli) { busq_.Send(cli, imsg, 100); });
      } else {
         MsgI pubmsg;
         if (!pubmsg.MakeRC(shm_, msg)) { return; }
         DEFER1(pubmsg.Release(shm_));
         Dispatch([&](const MQId &cli) { busq_.Send(cli, pubmsg, 100); });
      }
   };
   switch (msg.type()) {
   case kMsgTypeSubscribe: OnSubChange(Sub1); break;
   case kMsgTypeUnsubscribe: OnSubChange(Unsub1); break;
   case kMsgTypePublish: OnPublish(); break;
   default: break;
   }
}
} // namespace bhome_shm
}