#include "TablePublisher.h" #include "lib/quickbus/core/Advertisement.h" #include "lib/quickbus/core/LocalNode.h" #include "lib/quickbus/core/TableID.h" #include "lib/quickbus/core/SubscriptionID.h" #include "lib/quickbus/message_model/merge_updates.h" #include "lib/utils/bts_assert.h" #include namespace bts { namespace qbus { struct TablePublisher::PublisherImp : LocalNode { PublisherImp(Quickbus &qb,Topic const &t) : LocalNode(qb), my_table_id(make_table_id()), topic(t), sub_id(null_subscription_id()), synopsis(), has_synopsis(false) {} void start() { async_register(); async_invoke([this] () { Advertisement ad; ad.topic = topic; ad.maintain_synopsis = true; sync_advertise(my_table_id,ad); }); } void stop () {async_unregister();} void publish(std::shared_ptr const &changes) { async_invoke([this,changes] () { has_synopsis = true; update_synopsis(*changes,&synopsis); if (sub_id != null_subscription_id()) sync_notify(my_table_id,sub_id,*changes); }); } void on_subscribe (TableID const&tid, SubscriptionID const&sid) override { bts_assert (on_qb_thread()); bts_assert(tid == my_table_id); bts_assert(sid != null_subscription_id()); // we do this asynchrously because we want to avoid reentry into the router async_invoke([this,sid] () { bts_assert(sub_id == null_subscription_id()); sub_id = sid; if (has_synopsis) { Update update; get_update_from_synopsis(synopsis,&update); sync_notify(my_table_id,sub_id,update); } }); } void on_unsubscribe (TableID const&tid) override { bts_assert (on_qb_thread()); bts_assert(tid == my_table_id); // since subscribe is asynchronous this must be as // well. Otherwise the subscribe call could be handled out of // order with unsubscribe. async_invoke([this] () { bts_assert(sub_id != null_subscription_id()); sub_id = null_subscription_id(); }); } const TableID my_table_id; const Topic topic; SubscriptionID sub_id; std::unordered_map synopsis; bool has_synopsis; }; TablePublisher::TablePublisher () : pub_imp() {} TablePublisher::TablePublisher (TablePublisher &&src) : pub_imp (std::move(src.pub_imp)) {} TablePublisher::TablePublisher(Quickbus &qb,Topic const &t) : pub_imp (new PublisherImp(qb,t)) {pub_imp->start();} TablePublisher::~TablePublisher () {disconnect();} void TablePublisher::disconnect() { if (!is_null()) { pub_imp->stop(); pub_imp.reset(); } } #ifndef WIN32 void TablePublisher::publish (std::initializer_list const&changes) {publish(std::vector (changes));} #endif void TablePublisher::publish (std::vector const &changes) { bts_assert (!is_null()); auto v = std::make_shared> (changes); pub_imp->publish(v); } void TablePublisher::publish (std::vector &&changes) { bts_assert (!is_null()); auto v = std::make_shared> (std::move(changes)); pub_imp->publish(v); } TablePublisher&TablePublisher::operator=(TablePublisher &&src) { disconnect(); pub_imp = std::move(src.pub_imp); return *this; } bool TablePublisher::is_null() const {return !pub_imp;} }}