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:
faumarayandClaude Fable 5 committed 2026-07-11 23:39:10 +03:00
1 parent 7ca0e1b62e
commit ee4486e1d2
15 files changed
+750 -24

No files matched your search

+3 -3
View File
@@ -180,7 +180,7 @@ Other key points:
`Void::Service` — dependency inversion + FSM orchestration.
- `IService` base (`service_name()`, `on_start()`/`on_stop()` lifecycle).
- `ServiceRegistry` — type-keyed: `provide<I>(impl)`, `get<I>()` (nullptr if absent), `require<I>()` (throws), `has<I>()`, `start_all()`/`stop_all()`. Consumers depend only on interface `I` and resolve at runtime; a concrete deriving `IService` is recovered for lifecycle via `dynamic_cast` even when registered under a plain interface. `shared_mutex`, reads are the hot path.
- `ServiceRegistry` — type-keyed: `provide<I>(impl)`, `get<I>()` (nullptr if absent), `require<I>()` (throws), `has<I>()`, `remove<I>()` (withdraws the local entry; holders keep the instance alive, a parent's entry is re-exposed), `start_all()`/`stop_all()`. Consumers depend only on interface `I` and resolve at runtime; a concrete deriving `IService` is recovered for lifecycle via `dynamic_cast` even when registered under a plain interface. `shared_mutex`, reads are the hot path.
- `Fsm::Orchestrator` (in the Fsm module): owns a `ServiceRegistry`, `launch<F>(args...)` constructs an FSM, injects the registry (`set_services`), starts and supervises it via a `FsmHandle` (status/stop); `stop_all()` is balanced once against `start_services()`.
- `Service/PluginService.hpp`: `PluginServiceBinding<I>` binds a plugin-provided service into a registry and re-binds on hot reload. The interface `I` must derive `IService` (single inheritance) so the host recovers it from the plugin's exported `IService*` by `static_cast` — no `dynamic_cast` across the RTLD_LOCAL boundary. The registry entry pins the plugin instance.
@@ -218,9 +218,9 @@ Header layout (include `<Void/Fsm/Fsm.hpp>` — a thin umbrella): `Machine.hpp`
`Void::Plugin` loads C-ABI plugins (`.so`) and hot-reloads them with state transfer:
- **C ABI** (`Plugin.hpp`): required `void_plugin_create/destroy/info`; optional `void_plugin_transfer_state(old,new)` (raw) and the v2 state protocol `void_plugin_state_version` + `void_plugin_serialize_state`/`void_plugin_free_string` + `void_plugin_deserialize_state(inst, json, from_version)`. `ABI_VERSION` is checked; `IPlugin`'s vtable is frozen (append-only). State transfer prefers v2 serialize→deserialize (survives layout changes; migrations live in the *new* .so via `Json::MigrationChain`), falling back to `transfer_state`.
- **C ABI** (`Plugin.hpp`): required `void_plugin_create/destroy/info`; optional `void_plugin_transfer_state(old,new)` (raw), `void_plugin_configure(inst, config)` (host-supplied config string, called after create and after each reload swap, before `on_load()`), and the v2 state protocol `void_plugin_state_version` + `void_plugin_serialize_state`/`void_plugin_free_string` + `void_plugin_deserialize_state(inst, json, from_version)`. `ABI_VERSION` is checked; `IPlugin`'s vtable is frozen (append-only). State transfer prefers v2 serialize→deserialize (survives layout changes; migrations live in the *new* .so via `Json::MigrationChain`), falling back to `transfer_state`.
- **`PluginLoader`** — owns one instance; `reload()` copies the `.so` to a fresh-inode temp (so `dlopen` loads new bytes), creates the new instance, transfers state, swaps, destroys the old. Move-only.
- **`PluginManager`** — multi-plugin registry with **RCU-style pinned handles**: `acquire(name)` returns a `PluginHandle` (one `atomic<shared_ptr>` load) that keeps its instance alive for the whole call; `reload(name)` builds the new instance, transfers state, then `atomic_exchange`s it in — in-flight handles keep the old instance (and its mapped `.so`, since `dlclose_on_swap=false`) alive until they drop. Work never stops. `watch(name)` auto-reloads via `FileSystem::FileWatcher`; `on_reloaded` fires after each swap.
- **`PluginManager`** — multi-plugin registry with **RCU-style pinned handles**: `acquire(name)` returns a `PluginHandle` (one `atomic<shared_ptr>` load) that keeps its instance alive for the whole call; `reload(name)` builds the new instance, transfers state, then `atomic_exchange`s it in — in-flight handles keep the old instance (and its mapped `.so`, since `dlclose_on_swap=false`) alive until they drop. Work never stops. `watch(name)` auto-reloads via `FileSystem::FileWatcher`. Discovery: `load_directory(dir)` loads every shared-library file in a directory (filename order, per-file `expected` results). `unload(name)` drops the registry entry (instance dies with its last handle). `on_reloaded(cb)` is **multi-observer** — it returns a `ReloadCallbackId` for `remove_on_reloaded` and fires after every successful reload, manual or watched. `PluginManagerOptions::config_provider` feeds `void_plugin_configure`. Host-side state carry: `serialize_state(name)` → `StateSnapshot{json, version}` and `deserialize_state(name, json, from_version)` wrap the plugin's v2 exports so an embedder can persist plugin state across its *own* hot reload.
- **Reload safety rule**: deployments must install the new `.so` by **atomic rename (fresh inode)**, never by overwriting the mapped file in place — in-place overwrite corrupts the running instance's mmap (SIGBUS). The tests' `install()` helper shows the pattern (copy to `.incoming`, then rename).
## Code style
+70
View File
@@ -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)
{
+64 -4
View File
@@ -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;
};
+8
View File
@@ -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";
+29 -6
View File
@@ -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
+16
View File
@@ -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
+151 -11
View File
@@ -7,6 +7,7 @@
#define VOID_HAS_DLOPEN 1
#endif
#include <algorithm>
#include <cstdint>
#include <system_error>
#include <utility>
@@ -21,6 +22,7 @@ namespace Void::Plugin
IPlugin* plugin{nullptr};
destroy_fn destroy{nullptr};
transfer_fn transfer{nullptr};
configure_fn configure{nullptr};
state_version_fn state_version{nullptr};
serialize_fn serialize{nullptr};
free_string_fn free_string{nullptr};
@@ -115,6 +117,8 @@ namespace Void::Plugin
inst->destroy = destroy_sym;
inst->transfer =
reinterpret_cast<transfer_fn>(dlsym(h, kTransferSymbol));
inst->configure =
reinterpret_cast<configure_fn>(dlsym(h, kConfigureSymbol));
inst->state_version = reinterpret_cast<state_version_fn>(
dlsym(h, kStateVersionSymbol));
inst->serialize =
@@ -213,8 +217,12 @@ namespace Void::Plugin
path.string(), to_string(inst.error()));
return std::unexpected{inst.error()};
}
(*inst)->plugin->on_load();
std::string name{(*inst)->plugin->name()};
if (m_options.config_provider && (*inst)->configure != nullptr) {
const std::string config = m_options.config_provider(name);
(*inst)->configure((*inst)->plugin, config.c_str());
}
(*inst)->plugin->on_load();
std::lock_guard lock(m_mutex);
auto entry = std::make_unique<Entry>();
@@ -228,6 +236,52 @@ namespace Void::Plugin
return name;
}
std::vector<
std::pair<std::filesystem::path, std::expected<std::string, LoadError>>>
PluginManager::load_directory(const std::filesystem::path& dir)
{
#if defined(_WIN32)
constexpr std::string_view ext = ".dll";
#elif defined(__APPLE__)
constexpr std::string_view ext = ".dylib";
#else
constexpr std::string_view ext = ".so";
#endif
std::vector<std::filesystem::path> candidates;
std::error_code ec;
for (const auto& entry : std::filesystem::directory_iterator{dir, ec}) {
if (entry.is_regular_file(ec) && entry.path().extension() == ext) {
candidates.push_back(entry.path());
}
}
std::sort(candidates.begin(), candidates.end());
std::vector<std::pair<std::filesystem::path,
std::expected<std::string, LoadError>>>
out;
out.reserve(candidates.size());
for (auto& path : candidates) {
auto result = load(path);
out.emplace_back(std::move(path), std::move(result));
}
return out;
}
std::expected<void, LoadError> PluginManager::unload(std::string_view name)
{
std::lock_guard lock(m_mutex);
auto* entry = find(name);
if (entry == nullptr) {
return std::unexpected{LoadError::UnknownPlugin};
}
m_watcher.unwatch(entry->path);
// Erasing drops the registry's reference; outstanding handles keep
// the instance (and its mapped .so) alive until they drop.
m_plugins.erase(std::string{name});
Void::Log::info("Plugin.Manager", "unloaded '{}'", name);
return {};
}
PluginHandle PluginManager::acquire(std::string_view name) const
{
std::lock_guard lock(m_mutex);
@@ -241,12 +295,23 @@ namespace Void::Plugin
std::expected<void, LoadError> PluginManager::reload(std::string_view name)
{
std::lock_guard lock(m_mutex);
auto* entry = find(name);
if (entry == nullptr) {
return std::unexpected{LoadError::UnknownPlugin};
std::vector<std::function<void(std::string_view)>> callbacks;
{
std::lock_guard lock(m_mutex);
auto* entry = find(name);
if (entry == nullptr) {
return std::unexpected{LoadError::UnknownPlugin};
}
auto result = reload_locked(*entry, name);
if (!result.has_value()) {
return result;
}
callbacks = reload_callbacks_locked();
}
return reload_locked(*entry, name);
for (const auto& cb : callbacks) {
cb(name);
}
return {};
}
std::expected<void, LoadError>
@@ -271,6 +336,11 @@ namespace Void::Plugin
return std::unexpected{next.error()};
}
if (m_options.config_provider && (*next)->configure != nullptr) {
const std::string config = m_options.config_provider(name);
(*next)->configure((*next)->plugin, config.c_str());
}
// Transfer state with both instances alive (transactional).
auto old = entry.current.load(std::memory_order_acquire);
if (old) {
@@ -306,7 +376,7 @@ namespace Void::Plugin
if (!e.exists) {
return;
}
std::function<void(std::string_view)> cb;
std::vector<std::function<void(std::string_view)>> callbacks;
{
std::lock_guard lock(m_mutex);
auto* entry = find(name_str);
@@ -316,9 +386,9 @@ namespace Void::Plugin
if (!reload_locked(*entry, name_str).has_value()) {
return;
}
cb = m_on_reloaded;
callbacks = reload_callbacks_locked();
}
if (cb) {
for (const auto& cb : callbacks) {
cb(name_str);
}
});
@@ -333,11 +403,81 @@ namespace Void::Plugin
}
}
void PluginManager::on_reloaded(
ReloadCallbackId PluginManager::on_reloaded(
std::function<void(std::string_view name)> cb)
{
std::lock_guard lock(m_mutex);
m_on_reloaded = std::move(cb);
const ReloadCallbackId id = m_next_reload_id++;
m_on_reloaded.emplace_back(id, std::move(cb));
return id;
}
void PluginManager::remove_on_reloaded(ReloadCallbackId id)
{
std::lock_guard lock(m_mutex);
std::erase_if(m_on_reloaded,
[id](const auto& pair) { return pair.first == id; });
}
std::vector<std::function<void(std::string_view)>>
PluginManager::reload_callbacks_locked() const
{
std::vector<std::function<void(std::string_view)>> out;
out.reserve(m_on_reloaded.size());
for (const auto& [_, cb] : m_on_reloaded) {
out.push_back(cb);
}
return out;
}
std::optional<PluginManager::StateSnapshot>
PluginManager::serialize_state(std::string_view name) const
{
std::shared_ptr<detail::Instance> inst;
{
std::lock_guard lock(m_mutex);
auto* entry = find(name);
if (entry == nullptr) {
return std::nullopt;
}
inst = entry->current.load(std::memory_order_acquire);
}
if (!inst || inst->serialize == nullptr) {
return std::nullopt;
}
const char* json = inst->serialize(inst->plugin);
if (json == nullptr) {
return std::nullopt;
}
StateSnapshot snapshot{.json = std::string{json},
.version = inst->state_version != nullptr
? inst->state_version()
: 0};
if (inst->free_string != nullptr) {
inst->free_string(json);
}
return snapshot;
}
bool PluginManager::deserialize_state(std::string_view name,
std::string_view json,
std::uint32_t from_version)
{
std::shared_ptr<detail::Instance> inst;
{
std::lock_guard lock(m_mutex);
auto* entry = find(name);
if (entry == nullptr) {
return false;
}
inst = entry->current.load(std::memory_order_acquire);
}
if (!inst || inst->deserialize == nullptr) {
return false;
}
const std::string terminated{json};
return inst->deserialize(inst->plugin, terminated.c_str(),
from_version) == 0;
}
std::vector<std::string> PluginManager::names() const
+12
View File
@@ -98,6 +98,18 @@ if(TARGET Void::Plugin)
add_dependencies(VoidTests VoidTestPlugin)
endif()
# Configurable plugin — exercises the optional void_plugin_configure
# entry point driven by PluginManagerOptions::config_provider.
add_library(VoidConfigurablePlugin SHARED
"${CMAKE_CURRENT_SOURCE_DIR}/plugins/ConfigurablePlugin.cpp")
target_link_libraries(VoidConfigurablePlugin PRIVATE Void::Plugin)
target_include_directories(VoidConfigurablePlugin PRIVATE
"${CMAKE_CURRENT_SOURCE_DIR}/plugins")
target_compile_definitions(VoidTests PRIVATE
"VOID_CONFIGURABLE_PATH=\"$<TARGET_FILE:VoidConfigurablePlugin>\""
)
add_dependencies(VoidTests VoidConfigurablePlugin)
# Stateful plugins (schema v1 + v2) for hot-reload/state-migration
# tests. Same plugin name; v2 adds a field and migrates v1 JSON.
add_library(VoidStatefulPluginV1 SHARED
+25
View File
@@ -0,0 +1,25 @@
#pragma once
#include <Void/Plugin/Plugin.hpp>
#include <string_view>
// Shared interface for the configure-entry-point test plugin. Same
// single-inheritance static_cast recovery pattern as Stateful.hpp.
namespace VoidTest
{
class IConfigurable : public Void::Plugin::IPlugin
{
public:
[[nodiscard]] virtual std::string_view last_config() const = 0;
[[nodiscard]] virtual int configure_calls() const = 0;
[[nodiscard]] virtual bool configured_before_on_load() const = 0;
};
[[nodiscard]] inline IConfigurable*
as_configurable(Void::Plugin::IPlugin* p)
{
return static_cast<IConfigurable*>(p);
}
} // namespace VoidTest
+78
View File
@@ -0,0 +1,78 @@
#include "Configurable.hpp"
#include <Void/Plugin/Plugin.hpp>
#include <string>
// A plugin that records what the host passes through the optional
// void_plugin_configure entry point, and when (relative to on_load).
namespace
{
class ConfigurablePlugin final : public VoidTest::IConfigurable
{
public:
[[nodiscard]] std::string_view name() const noexcept override
{
return "ConfigurablePlugin";
}
void on_load() override { loaded_ = true; }
[[nodiscard]] std::string_view last_config() const override
{
return config_;
}
[[nodiscard]] int configure_calls() const override
{
return calls_;
}
[[nodiscard]] bool configured_before_on_load() const override
{
return before_on_load_;
}
void apply_config(const char* config)
{
config_ = config != nullptr ? config : "";
++calls_;
if (!loaded_) {
before_on_load_ = true;
}
}
private:
std::string config_;
int calls_{0};
bool loaded_{false};
bool before_on_load_{false};
};
} // namespace
extern "C" {
void* void_plugin_create() { return new ConfigurablePlugin; }
void void_plugin_destroy(void* p)
{
delete static_cast<ConfigurablePlugin*>(p);
}
Void::Plugin::PluginInfo void_plugin_info()
{
return {
.abi_version = Void::Plugin::ABI_VERSION,
.name = "ConfigurablePlugin",
.plugin_version = "1.0.0",
.description = "Configure entry-point test plugin",
};
}
void void_plugin_configure(void* instance, const char* config)
{
static_cast<ConfigurablePlugin*>(instance)->apply_config(config);
}
}
+40
View File
@@ -3,6 +3,7 @@
#include <Void/Testing/Test.hpp>
#include <string>
#include <utility>
using namespace Void::EventBus;
@@ -113,3 +114,42 @@ Void::Testing::Test bus_event_data_forwarded()
bus.publish(TextChanged{"hello"});
Void::Testing::expect_eq(received, std::string{"hello"});
}
// ── scoped (RAII) subscriptions ───────────────────────────────────────────────
Void::Testing::Test bus_scoped_subscription_unsubscribes_on_destruction()
{
EventBus bus;
int count = 0;
{
auto sub =
bus.subscribe_scoped<Clicked>([&](const Clicked&) { ++count; });
Void::Testing::expect(static_cast<bool>(sub));
bus.publish(Clicked{0, 0});
Void::Testing::expect_eq(count, 1);
}
// Handler removed with the subscription.
bus.publish(Clicked{0, 0});
Void::Testing::expect_eq(count, 1);
Void::Testing::expect_eq(bus.subscriber_count<Clicked>(), std::size_t{0});
}
Void::Testing::Test bus_scoped_subscription_moves_ownership()
{
EventBus bus;
int count = 0;
auto outer = EventBus::Subscription{};
{
auto inner =
bus.subscribe_scoped<Clicked>([&](const Clicked&) { ++count; });
outer = std::move(inner);
Void::Testing::expect(!static_cast<bool>(inner));
}
// The moved-from handle's death did not unsubscribe.
bus.publish(Clicked{0, 0});
Void::Testing::expect_eq(count, 1);
outer.reset();
bus.publish(Clicked{0, 0});
Void::Testing::expect_eq(count, 1);
}
+70
View File
@@ -0,0 +1,70 @@
#include <Void/Plugin/Manager.hpp>
#include <Void/System/TempDir.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include "Configurable.hpp"
#include <filesystem>
#include <string>
using namespace Void::Plugin;
#if defined(VOID_CONFIGURABLE_PATH) && __has_include(<dlfcn.h>)
namespace
{
VoidTest::IConfigurable* configurable(const PluginHandle& h)
{
return VoidTest::as_configurable(h.get());
}
} // namespace
Void::Testing::Test configure_called_with_provider_payload_before_on_load()
{
PluginManager mgr{{.config_provider = [](std::string_view name) {
return std::string{"{\"plugin\":\""} + std::string{name} + "\"}";
}}};
const auto name = mgr.load(VOID_CONFIGURABLE_PATH);
Void::Testing::expect(name.has_value());
auto h = mgr.acquire("ConfigurablePlugin");
Void::Testing::expect_eq(configurable(h)->configure_calls(), 1);
Void::Testing::expect(configurable(h)->configured_before_on_load());
Void::Testing::expect_eq(
configurable(h)->last_config(),
std::string_view{"{\"plugin\":\"ConfigurablePlugin\"}"});
}
Void::Testing::Test configure_reruns_on_reload_with_fresh_payload()
{
Void::FileSystem::TempDir tmp{"void_cfg"};
const auto so = tmp.path() / "plugin.so";
std::filesystem::copy_file(VOID_CONFIGURABLE_PATH, so);
int generation = 0;
PluginManager mgr{{.config_provider = [&generation](std::string_view) {
return std::string{"gen="} + std::to_string(generation);
}}};
Void::Testing::expect(mgr.load(so).has_value());
generation = 1;
Void::Testing::expect(mgr.reload("ConfigurablePlugin").has_value());
auto h = mgr.acquire("ConfigurablePlugin");
// The reloaded instance is fresh: one configure call, new payload.
Void::Testing::expect_eq(configurable(h)->configure_calls(), 1);
Void::Testing::expect_eq(configurable(h)->last_config(),
std::string_view{"gen=1"});
Void::Testing::expect(configurable(h)->configured_before_on_load());
}
Void::Testing::Test configure_skipped_without_provider()
{
PluginManager mgr;
Void::Testing::expect(mgr.load(VOID_CONFIGURABLE_PATH).has_value());
auto h = mgr.acquire("ConfigurablePlugin");
Void::Testing::expect_eq(configurable(h)->configure_calls(), 0);
}
#endif // configurable plugin available
+72
View File
@@ -0,0 +1,72 @@
#include <Void/Plugin/Loader.hpp>
#include <Void/Plugin/Manager.hpp>
#include <Void/System/TempDir.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <filesystem>
#include <fstream>
#include <string>
using namespace Void::Plugin;
#if defined(VOID_TEST_PLUGIN_PATH) && defined(VOID_STATEFUL_V1_PATH) && \
__has_include(<dlfcn.h>)
Void::Testing::Test discovery_loads_all_plugins_in_filename_order()
{
Void::FileSystem::TempDir tmp{"void_disc"};
std::filesystem::copy_file(VOID_STATEFUL_V1_PATH,
tmp.path() / "b_stateful.so");
std::filesystem::copy_file(VOID_TEST_PLUGIN_PATH, tmp.path() / "a_test.so");
{
std::ofstream decoy{tmp.path() / "readme.txt"};
decoy << "not a plugin";
}
std::filesystem::create_directory(tmp.path() / "subdir");
PluginManager mgr;
const auto results = mgr.load_directory(tmp.path());
// Only the two .so files count, sorted by filename.
Void::Testing::expect_eq(results.size(), std::size_t{2});
Void::Testing::expect_eq(results[0].first.filename().string(),
std::string{"a_test.so"});
Void::Testing::expect(results[0].second.has_value());
Void::Testing::expect_eq(*results[0].second, std::string{"TestPlugin"});
Void::Testing::expect_eq(results[1].first.filename().string(),
std::string{"b_stateful.so"});
Void::Testing::expect(results[1].second.has_value());
Void::Testing::expect_eq(*results[1].second, std::string{"StatefulPlugin"});
Void::Testing::expect(static_cast<bool>(mgr.acquire("TestPlugin")));
Void::Testing::expect(static_cast<bool>(mgr.acquire("StatefulPlugin")));
}
Void::Testing::Test discovery_reports_per_file_errors()
{
Void::FileSystem::TempDir tmp{"void_disc"};
std::filesystem::copy_file(VOID_TEST_PLUGIN_PATH, tmp.path() / "ok.so");
{
std::ofstream bogus{tmp.path() / "broken.so"};
bogus << "ELF? no.";
}
PluginManager mgr;
const auto results = mgr.load_directory(tmp.path());
Void::Testing::expect_eq(results.size(), std::size_t{2});
// broken.so sorts first and fails to dlopen; ok.so loads.
Void::Testing::expect(!results[0].second.has_value());
Void::Testing::expect(results[0].second.error() == LoadError::DlopenFailed);
Void::Testing::expect(results[1].second.has_value());
}
Void::Testing::Test discovery_missing_directory_yields_empty()
{
PluginManager mgr;
const auto results = mgr.load_directory("/nonexistent/void_discovery_test");
Void::Testing::expect(results.empty());
}
#endif // test plugins available
+75
View File
@@ -166,4 +166,79 @@ Void::Testing::Test manager_watch_auto_reloads_on_file_change()
mgr.unwatch("StatefulPlugin");
}
Void::Testing::Test manager_multiple_reload_observers_coexist()
{
Void::FileSystem::TempDir tmp{"void_mgr"};
const auto so = tmp.path() / "plugin.so";
std::filesystem::copy_file(VOID_STATEFUL_V1_PATH, so);
PluginManager mgr;
Void::Testing::expect(mgr.load(so).has_value());
int first = 0;
int second = 0;
std::string seen;
const auto id1 = mgr.on_reloaded([&](std::string_view n) {
++first;
seen = std::string{n};
});
(void)mgr.on_reloaded([&](std::string_view) { ++second; });
// Manual reloads notify every observer (not only watched ones).
install(VOID_STATEFUL_V2_PATH, so);
Void::Testing::expect(mgr.reload("StatefulPlugin").has_value());
Void::Testing::expect_eq(first, 1);
Void::Testing::expect_eq(second, 1);
Void::Testing::expect_eq(seen, std::string{"StatefulPlugin"});
// A removed observer stays silent; the other keeps firing.
mgr.remove_on_reloaded(id1);
Void::Testing::expect(mgr.reload("StatefulPlugin").has_value());
Void::Testing::expect_eq(first, 1);
Void::Testing::expect_eq(second, 2);
}
Void::Testing::Test manager_unload_drops_entry_but_pinned_handle_survives()
{
PluginManager mgr;
Void::Testing::expect(mgr.load(VOID_STATEFUL_V1_PATH).has_value());
auto pinned = mgr.acquire("StatefulPlugin");
stateful(pinned)->bump();
Void::Testing::expect(mgr.unload("StatefulPlugin").has_value());
// Gone from the registry…
Void::Testing::expect(!static_cast<bool>(mgr.acquire("StatefulPlugin")));
Void::Testing::expect(mgr.unload("StatefulPlugin").error() ==
LoadError::UnknownPlugin);
// …but the pinned instance still works until the handle drops.
Void::Testing::expect_eq(stateful(pinned)->counter(), 1);
}
Void::Testing::Test manager_state_snapshot_round_trip()
{
PluginManager mgr;
Void::Testing::expect(mgr.load(VOID_STATEFUL_V1_PATH).has_value());
auto h = mgr.acquire("StatefulPlugin");
stateful(h)->bump();
stateful(h)->bump(); // counter = 2
const auto snapshot = mgr.serialize_state("StatefulPlugin");
Void::Testing::expect(snapshot.has_value());
Void::Testing::expect_eq(snapshot->version, std::uint32_t{1});
stateful(h)->bump(); // counter = 3
// Injecting the snapshot restores the earlier state.
Void::Testing::expect(mgr.deserialize_state(
"StatefulPlugin", snapshot->json, snapshot->version));
Void::Testing::expect_eq(stateful(h)->counter(), 2);
// Unknown plugins produce no snapshot and reject injection.
Void::Testing::expect(!mgr.serialize_state("nope").has_value());
Void::Testing::expect(
!mgr.deserialize_state("nope", snapshot->json, snapshot->version));
}
#endif // stateful plugins available
+37
View File
@@ -114,6 +114,43 @@ Void::Testing::Test registry_replace_provider()
Void::Testing::expect_eq(reg.size(), std::size_t{1});
}
Void::Testing::Test registry_remove_withdraws_entry()
{
ServiceRegistry reg;
auto clock = std::make_shared<FixedClock>(7);
reg.provide<IClock>(clock);
// A consumer resolved before the removal keeps its instance.
auto held = reg.get<IClock>();
Void::Testing::expect(reg.remove<IClock>());
Void::Testing::expect(!reg.has<IClock>());
Void::Testing::expect(reg.get<IClock>() == nullptr);
Void::Testing::expect_eq(reg.size(), std::size_t{0});
Void::Testing::expect_eq(held->now(), 7);
// Removing again reports nothing to remove.
Void::Testing::expect(!reg.remove<IClock>());
// Re-providing after removal works (fresh lifecycle position).
reg.provide<IClock>(std::make_shared<FixedClock>(9));
Void::Testing::expect_eq(reg.require<IClock>().now(), 9);
}
Void::Testing::Test registry_remove_in_child_reexposes_parent()
{
ServiceRegistry parent;
parent.provide<IClock>(std::make_shared<FixedClock>(1));
ServiceRegistry child{&parent};
child.provide<IClock>(std::make_shared<FixedClock>(2));
Void::Testing::expect_eq(child.require<IClock>().now(), 2);
// Removing the child's shadow re-exposes the parent's entry.
Void::Testing::expect(child.remove<IClock>());
Void::Testing::expect_eq(child.require<IClock>().now(), 1);
}
Void::Testing::Test registry_lifecycle_order()
{
std::vector<std::string> log;