1150 lines
37 KiB
C++
1150 lines
37 KiB
C++
#pragma once
|
|
|
|
#include <Void/Async/Detail/Types.hpp>
|
|
#include <Void/Async/Executor.hpp>
|
|
#include <Void/Functional/Error.hpp>
|
|
#include <Void/Functional/Result.hpp>
|
|
|
|
#include <algorithm>
|
|
#include <atomic>
|
|
#include <condition_variable>
|
|
#include <coroutine>
|
|
#include <cstddef>
|
|
#include <cstdint>
|
|
#include <deque>
|
|
#include <exception>
|
|
#include <functional>
|
|
#include <memory>
|
|
#include <mutex>
|
|
#include <thread>
|
|
#include <typeindex>
|
|
#include <unordered_map>
|
|
#include <utility>
|
|
#include <vector>
|
|
|
|
namespace Void::EventBus
|
|
{
|
|
|
|
using HandlerId = std::uint64_t;
|
|
|
|
enum class Mode { Sync, Async, Injected };
|
|
|
|
struct BusOptions {
|
|
std::size_t max_subscriptions{1024};
|
|
std::size_t max_admitted_dispatches{1024};
|
|
std::function<void(std::exception_ptr)> error_sink{};
|
|
};
|
|
|
|
namespace detail
|
|
{
|
|
|
|
struct DispatchFrame {
|
|
const void* core{nullptr};
|
|
const void* entry{nullptr};
|
|
const DispatchFrame* prev{nullptr};
|
|
|
|
[[nodiscard]] static inline const DispatchFrame*& head() noexcept
|
|
{
|
|
thread_local const DispatchFrame* slot = nullptr;
|
|
return slot;
|
|
}
|
|
};
|
|
|
|
class DispatchGuard
|
|
{
|
|
public:
|
|
DispatchGuard(const void* core, const void* entry) noexcept
|
|
: frame_{core, entry, DispatchFrame::head()}
|
|
{
|
|
DispatchFrame::head() = &frame_;
|
|
}
|
|
|
|
~DispatchGuard()
|
|
{
|
|
DispatchFrame::head() = frame_.prev;
|
|
}
|
|
|
|
DispatchGuard(const DispatchGuard&) = delete;
|
|
DispatchGuard& operator=(const DispatchGuard&) = delete;
|
|
|
|
private:
|
|
DispatchFrame frame_;
|
|
};
|
|
|
|
[[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;
|
|
}
|
|
|
|
[[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;
|
|
}
|
|
|
|
[[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;
|
|
}
|
|
|
|
struct SubEntry {
|
|
HandlerId id{0};
|
|
std::type_index type{typeid(void)};
|
|
std::function<void(const void*)> handler{};
|
|
bool active{true};
|
|
bool purged{false};
|
|
std::size_t in_flight{0};
|
|
};
|
|
|
|
struct QueuedRecipient {
|
|
std::shared_ptr<SubEntry> entry{};
|
|
std::function<void(const void*)> legacy_fn{};
|
|
};
|
|
|
|
struct AsyncDelivery {
|
|
std::shared_ptr<const void> event{};
|
|
std::vector<QueuedRecipient> recipients{};
|
|
};
|
|
|
|
struct DispatchCoroutine {
|
|
struct promise_type {
|
|
DispatchCoroutine get_return_object() noexcept
|
|
{
|
|
return DispatchCoroutine{
|
|
std::coroutine_handle<promise_type>::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 {}
|
|
};
|
|
|
|
std::coroutine_handle<promise_type> handle{};
|
|
};
|
|
|
|
struct BusCore : std::enable_shared_from_this<BusCore> {
|
|
Mode mode{Mode::Sync};
|
|
BusOptions options{};
|
|
Void::Async::Executor* executor{nullptr};
|
|
bool invalid_injected{false};
|
|
|
|
mutable std::mutex mu{};
|
|
std::condition_variable cv{};
|
|
std::condition_variable done_cv{};
|
|
|
|
std::unordered_map<std::type_index, std::vector<std::shared_ptr<SubEntry>>>
|
|
handlers{};
|
|
std::unordered_map<HandlerId, std::shared_ptr<SubEntry>> by_id{};
|
|
HandlerId next_id{1};
|
|
|
|
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<std::uint64_t> callback_failures{0};
|
|
|
|
// Mode::Async worker state.
|
|
std::thread worker{};
|
|
std::deque<AsyncDelivery> async_queue{};
|
|
bool stop_worker{false};
|
|
|
|
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;
|
|
}
|
|
}
|
|
|
|
~BusCore()
|
|
{
|
|
if (worker.joinable()) {
|
|
if (std::this_thread::get_id() == worker.get_id()) {
|
|
worker.detach();
|
|
} else {
|
|
worker.join();
|
|
}
|
|
}
|
|
}
|
|
|
|
[[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 invoke_error_sink(std::exception_ptr ex) noexcept
|
|
{
|
|
callback_failures.fetch_add(1, std::memory_order_relaxed);
|
|
std::function<void(std::exception_ptr)> 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);
|
|
}
|
|
}
|
|
}
|
|
|
|
void release_entry_locked(const std::shared_ptr<SubEntry>& entry,
|
|
std::function<void(const void*)>& 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<SubEntry>& 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);
|
|
}
|
|
}
|
|
|
|
void finish_entry_dispatch(const std::shared_ptr<SubEntry>& entry) noexcept
|
|
{
|
|
for (;;) {
|
|
std::function<void(const void*)> cleanup_fn;
|
|
{
|
|
std::lock_guard lk{mu};
|
|
if (!entry->active && entry->in_flight == 1 && entry->handler) {
|
|
cleanup_fn = std::move(entry->handler);
|
|
} else {
|
|
--entry->in_flight;
|
|
--total_in_flight;
|
|
break;
|
|
}
|
|
}
|
|
// Destroy captured state outside mu while in_flight >= 1 so
|
|
// join_entry / close_and_join / ~EventBus cannot return early.
|
|
cleanup_fn = {};
|
|
}
|
|
done_cv.notify_all();
|
|
}
|
|
|
|
[[nodiscard]] Void::Result::Result<void> join_entry(
|
|
const std::shared_ptr<SubEntry>& 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")};
|
|
}
|
|
|
|
std::function<void(const void*)> released_fn;
|
|
std::vector<std::function<void(const void*)>> 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 {};
|
|
}
|
|
|
|
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();
|
|
}
|
|
|
|
const void* ev_raw = item.event.get();
|
|
for (auto& rec : item.recipients) {
|
|
std::function<void(const void*)> fn;
|
|
std::function<void(const void*)> discarded_legacy;
|
|
{
|
|
std::lock_guard lk{mu};
|
|
if (closed || rec.entry->purged) {
|
|
discarded_legacy = std::move(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;
|
|
}
|
|
|
|
{
|
|
DispatchGuard dg{this, rec.entry.get()};
|
|
try {
|
|
fn(ev_raw);
|
|
} catch (...) {
|
|
invoke_error_sink(std::current_exception());
|
|
}
|
|
}
|
|
fn = {};
|
|
|
|
finish_entry_dispatch(rec.entry);
|
|
}
|
|
|
|
// 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<std::function<void(const void*)>> to_drop;
|
|
std::deque<AsyncDelivery> 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<Void::Async::ManualExecutor*>(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<BusCore> core,
|
|
std::shared_ptr<const void> event_ptr,
|
|
std::vector<std::shared_ptr<SubEntry>> snapshot)
|
|
{
|
|
const void* ev_raw = event_ptr.get();
|
|
for (auto& entry : snapshot) {
|
|
std::function<void(const void*)> 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 = {};
|
|
|
|
core->finish_entry_dispatch(entry);
|
|
}
|
|
|
|
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<void(const void*)> 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<void> 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<detail::BusCore> core,
|
|
std::shared_ptr<detail::SubEntry> entry) noexcept
|
|
: core_(std::move(core))
|
|
, entry_(std::move(entry))
|
|
{
|
|
}
|
|
|
|
std::shared_ptr<detail::BusCore> core_{};
|
|
std::shared_ptr<detail::SubEntry> entry_{};
|
|
};
|
|
|
|
explicit EventBus(Mode mode = Mode::Sync, BusOptions options = {})
|
|
: core_(std::make_shared<detail::BusCore>(
|
|
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<detail::BusCore>(
|
|
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 <typename Event>
|
|
[[nodiscard]] Void::Result::Result<Subscription>
|
|
try_subscribe(std::function<void(const Event&)> 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<detail::SubEntry> 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<detail::SubEntry>();
|
|
entry->id = id;
|
|
entry->type = type_idx;
|
|
entry->handler = [f = std::move(fn)](const void* raw) {
|
|
f(*static_cast<const Event*>(raw));
|
|
};
|
|
core_->handlers[type_idx].push_back(entry);
|
|
core_->by_id.emplace(id, entry);
|
|
}
|
|
return Subscription{core_, std::move(entry)};
|
|
}
|
|
|
|
template <typename Event>
|
|
HandlerId subscribe(std::function<void(const Event&)> fn)
|
|
{
|
|
auto res = try_subscribe<Event>(std::move(fn));
|
|
if (!res.has_value()) {
|
|
return 0;
|
|
}
|
|
const HandlerId id = res->id();
|
|
res->entry_.reset();
|
|
res->core_.reset();
|
|
return id;
|
|
}
|
|
|
|
template <typename Event>
|
|
[[nodiscard]] Subscription subscribe_scoped(
|
|
std::function<void(const Event&)> fn)
|
|
{
|
|
auto res = try_subscribe<Event>(std::move(fn));
|
|
if (!res.has_value()) {
|
|
return {};
|
|
}
|
|
return std::move(*res);
|
|
}
|
|
|
|
template <typename Event>
|
|
[[nodiscard]] Void::Result::Result<void> try_publish(const Event& event)
|
|
{
|
|
auto core = core_;
|
|
const auto type_idx = std::type_index(typeid(Event));
|
|
|
|
if (core->mode == Mode::Sync) {
|
|
std::vector<std::shared_ptr<detail::SubEntry>> 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<void(const void*)> 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<detail::BusCore> core;
|
|
const std::shared_ptr<detail::SubEntry>& entry;
|
|
std::function<void(const void*)>& fn_ref;
|
|
~EntryExitGuard()
|
|
{
|
|
fn_ref = {};
|
|
core->finish_entry_dispatch(entry);
|
|
}
|
|
} 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<detail::QueuedRecipient> 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<const void> ev_copy;
|
|
try {
|
|
ev_copy = std::make_shared<Event>(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<std::shared_ptr<detail::SubEntry>> 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<const void> ev_copy;
|
|
detail::DispatchCoroutine coro{};
|
|
try {
|
|
ev_copy = std::make_shared<Event>(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 <typename Event>
|
|
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<void> 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<void>
|
|
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")};
|
|
}
|
|
if (detail::is_on_bus_callback(core_.get())) {
|
|
return std::unexpected{Void::Async::make_async_error(
|
|
Void::Async::AsyncErrorCode::self_join,
|
|
"EventBus::flush_pumping cannot be called from inside a callback")};
|
|
}
|
|
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<void> 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<std::function<void(const void*)>> to_drop;
|
|
std::deque<detail::AsyncDelivery> 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<void>
|
|
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")};
|
|
}
|
|
if (detail::is_on_bus_callback(core_.get())) {
|
|
return std::unexpected{Void::Async::make_async_error(
|
|
Void::Async::AsyncErrorCode::self_join,
|
|
"EventBus::close_and_join_pumping cannot be called from inside a callback")};
|
|
}
|
|
|
|
std::vector<std::function<void(const void*)>> 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<void(const void*)> 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 <typename Event>
|
|
void clear()
|
|
{
|
|
std::vector<std::function<void(const void*)>> 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<std::function<void(const void*)>> 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 <typename Event>
|
|
[[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<detail::BusCore> core_;
|
|
};
|
|
|
|
} // namespace Void::EventBus
|