Host-side additions for applications embedding a plugin system: - PluginManager::load_directory(dir) loads every shared-library file in a directory (filename order) with per-file expected results. - PluginManager::unload(name) drops the registry entry; the instance dies with its last pinned handle (RCU semantics, as on reload). - Optional C entry void_plugin_configure(inst, config): fed from PluginManagerOptions::config_provider after create and after each reload swap, before on_load(). - on_reloaded() is now multi-observer: returns a ReloadCallbackId, remove_on_reloaded() unregisters. Manual reload() now notifies observers too (previously only watched reloads did, contradicting the documented contract). PluginServiceBinding deregisters its callback on destruction (was a dangling-callback hazard). - PluginManager::serialize_state/deserialize_state expose the plugin's v2 state exports so an embedder can carry plugin state through its own hot reload. - ServiceRegistry::remove<I>() withdraws a provided service (child removal re-exposes a parent's entry). - EventBus::subscribe_scoped<E>() returns a move-only RAII Subscription that unsubscribes on destruction. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018yj92cCihyaYtf4gKCT3nv
287 lines
7.2 KiB
C++
287 lines
7.2 KiB
C++
#pragma once
|
|
|
|
#include <any>
|
|
#include <condition_variable>
|
|
#include <cstddef>
|
|
#include <cstdint>
|
|
#include <functional>
|
|
#include <mutex>
|
|
#include <queue>
|
|
#include <thread>
|
|
#include <typeindex>
|
|
#include <unordered_map>
|
|
#include <vector>
|
|
|
|
namespace Void::EventBus
|
|
{
|
|
|
|
// ── EventBus
|
|
// ──────────────────────────────────────────────────────────────────
|
|
// Publish/subscribe bus keyed by event type.
|
|
//
|
|
// Mode::Sync (default) handlers run inline on the publisher's thread
|
|
// inside
|
|
// publish() — the original zero-overhead behavior.
|
|
// Mode::Async publish() snapshots the handlers and a copy of
|
|
// the
|
|
// event onto an owned worker thread, so slow
|
|
// handlers (network / DB I/O) never block the
|
|
// publisher. flush() waits for everything submitted
|
|
// before the call.
|
|
//
|
|
// In Sync mode the bus is not thread-safe (use external locking if shared).
|
|
// In Async mode publish/subscribe/flush are safe to call from any thread.
|
|
|
|
enum class Mode { Sync, Async };
|
|
|
|
class EventBus
|
|
{
|
|
public:
|
|
|
|
using HandlerId = std::size_t;
|
|
|
|
explicit EventBus(Mode mode = Mode::Sync) : mode_(mode)
|
|
{
|
|
if (mode_ == Mode::Async) {
|
|
worker_ = std::thread([this] { run(); });
|
|
}
|
|
}
|
|
|
|
~EventBus()
|
|
{
|
|
if (mode_ == Mode::Async) {
|
|
{
|
|
std::unique_lock lock{mu_};
|
|
stop_ = true;
|
|
}
|
|
cv_.notify_all();
|
|
worker_.join();
|
|
}
|
|
}
|
|
|
|
EventBus(const EventBus&) = delete;
|
|
EventBus& operator=(const EventBus&) = delete;
|
|
EventBus(EventBus&&) = delete;
|
|
EventBus& operator=(EventBus&&) = delete;
|
|
|
|
// Subscribe to events of type Event. Returns a HandlerId for
|
|
// unsubscription.
|
|
template <typename Event>
|
|
HandlerId subscribe(std::function<void(const Event&)> 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<const Event&>(ev));
|
|
}});
|
|
return id;
|
|
}
|
|
|
|
// Move-only RAII handle for a subscription: unsubscribes on
|
|
// destruction (or reset()). Must not outlive the bus it came
|
|
// from — the bus is non-movable, so tie the Subscription's
|
|
// lifetime to a scope the bus outlives.
|
|
class Subscription
|
|
{
|
|
public:
|
|
|
|
Subscription() = default;
|
|
|
|
Subscription(Subscription&& other) noexcept
|
|
: bus_(other.bus_), id_(other.id_)
|
|
{
|
|
other.bus_ = nullptr;
|
|
}
|
|
|
|
Subscription& operator=(Subscription&& other) noexcept
|
|
{
|
|
if (this != &other) {
|
|
reset();
|
|
bus_ = other.bus_;
|
|
id_ = other.id_;
|
|
other.bus_ = nullptr;
|
|
}
|
|
return *this;
|
|
}
|
|
|
|
Subscription(const Subscription&) = delete;
|
|
Subscription& operator=(const Subscription&) = delete;
|
|
|
|
~Subscription() { reset(); }
|
|
|
|
// Unsubscribe now; safe to call repeatedly.
|
|
void reset()
|
|
{
|
|
if (bus_ != nullptr) {
|
|
bus_->unsubscribe(id_);
|
|
bus_ = nullptr;
|
|
}
|
|
}
|
|
|
|
[[nodiscard]] explicit operator bool() const noexcept
|
|
{
|
|
return bus_ != nullptr;
|
|
}
|
|
|
|
private:
|
|
|
|
friend class EventBus;
|
|
|
|
Subscription(EventBus* bus, HandlerId id)
|
|
: bus_(bus), id_(id)
|
|
{
|
|
}
|
|
|
|
EventBus* bus_ = nullptr;
|
|
HandlerId id_ = 0;
|
|
};
|
|
|
|
// Subscribe with automatic unsubscription: the returned handle
|
|
// removes the handler when it goes out of scope. Suits handlers
|
|
// owned by components (plugins, services) whose lifetime is
|
|
// shorter than the bus.
|
|
template <typename Event>
|
|
[[nodiscard]] Subscription
|
|
subscribe_scoped(std::function<void(const Event&)> handler)
|
|
{
|
|
return Subscription{this, subscribe<Event>(std::move(handler))};
|
|
}
|
|
|
|
// Publish an event to all subscribers of its type.
|
|
template <typename Event> void publish(const Event& event)
|
|
{
|
|
const auto key = std::type_index{typeid(Event)};
|
|
if (mode_ == Mode::Sync) {
|
|
const auto it = handlers_.find(key);
|
|
if (it == handlers_.end()) {
|
|
return;
|
|
}
|
|
for (const auto& e : it->second) {
|
|
e.fn(event);
|
|
}
|
|
return;
|
|
}
|
|
|
|
// Async: snapshot the current handlers and queue a dispatch
|
|
// carrying a copy of the event, so later unsubscribe()s don't
|
|
// affect this publish.
|
|
std::unique_lock lock{mu_};
|
|
const auto it = handlers_.find(key);
|
|
if (it == handlers_.end()) {
|
|
return;
|
|
}
|
|
std::vector<std::function<void(const std::any&)>> snapshot;
|
|
snapshot.reserve(it->second.size());
|
|
for (const auto& e : it->second) {
|
|
snapshot.push_back(e.fn);
|
|
}
|
|
tasks_.push([snap = std::move(snapshot), ev = std::any{event}] {
|
|
for (const auto& fn : snap) {
|
|
fn(ev);
|
|
}
|
|
});
|
|
++enqueued_;
|
|
lock.unlock();
|
|
cv_.notify_one();
|
|
}
|
|
|
|
// Async only: block until every event published before this call
|
|
// has been dispatched. A no-op in Sync mode (delivery already
|
|
// happened in publish()).
|
|
void flush()
|
|
{
|
|
if (mode_ != Mode::Async) {
|
|
return;
|
|
}
|
|
std::unique_lock lock{mu_};
|
|
const auto target = enqueued_;
|
|
done_cv_.wait(lock, [&] { return processed_ >= target; });
|
|
}
|
|
|
|
// Unsubscribe by id. O(n) per event type — acceptable for small
|
|
// handler counts.
|
|
void unsubscribe(HandlerId id)
|
|
{
|
|
std::unique_lock lock{mu_};
|
|
for (auto& [key, list] : handlers_) {
|
|
const auto before = list.size();
|
|
std::erase_if(list,
|
|
[id](const Entry& e) { return e.id == id; });
|
|
if (list.size() != before) {
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
|
|
// Remove all handlers for a given event type.
|
|
template <typename Event> void clear()
|
|
{
|
|
std::unique_lock lock{mu_};
|
|
handlers_.erase(std::type_index{typeid(Event)});
|
|
}
|
|
|
|
void clear_all()
|
|
{
|
|
std::unique_lock lock{mu_};
|
|
handlers_.clear();
|
|
}
|
|
|
|
template <typename Event>
|
|
[[nodiscard]] std::size_t subscriber_count() const
|
|
{
|
|
std::unique_lock lock{mu_};
|
|
const auto it = handlers_.find(std::type_index{typeid(Event)});
|
|
return it == handlers_.end() ? 0 : it->second.size();
|
|
}
|
|
|
|
[[nodiscard]] Mode mode() const noexcept { return mode_; }
|
|
|
|
private:
|
|
|
|
struct Entry {
|
|
HandlerId id;
|
|
std::function<void(const std::any&)> fn;
|
|
};
|
|
|
|
void run()
|
|
{
|
|
for (;;) {
|
|
std::function<void()> task;
|
|
{
|
|
std::unique_lock lock{mu_};
|
|
cv_.wait(lock,
|
|
[this] { return stop_ || !tasks_.empty(); });
|
|
if (stop_ && tasks_.empty()) {
|
|
return;
|
|
}
|
|
task = std::move(tasks_.front());
|
|
tasks_.pop();
|
|
}
|
|
task();
|
|
{
|
|
std::unique_lock lock{mu_};
|
|
++processed_;
|
|
}
|
|
done_cv_.notify_all();
|
|
}
|
|
}
|
|
|
|
Mode mode_;
|
|
std::unordered_map<std::type_index, std::vector<Entry>> handlers_;
|
|
HandlerId next_id_{1};
|
|
|
|
mutable std::mutex mu_;
|
|
// Async machinery (unused in Sync mode).
|
|
std::thread worker_;
|
|
std::queue<std::function<void()>> tasks_;
|
|
std::condition_variable cv_;
|
|
std::condition_variable done_cv_;
|
|
std::uint64_t enqueued_{0};
|
|
std::uint64_t processed_{0};
|
|
bool stop_{false};
|
|
};
|
|
|
|
} // namespace Void::EventBus
|