Fsm/PluginBehavior.hpp: IFsmBehaviorPack::register_into(Builder&) lets a plugin contribute states/events/guards/actions; plugins export it via extern "C" void_plugin_fsm_behaviors(). build_machine_def(pack) runs the pack through a Builder and validates. PluginManager::raw_symbol(name, symbol) resolves an optional extra entry point from a plugin's current .so (returns nullptr if absent), so the host can fetch the behaviour factory without widening the frozen IPlugin vtable. Integration flow (tests/internal/FsmPluginHotReload.cpp): build a machine def from the plugin pack, run it; on reload, rebuild from the reloaded pack and swap_definition between RTC steps. Same state names across versions ⇒ the live configuration is adopted seamlessly (machine keeps running, queue intact); v2's new "skip" transition goes live. Safety: plugin actions are std::functions whose code lives in the .so, so a PluginHandle is pinned for the machine's lifetime and dlclose_on_swap= false keeps the code pages mapped under in-flight frames. Tests: FsmPluginV1/V2 (same idle/busy/done states; v2 adds skip). Definition-swap test proves configuration survival + new behaviour; the stress test runs 4 producer threads posting while 5 v1<->v2 rebuild+swaps happen concurrently, then asserts exactly one active leaf. 967 tests green, stable across runs, ASan+UBSan clean. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
379 lines
11 KiB
C++
379 lines
11 KiB
C++
#include <Void/Plugin/Manager.hpp>
|
|
#include <Void/Log/Log.hpp>
|
|
#include <Void/Plugin/Loader.hpp>
|
|
|
|
#if defined(__unix__) || defined(__APPLE__)
|
|
#include <dlfcn.h>
|
|
#define VOID_HAS_DLOPEN 1
|
|
#endif
|
|
|
|
#include <cstdint>
|
|
#include <system_error>
|
|
#include <utility>
|
|
|
|
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<std::shared_ptr<detail::Instance>, 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<info_fn>(dlsym(h, kInfoSymbol));
|
|
const auto create_sym =
|
|
reinterpret_cast<create_fn>(dlsym(h, kCreateSymbol));
|
|
const auto destroy_sym =
|
|
reinterpret_cast<destroy_fn>(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<detail::Instance>();
|
|
inst->handle = h;
|
|
inst->plugin = static_cast<IPlugin*>(raw);
|
|
inst->destroy = destroy_sym;
|
|
inst->transfer =
|
|
reinterpret_cast<transfer_fn>(dlsym(h, kTransferSymbol));
|
|
inst->state_version = reinterpret_cast<state_version_fn>(
|
|
dlsym(h, kStateVersionSymbol));
|
|
inst->serialize =
|
|
reinterpret_cast<serialize_fn>(dlsym(h, kSerializeSymbol));
|
|
inst->free_string =
|
|
reinterpret_cast<free_string_fn>(dlsym(h, kFreeStringSymbol));
|
|
inst->deserialize =
|
|
reinterpret_cast<deserialize_fn>(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<std::filesystem::path, LoadError>
|
|
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<std::string, LoadError>
|
|
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>();
|
|
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<void, LoadError> PluginManager::reload(std::string_view name)
|
|
{
|
|
std::lock_guard lock(m_mutex);
|
|
auto* entry = find(name);
|
|
if (entry == nullptr) {
|
|
return std::unexpected{LoadError::UnknownPlugin};
|
|
}
|
|
return reload_locked(*entry, name);
|
|
}
|
|
|
|
std::expected<void, LoadError>
|
|
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<void(std::string_view)> 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<void(std::string_view name)> cb)
|
|
{
|
|
std::lock_guard lock(m_mutex);
|
|
m_on_reloaded = std::move(cb);
|
|
}
|
|
|
|
std::vector<std::string> PluginManager::names() const
|
|
{
|
|
std::lock_guard lock(m_mutex);
|
|
std::vector<std::string> out;
|
|
out.reserve(m_plugins.size());
|
|
for (const auto& [name, _] : m_plugins) {
|
|
out.push_back(name);
|
|
}
|
|
return out;
|
|
}
|
|
|
|
void* PluginManager::raw_symbol(std::string_view name,
|
|
const char* symbol) const
|
|
{
|
|
#ifdef VOID_HAS_DLOPEN
|
|
std::shared_ptr<detail::Instance> inst;
|
|
{
|
|
std::lock_guard lock(m_mutex);
|
|
auto* entry = find(name);
|
|
if (entry == nullptr) {
|
|
return nullptr;
|
|
}
|
|
inst = entry->current.load(std::memory_order_acquire);
|
|
}
|
|
if (!inst || inst->handle == nullptr) {
|
|
return nullptr;
|
|
}
|
|
return dlsym(inst->handle, symbol);
|
|
#else
|
|
(void)name;
|
|
(void)symbol;
|
|
return nullptr;
|
|
#endif
|
|
}
|
|
|
|
} // namespace Void::Plugin
|