| | |
| | | #include "defs.h" |
| | | #include "msg.h" |
| | | #include <chrono> |
| | | #include <condition_variable> |
| | | using namespace std::chrono; |
| | | using namespace std::chrono_literals; |
| | | |
| | | using namespace bhome_msg; |
| | | using namespace bhome_shm; |
| | | |
| | | namespace |
| | | ShmSocket::ShmSocket(Shm &shm, const MQId id, const int len) : |
| | | run_(false), mq_(shm, id, len), alloc_id_(0) { Start(); } |
| | | ShmSocket::ShmSocket(Shm &shm, const bool create_or_else_find, const MQId id, const int len) : |
| | | run_(false), mq_(shm, create_or_else_find, id, len), alloc_id_(0) { Start(); } |
| | | ShmSocket::ShmSocket(int64_t abs_addr, Shm &shm, const MQId id) : |
| | | run_(false), mq_(abs_addr, shm, id), alloc_id_(0) { Start(); } |
| | | |
| | | ShmSocket::~ShmSocket() { Stop(); } |
| | | |
| | | bool ShmSocket::Start(int nworker, const RecvCB &onData, const RawRecvCB &onRaw, const IdleCB &onIdle) |
| | | { |
| | | auto ioProc = [this, onData, onRaw, onIdle]() { |
| | | auto DoSend = [this]() { return send_buffer_.TrySend(mq()); }; |
| | | auto DoRecv = [=] { |
| | | // do not recv if no cb is set. |
| | | if (!onData && per_msg_cbs_->empty() && !onRaw && alloc_cbs_->empty()) { return false; } |
| | | |
| | | } // namespace |
| | | auto onMsgCB = [this, onData](ShmSocket &socket, MsgI &imsg, BHMsgHead &head) { |
| | | RecvCB cb; |
| | | if (per_msg_cbs_->Pick(head.msg_id(), cb)) { |
| | | cb(socket, imsg, head); |
| | | } else if (onData) { |
| | | onData(socket, imsg, head); |
| | | } |
| | | }; |
| | | auto onCmdCB = [this, onRaw](ShmSocket &socket, int64_t val) { |
| | | int cmd = DecodeCmd(val); |
| | | if (cmd == eCmdAllocReply0) { |
| | | int id = (val >> 4) & MaskBits(28); |
| | | RawRecvCB cb; |
| | | if (alloc_cbs_->Pick(id, cb)) { |
| | | cb(socket, val); |
| | | return; |
| | | } |
| | | } |
| | | if (onRaw) { |
| | | onRaw(socket, val); |
| | | } |
| | | }; |
| | | |
| | | //TODO maybe change to base class, each type is a sub class. |
| | | |
| | | ShmSocket::ShmSocket(Type type, bhome_shm::SharedMemory &shm) : |
| | | shm_(shm), type_(type), run_(false) |
| | | { |
| | | switch (type) { |
| | | case eSockBus: mq_.reset(new Queue(kBHBusQueueId, shm_, 1000)); break; |
| | | case eSockRequest: mq_.reset(new Queue(shm_, 12)); break; |
| | | case eSockReply: mq_.reset(new Queue(shm_, 64)); break; |
| | | case eSockSubscribe: mq_.reset(new Queue(shm_, 64)); break; |
| | | case eSockPublish: break; // no recv mq needed |
| | | default: break; |
| | | } |
| | | } |
| | | |
| | | ShmSocket::ShmSocket(Type type) : |
| | | ShmSocket(type, BHomeShm()) {} |
| | | |
| | | ShmSocket::~ShmSocket() |
| | | { |
| | | Stop(); |
| | | } |
| | | |
| | | bool ShmSocket::Publish(const std::string &topic, const void *data, const size_t size, const int timeout_ms) |
| | | { |
| | | if (type_ != eSockPublish) { |
| | | return false; |
| | | } |
| | | assert(!mq_); |
| | | try { |
| | | MsgI imsg; |
| | | if (!imsg.MakeRC(shm_, MakePub(topic, data, size))) { |
| | | auto onRecv = [&](auto &val) { |
| | | if (IsCmd(val)) { |
| | | onCmdCB(*this, val); |
| | | } else { |
| | | MsgI imsg(val); |
| | | DEFER1(imsg.Release()); |
| | | BHMsgHead head; |
| | | if (imsg.ParseHead(head)) { |
| | | onMsgCB(*this, imsg, head); |
| | | } |
| | | } |
| | | }; |
| | | ShmMsgQueue::RawData val = 0; |
| | | for (int i = 0; i < 100; ++i) { |
| | | if (mq().TryRecv(val)) { |
| | | onRecv(val); |
| | | return true; |
| | | } |
| | | } |
| | | return false; |
| | | } |
| | | DEFER1(imsg.Release(shm_)); |
| | | return Queue::Send(shm_, kBHBusQueueId, imsg, timeout_ms); |
| | | } catch (...) { |
| | | return false; |
| | | } |
| | | } |
| | | }; |
| | | |
| | | bool ShmSocket::Subscribe(const std::vector<std::string> &topics, const int timeout_ms) |
| | | { |
| | | if (type_ != eSockSubscribe) { |
| | | return false; |
| | | } |
| | | assert(mq_); |
| | | try { |
| | | return mq_->Send(kBHBusQueueId, MakeSub(mq_->Id(), topics), timeout_ms); |
| | | } catch (...) { |
| | | return false; |
| | | } |
| | | } |
| | | |
| | | bool ShmSocket::StartRaw(const RecvRawCB &onData, int nworker) |
| | | { |
| | | auto CanRecv = [this]() { |
| | | switch (type_) { |
| | | case eSockRequest: |
| | | case eSockReply: |
| | | case eSockBus: |
| | | case eSockSubscribe: |
| | | return true; |
| | | default: |
| | | return false; |
| | | try { |
| | | bool more_to_send = DoSend(); |
| | | bool more_to_recv = DoRecv(); |
| | | if (onIdle) { onIdle(*this); } |
| | | if (!more_to_send && !more_to_recv) { |
| | | robust::QuickSleep(); |
| | | } |
| | | } catch (...) { |
| | | } |
| | | }; |
| | | if (!CanRecv()) { |
| | | return false; |
| | | } |
| | | std::lock_guard<std::mutex> lock(mutex_); |
| | | |
| | | std::lock_guard<std::mutex> lock(mutex_); |
| | | StopNoLock(); |
| | | auto RecvProc = [this, onData]() { |
| | | while (run_) { |
| | | try { |
| | | MsgI imsg; |
| | | DEFER1(imsg.Release(shm_)); |
| | | if (mq_->Recv(imsg, 100)) { onData(imsg); } |
| | | } catch (...) { |
| | | } |
| | | |
| | | auto worker_proc = [this, ioProc]() { |
| | | while (run_) { ioProc(); } |
| | | // try send pending msgs. |
| | | auto end_time = steady_clock::now() + 3s; |
| | | while (send_buffer_.TrySend(mq()) && steady_clock::now() < end_time) { |
| | | // LOG_DEBUG() << "try send pending msgs."; |
| | | } |
| | | }; |
| | | |
| | | run_.store(true); |
| | | for (int i = 0; i < nworker; ++i) { |
| | | workers_.emplace_back(RecvProc); |
| | | workers_.emplace_back(worker_proc); |
| | | } |
| | | return true; |
| | | } |
| | | |
| | | bool ShmSocket::Start(const RecvCB &onData, int nworker) |
| | | { |
| | | return StartRaw([this, onData](MsgI &imsg) { BHMsg m; if (imsg.Unpack(m)) { onData(m); } }, nworker); |
| | | } |
| | | |
| | | bool ShmSocket::StartAsync(int nworker) |
| | | { |
| | | auto AsyncRecvProc = [this](BHMsg &msg) { |
| | | auto Find = [&](RecvCB &cb) { |
| | | std::lock_guard<std::mutex> lock(mutex_); |
| | | const std::string &msgid = msg.msg_id(); |
| | | auto pos = async_cbs_.find(msgid); |
| | | if (pos != async_cbs_.end()) { |
| | | cb.swap(pos->second); |
| | | async_cbs_.erase(pos); |
| | | return true; |
| | | } else { |
| | | return false; |
| | | } |
| | | }; |
| | | |
| | | RecvCB cb; |
| | | if (Find(cb) && cb) { |
| | | cb(msg); |
| | | } |
| | | }; |
| | | |
| | | return Start(AsyncRecvProc, nworker); |
| | | } |
| | | |
| | | bool ShmSocket::Stop() |
| | |
| | | w.join(); |
| | | } |
| | | } |
| | | workers_.clear(); |
| | | return true; |
| | | } |
| | | return false; |
| | | } |
| | | |
| | | bool ShmSocket::AsyncRequest(const void *remote, const void *pmsg, const int timeout_ms, const RecvCB &cb) |
| | | bool ShmSocket::Send(const MQInfo &remote, std::string &&content, const std::string &msg_id, RecvCB &&cb) |
| | | { |
| | | if (type_ != eSockRequest) { |
| | | return false; |
| | | } |
| | | assert(remote && pmsg && !mq_); |
| | | try { |
| | | const BHMsg &msg = *static_cast<const BHMsg *>(pmsg); |
| | | auto RegisterCB = [&]() { |
| | | std::lock_guard<std::mutex> lock(mutex_); |
| | | async_cbs_.emplace(msg.msg_id(), cb); |
| | | }; |
| | | size_t size = content.size(); |
| | | auto OnResult = [content = std::move(content), msg_id, remote, cb = std::move(cb), this](MsgI &msg) mutable { |
| | | if (!msg.Fill(content)) { return false; } |
| | | |
| | | return mq_->Send(*static_cast<const MQId *>(remote), msg, timeout_ms, RegisterCB); |
| | | } catch (...) { |
| | | return false; |
| | | } |
| | | } |
| | | |
| | | bool ShmSocket::SyncRequest(const void *remote, const void *msg, void *result, const int timeout_ms) |
| | | { |
| | | struct State { |
| | | std::mutex mutex; |
| | | std::condition_variable cv; |
| | | bool canceled = false; |
| | | }; |
| | | |
| | | try { |
| | | std::shared_ptr<State> st(new State); |
| | | auto OnRecv = [=](BHMsg &msg) { |
| | | std::unique_lock<std::mutex> lk(st->mutex); |
| | | if (!st->canceled) { |
| | | static_cast<BHMsg *>(result)->Swap(&msg); |
| | | st->cv.notify_one(); |
| | | try { |
| | | if (!cb) { |
| | | Send(remote, msg); |
| | | } else { |
| | | per_msg_cbs_->Store(msg_id, std::move(cb)); |
| | | auto onExpireRemoveCB = [this, msg_id](SendQ::Data const &msg) { |
| | | RecvCB cb_no_use; |
| | | per_msg_cbs_->Pick(msg_id, cb_no_use); |
| | | }; |
| | | Send(remote, msg, onExpireRemoveCB); |
| | | } |
| | | }; |
| | | |
| | | std::unique_lock<std::mutex> lk(st->mutex); |
| | | auto end = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeout_ms); |
| | | if (AsyncRequest(remote, msg, timeout_ms, OnRecv) && st->cv.wait_until(lk, end) == std::cv_status::no_timeout) { |
| | | return true; |
| | | } else { |
| | | st->canceled = true; |
| | | } catch (...) { |
| | | SetLastError(eError, "Send internal error."); |
| | | return false; |
| | | } |
| | | } catch (...) { |
| | | }; |
| | | #if 0 |
| | | // self alloc |
| | | MsgI msg; |
| | | if (msg.Make(size)) { |
| | | DEFER1(msg.Release()); |
| | | return OnResult(msg); |
| | | } |
| | | #else |
| | | // center alloc |
| | | return RequestAlloc(size, OnResult); |
| | | #endif |
| | | } |
| | | |
| | | bool ShmSocket::RequestAlloc(const int64_t size, std::function<void(MsgI &msg)> const &onResult) |
| | | { // 8bit size, 4bit socket index, 16bit proc index, 28bit id, ,4bit cmd+flag |
| | | // LOG_FUNCTION; |
| | | if (node_proc_index_ == -1 || socket_index_ == -1) { |
| | | return false; |
| | | } |
| | | } |
| | | |
| | | bool ShmSocket::QueryRPCTopic(const std::string &topic, bhome::msg::BHAddress &addr, const int timeout_ms) |
| | | { |
| | | BHMsg result; |
| | | const BHMsg &msg = MakeQueryTopic(topic); |
| | | if (SyncRequest(&kBHTopicRPCId, &msg, &result, timeout_ms)) { |
| | | if (result.type() == kMsgTypeQueryTopicReply) { |
| | | DataQueryTopicReply reply; |
| | | if (reply.ParseFromString(result.body())) { |
| | | addr = reply.address(); |
| | | return !addr.mq_id().empty(); |
| | | } |
| | | } |
| | | } |
| | | return false; |
| | | } |
| | | |
| | | bool ShmSocket::RequestRPC(const std::string &topic, const void *data, const size_t size, const int timeout_ms, const RequestResultCB &cb) |
| | | { |
| | | auto Call = [&](const void *remote) { |
| | | const BHMsg &msg(MakeRequest(mq_->Id(), topic, data, size)); |
| | | auto onRecv = [cb](BHMsg &msg) { |
| | | if (msg.type() == kMsgTypeReply) { |
| | | DataReply reply; |
| | | if (reply.ParseFromString(msg.body())) { |
| | | cb(reply.data().data(), reply.data().size()); |
| | | } |
| | | } |
| | | }; |
| | | return AsyncRequest(remote, &msg, timeout_ms, onRecv); |
| | | int id = (++alloc_id_) & MaskBits(28); |
| | | int64_t cmd = (CalcAllocIndex(size) << 52) | |
| | | ((socket_index_ & MaskBits(4)) << 48) | |
| | | ((node_proc_index_ & MaskBits(16)) << 32) | |
| | | (id << 4) | |
| | | EncodeCmd(eCmdAllocRequest0); |
| | | auto rawCB = [onResult](ShmSocket &sock, int64_t &val) { |
| | | MsgI msg((val >> 32) & MaskBits(31)); |
| | | DEFER1(msg.Release()); |
| | | onResult(msg); |
| | | return true; |
| | | }; |
| | | |
| | | try { |
| | | BHAddress addr; |
| | | if (QueryRPCTopic(topic, addr, timeout_ms)) { |
| | | return Call(addr.mq_id().data()); |
| | | } |
| | | } catch (...) { |
| | | return false; |
| | | } |
| | | } |
| | | alloc_cbs_->Store(id, std::move(rawCB)); |
| | | auto onExpireRemoveCB = [this, id](SendQ::Data const &msg) { |
| | | RawRecvCB cb_no_use; |
| | | alloc_cbs_->Pick(id, cb_no_use); |
| | | }; |
| | | |
| | | bool ShmSocket::RequestRPC(const std::string &topic, const void *data, const size_t size, const int timeout_ms, std::string &out) |
| | | { |
| | | try { |
| | | BHAddress addr; |
| | | if (QueryRPCTopic(topic, addr, timeout_ms)) { |
| | | const BHMsg &msg(MakeRequest(mq_->Id(), topic, data, size)); |
| | | BHMsg reply; |
| | | if (SyncRequest(addr.mq_id().data(), &msg, &reply, timeout_ms) && reply.type() == kMsgTypeReply) { |
| | | DataReply dr; |
| | | if (dr.ParseFromString(msg.body())) { |
| | | dr.mutable_data()->swap(out); |
| | | return true; |
| | | } |
| | | } |
| | | } |
| | | } catch (...) { |
| | | return false; |
| | | } |
| | | } |
| | | return Send(BHTopicCenterAddress(), cmd, onExpireRemoveCB); |
| | | } |