#pragma once #include #include #include #include #include #include #include #include #include #include #include namespace Void::EventBus { // ── EventBus // ────────────────────────────────────────────────────────────────── // Publish/subscribe bus keyed by event type. // // Mode::Sync (default) handlers run inline on the publisher's thread // inside // publish() — the original zero-overhead behavior. // Mode::Async publish() snapshots the handlers and a copy of // the // event onto an owned worker thread, so slow // handlers (network / DB I/O) never block the // publisher. flush() waits for everything submitted // before the call. // // In Sync mode the bus is not thread-safe (use external locking if shared). // In Async mode publish/subscribe/flush are safe to call from any thread. enum class Mode { Sync, Async }; class EventBus { public: using HandlerId = std::size_t; explicit EventBus(Mode mode = Mode::Sync) : mode_(mode) { if (mode_ == Mode::Async) { worker_ = std::thread([this] { run(); }); } } ~EventBus() { if (mode_ == Mode::Async) { { std::unique_lock lock{mu_}; stop_ = true; } cv_.notify_all(); worker_.join(); } } EventBus(const EventBus&) = delete; EventBus& operator=(const EventBus&) = delete; EventBus(EventBus&&) = delete; EventBus& operator=(EventBus&&) = delete; // Subscribe to events of type Event. Returns a HandlerId for // unsubscription. template HandlerId subscribe(std::function handler) { std::unique_lock lock{mu_}; const auto key = std::type_index{typeid(Event)}; const HandlerId id = next_id_++; handlers_[key].push_back( Entry{id, [h = std::move(handler)](const std::any& ev) { h(std::any_cast(ev)); }}); return id; } // Move-only RAII handle for a subscription: unsubscribes on // destruction (or reset()). Must not outlive the bus it came // from — the bus is non-movable, so tie the Subscription's // lifetime to a scope the bus outlives. class Subscription { public: Subscription() = default; Subscription(Subscription&& other) noexcept : bus_(other.bus_), id_(other.id_) { other.bus_ = nullptr; } Subscription& operator=(Subscription&& other) noexcept { if (this != &other) { reset(); bus_ = other.bus_; id_ = other.id_; other.bus_ = nullptr; } return *this; } Subscription(const Subscription&) = delete; Subscription& operator=(const Subscription&) = delete; ~Subscription() { reset(); } // Unsubscribe now; safe to call repeatedly. void reset() { if (bus_ != nullptr) { bus_->unsubscribe(id_); bus_ = nullptr; } } [[nodiscard]] explicit operator bool() const noexcept { return bus_ != nullptr; } private: friend class EventBus; Subscription(EventBus* bus, HandlerId id) : bus_(bus), id_(id) { } EventBus* bus_ = nullptr; HandlerId id_ = 0; }; // Subscribe with automatic unsubscription: the returned handle // removes the handler when it goes out of scope. Suits handlers // owned by components (plugins, services) whose lifetime is // shorter than the bus. template [[nodiscard]] Subscription subscribe_scoped(std::function handler) { return Subscription{this, subscribe(std::move(handler))}; } // Publish an event to all subscribers of its type. template void publish(const Event& event) { const auto key = std::type_index{typeid(Event)}; if (mode_ == Mode::Sync) { const auto it = handlers_.find(key); if (it == handlers_.end()) { return; } for (const auto& e : it->second) { e.fn(event); } return; } // Async: snapshot the current handlers and queue a dispatch // carrying a copy of the event, so later unsubscribe()s don't // affect this publish. std::unique_lock lock{mu_}; const auto it = handlers_.find(key); if (it == handlers_.end()) { return; } std::vector> snapshot; snapshot.reserve(it->second.size()); for (const auto& e : it->second) { snapshot.push_back(e.fn); } tasks_.push([snap = std::move(snapshot), ev = std::any{event}] { for (const auto& fn : snap) { fn(ev); } }); ++enqueued_; lock.unlock(); cv_.notify_one(); } // Async only: block until every event published before this call // has been dispatched. A no-op in Sync mode (delivery already // happened in publish()). void flush() { if (mode_ != Mode::Async) { return; } std::unique_lock lock{mu_}; const auto target = enqueued_; done_cv_.wait(lock, [&] { return processed_ >= target; }); } // Unsubscribe by id. O(n) per event type — acceptable for small // handler counts. void unsubscribe(HandlerId id) { std::unique_lock lock{mu_}; for (auto& [key, list] : handlers_) { const auto before = list.size(); std::erase_if(list, [id](const Entry& e) { return e.id == id; }); if (list.size() != before) { return; } } } // Remove all handlers for a given event type. template void clear() { std::unique_lock lock{mu_}; handlers_.erase(std::type_index{typeid(Event)}); } void clear_all() { std::unique_lock lock{mu_}; handlers_.clear(); } template [[nodiscard]] std::size_t subscriber_count() const { std::unique_lock lock{mu_}; const auto it = handlers_.find(std::type_index{typeid(Event)}); return it == handlers_.end() ? 0 : it->second.size(); } [[nodiscard]] Mode mode() const noexcept { return mode_; } private: struct Entry { HandlerId id; std::function fn; }; void run() { for (;;) { std::function task; { std::unique_lock lock{mu_}; cv_.wait(lock, [this] { return stop_ || !tasks_.empty(); }); if (stop_ && tasks_.empty()) { return; } task = std::move(tasks_.front()); tasks_.pop(); } task(); { std::unique_lock lock{mu_}; ++processed_; } done_cv_.notify_all(); } } Mode mode_; std::unordered_map> handlers_; HandlerId next_id_{1}; mutable std::mutex mu_; // Async machinery (unused in Sync mode). std::thread worker_; std::queue> tasks_; std::condition_variable cv_; std::condition_variable done_cv_; std::uint64_t enqueued_{0}; std::uint64_t processed_{0}; bool stop_{false}; }; } // namespace Void::EventBus