diff --git a/CLAUDE.md b/CLAUDE.md index 006af89..6fb1145 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -47,7 +47,8 @@ VoidLibrary is a C++26 modular shared library organized as **umbrella modules** | `Configuration` | SHARED | Config, Env + Argparse | | `Stacktrace` | SHARED | Boost.Stacktrace capture, color helpers (kept separate to isolate the Boost dep) | | `Plugin` | SHARED | dlopen loader + manager, C ABI, hot reload (see below) | -| `Fsm` | SHARED | inheritance + coroutine workflow FSM (see below) | +| `Service` | INTERFACE | `IService` + type-keyed `ServiceRegistry` (DI); plugin-service bridge | +| `Fsm` | SHARED | inheritance + coroutine workflow FSM + `Orchestrator` (see below) | | `Testing` / `TestingMock` | STATIC / INTERFACE | test + mock frameworks | `include/Void/Detail/` (e.g. `Enum.hpp` — P2996 enum reflection) is not a module; it is header-only and reachable from every module via the shared include root. @@ -135,9 +136,27 @@ Other key points: `Configuration::Config`: flat string store with dotted keys. Sources (overlay-composable, last wins): `from_env`, `from_env_prefix("APP_")` (`__`→`.`, lowercased), `from_file` (KEY=VALUE), `from_ini`, `from_json` (flattened), `from_args` (`--key=value`). Typed access `get_as` / `get_or_as` (numbers, bool spellings, enums by name via reflection, chrono durations like "250ms"). `subtree(prefix)` strips a prefix. `Bind.hpp`: `bind(cfg, prefix)` fills an aggregate via P2996 (defaults = schema). `Watch.hpp`: `ConfigWatch` reloads a file on change with per-key diff (debounced polling via `FileSystem::FileWatcher` in `System`). -### Fsm module +### Service module -`Void::Fsm` is being rewritten as an inheritance + coroutine workflow FSM (states as nested structs, async `run` returning next-state/success/fail, events, nesting, dynamic registration). Documented when it lands. +`Void::Service` — dependency inversion + FSM orchestration. + +- `IService` base (`service_name()`, `on_start()`/`on_stop()` lifecycle). +- `ServiceRegistry` — type-keyed: `provide(impl)`, `get()` (nullptr if absent), `require()` (throws), `has()`, `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(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` 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. + +### Fsm module (inheritance + coroutine workflow) + +`Void::Fsm::Machine` — derive it; declare states as nested structs deriving `State`; each implements `Coro::Task run()` returning `next()` / `succeed(...)` / `fail(...)`. There is no statechart/event-graph; states drive themselves. + +- **Async by default**: a non-template `Detail::ExecutionContext` (`src/Fsm/Engine.cpp`) owns one `Async::ManualExecutor` + worker thread + a lock-free MPSC event queue + a typed event mailbox. A single consumer (worker, or the embedder via `pump()` when `MachineOptions{.own_worker=false}`) touches all mutable state, so state code is lock-free/single-threaded. `start()`/`run_blocking()`/`wait()` for worker mode; `pump()` for embedder mode (deterministic tests). +- **Events**: `co_await await_event()` consumes the oldest queued `E` (typed mailbox), suspending until one arrives; `post(e)` is lock-free from any thread. +- **Nesting**: `co_await run_child(args...)` runs a child on the *same* executor (shared events + services) and yields its `Outcome` (`std::expected`). +- **Dynamic**: `add()` / `add_if(cond)`; `next` fails; `has_state()` lets a state branch. +- **Services**: `set_services(registry)`; `state.service()` resolves through the injected context. +- **Observation**: `current_state()` is a lock-free atomic-index read of an immutable name table (P2996 `identifier_of`, fallback to indexed names). +- **Persistence**: `serialize()` → `{state name, on_serialize data}`; `restore()` on an un-started machine resumes at the named state (override `on_serialize`/`on_restore` for derived data, reflection-JSON friendly). +- Hot-plug + state-saving are re-expressed via services: plugins provide `IService` impls; `PluginServiceBinding` swaps the registry entry on reload (state migrated by the plugin's v2 ABI), so running FSMs pick up the new impl on the next `service()` call without being patched. ### Plugin module (hot reload) diff --git a/README.md b/README.md index e3dff61..47f0438 100644 --- a/README.md +++ b/README.md @@ -64,8 +64,9 @@ The C++ namespaces of the absorbed components are unchanged — e.g. | `System` | SHARED | FileSystem path utilities (`Result`-based, RAII TempDir) + Process. | | `Configuration` | SHARED | Layered key-value Config, Env + Argparse. | | `Stacktrace` | SHARED | Stack capture + source snippets via Boost.Stacktrace; ANSI color helpers. | -| `Plugin` | SHARED | dlopen-based plugin loader with C ABI, hot reload, state transfer. | -| `StateMachine` | INTERFACE | Compile-time variant-based FSM. | +| `Plugin` | SHARED | dlopen-based plugin loader + manager with C ABI, hot reload, state transfer. | +| `Service` | INTERFACE | `IService` + type-keyed `ServiceRegistry` (dependency inversion); plugin-service bridge. | +| `Fsm` | SHARED | Inheritance + coroutine workflow state machine (states as nested structs, async, events, nesting, dynamic) + `Orchestrator`. | | `Testing` | STATIC | Self-registering test framework with fixtures, tags, JUnit/console reporters, crash capture. | | `TestingMock` | INTERFACE | Mock framework: `MockFunction`, `Mock`, matchers, move-only actions. | diff --git a/include/Void/Service/PluginService.hpp b/include/Void/Service/PluginService.hpp new file mode 100644 index 0000000..37183b9 --- /dev/null +++ b/include/Void/Service/PluginService.hpp @@ -0,0 +1,98 @@ +#pragma once + +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace Void::Service +{ + /// C entry point a plugin exports to expose a service: + /// extern "C" Void::Service::IService* void_plugin_service(void* inst); + /// It returns the IService subobject of the plugin's service object + /// (which must derive the host interface I, and I must derive + /// IService). The host recovers I* by static_cast — no dynamic_cast, so + /// it is robust across RTLD_LOCAL plugin boundaries. + using service_factory_fn = IService* (*)(void* instance); + + inline constexpr const char* kServiceSymbol = "void_plugin_service"; + + /// Binds a plugin-provided service (interface I) into a ServiceRegistry + /// and keeps it bound across hot reloads: after each reload the new + /// instance's service (carrying state migrated by the plugin's v2 ABI) + /// is re-resolved and re-registered, so FSMs resolving I through their + /// context transparently pick up the new implementation on their next + /// call. The registry entry pins the plugin instance, so in-flight + /// callers never see a freed object. + /// + /// Requires: I derives Void::Service::IService; the plugin's service + /// type derives I; the plugin exports void_plugin_service. + template class PluginServiceBinding + { + public: + + static_assert(std::is_base_of_v, + "plugin service interface must derive IService"); + + PluginServiceBinding(Plugin::PluginManager& manager, + ServiceRegistry& registry, std::string name) + : m_manager(&manager), m_registry(®istry), + m_name(std::move(name)) + { + } + + /// Resolve the current instance's service and (re)register it. + [[nodiscard]] bool bind() + { + auto handle = m_manager->acquire(m_name); + if (!handle) { + return false; + } + auto* fn = reinterpret_cast( + m_manager->raw_symbol(m_name, kServiceSymbol)); + if (fn == nullptr) { + return false; + } + IService* base = fn(handle.get()); + if (base == nullptr) { + return false; + } + I* iface = static_cast(base); // I : IService + + // Keep the plugin instance (and its mapped .so) alive for + // as long as the registry holds this service. + auto owner = std::make_shared(handle); + std::shared_ptr pinned(std::move(owner), iface); + m_registry->provide(std::move(pinned)); + Void::Log::debug("Service.Plugin", + "bound service from plugin '{}'", m_name); + return true; + } + + /// Auto-rebind on hot reload (debounced file watching). The + /// manager keeps old instances alive while pinned, so the swap + /// is seamless. + void enable_hot_reload() + { + m_manager->on_reloaded([this](std::string_view name) { + if (name == m_name) { + (void)bind(); + } + }); + m_manager->watch(m_name); + } + + private: + + Plugin::PluginManager* m_manager; + ServiceRegistry* m_registry; + std::string m_name; + }; + +} // namespace Void::Service diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 569696b..3a0ec87 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -116,4 +116,25 @@ if(TARGET Void::Plugin) target_include_directories(VoidTests PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/plugins") add_dependencies(VoidTests VoidStatefulPluginV1 VoidStatefulPluginV2) + + # Service plugins (a plugin provides an IService-derived interface) for + # the FSM x Service hot-reload integration test. Same plugin name; v2 + # migrates v1 state. + if(TARGET Void::Service AND TARGET Void::Data) + add_library(VoidServicePluginV1 SHARED + "${CMAKE_CURRENT_SOURCE_DIR}/plugins/ServicePluginV1.cpp") + add_library(VoidServicePluginV2 SHARED + "${CMAKE_CURRENT_SOURCE_DIR}/plugins/ServicePluginV2.cpp") + foreach(_sp VoidServicePluginV1 VoidServicePluginV2) + target_link_libraries(${_sp} + PRIVATE Void::Plugin Void::Service Void::Data) + target_include_directories(${_sp} PRIVATE + "${CMAKE_CURRENT_SOURCE_DIR}/plugins") + endforeach() + target_compile_definitions(VoidTests PRIVATE + "VOID_SERVICE_V1_PATH=\"$\"" + "VOID_SERVICE_V2_PATH=\"$\"" + ) + add_dependencies(VoidTests VoidServicePluginV1 VoidServicePluginV2) + endif() endif() diff --git a/tests/internal/FsmServiceHotReload.cpp b/tests/internal/FsmServiceHotReload.cpp new file mode 100644 index 0000000..0a93a66 --- /dev/null +++ b/tests/internal/FsmServiceHotReload.cpp @@ -0,0 +1,147 @@ +#include +#include +#include +#include +#include +#include +#include + +#include "ServiceInterface.hpp" + +#include +#include +#include +#include +#include +#include + +using Void::Coro::Task; +using Void::Fsm::MachineOptions; +using Void::Fsm::Step; + +#if defined(VOID_SERVICE_V1_PATH) && defined(VOID_SERVICE_V2_PATH) && \ + __has_include() + +namespace +{ + void install(const std::filesystem::path& src, + const std::filesystem::path& dst) + { + auto staging = dst; + staging += ".incoming"; + std::filesystem::copy_file( + src, staging, std::filesystem::copy_options::overwrite_existing); + std::filesystem::rename(staging, dst); + } + + // An FSM that drives the plugin-provided ICalc service: each Work step + // accumulates and loops until a target total is reached. It resolves + // the service every step, so it picks up a reloaded implementation. + class Accumulate : public Void::Fsm::Machine + { + public: + + struct Work : State { + Task run() override + { + auto& svc = service(); + const int total = svc.accumulate(1); + if (total >= 500) { + co_return succeed(total); + } + co_return next(); + } + }; + + Accumulate() { initial(); } // own worker + }; +} // namespace + +// A plugin provides the ICalc service; an FSM (via the orchestrator's +// registry) calls it continuously while the plugin is hot-reloaded v1<->v2 +// under load. The running total survives every migration and the FSM keeps +// progressing to completion. +Void::Testing::Test internal_fsm_service_hot_reload_under_load() +{ + Void::FileSystem::TempDir tmp{"void_svcplugin"}; + const auto so = tmp.path() / "calc.so"; + std::filesystem::copy_file(VOID_SERVICE_V1_PATH, so); + + Void::Fsm::Orchestrator orch; + Void::Plugin::PluginManager plugins; + Void::Testing::expect(plugins.load(so).has_value()); + + // Bind the plugin's service into the orchestrator's registry, with + // hot-reload re-binding. + Void::Service::PluginServiceBinding binding{ + plugins, orch.services(), "CalcPlugin"}; + Void::Testing::expect(binding.bind()); + + // Launch the FSM; it resolves ICalc each step. + auto handle = orch.launch(); + Void::Testing::expect(static_cast(handle)); + + // Hammer reloads v1<->v2 while the FSM runs. + std::atomic stop{false}; + std::thread reloader([&] { + int i = 0; + while (!stop.load(std::memory_order_relaxed)) { + const char* src = + (i % 2 == 0) ? VOID_SERVICE_V2_PATH : VOID_SERVICE_V1_PATH; + install(src, so); + if (plugins.reload("CalcPlugin").has_value()) { + (void)binding.bind(); // re-register the new instance + } + ++i; + std::this_thread::sleep_for(std::chrono::milliseconds{3}); + } + }); + + // Wait for the FSM to finish (it accumulates to >= 500). + for (int i = 0; i < 1000 && !handle.finished(); ++i) { + std::this_thread::sleep_for(std::chrono::milliseconds{2}); + } + stop.store(true); + reloader.join(); + + Void::Testing::expect(handle.status() == Void::Fsm::Status::Succeeded); + + // The accumulated total survived migrations: a fresh resolve sees a + // total at least as large as the FSM's completion threshold. + auto calc = orch.services().get(); + Void::Testing::expect(calc != nullptr); + Void::Testing::expect(calc->accumulate(0) >= 500); + + orch.stop_all(); +} + +// The seamless-swap path without load: bind v1, reload to v2, confirm the +// service the FSM resolves is now v2 with the v1 total migrated. +Void::Testing::Test internal_service_reload_migrates_and_swaps() +{ + Void::FileSystem::TempDir tmp{"void_svcplugin"}; + const auto so = tmp.path() / "calc.so"; + std::filesystem::copy_file(VOID_SERVICE_V1_PATH, so); + + Void::Service::ServiceRegistry registry; + Void::Plugin::PluginManager plugins; + Void::Testing::expect(plugins.load(so).has_value()); + + Void::Service::PluginServiceBinding binding{ + plugins, registry, "CalcPlugin"}; + Void::Testing::expect(binding.bind()); + + auto v1 = registry.get(); + Void::Testing::expect_eq(v1->version(), 1); + v1->accumulate(40); // total = 40 + + install(VOID_SERVICE_V2_PATH, so); + Void::Testing::expect(plugins.reload("CalcPlugin").has_value()); + Void::Testing::expect(binding.bind()); + + auto v2 = registry.get(); + Void::Testing::expect_eq(v2->version(), 2); // implementation swapped + Void::Testing::expect_eq(v2->accumulate(0), 40); // state migrated +} + +#endif // service plugins available diff --git a/tests/plugins/ServiceInterface.hpp b/tests/plugins/ServiceInterface.hpp new file mode 100644 index 0000000..e97b730 --- /dev/null +++ b/tests/plugins/ServiceInterface.hpp @@ -0,0 +1,24 @@ +#pragma once + +#include + +// Shared host/plugin interface for the service hot-reload tests. It +// derives Void::Service::IService so the host recovers it from the +// plugin's exported IService* by a single-inheritance static_cast (no +// dynamic_cast across the RTLD_LOCAL boundary). +namespace VoidTest +{ + class ICalc : public Void::Service::IService + { + public: + + /// Returns an accumulated value; each call adds `delta` to the + /// service's running total and returns the new total. The total + /// is the state migrated across plugin reloads. + virtual int accumulate(int delta) = 0; + + /// Schema version of this build (1 or 2) — lets tests confirm a + /// reload actually swapped the implementation. + [[nodiscard]] virtual int version() const = 0; + }; +} // namespace VoidTest diff --git a/tests/plugins/ServicePluginV1.cpp b/tests/plugins/ServicePluginV1.cpp new file mode 100644 index 0000000..7171049 --- /dev/null +++ b/tests/plugins/ServicePluginV1.cpp @@ -0,0 +1,116 @@ +#include "ServiceInterface.hpp" + +#include +#include + +#include +#include +#include +#include +#include + +// Service plugin, schema v1. The plugin object is the service: it derives +// IPlugin (for the loader) and ICalc (the host interface, which derives +// IService). State (the running total) survives reloads via the v2 state +// ABI, serialized with the reflection JSON serializer. + +namespace +{ + struct StateV1 { + int total = 0; + }; + + class CalcPlugin final : public Void::Plugin::IPlugin, + public VoidTest::ICalc + { + public: + + // IPlugin + [[nodiscard]] std::string_view name() const noexcept override + { + return "CalcPlugin"; + } + + // IService + [[nodiscard]] std::string_view service_name() const override + { + return "CalcPlugin"; + } + + // ICalc + int accumulate(int delta) override + { + return m_total.fetch_add(delta, std::memory_order_relaxed) + + delta; + } + [[nodiscard]] int version() const override { return 1; } + + std::atomic m_total{0}; + }; +} // namespace + +template <> struct Void::Json::StateTraits { + static constexpr std::uint32_t version = 1; +}; + +extern "C" { + +void* void_plugin_create() { return new CalcPlugin; } + +void void_plugin_destroy(void* p) { delete static_cast(p); } + +Void::Plugin::PluginInfo void_plugin_info() +{ + return { + .abi_version = Void::Plugin::ABI_VERSION, + .name = "CalcPlugin", + .plugin_version = "1.0.0", + .description = "Calc service plugin (schema v1)", + }; +} + +// Hand the host the IService subobject of the plugin's ICalc. +Void::Service::IService* void_plugin_service(void* instance) +{ + auto* self = static_cast(instance); + return static_cast( + static_cast(self)); +} + +std::uint32_t void_plugin_state_version() { return 1; } + +const char* void_plugin_serialize_state(void* instance) +{ + const auto* self = static_cast(instance); + const StateV1 state{.total = self->m_total.load(std::memory_order_relaxed)}; + const auto json = + Void::Json::serialize(Void::Json::to_versioned_json(state)); + char* out = static_cast(std::malloc(json.size() + 1)); + if (out != nullptr) { + std::memcpy(out, json.c_str(), json.size() + 1); + } + return out; +} + +void void_plugin_free_string(const char* s) +{ + std::free(const_cast(s)); // NOLINT +} + +int void_plugin_deserialize_state(void* instance, const char* json, + std::uint32_t /*from_version*/) +{ + auto* self = static_cast(instance); + const auto parsed = Void::Json::parse(json); + if (!parsed.has_value()) { + return 1; + } + const auto state = Void::Json::from_versioned_json(*parsed); + if (!state.has_value()) { + return 2; + } + self->m_total.store(state->total, std::memory_order_relaxed); + return 0; +} + +} // extern "C" diff --git a/tests/plugins/ServicePluginV2.cpp b/tests/plugins/ServicePluginV2.cpp new file mode 100644 index 0000000..dc6607a --- /dev/null +++ b/tests/plugins/ServicePluginV2.cpp @@ -0,0 +1,121 @@ +#include "ServiceInterface.hpp" + +#include +#include + +#include +#include +#include +#include +#include + +// Service plugin, schema v2. The plugin object is the service: it derives +// IPlugin (for the loader) and ICalc (the host interface, which derives +// IService). State (the running total) survives reloads via the v2 state +// ABI, serialized with the reflection JSON serializer. + +namespace +{ + struct StateV2 { + int total = 0; + }; + + class CalcPlugin final : public Void::Plugin::IPlugin, + public VoidTest::ICalc + { + public: + + // IPlugin + [[nodiscard]] std::string_view name() const noexcept override + { + return "CalcPlugin"; + } + + // IService + [[nodiscard]] std::string_view service_name() const override + { + return "CalcPlugin"; + } + + // ICalc + int accumulate(int delta) override + { + return m_total.fetch_add(delta, std::memory_order_relaxed) + + delta; + } + [[nodiscard]] int version() const override { return 2; } + + std::atomic m_total{0}; + }; +} // namespace + +template <> struct Void::Json::StateTraits { + static constexpr std::uint32_t version = 2; +}; + +extern "C" { + +void* void_plugin_create() { return new CalcPlugin; } + +void void_plugin_destroy(void* p) { delete static_cast(p); } + +Void::Plugin::PluginInfo void_plugin_info() +{ + return { + .abi_version = Void::Plugin::ABI_VERSION, + .name = "CalcPlugin", + .plugin_version = "2.0.0", + .description = "Calc service plugin (schema v2)", + }; +} + +// Hand the host the IService subobject of the plugin's ICalc. +Void::Service::IService* void_plugin_service(void* instance) +{ + auto* self = static_cast(instance); + return static_cast( + static_cast(self)); +} + +std::uint32_t void_plugin_state_version() { return 2; } + +const char* void_plugin_serialize_state(void* instance) +{ + const auto* self = static_cast(instance); + const StateV2 state{.total = self->m_total.load(std::memory_order_relaxed)}; + const auto json = + Void::Json::serialize(Void::Json::to_versioned_json(state)); + char* out = static_cast(std::malloc(json.size() + 1)); + if (out != nullptr) { + std::memcpy(out, json.c_str(), json.size() + 1); + } + return out; +} + +void void_plugin_free_string(const char* s) +{ + std::free(const_cast(s)); // NOLINT +} + +int void_plugin_deserialize_state(void* instance, const char* json, + std::uint32_t /*from_version*/) +{ + auto* self = static_cast(instance); + const auto parsed = Void::Json::parse(json); + if (!parsed.has_value()) { + return 1; + } + // Migrate v1 envelopes up to v2 (the `total` field is unchanged, so + // the step is identity — the running total carries across the swap). + Void::Json::MigrationChain migrations; + migrations.add(1, [](Void::Json::Value data) { return data; }); + const auto state = + Void::Json::from_versioned_json(*parsed, migrations); + if (!state.has_value()) { + return 2; + } + self->m_total.store(state->total, std::memory_order_relaxed); + return 0; +} + +} // extern "C"