Files
Library/src/Plugin/Host.cpp
T

1648 lines
50 KiB
C++

#include <Void/Plugin/Host.hpp>
#include <Void/Log/Log.hpp>
#include <Void/Text/Semver.hpp>
#if defined(__unix__) || defined(__APPLE__)
#include <dlfcn.h>
#define VOID_HOST_HAS_DLOPEN 1
#endif
#include <algorithm>
#include <atomic>
#include <condition_variable>
#include <cstring>
#include <deque>
#include <memory>
#include <mutex>
#include <queue>
#include <stop_token>
#include <string>
#include <system_error>
#include <thread>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
namespace Void::Plugin
{
namespace
{
PluginErrorCode map_cabi_status(std::int32_t status,
PluginErrorCode fallback) noexcept
{
switch (status) {
case VOID_STATUS_INVALID_ARGUMENT:
return PluginErrorCode::invalid_argument;
case VOID_STATUS_NOT_FOUND:
return PluginErrorCode::not_found;
case VOID_STATUS_CONFLICT:
return PluginErrorCode::conflict;
case VOID_STATUS_CANCELLED:
return PluginErrorCode::cancelled;
case VOID_STATUS_TIMEOUT:
return PluginErrorCode::timeout;
case VOID_STATUS_OVERLOADED:
case VOID_STATUS_EXHAUSTED:
return PluginErrorCode::budget_exceeded;
case VOID_STATUS_UNSUPPORTED:
return PluginErrorCode::abi_mismatch;
case VOID_STATUS_NOT_READY:
return PluginErrorCode::not_ready;
case VOID_STATUS_QUIESCING:
return PluginErrorCode::quiesce_failed;
case VOID_STATUS_STATE_REJECTED:
return PluginErrorCode::restore_failed;
case VOID_STATUS_RESTART_REQUIRED:
return PluginErrorCode::restart_required;
default:
return fallback;
}
}
std::string consume_error_detail(void_error_detail_v1& err)
{
std::string msg;
if (err.message != nullptr) {
const std::size_t len = ::strnlen(err.message, 1024);
msg.assign(err.message, len);
if (err.release != nullptr) {
err.release(err.release_ctx, err.message);
}
}
err.message = nullptr;
err.release = nullptr;
return msg;
}
bool is_all_zero(const void* data, std::size_t n) noexcept
{
const auto* bytes = static_cast<const std::uint8_t*>(data);
for (std::size_t i = 0; i < n; ++i) {
if (bytes[i] != 0) {
return false;
}
}
return true;
}
struct DependencySpec {
std::string module_id{};
std::string version_range{};
bool optional_dep{false};
};
} // namespace
struct detail::GenerationRecord
: public std::enable_shared_from_this<GenerationRecord> {
struct HostCtx {
std::weak_ptr<CModuleHost::Impl> host_impl;
std::weak_ptr<GenerationRecord> rec;
};
std::weak_ptr<CModuleHost::Impl> host_impl{};
HostCtx host_api_ctx{};
std::uint64_t generation{0};
std::string module_id{};
std::string version{};
std::uint64_t image_bytes{0};
void* dl_handle{nullptr};
void_module_api_v1 api{};
void_module_handle* mod_handle{nullptr};
std::vector<DependencySpec> dependencies{};
std::uint32_t activation_policy{VOID_POLICY_RELOADABLE};
std::atomic<GenerationHealth> health{GenerationHealth::Healthy};
std::atomic<std::size_t> external_refs{0};
std::atomic<std::size_t> activity_pins{0};
std::atomic<std::size_t> active_async_ops{0};
std::atomic<bool> retire_requested{false};
std::atomic<bool> retired_enqueued{false};
std::atomic<bool> destroyed{false};
std::atomic<bool> dlclosed{false};
bool allow_dlclose{false};
bool activated{false};
void add_external_ref() noexcept
{
external_refs.fetch_add(1, std::memory_order_acq_rel);
}
void release_external_ref() noexcept
{
if (external_refs.fetch_sub(1, std::memory_order_seq_cst) == 1) {
maybe_enqueue_retire();
}
}
void add_activity_pin() noexcept
{
activity_pins.fetch_add(1, std::memory_order_acq_rel);
}
void release_activity_pin() noexcept
{
if (activity_pins.fetch_sub(1, std::memory_order_seq_cst) == 1) {
maybe_enqueue_retire();
}
}
void maybe_enqueue_retire() noexcept;
};
struct CModuleHost::Impl
: public std::enable_shared_from_this<CModuleHost::Impl> {
struct ModuleSlot {
std::mutex reload_mu{};
std::shared_ptr<detail::GenerationRecord> current{};
std::vector<std::shared_ptr<detail::GenerationRecord>>
retained{};
};
explicit Impl(PluginHostLimits l,
const Void::Time::MonotonicClock& c)
: limits(l), clock(&c)
{
retire_thread = std::thread([this] { run_retire_loop(); });
}
~Impl() { shutdown(); }
void enqueue_retire(std::shared_ptr<detail::GenerationRecord> rec)
{
{
std::lock_guard lk{retire_mu};
if (retire_stop) {
return;
}
retire_queue.push_back(std::move(rec));
}
retire_cv.notify_one();
}
void run_retire_loop()
{
for (;;) {
std::shared_ptr<detail::GenerationRecord> rec;
{
std::unique_lock lk{retire_mu};
retire_cv.wait(lk, [this] {
return retire_stop || !retire_queue.empty();
});
if (retire_stop && retire_queue.empty()) {
return;
}
rec = std::move(retire_queue.front());
retire_queue.pop_front();
}
perform_retire(*rec);
}
}
void perform_retire(detail::GenerationRecord& rec) noexcept
{
if (rec.external_refs.load(std::memory_order_seq_cst) > 0 ||
rec.activity_pins.load(std::memory_order_seq_cst) > 0) {
return;
}
bool exp = false;
if (!rec.destroyed.compare_exchange_strong(
exp, true, std::memory_order_acq_rel)) {
return;
}
rec.health.store(GenerationHealth::Retired,
std::memory_order_release);
if (rec.mod_handle != nullptr) {
if (rec.activated && rec.api.deactivate != nullptr) {
(void)rec.api.deactivate(rec.mod_handle);
}
if (rec.api.destroy != nullptr) {
rec.api.destroy(rec.mod_handle);
}
rec.mod_handle = nullptr;
}
#ifdef VOID_HOST_HAS_DLOPEN
if (rec.allow_dlclose && rec.dl_handle != nullptr) {
dlclose(rec.dl_handle);
rec.dl_handle = nullptr;
rec.dlclosed.store(true, std::memory_order_release);
}
#endif
}
void shutdown()
{
std::vector<std::shared_ptr<ModuleSlot>> slots;
{
std::lock_guard lk{map_mu};
closing = true;
for (auto& [_, s] : modules) {
slots.push_back(s);
}
}
for (auto& slot : slots) {
std::lock_guard rlk{slot->reload_mu};
std::shared_ptr<detail::GenerationRecord> prev;
{
std::lock_guard lk{map_mu};
prev = std::exchange(slot->current, nullptr);
}
if (prev) {
prev->retire_requested.store(true,
std::memory_order_seq_cst);
if (prev->api.request_stop != nullptr &&
prev->mod_handle != nullptr) {
(void)prev->api.request_stop(prev->mod_handle);
}
prev->release_external_ref();
}
}
{
std::lock_guard lk{retire_mu};
retire_stop = true;
}
retire_cv.notify_all();
if (retire_thread.joinable()) {
retire_thread.join();
}
// Prune destroyed generations once retirement worker finished; any
// generation still holding external_refs or activity_pins stays
// un-dlclosed intentionally.
for (auto& slot : slots) {
std::lock_guard rlk{slot->reload_mu};
for (auto& r : slot->retained) {
if (r &&
r->external_refs.load(std::memory_order_seq_cst) ==
0 &&
r->activity_pins.load(std::memory_order_seq_cst) ==
0) {
perform_retire(*r);
}
}
}
}
static std::uint64_t host_monotonic_ns(void_host_context* ctx)
{
auto* hctx =
reinterpret_cast<detail::GenerationRecord::HostCtx*>(ctx);
if (hctx != nullptr) {
if (auto impl = hctx->host_impl.lock()) {
return static_cast<std::uint64_t>(std::max<std::int64_t>(
0, impl->clock->now().time_since_epoch().count()));
}
}
return 0;
}
static std::int32_t host_acquire_pin(void_host_context* ctx,
std::uint64_t generation)
{
auto* hctx =
reinterpret_cast<detail::GenerationRecord::HostCtx*>(ctx);
if (hctx == nullptr) {
return VOID_STATUS_INVALID_ARGUMENT;
}
auto rec = hctx->rec.lock();
if (!rec || rec->generation != generation ||
rec->destroyed.load(std::memory_order_acquire)) {
return VOID_STATUS_CONFLICT;
}
rec->add_activity_pin();
return VOID_STATUS_OK;
}
static void host_release_pin(void_host_context* ctx,
std::uint64_t generation)
{
auto* hctx =
reinterpret_cast<detail::GenerationRecord::HostCtx*>(ctx);
if (hctx == nullptr) {
return;
}
auto rec = hctx->rec.lock();
if (!rec || rec->generation != generation) {
return;
}
rec->release_activity_pin();
}
static void host_log_msg(void_host_context* /*ctx*/,
std::int32_t level, const char* msg)
{
if (msg == nullptr) {
return;
}
const std::size_t len = ::strnlen(msg, 1024);
const std::string_view sv{msg, len};
if (level <= 0) {
Void::Log::debug("Plugin.CAbi", "{}", sv);
} else {
Void::Log::info("Plugin.CAbi", "{}", sv);
}
}
void notify_observers(const ReloadEvent& ev)
{
std::vector<std::function<void(const ReloadEvent&)>> copy;
{
std::lock_guard lk{obs_mu};
copy.reserve(observers.size());
for (const auto& [_, cb] : observers) {
if (cb) copy.push_back(cb);
}
}
for (const auto& cb : copy) {
try {
cb(ev);
} catch (...) {
}
}
}
void_op_options_v1
make_op_opts(std::optional<Void::Time::MonotonicClock::time_point> dl,
bool stop) const noexcept
{
void_op_options_v1 opts{};
opts.struct_size = sizeof(void_op_options_v1);
opts.flags = 0;
opts.deadline_ns =
dl.has_value()
? static_cast<std::uint64_t>(std::max<std::int64_t>(
0, dl->time_since_epoch().count()))
: 0;
opts.stop_requested = stop ? 1 : 0;
return opts;
}
Void::Result::Result<std::shared_ptr<detail::GenerationRecord>>
open_candidate(const std::filesystem::path& path,
std::uint64_t gen)
{
#ifdef VOID_HOST_HAS_DLOPEN
std::error_code ec;
if (!std::filesystem::is_regular_file(path, ec)) {
return Void::Result::fail(make_plugin_error(
PluginErrorCode::file_not_found,
"CModuleHost: module file not found: " + path.string()));
}
const auto file_sz = std::filesystem::file_size(path, ec);
if (ec) {
return Void::Result::fail(make_plugin_error(
PluginErrorCode::dlopen_failed,
"CModuleHost: cannot stat module file"));
}
if (file_sz > limits.max_mapped_bytes_per_module) {
return Void::Result::fail(make_plugin_error(
PluginErrorCode::budget_exceeded,
"CModuleHost: candidate image exceeds max_mapped_bytes_per_module"));
}
// Fresh-inode copy so repeated loads at same path load fresh bytes.
const std::uint64_t copy_id =
temp_counter.fetch_add(1, std::memory_order_relaxed);
const auto tmp = path.parent_path() /
(path.filename().string() + ".void_cabi." +
std::to_string(copy_id));
std::filesystem::copy_file(
path, tmp, std::filesystem::copy_options::overwrite_existing,
ec);
if (ec) {
return Void::Result::fail(make_plugin_error(
PluginErrorCode::dlopen_failed,
"CModuleHost: failed to stage module copy"));
}
void* handle = dlopen(tmp.c_str(), RTLD_NOW | RTLD_LOCAL);
std::filesystem::remove(tmp, ec);
if (handle == nullptr) {
return Void::Result::fail(make_plugin_error(
PluginErrorCode::dlopen_failed,
std::string{"CModuleHost: dlopen failed: "} +
(dlerror() ? dlerror() : "unknown")));
}
auto cleanup_handle = [&]() {
if (handle != nullptr && limits.allow_safe_dlclose) {
dlclose(handle);
}
handle = nullptr;
};
auto query_fn = reinterpret_cast<void_module_query_v1_fn>(
dlsym(handle, VOID_MODULE_QUERY_SYMBOL_V1));
if (query_fn == nullptr) {
cleanup_handle();
return Void::Result::fail(make_plugin_error(
PluginErrorCode::symbol_missing,
"CModuleHost: missing void_module_query_v1 export"));
}
void_module_api_v1 api{};
const std::int32_t qrc =
query_fn(sizeof(void_module_api_v1), &api);
if (qrc != VOID_STATUS_OK) {
cleanup_handle();
return Void::Result::fail(make_plugin_error(
map_cabi_status(qrc, PluginErrorCode::abi_mismatch),
"CModuleHost: void_module_query_v1 failed"));
}
if (api.struct_size < VOID_MODULE_API_V1_MIN_SIZE ||
api.abi_major != VOID_CABI_MAJOR_V1 || api.reserved != 0) {
cleanup_handle();
return Void::Result::fail(make_plugin_error(
PluginErrorCode::abi_mismatch,
"CModuleHost: invalid C ABI table size, major version, or reserved field"));
}
if (api.get_info == nullptr || api.create == nullptr ||
api.activate == nullptr || api.readiness == nullptr ||
api.request_stop == nullptr || api.deactivate == nullptr ||
api.destroy == nullptr) {
cleanup_handle();
return Void::Result::fail(make_plugin_error(
PluginErrorCode::abi_mismatch,
"CModuleHost: required C ABI callbacks missing"));
}
if ((api.capabilities & VOID_CAP_STATEFUL_CHECKPOINT) != 0 &&
(api.quiesce == nullptr || api.resume == nullptr ||
api.checkpoint == nullptr || api.restore == nullptr)) {
cleanup_handle();
return Void::Result::fail(make_plugin_error(
PluginErrorCode::abi_mismatch,
"CModuleHost: stateful capability requires quiesce/resume/checkpoint/restore"));
}
void_module_info_v1 info{};
const std::int32_t irc = api.get_info(&info);
if (irc != VOID_STATUS_OK ||
info.struct_size < sizeof(void_module_info_v1) ||
info.reserved != 0 || info.module_id == nullptr ||
info.version == nullptr || info.module_id[0] == '\0') {
cleanup_handle();
return Void::Result::fail(make_plugin_error(
PluginErrorCode::abi_mismatch,
"CModuleHost: invalid void_module_info_v1 descriptor"));
}
if (info.dependency_count > limits.max_interfaces_per_module ||
(info.dependency_count > 0 && info.dependencies == nullptr)) {
cleanup_handle();
return Void::Result::fail(make_plugin_error(
PluginErrorCode::abi_mismatch,
"CModuleHost: invalid or oversized dependency list"));
}
auto rec = std::make_shared<detail::GenerationRecord>();
rec->host_impl = weak_from_this();
rec->host_api_ctx.host_impl = weak_from_this();
rec->host_api_ctx.rec = rec;
rec->generation = gen;
rec->module_id = std::string{
info.module_id, ::strnlen(info.module_id, 256)};
rec->version =
std::string{info.version, ::strnlen(info.version, 128)};
rec->image_bytes = file_sz;
rec->dl_handle = handle;
rec->api = api;
rec->activation_policy = info.activation_policy;
rec->allow_dlclose = limits.allow_safe_dlclose;
for (std::uint64_t i = 0; i < info.dependency_count; ++i) {
const auto& d = info.dependencies[i];
if (!is_all_zero(d.reserved, sizeof(d.reserved)) ||
d.module_id == nullptr || d.version_range == nullptr ||
d.module_id[0] == '\0') {
if (rec->allow_dlclose) dlclose(rec->dl_handle);
rec->dl_handle = nullptr;
return Void::Result::fail(make_plugin_error(
PluginErrorCode::abi_mismatch,
"CModuleHost: malformed dependency entry"));
}
if (!Semver::VersionRange::parse(d.version_range)) {
if (rec->allow_dlclose) dlclose(rec->dl_handle);
rec->dl_handle = nullptr;
return Void::Result::fail(make_plugin_error(
PluginErrorCode::abi_mismatch,
"CModuleHost: invalid dependency semver range"));
}
rec->dependencies.push_back(DependencySpec{
.module_id = d.module_id,
.version_range = d.version_range,
.optional_dep = d.optional_dep != 0});
}
void_host_api_v1 host_api{};
host_api.struct_size = sizeof(void_host_api_v1);
host_api.abi_major = VOID_CABI_MAJOR_V1;
host_api.abi_minor = VOID_CABI_MINOR_V1;
host_api.reserved = 0;
host_api.host_ctx =
reinterpret_cast<void_host_context*>(&rec->host_api_ctx);
host_api.generation = gen;
host_api.monotonic_now_ns = &host_monotonic_ns;
host_api.acquire_activity_pin = &host_acquire_pin;
host_api.release_activity_pin = &host_release_pin;
host_api.log_message = &host_log_msg;
void_module_handle* mod = nullptr;
const std::int32_t crc = api.create(&host_api, &mod);
if (crc != VOID_STATUS_OK || mod == nullptr) {
if (rec->allow_dlclose) dlclose(rec->dl_handle);
rec->dl_handle = nullptr;
return Void::Result::fail(make_plugin_error(
map_cabi_status(crc, PluginErrorCode::activation_failed),
"CModuleHost: plugin create failed"));
}
rec->mod_handle = mod;
return rec;
#else
(void)path;
(void)gen;
return Void::Result::fail(make_plugin_error(
PluginErrorCode::dlopen_failed,
"CModuleHost: dlopen unsupported on this platform"));
#endif
}
void dispose_uncommitted(
const std::shared_ptr<detail::GenerationRecord>& rec)
{
if (!rec) return;
rec->retire_requested.store(true, std::memory_order_seq_cst);
perform_retire(*rec);
}
Void::Result::Result<void>
activate_and_verify(detail::GenerationRecord& rec,
std::string_view config,
const Void::Time::MonotonicClock::time_point total_dl,
const Void::Async::OperationOptions& caller_opts)
{
if (config.size() > limits.max_config_bytes) {
return Void::Result::fail(make_plugin_error(
PluginErrorCode::budget_exceeded,
"CModuleHost: config payload exceeds max_config_bytes"));
}
if (caller_opts.stop.stop_requested()) {
return Void::Result::fail(make_plugin_error(
PluginErrorCode::cancelled,
"CModuleHost: cancelled before activation"));
}
if (clock->now() >= total_dl) {
return Void::Result::fail(make_plugin_error(
PluginErrorCode::timeout,
"CModuleHost: reload deadline expired before activation"));
}
void_bytes_v1 cfg{
.data = reinterpret_cast<const std::uint8_t*>(
config.empty() ? "" : config.data()),
.size = static_cast<std::uint64_t>(config.size())};
void_error_detail_v1 err{};
err.struct_size = sizeof(void_error_detail_v1);
const std::int32_t arc =
rec.api.activate(rec.mod_handle, cfg, &err);
std::string emsg = consume_error_detail(err);
if (arc != VOID_STATUS_OK) {
return Void::Result::fail(make_plugin_error(
map_cabi_status(arc, PluginErrorCode::activation_failed),
emsg.empty() ? "CModuleHost: module activate failed"
: emsg));
}
rec.activated = true;
if (clock->now() >= total_dl ||
caller_opts.stop.stop_requested()) {
return Void::Result::fail(make_plugin_error(
caller_opts.stop.stop_requested()
? PluginErrorCode::cancelled
: PluginErrorCode::timeout,
"CModuleHost: cancelled/timed out before readiness check"));
}
std::uint32_t ready_flag = 0;
void_error_detail_v1 rerr{};
rerr.struct_size = sizeof(void_error_detail_v1);
const std::int32_t rrc =
rec.api.readiness(rec.mod_handle, &ready_flag, &rerr);
std::string rmsg = consume_error_detail(rerr);
if (rrc != VOID_STATUS_OK || ready_flag == 0) {
return Void::Result::fail(make_plugin_error(
rrc == VOID_STATUS_OK
? PluginErrorCode::not_ready
: map_cabi_status(rrc, PluginErrorCode::not_ready),
rmsg.empty() ? "CModuleHost: module reported not ready"
: rmsg));
}
return {};
}
PluginHostLimits limits{};
const Void::Time::MonotonicClock* clock{
&Void::Time::SystemMonotonicClock::instance()};
std::atomic<std::uint64_t> next_gen{1};
std::atomic<std::uint64_t> temp_counter{1};
mutable std::mutex map_mu{};
bool closing{false};
std::unordered_map<std::string, std::shared_ptr<ModuleSlot>>
modules{};
std::mutex retire_mu{};
std::condition_variable retire_cv{};
bool retire_stop{false};
std::deque<std::shared_ptr<detail::GenerationRecord>>
retire_queue{};
std::thread retire_thread{};
std::mutex obs_mu{};
std::vector<
std::pair<std::size_t, std::function<void(const ReloadEvent&)>>>
observers{};
std::size_t next_obs_id{1};
};
void detail::GenerationRecord::maybe_enqueue_retire() noexcept
{
if (retire_requested.load(std::memory_order_seq_cst) &&
external_refs.load(std::memory_order_seq_cst) == 0 &&
activity_pins.load(std::memory_order_seq_cst) == 0) {
bool exp = false;
if (retired_enqueued.compare_exchange_strong(
exp, true, std::memory_order_acq_rel)) {
if (auto impl = host_impl.lock()) {
impl->enqueue_retire(shared_from_this());
}
}
}
}
// ── ActivityPin & InterfaceLease & GenerationLease ───────────────────
ActivityPin::~ActivityPin()
{
if (m_rec) {
m_rec->release_activity_pin();
m_rec.reset();
}
}
ActivityPin::ActivityPin(ActivityPin&& other) noexcept
: m_rec(std::move(other.m_rec))
{
}
ActivityPin& ActivityPin::operator=(ActivityPin&& other) noexcept
{
if (this != &other) {
if (m_rec) {
m_rec->release_activity_pin();
}
m_rec = std::move(other.m_rec);
}
return *this;
}
std::uint64_t ActivityPin::generation() const noexcept
{
return m_rec ? m_rec->generation : 0;
}
InterfaceLease::~InterfaceLease()
{
if (m_rec) {
if (m_view.function_table != nullptr &&
m_rec->api.release_interface != nullptr &&
m_rec->mod_handle != nullptr) {
m_rec->api.release_interface(m_rec->mod_handle, &m_id, &m_view);
}
m_rec->release_external_ref();
m_rec.reset();
}
m_view = {};
}
InterfaceLease::InterfaceLease(InterfaceLease&& other) noexcept
: m_rec(std::move(other.m_rec)), m_id(other.m_id),
m_view(other.m_view)
{
other.m_view = {};
}
InterfaceLease& InterfaceLease::operator=(InterfaceLease&& other) noexcept
{
if (this != &other) {
if (m_rec) {
if (m_view.function_table != nullptr &&
m_rec->api.release_interface != nullptr &&
m_rec->mod_handle != nullptr) {
m_rec->api.release_interface(m_rec->mod_handle, &m_id,
&m_view);
}
m_rec->release_external_ref();
}
m_rec = std::move(other.m_rec);
m_id = other.m_id;
m_view = other.m_view;
other.m_view = {};
}
return *this;
}
std::uint64_t InterfaceLease::generation() const noexcept
{
return m_rec ? m_rec->generation : 0;
}
GenerationLease::GenerationLease(
std::shared_ptr<detail::GenerationRecord> rec)
: m_rec(std::move(rec))
{
if (m_rec) {
m_rec->add_external_ref();
}
}
GenerationLease::GenerationLease(const GenerationLease& other)
: m_rec(other.m_rec)
{
if (m_rec) {
m_rec->add_external_ref();
}
}
GenerationLease& GenerationLease::operator=(const GenerationLease& other)
{
if (this != &other) {
if (m_rec) {
m_rec->release_external_ref();
}
m_rec = other.m_rec;
if (m_rec) {
m_rec->add_external_ref();
}
}
return *this;
}
GenerationLease::GenerationLease(GenerationLease&& other) noexcept
: m_rec(std::move(other.m_rec))
{
}
GenerationLease& GenerationLease::operator=(GenerationLease&& other) noexcept
{
if (this != &other) {
if (m_rec) {
m_rec->release_external_ref();
}
m_rec = std::move(other.m_rec);
}
return *this;
}
GenerationLease::~GenerationLease()
{
if (m_rec) {
m_rec->release_external_ref();
m_rec.reset();
}
}
std::uint64_t GenerationLease::generation() const noexcept
{
return m_rec ? m_rec->generation : 0;
}
std::string_view GenerationLease::module_id() const noexcept
{
return m_rec ? std::string_view{m_rec->module_id} : std::string_view{};
}
std::string_view GenerationLease::version() const noexcept
{
return m_rec ? std::string_view{m_rec->version} : std::string_view{};
}
GenerationHealth GenerationLease::health() const noexcept
{
return m_rec ? m_rec->health.load(std::memory_order_acquire)
: GenerationHealth::Retired;
}
ActivityPin GenerationLease::acquire_activity_pin() const
{
if (!m_rec) {
return ActivityPin{};
}
m_rec->add_activity_pin();
return ActivityPin{m_rec};
}
Void::Result::Result<InterfaceLease>
GenerationLease::query_interface(const void_interface_id_v1& id,
std::uint32_t min_major,
std::uint32_t min_table_size) const
{
if (!m_rec || m_rec->mod_handle == nullptr ||
m_rec->api.query_interface == nullptr) {
return Void::Result::fail(make_plugin_error(
PluginErrorCode::abi_mismatch,
"GenerationLease: interface query unsupported"));
}
void_interface_view_v1 view{};
view.struct_size = sizeof(void_interface_view_v1);
const std::int32_t rc = m_rec->api.query_interface(
m_rec->mod_handle, &id, min_major, min_table_size, &view);
if (rc != VOID_STATUS_OK) {
return Void::Result::fail(make_plugin_error(
map_cabi_status(rc, PluginErrorCode::abi_mismatch),
"GenerationLease: query_interface rejected or missing"));
}
if (view.struct_size < sizeof(void_interface_view_v1) ||
view.major != min_major || view.table_size < min_table_size ||
view.function_table == nullptr) {
if (m_rec->api.release_interface != nullptr) {
m_rec->api.release_interface(m_rec->mod_handle, &id, &view);
}
return Void::Result::fail(make_plugin_error(
PluginErrorCode::abi_mismatch,
"GenerationLease: interface table version or size mismatch"));
}
m_rec->add_external_ref();
return InterfaceLease{m_rec, id, view};
}
Void::Result::Result<std::vector<std::uint8_t>>
GenerationLease::run_async(std::uint32_t op_kind,
const std::vector<std::uint8_t>& payload,
Void::Async::OperationOptions options) const
{
if (!m_rec || m_rec->mod_handle == nullptr ||
m_rec->api.submit_async == nullptr) {
return Void::Result::fail(make_plugin_error(
PluginErrorCode::abi_mismatch,
"GenerationLease: async operations unsupported"));
}
auto impl = m_rec->host_impl.lock();
const std::size_t cap =
impl ? impl->limits.max_async_activities : 1024;
if (m_rec->active_async_ops.fetch_add(1, std::memory_order_acq_rel) >=
cap) {
m_rec->active_async_ops.fetch_sub(1, std::memory_order_acq_rel);
return Void::Result::fail(make_plugin_error(
PluginErrorCode::budget_exceeded,
"GenerationLease: async activity limit exceeded"));
}
struct AsyncState {
std::shared_ptr<detail::GenerationRecord> rec;
std::mutex mu{};
std::condition_variable cv{};
bool done{false};
std::int32_t status{VOID_STATUS_INTERNAL};
std::vector<std::uint8_t> result{};
};
auto st = std::make_shared<AsyncState>();
st->rec = m_rec;
m_rec->add_activity_pin();
auto release_guards = [&]() {
m_rec->active_async_ops.fetch_sub(1, std::memory_order_acq_rel);
m_rec->release_activity_pin();
};
const void_bytes_v1 in_bytes{
.data = payload.empty() ? nullptr : payload.data(),
.size = static_cast<std::uint64_t>(payload.size())};
void_op_options_v1 cabi_opts{};
cabi_opts.struct_size = sizeof(void_op_options_v1);
cabi_opts.deadline_ns =
options.deadline.has_value()
? static_cast<std::uint64_t>(std::max<std::int64_t>(
0, options.deadline->time_since_epoch().count()))
: 0;
cabi_opts.stop_requested = options.stop.stop_requested() ? 1 : 0;
auto* raw_state = new std::shared_ptr<AsyncState>(st);
auto cb = [](void* ctx, std::int32_t status,
const void_bytes_v1* result_bytes) {
auto* holder =
static_cast<std::shared_ptr<AsyncState>*>(ctx);
auto s = *holder;
delete holder;
{
std::lock_guard lk{s->mu};
s->status = status;
if (result_bytes != nullptr && result_bytes->data != nullptr &&
result_bytes->size > 0 &&
result_bytes->size <= 64 * 1024 * 1024) {
const auto sz =
static_cast<std::size_t>(result_bytes->size);
s->result.assign(result_bytes->data,
result_bytes->data + sz);
}
s->done = true;
}
s->cv.notify_all();
};
void_operation_handle* op_handle = nullptr;
void_error_detail_v1 err{};
err.struct_size = sizeof(void_error_detail_v1);
const std::int32_t rc = m_rec->api.submit_async(
m_rec->mod_handle, op_kind, in_bytes, &cabi_opts, cb, raw_state,
&op_handle, &err);
std::string emsg = consume_error_detail(err);
if (rc != VOID_STATUS_OK || op_handle == nullptr) {
delete raw_state;
release_guards();
return Void::Result::fail(make_plugin_error(
map_cabi_status(rc, PluginErrorCode::internal),
emsg.empty() ? "GenerationLease: submit_async failed" : emsg));
}
{
struct Canceller {
detail::GenerationRecord* rec;
void_operation_handle* op;
void operator()() const noexcept
{
if (rec->api.cancel_async != nullptr) {
(void)rec->api.cancel_async(rec->mod_handle, op);
}
}
};
std::optional<std::stop_callback<Canceller>> stop_cb;
if (options.stop.stop_possible()) {
stop_cb.emplace(options.stop,
Canceller{m_rec.get(), op_handle});
}
std::unique_lock lk{st->mu};
st->cv.wait(lk, [&] { return st->done; });
}
if (m_rec->api.release_async != nullptr) {
m_rec->api.release_async(m_rec->mod_handle, op_handle);
}
release_guards();
if (st->status != VOID_STATUS_OK) {
return Void::Result::fail(make_plugin_error(
map_cabi_status(st->status, PluginErrorCode::internal),
"GenerationLease: async operation failed"));
}
return st->result;
}
// ── CModuleHost ──────────────────────────────────────────────────────
CModuleHost::CModuleHost(PluginHostLimits limits,
const Void::Time::MonotonicClock& clock)
: m_impl(std::make_shared<Impl>(limits, clock))
{
}
CModuleHost::~CModuleHost()
{
if (m_impl) {
m_impl->shutdown();
}
}
void CModuleHost::close_and_join()
{
if (m_impl) {
m_impl->shutdown();
}
}
std::size_t
CModuleHost::add_observer(std::function<void(const ReloadEvent&)> cb)
{
std::lock_guard lk{m_impl->obs_mu};
const std::size_t id = m_impl->next_obs_id++;
m_impl->observers.emplace_back(id, std::move(cb));
return id;
}
void CModuleHost::remove_observer(std::size_t id)
{
std::lock_guard lk{m_impl->obs_mu};
std::erase_if(m_impl->observers,
[id](const auto& pair) { return pair.first == id; });
}
Void::Result::Result<std::string>
CModuleHost::load(const std::filesystem::path& path,
std::string_view config,
Void::Async::OperationOptions options)
{
{
std::lock_guard lk{m_impl->map_mu};
if (m_impl->closing) {
return Void::Result::fail(make_plugin_error(
PluginErrorCode::conflict,
"CModuleHost: host is closing"));
}
if (m_impl->modules.size() >= m_impl->limits.max_modules) {
return Void::Result::fail(make_plugin_error(
PluginErrorCode::budget_exceeded,
"CModuleHost: max_modules limit reached"));
}
}
const std::uint64_t gen =
m_impl->next_gen.fetch_add(1, std::memory_order_relaxed);
auto cand_res = m_impl->open_candidate(path, gen);
if (!cand_res) {
return Void::Result::fail(std::move(cand_res).error());
}
auto cand = std::move(*cand_res);
const auto now = m_impl->clock->now();
auto total_dl = now + m_impl->limits.total_reload_timeout;
if (options.deadline.has_value() && *options.deadline < total_dl) {
total_dl = *options.deadline;
}
if (auto ar = m_impl->activate_and_verify(*cand, config, total_dl,
options);
!ar) {
m_impl->dispose_uncommitted(cand);
return Void::Result::fail(std::move(ar).error());
}
std::shared_ptr<Impl::ModuleSlot> slot;
std::string mod_id = cand->module_id;
{
std::lock_guard lk{m_impl->map_mu};
if (m_impl->closing) {
m_impl->dispose_uncommitted(cand);
return Void::Result::fail(make_plugin_error(
PluginErrorCode::conflict, "CModuleHost: host closing"));
}
if (m_impl->modules.contains(mod_id)) {
m_impl->dispose_uncommitted(cand);
return Void::Result::fail(make_plugin_error(
PluginErrorCode::conflict,
"CModuleHost: module already loaded: " + mod_id));
}
slot = std::make_shared<Impl::ModuleSlot>();
cand->add_external_ref();
slot->current = cand;
slot->retained.push_back(cand);
m_impl->modules.emplace(mod_id, slot);
}
m_impl->notify_observers(ReloadEvent{
.module_id = mod_id, .generation = gen, .rollback = false,
.detail = "loaded"});
return mod_id;
}
Void::Result::Result<std::vector<std::string>>
CModuleHost::load_batch(const std::vector<BatchModuleSpec>& specs,
Void::Async::OperationOptions options)
{
if (specs.empty()) {
return std::vector<std::string>{};
}
{
std::lock_guard lk{m_impl->map_mu};
if (m_impl->closing) {
return Void::Result::fail(make_plugin_error(
PluginErrorCode::conflict, "CModuleHost: host closing"));
}
if (m_impl->modules.size() + specs.size() >
m_impl->limits.max_modules) {
return Void::Result::fail(make_plugin_error(
PluginErrorCode::budget_exceeded,
"CModuleHost: batch exceeds max_modules limit"));
}
}
struct Opened {
std::shared_ptr<detail::GenerationRecord> rec;
std::string config;
std::size_t seq;
};
std::vector<Opened> opened;
opened.reserve(specs.size());
std::unordered_map<std::string, std::size_t> by_id;
auto dispose_all = [&](std::size_t active_prefix) {
for (std::size_t i = active_prefix; i > 0; --i) {
m_impl->dispose_uncommitted(opened[i - 1].rec);
}
for (std::size_t i = active_prefix; i < opened.size(); ++i) {
m_impl->dispose_uncommitted(opened[i].rec);
}
};
for (std::size_t i = 0; i < specs.size(); ++i) {
const std::uint64_t gen =
m_impl->next_gen.fetch_add(1, std::memory_order_relaxed);
auto cr = m_impl->open_candidate(specs[i].path, gen);
if (!cr) {
dispose_all(0);
return Void::Result::fail(std::move(cr).error());
}
auto rec = std::move(*cr);
if (!by_id.emplace(rec->module_id, i).second) {
m_impl->dispose_uncommitted(rec);
dispose_all(0);
return Void::Result::fail(make_plugin_error(
PluginErrorCode::conflict,
"CModuleHost::load_batch: duplicate module_id '" +
rec->module_id + "'"));
}
opened.push_back(Opened{std::move(rec), specs[i].config, i});
}
// Topological dependency check and policy consistency.
const std::size_t n = opened.size();
std::vector<std::vector<std::size_t>> adj(n);
std::vector<std::size_t> indeg(n, 0);
for (std::size_t i = 0; i < n; ++i) {
for (const auto& dep : opened[i].rec->dependencies) {
auto it = by_id.find(dep.module_id);
if (it == by_id.end()) {
// Check already-loaded modules.
bool present_active = false;
{
std::lock_guard lk{m_impl->map_mu};
auto mit = m_impl->modules.find(dep.module_id);
if (mit != m_impl->modules.end() &&
mit->second->current) {
if (auto ver = Semver::parse(
mit->second->current->version)) {
if (auto rng = Semver::VersionRange::parse(
dep.version_range);
rng && rng->contains(*ver)) {
present_active = true;
}
}
}
}
if (!dep.optional_dep && !present_active) {
dispose_all(0);
return Void::Result::fail(make_plugin_error(
PluginErrorCode::missing_dependency,
"CModuleHost::load_batch: missing required dependency '" +
dep.module_id + "'"));
}
continue;
}
const std::size_t d = it->second;
if (d == i) {
dispose_all(0);
return Void::Result::fail(make_plugin_error(
PluginErrorCode::cycle_detected,
"CModuleHost::load_batch: self dependency cycle"));
}
const auto ver =
Semver::parse(opened[d].rec->version);
const auto rng =
Semver::VersionRange::parse(dep.version_range);
if (!ver || !rng || !rng->contains(*ver)) {
dispose_all(0);
return Void::Result::fail(make_plugin_error(
PluginErrorCode::missing_dependency,
"CModuleHost::load_batch: incompatible dependency version for '" +
dep.module_id + "'"));
}
adj[d].push_back(i);
++indeg[i];
}
}
std::priority_queue<std::size_t, std::vector<std::size_t>,
std::greater<std::size_t>>
ready;
for (std::size_t i = 0; i < n; ++i) {
if (indeg[i] == 0) ready.push(i);
}
std::vector<Opened> order;
order.reserve(n);
while (!ready.empty()) {
const std::size_t u = ready.top();
ready.pop();
order.push_back(std::move(opened[u]));
for (const std::size_t v : adj[u]) {
if (--indeg[v] == 0) ready.push(v);
}
}
if (order.size() != n) {
for (auto& o : opened) m_impl->dispose_uncommitted(o.rec);
for (auto& o : order) m_impl->dispose_uncommitted(o.rec);
return Void::Result::fail(make_plugin_error(
PluginErrorCode::cycle_detected,
"CModuleHost::load_batch: dependency cycle detected"));
}
const auto now = m_impl->clock->now();
auto total_dl = now + m_impl->limits.total_reload_timeout;
if (options.deadline.has_value() && *options.deadline < total_dl) {
total_dl = *options.deadline;
}
std::vector<std::size_t> activated_idx;
for (std::size_t i = 0; i < n; ++i) {
if (auto ar = m_impl->activate_and_verify(
*order[i].rec, order[i].config, total_dl, options);
!ar) {
for (auto it = activated_idx.rbegin();
it != activated_idx.rend(); ++it) {
m_impl->dispose_uncommitted(order[*it].rec);
}
for (std::size_t k = i; k < n; ++k) {
m_impl->dispose_uncommitted(order[k].rec);
}
return Void::Result::fail(std::move(ar).error());
}
activated_idx.push_back(i);
}
std::vector<std::string> ids;
ids.reserve(n);
{
std::lock_guard lk{m_impl->map_mu};
for (auto& o : order) {
if (m_impl->modules.contains(o.rec->module_id)) {
for (const auto idx : activated_idx) {
m_impl->dispose_uncommitted(order[idx].rec);
}
return Void::Result::fail(make_plugin_error(
PluginErrorCode::conflict,
"CModuleHost::load_batch: conflict with loaded module"));
}
}
for (auto& o : order) {
auto slot = std::make_shared<Impl::ModuleSlot>();
o.rec->add_external_ref();
slot->current = o.rec;
slot->retained.push_back(o.rec);
ids.push_back(o.rec->module_id);
m_impl->modules.emplace(o.rec->module_id, std::move(slot));
}
}
return ids;
}
Void::Result::Result<std::uint64_t> CModuleHost::replace(
std::string_view module_id, const std::filesystem::path& new_path,
std::string_view config,
std::optional<std::uint64_t> expected_generation,
Void::Async::OperationOptions options,
std::function<Void::Result::Result<void>(const GenerationLease&)>
on_publish_locked)
{
std::shared_ptr<Impl::ModuleSlot> slot;
{
std::lock_guard lk{m_impl->map_mu};
if (m_impl->closing) {
return Void::Result::fail(make_plugin_error(
PluginErrorCode::conflict, "CModuleHost: host is closing"));
}
auto it = m_impl->modules.find(std::string{module_id});
if (it == m_impl->modules.end()) {
return Void::Result::fail(make_plugin_error(
PluginErrorCode::not_found,
"CModuleHost: unknown module: " + std::string{module_id}));
}
slot = it->second;
}
std::lock_guard reload_lk{slot->reload_mu};
std::shared_ptr<detail::GenerationRecord> old_rec;
std::size_t active_retained_count = 0;
std::size_t total_mapped = 0;
{
std::lock_guard lk{m_impl->map_mu};
if (m_impl->closing) {
return Void::Result::fail(make_plugin_error(
PluginErrorCode::conflict, "CModuleHost: host is closing"));
}
old_rec = slot->current;
std::erase_if(slot->retained, [](const auto& r) {
return !r || (r->destroyed.load(std::memory_order_acquire) &&
r->dlclosed.load(std::memory_order_acquire));
});
for (const auto& r : slot->retained) {
if (!r->destroyed.load(std::memory_order_acquire)) {
++active_retained_count;
}
if (!r->dlclosed.load(std::memory_order_acquire)) {
total_mapped += static_cast<std::size_t>(r->image_bytes);
}
}
}
if (!old_rec) {
return Void::Result::fail(make_plugin_error(
PluginErrorCode::not_found, "CModuleHost: module unloaded"));
}
if (expected_generation.has_value() &&
old_rec->generation != *expected_generation) {
return Void::Result::fail(make_plugin_error(
PluginErrorCode::conflict,
"CModuleHost: expected generation conflict"));
}
if (old_rec->activation_policy == VOID_POLICY_RESTART_REQUIRED ||
old_rec->activation_policy == VOID_POLICY_INSTALLER_REQUIRED) {
return Void::Result::fail(make_plugin_error(
PluginErrorCode::restart_required,
"CModuleHost: active module requires restart for upgrade"));
}
if (m_impl->limits.max_retained_generations > 0 &&
active_retained_count >=
m_impl->limits.max_retained_generations) {
return Void::Result::fail(make_plugin_error(
PluginErrorCode::retention_limit,
"CModuleHost: max_retained_generations limit reached"));
}
const std::uint64_t new_gen =
m_impl->next_gen.fetch_add(1, std::memory_order_relaxed);
auto cand_res = m_impl->open_candidate(new_path, new_gen);
if (!cand_res) {
return Void::Result::fail(std::move(cand_res).error());
}
auto cand = std::move(*cand_res);
if (cand->module_id != module_id) {
m_impl->dispose_uncommitted(cand);
return Void::Result::fail(make_plugin_error(
PluginErrorCode::conflict,
"CModuleHost: replacement module_id mismatch"));
}
if (cand->activation_policy == VOID_POLICY_RESTART_REQUIRED ||
cand->activation_policy == VOID_POLICY_INSTALLER_REQUIRED) {
m_impl->dispose_uncommitted(cand);
return Void::Result::fail(make_plugin_error(
PluginErrorCode::restart_required,
"CModuleHost: candidate module requires restart"));
}
if (total_mapped + cand->image_bytes >
m_impl->limits.max_mapped_bytes_per_module) {
m_impl->dispose_uncommitted(cand);
return Void::Result::fail(make_plugin_error(
PluginErrorCode::budget_exceeded,
"CModuleHost: mapped image byte budget exceeded"));
}
const auto now = m_impl->clock->now();
auto total_dl = now + m_impl->limits.total_reload_timeout;
if (options.deadline.has_value() && *options.deadline < total_dl) {
total_dl = *options.deadline;
}
bool old_quiesced = false;
auto rollback_and_resume_old =
[&](Void::Result::Error primary) -> Void::Result::Result<std::uint64_t> {
m_impl->dispose_uncommitted(cand);
if (old_quiesced && old_rec->api.resume != nullptr &&
old_rec->mod_handle != nullptr) {
void_error_detail_v1 res_err{};
res_err.struct_size = sizeof(void_error_detail_v1);
const std::int32_t rrc =
old_rec->api.resume(old_rec->mod_handle, &res_err);
const std::string rmsg = consume_error_detail(res_err);
if (rrc != VOID_STATUS_OK) {
old_rec->health.store(GenerationHealth::Degraded,
std::memory_order_release);
m_impl->notify_observers(ReloadEvent{
.module_id = std::string{module_id},
.generation = old_rec->generation,
.rollback = true,
.detail = "degraded after resume failure: " + rmsg});
return Void::Result::fail(make_plugin_error(
PluginErrorCode::resume_degraded,
primary.message() + "; old resume failed: " + rmsg));
}
old_rec->health.store(GenerationHealth::Healthy,
std::memory_order_release);
}
m_impl->notify_observers(ReloadEvent{
.module_id = std::string{module_id},
.generation = old_rec->generation,
.rollback = true,
.detail = primary.message()});
return Void::Result::fail(std::move(primary));
};
const bool stateful =
((old_rec->api.capabilities & VOID_CAP_STATEFUL_CHECKPOINT) != 0) &&
((cand->api.capabilities & VOID_CAP_STATEFUL_CHECKPOINT) != 0);
if (stateful) {
old_rec->health.store(GenerationHealth::Quiescing,
std::memory_order_release);
const auto q_dl =
std::min(total_dl, m_impl->clock->now() +
m_impl->limits.quiesce_timeout);
const auto q_opts =
m_impl->make_op_opts(q_dl, options.stop.stop_requested());
void_error_detail_v1 qerr{};
qerr.struct_size = sizeof(void_error_detail_v1);
const std::int32_t qrc =
old_rec->api.quiesce(old_rec->mod_handle, &q_opts, &qerr);
const std::string qmsg = consume_error_detail(qerr);
old_quiesced = true;
if (qrc != VOID_STATUS_OK) {
return rollback_and_resume_old(make_plugin_error(
map_cabi_status(qrc, PluginErrorCode::quiesce_failed),
qmsg.empty() ? "CModuleHost: quiesce failed" : qmsg));
}
void_owned_bytes_v1 ckpt{};
void_error_detail_v1 cerr{};
cerr.struct_size = sizeof(void_error_detail_v1);
const std::int32_t crc = old_rec->api.checkpoint(
old_rec->mod_handle, &q_opts, &ckpt, &cerr);
const std::string cmsg = consume_error_detail(cerr);
std::vector<std::uint8_t> ckpt_copy;
bool size_ok = true;
if (crc == VOID_STATUS_OK) {
if (ckpt.size > m_impl->limits.max_checkpoint_bytes ||
(ckpt.size > 0 && ckpt.data == nullptr)) {
size_ok = false;
} else if (ckpt.size > 0) {
const auto sz = static_cast<std::size_t>(ckpt.size);
ckpt_copy.assign(ckpt.data, ckpt.data + sz);
}
}
if (ckpt.release != nullptr && ckpt.data != nullptr) {
ckpt.release(ckpt.release_ctx, ckpt.data, ckpt.size);
}
if (crc != VOID_STATUS_OK) {
return rollback_and_resume_old(make_plugin_error(
map_cabi_status(crc, PluginErrorCode::checkpoint_failed),
cmsg.empty() ? "CModuleHost: checkpoint failed" : cmsg));
}
if (!size_ok) {
return rollback_and_resume_old(make_plugin_error(
PluginErrorCode::budget_exceeded,
"CModuleHost: checkpoint exceeded max_checkpoint_bytes or invalid buffer"));
}
const void_bytes_v1 r_bytes{
.data = ckpt_copy.empty() ? nullptr : ckpt_copy.data(),
.size = static_cast<std::uint64_t>(ckpt_copy.size())};
void_error_detail_v1 rerr{};
rerr.struct_size = sizeof(void_error_detail_v1);
const std::int32_t rrc =
cand->api.restore(cand->mod_handle, r_bytes, &rerr);
const std::string rmsg = consume_error_detail(rerr);
if (rrc != VOID_STATUS_OK) {
return rollback_and_resume_old(make_plugin_error(
map_cabi_status(rrc, PluginErrorCode::restore_failed),
rmsg.empty() ? "CModuleHost: restore failed" : rmsg));
}
}
if (auto ar = m_impl->activate_and_verify(*cand, config, total_dl,
options);
!ar) {
return rollback_and_resume_old(std::move(ar).error());
}
if (on_publish_locked) {
GenerationLease cand_lease{cand};
if (auto phr = on_publish_locked(cand_lease); !phr) {
return rollback_and_resume_old(std::move(phr).error());
}
}
std::shared_ptr<detail::GenerationRecord> retired_old;
bool swap_conflict = false;
{
std::lock_guard lk{m_impl->map_mu};
if (m_impl->closing || slot->current != old_rec) {
swap_conflict = true;
} else {
cand->add_external_ref();
retired_old = std::exchange(slot->current, cand);
slot->retained.push_back(cand);
}
}
if (swap_conflict) {
return rollback_and_resume_old(make_plugin_error(
PluginErrorCode::conflict,
"CModuleHost: concurrent generation swap conflict"));
}
if (retired_old) {
retired_old->health.store(GenerationHealth::Retiring,
std::memory_order_release);
retired_old->retire_requested.store(true,
std::memory_order_seq_cst);
retired_old->release_external_ref();
}
m_impl->notify_observers(ReloadEvent{
.module_id = std::string{module_id},
.generation = new_gen,
.rollback = false,
.detail = "replaced"});
return new_gen;
}
Void::Result::Result<void> CModuleHost::unload(std::string_view module_id)
{
std::shared_ptr<Impl::ModuleSlot> slot;
{
std::lock_guard lk{m_impl->map_mu};
auto it = m_impl->modules.find(std::string{module_id});
if (it == m_impl->modules.end()) {
return Void::Result::fail(make_plugin_error(
PluginErrorCode::not_found,
"CModuleHost: unknown module: " + std::string{module_id}));
}
slot = it->second;
m_impl->modules.erase(it);
}
std::lock_guard reload_lk{slot->reload_mu};
std::shared_ptr<detail::GenerationRecord> old;
{
std::lock_guard lk{m_impl->map_mu};
old = std::exchange(slot->current, nullptr);
}
if (old) {
old->health.store(GenerationHealth::Retiring,
std::memory_order_release);
old->retire_requested.store(true, std::memory_order_seq_cst);
if (old->api.request_stop != nullptr && old->mod_handle != nullptr) {
(void)old->api.request_stop(old->mod_handle);
}
old->release_external_ref();
}
return {};
}
GenerationLease CModuleHost::acquire(std::string_view module_id) const
{
std::shared_ptr<detail::GenerationRecord> rec;
{
std::lock_guard lk{m_impl->map_mu};
if (m_impl->closing) {
return GenerationLease{};
}
auto it = m_impl->modules.find(std::string{module_id});
if (it != m_impl->modules.end() && it->second->current) {
rec = it->second->current;
rec->add_external_ref();
}
}
return rec ? GenerationLease{std::move(rec),
GenerationLease::AlreadyRefCountedTag{}}
: GenerationLease{};
}
std::vector<GenerationSummary>
CModuleHost::retained_generations(std::string_view module_id) const
{
std::lock_guard lk{m_impl->map_mu};
auto it = m_impl->modules.find(std::string{module_id});
if (it == m_impl->modules.end()) {
return {};
}
const auto& slot = it->second;
std::vector<GenerationSummary> out;
for (const auto& r : slot->retained) {
if (!r) continue;
if (r->destroyed.load(std::memory_order_acquire) &&
r->dlclosed.load(std::memory_order_acquire)) {
continue;
}
out.push_back(GenerationSummary{
.generation = r->generation,
.module_id = r->module_id,
.version = r->version,
.image_bytes = r->image_bytes,
.external_refs =
r->external_refs.load(std::memory_order_acquire),
.activity_pins =
r->activity_pins.load(std::memory_order_acquire),
.health = r->health.load(std::memory_order_acquire),
.dlclosed = r->dlclosed.load(std::memory_order_acquire)});
}
return out;
}
std::size_t CModuleHost::mapped_bytes(std::string_view module_id) const
{
std::size_t sum = 0;
for (const auto& g : retained_generations(module_id)) {
if (!g.dlclosed) {
sum += static_cast<std::size_t>(g.image_bytes);
}
}
return sum;
}
} // namespace Void::Plugin