diff --git a/include/Void/Fsm/Detail/Engine.hpp b/include/Void/Fsm/Detail/Engine.hpp new file mode 100644 index 0000000..5b2640d --- /dev/null +++ b/include/Void/Fsm/Detail/Engine.hpp @@ -0,0 +1,111 @@ +#pragma once + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Fsm::Detail +{ + /// Type-erased state. Concrete states derive Machine::State, which + /// derives this; run() is driven by the engine. + class StateBase + { + public: + + virtual ~StateBase() = default; + virtual Coro::Task run() = 0; + }; + + struct EventEnvelope { + const std::type_info* type{nullptr}; + std::any value; + }; + + /// Shared execution substrate for a machine and any machines it nests: + /// one executor + one worker thread + one typed event mailbox. A single + /// consumer (the worker, or the embedder via pump()) touches all + /// mailbox state, so state code runs lock-free and single-threaded; + /// cross-thread post() only enqueues. + class ExecutionContext + { + public: + + ExecutionContext() = default; + ~ExecutionContext(); + + ExecutionContext(const ExecutionContext&) = delete; + ExecutionContext& operator=(const ExecutionContext&) = delete; + + [[nodiscard]] Async::ManualExecutor& executor() noexcept + { + return m_executor; + } + + // ── events (post is the only cross-thread entry point) ──────── + void post(EventEnvelope env); + + // Mailbox ops — consumer thread only (called from awaiters that + // run on the executor, and from the worker drain). + [[nodiscard]] bool try_take(const std::type_info& type, + std::any& out); + void set_waiter(const std::type_info& type, + std::coroutine_handle<> cont, std::any* slot); + + // ── worker lifecycle ───────────────────────────────────────── + /// Spawn the worker thread (idempotent). + void start_worker(); + /// Mark finished and wake the worker so it can exit. + void finish(); + /// Stop and join the worker. + void stop(); + /// Join the worker without forcing finish (waits for the + /// driver to finish() on its own). + void join(); + [[nodiscard]] bool finished() const noexcept + { + return m_done.load(std::memory_order_acquire); + } + + /// Embedder-driven step: deliver queued events + run ready + /// coroutines. Returns work done count. Single consumer only. + std::size_t pump(); + + private: + + void deliver(EventEnvelope& env); + void run_loop(); + void wake() noexcept; + + Async::ManualExecutor m_executor; + Async::MpscQueue m_queue; + + std::unordered_map> m_buffers; + struct Waiter { + const std::type_info* type{nullptr}; + std::coroutine_handle<> cont{}; + std::any* slot{nullptr}; + }; + Waiter m_waiter; + + std::counting_semaphore<> m_wakeup{0}; + std::atomic m_sleeping{false}; + std::atomic m_done{false}; + std::atomic m_worker_started{false}; + std::once_flag m_worker_once; + std::thread m_worker; + }; + +} // namespace Void::Fsm::Detail diff --git a/include/Void/Fsm/Fsm.hpp b/include/Void/Fsm/Fsm.hpp new file mode 100644 index 0000000..1496f84 --- /dev/null +++ b/include/Void/Fsm/Fsm.hpp @@ -0,0 +1,468 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if __has_include() +#include +#define VOID_HAS_FSM_REFLECTION 1 +#endif + +namespace Void::Fsm +{ + /// Options for a Machine (namespace scope to dodge the GCC + /// nested-default-arg trap). + struct MachineOptions { + /// Spawn a worker thread on start(). When false, drive the machine + /// yourself with pump() (deterministic; used by most tests and by + /// nested children, which share the parent's worker). + bool own_worker = true; + }; + + // ── Machine ────────────────────────────────────────────────── + // + // Inheritance + coroutine workflow FSM. Derive it, declare states as + // nested structs deriving `State`, implement each state's async run() + // to return next() / succeed(...) / fail(...). States may co_await + // external events and nest child machines. + // + // class Login : public Void::Fsm::Machine { + // public: + // struct Idle : State { Coro::Task run() override { + // auto c = co_await await_event(); + // co_return next(); } }; + // struct Check : State { Coro::Task run() override { + // co_return service().ok() + // ? succeed(true) : fail("bad creds"); } }; + // Login() { initial(); add(); } + // }; + template class Machine + { + public: + + using result_type = ResultT; + using Options = MachineOptions; + using Outcome = std::expected; + + // ── State base ──────────────────────────────────────────────── + class State : public Detail::StateBase + { + public: + + [[nodiscard]] Machine& machine() const noexcept + { + return *m_machine; + } + + protected: + + /// Transition to another registered state. + template [[nodiscard]] Step next() const + { + return Step::transition(typeid(S)); + } + + /// Finish the machine successfully. + [[nodiscard]] Step succeed() const + requires std::is_void_v + { + return Step::success(std::any{}); + } + template + [[nodiscard]] Step succeed(V&& value) const + requires(!std::is_void_v) + { + return Step::success( + std::any{ResultT(std::forward(value))}); + } + + /// Finish the machine with a failure. + [[nodiscard]] Step fail(std::string message) const + { + return Step::failure(FsmError{std::move(message)}); + } + + /// Resolve a service from the injected registry. + template [[nodiscard]] I& service() const + { + return m_machine->template service(); + } + + /// Suspend until an event of type E is posted. + template [[nodiscard]] auto await_event() const + { + return m_machine->template await_event(); + } + + /// Run a child machine to completion and get its result. + template + [[nodiscard]] auto run_child(Args&&... args) const + { + return m_machine->template run_child( + std::forward(args)...); + } + + template [[nodiscard]] bool has_state() const + { + return m_machine->template has_state(); + } + + private: + + friend class Machine; + Machine* m_machine{nullptr}; + }; + + // ── construction ────────────────────────────────────────────── + explicit Machine(Options options = {}) : m_options(options) {} + + virtual ~Machine() { stop(); } + + Machine(const Machine&) = delete; + Machine& operator=(const Machine&) = delete; + + // ── registration (call from the derived ctor) ───────────────── + template void add() + { + static_assert(std::is_base_of_v, + "FSM state must derive Machine::State"); + const std::type_info& ti = typeid(S); + const std::type_index key{ti}; + if (m_factories.contains(key)) { + return; + } + const int idx = static_cast(m_names.size()); + m_index.emplace(key, idx); + m_names.push_back(state_name()); + m_name_to_type.emplace(m_names.back(), &ti); + m_factories.emplace( + key, [this]() -> std::unique_ptr { + auto s = std::make_unique(); + s->m_machine = this; + return s; + }); + } + + template void initial() + { + add(); + m_initial = &typeid(S); + } + + /// Conditionally register a state (dynamic machines). + template void add_if(bool condition) + { + if (condition) { + add(); + } + } + + template [[nodiscard]] bool has_state() const + { + return m_factories.contains(std::type_index{typeid(S)}); + } + + // ── service context ─────────────────────────────────────────── + void set_services(Service::ServiceRegistry& registry) noexcept + { + m_services = ®istry; + } + + template [[nodiscard]] I& service() const + { + return m_services->template require(); + } + + // ── lifecycle ───────────────────────────────────────────────── + void start() + { + if (m_status.load() != Status::Idle) { + return; + } + if (!m_ctx) { + m_ctx = std::make_shared(); + m_owns_ctx = true; + } + m_status.store(Status::Running); + Async::spawn(m_ctx->executor(), driver()); + if (m_options.own_worker && m_owns_ctx) { + m_ctx->start_worker(); + } + } + + /// Block until the machine finishes, returning its outcome. + /// With a worker, joins it. In embedder mode, drives the + /// machine to completion (returns early if it parks waiting + /// for an event that never arrives). Do not call from the + /// worker thread. + Outcome wait() + { + if (m_ctx) { + if (m_options.own_worker && m_owns_ctx) { + m_ctx->join(); + } else { + while (!finished()) { + if (m_ctx->pump() == 0 && !finished()) { + break; // parked on an unposted event + } + } + } + } + return take_outcome(); + } + + /// start() + wait(). + Outcome run_blocking() + { + start(); + return wait(); + } + + /// Drive a worker-less machine: deliver events + run ready + /// coroutines. Returns work done. Single consumer only. + std::size_t pump() { return m_ctx ? m_ctx->pump() : 0; } + + [[nodiscard]] bool finished() const noexcept + { + const auto s = m_status.load(); + return s == Status::Succeeded || s == Status::Failed; + } + + [[nodiscard]] Status status() const noexcept + { + return m_status.load(); + } + + void stop() + { + if (m_owns_ctx && m_ctx) { + m_ctx->stop(); + } + } + + // ── events ──────────────────────────────────────────────────── + template void post(E event) + { + if (!m_ctx) { + return; + } + m_ctx->post(Detail::EventEnvelope{&typeid(E), + std::any{std::move(event)}}); + } + + template [[nodiscard]] auto await_event() + { + struct Awaiter { + Detail::ExecutionContext* ctx; + std::any slot; + + [[nodiscard]] bool await_ready() + { + return ctx->try_take(typeid(E), slot); + } + void await_suspend(std::coroutine_handle<> h) + { + ctx->set_waiter(typeid(E), h, &slot); + } + [[nodiscard]] E await_resume() + { + return std::any_cast(std::move(slot)); + } + }; + return Awaiter{m_ctx.get(), {}}; + } + + // ── nesting ─────────────────────────────────────────────────── + template + [[nodiscard]] Coro::Task + run_child(Args&&... args) + { + Sub child{std::forward(args)...}; + child.attach(m_ctx, m_services); + co_return co_await child.drive(); + } + + // ── observation ─────────────────────────────────────────────── + [[nodiscard]] std::string current_state() const + { + const int idx = m_current.load(std::memory_order_acquire); + if (idx < 0 || idx >= static_cast(m_names.size())) { + return {}; + } + return m_names[static_cast(idx)]; + } + + // ── persistence ─────────────────────────────────────────────── + [[nodiscard]] Json::Value serialize() const + { + auto obj = Json::object(); + obj.as_object().emplace_back("state", + Json::Value{current_state()}); + Json::Value data = Json::object(); + on_serialize(data); + obj.as_object().emplace_back("data", std::move(data)); + return obj; + } + + [[nodiscard]] std::expected + restore(const Json::Value& state) + { + if (m_status.load() != Status::Idle) { + return std::unexpected{ + FsmError{"restore requires an un-started machine"}}; + } + const auto* st = state.find("state"); + if (st == nullptr || !st->is_string()) { + return std::unexpected{ + FsmError{"malformed machine state json"}}; + } + const auto it = m_name_to_type.find(st->as_string()); + if (it == m_name_to_type.end()) { + return std::unexpected{ + FsmError{"unknown state '" + st->as_string() + "'"}}; + } + m_initial = it->second; + if (const auto* data = state.find("data")) { + on_restore(*data); + } + return {}; + } + + protected: + + /// Override to snapshot derived FSM data into the "data" object + /// of serialize(), and to restore it. + virtual void on_serialize(Json::Value& /*data*/) const {} + virtual void on_restore(const Json::Value& /*data*/) {} + + private: + + template + friend class Machine; // run_child reaches child internals + + // Share a parent's execution context + services (nesting). + void attach(std::shared_ptr ctx, + Service::ServiceRegistry* services) + { + m_ctx = std::move(ctx); + m_owns_ctx = false; + if (services != nullptr) { + m_services = services; + } + m_status.store(Status::Running); + } + + template [[nodiscard]] std::string state_name() + { +#ifdef VOID_HAS_FSM_REFLECTION + return std::string{std::meta::identifier_of(^^S)}; +#else + return "state" + std::to_string(m_names.size()); +#endif + } + + void set_current(const std::type_info* type) + { + if (const auto it = m_index.find(std::type_index{*type}); + it != m_index.end()) { + m_current.store(it->second, std::memory_order_release); + } + } + + // The state loop. Builds each state, runs it, follows the + // returned Step. Runs on the execution context's executor. + Coro::Task drive() + { + const std::type_info* cur = m_initial; + if (cur == nullptr) { + co_return std::unexpected{FsmError{"no initial state"}}; + } + for (;;) { + const auto it = m_factories.find(std::type_index{*cur}); + if (it == m_factories.end()) { + co_return std::unexpected{ + FsmError{"transition to unregistered state"}}; + } + set_current(cur); + auto state = it->second(); + Step step = co_await state->run(); + switch (step.kind()) { + case Step::Kind::Transition: + cur = step.target(); + continue; + case Step::Kind::Success: + if constexpr (std::is_void_v) { + co_return Outcome{}; + } else { + co_return Outcome{std::any_cast( + std::move(step.result()))}; + } + case Step::Kind::Fail: + co_return std::unexpected{step.error()}; + } + } + } + + // Top-level driver: drives to completion, records the outcome, + // and signals the worker to wind down. + Coro::Task driver() + { + Outcome outcome = co_await drive(); + const bool ok = outcome.has_value(); + m_outcome.emplace(std::move(outcome)); + m_status.store(ok ? Status::Succeeded : Status::Failed, + std::memory_order_release); + if (m_owns_ctx) { + m_ctx->finish(); + } + } + + Outcome take_outcome() + { + if (m_outcome.has_value()) { + return std::move(*m_outcome); + } + return std::unexpected{FsmError{"machine did not finish"}}; + } + + Options m_options; + std::shared_ptr m_ctx; + bool m_owns_ctx{false}; + Service::ServiceRegistry* m_services{nullptr}; + + std::unordered_map< + std::type_index, + std::function()>> + m_factories; + std::unordered_map m_index; + std::vector m_names; + std::unordered_map + m_name_to_type; + const std::type_info* m_initial{nullptr}; + + std::atomic m_current{-1}; + std::atomic m_status{Status::Idle}; + std::optional m_outcome; + }; + +} // namespace Void::Fsm diff --git a/include/Void/Fsm/Step.hpp b/include/Void/Fsm/Step.hpp new file mode 100644 index 0000000..489602b --- /dev/null +++ b/include/Void/Fsm/Step.hpp @@ -0,0 +1,76 @@ +#pragma once + +#include +#include +#include +#include + +namespace Void::Fsm +{ + struct FsmError { + std::string message; + }; + + enum class Status { + Idle, // constructed, not started + Running, // worker active + Succeeded, // finished with a result + Failed // finished with an error + }; + + /// The outcome a state's run() returns: move to another state, finish + /// the machine with a result, or fail. Built only through the State + /// helpers (next() / succeed() / fail()). + class Step + { + public: + + enum class Kind { Transition, Success, Fail }; + + [[nodiscard]] static Step transition(const std::type_info& target) + { + Step s; + s.m_kind = Kind::Transition; + s.m_target = ⌖ + return s; + } + + [[nodiscard]] static Step success(std::any result) + { + Step s; + s.m_kind = Kind::Success; + s.m_result = std::move(result); + return s; + } + + [[nodiscard]] static Step failure(FsmError error) + { + Step s; + s.m_kind = Kind::Fail; + s.m_error = std::move(error); + return s; + } + + [[nodiscard]] Kind kind() const noexcept { return m_kind; } + + [[nodiscard]] const std::type_info* target() const noexcept + { + return m_target; + } + + [[nodiscard]] std::any& result() noexcept { return m_result; } + + [[nodiscard]] const FsmError& error() const noexcept + { + return m_error; + } + + private: + + Kind m_kind{Kind::Fail}; + const std::type_info* m_target{nullptr}; + std::any m_result; + FsmError m_error; + }; + +} // namespace Void::Fsm diff --git a/include/Void/Service/Registry.hpp b/include/Void/Service/Registry.hpp new file mode 100644 index 0000000..d818730 --- /dev/null +++ b/include/Void/Service/Registry.hpp @@ -0,0 +1,127 @@ +#pragma once + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Service +{ + /// Type-keyed service container: providers register an implementation + /// against an interface type, consumers resolve by that interface and + /// never name the concrete type — the core of the dependency-inversion + /// the orchestrator and FSMs rely on. + /// + /// registry.provide(std::make_shared()); + /// auto& clock = registry.require(); // no SystemClock dep + /// + /// Thread-safe. Reads (get/require/has) take a shared lock; they are + /// the hot path for running FSMs resolving services per step. + class ServiceRegistry + { + public: + + ServiceRegistry() = default; + ServiceRegistry(const ServiceRegistry&) = delete; + ServiceRegistry& operator=(const ServiceRegistry&) = delete; + + /// Register (or replace) the implementation for interface I. + /// If I derives IService, the instance joins the lifecycle. + template void provide(std::shared_ptr impl) + { + Entry entry; + entry.impl = std::shared_ptr(impl, impl.get()); + if constexpr (std::is_base_of_v) { + entry.service = static_cast(impl.get()); + } else { + // The interface I doesn't derive IService, but the + // concrete implementation might — recover the lifecycle + // aspect by cross-cast. + entry.service = dynamic_cast(impl.get()); + } + const std::type_index key{typeid(I)}; + std::unique_lock lock{m_mutex}; + if (!m_services.contains(key)) { + m_order.push_back(key); + } + m_services.insert_or_assign(key, std::move(entry)); + } + + /// Resolve I, or nullptr if not provided. + template [[nodiscard]] std::shared_ptr get() const + { + std::shared_lock lock{m_mutex}; + const auto it = m_services.find(std::type_index{typeid(I)}); + if (it == m_services.end()) { + return nullptr; + } + return std::static_pointer_cast(it->second.impl); + } + + /// Resolve I; throws std::runtime_error if not provided. + template [[nodiscard]] I& require() const + { + auto p = get(); + if (!p) { + throw std::runtime_error( + std::string{"ServiceRegistry: no service for '"} + + typeid(I).name() + "'"); + } + return *p; + } + + template [[nodiscard]] bool has() const + { + std::shared_lock lock{m_mutex}; + return m_services.contains(std::type_index{typeid(I)}); + } + + /// Call on_start() on every lifecycle service, registration + /// order. + void start_all() + { + std::shared_lock lock{m_mutex}; + for (const auto& key : m_order) { + if (auto* s = m_services.at(key).service) { + s->on_start(); + } + } + } + + /// Call on_stop() on every lifecycle service, reverse order. + void stop_all() + { + std::shared_lock lock{m_mutex}; + for (auto it = m_order.rbegin(); it != m_order.rend(); ++it) { + if (auto* s = m_services.at(*it).service) { + s->on_stop(); + } + } + } + + [[nodiscard]] std::size_t size() const + { + std::shared_lock lock{m_mutex}; + return m_services.size(); + } + + private: + + struct Entry { + std::shared_ptr impl; + IService* service = nullptr; // non-null iff I : IService + }; + + mutable std::shared_mutex m_mutex; + std::unordered_map m_services; + std::vector m_order; + }; + +} // namespace Void::Service diff --git a/include/Void/Service/Service.hpp b/include/Void/Service/Service.hpp new file mode 100644 index 0000000..25e1965 --- /dev/null +++ b/include/Void/Service/Service.hpp @@ -0,0 +1,27 @@ +#pragma once + +#include + +namespace Void::Service +{ + /// Base for services resolved through a ServiceRegistry by interface + /// type. Consumers depend only on an interface (which may but need not + /// derive IService); implementing IService additionally opts the + /// service into registry-driven lifecycle (start_all/stop_all). + class IService + { + public: + + virtual ~IService() = default; + + [[nodiscard]] virtual std::string_view service_name() const = 0; + + /// Called by ServiceRegistry::start_all(), in registration + /// order. + virtual void on_start() {} + + /// Called by ServiceRegistry::stop_all(), in reverse order. + virtual void on_stop() {} + }; + +} // namespace Void::Service diff --git a/src/Fsm/Engine.cpp b/src/Fsm/Engine.cpp new file mode 100644 index 0000000..f024ac9 --- /dev/null +++ b/src/Fsm/Engine.cpp @@ -0,0 +1,121 @@ +#include + +#include + +namespace Void::Fsm::Detail +{ + + ExecutionContext::~ExecutionContext() { stop(); } + + void ExecutionContext::post(EventEnvelope env) + { + m_queue.push(std::move(env)); + wake(); + } + + bool ExecutionContext::try_take(const std::type_info& type, std::any& out) + { + const auto it = m_buffers.find(std::type_index{type}); + if (it == m_buffers.end() || it->second.empty()) { + return false; + } + out = std::move(it->second.front()); + it->second.pop_front(); + return true; + } + + void ExecutionContext::set_waiter(const std::type_info& type, + std::coroutine_handle<> + cont, + std::any* slot) + { + m_waiter.type = &type; + m_waiter.cont = cont; + m_waiter.slot = slot; + } + + void ExecutionContext::deliver(EventEnvelope& env) + { + auto& buffer = m_buffers[std::type_index{*env.type}]; + buffer.push_back(std::move(env.value)); + + // Resume a matching waiter, if any. + if (m_waiter.type != nullptr && *m_waiter.type == *env.type && + !buffer.empty()) { + *m_waiter.slot = std::move(buffer.front()); + buffer.pop_front(); + auto cont = m_waiter.cont; + m_waiter = Waiter{}; + m_executor.post(cont); + } + } + + std::size_t ExecutionContext::pump() + { + std::size_t work = 0; + while (auto env = m_queue.try_pop()) { + deliver(*env); + ++work; + } + work += m_executor.drain(); + return work; + } + + void ExecutionContext::wake() noexcept + { + if (m_sleeping.exchange(false, std::memory_order_acq_rel)) { + m_wakeup.release(); + } + } + + void ExecutionContext::start_worker() + { + if (m_worker_started.load(std::memory_order_acquire)) { + return; + } + std::call_once(m_worker_once, [this] { + m_worker = std::thread([this] { run_loop(); }); + m_worker_started.store(true, std::memory_order_release); + }); + } + + void ExecutionContext::finish() + { + m_done.store(true, std::memory_order_release); + wake(); + } + + void ExecutionContext::stop() + { + m_done.store(true, std::memory_order_release); + wake(); + if (m_worker.joinable()) { + m_worker.join(); + } + } + + void ExecutionContext::join() + { + if (m_worker.joinable()) { + m_worker.join(); + } + } + + void ExecutionContext::run_loop() + { + for (;;) { + pump(); + if (m_done.load(std::memory_order_acquire)) { + return; + } + m_sleeping.store(true, std::memory_order_release); + if (!m_queue.empty() || m_done.load(std::memory_order_acquire)) { + m_sleeping.store(false, std::memory_order_release); + continue; + } + m_wakeup.acquire(); + m_sleeping.store(false, std::memory_order_release); + } + } + +} // namespace Void::Fsm::Detail diff --git a/src/Fsm/module.cmake b/src/Fsm/module.cmake new file mode 100644 index 0000000..cafde28 --- /dev/null +++ b/src/Fsm/module.cmake @@ -0,0 +1,3 @@ +void_add_module(Fsm + INTERNAL_DEPS Async Data Functional Log Service +) diff --git a/src/Service/module.cmake b/src/Service/module.cmake new file mode 100644 index 0000000..a59a95b --- /dev/null +++ b/src/Service/module.cmake @@ -0,0 +1,3 @@ +void_add_module(Service + INTERNAL_DEPS Functional Log +) diff --git a/tests/standalone/Fsm/Basic.cpp b/tests/standalone/Fsm/Basic.cpp new file mode 100644 index 0000000..3bc15c8 --- /dev/null +++ b/tests/standalone/Fsm/Basic.cpp @@ -0,0 +1,181 @@ +#include +#include +#include + +#include +#include + +using Void::Coro::Task; +using Void::Fsm::MachineOptions; +using Void::Fsm::Step; + +namespace +{ + // A linear workflow: Start -> Work (loops 3x) -> success(count). + class Counter : public Void::Fsm::Machine + { + public: + + int count = 0; + std::vector* log = nullptr; + + struct Start : State { + Task run() override + { + auto& m = static_cast(machine()); + if (m.log) { + m.log->push_back("start"); + } + co_return next(); + } + }; + + struct Work : State { + Task run() override + { + auto& m = static_cast(machine()); + ++m.count; + if (m.log) { + m.log->push_back("work" + std::to_string(m.count)); + } + if (m.count >= 3) { + co_return succeed(m.count); + } + co_return next(); + } + }; + + Counter() + : Void::Fsm::Machine(MachineOptions{.own_worker = false}) + { + initial(); + add(); + } + }; + + // A workflow that fails. + class Failing : public Void::Fsm::Machine + { + public: + + struct Boom : State { + Task run() override { co_return fail("kaboom"); } + }; + + Failing() + : Void::Fsm::Machine(MachineOptions{.own_worker = false}) + { + initial(); + } + }; +} // namespace + +Void::Testing::Test fsm_runs_to_success_with_result() +{ + std::vector log; + Counter fsm; + fsm.log = &log; + const auto outcome = fsm.run_blocking(); + + Void::Testing::expect(outcome.has_value()); + Void::Testing::expect_eq(*outcome, 3); + Void::Testing::expect(fsm.status() == Void::Fsm::Status::Succeeded); + + const std::vector expected{"start", "work1", "work2", "work3"}; + Void::Testing::expect(log == expected); +} + +Void::Testing::Test fsm_failure_outcome() +{ + Failing fsm; + const auto outcome = fsm.run_blocking(); + Void::Testing::expect(!outcome.has_value()); + Void::Testing::expect_eq(outcome.error().message, std::string{"kaboom"}); + Void::Testing::expect(fsm.status() == Void::Fsm::Status::Failed); +} + +Void::Testing::Test fsm_pump_drives_to_completion() +{ + Counter fsm; + fsm.start(); + Void::Testing::expect(!fsm.finished()); // driver queued, not yet run + fsm.pump(); // Start -> Work* -> success + Void::Testing::expect(fsm.finished()); + Void::Testing::expect_eq(*fsm.wait(), 3); +} + +Void::Testing::Test fsm_transition_to_unregistered_fails() +{ + struct Lonely : Void::Fsm::Machine { + struct Other : State { + Task run() override { co_return succeed(); } + }; + struct Start : State { + Task run() override { co_return next(); } + }; + Lonely() + : Void::Fsm::Machine(MachineOptions{.own_worker = false}) + { + initial(); // Other intentionally not registered + } + } fsm; + + const auto outcome = fsm.run_blocking(); + Void::Testing::expect(!outcome.has_value()); +} + +Void::Testing::Test fsm_void_result_succeeds() +{ + struct Trivial : Void::Fsm::Machine { + struct Done : State { + Task run() override { co_return succeed(); } + }; + Trivial() + : Void::Fsm::Machine(MachineOptions{.own_worker = false}) + { + initial(); + } + } fsm; + + const auto outcome = fsm.run_blocking(); + Void::Testing::expect(outcome.has_value()); +} + +Void::Testing::Test fsm_dynamic_state_registration() +{ + // Two configurations of the same machine type: with and without the + // optional Express state. + struct Flow : Void::Fsm::Machine { + bool express; + struct Express : State { + Task run() override { co_return succeed(99); } + }; + struct Normal : State { + Task run() override { co_return succeed(1); } + }; + struct Start : State { + Task run() override + { + auto& m = static_cast(machine()); + if (m.has_state()) { + co_return next(); + } + co_return next(); + } + }; + explicit Flow(bool e) + : Void::Fsm::Machine(MachineOptions{.own_worker = false}), + express(e) + { + initial(); + add(); + add_if(express); + } + }; + + Flow with{true}; + Void::Testing::expect_eq(*with.run_blocking(), 99); + + Flow without{false}; + Void::Testing::expect_eq(*without.run_blocking(), 1); +} diff --git a/tests/standalone/Fsm/Concurrency.cpp b/tests/standalone/Fsm/Concurrency.cpp new file mode 100644 index 0000000..59c5447 --- /dev/null +++ b/tests/standalone/Fsm/Concurrency.cpp @@ -0,0 +1,157 @@ +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +using Void::Coro::Task; +using Void::Fsm::MachineOptions; +using Void::Fsm::Step; + +namespace +{ + struct Tick { + int n; + }; + + // Sums many Tick events delivered from several threads, finishing when + // the running total reaches a target. Single consumer (the worker) so + // the total is race-free without the FSM holding any lock. + class Summer : public Void::Fsm::Machine + { + public: + + long long total = 0; + long long target; + + struct Run : State { + Task run() override + { + auto& m = static_cast(machine()); + while (m.total < m.target) { + auto t = co_await await_event(); + m.total += t.n; + } + co_return succeed(m.total); + } + }; + + explicit Summer(long long tgt) + : Void::Fsm::Machine(), target(tgt) + { + initial(); + } + }; + + // A service the FSM resolves through its injected context. + class IDoubler + { + public: + + virtual ~IDoubler() = default; + [[nodiscard]] virtual int twice(int x) const = 0; + }; + class Doubler final : public IDoubler + { + public: + + [[nodiscard]] int twice(int x) const override { return x * 2; } + }; +} // namespace + +// @tag stress, concurrency +Void::Testing::Test fsm_concurrent_event_posting() +{ + constexpr int producers = 6; + constexpr int per_producer = 5000; + const long long target = + static_cast(producers) * per_producer; // each Tick n=1 + + Summer fsm{target}; + fsm.start(); + + std::vector threads; + threads.reserve(producers); + for (int p = 0; p < producers; ++p) { + threads.emplace_back([&fsm] { + for (int i = 0; i < per_producer; ++i) { + fsm.post(Tick{1}); + } + }); + } + for (auto& t : threads) { + t.join(); + } + + const auto outcome = fsm.wait(); + Void::Testing::expect(outcome.has_value()); + Void::Testing::expect_eq(*outcome, target); +} + +// @tag concurrency +Void::Testing::Test fsm_current_state_reads_never_tear_under_load() +{ + Summer fsm{1'000'000}; + fsm.start(); + + std::atomic stop{false}; + std::atomic reads{0}; + bool sane = true; + std::vector readers; + for (int r = 0; r < 3; ++r) { + readers.emplace_back([&] { + while (!stop.load(std::memory_order_relaxed)) { + const auto name = fsm.current_state(); + if (!name.empty() && name != "Run") { + sane = false; + } + ++reads; + } + }); + } + + for (int i = 0; i < 200'000; ++i) { + fsm.post(Tick{1}); + } + fsm.post(Tick{1'000'000}); // push over target → finish + + const auto outcome = fsm.wait(); + stop = true; + for (auto& t : readers) { + t.join(); + } + Void::Testing::expect(outcome.has_value()); + Void::Testing::expect(sane); + Void::Testing::expect(reads.load() > 0); +} + +Void::Testing::Test fsm_resolves_service_through_context() +{ + struct Calc : Void::Fsm::Machine { + struct Go : State { + Task run() override + { + co_return succeed(service().twice(21)); + } + }; + Calc() + : Void::Fsm::Machine(MachineOptions{.own_worker = false}) + { + initial(); + } + }; + + Void::Service::ServiceRegistry registry; + registry.provide(std::make_shared()); + + Calc fsm; + fsm.set_services(registry); + const auto outcome = fsm.run_blocking(); + Void::Testing::expect(outcome.has_value()); + Void::Testing::expect_eq(*outcome, 42); +} diff --git a/tests/standalone/Fsm/Events.cpp b/tests/standalone/Fsm/Events.cpp new file mode 100644 index 0000000..5fb3659 --- /dev/null +++ b/tests/standalone/Fsm/Events.cpp @@ -0,0 +1,115 @@ +#include +#include +#include + +#include +#include +#include +#include + +using Void::Coro::Task; +using Void::Fsm::MachineOptions; +using Void::Fsm::Step; + +namespace +{ + struct Input { + int value; + }; + struct Stop { + }; + + // Waits for Input events, accumulating until a Stop event arrives. + class Accumulator : public Void::Fsm::Machine + { + public: + + int total = 0; + std::vector* order = nullptr; + + struct Waiting : State { + Task run() override + { + auto& m = static_cast(machine()); + // Two typed mailboxes: pull whichever arrives. + auto in = co_await await_event(); + m.total += in.value; + if (m.order) { + m.order->push_back(in.value); + } + if (in.value == 0) { + co_return succeed(m.total); + } + co_return next(); + } + }; + + explicit Accumulator(bool own_worker) + : Void::Fsm::Machine( + MachineOptions{.own_worker = own_worker}) + { + initial(); + } + }; +} // namespace + +Void::Testing::Test fsm_await_event_buffered_then_consumed() +{ + // Post before pumping — events buffer in the typed mailbox. + Accumulator fsm{false}; + fsm.start(); + fsm.post(Input{5}); + fsm.post(Input{7}); + fsm.post(Input{0}); // terminator + const auto outcome = fsm.run_blocking(); + Void::Testing::expect(outcome.has_value()); + Void::Testing::expect_eq(*outcome, 12); +} + +Void::Testing::Test fsm_await_event_preserves_order() +{ + std::vector order; + Accumulator fsm{false}; + fsm.order = ℴ + fsm.start(); + fsm.post(Input{1}); + fsm.post(Input{2}); + fsm.post(Input{3}); + fsm.post(Input{0}); + (void)fsm.run_blocking(); + const std::vector expected{1, 2, 3, 0}; + Void::Testing::expect(order == expected); +} + +// @tag integration +Void::Testing::Test fsm_await_event_cross_thread_with_worker() +{ + Accumulator fsm{true}; // own worker thread + fsm.start(); + + // Feed events from another thread while the worker awaits them. + std::thread producer([&] { + for (int i = 1; i <= 4; ++i) { + fsm.post(Input{i}); + std::this_thread::sleep_for(std::chrono::milliseconds{2}); + } + fsm.post(Input{0}); + }); + + const auto outcome = fsm.wait(); // blocks until Stop terminator + producer.join(); + Void::Testing::expect(outcome.has_value()); + Void::Testing::expect_eq(*outcome, 10); // 1+2+3+4 +} + +Void::Testing::Test fsm_current_state_during_event_wait() +{ + Accumulator fsm{false}; + fsm.start(); + fsm.pump(); // runs Waiting::run until it suspends on await_event + Void::Testing::expect_eq(fsm.current_state(), std::string{"Waiting"}); + Void::Testing::expect(!fsm.finished()); + fsm.post(Input{0}); + (void)fsm.wait(); + Void::Testing::expect(fsm.finished()); +} diff --git a/tests/standalone/Fsm/Nesting.cpp b/tests/standalone/Fsm/Nesting.cpp new file mode 100644 index 0000000..0ab3f3f --- /dev/null +++ b/tests/standalone/Fsm/Nesting.cpp @@ -0,0 +1,134 @@ +#include +#include +#include + +#include + +using Void::Coro::Task; +using Void::Fsm::MachineOptions; +using Void::Fsm::Step; + +namespace +{ + // Child machine: computes a value and succeeds. + class Subtotal : public Void::Fsm::Machine + { + public: + + int seed; + + struct Compute : State { + Task run() override + { + auto& m = static_cast(machine()); + co_return succeed(m.seed * 10); + } + }; + + explicit Subtotal(int s) + : Void::Fsm::Machine(MachineOptions{.own_worker = false}), + seed(s) + { + initial(); + } + }; + + // Child machine that fails. + class FailingChild : public Void::Fsm::Machine + { + public: + + struct Boom : State { + Task run() override { co_return fail("child boom"); } + }; + FailingChild() + : Void::Fsm::Machine(MachineOptions{.own_worker = false}) + { + initial(); + } + }; + + // Parent: enters a child, uses its result to decide the outcome. + class Parent : public Void::Fsm::Machine + { + public: + + struct Start : State { + Task run() override + { + auto a = co_await run_child(3); // 30 + auto b = co_await run_child(4); // 40 + if (!a.has_value() || !b.has_value()) { + co_return fail("child failed"); + } + co_return succeed(*a + *b); + } + }; + + Parent() + : Void::Fsm::Machine(MachineOptions{.own_worker = false}) + { + initial(); + } + }; + + class ParentOfFailure : public Void::Fsm::Machine + { + public: + + struct Start : State { + Task run() override + { + auto r = co_await run_child(); + if (!r.has_value()) { + co_return fail("propagated: " + r.error().message); + } + co_return succeed(*r); + } + }; + + ParentOfFailure() + : Void::Fsm::Machine(MachineOptions{.own_worker = false}) + { + initial(); + } + }; +} // namespace + +Void::Testing::Test fsm_nested_child_result_drives_parent() +{ + Parent fsm; + const auto outcome = fsm.run_blocking(); + Void::Testing::expect(outcome.has_value()); + Void::Testing::expect_eq(*outcome, 70); // 30 + 40 +} + +Void::Testing::Test fsm_nested_child_failure_propagates() +{ + ParentOfFailure fsm; + const auto outcome = fsm.run_blocking(); + Void::Testing::expect(!outcome.has_value()); + Void::Testing::expect_eq(outcome.error().message, + std::string{"propagated: child boom"}); +} + +// @tag integration +Void::Testing::Test fsm_nesting_with_worker_thread() +{ + Parent fsm{}; // embedder by default here + // Re-run as worker-driven to exercise the shared executor + worker. + struct WorkerParent : Void::Fsm::Machine { + struct Start : State { + Task run() override + { + auto a = co_await run_child(5); // 50 + co_return succeed(a.value_or(-1)); + } + }; + WorkerParent() { initial(); } // own worker + } wfsm; + const auto outcome = wfsm.run_blocking(); + Void::Testing::expect(outcome.has_value()); + Void::Testing::expect_eq(*outcome, 50); + (void)fsm; +} diff --git a/tests/standalone/Fsm/Serialize.cpp b/tests/standalone/Fsm/Serialize.cpp new file mode 100644 index 0000000..71694d3 --- /dev/null +++ b/tests/standalone/Fsm/Serialize.cpp @@ -0,0 +1,109 @@ +#include +#include +#include +#include + +#include + +using Void::Coro::Task; +using Void::Fsm::MachineOptions; +using Void::Fsm::Step; + +namespace +{ + // A machine that parks at a named state and exposes its data for + // serialize/restore. + class Pipeline : public Void::Fsm::Machine + { + public: + + struct Data { + int processed = 0; + std::string stage = "init"; + }; + Data data; + + struct Ingest : State { + Task run() override + { + co_await await_event(); // park here + co_return next(); + } + }; + struct Process : State { + Task run() override + { + auto& m = static_cast(machine()); + m.data.processed += 1; + co_return succeed(m.data.processed); + } + }; + + Pipeline() + : Void::Fsm::Machine(MachineOptions{.own_worker = false}) + { + initial(); + add(); + } + + protected: + + void on_serialize(Void::Json::Value& out) const override + { + out = Void::Json::to_json(data); + } + void on_restore(const Void::Json::Value& in) override + { + if (auto r = Void::Json::from_json(in); r.has_value()) { + data = std::move(*r); + } + } + }; +} // namespace + +Void::Testing::Test fsm_serialize_captures_state_and_data() +{ + Pipeline fsm; + fsm.data.processed = 5; + fsm.data.stage = "running"; + fsm.start(); + fsm.pump(); // enters Ingest, parks on await_event + + const auto json = fsm.serialize(); + Void::Testing::expect_eq(json["state"].as_string(), std::string{"Ingest"}); + Void::Testing::expect_eq(json["data"]["processed"].as_int(), + std::int64_t{5}); + Void::Testing::expect_eq(json["data"]["stage"].as_string(), + std::string{"running"}); + fsm.stop(); +} + +Void::Testing::Test fsm_restore_resumes_at_named_state() +{ + const auto saved = Void::Json::parse( + R"({"state":"Process","data":{"processed":9,"stage":"mid"}})"); + Void::Testing::expect(saved.has_value()); + + Pipeline fsm; + const auto r = fsm.restore(*saved); + Void::Testing::expect(r.has_value()); + + // Starts directly at Process (skipping Ingest's event wait), with the + // restored data → succeeds with processed+1. + const auto outcome = fsm.run_blocking(); + Void::Testing::expect(outcome.has_value()); + Void::Testing::expect_eq(*outcome, 10); +} + +Void::Testing::Test fsm_restore_rejects_unknown_state_and_running() +{ + const auto bogus = Void::Json::parse(R"({"state":"NoSuch","data":{}})"); + Void::Testing::expect(bogus.has_value()); + + Pipeline fsm; + Void::Testing::expect(!fsm.restore(*bogus).has_value()); + + fsm.start(); + Void::Testing::expect(!fsm.restore(*bogus).has_value()); // running + fsm.stop(); +} diff --git a/tests/standalone/Service/Registry.cpp b/tests/standalone/Service/Registry.cpp new file mode 100644 index 0000000..4fbff1d --- /dev/null +++ b/tests/standalone/Service/Registry.cpp @@ -0,0 +1,112 @@ +#include +#include +#include +#include + +#include +#include +#include + +using Void::Service::IService; +using Void::Service::ServiceRegistry; + +namespace +{ + // A plain interface (does not derive IService) — still resolvable. + class IClock + { + public: + + virtual ~IClock() = default; + [[nodiscard]] virtual int now() const = 0; + }; + + class FixedClock final : public IClock + { + public: + + explicit FixedClock(int t) : m_t(t) {} + [[nodiscard]] int now() const override { return m_t; } + int m_t; + }; + + // A lifecycle service (derives IService). + class IGreeter + { + public: + + virtual ~IGreeter() = default; + [[nodiscard]] virtual std::string greet() const = 0; + }; + + class Greeter final : public IService, public IGreeter + { + public: + + explicit Greeter(std::vector* log) : m_log(log) {} + [[nodiscard]] std::string_view service_name() const override + { + return "Greeter"; + } + void on_start() override { m_log->push_back("start"); } + void on_stop() override { m_log->push_back("stop"); } + [[nodiscard]] std::string greet() const override { return "hi"; } + std::vector* m_log; + }; +} // namespace + +Void::Testing::Test registry_provide_and_get() +{ + ServiceRegistry reg; + reg.provide(std::make_shared(42)); + auto clock = reg.get(); + Void::Testing::expect(clock != nullptr); + Void::Testing::expect_eq(clock->now(), 42); +} + +Void::Testing::Test registry_missing_get_is_null_require_throws() +{ + ServiceRegistry reg; + Void::Testing::expect(reg.get() == nullptr); + Void::Testing::expect(!reg.has()); + bool threw = false; + try { + (void)reg.require(); + } catch (const std::exception&) { + threw = true; + } + Void::Testing::expect(threw); +} + +Void::Testing::Test registry_require_returns_reference() +{ + ServiceRegistry reg; + reg.provide(std::make_shared(7)); + Void::Testing::expect_eq(reg.require().now(), 7); + Void::Testing::expect(reg.has()); +} + +Void::Testing::Test registry_replace_provider() +{ + ServiceRegistry reg; + reg.provide(std::make_shared(1)); + reg.provide(std::make_shared(2)); + Void::Testing::expect_eq(reg.require().now(), 2); + Void::Testing::expect_eq(reg.size(), std::size_t{1}); +} + +Void::Testing::Test registry_lifecycle_order() +{ + std::vector log; + ServiceRegistry reg; + reg.provide(std::make_shared(&log)); + reg.start_all(); + reg.stop_all(); + Void::Testing::expect_eq(log.size(), std::size_t{2}); + Void::Testing::expect_eq(log[0], std::string{"start"}); + Void::Testing::expect_eq(log[1], std::string{"stop"}); + + // Resolvable through the IGreeter interface. + Void::Testing::expect_eq(reg.require().greet(), + std::string{"hi"}); +}