Files

240 lines
9.6 KiB
C++

#pragma once
#include <Void/Plugin/Plugin.hpp>
#include <Void/System/FileWatcher.hpp>
#include <atomic>
#include <chrono>
#include <cstdint>
#include <expected>
#include <filesystem>
#include <functional>
#include <memory>
#include <mutex>
#include <optional>
#include <string>
#include <string_view>
#include <unordered_map>
#include <utility>
#include <vector>
namespace Void::Plugin
{
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;
/// Resolve an optional symbol from the exact shared object pinned
/// by this handle. The returned address remains valid while the
/// handle is alive, even if the manager concurrently reloads the
/// plugin.
[[nodiscard]] void* raw_symbol(const char* symbol) const noexcept;
private:
friend class PluginManager;
explicit PluginHandle(std::shared_ptr<detail::Instance> pin)
: m_pin(std::move(pin))
{
}
std::shared_ptr<detail::Instance> 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;
// 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
// name argument is the registry name (IPlugin::name()).
std::function<std::string(std::string_view plugin_name)>
config_provider;
// Host-specific contract checked after plugin activation and before
// publication. A failed validation aborts load/reload
// transactionally.
std::function<bool(IPlugin&, const PluginInfo&)> instance_validator;
// Binary-level contract checked immediately after the shared object
// is opened and identified, before configuration, activation, state
// transfer, or publication. Hosts can inspect optional exported
// symbols through the pinned handle. A rejection is transactional:
// initial loads are discarded and reloads keep the current
// instance.
std::function<bool(const PluginHandle&)> candidate_validator;
};
// Identifies an on_reloaded observer for remove_on_reloaded.
using ReloadCallbackId = std::size_t;
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<std::string, LoadError>
load(const std::filesystem::path& path);
/// Load every plugin file in `dir` (non-recursive), in filename
/// order for determinism. Only files with the platform's shared-
/// library extension are considered. Returns one entry per
/// candidate: its path and either the loaded plugin's name or
/// the load error. An empty result means no candidates existed
/// (or the directory does not).
std::vector<std::pair<std::filesystem::path,
std::expected<std::string, LoadError>>>
load_directory(const std::filesystem::path& dir);
/// Unload `name`: stop watching it and drop it from the
/// registry. The instance is destroyed once the last
/// outstanding PluginHandle drops (RCU semantics, same as a
/// reload swap).
std::expected<void, LoadError> unload(std::string_view name);
/// Pin the current instance for `name`. The returned handle
/// keeps it alive for as long as it lives. Empty handle if no
/// such plugin. One atomic load on the hot path.
[[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<void, LoadError> reload(std::string_view name);
/// Replace `name` from an immutable new library path. The candidate
/// must report the same plugin name. It is configured, receives the
/// old state, activates and passes host validation before one
/// atomic publication. On any error the current instance, source
/// path and watcher remain unchanged. Pinned old handles remain
/// valid.
std::expected<void, LoadError>
replace(std::string_view name,
const std::filesystem::path& newPath);
/// 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);
/// Register an observer invoked after every successful reload
/// (manual or watched), on the reloading thread. Multiple
/// observers coexist; the returned id removes this one.
ReloadCallbackId
on_reloaded(std::function<void(std::string_view name)> cb);
void remove_on_reloaded(ReloadCallbackId id);
/// A point-in-time state snapshot taken through the plugin's v2
/// serialize export, for embedders that need to carry plugin
/// state through their *own* lifecycle (e.g. the host process
/// hot-reloading itself). `version` is the plugin's state
/// schema version at snapshot time.
struct StateSnapshot {
std::string json;
std::uint32_t version{0};
};
/// Snapshot `name`'s current state. Empty when the plugin is
/// unknown, exports no v2 serialize, or serialization fails.
[[nodiscard]] std::optional<StateSnapshot>
serialize_state(std::string_view name) const;
/// Inject a serialized state into `name`'s current instance via
/// its v2 deserialize export. `from_version` is the schema
/// version the JSON was produced with (migrations live in the
/// plugin). Returns false when the plugin is unknown, exports
/// no deserialize, or rejects the state.
bool deserialize_state(std::string_view name,
std::string_view json,
std::uint32_t from_version);
[[nodiscard]] std::vector<std::string> names() const;
/// Resolve an optional extra entry point exported by the
/// plugin's current .so (e.g. an FSM behaviour factory).
/// Returns nullptr if the plugin or symbol is absent.
/// reinterpret_cast the result to the expected function type.
[[nodiscard]] void* raw_symbol(std::string_view name,
const char* symbol) const;
private:
struct Entry {
std::filesystem::path path;
std::atomic<std::shared_ptr<detail::Instance>> current;
bool watched{false};
std::mutex reload_mutex;
};
Entry* find(std::string_view name) const;
std::shared_ptr<Entry> find_shared(std::string_view name) const;
std::expected<void, LoadError> reload_entry_unlocked(
const std::shared_ptr<Entry>& entry, std::string_view name,
const std::optional<std::filesystem::path>& newPath);
std::vector<std::function<void(std::string_view)>>
reload_callbacks_locked() const;
Options m_options;
mutable std::mutex m_mutex; // guards the registry map & observer list
std::unordered_map<std::string, std::shared_ptr<Entry>> m_plugins;
std::vector<std::pair<ReloadCallbackId,
std::function<void(std::string_view)>>>
m_on_reloaded;
ReloadCallbackId m_next_reload_id{1};
FileSystem::FileWatcher m_watcher;
};
} // namespace Void::Plugin