From ef85ce07b7ba42245f847583661497df7fa2c2b4 Mon Sep 17 00:00:00 2001 From: faumaray Date: Tue, 1 Dec 2026 10:27:50 +0300 Subject: [PATCH] feat(async): add EventBus injected/joined lifecycle and Observable reentrancy queue (M-ASYNC-05) --- include/Void/Async/EventBus.hpp | 1335 ++++++++++++++--- include/Void/Async/Observable.hpp | 273 +++- tests/standalone/Async/EventBusJoin.cpp | 600 ++++++++ .../standalone/Async/ObservableReentrancy.cpp | 236 +++ 4 files changed, 2156 insertions(+), 288 deletions(-) create mode 100644 tests/standalone/Async/EventBusJoin.cpp create mode 100644 tests/standalone/Async/ObservableReentrancy.cpp diff --git a/include/Void/Async/EventBus.hpp b/include/Void/Async/EventBus.hpp index 276892e..cd78e77 100644 --- a/include/Void/Async/EventBus.hpp +++ b/include/Void/Async/EventBus.hpp @@ -1,286 +1,1149 @@ #pragma once -#include +#include +#include +#include +#include + +#include +#include #include +#include #include #include +#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. +using HandlerId = std::uint64_t; - enum class Mode { Sync, Async }; +enum class Mode { Sync, Async, Injected }; - class EventBus - { - public: +struct BusOptions { + std::size_t max_subscriptions{1024}; + std::size_t max_admitted_dispatches{1024}; + std::function error_sink{}; +}; - using HandlerId = std::size_t; +namespace detail +{ - explicit EventBus(Mode mode = Mode::Sync) : mode_(mode) - { - if (mode_ == Mode::Async) { - worker_ = std::thread([this] { run(); }); - } - } +struct DispatchFrame { + const void* core{nullptr}; + const void* entry{nullptr}; + const DispatchFrame* prev{nullptr}; - ~EventBus() - { - if (mode_ == Mode::Async) { - { - std::unique_lock lock{mu_}; - stop_ = true; - } - cv_.notify_all(); - worker_.join(); - } - } + [[nodiscard]] static inline const DispatchFrame*& head() noexcept + { + thread_local const DispatchFrame* slot = nullptr; + return slot; + } +}; - EventBus(const EventBus&) = delete; - EventBus& operator=(const EventBus&) = delete; - EventBus(EventBus&&) = delete; - EventBus& operator=(EventBus&&) = delete; +class DispatchGuard +{ +public: + DispatchGuard(const void* core, const void* entry) noexcept + : frame_{core, entry, DispatchFrame::head()} + { + DispatchFrame::head() = &frame_; + } - // 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; - } + ~DispatchGuard() + { + DispatchFrame::head() = frame_.prev; + } - // 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: + DispatchGuard(const DispatchGuard&) = delete; + DispatchGuard& operator=(const DispatchGuard&) = delete; - Subscription() = default; +private: + DispatchFrame frame_; +}; - Subscription(Subscription&& other) noexcept - : bus_(other.bus_), id_(other.id_) - { - other.bus_ = nullptr; - } +[[nodiscard]] inline bool is_on_bus_callback(const void* core) noexcept +{ + for (const auto* f = DispatchFrame::head(); f != nullptr; f = f->prev) { + if (f->core == core) { + return true; + } + } + return false; +} - Subscription& operator=(Subscription&& other) noexcept - { - if (this != &other) { - reset(); - bus_ = other.bus_; - id_ = other.id_; - other.bus_ = nullptr; - } - return *this; - } +[[nodiscard]] inline bool is_on_entry_callback(const void* entry) noexcept +{ + for (const auto* f = DispatchFrame::head(); f != nullptr; f = f->prev) { + if (f->entry == entry) { + return true; + } + } + return false; +} - Subscription(const Subscription&) = delete; - Subscription& operator=(const Subscription&) = delete; +[[nodiscard]] inline std::size_t bus_callback_depth_on_thread( + const void* core) noexcept +{ + std::size_t count = 0; + for (const auto* f = DispatchFrame::head(); f != nullptr; f = f->prev) { + if (f->core == core) { + ++count; + } + } + return count; +} - ~Subscription() { reset(); } +struct SubEntry { + HandlerId id{0}; + std::type_index type{typeid(void)}; + std::function handler{}; + bool active{true}; + bool purged{false}; + std::size_t in_flight{0}; +}; - // Unsubscribe now; safe to call repeatedly. - void reset() - { - if (bus_ != nullptr) { - bus_->unsubscribe(id_); - bus_ = nullptr; - } - } +struct QueuedRecipient { + std::shared_ptr entry{}; + std::function legacy_fn{}; +}; - [[nodiscard]] explicit operator bool() const noexcept - { - return bus_ != nullptr; - } +struct AsyncDelivery { + std::shared_ptr event{}; + std::vector recipients{}; +}; - private: +struct DispatchCoroutine { + struct promise_type { + DispatchCoroutine get_return_object() noexcept + { + return DispatchCoroutine{ + std::coroutine_handle::from_promise(*this)}; + } + std::suspend_always initial_suspend() noexcept { return {}; } + std::suspend_never final_suspend() noexcept { return {}; } + void return_void() noexcept {} + void unhandled_exception() noexcept {} + }; - friend class EventBus; + std::coroutine_handle handle{}; +}; - Subscription(EventBus* bus, HandlerId id) - : bus_(bus), id_(id) - { - } +struct BusCore : std::enable_shared_from_this { + Mode mode{Mode::Sync}; + BusOptions options{}; + Void::Async::Executor* executor{nullptr}; + bool invalid_injected{false}; - EventBus* bus_ = nullptr; - HandlerId id_ = 0; - }; + mutable std::mutex mu{}; + std::condition_variable cv{}; + std::condition_variable done_cv{}; - // 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))}; - } + std::unordered_map>> + handlers{}; + std::unordered_map> by_id{}; + HandlerId next_id{1}; - // 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; - } + bool closed{false}; + std::size_t total_in_flight{0}; + std::size_t admitted_dispatches{0}; + std::uint64_t enqueued{0}; + std::uint64_t processed{0}; + std::atomic callback_failures{0}; - // 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(); - } + // Mode::Async worker state. + std::thread worker{}; + std::deque async_queue{}; + bool stop_worker{false}; - // 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; }); - } + BusCore(Mode m, BusOptions opts, Void::Async::Executor* exec) + : mode{m} + , options{std::move(opts)} + , executor{exec} + , invalid_injected{m == Mode::Injected && exec == nullptr} + { + if (invalid_injected) { + closed = true; + } + } - // 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; - } - } - } + ~BusCore() + { + if (worker.joinable()) { + if (std::this_thread::get_id() == worker.get_id()) { + worker.detach(); + } else { + worker.join(); + } + } + } - // Remove all handlers for a given event type. - template void clear() - { - std::unique_lock lock{mu_}; - handlers_.erase(std::type_index{typeid(Event)}); - } + [[nodiscard]] bool is_self_worker() const noexcept + { + if (mode == Mode::Async && worker.joinable() && + std::this_thread::get_id() == worker.get_id()) { + return true; + } + if (mode == Mode::Injected && executor != nullptr && + executor->is_executor_thread()) { + return true; + } + return false; + } - void clear_all() - { - std::unique_lock lock{mu_}; - handlers_.clear(); - } + void invoke_error_sink(std::exception_ptr ex) noexcept + { + callback_failures.fetch_add(1, std::memory_order_relaxed); + std::function sink; + { + std::lock_guard lk{mu}; + sink = options.error_sink; + } + if (sink) { + try { + sink(std::move(ex)); + } catch (...) { + callback_failures.fetch_add(1, std::memory_order_relaxed); + } + } + } - 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(); - } + void release_entry_locked(const std::shared_ptr& entry, + std::function& out_fn) + { + if (entry->active) { + entry->active = false; + auto it = handlers.find(entry->type); + if (it != handlers.end()) { + auto& vec = it->second; + vec.erase( + std::remove_if(vec.begin(), + vec.end(), + [&](const std::shared_ptr& e) { + return e.get() == entry.get(); + }), + vec.end()); + } + by_id.erase(entry->id); + } + if (entry->in_flight == 0 && entry->handler) { + out_fn = std::move(entry->handler); + } + } - [[nodiscard]] Mode mode() const noexcept { return mode_; } + [[nodiscard]] Void::Result::Result join_entry( + const std::shared_ptr& entry) + { + if (is_on_entry_callback(entry.get())) { + return std::unexpected{Void::Async::make_async_error( + Void::Async::AsyncErrorCode::self_join, + "Subscription::close_and_join called from inside its own callback")}; + } - private: + std::function released_fn; + std::vector> purged_fns; + { + std::unique_lock lk{mu}; + entry->purged = true; + for (auto& item : async_queue) { + for (auto& rec : item.recipients) { + if (rec.entry.get() == entry.get() && rec.legacy_fn) { + purged_fns.push_back(std::move(rec.legacy_fn)); + } + } + } + release_entry_locked(entry, released_fn); + // Drop purged copies before releasing lock only outside lock below. + lk.unlock(); + purged_fns.clear(); + released_fn = {}; + lk.lock(); + done_cv.wait(lk, [&] { return entry->in_flight == 0; }); + if (entry->handler) { + released_fn = std::move(entry->handler); + } + } + released_fn = {}; + return {}; + } - struct Entry { - HandlerId id; - std::function fn; - }; + void run_worker() + { + for (;;) { + AsyncDelivery item; + { + std::unique_lock lk{mu}; + cv.wait(lk, [&] { + return stop_worker || closed || !async_queue.empty(); + }); + if (stop_worker || closed || async_queue.empty()) { + if (stop_worker || closed) { + return; + } + continue; + } + item = std::move(async_queue.front()); + async_queue.pop_front(); + } - 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(); - } - } + const void* ev_raw = item.event.get(); + for (auto& rec : item.recipients) { + std::function fn; + { + std::lock_guard lk{mu}; + if (closed || rec.entry->purged) { + rec.legacy_fn = {}; + continue; + } + if (!rec.legacy_fn && !rec.entry->active) { + continue; + } + fn = rec.legacy_fn ? std::move(rec.legacy_fn) + : rec.entry->handler; + if (!fn) { + continue; + } + ++rec.entry->in_flight; + ++total_in_flight; + } - Mode mode_; - std::unordered_map> handlers_; - HandlerId next_id_{1}; + { + DispatchGuard dg{this, rec.entry.get()}; + try { + fn(ev_raw); + } catch (...) { + invoke_error_sink(std::current_exception()); + } + } + fn = {}; - 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}; - }; + std::function cleanup_fn; + { + std::lock_guard lk{mu}; + --rec.entry->in_flight; + --total_in_flight; + if (!rec.entry->active && rec.entry->in_flight == 0 && + rec.entry->handler) { + cleanup_fn = std::move(rec.entry->handler); + } + } + done_cv.notify_all(); + cleanup_fn = {}; + } + + // Destroy event payload and recipient handles before completion notify. + item.recipients.clear(); + item.event.reset(); + + { + std::lock_guard lk{mu}; + if (admitted_dispatches > 0) { + --admitted_dispatches; + } + ++processed; + } + done_cv.notify_all(); + } + } + + void start_async_worker() + { + auto self = shared_from_this(); + worker = std::thread([s = std::move(self)]() { s->run_worker(); }); + } + + void close_from_destructor() noexcept + { + std::vector> to_drop; + std::deque queued_to_drop; + Void::Async::ManualExecutor* manual = nullptr; + { + std::lock_guard lk{mu}; + closed = true; + stop_worker = true; + for (auto& [id, e] : by_id) { + e->active = false; + e->purged = true; + if (e->in_flight == 0 && e->handler) { + to_drop.push_back(std::move(e->handler)); + } + } + handlers.clear(); + by_id.clear(); + queued_to_drop.swap(async_queue); + if (admitted_dispatches >= queued_to_drop.size()) { + admitted_dispatches -= queued_to_drop.size(); + } else { + admitted_dispatches = 0; + } + processed += queued_to_drop.size(); + if (mode == Mode::Injected && executor != nullptr && + !is_on_bus_callback(this)) { + manual = dynamic_cast(executor); + } + } + cv.notify_all(); + done_cv.notify_all(); + to_drop.clear(); + queued_to_drop.clear(); + + if (mode == Mode::Async && worker.joinable()) { + if (std::this_thread::get_id() != worker.get_id()) { + worker.join(); + } + } + + if (manual != nullptr) { + for (;;) { + std::size_t pending = 0; + { + std::lock_guard lk{mu}; + pending = admitted_dispatches; + } + if (pending == 0) { + break; + } + if (manual->drain() == 0) { + break; + } + } + } + + // Wait for callbacks running on OTHER threads, excluding current thread's depth. + { + std::unique_lock lk{mu}; + const std::size_t self_depth = bus_callback_depth_on_thread(this); + done_cv.wait(lk, [&] { + return total_in_flight <= self_depth; + }); + } + } +}; + +inline DispatchCoroutine make_injected_dispatch( + std::shared_ptr core, + std::shared_ptr event_ptr, + std::vector> snapshot) +{ + const void* ev_raw = event_ptr.get(); + for (auto& entry : snapshot) { + std::function fn; + { + std::lock_guard lk{core->mu}; + if (core->closed || !entry->active) { + continue; + } + fn = entry->handler; + if (!fn) { + continue; + } + ++entry->in_flight; + ++core->total_in_flight; + } + + { + DispatchGuard dg{core.get(), entry.get()}; + try { + fn(ev_raw); + } catch (...) { + core->invoke_error_sink(std::current_exception()); + } + } + fn = {}; + + std::function cleanup_fn; + { + std::lock_guard lk{core->mu}; + --entry->in_flight; + --core->total_in_flight; + if (!entry->active && entry->in_flight == 0 && entry->handler) { + cleanup_fn = std::move(entry->handler); + } + } + core->done_cv.notify_all(); + cleanup_fn = {}; + } + + snapshot.clear(); + event_ptr.reset(); + + { + std::lock_guard lk{core->mu}; + if (core->admitted_dispatches > 0) { + --core->admitted_dispatches; + } + ++core->processed; + } + core->done_cv.notify_all(); + co_return; +} + +} // namespace detail + +/// Type-safe in-process publish/subscribe event bus supporting synchronous, +/// private-worker asynchronous, and externally injected executor dispatch. +/// Destroying an active bus closes unstarted deliveries immediately and waits +/// only for callbacks running on other threads. +class EventBus +{ +public: + class Subscription + { + public: + Subscription() noexcept = default; + ~Subscription() noexcept { reset(); } + + Subscription(Subscription&& other) noexcept + : core_(std::move(other.core_)) + , entry_(std::move(other.entry_)) + { + } + + Subscription& operator=(Subscription&& other) noexcept + { + if (this != &other) { + reset(); + core_ = std::move(other.core_); + entry_ = std::move(other.entry_); + } + return *this; + } + + Subscription(const Subscription&) = delete; + Subscription& operator=(const Subscription&) = delete; + + void reset() noexcept + { + if (core_ && entry_) { + std::function dropped; + { + std::lock_guard lk{core_->mu}; + core_->release_entry_locked(entry_, dropped); + } + dropped = {}; + } + entry_.reset(); + core_.reset(); + } + + /// Suppresses unstarted deliveries (including queued Async copies) and + /// blocks until any active in-flight callback finishes and captured + /// handler state is released. + [[nodiscard]] Void::Result::Result close_and_join() + { + if (!core_ || !entry_) { + return {}; + } + auto res = core_->join_entry(entry_); + if (res.has_value()) { + entry_.reset(); + core_.reset(); + } + return res; + } + + [[nodiscard]] explicit operator bool() const noexcept + { + return core_ && entry_; + } + + [[nodiscard]] HandlerId id() const noexcept + { + return entry_ ? entry_->id : 0; + } + + private: + friend class EventBus; + Subscription(std::shared_ptr core, + std::shared_ptr entry) noexcept + : core_(std::move(core)) + , entry_(std::move(entry)) + { + } + + std::shared_ptr core_{}; + std::shared_ptr entry_{}; + }; + + explicit EventBus(Mode mode = Mode::Sync, BusOptions options = {}) + : core_(std::make_shared( + mode, std::move(options), nullptr)) + { + if (core_->mode == Mode::Async) { + core_->start_async_worker(); + } + } + + explicit EventBus(Void::Async::Executor& executor, BusOptions options = {}) + : core_(std::make_shared( + Mode::Injected, std::move(options), &executor)) + { + } + + ~EventBus() noexcept + { + if (core_) { + core_->close_from_destructor(); + } + } + + EventBus(const EventBus&) = delete; + EventBus& operator=(const EventBus&) = delete; + EventBus(EventBus&&) = delete; + EventBus& operator=(EventBus&&) = delete; + + template + [[nodiscard]] Void::Result::Result + try_subscribe(std::function fn) + { + if (!fn) { + return std::unexpected{Void::Async::make_async_error( + Void::Async::AsyncErrorCode::invalid_argument, + "EventBus subscriber callback must not be empty")}; + } + std::shared_ptr entry; + { + std::lock_guard lk{core_->mu}; + if (core_->invalid_injected) { + return std::unexpected{Void::Async::make_async_error( + Void::Async::AsyncErrorCode::invalid_argument, + "Mode::Injected requires an Executor")}; + } + if (core_->closed) { + return std::unexpected{Void::Async::make_async_error( + Void::Async::AsyncErrorCode::closed, + "EventBus is closed")}; + } + if (core_->by_id.size() >= core_->options.max_subscriptions) { + return std::unexpected{Void::Async::make_async_error( + Void::Async::AsyncErrorCode::overloaded, + "EventBus max_subscriptions reached")}; + } + const HandlerId id = core_->next_id++; + const auto type_idx = std::type_index(typeid(Event)); + entry = std::make_shared(); + entry->id = id; + entry->type = type_idx; + entry->handler = [f = std::move(fn)](const void* raw) { + f(*static_cast(raw)); + }; + core_->handlers[type_idx].push_back(entry); + core_->by_id.emplace(id, entry); + } + return Subscription{core_, std::move(entry)}; + } + + template + HandlerId subscribe(std::function fn) + { + auto res = try_subscribe(std::move(fn)); + if (!res.has_value()) { + return 0; + } + const HandlerId id = res->id(); + res->entry_.reset(); + res->core_.reset(); + return id; + } + + template + [[nodiscard]] Subscription subscribe_scoped( + std::function fn) + { + auto res = try_subscribe(std::move(fn)); + if (!res.has_value()) { + return {}; + } + return std::move(*res); + } + + template + [[nodiscard]] Void::Result::Result try_publish(const Event& event) + { + auto core = core_; + const auto type_idx = std::type_index(typeid(Event)); + + if (core->mode == Mode::Sync) { + std::vector> snapshot; + { + std::lock_guard lk{core->mu}; + if (core->closed) { + return std::unexpected{Void::Async::make_async_error( + Void::Async::AsyncErrorCode::closed, + "EventBus is closed")}; + } + auto it = core->handlers.find(type_idx); + if (it != core->handlers.end()) { + snapshot = it->second; + } + } + const void* ev_raw = std::addressof(event); + for (const auto& entry : snapshot) { + std::function fn; + { + std::lock_guard lk{core->mu}; + if (core->closed || !entry->active) { + continue; + } + fn = entry->handler; + if (!fn) { + continue; + } + ++entry->in_flight; + ++core->total_in_flight; + } + + struct EntryExitGuard { + std::shared_ptr core; + const std::shared_ptr& entry; + std::function& fn_ref; + ~EntryExitGuard() + { + fn_ref = {}; + std::function cleanup; + { + std::lock_guard lk{core->mu}; + --entry->in_flight; + --core->total_in_flight; + if (!entry->active && entry->in_flight == 0 && + entry->handler) { + cleanup = std::move(entry->handler); + } + } + core->done_cv.notify_all(); + cleanup = {}; + } + } exit_guard{core, entry, fn}; + + detail::DispatchGuard dg{core.get(), entry.get()}; + fn(ev_raw); + } + return {}; + } + + if (core_->invalid_injected) { + return std::unexpected{Void::Async::make_async_error( + Void::Async::AsyncErrorCode::invalid_argument, + "Mode::Injected requires an Executor")}; + } + + if (core_->mode == Mode::Async) { + std::vector recipients; + { + std::lock_guard lk{core_->mu}; + if (core_->closed) { + return std::unexpected{Void::Async::make_async_error( + Void::Async::AsyncErrorCode::closed, + "EventBus is closed")}; + } + if (core_->admitted_dispatches >= + core_->options.max_admitted_dispatches) { + return std::unexpected{Void::Async::make_async_error( + Void::Async::AsyncErrorCode::overloaded, + "EventBus max_admitted_dispatches reached")}; + } + auto it = core_->handlers.find(type_idx); + if (it != core_->handlers.end()) { + recipients.reserve(it->second.size()); + for (const auto& e : it->second) { + if (e->active && e->handler) { + recipients.push_back( + detail::QueuedRecipient{e, e->handler}); + } + } + } + ++core_->admitted_dispatches; + ++core_->enqueued; + } + + std::shared_ptr ev_copy; + try { + ev_copy = std::make_shared(event); + } catch (...) { + { + std::lock_guard lk{core_->mu}; + if (core_->admitted_dispatches > 0) { + --core_->admitted_dispatches; + } + ++core_->processed; + } + core_->done_cv.notify_all(); + throw; + } + + { + std::lock_guard lk{core_->mu}; + if (core_->closed) { + if (core_->admitted_dispatches > 0) { + --core_->admitted_dispatches; + } + ++core_->processed; + core_->done_cv.notify_all(); + return std::unexpected{Void::Async::make_async_error( + Void::Async::AsyncErrorCode::closed, + "EventBus is closed")}; + } + core_->async_queue.push_back(detail::AsyncDelivery{ + std::move(ev_copy), std::move(recipients)}); + } + core_->cv.notify_one(); + return {}; + } + + // Mode::Injected + std::vector> snapshot; + { + std::lock_guard lk{core_->mu}; + if (core_->closed) { + return std::unexpected{Void::Async::make_async_error( + Void::Async::AsyncErrorCode::closed, + "EventBus is closed")}; + } + if (core_->admitted_dispatches >= + core_->options.max_admitted_dispatches) { + return std::unexpected{Void::Async::make_async_error( + Void::Async::AsyncErrorCode::overloaded, + "EventBus max_admitted_dispatches reached")}; + } + auto it = core_->handlers.find(type_idx); + if (it != core_->handlers.end()) { + snapshot = it->second; + } + ++core_->admitted_dispatches; + ++core_->enqueued; + } + + auto rollback_bus_admission = [&]() { + { + std::lock_guard lk{core_->mu}; + if (core_->admitted_dispatches > 0) { + --core_->admitted_dispatches; + } + ++core_->processed; + } + core_->done_cv.notify_all(); + }; + + auto* exec = core_->executor; + const bool use_reserved = exec->supports_reservation(); + if (use_reserved) { + if (auto r = exec->try_reserve_slot(); !r.has_value()) { + rollback_bus_admission(); + return std::unexpected{Void::Async::make_async_error(r.error())}; + } + } + + std::shared_ptr ev_copy; + detail::DispatchCoroutine coro{}; + try { + ev_copy = std::make_shared(event); + coro = detail::make_injected_dispatch( + core_, std::move(ev_copy), std::move(snapshot)); + } catch (...) { + if (coro.handle) { + coro.handle.destroy(); + } + if (use_reserved) { + exec->release_reserved(); + } + rollback_bus_admission(); + throw; + } + + if (use_reserved) { + try { + exec->commit_reserved(coro.handle); + } catch (...) { + coro.handle.destroy(); + exec->release_reserved(); + rollback_bus_admission(); + return std::unexpected{Void::Async::make_async_error( + Void::Async::AsyncErrorCode::overloaded, + "Executor commit_reserved failed")}; + } + } else { + auto post_res = exec->try_post(coro.handle); + if (!post_res.has_value()) { + coro.handle.destroy(); + rollback_bus_admission(); + return std::unexpected{ + Void::Async::make_async_error(post_res.error())}; + } + } + + return {}; + } + + template + void publish(const Event& event) + { + (void)try_publish(event); + } + + /// Blocks until previously admitted deliveries finish. Rejects executor + /// and callback threads with self_join, and ManualExecutor with + /// invalid_argument. + [[nodiscard]] Void::Result::Result flush_blocking() + { + if (detail::is_on_bus_callback(core_.get()) || + core_->is_self_worker()) { + return std::unexpected{Void::Async::make_async_error( + Void::Async::AsyncErrorCode::self_join, + "EventBus::flush_blocking cannot be called from an executor or callback thread")}; + } + if (core_->invalid_injected) { + return std::unexpected{Void::Async::make_async_error( + Void::Async::AsyncErrorCode::invalid_argument, + "EventBus has no Executor")}; + } + if (core_->mode == Mode::Sync) { + return {}; + } + if (core_->mode == Mode::Injected && + !core_->executor->has_background_workers()) { + return std::unexpected{Void::Async::make_async_error( + Void::Async::AsyncErrorCode::invalid_argument, + "EventBus::flush_blocking requires a background executor; use flush_pumping")}; + } + std::unique_lock lk{core_->mu}; + const auto target = core_->enqueued; + core_->done_cv.wait(lk, [&] { + return core_->processed >= target || + (core_->closed && core_->total_in_flight == 0 && + core_->admitted_dispatches == 0); + }); + return {}; + } + + /// Pumps a ManualExecutor until previously admitted deliveries finish. + [[nodiscard]] Void::Result::Result + flush_pumping(Void::Async::ManualExecutor& manual) + { + if (core_->mode != Mode::Injected || core_->executor != &manual) { + return std::unexpected{Void::Async::make_async_error( + Void::Async::AsyncErrorCode::invalid_argument, + "EventBus::flush_pumping requires a matching ManualExecutor")}; + } + std::uint64_t target = 0; + { + std::lock_guard lk{core_->mu}; + target = core_->enqueued; + } + for (;;) { + { + std::lock_guard lk{core_->mu}; + if (core_->processed >= target || + (core_->closed && core_->total_in_flight == 0 && + core_->admitted_dispatches == 0)) { + return {}; + } + } + if (manual.drain() == 0) { + std::lock_guard lk{core_->mu}; + if (core_->processed >= target || + (core_->closed && core_->total_in_flight == 0 && + core_->admitted_dispatches == 0)) { + return {}; + } + std::this_thread::yield(); + } + } + } + + void flush() + { + if (core_->mode == Mode::Sync) { + return; + } + (void)flush_blocking(); + } + + /// Closes admission, purges unstarted deliveries, joins the internal worker + /// if any, and waits for all in-flight callbacks and releases. + [[nodiscard]] Void::Result::Result close_and_join() + { + if (detail::is_on_bus_callback(core_.get()) || + core_->is_self_worker()) { + return std::unexpected{Void::Async::make_async_error( + Void::Async::AsyncErrorCode::self_join, + "EventBus::close_and_join cannot be called from an executor or callback thread")}; + } + if (core_->mode == Mode::Injected && core_->executor != nullptr && + !core_->executor->has_background_workers()) { + return std::unexpected{Void::Async::make_async_error( + Void::Async::AsyncErrorCode::invalid_argument, + "EventBus::close_and_join requires background workers; use close_and_join_pumping")}; + } + + std::vector> to_drop; + std::deque queued_to_drop; + { + std::lock_guard lk{core_->mu}; + core_->closed = true; + core_->stop_worker = true; + for (auto& [id, e] : core_->by_id) { + e->active = false; + e->purged = true; + if (e->in_flight == 0 && e->handler) { + to_drop.push_back(std::move(e->handler)); + } + } + core_->handlers.clear(); + core_->by_id.clear(); + queued_to_drop.swap(core_->async_queue); + if (core_->admitted_dispatches >= queued_to_drop.size()) { + core_->admitted_dispatches -= queued_to_drop.size(); + } else { + core_->admitted_dispatches = 0; + } + core_->processed += queued_to_drop.size(); + } + core_->cv.notify_all(); + core_->done_cv.notify_all(); + to_drop.clear(); + queued_to_drop.clear(); + + if (core_->mode == Mode::Async && core_->worker.joinable()) { + core_->worker.join(); + } + + { + std::unique_lock lk{core_->mu}; + core_->done_cv.wait(lk, [&] { + return core_->total_in_flight == 0 && + core_->admitted_dispatches == 0; + }); + } + return {}; + } + + /// Closes admission and pumps a ManualExecutor until all admitted dispatches + /// finish and captured handler state is released. + [[nodiscard]] Void::Result::Result + close_and_join_pumping(Void::Async::ManualExecutor& manual) + { + if (core_->mode != Mode::Injected || core_->executor != &manual) { + return std::unexpected{Void::Async::make_async_error( + Void::Async::AsyncErrorCode::invalid_argument, + "EventBus::close_and_join_pumping requires a matching ManualExecutor")}; + } + + std::vector> to_drop; + { + std::lock_guard lk{core_->mu}; + core_->closed = true; + for (auto& [id, e] : core_->by_id) { + e->active = false; + e->purged = true; + if (e->in_flight == 0 && e->handler) { + to_drop.push_back(std::move(e->handler)); + } + } + core_->handlers.clear(); + core_->by_id.clear(); + } + to_drop.clear(); + + for (;;) { + { + std::lock_guard lk{core_->mu}; + if (core_->total_in_flight == 0 && + core_->admitted_dispatches == 0) { + return {}; + } + } + if (manual.drain() == 0) { + std::lock_guard lk{core_->mu}; + if (core_->total_in_flight == 0 && + core_->admitted_dispatches == 0) { + return {}; + } + std::this_thread::yield(); + } + } + } + + void unsubscribe(HandlerId id) + { + std::function released; + { + std::lock_guard lk{core_->mu}; + auto it = core_->by_id.find(id); + if (it == core_->by_id.end()) { + return; + } + auto entry = it->second; + core_->release_entry_locked(entry, released); + } + released = {}; + } + + template + void clear() + { + std::vector> released; + { + std::lock_guard lk{core_->mu}; + auto it = core_->handlers.find(std::type_index(typeid(Event))); + if (it == core_->handlers.end()) { + return; + } + auto vec = std::move(it->second); + core_->handlers.erase(it); + for (auto& entry : vec) { + entry->active = false; + core_->by_id.erase(entry->id); + if (entry->in_flight == 0 && entry->handler) { + released.push_back(std::move(entry->handler)); + } + } + } + released.clear(); + } + + void clear_all() + { + std::vector> released; + { + std::lock_guard lk{core_->mu}; + for (auto& [id, entry] : core_->by_id) { + entry->active = false; + if (entry->in_flight == 0 && entry->handler) { + released.push_back(std::move(entry->handler)); + } + } + core_->handlers.clear(); + core_->by_id.clear(); + } + released.clear(); + } + + template + [[nodiscard]] std::size_t subscriber_count() const + { + std::lock_guard lk{core_->mu}; + auto it = core_->handlers.find(std::type_index(typeid(Event))); + return it == core_->handlers.end() ? 0 : it->second.size(); + } + + [[nodiscard]] Mode mode() const noexcept { return core_->mode; } + + [[nodiscard]] std::uint64_t callback_failures() const noexcept + { + return core_->callback_failures.load(std::memory_order_relaxed); + } + +private: + std::shared_ptr core_; +}; } // namespace Void::EventBus diff --git a/include/Void/Async/Observable.hpp b/include/Void/Async/Observable.hpp index 88f5b0c..5c1e122 100644 --- a/include/Void/Async/Observable.hpp +++ b/include/Void/Async/Observable.hpp @@ -1,45 +1,92 @@ #pragma once +#include +#include + #include +#include +#include #include +#include #include +#include +#include +#include #include #include namespace Void::Observable { -// ── Handle — opaque subscription identifier ─────────────────────────────────── +inline constexpr std::size_t kMaxPendingNotifications = 1024; -struct Handle -{ +struct Handle { std::uint64_t id{0}; - [[nodiscard]] bool valid() const noexcept { return id != 0; } [[nodiscard]] bool operator==(const Handle&) const noexcept = default; }; -// ── Observable ───────────────────────────────────────────────────────────── -// A value that observers can subscribe to via on_change(). -// Observers receive (old_value, new_value) on every set() call that changes -// the stored value. +namespace detail +{ +struct EmptyQueue {}; +} // namespace detail +/// Observable value container holding a T and notifying listeners on change. +/// Single-threaded (not thread-safe across threads), reentrancy-safe: +/// - Copyable T: nested set() updates the value immediately and queues (old, new) +/// notifications FIFO after the active pass (bounded at kMaxPendingNotifications). +/// - Move-only T: 1.x immediate recursive notification over a listener snapshot. template class Observable { public: using Listener = std::function; - explicit Observable(T initial = {}) : value_{std::move(initial)} {} + explicit Observable(T initial = {}) + : value_{std::move(initial)} + { + } [[nodiscard]] const T& get() const noexcept { return value_; } [[nodiscard]] operator const T&() const noexcept { return value_; } void set(T new_val) { - if (new_val == value_) return; + if (new_val == value_) { + return; + } T old = std::move(value_); value_ = std::move(new_val); - notify(old, value_); + if constexpr (std::copy_constructible) { + if (dispatch_depth_ > 0) { + if (pending_.size() < kMaxPendingNotifications) { + pending_.emplace_back(std::move(old), value_); + } else { + ++dropped_notifications_; + } + return; + } + dispatch_fifo(std::move(old), value_); + } else { + notify_snapshot(old, value_); + } + } + + /// Bounded reentrant update for copyable T: returns overloaded without + /// modifying value_ if the nested notification queue is full. + [[nodiscard]] Void::Result::Result try_set(T new_val) + requires std::copy_constructible + { + if (new_val == value_) { + return {}; + } + if (dispatch_depth_ > 0 && + pending_.size() >= kMaxPendingNotifications) { + return std::unexpected{Void::Async::make_async_error( + Void::Async::AsyncErrorCode::overloaded, + "Observable pending notification queue full")}; + } + set(std::move(new_val)); + return {}; } Observable& operator=(T new_val) @@ -48,21 +95,26 @@ public: return *this; } - Handle on_change(Listener listener) + Handle on_change(Listener fn) { - const Handle h{++next_id_}; - listeners_.push_back({h, std::move(listener)}); + const Handle h{next_id_++}; + auto entry = std::make_shared(Entry{h, true, std::move(fn)}); + listeners_.push_back(std::move(entry)); return h; } bool unsubscribe(Handle h) { - const auto it = - std::ranges::find_if(listeners_, - [&](const auto& e) { return e.h == h; }); - if (it == listeners_.end()) return false; - listeners_.erase(it); - return true; + for (auto it = listeners_.begin(); it != listeners_.end(); ++it) { + if ((*it)->handle == h) { + (*it)->active = false; + auto dropped = std::move((*it)->fn); + listeners_.erase(it); + dropped = {}; + return true; + } + } + return false; } [[nodiscard]] std::size_t listener_count() const noexcept @@ -70,52 +122,141 @@ public: return listeners_.size(); } -private: - void notify(const T& old_val, const T& new_val) + [[nodiscard]] std::size_t dropped_notifications() const noexcept { - for (auto& [h, fn] : listeners_) fn(old_val, new_val); + return dropped_notifications_; } - T value_; - std::uint64_t next_id_{0}; - - struct Entry - { - Handle h; - Listener fn; +private: + struct Entry { + Handle handle{0}; + bool active{true}; + Listener fn{}; }; - std::vector listeners_; + + void notify_snapshot(const T& old_val, const T& new_val) const + { + auto snapshot = listeners_; + for (const auto& entry : snapshot) { + if (!entry->active || !entry->fn) { + continue; + } + auto fn = entry->fn; + fn(old_val, new_val); + fn = {}; + } + } + + void dispatch_fifo(T first_old, T first_new) + requires std::copy_constructible + { + dispatch_depth_ = 1; + try { + notify_snapshot(first_old, first_new); + while (!pending_.empty()) { + auto next = std::move(pending_.front()); + pending_.pop_front(); + notify_snapshot(next.first, next.second); + } + } catch (...) { + dropped_notifications_ += pending_.size(); + pending_.clear(); + dispatch_depth_ = 0; + throw; + } + dispatch_depth_ = 0; + } + + using QueueType = std::conditional_t< + std::copy_constructible, + std::deque>, + detail::EmptyQueue>; + + T value_; + std::vector> listeners_{}; + QueueType pending_{}; + std::size_t dispatch_depth_{0}; + std::size_t dropped_notifications_{0}; + std::uint64_t next_id_{1}; }; -// ── Signal ─────────────────────────────────────────────────────────── -// An event signal that observers connect to. emit() calls all connected slots. - +/// Typed multi-slot signal. +/// Single-threaded (not thread-safe across threads), reentrancy-safe: +/// snapshots connected slots and queues nested emit() calls FIFO when all +/// decayed Args are copy-constructible (bounded at kMaxPendingNotifications). template class Signal { public: using Slot = std::function; - Handle connect(Slot slot) + Handle connect(Slot fn) { - const Handle h{++next_id_}; - slots_.push_back({h, std::move(slot)}); + const Handle h{next_id_++}; + auto entry = std::make_shared(Entry{h, true, std::move(fn)}); + slots_.push_back(std::move(entry)); return h; } bool disconnect(Handle h) { - const auto it = - std::ranges::find_if(slots_, - [&](const auto& e) { return e.h == h; }); - if (it == slots_.end()) return false; - slots_.erase(it); - return true; + for (auto it = slots_.begin(); it != slots_.end(); ++it) { + if ((*it)->handle == h) { + (*it)->active = false; + auto dropped = std::move((*it)->fn); + slots_.erase(it); + dropped = {}; + return true; + } + } + return false; + } + + void clear() noexcept + { + auto all = std::move(slots_); + slots_.clear(); + for (auto& e : all) { + e->active = false; + e->fn = {}; + } } void emit(const Args&... args) const { - for (const auto& [h, fn] : slots_) fn(args...); + constexpr bool kAllCopyable = + (std::copy_constructible> && ...); + if constexpr (kAllCopyable) { + if (dispatch_depth_ > 0) { + if (pending_.size() < kMaxPendingNotifications) { + pending_.emplace_back(args...); + } else { + ++dropped_notifications_; + } + return; + } + dispatch_depth_ = 1; + try { + emit_snapshot(args...); + while (!pending_.empty()) { + auto next = std::move(pending_.front()); + pending_.pop_front(); + std::apply( + [this](const auto&... packed) { + emit_snapshot(packed...); + }, + next); + } + } catch (...) { + dropped_notifications_ += pending_.size(); + pending_.clear(); + dispatch_depth_ = 0; + throw; + } + dispatch_depth_ = 0; + } else { + emit_snapshot(args...); + } } [[nodiscard]] std::size_t slot_count() const noexcept @@ -123,17 +264,45 @@ public: return slots_.size(); } - void clear() noexcept { slots_.clear(); } + [[nodiscard]] std::size_t dropped_notifications() const noexcept + { + return dropped_notifications_; + } private: - std::uint64_t next_id_{0}; - - struct Entry - { - Handle h; - Slot fn; + struct Entry { + Handle handle{0}; + bool active{true}; + Slot fn{}; }; - std::vector slots_; + + void emit_snapshot(const Args&... args) const + { + auto snapshot = slots_; + for (const auto& entry : snapshot) { + if (!entry->active || !entry->fn) { + continue; + } + auto fn = entry->fn; + fn(args...); + fn = {}; + } + } + + static constexpr bool kCopyableArgs = + (std::copy_constructible> && ...); + + using TupleType = std::tuple...>; + using QueueType = std::conditional_t< + kCopyableArgs, + std::deque, + detail::EmptyQueue>; + + std::vector> slots_{}; + mutable QueueType pending_{}; + mutable std::size_t dispatch_depth_{0}; + mutable std::size_t dropped_notifications_{0}; + std::uint64_t next_id_{1}; }; } // namespace Void::Observable diff --git a/tests/standalone/Async/EventBusJoin.cpp b/tests/standalone/Async/EventBusJoin.cpp new file mode 100644 index 0000000..85e0188 --- /dev/null +++ b/tests/standalone/Async/EventBusJoin.cpp @@ -0,0 +1,600 @@ +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + +struct Ping { + int value{0}; +}; + +[[nodiscard]] std::size_t current_thread_count() +{ + std::size_t count = 0; + std::error_code ec; + for (const auto& _ : + std::filesystem::directory_iterator("/proc/self/task", ec)) { + (void)_; + ++count; + } + return count; +} + +[[nodiscard]] std::int32_t async_code(const Void::Result::Error& err) noexcept +{ + return err.code().value; +} + +} // namespace + +Void::Testing::Test bus_injected_no_private_thread_manual_pumping() +{ + using namespace Void::EventBus; + const std::size_t threads_before = current_thread_count(); + Void::Async::ManualExecutor manual; + EventBus bus{manual}; + const std::size_t threads_after = current_thread_count(); + Void::Testing::expect_eq(threads_after, threads_before); + Void::Testing::expect(bus.mode() == Mode::Injected); + + int sum = 0; + std::thread::id caller_id = std::this_thread::get_id(); + std::thread::id seen_id{}; + auto sub = bus.try_subscribe([&](const Ping& p) { + seen_id = std::this_thread::get_id(); + sum += p.value; + }); + Void::Testing::require(sub.has_value()); + + Void::Testing::require(bus.try_publish(Ping{10}).has_value()); + Void::Testing::require(bus.try_publish(Ping{25}).has_value()); + Void::Testing::expect_eq(sum, 0); + + Void::Testing::require(bus.flush_pumping(manual).has_value()); + Void::Testing::expect_eq(sum, 35); + Void::Testing::expect(seen_id == caller_id); + + Void::Testing::require(bus.close_and_join_pumping(manual).has_value()); +} + +Void::Testing::Test bus_injected_subscription_limit_overloaded() +{ + using namespace Void::EventBus; + Void::Async::ManualExecutor manual; + EventBus bus{manual, BusOptions{.max_subscriptions = 2}}; + + auto s1 = bus.try_subscribe([](const Ping&) {}); + auto s2 = bus.try_subscribe([](const Ping&) {}); + Void::Testing::require(s1.has_value()); + Void::Testing::require(s2.has_value()); + + auto s3 = bus.try_subscribe([](const Ping&) {}); + Void::Testing::require(!s3.has_value()); + Void::Testing::expect_eq( + async_code(s3.error()), + static_cast(Void::Async::AsyncErrorCode::overloaded)); + + s1->reset(); + auto s4 = bus.try_subscribe([](const Ping&) {}); + Void::Testing::expect(s4.has_value()); + Void::Testing::require(bus.close_and_join_pumping(manual).has_value()); +} + +Void::Testing::Test bus_injected_dispatch_limit_overloaded() +{ + using namespace Void::EventBus; + Void::Async::ManualExecutor manual; + EventBus bus{manual, BusOptions{.max_admitted_dispatches = 2}}; + + int hits = 0; + auto sub = bus.try_subscribe([&](const Ping& p) { hits += p.value; }); + Void::Testing::require(sub.has_value()); + + Void::Testing::require(bus.try_publish(Ping{1}).has_value()); + Void::Testing::require(bus.try_publish(Ping{2}).has_value()); + auto third = bus.try_publish(Ping{3}); + Void::Testing::require(!third.has_value()); + Void::Testing::expect_eq( + async_code(third.error()), + static_cast(Void::Async::AsyncErrorCode::overloaded)); + + Void::Testing::require(bus.flush_pumping(manual).has_value()); + Void::Testing::expect_eq(hits, 3); + Void::Testing::require(bus.try_publish(Ping{4}).has_value()); + Void::Testing::require(bus.flush_pumping(manual).has_value()); + Void::Testing::expect_eq(hits, 7); + Void::Testing::require(bus.close_and_join_pumping(manual).has_value()); +} + +Void::Testing::Test bus_close_and_join_waits_inflight_releases_capture_tsan() +{ + using namespace Void::EventBus; + auto exec_res = Void::Async::ThreadExecutor::create( + Void::Async::ThreadExecutorOptions{.workers = 2, .max_admitted = 32}); + Void::Testing::require(exec_res.has_value()); + auto exec = std::move(*exec_res); + Void::Testing::require(exec->start().has_value()); + + { + EventBus bus{*exec}; + auto sentinel = std::make_shared(99); + std::latch started{1}; + std::promise release_promise; + auto release_future = release_promise.get_future().share(); + std::atomic finished{false}; + + auto sub = bus.try_subscribe( + [&, sentinel](const Ping&) { + started.count_down(); + release_future.wait(); + finished.store(true, std::memory_order_release); + }); + Void::Testing::require(sub.has_value()); + Void::Testing::expect(sentinel.use_count() >= 2); + + Void::Testing::require(bus.try_publish(Ping{1}).has_value()); + started.wait(); + + std::atomic join_done{false}; + Void::Result::Result join_res; + std::thread joiner([&]() { + join_res = sub->close_and_join(); + join_done.store(true, std::memory_order_release); + }); + + std::this_thread::sleep_for(std::chrono::milliseconds{15}); + Void::Testing::expect(!join_done.load(std::memory_order_acquire)); + + release_promise.set_value(); + joiner.join(); + + Void::Testing::expect(join_res.has_value()); + Void::Testing::expect(finished.load(std::memory_order_acquire)); + Void::Testing::expect_eq(sentinel.use_count(), 1L); + Void::Testing::require(bus.close_and_join().has_value()); + } + exec->close(); + Void::Testing::require(exec->join().has_value()); +} + +Void::Testing::Test bus_unsubscribe_during_dispatch_prevents_later_admission() +{ + using namespace Void::EventBus; + EventBus bus{Mode::Sync}; + + int first_hits = 0; + int second_hits = 0; + HandlerId id2 = 0; + bus.subscribe([&](const Ping&) { + ++first_hits; + bus.unsubscribe(id2); + }); + id2 = bus.subscribe([&](const Ping&) { ++second_hits; }); + + bus.publish(Ping{1}); + Void::Testing::expect_eq(first_hits, 1); + Void::Testing::expect_eq(second_hits, 0); + + bus.publish(Ping{2}); + Void::Testing::expect_eq(first_hits, 2); + Void::Testing::expect_eq(second_hits, 0); +} + +Void::Testing::Test bus_self_unsubscribe_ok_self_join_rejected() +{ + using namespace Void::EventBus; + EventBus bus{Mode::Sync}; + EventBus::Subscription sub; + Void::Result::Result join_res; + int calls = 0; + + auto sub_res = bus.try_subscribe([&](const Ping&) { + ++calls; + join_res = sub.close_and_join(); + sub.reset(); + }); + Void::Testing::require(sub_res.has_value()); + sub = std::move(*sub_res); + + bus.publish(Ping{1}); + bus.publish(Ping{2}); + Void::Testing::expect_eq(calls, 1); + Void::Testing::require(!join_res.has_value()); + Void::Testing::expect_eq( + async_code(join_res.error()), + static_cast(Void::Async::AsyncErrorCode::self_join)); + Void::Testing::expect(!static_cast(sub)); +} + +Void::Testing::Test bus_callback_throw_to_error_sink_others_run() +{ + using namespace Void::EventBus; + Void::Async::ManualExecutor manual; + std::vector errors; + EventBus bus{ + manual, + BusOptions{.error_sink = [&](std::exception_ptr ex) { + try { + if (ex) { + std::rethrow_exception(ex); + } + } catch (const std::exception& e) { + errors.emplace_back(e.what()); + } + }}}; + + int second_hits = 0; + auto s1 = bus.try_subscribe([](const Ping&) { + throw std::runtime_error("boom_injected"); + }); + auto s2 = bus.try_subscribe([&](const Ping& p) { second_hits += p.value; }); + Void::Testing::require(s1.has_value() && s2.has_value()); + + Void::Testing::require(bus.try_publish(Ping{9}).has_value()); + Void::Testing::require(bus.flush_pumping(manual).has_value()); + Void::Testing::expect_eq(second_hits, 9); + Void::Testing::expect_eq(bus.callback_failures(), std::uint64_t{1}); + Void::Testing::require(errors.size() == 1); + Void::Testing::expect_eq(errors[0], std::string{"boom_injected"}); + + // Legacy Sync publish retains exception propagation. + EventBus sync_bus{Mode::Sync}; + sync_bus.subscribe([](const Ping&) { throw std::runtime_error("sync_boom"); }); + bool caught = false; + try { + sync_bus.publish(Ping{1}); + } catch (const std::runtime_error&) { + caught = true; + } + Void::Testing::expect(caught); + Void::Testing::require(bus.close_and_join_pumping(manual).has_value()); +} + +Void::Testing::Test bus_error_sink_throw_caught_and_counted() +{ + using namespace Void::EventBus; + EventBus bus{ + Mode::Async, + BusOptions{.error_sink = [](std::exception_ptr) { + throw std::runtime_error("sink_boom"); + }}}; + + std::atomic second_hits{0}; + bus.subscribe([](const Ping&) { + throw std::runtime_error("cb_boom"); + }); + bus.subscribe([&](const Ping& p) { + second_hits.fetch_add(p.value, std::memory_order_relaxed); + }); + + Void::Testing::require(bus.try_publish(Ping{7}).has_value()); + Void::Testing::require(bus.flush_blocking().has_value()); + Void::Testing::expect_eq(second_hits.load(), 7); + // 1 for handler throw + 1 for throwing error_sink + Void::Testing::expect_eq(bus.callback_failures(), std::uint64_t{2}); + Void::Testing::require(bus.close_and_join().has_value()); +} + +Void::Testing::Test bus_legacy_async_unsubscribe_keeps_queued_copy() +{ + using namespace Void::EventBus; + struct Unblock {}; + EventBus bus{Mode::Async}; + + std::latch blocker_entered{1}; + std::promise release_blocker; + auto release_future = release_blocker.get_future().share(); + + bus.subscribe([&](const Unblock&) { + blocker_entered.count_down(); + release_future.wait(); + }); + + std::atomic target_hits{0}; + const HandlerId target_id = bus.subscribe([&](const Ping& p) { + target_hits.fetch_add(p.value, std::memory_order_relaxed); + }); + + bus.publish(Unblock{}); + blocker_entered.wait(); + + bus.publish(Ping{13}); + bus.unsubscribe(target_id); + bus.publish(Ping{100}); + + release_blocker.set_value(); + bus.flush(); + + Void::Testing::expect_eq(target_hits.load(), 13); + Void::Testing::require(bus.close_and_join().has_value()); +} + +Void::Testing::Test bus_sync_reentrant_subscribe_unsubscribe_asan() +{ + using namespace Void::EventBus; + EventBus bus{Mode::Sync}; + + int late_hits = 0; + int primary_hits = 0; + HandlerId removable_id = 0; + + bus.subscribe([&](const Ping& p) { + ++primary_hits; + if (p.value == 1) { + bus.subscribe([&](const Ping&) { ++late_hits; }); + bus.unsubscribe(removable_id); + } + }); + int removed_hits = 0; + removable_id = bus.subscribe([&](const Ping&) { ++removed_hits; }); + + bus.publish(Ping{1}); + Void::Testing::expect_eq(primary_hits, 1); + Void::Testing::expect_eq(removed_hits, 0); + Void::Testing::expect_eq(late_hits, 0); + + bus.publish(Ping{2}); + Void::Testing::expect_eq(primary_hits, 2); + Void::Testing::expect_eq(removed_hits, 0); + Void::Testing::expect_eq(late_hits, 1); +} + +Void::Testing::Test bus_publish_after_close_closed() +{ + using namespace Void::EventBus; + EventBus bus{Mode::Async}; + Void::Testing::require(bus.close_and_join().has_value()); + + auto sub_res = bus.try_subscribe([](const Ping&) {}); + Void::Testing::require(!sub_res.has_value()); + Void::Testing::expect_eq( + async_code(sub_res.error()), + static_cast(Void::Async::AsyncErrorCode::closed)); + + auto pub_res = bus.try_publish(Ping{42}); + Void::Testing::require(!pub_res.has_value()); + Void::Testing::expect_eq( + async_code(pub_res.error()), + static_cast(Void::Async::AsyncErrorCode::closed)); +} + +Void::Testing::Test bus_sync_unsubscribe_releases_captured_state() +{ + using namespace Void::EventBus; + EventBus bus{Mode::Sync}; + + auto s1 = std::make_shared(1); + const HandlerId id = bus.subscribe([s1](const Ping&) { (void)s1; }); + Void::Testing::expect_eq(s1.use_count(), 2L); + bus.unsubscribe(id); + Void::Testing::expect_eq(s1.use_count(), 1L); + + auto s2 = std::make_shared(2); + auto scoped = bus.try_subscribe([s2](const Ping&) { (void)s2; }); + Void::Testing::require(scoped.has_value()); + Void::Testing::expect_eq(s2.use_count(), 2L); + scoped->reset(); + Void::Testing::expect_eq(s2.use_count(), 1L); +} + +Void::Testing::Test bus_legacy_async_unsubscribe_then_flush_releases_captured_state() +{ + using namespace Void::EventBus; + struct Hold {}; + EventBus bus{Mode::Async}; + + std::latch entered{1}; + std::promise rel; + auto rel_fut = rel.get_future().share(); + bus.subscribe([&](const Hold&) { + entered.count_down(); + rel_fut.wait(); + }); + + auto sentinel = std::make_shared(77); + const HandlerId id = bus.subscribe([sentinel](const Ping&) { (void)sentinel; }); + + bus.publish(Hold{}); + entered.wait(); + + bus.publish(Ping{1}); + bus.unsubscribe(id); + Void::Testing::expect(sentinel.use_count() >= 2L); + + rel.set_value(); + bus.flush(); + Void::Testing::expect_eq(sentinel.use_count(), 1L); + Void::Testing::require(bus.close_and_join().has_value()); +} + +Void::Testing::Test bus_legacy_async_close_and_join_releases_capture_with_queued_copies() +{ + using namespace Void::EventBus; + struct Hold {}; + EventBus bus{Mode::Async}; + + std::latch entered{1}; + std::promise rel; + auto rel_fut = rel.get_future().share(); + bus.subscribe([&](const Hold&) { + entered.count_down(); + rel_fut.wait(); + }); + + auto sentinel = std::make_shared(88); + auto sub = bus.try_subscribe([sentinel](const Ping&) { (void)sentinel; }); + Void::Testing::require(sub.has_value()); + + bus.publish(Hold{}); + entered.wait(); + + // Queue copies on the worker queue while Hold keeps worker busy. + bus.publish(Ping{1}); + bus.publish(Ping{2}); + Void::Testing::expect(sentinel.use_count() >= 3L); + + // Must purge queued copies for sub and release captured state immediately + // without blocking on Hold or executing queued Ping callbacks. + Void::Testing::require(sub->close_and_join().has_value()); + Void::Testing::expect_eq(sentinel.use_count(), 1L); + + rel.set_value(); + Void::Testing::require(bus.close_and_join().has_value()); +} + +Void::Testing::Test bus_destructor_gates_admitted_deliveries() +{ + using namespace Void::EventBus; + // 1. Queued ManualExecutor deliveries are gated when ~EventBus destroys. + { + Void::Async::ManualExecutor manual; + int delivered = 0; + { + EventBus bus{manual}; + auto sub = bus.try_subscribe([&](const Ping&) { ++delivered; }); + Void::Testing::require(sub.has_value()); + Void::Testing::require(bus.try_publish(Ping{1}).has_value()); + Void::Testing::require(bus.try_publish(Ping{2}).has_value()); + } + manual.drain(); + Void::Testing::expect_eq(delivered, 0); + } + + // 2. Destruction on a thread waits for OTHER thread's in-flight callback, + // gates queued unstarted work, and self-destruction in callback doesn't deadlock. + { + auto exec_res = Void::Async::ThreadExecutor::create( + Void::Async::ThreadExecutorOptions{.workers = 1, .max_admitted = 32}); + Void::Testing::require(exec_res.has_value()); + auto exec = std::move(*exec_res); + Void::Testing::require(exec->start().has_value()); + + std::atomic started_count{0}; + std::atomic gated_count{0}; + std::latch first_in_flight{1}; + std::promise allow_first_finish; + auto finish_fut = allow_first_finish.get_future().share(); + + { + std::optional bus{std::in_place, *exec}; + auto s1 = bus->try_subscribe([&](const Ping& p) { + if (p.value == 1) { + started_count.fetch_add(1, std::memory_order_relaxed); + first_in_flight.count_down(); + finish_fut.wait(); + } else { + gated_count.fetch_add(1, std::memory_order_relaxed); + } + }); + Void::Testing::require(s1.has_value()); + Void::Testing::require(bus->try_publish(Ping{1}).has_value()); + first_in_flight.wait(); + Void::Testing::require(bus->try_publish(Ping{2}).has_value()); + + std::atomic destroyed{false}; + std::thread destroyer([&]() { + bus.reset(); + destroyed.store(true, std::memory_order_release); + }); + std::this_thread::sleep_for(std::chrono::milliseconds{15}); + Void::Testing::expect(!destroyed.load(std::memory_order_acquire)); + allow_first_finish.set_value(); + destroyer.join(); + } + exec->close(); + Void::Testing::require(exec->join().has_value()); + Void::Testing::expect_eq(started_count.load(), 1); + Void::Testing::expect_eq(gated_count.load(), 0); + } + + // 3. Destroying EventBus from inside its own Sync callback doesn't deadlock. + { + std::optional bus{std::in_place, Mode::Sync}; + int ran = 0; + bus->subscribe([&](const Ping&) { + ++ran; + bus.reset(); + }); + bus->publish(Ping{1}); + Void::Testing::expect_eq(ran, 1); + Void::Testing::expect(!bus.has_value()); + } +} + +Void::Testing::Test bus_flush_blocking_self_join_and_manual_invalid() +{ + using namespace Void::EventBus; + // ManualExecutor rejects flush_blocking and close_and_join with invalid_argument. + { + Void::Async::ManualExecutor manual; + EventBus bus{manual}; + auto fb = bus.flush_blocking(); + Void::Testing::require(!fb.has_value()); + Void::Testing::expect_eq( + async_code(fb.error()), + static_cast(Void::Async::AsyncErrorCode::invalid_argument)); + auto cj = bus.close_and_join(); + Void::Testing::require(!cj.has_value()); + Void::Testing::expect_eq( + async_code(cj.error()), + static_cast(Void::Async::AsyncErrorCode::invalid_argument)); + } + + // Executor worker thread calling flush_blocking or close_and_join gets self_join. + { + auto exec_res = Void::Async::ThreadExecutor::create( + Void::Async::ThreadExecutorOptions{.workers = 1, .max_admitted = 16}); + Void::Testing::require(exec_res.has_value()); + auto exec = std::move(*exec_res); + Void::Testing::require(exec->start().has_value()); + + EventBus bus{*exec}; + std::optional> fb_res; + std::optional> cj_res; + auto sub = bus.try_subscribe([&](const Ping&) { + fb_res = bus.flush_blocking(); + cj_res = bus.close_and_join(); + }); + Void::Testing::require(sub.has_value()); + Void::Testing::require(bus.try_publish(Ping{1}).has_value()); + Void::Testing::require(bus.flush_blocking().has_value()); + Void::Testing::require(fb_res.has_value() && !fb_res->has_value()); + Void::Testing::expect_eq( + async_code(fb_res->error()), + static_cast(Void::Async::AsyncErrorCode::self_join)); + Void::Testing::require(cj_res.has_value() && !cj_res->has_value()); + Void::Testing::expect_eq( + async_code(cj_res->error()), + static_cast(Void::Async::AsyncErrorCode::self_join)); + + // Wrong executor passed to flush_pumping returns invalid_argument. + Void::Async::ManualExecutor other_manual; + auto fp = bus.flush_pumping(other_manual); + Void::Testing::require(!fp.has_value()); + Void::Testing::expect_eq( + async_code(fp.error()), + static_cast(Void::Async::AsyncErrorCode::invalid_argument)); + + Void::Testing::require(bus.close_and_join().has_value()); + exec->close(); + Void::Testing::require(exec->join().has_value()); + } +} diff --git a/tests/standalone/Async/ObservableReentrancy.cpp b/tests/standalone/Async/ObservableReentrancy.cpp new file mode 100644 index 0000000..1c441ff --- /dev/null +++ b/tests/standalone/Async/ObservableReentrancy.cpp @@ -0,0 +1,236 @@ +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace +{ + +struct MoveOnlyVal { + int id{0}; + + MoveOnlyVal() = default; + explicit MoveOnlyVal(int v) noexcept : id{v} {} + MoveOnlyVal(const MoveOnlyVal&) = delete; + MoveOnlyVal& operator=(const MoveOnlyVal&) = delete; + MoveOnlyVal(MoveOnlyVal&&) noexcept = default; + MoveOnlyVal& operator=(MoveOnlyVal&&) noexcept = default; + + [[nodiscard]] bool operator==(const MoveOnlyVal& other) const noexcept + { + return id == other.id; + } +}; + +} // namespace + +Void::Testing::Test observable_nested_set_fifo() +{ + using namespace Void::Observable; + Observable obs{0}; + std::vector> seen; + + obs.on_change([&](const int& old_v, const int& new_v) { + seen.emplace_back(old_v, new_v); + if (new_v == 1) { + obs.set(2); + Void::Testing::expect_eq(obs.get(), 2); + obs.set(3); + Void::Testing::expect_eq(obs.get(), 3); + } + }); + + obs.set(1); + Void::Testing::expect_eq(obs.get(), 3); + Void::Testing::require(seen.size() == 3); + Void::Testing::expect_eq(seen[0].first, 0); + Void::Testing::expect_eq(seen[0].second, 1); + Void::Testing::expect_eq(seen[1].first, 1); + Void::Testing::expect_eq(seen[1].second, 2); + Void::Testing::expect_eq(seen[2].first, 2); + Void::Testing::expect_eq(seen[2].second, 3); +} + +Void::Testing::Test observable_unsubscribe_in_listener_skips_rest() +{ + using namespace Void::Observable; + Observable obs{0}; + int second_hits = 0; + Handle second_h{}; + + obs.on_change([&](const int&, const int&) { obs.unsubscribe(second_h); }); + second_h = obs.on_change([&](const int&, const int&) { ++second_hits; }); + + obs.set(1); + Void::Testing::expect_eq(second_hits, 0); + obs.set(2); + Void::Testing::expect_eq(second_hits, 0); +} + +Void::Testing::Test observable_subscribe_in_listener_not_current_pass() +{ + using namespace Void::Observable; + Observable obs{0}; + int late_hits = 0; + bool added = false; + + obs.on_change([&](const int&, const int&) { + if (!added) { + added = true; + obs.on_change([&](const int&, const int&) { ++late_hits; }); + } + }); + + obs.set(1); + Void::Testing::expect_eq(late_hits, 0); + obs.set(2); + Void::Testing::expect_eq(late_hits, 1); +} + +Void::Testing::Test observable_try_set_overloaded_when_pending_full() +{ + using namespace Void::Observable; + Observable obs{0}; + Void::Result::Result overflow_res{}; + bool overflow_checked = false; + + obs.on_change([&](const int&, const int& new_v) { + if (new_v == 1) { + for (std::size_t i = 0; i < kMaxPendingNotifications; ++i) { + auto r = obs.try_set(static_cast(i + 2)); + if (!r.has_value()) { + overflow_checked = false; + return; + } + } + const int val_before_overload = obs.get(); + overflow_res = obs.try_set(999999); + Void::Testing::expect_eq(obs.get(), val_before_overload); + // Overflow via set() updates value and increments dropped_notifications. + obs.set(888888); + Void::Testing::expect_eq(obs.get(), 888888); + overflow_checked = true; + } + }); + + obs.set(1); + Void::Testing::expect(overflow_checked); + Void::Testing::require(!overflow_res.has_value()); + Void::Testing::expect_eq( + overflow_res.error().code().value, + static_cast(Void::Async::AsyncErrorCode::overloaded)); + Void::Testing::expect_eq(obs.get(), 888888); + Void::Testing::expect_eq(obs.dropped_notifications(), std::size_t{1}); +} + +Void::Testing::Test observable_listener_throw_restores_state() +{ + using namespace Void::Observable; + Observable obs{0}; + int normal_hits = 0; + + obs.on_change([&](const int&, const int& new_v) { + if (new_v == 1) { + obs.set(2); + obs.set(3); + throw std::runtime_error("listener_boom"); + } + ++normal_hits; + }); + + bool caught = false; + try { + obs.set(1); + } catch (const std::runtime_error&) { + caught = true; + } + Void::Testing::expect(caught); + Void::Testing::expect_eq(obs.get(), 3); + Void::Testing::expect_eq(obs.dropped_notifications(), std::size_t{2}); + + // Subsequent set operates cleanly with depth restored to 0. + obs.set(4); + Void::Testing::expect_eq(obs.get(), 4); + Void::Testing::expect_eq(normal_hits, 1); +} + +Void::Testing::Test observable_self_unsubscribe_releases_capture() +{ + using namespace Void::Observable; + Observable obs{0}; + auto sentinel = std::make_shared(55); + Handle h{}; + + h = obs.on_change([&, sentinel](const int&, const int&) { + (void)sentinel; + Void::Testing::expect(obs.unsubscribe(h)); + }); + Void::Testing::expect_eq(sentinel.use_count(), 2L); + + obs.set(1); + Void::Testing::expect_eq(sentinel.use_count(), 1L); + Void::Testing::expect_eq(obs.listener_count(), std::size_t{0}); +} + +Void::Testing::Test observable_move_only_immediate_notification_compat() +{ + using namespace Void::Observable; + Observable obs{MoveOnlyVal{0}}; + std::vector> trace; + + obs.on_change([&](const MoveOnlyVal& ov, const MoveOnlyVal& nv) { + trace.emplace_back(ov.id, nv.id); + if (nv.id == 1) { + obs.set(MoveOnlyVal{2}); + } + }); + obs.on_change([&](const MoveOnlyVal& ov, const MoveOnlyVal& nv) { + trace.emplace_back(ov.id * 10, nv.id * 10); + }); + + obs.set(MoveOnlyVal{1}); + // Immediate recursive delivery matches 1.x notify(old, value_) aliasing. + Void::Testing::require(trace.size() == 4); + Void::Testing::expect_eq(trace[0].first, 0); + Void::Testing::expect_eq(trace[0].second, 1); + Void::Testing::expect_eq(trace[1].first, 1); + Void::Testing::expect_eq(trace[1].second, 2); + Void::Testing::expect_eq(trace[2].first, 10); + Void::Testing::expect_eq(trace[2].second, 20); + Void::Testing::expect_eq(trace[3].first, 0); + Void::Testing::expect_eq(trace[3].second, 20); + Void::Testing::expect_eq(obs.dropped_notifications(), std::size_t{0}); +} + +Void::Testing::Test signal_reentrant_connect_disconnect_during_emit() +{ + using namespace Void::Observable; + Signal sig; + std::vector log; + Handle second_h{}; + Handle third_h{}; + + sig.connect([&](const int& v) { + log.push_back(v); + if (v == 1) { + Void::Testing::expect(sig.disconnect(second_h)); + third_h = sig.connect([&](const int& x) { log.push_back(x * 100); }); + sig.emit(2); + } + }); + second_h = sig.connect([&](const int& v) { log.push_back(v * 10); }); + + sig.emit(1); + // First emit skips disconnected second_h and skips newly added third_h; + // queued emit(2) runs first slot and third_h FIFO. + Void::Testing::require(log.size() == 3); + Void::Testing::expect_eq(log[0], 1); + Void::Testing::expect_eq(log[1], 2); + Void::Testing::expect_eq(log[2], 200); + Void::Testing::expect(third_h.id != 0); +}