From ee4486e1d27072dfe6da60b8968cf62a7cfc6994 Mon Sep 17 00:00:00 2001 From: faumaray Date: Sat, 11 Jul 2026 23:39:10 +0300 Subject: [PATCH 1/4] 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() withdraws a provided service (child removal re-exposes a parent's entry). - EventBus::subscribe_scoped() returns a move-only RAII Subscription that unsubscribes on destruction. Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_018yj92cCihyaYtf4gKCT3nv --- CLAUDE.md | 6 +- include/Void/Async/EventBus.hpp | 70 +++++++++++ include/Void/Plugin/Manager.hpp | 68 ++++++++++- include/Void/Plugin/Plugin.hpp | 8 ++ include/Void/Service/PluginService.hpp | 35 +++++- include/Void/Service/Registry.hpp | 16 +++ src/Plugin/Manager.cpp | 162 +++++++++++++++++++++++-- tests/CMakeLists.txt | 12 ++ tests/plugins/Configurable.hpp | 25 ++++ tests/plugins/ConfigurablePlugin.cpp | 78 ++++++++++++ tests/standalone/Async/EventBus.cpp | 40 ++++++ tests/standalone/Plugin/Configure.cpp | 70 +++++++++++ tests/standalone/Plugin/Discovery.cpp | 72 +++++++++++ tests/standalone/Plugin/Manager.cpp | 75 ++++++++++++ tests/standalone/Service/Registry.cpp | 37 ++++++ 15 files changed, 750 insertions(+), 24 deletions(-) create mode 100644 tests/plugins/Configurable.hpp create mode 100644 tests/plugins/ConfigurablePlugin.cpp create mode 100644 tests/standalone/Plugin/Configure.cpp create mode 100644 tests/standalone/Plugin/Discovery.cpp diff --git a/CLAUDE.md b/CLAUDE.md index c97470e..4c72be8 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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(impl)`, `get()` (nullptr if absent), `require()` (throws), `has()`, `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(impl)`, `get()` (nullptr if absent), `require()` (throws), `has()`, `remove()` (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(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` 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 `` — 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` 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` 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 diff --git a/include/Void/Async/EventBus.hpp b/include/Void/Async/EventBus.hpp index d12edca..276892e 100644 --- a/include/Void/Async/EventBus.hpp +++ b/include/Void/Async/EventBus.hpp @@ -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 + [[nodiscard]] Subscription + subscribe_scoped(std::function handler) + { + return Subscription{this, subscribe(std::move(handler))}; + } + // Publish an event to all subscribers of its type. template void publish(const Event& event) { diff --git a/include/Void/Plugin/Manager.hpp b/include/Void/Plugin/Manager.hpp index 86cfdc1..e132f7a 100644 --- a/include/Void/Plugin/Manager.hpp +++ b/include/Void/Plugin/Manager.hpp @@ -5,14 +5,17 @@ #include #include +#include #include #include #include #include #include +#include #include #include #include +#include #include 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 + 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 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>> + 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 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 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 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 + 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 names() const; @@ -132,11 +187,16 @@ namespace Void::Plugin Entry* find(std::string_view name) const; std::expected reload_locked(Entry& entry, std::string_view name); + std::vector> + reload_callbacks_locked() const; Options m_options; mutable std::mutex m_mutex; // guards the registry map + reloads std::unordered_map> m_plugins; - std::function m_on_reloaded; + std::vector>> + m_on_reloaded; + ReloadCallbackId m_next_reload_id{1}; FileSystem::FileWatcher m_watcher; }; diff --git a/include/Void/Plugin/Plugin.hpp b/include/Void/Plugin/Plugin.hpp index f1bb3ed..b74aa54 100644 --- a/include/Void/Plugin/Plugin.hpp +++ b/include/Void/Plugin/Plugin.hpp @@ -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"; diff --git a/include/Void/Service/PluginService.hpp b/include/Void/Service/PluginService.hpp index 37183b9..b44d38a 100644 --- a/include/Void/Service/PluginService.hpp +++ b/include/Void/Service/PluginService.hpp @@ -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 diff --git a/include/Void/Service/Registry.hpp b/include/Void/Service/Registry.hpp index 5902755..aec3459 100644 --- a/include/Void/Service/Registry.hpp +++ b/include/Void/Service/Registry.hpp @@ -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 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 [[nodiscard]] std::shared_ptr get() const diff --git a/src/Plugin/Manager.cpp b/src/Plugin/Manager.cpp index fd2ba6b..f7bcb9d 100644 --- a/src/Plugin/Manager.cpp +++ b/src/Plugin/Manager.cpp @@ -7,6 +7,7 @@ #define VOID_HAS_DLOPEN 1 #endif +#include #include #include #include @@ -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(dlsym(h, kTransferSymbol)); + inst->configure = + reinterpret_cast(dlsym(h, kConfigureSymbol)); inst->state_version = reinterpret_cast( 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(); @@ -228,6 +236,52 @@ namespace Void::Plugin return name; } + std::vector< + std::pair>> + 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 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>> + 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 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 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> 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 @@ -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 cb; + std::vector> 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 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> + PluginManager::reload_callbacks_locked() const + { + std::vector> out; + out.reserve(m_on_reloaded.size()); + for (const auto& [_, cb] : m_on_reloaded) { + out.push_back(cb); + } + return out; + } + + std::optional + PluginManager::serialize_state(std::string_view name) const + { + std::shared_ptr 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 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 PluginManager::names() const diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 3a0ec87..8b28b3d 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -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=\"$\"" + ) + 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 diff --git a/tests/plugins/Configurable.hpp b/tests/plugins/Configurable.hpp new file mode 100644 index 0000000..f5a2a37 --- /dev/null +++ b/tests/plugins/Configurable.hpp @@ -0,0 +1,25 @@ +#pragma once + +#include + +#include + +// 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(p); + } +} // namespace VoidTest diff --git a/tests/plugins/ConfigurablePlugin.cpp b/tests/plugins/ConfigurablePlugin.cpp new file mode 100644 index 0000000..8140130 --- /dev/null +++ b/tests/plugins/ConfigurablePlugin.cpp @@ -0,0 +1,78 @@ +#include "Configurable.hpp" + +#include + +#include + +// 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(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(instance)->apply_config(config); +} +} diff --git a/tests/standalone/Async/EventBus.cpp b/tests/standalone/Async/EventBus.cpp index 88a2ab5..5042755 100644 --- a/tests/standalone/Async/EventBus.cpp +++ b/tests/standalone/Async/EventBus.cpp @@ -3,6 +3,7 @@ #include #include +#include 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([&](const Clicked&) { ++count; }); + Void::Testing::expect(static_cast(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(), 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([&](const Clicked&) { ++count; }); + outer = std::move(inner); + Void::Testing::expect(!static_cast(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); +} diff --git a/tests/standalone/Plugin/Configure.cpp b/tests/standalone/Plugin/Configure.cpp new file mode 100644 index 0000000..9aacaaf --- /dev/null +++ b/tests/standalone/Plugin/Configure.cpp @@ -0,0 +1,70 @@ +#include +#include +#include +#include + +#include "Configurable.hpp" + +#include +#include + +using namespace Void::Plugin; + +#if defined(VOID_CONFIGURABLE_PATH) && __has_include() + +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 diff --git a/tests/standalone/Plugin/Discovery.cpp b/tests/standalone/Plugin/Discovery.cpp new file mode 100644 index 0000000..f004bf0 --- /dev/null +++ b/tests/standalone/Plugin/Discovery.cpp @@ -0,0 +1,72 @@ +#include +#include +#include +#include +#include + +#include +#include +#include + +using namespace Void::Plugin; + +#if defined(VOID_TEST_PLUGIN_PATH) && defined(VOID_STATEFUL_V1_PATH) && \ + __has_include() + +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(mgr.acquire("TestPlugin"))); + Void::Testing::expect(static_cast(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 diff --git a/tests/standalone/Plugin/Manager.cpp b/tests/standalone/Plugin/Manager.cpp index 5f7d4c8..7e929a0 100644 --- a/tests/standalone/Plugin/Manager.cpp +++ b/tests/standalone/Plugin/Manager.cpp @@ -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(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 diff --git a/tests/standalone/Service/Registry.cpp b/tests/standalone/Service/Registry.cpp index f8359e4..c7e2288 100644 --- a/tests/standalone/Service/Registry.cpp +++ b/tests/standalone/Service/Registry.cpp @@ -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(7); + reg.provide(clock); + + // A consumer resolved before the removal keeps its instance. + auto held = reg.get(); + + Void::Testing::expect(reg.remove()); + Void::Testing::expect(!reg.has()); + Void::Testing::expect(reg.get() == 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()); + + // Re-providing after removal works (fresh lifecycle position). + reg.provide(std::make_shared(9)); + Void::Testing::expect_eq(reg.require().now(), 9); +} + +Void::Testing::Test registry_remove_in_child_reexposes_parent() +{ + ServiceRegistry parent; + parent.provide(std::make_shared(1)); + + ServiceRegistry child{&parent}; + child.provide(std::make_shared(2)); + Void::Testing::expect_eq(child.require().now(), 2); + + // Removing the child's shadow re-exposes the parent's entry. + Void::Testing::expect(child.remove()); + Void::Testing::expect_eq(child.require().now(), 1); +} + Void::Testing::Test registry_lifecycle_order() { std::vector log; From a06f639393d0b5fd577befab63e5026ed173b6dd Mon Sep 17 00:00:00 2001 From: faumaray Date: Sat, 11 Jul 2026 23:42:31 +0300 Subject: [PATCH 2/4] Plugin: copy_on_load option; unique hotswap temp names MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - copy_on_load: dlopen a fresh-inode temp copy on first load (reloads already did), so deployments that rewrite the plugin file in place — e.g. a build writing its output — cannot corrupt the mapped image. The registry keeps addressing the original path for watch/reload. - hotswap_copy now generates a unique temp name per copy. glibc dedupes dlopen by pathname, so the previous fixed ".void_hotswap" name made every second reload through the same path silently return the already-mapped OLD image instead of the new bytes. - hot_reload_under_concurrent_load now asserts the true downgrade semantics (v2 -> v1 is rejected transactionally, v2 stays); it only ever passed the old all-succeed expectation via the dedup bug, since no flip after the first actually took effect. Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_018yj92cCihyaYtf4gKCT3nv --- include/Void/Plugin/Manager.hpp | 6 ++++ src/Plugin/Manager.cpp | 29 ++++++++++++++++--- .../standalone/Plugin/HotReloadUnderLoad.cpp | 29 ++++++++++++++----- tests/standalone/Plugin/Manager.cpp | 28 ++++++++++++++++++ 4 files changed, 80 insertions(+), 12 deletions(-) diff --git a/include/Void/Plugin/Manager.hpp b/include/Void/Plugin/Manager.hpp index e132f7a..06d6b09 100644 --- a/include/Void/Plugin/Manager.hpp +++ b/include/Void/Plugin/Manager.hpp @@ -74,6 +74,12 @@ namespace Void::Plugin // executing would crash. Pins already prevent the instance from // being destroyed; this guards the code pages. bool dlclose_on_swap = false; + // dlopen a fresh-inode temp copy instead of the original file on + // the first load (reloads already do). Turn on when deployments + // overwrite the plugin file in place (e.g. a build writing its + // output) — mapping the original would then corrupt the running + // image (SIGBUS). The registry keeps tracking the original path. + bool copy_on_load = 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 diff --git a/src/Plugin/Manager.cpp b/src/Plugin/Manager.cpp index f7bcb9d..c97799a 100644 --- a/src/Plugin/Manager.cpp +++ b/src/Plugin/Manager.cpp @@ -8,7 +8,9 @@ #endif #include +#include #include +#include #include #include @@ -170,12 +172,18 @@ namespace Void::Plugin } // Copy to a fresh-inode temp path so dlopen does not return the - // already-mapped image when the file is replaced in place. + // already-mapped image when the file is replaced in place. The name + // must be unique per copy: glibc dedupes dlopen by pathname, so + // reusing a temp name would hand back the previously mapped (old) + // image no matter what bytes the file now holds. std::expected hotswap_copy(const std::filesystem::path& path) { - const auto tmp = path.parent_path() / - (path.filename().string() + ".void_hotswap"); + static std::atomic counter{0}; + const auto tmp = + path.parent_path() / + (path.filename().string() + ".void_hotswap." + + std::to_string(counter.fetch_add(1, std::memory_order_relaxed))); std::error_code ec; std::filesystem::copy_file( path, tmp, std::filesystem::copy_options::overwrite_existing, @@ -211,7 +219,20 @@ namespace Void::Plugin if (!std::filesystem::exists(path, ec)) { return std::unexpected{LoadError::FileNotFound}; } - auto inst = open_instance(path, m_options.dlclose_on_swap); + std::filesystem::path load_path = path; + if (m_options.copy_on_load) { + auto tmp = hotswap_copy(path); + if (!tmp.has_value()) { + return std::unexpected{tmp.error()}; + } + load_path = *tmp; + } + auto inst = open_instance(load_path, m_options.dlclose_on_swap); + if (m_options.copy_on_load) { + // The mapping keeps the unlinked inode alive; the registry + // keeps addressing the original path for watch/reload. + std::filesystem::remove(load_path, ec); + } if (!inst.has_value()) { Void::Log::warn("Plugin.Manager", "load '{}' failed: {}", path.string(), to_string(inst.error())); diff --git a/tests/standalone/Plugin/HotReloadUnderLoad.cpp b/tests/standalone/Plugin/HotReloadUnderLoad.cpp index 7807d32..4b45f03 100644 --- a/tests/standalone/Plugin/HotReloadUnderLoad.cpp +++ b/tests/standalone/Plugin/HotReloadUnderLoad.cpp @@ -1,3 +1,4 @@ +#include #include #include #include @@ -78,13 +79,23 @@ Void::Testing::Test hot_reload_under_concurrent_load() }); } - // Main thread flips the file v1<->v2 and reloads repeatedly. + // Main thread flips the file v1<->v2 and reloads repeatedly. The first + // v2 reload migrates v1 state forward; after that, installing v1 is a + // DOWNGRADE — v1 cannot deserialize v2 state, so the transactional + // reload must fail with StateRejected and keep the v2 instance. (An + // earlier version of this test expected every reload to succeed; that + // only passed because a fixed hotswap temp name made dlopen return the + // already-mapped image, so no flip after the first ever took effect.) for (int i = 0; i < 24; ++i) { - const char* src = - (i % 2 == 0) ? VOID_STATEFUL_V2_PATH : VOID_STATEFUL_V1_PATH; - install(src, so); + const bool to_v2 = (i % 2 == 0); + install(to_v2 ? VOID_STATEFUL_V2_PATH : VOID_STATEFUL_V1_PATH, so); const auto r = mgr.reload("StatefulPlugin"); - Void::Testing::expect(r.has_value()); + if (to_v2) { + Void::Testing::expect(r.has_value()); + } else { + Void::Testing::expect(!r.has_value()); + Void::Testing::expect(r.error() == LoadError::StateRejected); + } std::this_thread::sleep_for(std::chrono::milliseconds{2}); } @@ -97,12 +108,14 @@ Void::Testing::Test hot_reload_under_concurrent_load() Void::Testing::expect_eq(crashes.load(), 0); Void::Testing::expect(ops.load() > 0); - // State survived every migration: the final instance's counter is at - // least the number of reloads' worth of preserved bumps (monotonic, - // never reset to zero by a swap). + // State survived every migration: the counter is monotonic, never + // reset by a swap, and the surviving instance is the v2 build (every + // attempted downgrade was rejected transactionally). auto final = mgr.acquire("StatefulPlugin"); Void::Testing::expect(static_cast(final)); Void::Testing::expect(VoidTest::as_stateful(final.get())->counter() > 0); + Void::Testing::expect_eq( + VoidTest::as_stateful(final.get())->schema_version(), 2); } #endif // stateful plugins available diff --git a/tests/standalone/Plugin/Manager.cpp b/tests/standalone/Plugin/Manager.cpp index 7e929a0..fa7c0c0 100644 --- a/tests/standalone/Plugin/Manager.cpp +++ b/tests/standalone/Plugin/Manager.cpp @@ -215,6 +215,34 @@ Void::Testing::Test manager_unload_drops_entry_but_pinned_handle_survives() Void::Testing::expect_eq(stateful(pinned)->counter(), 1); } +Void::Testing::Test manager_copy_on_load_survives_in_place_overwrite() +{ + Void::FileSystem::TempDir tmp{"void_mgr"}; + const auto so = tmp.path() / "plugin.so"; + std::filesystem::copy_file(VOID_STATEFUL_V1_PATH, so); + + PluginManager mgr{{.copy_on_load = true}}; + Void::Testing::expect(mgr.load(so).has_value()); + + auto h = mgr.acquire("StatefulPlugin"); + stateful(h)->bump(); + + // Overwrite the original file IN PLACE (what a build does). With + // copy_on_load the mapped image is a private unlinked copy, so the + // running instance is unaffected. + std::filesystem::copy_file( + VOID_STATEFUL_V2_PATH, so, + std::filesystem::copy_options::overwrite_existing); + Void::Testing::expect_eq(stateful(h)->schema_version(), 1); + Void::Testing::expect_eq(stateful(h)->counter(), 1); + + // Reload still tracks the original path and picks up the new bytes. + Void::Testing::expect(mgr.reload("StatefulPlugin").has_value()); + auto fresh = mgr.acquire("StatefulPlugin"); + Void::Testing::expect_eq(stateful(fresh)->schema_version(), 2); + Void::Testing::expect_eq(stateful(fresh)->counter(), 1); +} + Void::Testing::Test manager_state_snapshot_round_trip() { PluginManager mgr; From 9a54f15e7e968de5510b6be9e91cf654cc9764c8 Mon Sep 17 00:00:00 2001 From: faumaray Date: Sun, 12 Jul 2026 00:14:01 +0300 Subject: [PATCH 3/4] Net: actually enforce Request::timeout on HTTP socket I/O MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Request::timeout was declared but never used — every sync Asio operation (TLS handshake, read, write) blocked without bound, so a stalled peer hung the calling thread indefinitely (observed: a stalled CDN download blocking a host's shutdown join forever). SO_RCVTIMEO cannot fix this: Asio's sync emulation treats the resulting EAGAIN as would-block and poll()s with no deadline. Instead a per-request DeadlineGuard watchdog ::shutdown()s the descriptor on expiry, which wakes any blocked sync op with EOF and fails the request. Declaration order in send() keeps the descriptor owners alive past the guard. Resolution and connect() remain on kernel defaults. Regression test: a stalled localhost server is bounded at ~1s. Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_018yj92cCihyaYtf4gKCT3nv --- src/Net/Http.cpp | 110 +++++++++++++++++++++++++--- tests/standalone/Net/HttpClient.cpp | 54 ++++++++++++++ 2 files changed, 152 insertions(+), 12 deletions(-) diff --git a/src/Net/Http.cpp b/src/Net/Http.cpp index 3ef6ec6..84134c7 100644 --- a/src/Net/Http.cpp +++ b/src/Net/Http.cpp @@ -14,12 +14,21 @@ #include +#if !defined(_WIN32) +#include +#include +#endif + #include #include +#include #include #include #include +#include +#include #include +#include #include namespace Void::Net @@ -227,17 +236,88 @@ namespace Void::Net stream.handshake(ssl::stream_base::client); } + // Bounds every sync operation on an open socket with the request + // timeout. Asio's synchronous ops cannot be bounded any other way + // short of going fully async: SO_RCVTIMEO merely makes recv return + // EAGAIN, which the sync emulation treats as would-block and then + // poll()s without a deadline. On expiry the watchdog ::shutdown()s + // the descriptor — shutdown (unlike close) is safe against a + // concurrent blocked op and wakes it with EOF, so the op fails and + // the request errors out instead of hanging the calling thread + // forever. The descriptor must stay open for the guard's lifetime + // (declare the guard after the connected socket, in the same scope). + // Name resolution and connect() are not covered (kernel defaults). + class DeadlineGuard + { + public: + + DeadlineGuard(tcp::socket& socket, + std::chrono::seconds timeout) + { + if (timeout <= std::chrono::seconds::zero() || + !socket.is_open()) { + return; + } + const auto fd = socket.native_handle(); + m_worker = std::thread([this, fd, timeout] { + std::unique_lock lock{m_mutex}; + if (!m_cv.wait_for(lock, timeout, + [this] { return m_done; })) { +#if defined(_WIN32) + ::shutdown(fd, SD_BOTH); +#else + ::shutdown(fd, SHUT_RDWR); +#endif + m_timed_out = true; + } + }); + } + + DeadlineGuard(const DeadlineGuard&) = delete; + DeadlineGuard& operator=(const DeadlineGuard&) = delete; + + ~DeadlineGuard() + { + if (!m_worker.joinable()) { + return; + } + { + std::lock_guard lock{m_mutex}; + m_done = true; + } + m_cv.notify_all(); + m_worker.join(); + } + + [[nodiscard]] bool timed_out() const noexcept + { + return m_timed_out; + } + + private: + + std::thread m_worker; + std::mutex m_mutex; + std::condition_variable m_cv; + bool m_done{false}; + bool m_timed_out{false}; + }; + // Perform the request over an already-connected plain socket, doing a - // TLS upgrade in place when the target is https. - Response finish(tcp::socket socket, ssl::context& ctx, const Url& url, - const Request& req, std::string_view ua, - std::uint64_t max_body) + // TLS upgrade in place when the target is https. The TLS stream is an + // out-parameter declared in the caller's scope so the descriptor + // outlives the caller's DeadlineGuard (declaration order there is + // socket, stream, guard — the guard is destroyed first). + Response finish(tcp::socket& socket, + std::optional>& tls, + ssl::context& ctx, const Url& url, const Request& req, + std::string_view ua, std::uint64_t max_body) { if (url.is_tls) { - ssl::stream stream{std::move(socket), ctx}; - tls_handshake(stream, url); + tls.emplace(std::move(socket), ctx); + tls_handshake(*tls, url); auto rq = build_request(url, req, ua, url.target); - return write_read(stream, rq, max_body); + return write_read(*tls, rq, max_body); } auto rq = build_request(url, req, ua, url.target); return write_read(socket, rq, max_body); @@ -310,19 +390,25 @@ namespace Void::Net Response response; tcp::resolver resolver{ioc}; + // Declaration order matters: the DeadlineGuard must be + // destroyed (and its watchdog joined) BEFORE the objects + // that own the descriptor it may shut down. + tcp::socket socket{ioc}; + std::optional> tls; + if (m_proxy.enabled()) { - tcp::socket socket{ioc}; asio::connect(socket, resolver.resolve( m_proxy.host, std::to_string(m_proxy.port))); + DeadlineGuard deadline{socket, req.timeout}; if (m_proxy.kind == ProxyConfig::Kind::Socks5) { socks5_connect(socket, *url, m_proxy); - response = finish(std::move(socket), ctx, *url, req, + response = finish(socket, tls, ctx, *url, req, m_user_agent, m_max_body); } else { // Http proxy if (url->is_tls) { http_connect_tunnel(socket, *url, m_proxy); - response = finish(std::move(socket), ctx, *url, req, + response = finish(socket, tls, ctx, *url, req, m_user_agent, m_max_body); } else { // Plain HTTP through proxy: absolute-form target. @@ -341,10 +427,10 @@ namespace Void::Net } } } else { - tcp::socket socket{ioc}; asio::connect(socket, resolver.resolve(url->host, url->port)); - response = finish(std::move(socket), ctx, *url, req, + DeadlineGuard deadline{socket, req.timeout}; + response = finish(socket, tls, ctx, *url, req, m_user_agent, m_max_body); } diff --git a/tests/standalone/Net/HttpClient.cpp b/tests/standalone/Net/HttpClient.cpp index 4d831fc..007e003 100644 --- a/tests/standalone/Net/HttpClient.cpp +++ b/tests/standalone/Net/HttpClient.cpp @@ -110,3 +110,57 @@ Void::Testing::Test http_client_connection_refused_is_error() const auto resp = client.get("http://127.0.0.1:1/"); Void::Testing::expect(!resp.has_value()); } + +Void::Testing::Test http_client_timeout_bounds_a_stalled_server() +{ + // A server that accepts and then never responds. Without an enforced + // Request::timeout the sync read blocks forever (Asio's sync emulation + // poll()s on would-block with no deadline). + struct StallServer { + int fd = -1; + std::uint16_t port = 0; + int conn = -1; + std::thread worker; + + StallServer() + { + fd = ::socket(AF_INET, SOCK_STREAM, 0); + int yes = 1; + ::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)); + sockaddr_in addr{}; + addr.sin_family = AF_INET; + addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); + addr.sin_port = 0; + ::bind(fd, reinterpret_cast(&addr), sizeof(addr)); + socklen_t len = sizeof(addr); + ::getsockname(fd, reinterpret_cast(&addr), &len); + port = ntohs(addr.sin_port); + ::listen(fd, 1); + worker = std::thread([this] { + conn = ::accept(fd, nullptr, nullptr); + // Never write a byte; hold the connection open. + }); + } + + ~StallServer() + { + if (conn >= 0) ::close(conn); + if (worker.joinable()) worker.join(); + if (fd >= 0) ::close(fd); + } + }; + + StallServer server; + Void::Net::HttpClient client; + Void::Net::Request req; + req.url = "http://127.0.0.1:" + std::to_string(server.port) + "/stall"; + req.timeout = std::chrono::seconds{1}; + + const auto start = std::chrono::steady_clock::now(); + const auto resp = client.send(req); + const auto elapsed = std::chrono::steady_clock::now() - start; + + Void::Testing::expect(!resp.has_value()); + // Well under the old "forever": the deadline tripped around 1s. + Void::Testing::expect(elapsed < std::chrono::seconds{5}); +} From f94366104e2be8d8ed51de1dce60fb4492463bd9 Mon Sep 17 00:00:00 2001 From: faumaray Date: Sun, 12 Jul 2026 02:37:49 +0300 Subject: [PATCH 4/4] Update Signed-off-by: faumaray --- cmake/Module.cmake | 16 +++++++++------- include/Void/Plugin/Loader.hpp | 2 ++ include/Void/Plugin/Plugin.hpp | 8 ++++++++ src/Plugin/Loader.cpp | 27 +++++++++++++++++++++++---- src/Plugin/Manager.cpp | 25 +++++++++++++++++++++++-- tests/plugins/ConfigurablePlugin.cpp | 10 ++++++++++ tests/standalone/Plugin/Configure.cpp | 25 +++++++++++++++++++++++++ 7 files changed, 100 insertions(+), 13 deletions(-) diff --git a/cmake/Module.cmake b/cmake/Module.cmake index ab1c96e..0a8081a 100644 --- a/cmake/Module.cmake +++ b/cmake/Module.cmake @@ -23,13 +23,15 @@ function(void_add_module MODULE_NAME) add_library(${TGT} INTERFACE) target_compile_features(${TGT} INTERFACE cxx_std_26) else() - set(LIB_TYPE "SHARED") - set(SCOPE "PUBLIC") - if (MODULE_NAME STREQUAL "Testing") - add_library(${TGT} STATIC) - else() - add_library(${TGT} SHARED) - endif() + set(SCOPE "PUBLIC") + if (MODULE_NAME STREQUAL "Testing") + add_library(${TGT} STATIC) + else() + # Honour the standard BUILD_SHARED_LIBS policy. Consumers that ship a + # single validated executable must be able to embed Void modules, + # while Void's standalone default remains shared. + add_library(${TGT}) + endif() target_sources(${TGT} PRIVATE ${SRC}) target_compile_features(${TGT} PUBLIC cxx_std_26) endif() diff --git a/include/Void/Plugin/Loader.hpp b/include/Void/Plugin/Loader.hpp index 4d0d894..77e4806 100644 --- a/include/Void/Plugin/Loader.hpp +++ b/include/Void/Plugin/Loader.hpp @@ -17,6 +17,7 @@ enum class LoadError { CreateFailed, NotSupported, // platform does not support dlopen StateRejected, // new instance refused the serialized state + ActivationFailed, // on_load threw or readiness validation failed UnknownPlugin, // PluginManager: no plugin registered under that name }; @@ -72,6 +73,7 @@ private: IPlugin* plugin_ {}; destroy_fn destroy_ {}; transfer_fn transfer_ {}; + ready_fn ready_ {}; state_version_fn state_version_{}; serialize_fn serialize_ {}; free_string_fn free_string_ {}; diff --git a/include/Void/Plugin/Plugin.hpp b/include/Void/Plugin/Plugin.hpp index b74aa54..f401848 100644 --- a/include/Void/Plugin/Plugin.hpp +++ b/include/Void/Plugin/Plugin.hpp @@ -55,6 +55,12 @@ public: // JSON) after create and after each hot-reload swap, before // on_load(). The string is only valid for the duration of the call. // +// Optional (transactional activation check): +// int void_plugin_ready(void* instance) +// — called after on_load() and state restoration, immediately before +// the instance becomes visible. Return 0 when the plugin is ready. +// Any other value aborts load/reload and keeps the old instance. +// // Optional v2 state protocol (preferred over transfer_state when both // sides provide it; survives layout changes between plugin versions): // @@ -74,6 +80,7 @@ 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 ready_fn = int (*)(void* instance); using state_version_fn = std::uint32_t (*)(void); using serialize_fn = const char* (*)(void* instance); using free_string_fn = void (*)(const char*); @@ -85,6 +92,7 @@ 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* kReadySymbol = "void_plugin_ready"; 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"; diff --git a/src/Plugin/Loader.cpp b/src/Plugin/Loader.cpp index ad6c851..063e57e 100644 --- a/src/Plugin/Loader.cpp +++ b/src/Plugin/Loader.cpp @@ -23,6 +23,7 @@ std::string_view to_string(LoadError e) noexcept case LoadError::CreateFailed: return "plugin create() returned null"; case LoadError::NotSupported: return "platform does not support dlopen"; case LoadError::StateRejected: return "new instance rejected state"; + case LoadError::ActivationFailed: return "plugin activation failed"; case LoadError::UnknownPlugin: return "no plugin registered under name"; } return "unknown"; @@ -44,6 +45,7 @@ void PluginLoader::destroy_current() noexcept } destroy_ = nullptr; transfer_ = nullptr; + ready_ = nullptr; state_version_ = nullptr; serialize_ = nullptr; free_string_ = nullptr; @@ -121,6 +123,7 @@ PluginLoader::load_from(const std::filesystem::path& path) plugin_ = static_cast(raw); destroy_ = sym_destroy; transfer_ = reinterpret_cast(dlsym(h, kTransferSymbol)); + ready_ = reinterpret_cast(dlsym(h, kReadySymbol)); state_version_ = reinterpret_cast( dlsym(h, kStateVersionSymbol)); serialize_ = reinterpret_cast(dlsym(h, kSerializeSymbol)); @@ -153,7 +156,14 @@ PluginLoader::load(std::filesystem::path path) return std::unexpected{r.error()}; } - ldr.plugin_->on_load(); + try { + ldr.plugin_->on_load(); + } catch (...) { + return std::unexpected{LoadError::ActivationFailed}; + } + if (ldr.ready_ && ldr.ready_(ldr.plugin_) != 0) { + return std::unexpected{LoadError::ActivationFailed}; + } Void::Log::info("Plugin", "loaded '{}' ({} v{})", path.string(), ldr.info_.name, ldr.info_.plugin_version); return ldr; @@ -166,6 +176,7 @@ PluginLoader::PluginLoader(PluginLoader&& o) noexcept , plugin_ {std::exchange(o.plugin_, nullptr)} , destroy_ {std::exchange(o.destroy_, nullptr)} , transfer_ {std::exchange(o.transfer_, nullptr)} + , ready_ {std::exchange(o.ready_, nullptr)} , state_version_{std::exchange(o.state_version_, nullptr)} , serialize_ {std::exchange(o.serialize_, nullptr)} , free_string_ {std::exchange(o.free_string_, nullptr)} @@ -182,6 +193,7 @@ PluginLoader& PluginLoader::operator=(PluginLoader&& o) noexcept plugin_ = std::exchange(o.plugin_, nullptr); destroy_ = std::exchange(o.destroy_, nullptr); transfer_ = std::exchange(o.transfer_, nullptr); + ready_ = std::exchange(o.ready_, nullptr); state_version_ = std::exchange(o.state_version_, nullptr); serialize_ = std::exchange(o.serialize_, nullptr); free_string_ = std::exchange(o.free_string_, nullptr); @@ -228,11 +240,18 @@ std::expected PluginLoader::reload() return std::unexpected{LoadError::StateRejected}; } - // Destroy old, install new. + try { + next.plugin_->on_load(); + } catch (...) { + return std::unexpected{LoadError::ActivationFailed}; + } + if (next.ready_ && next.ready_(next.plugin_) != 0) { + return std::unexpected{LoadError::ActivationFailed}; + } + + // Activation succeeded; only now destroy old and install new. destroy_current(); *this = std::move(next); - - plugin_->on_load(); Void::Log::info("Plugin", "reloaded '{}' ({} v{})", path_.string(), info_.name, info_.plugin_version); diff --git a/src/Plugin/Manager.cpp b/src/Plugin/Manager.cpp index c97799a..52da33d 100644 --- a/src/Plugin/Manager.cpp +++ b/src/Plugin/Manager.cpp @@ -25,6 +25,7 @@ namespace Void::Plugin destroy_fn destroy{nullptr}; transfer_fn transfer{nullptr}; configure_fn configure{nullptr}; + ready_fn ready{nullptr}; state_version_fn state_version{nullptr}; serialize_fn serialize{nullptr}; free_string_fn free_string{nullptr}; @@ -121,6 +122,8 @@ namespace Void::Plugin reinterpret_cast(dlsym(h, kTransferSymbol)); inst->configure = reinterpret_cast(dlsym(h, kConfigureSymbol)); + inst->ready = + reinterpret_cast(dlsym(h, kReadySymbol)); inst->state_version = reinterpret_cast( dlsym(h, kStateVersionSymbol)); inst->serialize = @@ -243,7 +246,15 @@ namespace Void::Plugin const std::string config = m_options.config_provider(name); (*inst)->configure((*inst)->plugin, config.c_str()); } - (*inst)->plugin->on_load(); + try { + (*inst)->plugin->on_load(); + } catch (...) { + return std::unexpected{LoadError::ActivationFailed}; + } + if ((*inst)->ready != nullptr && + (*inst)->ready((*inst)->plugin) != 0) { + return std::unexpected{LoadError::ActivationFailed}; + } std::lock_guard lock(m_mutex); auto entry = std::make_unique(); @@ -372,7 +383,17 @@ namespace Void::Plugin } } - (*next)->plugin->on_load(); + try { + (*next)->plugin->on_load(); + } catch (...) { + return std::unexpected{LoadError::ActivationFailed}; + } + if ((*next)->ready != nullptr && + (*next)->ready((*next)->plugin) != 0) { + Void::Log::warn("Plugin.Manager", + "reload '{}' aborted: activation failed", name); + return std::unexpected{LoadError::ActivationFailed}; + } // Atomic swap. The old instance keeps living while any acquired // handle still pins it; it is destroyed when the last one drops. entry.current.store(std::move(*next), std::memory_order_release); diff --git a/tests/plugins/ConfigurablePlugin.cpp b/tests/plugins/ConfigurablePlugin.cpp index 8140130..ea997e8 100644 --- a/tests/plugins/ConfigurablePlugin.cpp +++ b/tests/plugins/ConfigurablePlugin.cpp @@ -44,6 +44,11 @@ namespace } } + [[nodiscard]] bool ready() const noexcept + { + return config_ != "reject"; + } + private: std::string config_; @@ -75,4 +80,9 @@ void void_plugin_configure(void* instance, const char* config) { static_cast(instance)->apply_config(config); } + +int void_plugin_ready(void* instance) +{ + return static_cast(instance)->ready() ? 0 : -1; +} } diff --git a/tests/standalone/Plugin/Configure.cpp b/tests/standalone/Plugin/Configure.cpp index 9aacaaf..1196e6b 100644 --- a/tests/standalone/Plugin/Configure.cpp +++ b/tests/standalone/Plugin/Configure.cpp @@ -67,4 +67,29 @@ Void::Testing::Test configure_skipped_without_provider() Void::Testing::expect_eq(configurable(h)->configure_calls(), 0); } +Void::Testing::Test activation_failure_keeps_current_instance() +{ + Void::FileSystem::TempDir tmp{"void_cfg_ready"}; + const auto so = tmp.path() / "plugin.so"; + std::filesystem::copy_file(VOID_CONFIGURABLE_PATH, so); + + std::string payload{"accepted"}; + PluginManager mgr{{.config_provider = [&payload](std::string_view) { + return payload; + }}}; + Void::Testing::expect(mgr.load(so).has_value()); + auto before = mgr.acquire("ConfigurablePlugin"); + Void::Testing::expect_eq(configurable(before)->last_config(), + std::string_view{"accepted"}); + + payload = "reject"; + const auto result = mgr.reload("ConfigurablePlugin"); + Void::Testing::expect(!result.has_value()); + Void::Testing::expect(result.error() == LoadError::ActivationFailed); + auto after = mgr.acquire("ConfigurablePlugin"); + Void::Testing::expect(after.get() == before.get()); + Void::Testing::expect_eq(configurable(after)->last_config(), + std::string_view{"accepted"}); +} + #endif // configurable plugin available