#pragma once #include #include #include #include namespace Void::Plugin { enum class LoadError { FileNotFound, DlopenFailed, SymbolMissing, AbiMismatch, 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 NameMismatch, // replacement reports a different registry name }; [[nodiscard]] std::string_view to_string(LoadError e) noexcept; // ── PluginLoader // ────────────────────────────────────────────────────────────── Owns one // plugin instance loaded from a shared library. // // Hot-reload protocol: // 1. The new .so (at the same canonical path) is copied to a temp file so // dlopen gets a fresh inode even if the path was already cached. // 2. New instance is created and optional transfer_state() called (both // old and new instances are alive simultaneously at this point). // 3. Old instance is destroyed and old handle is closed. // // Thread safety: not thread-safe. Protect with external locking if needed. class PluginLoader { public: [[nodiscard]] static std::expected load(std::filesystem::path path); ~PluginLoader(); PluginLoader(PluginLoader&&) noexcept; PluginLoader& operator=(PluginLoader&&) noexcept; PluginLoader(const PluginLoader&) = delete; PluginLoader& operator=(const PluginLoader&) = delete; [[nodiscard]] IPlugin* plugin() noexcept { return plugin_; } [[nodiscard]] const IPlugin* plugin() const noexcept { return plugin_; } [[nodiscard]] const PluginInfo& info() const noexcept { return info_; } [[nodiscard]] bool loaded() const noexcept { return handle_ != nullptr; } 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. 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; // 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_{}; ready_fn ready_{}; 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 load_from(const std::filesystem::path& path); void destroy_current() noexcept; }; } // namespace Void::Plugin