Plugin: discovery, unload, config entry, multi-observer reloads, state API
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
This commit is contained in:
1 parent
7ca0e1b62e
commit
ee4486e1d2
15 files changed
+750
-24
No files matched your search
@@ -79,6 +79,76 @@ namespace Void::EventBus
|
||||
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)
|
||||
{
|
||||
|
||||
@@ -5,14 +5,17 @@
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <expected>
|
||||
#include <filesystem>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <unordered_map>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Plugin
|
||||
@@ -71,8 +74,17 @@ namespace Void::Plugin
|
||||
// executing would crash. Pins already prevent the instance from
|
||||
// being destroyed; this guards the code pages.
|
||||
bool dlclose_on_swap = false;
|
||||
// Per-plugin configuration source. When set, its result is passed
|
||||
// to the plugin's optional void_plugin_configure entry point after
|
||||
// create and after each reload swap, before on_load(). The plugin
|
||||
// name argument is the registry name (IPlugin::name()).
|
||||
std::function<std::string(std::string_view plugin_name)>
|
||||
config_provider;
|
||||
};
|
||||
|
||||
// Identifies an on_reloaded observer for remove_on_reloaded.
|
||||
using ReloadCallbackId = std::size_t;
|
||||
|
||||
class PluginManager
|
||||
{
|
||||
public:
|
||||
@@ -92,6 +104,22 @@ namespace Void::Plugin
|
||||
std::expected<std::string, LoadError>
|
||||
load(const std::filesystem::path& path);
|
||||
|
||||
/// Load every plugin file in `dir` (non-recursive), in filename
|
||||
/// order for determinism. Only files with the platform's shared-
|
||||
/// library extension are considered. Returns one entry per
|
||||
/// candidate: its path and either the loaded plugin's name or
|
||||
/// the load error. An empty result means no candidates existed
|
||||
/// (or the directory does not).
|
||||
std::vector<std::pair<std::filesystem::path,
|
||||
std::expected<std::string, LoadError>>>
|
||||
load_directory(const std::filesystem::path& dir);
|
||||
|
||||
/// Unload `name`: stop watching it and drop it from the
|
||||
/// registry. The instance is destroyed once the last
|
||||
/// outstanding PluginHandle drops (RCU semantics, same as a
|
||||
/// reload swap).
|
||||
std::expected<void, LoadError> unload(std::string_view name);
|
||||
|
||||
/// Pin the current instance for `name`. The returned handle
|
||||
/// keeps it alive for as long as it lives. Empty handle if no
|
||||
/// such plugin. One atomic load on the hot path.
|
||||
@@ -109,9 +137,36 @@ namespace Void::Plugin
|
||||
void watch(std::string_view name);
|
||||
void unwatch(std::string_view name);
|
||||
|
||||
/// Invoked after every successful reload (manual or watched),
|
||||
/// on the caller's / watcher's thread.
|
||||
void on_reloaded(std::function<void(std::string_view name)> cb);
|
||||
/// Register an observer invoked after every successful reload
|
||||
/// (manual or watched), on the reloading thread. Multiple
|
||||
/// observers coexist; the returned id removes this one.
|
||||
ReloadCallbackId
|
||||
on_reloaded(std::function<void(std::string_view name)> cb);
|
||||
void remove_on_reloaded(ReloadCallbackId id);
|
||||
|
||||
/// A point-in-time state snapshot taken through the plugin's v2
|
||||
/// serialize export, for embedders that need to carry plugin
|
||||
/// state through their *own* lifecycle (e.g. the host process
|
||||
/// hot-reloading itself). `version` is the plugin's state
|
||||
/// schema version at snapshot time.
|
||||
struct StateSnapshot {
|
||||
std::string json;
|
||||
std::uint32_t version{0};
|
||||
};
|
||||
|
||||
/// Snapshot `name`'s current state. Empty when the plugin is
|
||||
/// unknown, exports no v2 serialize, or serialization fails.
|
||||
[[nodiscard]] std::optional<StateSnapshot>
|
||||
serialize_state(std::string_view name) const;
|
||||
|
||||
/// Inject a serialized state into `name`'s current instance via
|
||||
/// its v2 deserialize export. `from_version` is the schema
|
||||
/// version the JSON was produced with (migrations live in the
|
||||
/// plugin). Returns false when the plugin is unknown, exports
|
||||
/// no deserialize, or rejects the state.
|
||||
bool deserialize_state(std::string_view name,
|
||||
std::string_view json,
|
||||
std::uint32_t from_version);
|
||||
|
||||
[[nodiscard]] std::vector<std::string> names() const;
|
||||
|
||||
@@ -132,11 +187,16 @@ namespace Void::Plugin
|
||||
Entry* find(std::string_view name) const;
|
||||
std::expected<void, LoadError> reload_locked(Entry& entry,
|
||||
std::string_view name);
|
||||
std::vector<std::function<void(std::string_view)>>
|
||||
reload_callbacks_locked() const;
|
||||
|
||||
Options m_options;
|
||||
mutable std::mutex m_mutex; // guards the registry map + reloads
|
||||
std::unordered_map<std::string, std::unique_ptr<Entry>> m_plugins;
|
||||
std::function<void(std::string_view)> m_on_reloaded;
|
||||
std::vector<std::pair<ReloadCallbackId,
|
||||
std::function<void(std::string_view)>>>
|
||||
m_on_reloaded;
|
||||
ReloadCallbackId m_next_reload_id{1};
|
||||
FileSystem::FileWatcher m_watcher;
|
||||
};
|
||||
|
||||
|
||||
@@ -49,6 +49,12 @@ public:
|
||||
// Optional (enables hot-reload state transfer):
|
||||
// void void_plugin_transfer_state(void* old, void* new)
|
||||
//
|
||||
// Optional (enables host-supplied configuration):
|
||||
// void void_plugin_configure(void* instance, const char* config)
|
||||
// — called by the host with an opaque configuration string (typically
|
||||
// JSON) after create and after each hot-reload swap, before
|
||||
// on_load(). The string is only valid for the duration of the call.
|
||||
//
|
||||
// Optional v2 state protocol (preferred over transfer_state when both
|
||||
// sides provide it; survives layout changes between plugin versions):
|
||||
//
|
||||
@@ -67,6 +73,7 @@ using create_fn = void* (*)(void);
|
||||
using destroy_fn = void (*)(void*);
|
||||
using info_fn = PluginInfo (*)(void);
|
||||
using transfer_fn = void (*)(void* old_instance, void* new_instance);
|
||||
using configure_fn = void (*)(void* instance, const char* config);
|
||||
using state_version_fn = std::uint32_t (*)(void);
|
||||
using serialize_fn = const char* (*)(void* instance);
|
||||
using free_string_fn = void (*)(const char*);
|
||||
@@ -77,6 +84,7 @@ inline constexpr const char* kCreateSymbol = "void_plugin_create";
|
||||
inline constexpr const char* kDestroySymbol = "void_plugin_destroy";
|
||||
inline constexpr const char* kInfoSymbol = "void_plugin_info";
|
||||
inline constexpr const char* kTransferSymbol = "void_plugin_transfer_state";
|
||||
inline constexpr const char* kConfigureSymbol = "void_plugin_configure";
|
||||
inline constexpr const char* kStateVersionSymbol = "void_plugin_state_version";
|
||||
inline constexpr const char* kSerializeSymbol = "void_plugin_serialize_state";
|
||||
inline constexpr const char* kFreeStringSymbol = "void_plugin_free_string";
|
||||
|
||||
@@ -47,6 +47,14 @@ namespace Void::Service
|
||||
{
|
||||
}
|
||||
|
||||
// The reload callback captures `this`; the binding must
|
||||
// deregister it before dying and therefore cannot move.
|
||||
PluginServiceBinding(const PluginServiceBinding&) = delete;
|
||||
PluginServiceBinding&
|
||||
operator=(const PluginServiceBinding&) = delete;
|
||||
|
||||
~PluginServiceBinding() { disable_hot_reload(); }
|
||||
|
||||
/// Resolve the current instance's service and (re)register it.
|
||||
[[nodiscard]] bool bind()
|
||||
{
|
||||
@@ -77,22 +85,37 @@ namespace Void::Service
|
||||
|
||||
/// Auto-rebind on hot reload (debounced file watching). The
|
||||
/// manager keeps old instances alive while pinned, so the swap
|
||||
/// is seamless.
|
||||
/// is seamless. Idempotent.
|
||||
void enable_hot_reload()
|
||||
{
|
||||
m_manager->on_reloaded([this](std::string_view name) {
|
||||
if (name == m_name) {
|
||||
(void)bind();
|
||||
}
|
||||
});
|
||||
if (m_reload_id != 0) {
|
||||
return;
|
||||
}
|
||||
m_reload_id =
|
||||
m_manager->on_reloaded([this](std::string_view name) {
|
||||
if (name == m_name) {
|
||||
(void)bind();
|
||||
}
|
||||
});
|
||||
m_manager->watch(m_name);
|
||||
}
|
||||
|
||||
/// Stop observing reloads (the file watch itself is shared and
|
||||
/// stays). Idempotent; called by the destructor.
|
||||
void disable_hot_reload()
|
||||
{
|
||||
if (m_reload_id != 0) {
|
||||
m_manager->remove_on_reloaded(m_reload_id);
|
||||
m_reload_id = 0;
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
Plugin::PluginManager* m_manager;
|
||||
ServiceRegistry* m_registry;
|
||||
std::string m_name;
|
||||
Plugin::ReloadCallbackId m_reload_id{0};
|
||||
};
|
||||
|
||||
} // namespace Void::Service
|
||||
@@ -80,6 +80,22 @@ namespace Void::Service
|
||||
m_services.insert_or_assign(key, std::move(entry));
|
||||
}
|
||||
|
||||
/// Withdraw the implementation for interface I from this registry
|
||||
/// (a parent's entry is unaffected: later lookups fall through to
|
||||
/// it again). Consumers still holding the shared_ptr keep the
|
||||
/// instance alive; only new lookups miss. Returns true when an
|
||||
/// entry was removed.
|
||||
template <typename I> bool remove()
|
||||
{
|
||||
const std::type_index key{typeid(I)};
|
||||
std::unique_lock lock{m_mutex};
|
||||
if (m_services.erase(key) == 0) {
|
||||
return false;
|
||||
}
|
||||
std::erase(m_order, key);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// Resolve I, or nullptr if not provided. Falls through to the
|
||||
/// parent registry (if any) on a local miss.
|
||||
template <typename I> [[nodiscard]] std::shared_ptr<I> get() const
|
||||
|
||||
Reference in new issue
Block a user