From b343bce39620e97915a1a7520235c5a2f2db74f9 Mon Sep 17 00:00:00 2001 From: faumaray Date: Sat, 13 Jun 2026 18:08:06 +0300 Subject: [PATCH] Add Plugin hot-plug: PluginManager, versioned state ABI, file watching Backward-compatible C ABI v2 (Plugin.hpp; ABI_VERSION unchanged, IPlugin vtable frozen): optional void_plugin_state_version / serialize_state / free_string / deserialize_state(inst, json, from_version). State transfer prefers serialize->deserialize (survives layout changes; migrations live in the new .so via Json::MigrationChain), falling back to the existing transfer_state, then no-op. PluginLoader::reload gains this chain; the shared transfer_plugin_state helper drives it. Existing ABI-v1 plugins (TestPlugin) load and reload unchanged. PluginManager (Manager.hpp/.cpp): multi-plugin registry with RCU-style pinned handles. acquire(name) is one atomic load returning a PluginHandle that keeps its instance alive for the whole call. reload() is transactional: build new instance, transfer state from old, then atomic-exchange it in; on any failure the old instance stays. In-flight handles keep the old instance and its mapped .so alive (dlclose_on_swap= false) until they drop, so work never stops and callers never see a torn or freed object. watch(name) auto-reloads via FileSystem::FileWatcher (debounced); on_reloaded fires after each swap. Reload-safety: dlopen of a fresh-inode hotswap copy is required to load new bytes; deployments must install the new .so by atomic rename, never in-place overwrite of the mapped file (corrupts the running mapping -> SIGBUS). Documented; tests install via copy-to-.incoming + rename. Tests: StatefulPluginV1/V2 (shared IStateful interface, atomic counter; v2 adds a field and migrates v1 JSON). Manager.cpp covers load/acquire, v1->v2 migration, pinned-handle-survives-reload, legacy transfer_state fallback, and watch auto-reload. HotReloadUnderLoad.cpp: 6 reader threads calling through acquire() while 24 v1<->v2 reloads run concurrently -- zero crashes, state survives every migration, ASan+UBSan clean, stable across 10+ runs. 965 tests green. Co-Authored-By: Claude Fable 5 --- CLAUDE.md | 11 +- include/Void/Plugin/Loader.hpp | 29 +- include/Void/Plugin/Manager.hpp | 136 +++++++ include/Void/Plugin/Plugin.hpp | 39 +- src/Plugin/Loader.cpp | 109 ++++-- src/Plugin/Manager.cpp | 354 ++++++++++++++++++ src/Plugin/module.cmake | 1 + tests/CMakeLists.txt | 19 + tests/plugins/Stateful.hpp | 28 ++ tests/plugins/StatefulPluginV1.cpp | 98 +++++ tests/plugins/StatefulPluginV2.cpp | 116 ++++++ .../standalone/Plugin/HotReloadUnderLoad.cpp | 108 ++++++ tests/standalone/Plugin/Manager.cpp | 169 +++++++++ 13 files changed, 1179 insertions(+), 38 deletions(-) create mode 100644 include/Void/Plugin/Manager.hpp create mode 100644 src/Plugin/Manager.cpp create mode 100644 tests/plugins/Stateful.hpp create mode 100644 tests/plugins/StatefulPluginV1.cpp create mode 100644 tests/plugins/StatefulPluginV2.cpp create mode 100644 tests/standalone/Plugin/HotReloadUnderLoad.cpp create mode 100644 tests/standalone/Plugin/Manager.cpp diff --git a/CLAUDE.md b/CLAUDE.md index b7108bd..5c7358f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -46,7 +46,7 @@ VoidLibrary is a C++26 modular shared library organized as **umbrella modules** | `System` | SHARED | FileSystem (Path, Query, TempDir) + Process | | `Configuration` | SHARED | Config, Env + Argparse | | `Stacktrace` | SHARED | Boost.Stacktrace capture, color helpers (kept separate to isolate the Boost dep) | -| `Plugin` | SHARED | dlopen loader, C ABI, hot reload | +| `Plugin` | SHARED | dlopen loader + manager, C ABI, hot reload (see below) | | `StateMachine` | INTERFACE | compile-time variant-based FSM | | `Fsm` | SHARED | runtime hierarchical FSM (see below) | | `Testing` / `TestingMock` | STATIC / INTERFACE | test + mock frameworks | @@ -146,6 +146,15 @@ Other key points: - **Persistence**: `serialize_state()` → JSON with leaf/history *names*; `restore_state(json)` on a stopped machine re-activates silently (no entry actions). - History records are snapshotted at exit time in `perform_transition` (not incrementally) — keep it that way; incremental recording accumulates stale leaves. +### Plugin module (hot reload) + +`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`. +- **`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. +- **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 Enforced by `.clang-format` (LLVM-based): 4-space indent (tabs), 80-column limit, Linux brace wrapping style, pointer alignment right. diff --git a/include/Void/Plugin/Loader.hpp b/include/Void/Plugin/Loader.hpp index a6753aa..4d0d894 100644 --- a/include/Void/Plugin/Loader.hpp +++ b/include/Void/Plugin/Loader.hpp @@ -16,6 +16,8 @@ enum class LoadError { AbiMismatch, CreateFailed, NotSupported, // platform does not support dlopen + StateRejected, // new instance refused the serialized state + UnknownPlugin, // PluginManager: no plugin registered under that name }; [[nodiscard]] std::string_view to_string(LoadError e) noexcept; @@ -50,18 +52,31 @@ public: IPlugin* operator->() noexcept { return plugin_; } - // Hot-reload: copies current .so to a temp file (fresh inode), loads it, - // transfers state, then destroys old instance and swaps handles. + // Hot-reload: copies current .so to a temp file (fresh inode), loads + // it, transfers state, then destroys old instance and swaps handles. + // State transfer prefers the v2 serialize/deserialize protocol (old + // serializes, new deserializes with the old schema version); falls + // back to void_plugin_transfer_state; else no transfer. [[nodiscard]] std::expected reload(); private: PluginLoader() = default; - void* handle_ {}; - IPlugin* plugin_ {}; - destroy_fn destroy_ {}; - transfer_fn transfer_{}; - PluginInfo info_ {}; + // Moves plugin state old -> new during a reload (v2 serialize/ + // deserialize, else transfer_state). Returns false only if the new + // instance rejects the state. + friend bool transfer_plugin_state(const PluginLoader& from, + PluginLoader& to); + + void* handle_ {}; + IPlugin* plugin_ {}; + destroy_fn destroy_ {}; + transfer_fn transfer_ {}; + state_version_fn state_version_{}; + serialize_fn serialize_ {}; + free_string_fn free_string_ {}; + deserialize_fn deserialize_ {}; + PluginInfo info_ {}; std::filesystem::path path_; [[nodiscard]] std::expected diff --git a/include/Void/Plugin/Manager.hpp b/include/Void/Plugin/Manager.hpp new file mode 100644 index 0000000..957bf87 --- /dev/null +++ b/include/Void/Plugin/Manager.hpp @@ -0,0 +1,136 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Plugin +{ + enum class LoadError; // from Loader.hpp + + namespace detail + { + // One loaded .so + its instance, with the C ABI entry points + // resolved. Destruction runs on_unload -> destroy -> (optional) + // dlclose. Shared via shared_ptr so in-flight callers keep it + // alive across a swap (RCU-style). + struct Instance; + } // namespace detail + + // ── PluginHandle ────────────────────────────────────────────────────── + // A pinned reference to a plugin instance. While any handle is alive, + // the underlying .so and instance are kept loaded even if a reload + // swaps in a newer instance — so calls in flight never see a torn or + // freed object. The old instance is destroyed once the last handle to + // it drops. Work never stops for a reload. + class PluginHandle + { + public: + + PluginHandle() = default; + + [[nodiscard]] IPlugin* operator->() const noexcept; + [[nodiscard]] IPlugin& operator*() const noexcept; + [[nodiscard]] IPlugin* get() const noexcept; + [[nodiscard]] explicit operator bool() const noexcept; + + [[nodiscard]] const PluginInfo& info() const noexcept; + + private: + + friend class PluginManager; + explicit PluginHandle(std::shared_ptr pin) + : m_pin(std::move(pin)) + { + } + + std::shared_ptr m_pin; + }; + + // ── PluginManager ───────────────────────────────────────────────────── + // Loads plugins by name, hands out pinned handles, and hot-reloads + // (manually or by watching the file). Reload is transactional: the new + // instance is created and given the old instance's serialized state + // before any swap; on any failure the old instance stays installed. + struct PluginManagerOptions { + std::chrono::milliseconds poll_interval{500}; + int debounce_polls = 2; + // Keep the old .so mapped after a swap (default) — closing it + // while a coroutine frame or std::function from that .so is still + // executing would crash. Pins already prevent the instance from + // being destroyed; this guards the code pages. + bool dlclose_on_swap = false; + }; + + class PluginManager + { + public: + + using Options = PluginManagerOptions; + + explicit PluginManager(Options options = {}); + ~PluginManager(); + + PluginManager(const PluginManager&) = delete; + PluginManager& operator=(const PluginManager&) = delete; + PluginManager(PluginManager&&) = delete; + PluginManager& operator=(PluginManager&&) = delete; + + /// Load a plugin from `path`. Returns the plugin's name (used to + /// address it later). The name comes from PluginInfo::name. + std::expected + load(const std::filesystem::path& path); + + /// 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. + [[nodiscard]] PluginHandle acquire(std::string_view name) const; + + /// Reload `name` from its file: create new, transfer state from + /// old, atomically swap. Transactional — old instance is kept + /// on any failure. In-flight handles to the old instance keep + /// it alive until they drop. + std::expected reload(std::string_view name); + + /// Begin watching the plugin's file; reload automatically when + /// it changes (debounced). Reload failures are logged and the + /// old instance is kept. + 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); + + [[nodiscard]] std::vector names() const; + + private: + + struct Entry { + std::filesystem::path path; + std::atomic> current; + }; + + Entry* find(std::string_view name) const; + std::expected reload_locked(Entry& entry, + std::string_view name); + + Options m_options; + mutable std::mutex m_mutex; // guards the registry map + reloads + std::unordered_map> m_plugins; + std::function m_on_reloaded; + FileSystem::FileWatcher m_watcher; + }; + +} // namespace Void::Plugin diff --git a/include/Void/Plugin/Plugin.hpp b/include/Void/Plugin/Plugin.hpp index cc5074e..f1bb3ed 100644 --- a/include/Void/Plugin/Plugin.hpp +++ b/include/Void/Plugin/Plugin.hpp @@ -48,15 +48,38 @@ public: // // Optional (enables hot-reload state transfer): // void void_plugin_transfer_state(void* old, void* new) +// +// Optional v2 state protocol (preferred over transfer_state when both +// sides provide it; survives layout changes between plugin versions): +// +// uint32_t void_plugin_state_version() +// — schema version of the state this build serializes +// const char* void_plugin_serialize_state(void* instance) +// — heap-allocated JSON; release with void_plugin_free_string +// void void_plugin_free_string(const char*) +// — frees serialize output (allocator stays inside the .so) +// int void_plugin_deserialize_state(void* instance, +// const char* json, uint32_t from_version) +// — 0 on success; migrations from historical versions live in the +// NEW .so (it knows the old formats; Json::MigrationChain helps) -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 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 state_version_fn = std::uint32_t (*)(void); +using serialize_fn = const char* (*)(void* instance); +using free_string_fn = void (*)(const char*); +using deserialize_fn = int (*)(void* instance, const char* json, + std::uint32_t from_version); -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* 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* kStateVersionSymbol = "void_plugin_state_version"; +inline constexpr const char* kSerializeSymbol = "void_plugin_serialize_state"; +inline constexpr const char* kFreeStringSymbol = "void_plugin_free_string"; +inline constexpr const char* kDeserializeSymbol = "void_plugin_deserialize_state"; } // namespace Void::Plugin diff --git a/src/Plugin/Loader.cpp b/src/Plugin/Loader.cpp index 01eca53..ad6c851 100644 --- a/src/Plugin/Loader.cpp +++ b/src/Plugin/Loader.cpp @@ -22,6 +22,8 @@ std::string_view to_string(LoadError e) noexcept case LoadError::AbiMismatch: return "ABI version mismatch"; 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::UnknownPlugin: return "no plugin registered under name"; } return "unknown"; } @@ -40,11 +42,53 @@ void PluginLoader::destroy_current() noexcept dlclose(handle_); handle_ = nullptr; } - destroy_ = nullptr; - transfer_ = nullptr; + destroy_ = nullptr; + transfer_ = nullptr; + state_version_ = nullptr; + serialize_ = nullptr; + free_string_ = nullptr; + deserialize_ = nullptr; #endif } +// Move plugin state old -> new across a reload. Prefers the v2 +// serialize/deserialize protocol (survives layout changes between +// versions); falls back to the raw transfer_state hook; else no-op. +// Returns false only when the new instance actively rejects the state. +bool transfer_plugin_state(const PluginLoader& from, PluginLoader& to) +{ + if (!from.plugin_ || !to.plugin_) { + return true; + } + if (from.serialize_ && to.deserialize_) { + const std::uint32_t from_version = + from.state_version_ ? from.state_version_() : 0; + const char* json = from.serialize_(from.plugin_); + if (json != nullptr) { + const int rc = to.deserialize_(to.plugin_, json, from_version); + if (from.free_string_) { + from.free_string_(json); + } + if (rc != 0) { + Void::Log::warn("Plugin", + "deserialize_state rejected state " + "(from v{}, rc={})", + from_version, rc); + return false; + } + Void::Log::debug("Plugin", + "state transferred via v2 protocol (v{})", + from_version); + return true; + } + } + if (to.transfer_) { + to.transfer_(from.plugin_, to.plugin_); + Void::Log::debug("Plugin", "state transferred via transfer_state"); + } + return true; +} + std::expected PluginLoader::load_from(const std::filesystem::path& path) { @@ -73,11 +117,18 @@ PluginLoader::load_from(const std::filesystem::path& path) return std::unexpected{LoadError::CreateFailed}; } - handle_ = h; - plugin_ = static_cast(raw); - destroy_ = sym_destroy; - transfer_ = reinterpret_cast(dlsym(h, kTransferSymbol)); - info_ = info; + handle_ = h; + plugin_ = static_cast(raw); + destroy_ = sym_destroy; + transfer_ = reinterpret_cast(dlsym(h, kTransferSymbol)); + state_version_ = reinterpret_cast( + dlsym(h, kStateVersionSymbol)); + serialize_ = reinterpret_cast(dlsym(h, kSerializeSymbol)); + free_string_ = reinterpret_cast( + dlsym(h, kFreeStringSymbol)); + deserialize_ = reinterpret_cast( + dlsym(h, kDeserializeSymbol)); + info_ = info; return {}; #else (void)path; @@ -111,24 +162,32 @@ PluginLoader::load(std::filesystem::path path) PluginLoader::~PluginLoader() { destroy_current(); } PluginLoader::PluginLoader(PluginLoader&& o) noexcept - : handle_ {std::exchange(o.handle_, nullptr)} - , plugin_ {std::exchange(o.plugin_, nullptr)} - , destroy_ {std::exchange(o.destroy_, nullptr)} - , transfer_{std::exchange(o.transfer_, nullptr)} - , info_ {o.info_} - , path_ {std::move(o.path_)} + : handle_ {std::exchange(o.handle_, nullptr)} + , plugin_ {std::exchange(o.plugin_, nullptr)} + , destroy_ {std::exchange(o.destroy_, nullptr)} + , transfer_ {std::exchange(o.transfer_, nullptr)} + , state_version_{std::exchange(o.state_version_, nullptr)} + , serialize_ {std::exchange(o.serialize_, nullptr)} + , free_string_ {std::exchange(o.free_string_, nullptr)} + , deserialize_ {std::exchange(o.deserialize_, nullptr)} + , info_ {o.info_} + , path_ {std::move(o.path_)} {} PluginLoader& PluginLoader::operator=(PluginLoader&& o) noexcept { if (this != &o) { destroy_current(); - handle_ = std::exchange(o.handle_, nullptr); - plugin_ = std::exchange(o.plugin_, nullptr); - destroy_ = std::exchange(o.destroy_, nullptr); - transfer_ = std::exchange(o.transfer_, nullptr); - info_ = o.info_; - path_ = std::move(o.path_); + handle_ = std::exchange(o.handle_, nullptr); + plugin_ = std::exchange(o.plugin_, nullptr); + destroy_ = std::exchange(o.destroy_, nullptr); + transfer_ = std::exchange(o.transfer_, nullptr); + state_version_ = std::exchange(o.state_version_, nullptr); + serialize_ = std::exchange(o.serialize_, nullptr); + free_string_ = std::exchange(o.free_string_, nullptr); + deserialize_ = std::exchange(o.deserialize_, nullptr); + info_ = o.info_; + path_ = std::move(o.path_); } return *this; } @@ -159,9 +218,15 @@ std::expected PluginLoader::reload() return r; } - // Transfer state with both instances alive. - if (plugin_ && next.plugin_ && next.transfer_) - next.transfer_(plugin_, next.plugin_); + // Transfer state with both instances alive. A rejection aborts the + // reload and keeps the old instance. + if (!transfer_plugin_state(*this, next)) { + std::error_code ec; + std::filesystem::remove(tmp, ec); + Void::Log::warn("Plugin", "reload '{}' aborted: state rejected", + path_.string()); + return std::unexpected{LoadError::StateRejected}; + } // Destroy old, install new. destroy_current(); diff --git a/src/Plugin/Manager.cpp b/src/Plugin/Manager.cpp new file mode 100644 index 0000000..7f4e29c --- /dev/null +++ b/src/Plugin/Manager.cpp @@ -0,0 +1,354 @@ +#include +#include +#include + +#if defined(__unix__) || defined(__APPLE__) +#include +#define VOID_HAS_DLOPEN 1 +#endif + +#include +#include +#include + +namespace Void::Plugin +{ + + namespace detail + { + struct Instance { + void* handle{nullptr}; + IPlugin* plugin{nullptr}; + destroy_fn destroy{nullptr}; + transfer_fn transfer{nullptr}; + state_version_fn state_version{nullptr}; + serialize_fn serialize{nullptr}; + free_string_fn free_string{nullptr}; + deserialize_fn deserialize{nullptr}; + PluginInfo info{}; + bool dlclose_on_destroy{false}; + + Instance() = default; + Instance(const Instance&) = delete; + Instance& operator=(const Instance&) = delete; + + ~Instance() + { +#ifdef VOID_HAS_DLOPEN + if (plugin != nullptr) { + plugin->on_unload(); + if (destroy != nullptr) { + destroy(plugin); + } + } + if (handle != nullptr && dlclose_on_destroy) { + dlclose(handle); + } +#endif + } + }; + } // namespace detail + + // ── PluginHandle ────────────────────────────────────────────────────── + + IPlugin* PluginHandle::operator->() const noexcept + { + return m_pin ? m_pin->plugin : nullptr; + } + + IPlugin& PluginHandle::operator*() const noexcept { return *m_pin->plugin; } + + IPlugin* PluginHandle::get() const noexcept + { + return m_pin ? m_pin->plugin : nullptr; + } + + PluginHandle::operator bool() const noexcept + { + return m_pin != nullptr && m_pin->plugin != nullptr; + } + + const PluginInfo& PluginHandle::info() const noexcept + { + return m_pin->info; + } + + // ── loading helpers ─────────────────────────────────────────────────── + + namespace + { + // dlopen a (fresh-inode) copy of `path` and resolve all symbols. + std::expected, LoadError> + open_instance(const std::filesystem::path& load_path, + bool dlclose_on_destroy) + { +#ifdef VOID_HAS_DLOPEN + void* h = dlopen(load_path.c_str(), RTLD_NOW | RTLD_LOCAL); + if (h == nullptr) { + return std::unexpected{LoadError::DlopenFailed}; + } + const auto info_sym = + reinterpret_cast(dlsym(h, kInfoSymbol)); + const auto create_sym = + reinterpret_cast(dlsym(h, kCreateSymbol)); + const auto destroy_sym = + reinterpret_cast(dlsym(h, kDestroySymbol)); + if (info_sym == nullptr || create_sym == nullptr || + destroy_sym == nullptr) { + dlclose(h); + return std::unexpected{LoadError::SymbolMissing}; + } + const PluginInfo info = info_sym(); + if (info.abi_version != ABI_VERSION) { + dlclose(h); + return std::unexpected{LoadError::AbiMismatch}; + } + void* raw = create_sym(); + if (raw == nullptr) { + dlclose(h); + return std::unexpected{LoadError::CreateFailed}; + } + + auto inst = std::make_shared(); + inst->handle = h; + inst->plugin = static_cast(raw); + inst->destroy = destroy_sym; + inst->transfer = + reinterpret_cast(dlsym(h, kTransferSymbol)); + inst->state_version = reinterpret_cast( + dlsym(h, kStateVersionSymbol)); + inst->serialize = + reinterpret_cast(dlsym(h, kSerializeSymbol)); + inst->free_string = + reinterpret_cast(dlsym(h, kFreeStringSymbol)); + inst->deserialize = + reinterpret_cast(dlsym(h, kDeserializeSymbol)); + inst->info = info; + inst->dlclose_on_destroy = dlclose_on_destroy; + return inst; +#else + (void)load_path; + (void)dlclose_on_destroy; + return std::unexpected{LoadError::NotSupported}; +#endif + } + + // Move state old -> new (v2 serialize/deserialize, else transfer). + // Returns false only if the new instance rejects the state. + bool transfer_state(const detail::Instance& from, detail::Instance& to) + { + if (from.plugin == nullptr || to.plugin == nullptr) { + return true; + } + if (from.serialize != nullptr && to.deserialize != nullptr) { + const std::uint32_t version = + from.state_version != nullptr ? from.state_version() : 0; + const char* json = from.serialize(from.plugin); + if (json != nullptr) { + const int rc = to.deserialize(to.plugin, json, version); + if (from.free_string != nullptr) { + from.free_string(json); + } + if (rc != 0) { + Void::Log::warn( + "Plugin.Manager", + "deserialize rejected state (v{}, rc={})", version, + rc); + return false; + } + return true; + } + } + if (to.transfer != nullptr) { + to.transfer(from.plugin, to.plugin); + } + return true; + } + + // Copy to a fresh-inode temp path so dlopen does not return the + // already-mapped image when the file is replaced in place. + std::expected + hotswap_copy(const std::filesystem::path& path) + { + const auto tmp = path.parent_path() / + (path.filename().string() + ".void_hotswap"); + std::error_code ec; + std::filesystem::copy_file( + path, tmp, std::filesystem::copy_options::overwrite_existing, + ec); + if (ec) { + return std::unexpected{LoadError::FileNotFound}; + } + return tmp; + } + } // namespace + + // ── PluginManager ───────────────────────────────────────────────────── + + PluginManager::PluginManager(Options options) + : m_options(options), m_watcher(FileSystem::FileWatcherOptions{ + .poll_interval = options.poll_interval, + .debounce_polls = options.debounce_polls}) + { + } + + PluginManager::~PluginManager() = default; + + PluginManager::Entry* PluginManager::find(std::string_view name) const + { + const auto it = m_plugins.find(std::string{name}); + return it == m_plugins.end() ? nullptr : it->second.get(); + } + + std::expected + PluginManager::load(const std::filesystem::path& path) + { + std::error_code ec; + if (!std::filesystem::exists(path, ec)) { + return std::unexpected{LoadError::FileNotFound}; + } + auto inst = open_instance(path, m_options.dlclose_on_swap); + if (!inst.has_value()) { + Void::Log::warn("Plugin.Manager", "load '{}' failed: {}", + path.string(), to_string(inst.error())); + return std::unexpected{inst.error()}; + } + (*inst)->plugin->on_load(); + std::string name{(*inst)->plugin->name()}; + + std::lock_guard lock(m_mutex); + auto entry = std::make_unique(); + entry->path = path; + entry->current.store(std::move(*inst), std::memory_order_release); + Void::Log::info("Plugin.Manager", "loaded '{}' as '{}' (v{})", + path.string(), name, + entry->current.load(std::memory_order_relaxed) + ->info.plugin_version); + m_plugins.insert_or_assign(name, std::move(entry)); + return name; + } + + PluginHandle PluginManager::acquire(std::string_view name) const + { + std::lock_guard lock(m_mutex); + auto* entry = find(name); + if (entry == nullptr) { + return PluginHandle{}; + } + // One atomic load pins the instance; it survives any later swap. + return PluginHandle{entry->current.load(std::memory_order_acquire)}; + } + + 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}; + } + return reload_locked(*entry, name); + } + + std::expected + PluginManager::reload_locked(Entry& entry, std::string_view name) + { + // Copy to a fresh inode so dlopen loads the new bytes instead of + // returning the still-open handle for this path. The caller must + // have installed the new file via atomic rename (a fresh inode of + // its own) — overwriting the mapped file in place corrupts the + // running instance's mapping (SIGBUS). + auto tmp = hotswap_copy(entry.path); + if (!tmp.has_value()) { + return std::unexpected{tmp.error()}; + } + auto next = open_instance(*tmp, m_options.dlclose_on_swap); + std::error_code ec; + std::filesystem::remove(*tmp, ec); + if (!next.has_value()) { + Void::Log::warn("Plugin.Manager", + "reload '{}' failed: {}; keeping old", name, + to_string(next.error())); + return std::unexpected{next.error()}; + } + + // Transfer state with both instances alive (transactional). + auto old = entry.current.load(std::memory_order_acquire); + if (old) { + if (!transfer_state(*old, **next)) { + Void::Log::warn("Plugin.Manager", + "reload '{}' aborted: state rejected", name); + return std::unexpected{LoadError::StateRejected}; + } + } + + (*next)->plugin->on_load(); + // 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); + Void::Log::info("Plugin.Manager", "reloaded '{}'", name); + return {}; + } + + void PluginManager::watch(std::string_view name) + { + std::filesystem::path path; + { + std::lock_guard lock(m_mutex); + auto* entry = find(name); + if (entry == nullptr) { + return; + } + path = entry->path; + } + const std::string name_str{name}; + m_watcher.watch( + path, [this, name_str](const FileSystem::FileWatcher::Event& e) { + if (!e.exists) { + return; + } + std::function cb; + { + std::lock_guard lock(m_mutex); + auto* entry = find(name_str); + if (entry == nullptr) { + return; + } + if (!reload_locked(*entry, name_str).has_value()) { + return; + } + cb = m_on_reloaded; + } + if (cb) { + cb(name_str); + } + }); + } + + void PluginManager::unwatch(std::string_view name) + { + std::lock_guard lock(m_mutex); + auto* entry = find(name); + if (entry != nullptr) { + m_watcher.unwatch(entry->path); + } + } + + void PluginManager::on_reloaded( + std::function cb) + { + std::lock_guard lock(m_mutex); + m_on_reloaded = std::move(cb); + } + + std::vector PluginManager::names() const + { + std::lock_guard lock(m_mutex); + std::vector out; + out.reserve(m_plugins.size()); + for (const auto& [name, _] : m_plugins) { + out.push_back(name); + } + return out; + } + +} // namespace Void::Plugin diff --git a/src/Plugin/module.cmake b/src/Plugin/module.cmake index 7420909..7438e40 100644 --- a/src/Plugin/module.cmake +++ b/src/Plugin/module.cmake @@ -1,3 +1,4 @@ void_add_module(Plugin + INTERNAL_DEPS Functional System Data DEPS_UNIX dl ) diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 260e423..569696b 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -97,4 +97,23 @@ if(TARGET Void::Plugin) ) add_dependencies(VoidTests VoidTestPlugin) endif() + + # 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 + "${CMAKE_CURRENT_SOURCE_DIR}/plugins/StatefulPluginV1.cpp") + add_library(VoidStatefulPluginV2 SHARED + "${CMAKE_CURRENT_SOURCE_DIR}/plugins/StatefulPluginV2.cpp") + foreach(_sp VoidStatefulPluginV1 VoidStatefulPluginV2) + target_link_libraries(${_sp} PRIVATE Void::Plugin Void::Data) + target_include_directories(${_sp} PRIVATE + "${CMAKE_CURRENT_SOURCE_DIR}/plugins") + endforeach() + target_compile_definitions(VoidTests PRIVATE + "VOID_STATEFUL_V1_PATH=\"$\"" + "VOID_STATEFUL_V2_PATH=\"$\"" + ) + target_include_directories(VoidTests PRIVATE + "${CMAKE_CURRENT_SOURCE_DIR}/plugins") + add_dependencies(VoidTests VoidStatefulPluginV1 VoidStatefulPluginV2) endif() diff --git a/tests/plugins/Stateful.hpp b/tests/plugins/Stateful.hpp new file mode 100644 index 0000000..f450e3a --- /dev/null +++ b/tests/plugins/Stateful.hpp @@ -0,0 +1,28 @@ +#pragma once + +#include + +#include + +// Shared interface for the stateful hot-reload test plugins. The host +// holds an IPlugin*; because every stateful plugin's concrete type derives +// from IStateful through a single-inheritance chain, the host recovers the +// richer interface with static_cast (dynamic_cast is unreliable across +// RTLD_LOCAL boundaries). The vtable layout is identical on both sides as +// long as this header is shared — which it is. +namespace VoidTest +{ + class IStateful : public Void::Plugin::IPlugin + { + public: + + [[nodiscard]] virtual int counter() const = 0; + virtual void bump() = 0; + [[nodiscard]] virtual int schema_version() const = 0; + }; + + [[nodiscard]] inline IStateful* as_stateful(Void::Plugin::IPlugin* p) + { + return static_cast(p); + } +} // namespace VoidTest diff --git a/tests/plugins/StatefulPluginV1.cpp b/tests/plugins/StatefulPluginV1.cpp new file mode 100644 index 0000000..466e4a3 --- /dev/null +++ b/tests/plugins/StatefulPluginV1.cpp @@ -0,0 +1,98 @@ +#include "Stateful.hpp" + +#include + +#include +#include +#include +#include + +// Stateful plugin, schema v1. State is a single counter, serialized as +// {"__version":1,"data":{"count":N}} via the reflection JSON serializer. + +namespace +{ + struct StateV1 { + int count = 0; + }; + + class PluginV1 final : public VoidTest::IStateful + { + public: + + [[nodiscard]] std::string_view name() const noexcept override + { + return "StatefulPlugin"; + } + + [[nodiscard]] int counter() const override + { + return m_count.load(std::memory_order_relaxed); + } + void bump() override + { + m_count.fetch_add(1, std::memory_order_relaxed); + } + [[nodiscard]] int schema_version() const override { return 1; } + + std::atomic m_count{0}; + }; +} // namespace + +template <> struct Void::Json::StateTraits { + static constexpr std::uint32_t version = 1; +}; + +extern "C" { + +void* void_plugin_create() { return new PluginV1; } + +void void_plugin_destroy(void* p) { delete static_cast(p); } + +Void::Plugin::PluginInfo void_plugin_info() +{ + return { + .abi_version = Void::Plugin::ABI_VERSION, + .name = "StatefulPlugin", + .plugin_version = "1.0.0", + .description = "Stateful test plugin (schema v1)", + }; +} + +std::uint32_t void_plugin_state_version() { return 1; } + +const char* void_plugin_serialize_state(void* instance) +{ + const auto* self = static_cast(instance); + const StateV1 state{.count = self->counter()}; + const auto json = + Void::Json::serialize(Void::Json::to_versioned_json(state)); + char* out = static_cast(std::malloc(json.size() + 1)); + if (out != nullptr) { + std::memcpy(out, json.c_str(), json.size() + 1); + } + return out; +} + +void void_plugin_free_string(const char* s) +{ + std::free(const_cast(s)); // NOLINT +} + +int void_plugin_deserialize_state(void* instance, const char* json, + std::uint32_t /*from_version*/) +{ + auto* self = static_cast(instance); + const auto parsed = Void::Json::parse(json); + if (!parsed.has_value()) { + return 1; + } + const auto state = Void::Json::from_versioned_json(*parsed); + if (!state.has_value()) { + return 2; + } + self->m_count.store(state->count, std::memory_order_relaxed); + return 0; +} + +} // extern "C" diff --git a/tests/plugins/StatefulPluginV2.cpp b/tests/plugins/StatefulPluginV2.cpp new file mode 100644 index 0000000..644f6b9 --- /dev/null +++ b/tests/plugins/StatefulPluginV2.cpp @@ -0,0 +1,116 @@ +#include "Stateful.hpp" + +#include + +#include +#include +#include +#include + +// Stateful plugin, schema v2 — same plugin name as v1, so a PluginManager +// reload swaps v1 -> v2 in place. State gains a `tag` field; v1 JSON is +// migrated by the chain living here (the new build knows the old format). + +namespace +{ + struct StateV2 { + int count = 0; + std::string tag = "v2"; // added in v2 + }; + + class PluginV2 final : public VoidTest::IStateful + { + public: + + [[nodiscard]] std::string_view name() const noexcept override + { + return "StatefulPlugin"; + } + + [[nodiscard]] int counter() const override + { + return m_count.load(std::memory_order_relaxed); + } + void bump() override + { + m_count.fetch_add(1, std::memory_order_relaxed); + } + [[nodiscard]] int schema_version() const override { return 2; } + + std::atomic m_count{0}; + std::string m_tag{"v2"}; + }; + + Void::Json::MigrationChain migrations() + { + Void::Json::MigrationChain chain; + // v1 -> v2: keep count, introduce tag marking the upgrade. + chain.add(1, [](Void::Json::Value data) { + data.as_object().emplace_back("tag", Void::Json::Value{"migrated"}); + return data; + }); + return chain; + } +} // namespace + +template <> struct Void::Json::StateTraits { + static constexpr std::uint32_t version = 2; +}; + +extern "C" { + +void* void_plugin_create() { return new PluginV2; } + +void void_plugin_destroy(void* p) { delete static_cast(p); } + +Void::Plugin::PluginInfo void_plugin_info() +{ + return { + .abi_version = Void::Plugin::ABI_VERSION, + .name = "StatefulPlugin", + .plugin_version = "2.0.0", + .description = "Stateful test plugin (schema v2)", + }; +} + +std::uint32_t void_plugin_state_version() { return 2; } + +const char* void_plugin_serialize_state(void* instance) +{ + const auto* self = static_cast(instance); + const StateV2 state{.count = self->counter(), .tag = self->m_tag}; + const auto json = + Void::Json::serialize(Void::Json::to_versioned_json(state)); + char* out = static_cast(std::malloc(json.size() + 1)); + if (out != nullptr) { + std::memcpy(out, json.c_str(), json.size() + 1); + } + return out; +} + +void void_plugin_free_string(const char* s) +{ + std::free(const_cast(s)); // NOLINT +} + +int void_plugin_deserialize_state(void* instance, const char* json, + std::uint32_t /*from_version*/) +{ + auto* self = static_cast(instance); + const auto parsed = Void::Json::parse(json); + if (!parsed.has_value()) { + return 1; + } + // from_versioned_json reads the envelope's own __version and migrates + // up to StateV2's version (2) using the chain. + const auto state = + Void::Json::from_versioned_json(*parsed, migrations()); + if (!state.has_value()) { + return 2; + } + self->m_count.store(state->count, std::memory_order_relaxed); + self->m_tag = state->tag; + return 0; +} + +} // extern "C" diff --git a/tests/standalone/Plugin/HotReloadUnderLoad.cpp b/tests/standalone/Plugin/HotReloadUnderLoad.cpp new file mode 100644 index 0000000..7807d32 --- /dev/null +++ b/tests/standalone/Plugin/HotReloadUnderLoad.cpp @@ -0,0 +1,108 @@ +#include +#include +#include +#include + +#include "Stateful.hpp" + +#include +#include +#include +#include +#include + +using namespace Void::Plugin; + +#if defined(VOID_STATEFUL_V1_PATH) && defined(VOID_STATEFUL_V2_PATH) && \ + __has_include() + +namespace +{ + // Atomic-rename install (fresh inode) — overwriting a mapped .so in + // place corrupts the running mapping (SIGBUS). + void install(const std::filesystem::path& src, + const std::filesystem::path& dst) + { + auto staging = dst; + staging += ".incoming"; + std::filesystem::copy_file( + src, staging, std::filesystem::copy_options::overwrite_existing); + std::filesystem::rename(staging, dst); + } +} // namespace + +// @tag stress, concurrency +Void::Testing::Test hot_reload_under_concurrent_load() +{ + Void::FileSystem::TempDir tmp{"void_hotload"}; + 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()); + + std::atomic stop{false}; + std::atomic ops{0}; + std::atomic sane{true}; + std::atomic crashes{0}; + + // Reader threads continuously acquire a pinned handle and use the + // plugin through it. acquire() returns a handle that keeps whichever + // instance was current alive for the whole call — so even as the main + // thread swaps instances underneath, no reader ever touches a freed + // object (ASan would catch it otherwise). + std::vector readers; + readers.reserve(6); + for (int r = 0; r < 6; ++r) { + readers.emplace_back([&] { + while (!stop.load(std::memory_order_relaxed)) { + auto h = mgr.acquire("StatefulPlugin"); + if (!h) { + crashes.fetch_add(1); + continue; + } + auto* s = VoidTest::as_stateful(h.get()); + const int before = s->counter(); + s->bump(); + const int after = s->counter(); + // The pinned instance is consistent within the call. + if (after < before + 1) { + sane.store(false); + } + const int v = s->schema_version(); + if (v != 1 && v != 2) { + sane.store(false); + } + ops.fetch_add(1, std::memory_order_relaxed); + } + }); + } + + // Main thread flips the file v1<->v2 and reloads repeatedly. + 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 auto r = mgr.reload("StatefulPlugin"); + Void::Testing::expect(r.has_value()); + std::this_thread::sleep_for(std::chrono::milliseconds{2}); + } + + stop.store(true); + for (auto& t : readers) { + t.join(); + } + + Void::Testing::expect(sane.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). + auto final = mgr.acquire("StatefulPlugin"); + Void::Testing::expect(static_cast(final)); + Void::Testing::expect(VoidTest::as_stateful(final.get())->counter() > 0); +} + +#endif // stateful plugins available diff --git a/tests/standalone/Plugin/Manager.cpp b/tests/standalone/Plugin/Manager.cpp new file mode 100644 index 0000000..5f7d4c8 --- /dev/null +++ b/tests/standalone/Plugin/Manager.cpp @@ -0,0 +1,169 @@ +#include +#include +#include +#include +#include + +#include "Stateful.hpp" + +#include +#include +#include +#include +#include + +using namespace Void::Plugin; + +#if defined(VOID_STATEFUL_V1_PATH) && defined(VOID_STATEFUL_V2_PATH) && \ + __has_include() + +namespace +{ + VoidTest::IStateful* stateful(const PluginHandle& h) + { + return VoidTest::as_stateful(h.get()); + } + + // Install a plugin version by atomic rename (fresh inode). Overwriting + // a mapped .so in place would corrupt the running instance's mapping + // (SIGBUS) — deployments must swap the file, not rewrite it. + void install(const std::filesystem::path& src, + const std::filesystem::path& dst) + { + auto staging = dst; + staging += ".incoming"; + std::filesystem::copy_file( + src, staging, std::filesystem::copy_options::overwrite_existing); + std::filesystem::rename(staging, dst); + } +} // namespace + +Void::Testing::Test manager_loads_and_acquires() +{ + PluginManager mgr; + const auto name = mgr.load(VOID_STATEFUL_V1_PATH); + Void::Testing::expect(name.has_value()); + Void::Testing::expect_eq(*name, std::string{"StatefulPlugin"}); + + auto h = mgr.acquire("StatefulPlugin"); + Void::Testing::expect(static_cast(h)); + Void::Testing::expect_eq(stateful(h)->schema_version(), 1); + stateful(h)->bump(); + stateful(h)->bump(); + Void::Testing::expect_eq(stateful(h)->counter(), 2); +} + +Void::Testing::Test manager_unknown_plugin_yields_empty_handle() +{ + PluginManager mgr; + Void::Testing::expect(!static_cast(mgr.acquire("nope"))); + Void::Testing::expect(mgr.reload("nope").error() == + LoadError::UnknownPlugin); +} + +Void::Testing::Test manager_reload_migrates_v1_state_to_v2() +{ + // Copy v1 into a temp path we control, then overwrite with v2 and + // reload — exactly the in-place upgrade a deployment performs. + Void::FileSystem::TempDir tmp{"void_mgr"}; + const auto so = tmp.path() / "plugin.so"; + std::filesystem::copy_file(VOID_STATEFUL_V1_PATH, so); + + PluginManager mgr; + const auto name = mgr.load(so); + Void::Testing::expect(name.has_value()); + + { + auto h = mgr.acquire("StatefulPlugin"); + Void::Testing::expect_eq(stateful(h)->schema_version(), 1); + stateful(h)->bump(); + stateful(h)->bump(); + stateful(h)->bump(); // count = 3 + } + + install(VOID_STATEFUL_V2_PATH, so); + const auto reloaded = mgr.reload("StatefulPlugin"); + Void::Testing::expect(reloaded.has_value()); + + auto h = mgr.acquire("StatefulPlugin"); + Void::Testing::expect_eq(stateful(h)->schema_version(), 2); + Void::Testing::expect_eq(stateful(h)->counter(), 3); // migrated +} + +Void::Testing::Test manager_pinned_handle_survives_reload() +{ + 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()); + + // Pin the v1 instance, then reload to v2 while still holding it. + auto old = mgr.acquire("StatefulPlugin"); + stateful(old)->bump(); + stateful(old)->bump(); // old count = 2 + + install(VOID_STATEFUL_V2_PATH, so); + Void::Testing::expect(mgr.reload("StatefulPlugin").has_value()); + + // The pinned handle still addresses the live v1 instance (no torn + // state, no use-after-free — the old .so stays mapped while pinned). + Void::Testing::expect_eq(stateful(old)->schema_version(), 1); + Void::Testing::expect_eq(stateful(old)->counter(), 2); + + // A fresh acquire gets the migrated v2 instance. + auto fresh = mgr.acquire("StatefulPlugin"); + Void::Testing::expect_eq(stateful(fresh)->schema_version(), 2); + Void::Testing::expect_eq(stateful(fresh)->counter(), 2); +} + +Void::Testing::Test manager_legacy_transfer_state_plugin_still_reloads() +{ + // The original TestPlugin uses only transfer_state (no v2 protocol); + // the manager must still reload it via the fallback path. +#ifdef VOID_TEST_PLUGIN_PATH + Void::FileSystem::TempDir tmp{"void_mgr"}; + const auto so = tmp.path() / "legacy.so"; + std::filesystem::copy_file(VOID_TEST_PLUGIN_PATH, so); + + PluginManager mgr; + const auto name = mgr.load(so); + Void::Testing::expect(name.has_value()); + Void::Testing::expect(mgr.reload(*name).has_value()); + Void::Testing::expect(static_cast(mgr.acquire("TestPlugin"))); +#endif +} + +// @tag integration +Void::Testing::Test manager_watch_auto_reloads_on_file_change() +{ + Void::FileSystem::TempDir tmp{"void_mgr"}; + const auto so = tmp.path() / "plugin.so"; + std::filesystem::copy_file(VOID_STATEFUL_V1_PATH, so); + + PluginManager mgr{ + {.poll_interval = std::chrono::milliseconds{10}, .debounce_polls = 2}}; + Void::Testing::expect(mgr.load(so).has_value()); + + std::atomic reloads{0}; + mgr.on_reloaded([&](std::string_view) { ++reloads; }); + mgr.watch("StatefulPlugin"); + + Void::Testing::expect_eq( + mgr.acquire("StatefulPlugin").info().plugin_version, + std::string_view{"1.0.0"}); + + // Replace the file with v2 (atomic rename); the watcher reloads it. + install(VOID_STATEFUL_V2_PATH, so); + + for (int i = 0; i < 300 && reloads.load() == 0; ++i) { + std::this_thread::sleep_for(std::chrono::milliseconds{5}); + } + Void::Testing::expect(reloads.load() >= 1); + Void::Testing::expect_eq(mgr.acquire("StatefulPlugin")->name(), + std::string_view{"StatefulPlugin"}); + mgr.unwatch("StatefulPlugin"); +} + +#endif // stateful plugins available