feat/plugin-system #2
No files matched your search
@@ -180,7 +180,7 @@ Other key points:
|
|||||||
`Void::Service` — dependency inversion + FSM orchestration.
|
`Void::Service` — dependency inversion + FSM orchestration.
|
||||||
|
|
||||||
- `IService` base (`service_name()`, `on_start()`/`on_stop()` lifecycle).
|
- `IService` base (`service_name()`, `on_start()`/`on_stop()` lifecycle).
|
||||||
- `ServiceRegistry` — type-keyed: `provide<I>(impl)`, `get<I>()` (nullptr if absent), `require<I>()` (throws), `has<I>()`, `start_all()`/`stop_all()`. Consumers depend only on interface `I` and resolve at runtime; a concrete deriving `IService` is recovered for lifecycle via `dynamic_cast` even when registered under a plain interface. `shared_mutex`, reads are the hot path.
|
- `ServiceRegistry` — type-keyed: `provide<I>(impl)`, `get<I>()` (nullptr if absent), `require<I>()` (throws), `has<I>()`, `remove<I>()` (withdraws the local entry; holders keep the instance alive, a parent's entry is re-exposed), `start_all()`/`stop_all()`. Consumers depend only on interface `I` and resolve at runtime; a concrete deriving `IService` is recovered for lifecycle via `dynamic_cast` even when registered under a plain interface. `shared_mutex`, reads are the hot path.
|
||||||
- `Fsm::Orchestrator` (in the Fsm module): owns a `ServiceRegistry`, `launch<F>(args...)` constructs an FSM, injects the registry (`set_services`), starts and supervises it via a `FsmHandle` (status/stop); `stop_all()` is balanced once against `start_services()`.
|
- `Fsm::Orchestrator` (in the Fsm module): owns a `ServiceRegistry`, `launch<F>(args...)` constructs an FSM, injects the registry (`set_services`), starts and supervises it via a `FsmHandle` (status/stop); `stop_all()` is balanced once against `start_services()`.
|
||||||
- `Service/PluginService.hpp`: `PluginServiceBinding<I>` binds a plugin-provided service into a registry and re-binds on hot reload. The interface `I` must derive `IService` (single inheritance) so the host recovers it from the plugin's exported `IService*` by `static_cast` — no `dynamic_cast` across the RTLD_LOCAL boundary. The registry entry pins the plugin instance.
|
- `Service/PluginService.hpp`: `PluginServiceBinding<I>` binds a plugin-provided service into a registry and re-binds on hot reload. The interface `I` must derive `IService` (single inheritance) so the host recovers it from the plugin's exported `IService*` by `static_cast` — no `dynamic_cast` across the RTLD_LOCAL boundary. The registry entry pins the plugin instance.
|
||||||
|
|
||||||
@@ -218,9 +218,9 @@ Header layout (include `<Void/Fsm/Fsm.hpp>` — a thin umbrella): `Machine.hpp`
|
|||||||
|
|
||||||
`Void::Plugin` loads C-ABI plugins (`.so`) and hot-reloads them with state transfer:
|
`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`.
|
- **C ABI** (`Plugin.hpp`): required `void_plugin_create/destroy/info`; optional `void_plugin_transfer_state(old,new)` (raw), `void_plugin_configure(inst, config)` (host-supplied config string, called after create and after each reload swap, before `on_load()`), 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.
|
- **`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<shared_ptr>` 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.
|
- **`PluginManager`** — multi-plugin registry with **RCU-style pinned handles**: `acquire(name)` returns a `PluginHandle` (one `atomic<shared_ptr>` 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`. Discovery: `load_directory(dir)` loads every shared-library file in a directory (filename order, per-file `expected` results). `unload(name)` drops the registry entry (instance dies with its last handle). `on_reloaded(cb)` is **multi-observer** — it returns a `ReloadCallbackId` for `remove_on_reloaded` and fires after every successful reload, manual or watched. `PluginManagerOptions::config_provider` feeds `void_plugin_configure`. Host-side state carry: `serialize_state(name)` → `StateSnapshot{json, version}` and `deserialize_state(name, json, from_version)` wrap the plugin's v2 exports so an embedder can persist plugin state across its *own* hot reload.
|
||||||
- **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).
|
- **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
|
## Code style
|
||||||
|
|||||||
+9
-7
@@ -23,13 +23,15 @@ function(void_add_module MODULE_NAME)
|
|||||||
add_library(${TGT} INTERFACE)
|
add_library(${TGT} INTERFACE)
|
||||||
target_compile_features(${TGT} INTERFACE cxx_std_26)
|
target_compile_features(${TGT} INTERFACE cxx_std_26)
|
||||||
else()
|
else()
|
||||||
set(LIB_TYPE "SHARED")
|
set(SCOPE "PUBLIC")
|
||||||
set(SCOPE "PUBLIC")
|
if (MODULE_NAME STREQUAL "Testing")
|
||||||
if (MODULE_NAME STREQUAL "Testing")
|
add_library(${TGT} STATIC)
|
||||||
add_library(${TGT} STATIC)
|
else()
|
||||||
else()
|
# Honour the standard BUILD_SHARED_LIBS policy. Consumers that ship a
|
||||||
add_library(${TGT} SHARED)
|
# single validated executable must be able to embed Void modules,
|
||||||
endif()
|
# while Void's standalone default remains shared.
|
||||||
|
add_library(${TGT})
|
||||||
|
endif()
|
||||||
target_sources(${TGT} PRIVATE ${SRC})
|
target_sources(${TGT} PRIVATE ${SRC})
|
||||||
target_compile_features(${TGT} PUBLIC cxx_std_26)
|
target_compile_features(${TGT} PUBLIC cxx_std_26)
|
||||||
endif()
|
endif()
|
||||||
|
|||||||
@@ -79,6 +79,76 @@ namespace Void::EventBus
|
|||||||
return id;
|
return id;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Move-only RAII handle for a subscription: unsubscribes on
|
||||||
|
// destruction (or reset()). Must not outlive the bus it came
|
||||||
|
// from — the bus is non-movable, so tie the Subscription's
|
||||||
|
// lifetime to a scope the bus outlives.
|
||||||
|
class Subscription
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
|
||||||
|
Subscription() = default;
|
||||||
|
|
||||||
|
Subscription(Subscription&& other) noexcept
|
||||||
|
: bus_(other.bus_), id_(other.id_)
|
||||||
|
{
|
||||||
|
other.bus_ = nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
Subscription& operator=(Subscription&& other) noexcept
|
||||||
|
{
|
||||||
|
if (this != &other) {
|
||||||
|
reset();
|
||||||
|
bus_ = other.bus_;
|
||||||
|
id_ = other.id_;
|
||||||
|
other.bus_ = nullptr;
|
||||||
|
}
|
||||||
|
return *this;
|
||||||
|
}
|
||||||
|
|
||||||
|
Subscription(const Subscription&) = delete;
|
||||||
|
Subscription& operator=(const Subscription&) = delete;
|
||||||
|
|
||||||
|
~Subscription() { reset(); }
|
||||||
|
|
||||||
|
// Unsubscribe now; safe to call repeatedly.
|
||||||
|
void reset()
|
||||||
|
{
|
||||||
|
if (bus_ != nullptr) {
|
||||||
|
bus_->unsubscribe(id_);
|
||||||
|
bus_ = nullptr;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] explicit operator bool() const noexcept
|
||||||
|
{
|
||||||
|
return bus_ != nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
friend class EventBus;
|
||||||
|
|
||||||
|
Subscription(EventBus* bus, HandlerId id)
|
||||||
|
: bus_(bus), id_(id)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
EventBus* bus_ = nullptr;
|
||||||
|
HandlerId id_ = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Subscribe with automatic unsubscription: the returned handle
|
||||||
|
// removes the handler when it goes out of scope. Suits handlers
|
||||||
|
// owned by components (plugins, services) whose lifetime is
|
||||||
|
// shorter than the bus.
|
||||||
|
template <typename Event>
|
||||||
|
[[nodiscard]] Subscription
|
||||||
|
subscribe_scoped(std::function<void(const Event&)> handler)
|
||||||
|
{
|
||||||
|
return Subscription{this, subscribe<Event>(std::move(handler))};
|
||||||
|
}
|
||||||
|
|
||||||
// Publish an event to all subscribers of its type.
|
// Publish an event to all subscribers of its type.
|
||||||
template <typename Event> void publish(const Event& event)
|
template <typename Event> void publish(const Event& event)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ enum class LoadError {
|
|||||||
CreateFailed,
|
CreateFailed,
|
||||||
NotSupported, // platform does not support dlopen
|
NotSupported, // platform does not support dlopen
|
||||||
StateRejected, // new instance refused the serialized state
|
StateRejected, // new instance refused the serialized state
|
||||||
|
ActivationFailed, // on_load threw or readiness validation failed
|
||||||
UnknownPlugin, // PluginManager: no plugin registered under that name
|
UnknownPlugin, // PluginManager: no plugin registered under that name
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -72,6 +73,7 @@ private:
|
|||||||
IPlugin* plugin_ {};
|
IPlugin* plugin_ {};
|
||||||
destroy_fn destroy_ {};
|
destroy_fn destroy_ {};
|
||||||
transfer_fn transfer_ {};
|
transfer_fn transfer_ {};
|
||||||
|
ready_fn ready_ {};
|
||||||
state_version_fn state_version_{};
|
state_version_fn state_version_{};
|
||||||
serialize_fn serialize_ {};
|
serialize_fn serialize_ {};
|
||||||
free_string_fn free_string_ {};
|
free_string_fn free_string_ {};
|
||||||
|
|||||||
@@ -5,14 +5,17 @@
|
|||||||
|
|
||||||
#include <atomic>
|
#include <atomic>
|
||||||
#include <chrono>
|
#include <chrono>
|
||||||
|
#include <cstdint>
|
||||||
#include <expected>
|
#include <expected>
|
||||||
#include <filesystem>
|
#include <filesystem>
|
||||||
#include <functional>
|
#include <functional>
|
||||||
#include <memory>
|
#include <memory>
|
||||||
#include <mutex>
|
#include <mutex>
|
||||||
|
#include <optional>
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <string_view>
|
#include <string_view>
|
||||||
#include <unordered_map>
|
#include <unordered_map>
|
||||||
|
#include <utility>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
namespace Void::Plugin
|
namespace Void::Plugin
|
||||||
@@ -71,8 +74,23 @@ namespace Void::Plugin
|
|||||||
// executing would crash. Pins already prevent the instance from
|
// executing would crash. Pins already prevent the instance from
|
||||||
// being destroyed; this guards the code pages.
|
// being destroyed; this guards the code pages.
|
||||||
bool dlclose_on_swap = false;
|
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;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Identifies an on_reloaded observer for remove_on_reloaded.
|
||||||
|
using ReloadCallbackId = std::size_t;
|
||||||
|
|
||||||
class PluginManager
|
class PluginManager
|
||||||
{
|
{
|
||||||
public:
|
public:
|
||||||
@@ -92,6 +110,22 @@ namespace Void::Plugin
|
|||||||
std::expected<std::string, LoadError>
|
std::expected<std::string, LoadError>
|
||||||
load(const std::filesystem::path& path);
|
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
|
/// Pin the current instance for `name`. The returned handle
|
||||||
/// keeps it alive for as long as it lives. Empty handle if no
|
/// keeps it alive for as long as it lives. Empty handle if no
|
||||||
/// such plugin. One atomic load on the hot path.
|
/// such plugin. One atomic load on the hot path.
|
||||||
@@ -109,9 +143,36 @@ namespace Void::Plugin
|
|||||||
void watch(std::string_view name);
|
void watch(std::string_view name);
|
||||||
void unwatch(std::string_view name);
|
void unwatch(std::string_view name);
|
||||||
|
|
||||||
/// Invoked after every successful reload (manual or watched),
|
/// Register an observer invoked after every successful reload
|
||||||
/// on the caller's / watcher's thread.
|
/// (manual or watched), on the reloading thread. Multiple
|
||||||
void on_reloaded(std::function<void(std::string_view name)> cb);
|
/// 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;
|
[[nodiscard]] std::vector<std::string> names() const;
|
||||||
|
|
||||||
@@ -132,11 +193,16 @@ namespace Void::Plugin
|
|||||||
Entry* find(std::string_view name) const;
|
Entry* find(std::string_view name) const;
|
||||||
std::expected<void, LoadError> reload_locked(Entry& entry,
|
std::expected<void, LoadError> reload_locked(Entry& entry,
|
||||||
std::string_view name);
|
std::string_view name);
|
||||||
|
std::vector<std::function<void(std::string_view)>>
|
||||||
|
reload_callbacks_locked() const;
|
||||||
|
|
||||||
Options m_options;
|
Options m_options;
|
||||||
mutable std::mutex m_mutex; // guards the registry map + reloads
|
mutable std::mutex m_mutex; // guards the registry map + reloads
|
||||||
std::unordered_map<std::string, std::unique_ptr<Entry>> m_plugins;
|
std::unordered_map<std::string, std::unique_ptr<Entry>> m_plugins;
|
||||||
std::function<void(std::string_view)> m_on_reloaded;
|
std::vector<std::pair<ReloadCallbackId,
|
||||||
|
std::function<void(std::string_view)>>>
|
||||||
|
m_on_reloaded;
|
||||||
|
ReloadCallbackId m_next_reload_id{1};
|
||||||
FileSystem::FileWatcher m_watcher;
|
FileSystem::FileWatcher m_watcher;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -49,6 +49,18 @@ public:
|
|||||||
// Optional (enables hot-reload state transfer):
|
// Optional (enables hot-reload state transfer):
|
||||||
// void void_plugin_transfer_state(void* old, void* new)
|
// void void_plugin_transfer_state(void* old, void* new)
|
||||||
//
|
//
|
||||||
|
// Optional (enables host-supplied configuration):
|
||||||
|
// void void_plugin_configure(void* instance, const char* config)
|
||||||
|
// — called by the host with an opaque configuration string (typically
|
||||||
|
// JSON) after create and after each hot-reload swap, before
|
||||||
|
// on_load(). The string is only valid for the duration of the call.
|
||||||
|
//
|
||||||
|
// Optional (transactional activation check):
|
||||||
|
// int void_plugin_ready(void* instance)
|
||||||
|
// — called after on_load() and state restoration, immediately before
|
||||||
|
// the instance becomes visible. Return 0 when the plugin is ready.
|
||||||
|
// Any other value aborts load/reload and keeps the old instance.
|
||||||
|
//
|
||||||
// Optional v2 state protocol (preferred over transfer_state when both
|
// Optional v2 state protocol (preferred over transfer_state when both
|
||||||
// sides provide it; survives layout changes between plugin versions):
|
// sides provide it; survives layout changes between plugin versions):
|
||||||
//
|
//
|
||||||
@@ -67,6 +79,8 @@ using create_fn = void* (*)(void);
|
|||||||
using destroy_fn = void (*)(void*);
|
using destroy_fn = void (*)(void*);
|
||||||
using info_fn = PluginInfo (*)(void);
|
using info_fn = PluginInfo (*)(void);
|
||||||
using transfer_fn = void (*)(void* old_instance, void* new_instance);
|
using transfer_fn = void (*)(void* old_instance, void* new_instance);
|
||||||
|
using configure_fn = void (*)(void* instance, const char* config);
|
||||||
|
using ready_fn = int (*)(void* instance);
|
||||||
using state_version_fn = std::uint32_t (*)(void);
|
using state_version_fn = std::uint32_t (*)(void);
|
||||||
using serialize_fn = const char* (*)(void* instance);
|
using serialize_fn = const char* (*)(void* instance);
|
||||||
using free_string_fn = void (*)(const char*);
|
using free_string_fn = void (*)(const char*);
|
||||||
@@ -77,6 +91,8 @@ inline constexpr const char* kCreateSymbol = "void_plugin_create";
|
|||||||
inline constexpr const char* kDestroySymbol = "void_plugin_destroy";
|
inline constexpr const char* kDestroySymbol = "void_plugin_destroy";
|
||||||
inline constexpr const char* kInfoSymbol = "void_plugin_info";
|
inline constexpr const char* kInfoSymbol = "void_plugin_info";
|
||||||
inline constexpr const char* kTransferSymbol = "void_plugin_transfer_state";
|
inline constexpr const char* kTransferSymbol = "void_plugin_transfer_state";
|
||||||
|
inline constexpr const char* kConfigureSymbol = "void_plugin_configure";
|
||||||
|
inline constexpr const char* kReadySymbol = "void_plugin_ready";
|
||||||
inline constexpr const char* kStateVersionSymbol = "void_plugin_state_version";
|
inline constexpr const char* kStateVersionSymbol = "void_plugin_state_version";
|
||||||
inline constexpr const char* kSerializeSymbol = "void_plugin_serialize_state";
|
inline constexpr const char* kSerializeSymbol = "void_plugin_serialize_state";
|
||||||
inline constexpr const char* kFreeStringSymbol = "void_plugin_free_string";
|
inline constexpr const char* kFreeStringSymbol = "void_plugin_free_string";
|
||||||
|
|||||||
@@ -47,6 +47,14 @@ namespace Void::Service
|
|||||||
{
|
{
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The reload callback captures `this`; the binding must
|
||||||
|
// deregister it before dying and therefore cannot move.
|
||||||
|
PluginServiceBinding(const PluginServiceBinding&) = delete;
|
||||||
|
PluginServiceBinding&
|
||||||
|
operator=(const PluginServiceBinding&) = delete;
|
||||||
|
|
||||||
|
~PluginServiceBinding() { disable_hot_reload(); }
|
||||||
|
|
||||||
/// Resolve the current instance's service and (re)register it.
|
/// Resolve the current instance's service and (re)register it.
|
||||||
[[nodiscard]] bool bind()
|
[[nodiscard]] bool bind()
|
||||||
{
|
{
|
||||||
@@ -77,22 +85,37 @@ namespace Void::Service
|
|||||||
|
|
||||||
/// Auto-rebind on hot reload (debounced file watching). The
|
/// Auto-rebind on hot reload (debounced file watching). The
|
||||||
/// manager keeps old instances alive while pinned, so the swap
|
/// manager keeps old instances alive while pinned, so the swap
|
||||||
/// is seamless.
|
/// is seamless. Idempotent.
|
||||||
void enable_hot_reload()
|
void enable_hot_reload()
|
||||||
{
|
{
|
||||||
m_manager->on_reloaded([this](std::string_view name) {
|
if (m_reload_id != 0) {
|
||||||
if (name == m_name) {
|
return;
|
||||||
(void)bind();
|
}
|
||||||
}
|
m_reload_id =
|
||||||
});
|
m_manager->on_reloaded([this](std::string_view name) {
|
||||||
|
if (name == m_name) {
|
||||||
|
(void)bind();
|
||||||
|
}
|
||||||
|
});
|
||||||
m_manager->watch(m_name);
|
m_manager->watch(m_name);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Stop observing reloads (the file watch itself is shared and
|
||||||
|
/// stays). Idempotent; called by the destructor.
|
||||||
|
void disable_hot_reload()
|
||||||
|
{
|
||||||
|
if (m_reload_id != 0) {
|
||||||
|
m_manager->remove_on_reloaded(m_reload_id);
|
||||||
|
m_reload_id = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private:
|
private:
|
||||||
|
|
||||||
Plugin::PluginManager* m_manager;
|
Plugin::PluginManager* m_manager;
|
||||||
ServiceRegistry* m_registry;
|
ServiceRegistry* m_registry;
|
||||||
std::string m_name;
|
std::string m_name;
|
||||||
|
Plugin::ReloadCallbackId m_reload_id{0};
|
||||||
};
|
};
|
||||||
|
|
||||||
} // namespace Void::Service
|
} // namespace Void::Service
|
||||||
@@ -80,6 +80,22 @@ namespace Void::Service
|
|||||||
m_services.insert_or_assign(key, std::move(entry));
|
m_services.insert_or_assign(key, std::move(entry));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Withdraw the implementation for interface I from this registry
|
||||||
|
/// (a parent's entry is unaffected: later lookups fall through to
|
||||||
|
/// it again). Consumers still holding the shared_ptr keep the
|
||||||
|
/// instance alive; only new lookups miss. Returns true when an
|
||||||
|
/// entry was removed.
|
||||||
|
template <typename I> bool remove()
|
||||||
|
{
|
||||||
|
const std::type_index key{typeid(I)};
|
||||||
|
std::unique_lock lock{m_mutex};
|
||||||
|
if (m_services.erase(key) == 0) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
std::erase(m_order, key);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
/// Resolve I, or nullptr if not provided. Falls through to the
|
/// Resolve I, or nullptr if not provided. Falls through to the
|
||||||
/// parent registry (if any) on a local miss.
|
/// parent registry (if any) on a local miss.
|
||||||
template <typename I> [[nodiscard]] std::shared_ptr<I> get() const
|
template <typename I> [[nodiscard]] std::shared_ptr<I> get() const
|
||||||
|
|||||||
+98
-12
@@ -14,12 +14,21 @@
|
|||||||
|
|
||||||
#include <openssl/ssl.h>
|
#include <openssl/ssl.h>
|
||||||
|
|
||||||
|
#if !defined(_WIN32)
|
||||||
|
#include <sys/socket.h>
|
||||||
|
#include <sys/time.h>
|
||||||
|
#endif
|
||||||
|
|
||||||
#include <cctype>
|
#include <cctype>
|
||||||
#include <chrono>
|
#include <chrono>
|
||||||
|
#include <condition_variable>
|
||||||
#include <cstdint>
|
#include <cstdint>
|
||||||
#include <format>
|
#include <format>
|
||||||
#include <limits>
|
#include <limits>
|
||||||
|
#include <mutex>
|
||||||
|
#include <optional>
|
||||||
#include <stdexcept>
|
#include <stdexcept>
|
||||||
|
#include <thread>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
namespace Void::Net
|
namespace Void::Net
|
||||||
@@ -227,17 +236,88 @@ namespace Void::Net
|
|||||||
stream.handshake(ssl::stream_base::client);
|
stream.handshake(ssl::stream_base::client);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Bounds every sync operation on an open socket with the request
|
||||||
|
// timeout. Asio's synchronous ops cannot be bounded any other way
|
||||||
|
// short of going fully async: SO_RCVTIMEO merely makes recv return
|
||||||
|
// EAGAIN, which the sync emulation treats as would-block and then
|
||||||
|
// poll()s without a deadline. On expiry the watchdog ::shutdown()s
|
||||||
|
// the descriptor — shutdown (unlike close) is safe against a
|
||||||
|
// concurrent blocked op and wakes it with EOF, so the op fails and
|
||||||
|
// the request errors out instead of hanging the calling thread
|
||||||
|
// forever. The descriptor must stay open for the guard's lifetime
|
||||||
|
// (declare the guard after the connected socket, in the same scope).
|
||||||
|
// Name resolution and connect() are not covered (kernel defaults).
|
||||||
|
class DeadlineGuard
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
|
||||||
|
DeadlineGuard(tcp::socket& socket,
|
||||||
|
std::chrono::seconds timeout)
|
||||||
|
{
|
||||||
|
if (timeout <= std::chrono::seconds::zero() ||
|
||||||
|
!socket.is_open()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const auto fd = socket.native_handle();
|
||||||
|
m_worker = std::thread([this, fd, timeout] {
|
||||||
|
std::unique_lock lock{m_mutex};
|
||||||
|
if (!m_cv.wait_for(lock, timeout,
|
||||||
|
[this] { return m_done; })) {
|
||||||
|
#if defined(_WIN32)
|
||||||
|
::shutdown(fd, SD_BOTH);
|
||||||
|
#else
|
||||||
|
::shutdown(fd, SHUT_RDWR);
|
||||||
|
#endif
|
||||||
|
m_timed_out = true;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
DeadlineGuard(const DeadlineGuard&) = delete;
|
||||||
|
DeadlineGuard& operator=(const DeadlineGuard&) = delete;
|
||||||
|
|
||||||
|
~DeadlineGuard()
|
||||||
|
{
|
||||||
|
if (!m_worker.joinable()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
{
|
||||||
|
std::lock_guard lock{m_mutex};
|
||||||
|
m_done = true;
|
||||||
|
}
|
||||||
|
m_cv.notify_all();
|
||||||
|
m_worker.join();
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] bool timed_out() const noexcept
|
||||||
|
{
|
||||||
|
return m_timed_out;
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
std::thread m_worker;
|
||||||
|
std::mutex m_mutex;
|
||||||
|
std::condition_variable m_cv;
|
||||||
|
bool m_done{false};
|
||||||
|
bool m_timed_out{false};
|
||||||
|
};
|
||||||
|
|
||||||
// Perform the request over an already-connected plain socket, doing a
|
// Perform the request over an already-connected plain socket, doing a
|
||||||
// TLS upgrade in place when the target is https.
|
// TLS upgrade in place when the target is https. The TLS stream is an
|
||||||
Response finish(tcp::socket socket, ssl::context& ctx, const Url& url,
|
// out-parameter declared in the caller's scope so the descriptor
|
||||||
const Request& req, std::string_view ua,
|
// outlives the caller's DeadlineGuard (declaration order there is
|
||||||
std::uint64_t max_body)
|
// socket, stream, guard — the guard is destroyed first).
|
||||||
|
Response finish(tcp::socket& socket,
|
||||||
|
std::optional<ssl::stream<tcp::socket>>& tls,
|
||||||
|
ssl::context& ctx, const Url& url, const Request& req,
|
||||||
|
std::string_view ua, std::uint64_t max_body)
|
||||||
{
|
{
|
||||||
if (url.is_tls) {
|
if (url.is_tls) {
|
||||||
ssl::stream<tcp::socket> stream{std::move(socket), ctx};
|
tls.emplace(std::move(socket), ctx);
|
||||||
tls_handshake(stream, url);
|
tls_handshake(*tls, url);
|
||||||
auto rq = build_request(url, req, ua, url.target);
|
auto rq = build_request(url, req, ua, url.target);
|
||||||
return write_read(stream, rq, max_body);
|
return write_read(*tls, rq, max_body);
|
||||||
}
|
}
|
||||||
auto rq = build_request(url, req, ua, url.target);
|
auto rq = build_request(url, req, ua, url.target);
|
||||||
return write_read(socket, rq, max_body);
|
return write_read(socket, rq, max_body);
|
||||||
@@ -310,19 +390,25 @@ namespace Void::Net
|
|||||||
Response response;
|
Response response;
|
||||||
tcp::resolver resolver{ioc};
|
tcp::resolver resolver{ioc};
|
||||||
|
|
||||||
|
// Declaration order matters: the DeadlineGuard must be
|
||||||
|
// destroyed (and its watchdog joined) BEFORE the objects
|
||||||
|
// that own the descriptor it may shut down.
|
||||||
|
tcp::socket socket{ioc};
|
||||||
|
std::optional<ssl::stream<tcp::socket>> tls;
|
||||||
|
|
||||||
if (m_proxy.enabled()) {
|
if (m_proxy.enabled()) {
|
||||||
tcp::socket socket{ioc};
|
|
||||||
asio::connect(socket, resolver.resolve(
|
asio::connect(socket, resolver.resolve(
|
||||||
m_proxy.host,
|
m_proxy.host,
|
||||||
std::to_string(m_proxy.port)));
|
std::to_string(m_proxy.port)));
|
||||||
|
DeadlineGuard deadline{socket, req.timeout};
|
||||||
if (m_proxy.kind == ProxyConfig::Kind::Socks5) {
|
if (m_proxy.kind == ProxyConfig::Kind::Socks5) {
|
||||||
socks5_connect(socket, *url, m_proxy);
|
socks5_connect(socket, *url, m_proxy);
|
||||||
response = finish(std::move(socket), ctx, *url, req,
|
response = finish(socket, tls, ctx, *url, req,
|
||||||
m_user_agent, m_max_body);
|
m_user_agent, m_max_body);
|
||||||
} else { // Http proxy
|
} else { // Http proxy
|
||||||
if (url->is_tls) {
|
if (url->is_tls) {
|
||||||
http_connect_tunnel(socket, *url, m_proxy);
|
http_connect_tunnel(socket, *url, m_proxy);
|
||||||
response = finish(std::move(socket), ctx, *url, req,
|
response = finish(socket, tls, ctx, *url, req,
|
||||||
m_user_agent, m_max_body);
|
m_user_agent, m_max_body);
|
||||||
} else {
|
} else {
|
||||||
// Plain HTTP through proxy: absolute-form target.
|
// Plain HTTP through proxy: absolute-form target.
|
||||||
@@ -341,10 +427,10 @@ namespace Void::Net
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
tcp::socket socket{ioc};
|
|
||||||
asio::connect(socket,
|
asio::connect(socket,
|
||||||
resolver.resolve(url->host, url->port));
|
resolver.resolve(url->host, url->port));
|
||||||
response = finish(std::move(socket), ctx, *url, req,
|
DeadlineGuard deadline{socket, req.timeout};
|
||||||
|
response = finish(socket, tls, ctx, *url, req,
|
||||||
m_user_agent, m_max_body);
|
m_user_agent, m_max_body);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+23
-4
@@ -23,6 +23,7 @@ std::string_view to_string(LoadError e) noexcept
|
|||||||
case LoadError::CreateFailed: return "plugin create() returned null";
|
case LoadError::CreateFailed: return "plugin create() returned null";
|
||||||
case LoadError::NotSupported: return "platform does not support dlopen";
|
case LoadError::NotSupported: return "platform does not support dlopen";
|
||||||
case LoadError::StateRejected: return "new instance rejected state";
|
case LoadError::StateRejected: return "new instance rejected state";
|
||||||
|
case LoadError::ActivationFailed: return "plugin activation failed";
|
||||||
case LoadError::UnknownPlugin: return "no plugin registered under name";
|
case LoadError::UnknownPlugin: return "no plugin registered under name";
|
||||||
}
|
}
|
||||||
return "unknown";
|
return "unknown";
|
||||||
@@ -44,6 +45,7 @@ void PluginLoader::destroy_current() noexcept
|
|||||||
}
|
}
|
||||||
destroy_ = nullptr;
|
destroy_ = nullptr;
|
||||||
transfer_ = nullptr;
|
transfer_ = nullptr;
|
||||||
|
ready_ = nullptr;
|
||||||
state_version_ = nullptr;
|
state_version_ = nullptr;
|
||||||
serialize_ = nullptr;
|
serialize_ = nullptr;
|
||||||
free_string_ = nullptr;
|
free_string_ = nullptr;
|
||||||
@@ -121,6 +123,7 @@ PluginLoader::load_from(const std::filesystem::path& path)
|
|||||||
plugin_ = static_cast<IPlugin*>(raw);
|
plugin_ = static_cast<IPlugin*>(raw);
|
||||||
destroy_ = sym_destroy;
|
destroy_ = sym_destroy;
|
||||||
transfer_ = reinterpret_cast<transfer_fn>(dlsym(h, kTransferSymbol));
|
transfer_ = reinterpret_cast<transfer_fn>(dlsym(h, kTransferSymbol));
|
||||||
|
ready_ = reinterpret_cast<ready_fn>(dlsym(h, kReadySymbol));
|
||||||
state_version_ = reinterpret_cast<state_version_fn>(
|
state_version_ = reinterpret_cast<state_version_fn>(
|
||||||
dlsym(h, kStateVersionSymbol));
|
dlsym(h, kStateVersionSymbol));
|
||||||
serialize_ = reinterpret_cast<serialize_fn>(dlsym(h, kSerializeSymbol));
|
serialize_ = reinterpret_cast<serialize_fn>(dlsym(h, kSerializeSymbol));
|
||||||
@@ -153,7 +156,14 @@ PluginLoader::load(std::filesystem::path path)
|
|||||||
return std::unexpected{r.error()};
|
return std::unexpected{r.error()};
|
||||||
}
|
}
|
||||||
|
|
||||||
ldr.plugin_->on_load();
|
try {
|
||||||
|
ldr.plugin_->on_load();
|
||||||
|
} catch (...) {
|
||||||
|
return std::unexpected{LoadError::ActivationFailed};
|
||||||
|
}
|
||||||
|
if (ldr.ready_ && ldr.ready_(ldr.plugin_) != 0) {
|
||||||
|
return std::unexpected{LoadError::ActivationFailed};
|
||||||
|
}
|
||||||
Void::Log::info("Plugin", "loaded '{}' ({} v{})", path.string(),
|
Void::Log::info("Plugin", "loaded '{}' ({} v{})", path.string(),
|
||||||
ldr.info_.name, ldr.info_.plugin_version);
|
ldr.info_.name, ldr.info_.plugin_version);
|
||||||
return ldr;
|
return ldr;
|
||||||
@@ -166,6 +176,7 @@ PluginLoader::PluginLoader(PluginLoader&& o) noexcept
|
|||||||
, plugin_ {std::exchange(o.plugin_, nullptr)}
|
, plugin_ {std::exchange(o.plugin_, nullptr)}
|
||||||
, destroy_ {std::exchange(o.destroy_, nullptr)}
|
, destroy_ {std::exchange(o.destroy_, nullptr)}
|
||||||
, transfer_ {std::exchange(o.transfer_, nullptr)}
|
, transfer_ {std::exchange(o.transfer_, nullptr)}
|
||||||
|
, ready_ {std::exchange(o.ready_, nullptr)}
|
||||||
, state_version_{std::exchange(o.state_version_, nullptr)}
|
, state_version_{std::exchange(o.state_version_, nullptr)}
|
||||||
, serialize_ {std::exchange(o.serialize_, nullptr)}
|
, serialize_ {std::exchange(o.serialize_, nullptr)}
|
||||||
, free_string_ {std::exchange(o.free_string_, nullptr)}
|
, free_string_ {std::exchange(o.free_string_, nullptr)}
|
||||||
@@ -182,6 +193,7 @@ PluginLoader& PluginLoader::operator=(PluginLoader&& o) noexcept
|
|||||||
plugin_ = std::exchange(o.plugin_, nullptr);
|
plugin_ = std::exchange(o.plugin_, nullptr);
|
||||||
destroy_ = std::exchange(o.destroy_, nullptr);
|
destroy_ = std::exchange(o.destroy_, nullptr);
|
||||||
transfer_ = std::exchange(o.transfer_, nullptr);
|
transfer_ = std::exchange(o.transfer_, nullptr);
|
||||||
|
ready_ = std::exchange(o.ready_, nullptr);
|
||||||
state_version_ = std::exchange(o.state_version_, nullptr);
|
state_version_ = std::exchange(o.state_version_, nullptr);
|
||||||
serialize_ = std::exchange(o.serialize_, nullptr);
|
serialize_ = std::exchange(o.serialize_, nullptr);
|
||||||
free_string_ = std::exchange(o.free_string_, nullptr);
|
free_string_ = std::exchange(o.free_string_, nullptr);
|
||||||
@@ -228,11 +240,18 @@ std::expected<void, LoadError> PluginLoader::reload()
|
|||||||
return std::unexpected{LoadError::StateRejected};
|
return std::unexpected{LoadError::StateRejected};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Destroy old, install new.
|
try {
|
||||||
|
next.plugin_->on_load();
|
||||||
|
} catch (...) {
|
||||||
|
return std::unexpected{LoadError::ActivationFailed};
|
||||||
|
}
|
||||||
|
if (next.ready_ && next.ready_(next.plugin_) != 0) {
|
||||||
|
return std::unexpected{LoadError::ActivationFailed};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Activation succeeded; only now destroy old and install new.
|
||||||
destroy_current();
|
destroy_current();
|
||||||
*this = std::move(next);
|
*this = std::move(next);
|
||||||
|
|
||||||
plugin_->on_load();
|
|
||||||
Void::Log::info("Plugin", "reloaded '{}' ({} v{})", path_.string(),
|
Void::Log::info("Plugin", "reloaded '{}' ({} v{})", path_.string(),
|
||||||
info_.name, info_.plugin_version);
|
info_.name, info_.plugin_version);
|
||||||
|
|
||||||
|
|||||||
+198
-16
@@ -7,7 +7,10 @@
|
|||||||
#define VOID_HAS_DLOPEN 1
|
#define VOID_HAS_DLOPEN 1
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <atomic>
|
||||||
#include <cstdint>
|
#include <cstdint>
|
||||||
|
#include <string>
|
||||||
#include <system_error>
|
#include <system_error>
|
||||||
#include <utility>
|
#include <utility>
|
||||||
|
|
||||||
@@ -21,6 +24,8 @@ namespace Void::Plugin
|
|||||||
IPlugin* plugin{nullptr};
|
IPlugin* plugin{nullptr};
|
||||||
destroy_fn destroy{nullptr};
|
destroy_fn destroy{nullptr};
|
||||||
transfer_fn transfer{nullptr};
|
transfer_fn transfer{nullptr};
|
||||||
|
configure_fn configure{nullptr};
|
||||||
|
ready_fn ready{nullptr};
|
||||||
state_version_fn state_version{nullptr};
|
state_version_fn state_version{nullptr};
|
||||||
serialize_fn serialize{nullptr};
|
serialize_fn serialize{nullptr};
|
||||||
free_string_fn free_string{nullptr};
|
free_string_fn free_string{nullptr};
|
||||||
@@ -115,6 +120,10 @@ namespace Void::Plugin
|
|||||||
inst->destroy = destroy_sym;
|
inst->destroy = destroy_sym;
|
||||||
inst->transfer =
|
inst->transfer =
|
||||||
reinterpret_cast<transfer_fn>(dlsym(h, kTransferSymbol));
|
reinterpret_cast<transfer_fn>(dlsym(h, kTransferSymbol));
|
||||||
|
inst->configure =
|
||||||
|
reinterpret_cast<configure_fn>(dlsym(h, kConfigureSymbol));
|
||||||
|
inst->ready =
|
||||||
|
reinterpret_cast<ready_fn>(dlsym(h, kReadySymbol));
|
||||||
inst->state_version = reinterpret_cast<state_version_fn>(
|
inst->state_version = reinterpret_cast<state_version_fn>(
|
||||||
dlsym(h, kStateVersionSymbol));
|
dlsym(h, kStateVersionSymbol));
|
||||||
inst->serialize =
|
inst->serialize =
|
||||||
@@ -166,12 +175,18 @@ namespace Void::Plugin
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Copy to a fresh-inode temp path so dlopen does not return the
|
// Copy to a fresh-inode temp path so dlopen does not return the
|
||||||
// already-mapped image when the file is replaced in place.
|
// already-mapped image when the file is replaced in place. The name
|
||||||
|
// must be unique per copy: glibc dedupes dlopen by pathname, so
|
||||||
|
// reusing a temp name would hand back the previously mapped (old)
|
||||||
|
// image no matter what bytes the file now holds.
|
||||||
std::expected<std::filesystem::path, LoadError>
|
std::expected<std::filesystem::path, LoadError>
|
||||||
hotswap_copy(const std::filesystem::path& path)
|
hotswap_copy(const std::filesystem::path& path)
|
||||||
{
|
{
|
||||||
const auto tmp = path.parent_path() /
|
static std::atomic<std::uint64_t> counter{0};
|
||||||
(path.filename().string() + ".void_hotswap");
|
const auto tmp =
|
||||||
|
path.parent_path() /
|
||||||
|
(path.filename().string() + ".void_hotswap." +
|
||||||
|
std::to_string(counter.fetch_add(1, std::memory_order_relaxed)));
|
||||||
std::error_code ec;
|
std::error_code ec;
|
||||||
std::filesystem::copy_file(
|
std::filesystem::copy_file(
|
||||||
path, tmp, std::filesystem::copy_options::overwrite_existing,
|
path, tmp, std::filesystem::copy_options::overwrite_existing,
|
||||||
@@ -207,14 +222,39 @@ namespace Void::Plugin
|
|||||||
if (!std::filesystem::exists(path, ec)) {
|
if (!std::filesystem::exists(path, ec)) {
|
||||||
return std::unexpected{LoadError::FileNotFound};
|
return std::unexpected{LoadError::FileNotFound};
|
||||||
}
|
}
|
||||||
auto inst = open_instance(path, m_options.dlclose_on_swap);
|
std::filesystem::path load_path = path;
|
||||||
|
if (m_options.copy_on_load) {
|
||||||
|
auto tmp = hotswap_copy(path);
|
||||||
|
if (!tmp.has_value()) {
|
||||||
|
return std::unexpected{tmp.error()};
|
||||||
|
}
|
||||||
|
load_path = *tmp;
|
||||||
|
}
|
||||||
|
auto inst = open_instance(load_path, m_options.dlclose_on_swap);
|
||||||
|
if (m_options.copy_on_load) {
|
||||||
|
// The mapping keeps the unlinked inode alive; the registry
|
||||||
|
// keeps addressing the original path for watch/reload.
|
||||||
|
std::filesystem::remove(load_path, ec);
|
||||||
|
}
|
||||||
if (!inst.has_value()) {
|
if (!inst.has_value()) {
|
||||||
Void::Log::warn("Plugin.Manager", "load '{}' failed: {}",
|
Void::Log::warn("Plugin.Manager", "load '{}' failed: {}",
|
||||||
path.string(), to_string(inst.error()));
|
path.string(), to_string(inst.error()));
|
||||||
return std::unexpected{inst.error()};
|
return std::unexpected{inst.error()};
|
||||||
}
|
}
|
||||||
(*inst)->plugin->on_load();
|
|
||||||
std::string name{(*inst)->plugin->name()};
|
std::string name{(*inst)->plugin->name()};
|
||||||
|
if (m_options.config_provider && (*inst)->configure != nullptr) {
|
||||||
|
const std::string config = m_options.config_provider(name);
|
||||||
|
(*inst)->configure((*inst)->plugin, config.c_str());
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
(*inst)->plugin->on_load();
|
||||||
|
} catch (...) {
|
||||||
|
return std::unexpected{LoadError::ActivationFailed};
|
||||||
|
}
|
||||||
|
if ((*inst)->ready != nullptr &&
|
||||||
|
(*inst)->ready((*inst)->plugin) != 0) {
|
||||||
|
return std::unexpected{LoadError::ActivationFailed};
|
||||||
|
}
|
||||||
|
|
||||||
std::lock_guard lock(m_mutex);
|
std::lock_guard lock(m_mutex);
|
||||||
auto entry = std::make_unique<Entry>();
|
auto entry = std::make_unique<Entry>();
|
||||||
@@ -228,6 +268,52 @@ namespace Void::Plugin
|
|||||||
return name;
|
return name;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
std::vector<
|
||||||
|
std::pair<std::filesystem::path, std::expected<std::string, LoadError>>>
|
||||||
|
PluginManager::load_directory(const std::filesystem::path& dir)
|
||||||
|
{
|
||||||
|
#if defined(_WIN32)
|
||||||
|
constexpr std::string_view ext = ".dll";
|
||||||
|
#elif defined(__APPLE__)
|
||||||
|
constexpr std::string_view ext = ".dylib";
|
||||||
|
#else
|
||||||
|
constexpr std::string_view ext = ".so";
|
||||||
|
#endif
|
||||||
|
std::vector<std::filesystem::path> candidates;
|
||||||
|
std::error_code ec;
|
||||||
|
for (const auto& entry : std::filesystem::directory_iterator{dir, ec}) {
|
||||||
|
if (entry.is_regular_file(ec) && entry.path().extension() == ext) {
|
||||||
|
candidates.push_back(entry.path());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
std::sort(candidates.begin(), candidates.end());
|
||||||
|
|
||||||
|
std::vector<std::pair<std::filesystem::path,
|
||||||
|
std::expected<std::string, LoadError>>>
|
||||||
|
out;
|
||||||
|
out.reserve(candidates.size());
|
||||||
|
for (auto& path : candidates) {
|
||||||
|
auto result = load(path);
|
||||||
|
out.emplace_back(std::move(path), std::move(result));
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::expected<void, LoadError> PluginManager::unload(std::string_view name)
|
||||||
|
{
|
||||||
|
std::lock_guard lock(m_mutex);
|
||||||
|
auto* entry = find(name);
|
||||||
|
if (entry == nullptr) {
|
||||||
|
return std::unexpected{LoadError::UnknownPlugin};
|
||||||
|
}
|
||||||
|
m_watcher.unwatch(entry->path);
|
||||||
|
// Erasing drops the registry's reference; outstanding handles keep
|
||||||
|
// the instance (and its mapped .so) alive until they drop.
|
||||||
|
m_plugins.erase(std::string{name});
|
||||||
|
Void::Log::info("Plugin.Manager", "unloaded '{}'", name);
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
PluginHandle PluginManager::acquire(std::string_view name) const
|
PluginHandle PluginManager::acquire(std::string_view name) const
|
||||||
{
|
{
|
||||||
std::lock_guard lock(m_mutex);
|
std::lock_guard lock(m_mutex);
|
||||||
@@ -241,12 +327,23 @@ namespace Void::Plugin
|
|||||||
|
|
||||||
std::expected<void, LoadError> PluginManager::reload(std::string_view name)
|
std::expected<void, LoadError> PluginManager::reload(std::string_view name)
|
||||||
{
|
{
|
||||||
std::lock_guard lock(m_mutex);
|
std::vector<std::function<void(std::string_view)>> callbacks;
|
||||||
auto* entry = find(name);
|
{
|
||||||
if (entry == nullptr) {
|
std::lock_guard lock(m_mutex);
|
||||||
return std::unexpected{LoadError::UnknownPlugin};
|
auto* entry = find(name);
|
||||||
|
if (entry == nullptr) {
|
||||||
|
return std::unexpected{LoadError::UnknownPlugin};
|
||||||
|
}
|
||||||
|
auto result = reload_locked(*entry, name);
|
||||||
|
if (!result.has_value()) {
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
callbacks = reload_callbacks_locked();
|
||||||
}
|
}
|
||||||
return reload_locked(*entry, name);
|
for (const auto& cb : callbacks) {
|
||||||
|
cb(name);
|
||||||
|
}
|
||||||
|
return {};
|
||||||
}
|
}
|
||||||
|
|
||||||
std::expected<void, LoadError>
|
std::expected<void, LoadError>
|
||||||
@@ -271,6 +368,11 @@ namespace Void::Plugin
|
|||||||
return std::unexpected{next.error()};
|
return std::unexpected{next.error()};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (m_options.config_provider && (*next)->configure != nullptr) {
|
||||||
|
const std::string config = m_options.config_provider(name);
|
||||||
|
(*next)->configure((*next)->plugin, config.c_str());
|
||||||
|
}
|
||||||
|
|
||||||
// Transfer state with both instances alive (transactional).
|
// Transfer state with both instances alive (transactional).
|
||||||
auto old = entry.current.load(std::memory_order_acquire);
|
auto old = entry.current.load(std::memory_order_acquire);
|
||||||
if (old) {
|
if (old) {
|
||||||
@@ -281,7 +383,17 @@ namespace Void::Plugin
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
(*next)->plugin->on_load();
|
try {
|
||||||
|
(*next)->plugin->on_load();
|
||||||
|
} catch (...) {
|
||||||
|
return std::unexpected{LoadError::ActivationFailed};
|
||||||
|
}
|
||||||
|
if ((*next)->ready != nullptr &&
|
||||||
|
(*next)->ready((*next)->plugin) != 0) {
|
||||||
|
Void::Log::warn("Plugin.Manager",
|
||||||
|
"reload '{}' aborted: activation failed", name);
|
||||||
|
return std::unexpected{LoadError::ActivationFailed};
|
||||||
|
}
|
||||||
// Atomic swap. The old instance keeps living while any acquired
|
// Atomic swap. The old instance keeps living while any acquired
|
||||||
// handle still pins it; it is destroyed when the last one drops.
|
// handle still pins it; it is destroyed when the last one drops.
|
||||||
entry.current.store(std::move(*next), std::memory_order_release);
|
entry.current.store(std::move(*next), std::memory_order_release);
|
||||||
@@ -306,7 +418,7 @@ namespace Void::Plugin
|
|||||||
if (!e.exists) {
|
if (!e.exists) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
std::function<void(std::string_view)> cb;
|
std::vector<std::function<void(std::string_view)>> callbacks;
|
||||||
{
|
{
|
||||||
std::lock_guard lock(m_mutex);
|
std::lock_guard lock(m_mutex);
|
||||||
auto* entry = find(name_str);
|
auto* entry = find(name_str);
|
||||||
@@ -316,9 +428,9 @@ namespace Void::Plugin
|
|||||||
if (!reload_locked(*entry, name_str).has_value()) {
|
if (!reload_locked(*entry, name_str).has_value()) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
cb = m_on_reloaded;
|
callbacks = reload_callbacks_locked();
|
||||||
}
|
}
|
||||||
if (cb) {
|
for (const auto& cb : callbacks) {
|
||||||
cb(name_str);
|
cb(name_str);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -333,11 +445,81 @@ namespace Void::Plugin
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void PluginManager::on_reloaded(
|
ReloadCallbackId PluginManager::on_reloaded(
|
||||||
std::function<void(std::string_view name)> cb)
|
std::function<void(std::string_view name)> cb)
|
||||||
{
|
{
|
||||||
std::lock_guard lock(m_mutex);
|
std::lock_guard lock(m_mutex);
|
||||||
m_on_reloaded = std::move(cb);
|
const ReloadCallbackId id = m_next_reload_id++;
|
||||||
|
m_on_reloaded.emplace_back(id, std::move(cb));
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
void PluginManager::remove_on_reloaded(ReloadCallbackId id)
|
||||||
|
{
|
||||||
|
std::lock_guard lock(m_mutex);
|
||||||
|
std::erase_if(m_on_reloaded,
|
||||||
|
[id](const auto& pair) { return pair.first == id; });
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<std::function<void(std::string_view)>>
|
||||||
|
PluginManager::reload_callbacks_locked() const
|
||||||
|
{
|
||||||
|
std::vector<std::function<void(std::string_view)>> out;
|
||||||
|
out.reserve(m_on_reloaded.size());
|
||||||
|
for (const auto& [_, cb] : m_on_reloaded) {
|
||||||
|
out.push_back(cb);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::optional<PluginManager::StateSnapshot>
|
||||||
|
PluginManager::serialize_state(std::string_view name) const
|
||||||
|
{
|
||||||
|
std::shared_ptr<detail::Instance> inst;
|
||||||
|
{
|
||||||
|
std::lock_guard lock(m_mutex);
|
||||||
|
auto* entry = find(name);
|
||||||
|
if (entry == nullptr) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
inst = entry->current.load(std::memory_order_acquire);
|
||||||
|
}
|
||||||
|
if (!inst || inst->serialize == nullptr) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
const char* json = inst->serialize(inst->plugin);
|
||||||
|
if (json == nullptr) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
StateSnapshot snapshot{.json = std::string{json},
|
||||||
|
.version = inst->state_version != nullptr
|
||||||
|
? inst->state_version()
|
||||||
|
: 0};
|
||||||
|
if (inst->free_string != nullptr) {
|
||||||
|
inst->free_string(json);
|
||||||
|
}
|
||||||
|
return snapshot;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool PluginManager::deserialize_state(std::string_view name,
|
||||||
|
std::string_view json,
|
||||||
|
std::uint32_t from_version)
|
||||||
|
{
|
||||||
|
std::shared_ptr<detail::Instance> inst;
|
||||||
|
{
|
||||||
|
std::lock_guard lock(m_mutex);
|
||||||
|
auto* entry = find(name);
|
||||||
|
if (entry == nullptr) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
inst = entry->current.load(std::memory_order_acquire);
|
||||||
|
}
|
||||||
|
if (!inst || inst->deserialize == nullptr) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const std::string terminated{json};
|
||||||
|
return inst->deserialize(inst->plugin, terminated.c_str(),
|
||||||
|
from_version) == 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::vector<std::string> PluginManager::names() const
|
std::vector<std::string> PluginManager::names() const
|
||||||
|
|||||||
@@ -98,6 +98,18 @@ if(TARGET Void::Plugin)
|
|||||||
add_dependencies(VoidTests VoidTestPlugin)
|
add_dependencies(VoidTests VoidTestPlugin)
|
||||||
endif()
|
endif()
|
||||||
|
|
||||||
|
# Configurable plugin — exercises the optional void_plugin_configure
|
||||||
|
# entry point driven by PluginManagerOptions::config_provider.
|
||||||
|
add_library(VoidConfigurablePlugin SHARED
|
||||||
|
"${CMAKE_CURRENT_SOURCE_DIR}/plugins/ConfigurablePlugin.cpp")
|
||||||
|
target_link_libraries(VoidConfigurablePlugin PRIVATE Void::Plugin)
|
||||||
|
target_include_directories(VoidConfigurablePlugin PRIVATE
|
||||||
|
"${CMAKE_CURRENT_SOURCE_DIR}/plugins")
|
||||||
|
target_compile_definitions(VoidTests PRIVATE
|
||||||
|
"VOID_CONFIGURABLE_PATH=\"$<TARGET_FILE:VoidConfigurablePlugin>\""
|
||||||
|
)
|
||||||
|
add_dependencies(VoidTests VoidConfigurablePlugin)
|
||||||
|
|
||||||
# Stateful plugins (schema v1 + v2) for hot-reload/state-migration
|
# Stateful plugins (schema v1 + v2) for hot-reload/state-migration
|
||||||
# tests. Same plugin name; v2 adds a field and migrates v1 JSON.
|
# tests. Same plugin name; v2 adds a field and migrates v1 JSON.
|
||||||
add_library(VoidStatefulPluginV1 SHARED
|
add_library(VoidStatefulPluginV1 SHARED
|
||||||
|
|||||||
@@ -0,0 +1,25 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Void/Plugin/Plugin.hpp>
|
||||||
|
|
||||||
|
#include <string_view>
|
||||||
|
|
||||||
|
// Shared interface for the configure-entry-point test plugin. Same
|
||||||
|
// single-inheritance static_cast recovery pattern as Stateful.hpp.
|
||||||
|
namespace VoidTest
|
||||||
|
{
|
||||||
|
class IConfigurable : public Void::Plugin::IPlugin
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
|
||||||
|
[[nodiscard]] virtual std::string_view last_config() const = 0;
|
||||||
|
[[nodiscard]] virtual int configure_calls() const = 0;
|
||||||
|
[[nodiscard]] virtual bool configured_before_on_load() const = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
[[nodiscard]] inline IConfigurable*
|
||||||
|
as_configurable(Void::Plugin::IPlugin* p)
|
||||||
|
{
|
||||||
|
return static_cast<IConfigurable*>(p);
|
||||||
|
}
|
||||||
|
} // namespace VoidTest
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
#include "Configurable.hpp"
|
||||||
|
|
||||||
|
#include <Void/Plugin/Plugin.hpp>
|
||||||
|
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
// A plugin that records what the host passes through the optional
|
||||||
|
// void_plugin_configure entry point, and when (relative to on_load).
|
||||||
|
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
class ConfigurablePlugin final : public VoidTest::IConfigurable
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
|
||||||
|
[[nodiscard]] std::string_view name() const noexcept override
|
||||||
|
{
|
||||||
|
return "ConfigurablePlugin";
|
||||||
|
}
|
||||||
|
|
||||||
|
void on_load() override { loaded_ = true; }
|
||||||
|
|
||||||
|
[[nodiscard]] std::string_view last_config() const override
|
||||||
|
{
|
||||||
|
return config_;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] int configure_calls() const override
|
||||||
|
{
|
||||||
|
return calls_;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] bool configured_before_on_load() const override
|
||||||
|
{
|
||||||
|
return before_on_load_;
|
||||||
|
}
|
||||||
|
|
||||||
|
void apply_config(const char* config)
|
||||||
|
{
|
||||||
|
config_ = config != nullptr ? config : "";
|
||||||
|
++calls_;
|
||||||
|
if (!loaded_) {
|
||||||
|
before_on_load_ = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] bool ready() const noexcept
|
||||||
|
{
|
||||||
|
return config_ != "reject";
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
std::string config_;
|
||||||
|
int calls_{0};
|
||||||
|
bool loaded_{false};
|
||||||
|
bool before_on_load_{false};
|
||||||
|
};
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
extern "C" {
|
||||||
|
void* void_plugin_create() { return new ConfigurablePlugin; }
|
||||||
|
|
||||||
|
void void_plugin_destroy(void* p)
|
||||||
|
{
|
||||||
|
delete static_cast<ConfigurablePlugin*>(p);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Plugin::PluginInfo void_plugin_info()
|
||||||
|
{
|
||||||
|
return {
|
||||||
|
.abi_version = Void::Plugin::ABI_VERSION,
|
||||||
|
.name = "ConfigurablePlugin",
|
||||||
|
.plugin_version = "1.0.0",
|
||||||
|
.description = "Configure entry-point test plugin",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
void void_plugin_configure(void* instance, const char* config)
|
||||||
|
{
|
||||||
|
static_cast<ConfigurablePlugin*>(instance)->apply_config(config);
|
||||||
|
}
|
||||||
|
|
||||||
|
int void_plugin_ready(void* instance)
|
||||||
|
{
|
||||||
|
return static_cast<ConfigurablePlugin*>(instance)->ready() ? 0 : -1;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@
|
|||||||
#include <Void/Testing/Test.hpp>
|
#include <Void/Testing/Test.hpp>
|
||||||
|
|
||||||
#include <string>
|
#include <string>
|
||||||
|
#include <utility>
|
||||||
|
|
||||||
using namespace Void::EventBus;
|
using namespace Void::EventBus;
|
||||||
|
|
||||||
@@ -113,3 +114,42 @@ Void::Testing::Test bus_event_data_forwarded()
|
|||||||
bus.publish(TextChanged{"hello"});
|
bus.publish(TextChanged{"hello"});
|
||||||
Void::Testing::expect_eq(received, std::string{"hello"});
|
Void::Testing::expect_eq(received, std::string{"hello"});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── scoped (RAII) subscriptions ───────────────────────────────────────────────
|
||||||
|
|
||||||
|
Void::Testing::Test bus_scoped_subscription_unsubscribes_on_destruction()
|
||||||
|
{
|
||||||
|
EventBus bus;
|
||||||
|
int count = 0;
|
||||||
|
{
|
||||||
|
auto sub =
|
||||||
|
bus.subscribe_scoped<Clicked>([&](const Clicked&) { ++count; });
|
||||||
|
Void::Testing::expect(static_cast<bool>(sub));
|
||||||
|
bus.publish(Clicked{0, 0});
|
||||||
|
Void::Testing::expect_eq(count, 1);
|
||||||
|
}
|
||||||
|
// Handler removed with the subscription.
|
||||||
|
bus.publish(Clicked{0, 0});
|
||||||
|
Void::Testing::expect_eq(count, 1);
|
||||||
|
Void::Testing::expect_eq(bus.subscriber_count<Clicked>(), std::size_t{0});
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test bus_scoped_subscription_moves_ownership()
|
||||||
|
{
|
||||||
|
EventBus bus;
|
||||||
|
int count = 0;
|
||||||
|
auto outer = EventBus::Subscription{};
|
||||||
|
{
|
||||||
|
auto inner =
|
||||||
|
bus.subscribe_scoped<Clicked>([&](const Clicked&) { ++count; });
|
||||||
|
outer = std::move(inner);
|
||||||
|
Void::Testing::expect(!static_cast<bool>(inner));
|
||||||
|
}
|
||||||
|
// The moved-from handle's death did not unsubscribe.
|
||||||
|
bus.publish(Clicked{0, 0});
|
||||||
|
Void::Testing::expect_eq(count, 1);
|
||||||
|
|
||||||
|
outer.reset();
|
||||||
|
bus.publish(Clicked{0, 0});
|
||||||
|
Void::Testing::expect_eq(count, 1);
|
||||||
|
}
|
||||||
@@ -110,3 +110,57 @@ Void::Testing::Test http_client_connection_refused_is_error()
|
|||||||
const auto resp = client.get("http://127.0.0.1:1/");
|
const auto resp = client.get("http://127.0.0.1:1/");
|
||||||
Void::Testing::expect(!resp.has_value());
|
Void::Testing::expect(!resp.has_value());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test http_client_timeout_bounds_a_stalled_server()
|
||||||
|
{
|
||||||
|
// A server that accepts and then never responds. Without an enforced
|
||||||
|
// Request::timeout the sync read blocks forever (Asio's sync emulation
|
||||||
|
// poll()s on would-block with no deadline).
|
||||||
|
struct StallServer {
|
||||||
|
int fd = -1;
|
||||||
|
std::uint16_t port = 0;
|
||||||
|
int conn = -1;
|
||||||
|
std::thread worker;
|
||||||
|
|
||||||
|
StallServer()
|
||||||
|
{
|
||||||
|
fd = ::socket(AF_INET, SOCK_STREAM, 0);
|
||||||
|
int yes = 1;
|
||||||
|
::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
|
||||||
|
sockaddr_in addr{};
|
||||||
|
addr.sin_family = AF_INET;
|
||||||
|
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
|
||||||
|
addr.sin_port = 0;
|
||||||
|
::bind(fd, reinterpret_cast<sockaddr*>(&addr), sizeof(addr));
|
||||||
|
socklen_t len = sizeof(addr);
|
||||||
|
::getsockname(fd, reinterpret_cast<sockaddr*>(&addr), &len);
|
||||||
|
port = ntohs(addr.sin_port);
|
||||||
|
::listen(fd, 1);
|
||||||
|
worker = std::thread([this] {
|
||||||
|
conn = ::accept(fd, nullptr, nullptr);
|
||||||
|
// Never write a byte; hold the connection open.
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
~StallServer()
|
||||||
|
{
|
||||||
|
if (conn >= 0) ::close(conn);
|
||||||
|
if (worker.joinable()) worker.join();
|
||||||
|
if (fd >= 0) ::close(fd);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
StallServer server;
|
||||||
|
Void::Net::HttpClient client;
|
||||||
|
Void::Net::Request req;
|
||||||
|
req.url = "http://127.0.0.1:" + std::to_string(server.port) + "/stall";
|
||||||
|
req.timeout = std::chrono::seconds{1};
|
||||||
|
|
||||||
|
const auto start = std::chrono::steady_clock::now();
|
||||||
|
const auto resp = client.send(req);
|
||||||
|
const auto elapsed = std::chrono::steady_clock::now() - start;
|
||||||
|
|
||||||
|
Void::Testing::expect(!resp.has_value());
|
||||||
|
// Well under the old "forever": the deadline tripped around 1s.
|
||||||
|
Void::Testing::expect(elapsed < std::chrono::seconds{5});
|
||||||
|
}
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
#include <Void/Plugin/Manager.hpp>
|
||||||
|
#include <Void/System/TempDir.hpp>
|
||||||
|
#include <Void/Testing/Assert.hpp>
|
||||||
|
#include <Void/Testing/Test.hpp>
|
||||||
|
|
||||||
|
#include "Configurable.hpp"
|
||||||
|
|
||||||
|
#include <filesystem>
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
using namespace Void::Plugin;
|
||||||
|
|
||||||
|
#if defined(VOID_CONFIGURABLE_PATH) && __has_include(<dlfcn.h>)
|
||||||
|
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
VoidTest::IConfigurable* configurable(const PluginHandle& h)
|
||||||
|
{
|
||||||
|
return VoidTest::as_configurable(h.get());
|
||||||
|
}
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
Void::Testing::Test configure_called_with_provider_payload_before_on_load()
|
||||||
|
{
|
||||||
|
PluginManager mgr{{.config_provider = [](std::string_view name) {
|
||||||
|
return std::string{"{\"plugin\":\""} + std::string{name} + "\"}";
|
||||||
|
}}};
|
||||||
|
const auto name = mgr.load(VOID_CONFIGURABLE_PATH);
|
||||||
|
Void::Testing::expect(name.has_value());
|
||||||
|
|
||||||
|
auto h = mgr.acquire("ConfigurablePlugin");
|
||||||
|
Void::Testing::expect_eq(configurable(h)->configure_calls(), 1);
|
||||||
|
Void::Testing::expect(configurable(h)->configured_before_on_load());
|
||||||
|
Void::Testing::expect_eq(
|
||||||
|
configurable(h)->last_config(),
|
||||||
|
std::string_view{"{\"plugin\":\"ConfigurablePlugin\"}"});
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test configure_reruns_on_reload_with_fresh_payload()
|
||||||
|
{
|
||||||
|
Void::FileSystem::TempDir tmp{"void_cfg"};
|
||||||
|
const auto so = tmp.path() / "plugin.so";
|
||||||
|
std::filesystem::copy_file(VOID_CONFIGURABLE_PATH, so);
|
||||||
|
|
||||||
|
int generation = 0;
|
||||||
|
PluginManager mgr{{.config_provider = [&generation](std::string_view) {
|
||||||
|
return std::string{"gen="} + std::to_string(generation);
|
||||||
|
}}};
|
||||||
|
Void::Testing::expect(mgr.load(so).has_value());
|
||||||
|
|
||||||
|
generation = 1;
|
||||||
|
Void::Testing::expect(mgr.reload("ConfigurablePlugin").has_value());
|
||||||
|
|
||||||
|
auto h = mgr.acquire("ConfigurablePlugin");
|
||||||
|
// The reloaded instance is fresh: one configure call, new payload.
|
||||||
|
Void::Testing::expect_eq(configurable(h)->configure_calls(), 1);
|
||||||
|
Void::Testing::expect_eq(configurable(h)->last_config(),
|
||||||
|
std::string_view{"gen=1"});
|
||||||
|
Void::Testing::expect(configurable(h)->configured_before_on_load());
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test configure_skipped_without_provider()
|
||||||
|
{
|
||||||
|
PluginManager mgr;
|
||||||
|
Void::Testing::expect(mgr.load(VOID_CONFIGURABLE_PATH).has_value());
|
||||||
|
auto h = mgr.acquire("ConfigurablePlugin");
|
||||||
|
Void::Testing::expect_eq(configurable(h)->configure_calls(), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test activation_failure_keeps_current_instance()
|
||||||
|
{
|
||||||
|
Void::FileSystem::TempDir tmp{"void_cfg_ready"};
|
||||||
|
const auto so = tmp.path() / "plugin.so";
|
||||||
|
std::filesystem::copy_file(VOID_CONFIGURABLE_PATH, so);
|
||||||
|
|
||||||
|
std::string payload{"accepted"};
|
||||||
|
PluginManager mgr{{.config_provider = [&payload](std::string_view) {
|
||||||
|
return payload;
|
||||||
|
}}};
|
||||||
|
Void::Testing::expect(mgr.load(so).has_value());
|
||||||
|
auto before = mgr.acquire("ConfigurablePlugin");
|
||||||
|
Void::Testing::expect_eq(configurable(before)->last_config(),
|
||||||
|
std::string_view{"accepted"});
|
||||||
|
|
||||||
|
payload = "reject";
|
||||||
|
const auto result = mgr.reload("ConfigurablePlugin");
|
||||||
|
Void::Testing::expect(!result.has_value());
|
||||||
|
Void::Testing::expect(result.error() == LoadError::ActivationFailed);
|
||||||
|
auto after = mgr.acquire("ConfigurablePlugin");
|
||||||
|
Void::Testing::expect(after.get() == before.get());
|
||||||
|
Void::Testing::expect_eq(configurable(after)->last_config(),
|
||||||
|
std::string_view{"accepted"});
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif // configurable plugin available
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
#include <Void/Plugin/Loader.hpp>
|
||||||
|
#include <Void/Plugin/Manager.hpp>
|
||||||
|
#include <Void/System/TempDir.hpp>
|
||||||
|
#include <Void/Testing/Assert.hpp>
|
||||||
|
#include <Void/Testing/Test.hpp>
|
||||||
|
|
||||||
|
#include <filesystem>
|
||||||
|
#include <fstream>
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
using namespace Void::Plugin;
|
||||||
|
|
||||||
|
#if defined(VOID_TEST_PLUGIN_PATH) && defined(VOID_STATEFUL_V1_PATH) && \
|
||||||
|
__has_include(<dlfcn.h>)
|
||||||
|
|
||||||
|
Void::Testing::Test discovery_loads_all_plugins_in_filename_order()
|
||||||
|
{
|
||||||
|
Void::FileSystem::TempDir tmp{"void_disc"};
|
||||||
|
std::filesystem::copy_file(VOID_STATEFUL_V1_PATH,
|
||||||
|
tmp.path() / "b_stateful.so");
|
||||||
|
std::filesystem::copy_file(VOID_TEST_PLUGIN_PATH, tmp.path() / "a_test.so");
|
||||||
|
{
|
||||||
|
std::ofstream decoy{tmp.path() / "readme.txt"};
|
||||||
|
decoy << "not a plugin";
|
||||||
|
}
|
||||||
|
std::filesystem::create_directory(tmp.path() / "subdir");
|
||||||
|
|
||||||
|
PluginManager mgr;
|
||||||
|
const auto results = mgr.load_directory(tmp.path());
|
||||||
|
|
||||||
|
// Only the two .so files count, sorted by filename.
|
||||||
|
Void::Testing::expect_eq(results.size(), std::size_t{2});
|
||||||
|
Void::Testing::expect_eq(results[0].first.filename().string(),
|
||||||
|
std::string{"a_test.so"});
|
||||||
|
Void::Testing::expect(results[0].second.has_value());
|
||||||
|
Void::Testing::expect_eq(*results[0].second, std::string{"TestPlugin"});
|
||||||
|
Void::Testing::expect_eq(results[1].first.filename().string(),
|
||||||
|
std::string{"b_stateful.so"});
|
||||||
|
Void::Testing::expect(results[1].second.has_value());
|
||||||
|
Void::Testing::expect_eq(*results[1].second, std::string{"StatefulPlugin"});
|
||||||
|
|
||||||
|
Void::Testing::expect(static_cast<bool>(mgr.acquire("TestPlugin")));
|
||||||
|
Void::Testing::expect(static_cast<bool>(mgr.acquire("StatefulPlugin")));
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test discovery_reports_per_file_errors()
|
||||||
|
{
|
||||||
|
Void::FileSystem::TempDir tmp{"void_disc"};
|
||||||
|
std::filesystem::copy_file(VOID_TEST_PLUGIN_PATH, tmp.path() / "ok.so");
|
||||||
|
{
|
||||||
|
std::ofstream bogus{tmp.path() / "broken.so"};
|
||||||
|
bogus << "ELF? no.";
|
||||||
|
}
|
||||||
|
|
||||||
|
PluginManager mgr;
|
||||||
|
const auto results = mgr.load_directory(tmp.path());
|
||||||
|
|
||||||
|
Void::Testing::expect_eq(results.size(), std::size_t{2});
|
||||||
|
// broken.so sorts first and fails to dlopen; ok.so loads.
|
||||||
|
Void::Testing::expect(!results[0].second.has_value());
|
||||||
|
Void::Testing::expect(results[0].second.error() == LoadError::DlopenFailed);
|
||||||
|
Void::Testing::expect(results[1].second.has_value());
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test discovery_missing_directory_yields_empty()
|
||||||
|
{
|
||||||
|
PluginManager mgr;
|
||||||
|
const auto results = mgr.load_directory("/nonexistent/void_discovery_test");
|
||||||
|
Void::Testing::expect(results.empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif // test plugins available
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
#include <Void/Plugin/Loader.hpp>
|
||||||
#include <Void/Plugin/Manager.hpp>
|
#include <Void/Plugin/Manager.hpp>
|
||||||
#include <Void/System/TempDir.hpp>
|
#include <Void/System/TempDir.hpp>
|
||||||
#include <Void/Testing/Assert.hpp>
|
#include <Void/Testing/Assert.hpp>
|
||||||
@@ -78,13 +79,23 @@ Void::Testing::Test hot_reload_under_concurrent_load()
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Main thread flips the file v1<->v2 and reloads repeatedly.
|
// Main thread flips the file v1<->v2 and reloads repeatedly. The first
|
||||||
|
// v2 reload migrates v1 state forward; after that, installing v1 is a
|
||||||
|
// DOWNGRADE — v1 cannot deserialize v2 state, so the transactional
|
||||||
|
// reload must fail with StateRejected and keep the v2 instance. (An
|
||||||
|
// earlier version of this test expected every reload to succeed; that
|
||||||
|
// only passed because a fixed hotswap temp name made dlopen return the
|
||||||
|
// already-mapped image, so no flip after the first ever took effect.)
|
||||||
for (int i = 0; i < 24; ++i) {
|
for (int i = 0; i < 24; ++i) {
|
||||||
const char* src =
|
const bool to_v2 = (i % 2 == 0);
|
||||||
(i % 2 == 0) ? VOID_STATEFUL_V2_PATH : VOID_STATEFUL_V1_PATH;
|
install(to_v2 ? VOID_STATEFUL_V2_PATH : VOID_STATEFUL_V1_PATH, so);
|
||||||
install(src, so);
|
|
||||||
const auto r = mgr.reload("StatefulPlugin");
|
const auto r = mgr.reload("StatefulPlugin");
|
||||||
Void::Testing::expect(r.has_value());
|
if (to_v2) {
|
||||||
|
Void::Testing::expect(r.has_value());
|
||||||
|
} else {
|
||||||
|
Void::Testing::expect(!r.has_value());
|
||||||
|
Void::Testing::expect(r.error() == LoadError::StateRejected);
|
||||||
|
}
|
||||||
std::this_thread::sleep_for(std::chrono::milliseconds{2});
|
std::this_thread::sleep_for(std::chrono::milliseconds{2});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -97,12 +108,14 @@ Void::Testing::Test hot_reload_under_concurrent_load()
|
|||||||
Void::Testing::expect_eq(crashes.load(), 0);
|
Void::Testing::expect_eq(crashes.load(), 0);
|
||||||
Void::Testing::expect(ops.load() > 0);
|
Void::Testing::expect(ops.load() > 0);
|
||||||
|
|
||||||
// State survived every migration: the final instance's counter is at
|
// State survived every migration: the counter is monotonic, never
|
||||||
// least the number of reloads' worth of preserved bumps (monotonic,
|
// reset by a swap, and the surviving instance is the v2 build (every
|
||||||
// never reset to zero by a swap).
|
// attempted downgrade was rejected transactionally).
|
||||||
auto final = mgr.acquire("StatefulPlugin");
|
auto final = mgr.acquire("StatefulPlugin");
|
||||||
Void::Testing::expect(static_cast<bool>(final));
|
Void::Testing::expect(static_cast<bool>(final));
|
||||||
Void::Testing::expect(VoidTest::as_stateful(final.get())->counter() > 0);
|
Void::Testing::expect(VoidTest::as_stateful(final.get())->counter() > 0);
|
||||||
|
Void::Testing::expect_eq(
|
||||||
|
VoidTest::as_stateful(final.get())->schema_version(), 2);
|
||||||
}
|
}
|
||||||
|
|
||||||
#endif // stateful plugins available
|
#endif // stateful plugins available
|
||||||
@@ -166,4 +166,107 @@ Void::Testing::Test manager_watch_auto_reloads_on_file_change()
|
|||||||
mgr.unwatch("StatefulPlugin");
|
mgr.unwatch("StatefulPlugin");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test manager_multiple_reload_observers_coexist()
|
||||||
|
{
|
||||||
|
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());
|
||||||
|
|
||||||
|
int first = 0;
|
||||||
|
int second = 0;
|
||||||
|
std::string seen;
|
||||||
|
const auto id1 = mgr.on_reloaded([&](std::string_view n) {
|
||||||
|
++first;
|
||||||
|
seen = std::string{n};
|
||||||
|
});
|
||||||
|
(void)mgr.on_reloaded([&](std::string_view) { ++second; });
|
||||||
|
|
||||||
|
// Manual reloads notify every observer (not only watched ones).
|
||||||
|
install(VOID_STATEFUL_V2_PATH, so);
|
||||||
|
Void::Testing::expect(mgr.reload("StatefulPlugin").has_value());
|
||||||
|
Void::Testing::expect_eq(first, 1);
|
||||||
|
Void::Testing::expect_eq(second, 1);
|
||||||
|
Void::Testing::expect_eq(seen, std::string{"StatefulPlugin"});
|
||||||
|
|
||||||
|
// A removed observer stays silent; the other keeps firing.
|
||||||
|
mgr.remove_on_reloaded(id1);
|
||||||
|
Void::Testing::expect(mgr.reload("StatefulPlugin").has_value());
|
||||||
|
Void::Testing::expect_eq(first, 1);
|
||||||
|
Void::Testing::expect_eq(second, 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test manager_unload_drops_entry_but_pinned_handle_survives()
|
||||||
|
{
|
||||||
|
PluginManager mgr;
|
||||||
|
Void::Testing::expect(mgr.load(VOID_STATEFUL_V1_PATH).has_value());
|
||||||
|
|
||||||
|
auto pinned = mgr.acquire("StatefulPlugin");
|
||||||
|
stateful(pinned)->bump();
|
||||||
|
|
||||||
|
Void::Testing::expect(mgr.unload("StatefulPlugin").has_value());
|
||||||
|
// Gone from the registry…
|
||||||
|
Void::Testing::expect(!static_cast<bool>(mgr.acquire("StatefulPlugin")));
|
||||||
|
Void::Testing::expect(mgr.unload("StatefulPlugin").error() ==
|
||||||
|
LoadError::UnknownPlugin);
|
||||||
|
// …but the pinned instance still works until the handle drops.
|
||||||
|
Void::Testing::expect_eq(stateful(pinned)->counter(), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test manager_copy_on_load_survives_in_place_overwrite()
|
||||||
|
{
|
||||||
|
Void::FileSystem::TempDir tmp{"void_mgr"};
|
||||||
|
const auto so = tmp.path() / "plugin.so";
|
||||||
|
std::filesystem::copy_file(VOID_STATEFUL_V1_PATH, so);
|
||||||
|
|
||||||
|
PluginManager mgr{{.copy_on_load = true}};
|
||||||
|
Void::Testing::expect(mgr.load(so).has_value());
|
||||||
|
|
||||||
|
auto h = mgr.acquire("StatefulPlugin");
|
||||||
|
stateful(h)->bump();
|
||||||
|
|
||||||
|
// Overwrite the original file IN PLACE (what a build does). With
|
||||||
|
// copy_on_load the mapped image is a private unlinked copy, so the
|
||||||
|
// running instance is unaffected.
|
||||||
|
std::filesystem::copy_file(
|
||||||
|
VOID_STATEFUL_V2_PATH, so,
|
||||||
|
std::filesystem::copy_options::overwrite_existing);
|
||||||
|
Void::Testing::expect_eq(stateful(h)->schema_version(), 1);
|
||||||
|
Void::Testing::expect_eq(stateful(h)->counter(), 1);
|
||||||
|
|
||||||
|
// Reload still tracks the original path and picks up the new bytes.
|
||||||
|
Void::Testing::expect(mgr.reload("StatefulPlugin").has_value());
|
||||||
|
auto fresh = mgr.acquire("StatefulPlugin");
|
||||||
|
Void::Testing::expect_eq(stateful(fresh)->schema_version(), 2);
|
||||||
|
Void::Testing::expect_eq(stateful(fresh)->counter(), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test manager_state_snapshot_round_trip()
|
||||||
|
{
|
||||||
|
PluginManager mgr;
|
||||||
|
Void::Testing::expect(mgr.load(VOID_STATEFUL_V1_PATH).has_value());
|
||||||
|
|
||||||
|
auto h = mgr.acquire("StatefulPlugin");
|
||||||
|
stateful(h)->bump();
|
||||||
|
stateful(h)->bump(); // counter = 2
|
||||||
|
|
||||||
|
const auto snapshot = mgr.serialize_state("StatefulPlugin");
|
||||||
|
Void::Testing::expect(snapshot.has_value());
|
||||||
|
Void::Testing::expect_eq(snapshot->version, std::uint32_t{1});
|
||||||
|
|
||||||
|
stateful(h)->bump(); // counter = 3
|
||||||
|
|
||||||
|
// Injecting the snapshot restores the earlier state.
|
||||||
|
Void::Testing::expect(mgr.deserialize_state(
|
||||||
|
"StatefulPlugin", snapshot->json, snapshot->version));
|
||||||
|
Void::Testing::expect_eq(stateful(h)->counter(), 2);
|
||||||
|
|
||||||
|
// Unknown plugins produce no snapshot and reject injection.
|
||||||
|
Void::Testing::expect(!mgr.serialize_state("nope").has_value());
|
||||||
|
Void::Testing::expect(
|
||||||
|
!mgr.deserialize_state("nope", snapshot->json, snapshot->version));
|
||||||
|
}
|
||||||
|
|
||||||
#endif // stateful plugins available
|
#endif // stateful plugins available
|
||||||
@@ -114,6 +114,43 @@ Void::Testing::Test registry_replace_provider()
|
|||||||
Void::Testing::expect_eq(reg.size(), std::size_t{1});
|
Void::Testing::expect_eq(reg.size(), std::size_t{1});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test registry_remove_withdraws_entry()
|
||||||
|
{
|
||||||
|
ServiceRegistry reg;
|
||||||
|
auto clock = std::make_shared<FixedClock>(7);
|
||||||
|
reg.provide<IClock>(clock);
|
||||||
|
|
||||||
|
// A consumer resolved before the removal keeps its instance.
|
||||||
|
auto held = reg.get<IClock>();
|
||||||
|
|
||||||
|
Void::Testing::expect(reg.remove<IClock>());
|
||||||
|
Void::Testing::expect(!reg.has<IClock>());
|
||||||
|
Void::Testing::expect(reg.get<IClock>() == nullptr);
|
||||||
|
Void::Testing::expect_eq(reg.size(), std::size_t{0});
|
||||||
|
Void::Testing::expect_eq(held->now(), 7);
|
||||||
|
|
||||||
|
// Removing again reports nothing to remove.
|
||||||
|
Void::Testing::expect(!reg.remove<IClock>());
|
||||||
|
|
||||||
|
// Re-providing after removal works (fresh lifecycle position).
|
||||||
|
reg.provide<IClock>(std::make_shared<FixedClock>(9));
|
||||||
|
Void::Testing::expect_eq(reg.require<IClock>().now(), 9);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test registry_remove_in_child_reexposes_parent()
|
||||||
|
{
|
||||||
|
ServiceRegistry parent;
|
||||||
|
parent.provide<IClock>(std::make_shared<FixedClock>(1));
|
||||||
|
|
||||||
|
ServiceRegistry child{&parent};
|
||||||
|
child.provide<IClock>(std::make_shared<FixedClock>(2));
|
||||||
|
Void::Testing::expect_eq(child.require<IClock>().now(), 2);
|
||||||
|
|
||||||
|
// Removing the child's shadow re-exposes the parent's entry.
|
||||||
|
Void::Testing::expect(child.remove<IClock>());
|
||||||
|
Void::Testing::expect_eq(child.require<IClock>().now(), 1);
|
||||||
|
}
|
||||||
|
|
||||||
Void::Testing::Test registry_lifecycle_order()
|
Void::Testing::Test registry_lifecycle_order()
|
||||||
{
|
{
|
||||||
std::vector<std::string> log;
|
std::vector<std::string> log;
|
||||||
|
|||||||
Reference in new issue
Block a user