diff --git a/include/Void/Fsm/Detail/Awaiter.hpp b/include/Void/Fsm/Detail/Awaiter.hpp new file mode 100644 index 0000000..88f719a --- /dev/null +++ b/include/Void/Fsm/Detail/Awaiter.hpp @@ -0,0 +1,58 @@ +#pragma once + +#include + +#include +#include +#include +#include +#include +#include + +namespace Void::Fsm::Detail +{ + /// One awaiter for every "wait for an event (optionally with a deadline)" + /// operation on a machine. `Storage` is the type-list container (a + /// std::array for fixed sets, a std::vector for dynamic ones); `Resume` is + /// the projection `(EventEnvelope&&, bool timed_out) -> R` that shapes the + /// awaited value (the matched event, an optional on timeout, a variant, + /// …). Built on ExecutionContext::{try_take_any,set_waiter}. + template struct EventAwaiter { + ExecutionContext* ctx; + Storage types; + EventEnvelope env; + bool timed_out{false}; + std::optional deadline; + Resume resume; + + [[nodiscard]] bool await_ready() + { + return ctx->try_take_any(span(), env); + } + void await_suspend(std::coroutine_handle<> h) + { + ctx->set_waiter(span(), h, &env, &timed_out, deadline); + } + [[nodiscard]] decltype(auto) await_resume() + { + return resume(std::move(env), timed_out); + } + + private: + + [[nodiscard]] std::span span() const + { + return std::span{types}; + } + }; + + template + [[nodiscard]] auto make_event_awaiter( + ExecutionContext* ctx, Storage types, + std::optional deadline, + Resume resume) + { + return EventAwaiter{ + ctx, std::move(types), {}, false, deadline, std::move(resume)}; + } +} // namespace Void::Fsm::Detail diff --git a/include/Void/Fsm/Detail/Introspect.hpp b/include/Void/Fsm/Detail/Introspect.hpp new file mode 100644 index 0000000..165ed91 --- /dev/null +++ b/include/Void/Fsm/Detail/Introspect.hpp @@ -0,0 +1,49 @@ +#pragma once + +#include +#include +#include + +namespace Void::Fsm +{ + /// A declarable transition edge (from a reactive state's table). + struct EdgeInfo { + std::string event; // event type name, or "(timeout)" + std::string target; // target state, "(success)"/"(fail)" + bool guarded{false}; + }; + + /// A registered state plus the edges that are statically knowable + /// (reactive states only; imperative run()-chosen edges are not). + struct StateInfo { + std::string name; + bool reactive{false}; + bool initial{false}; + std::vector edges; + }; + + namespace Detail + { + /// Render a state description as a Mermaid `stateDiagram-v2` string. + [[nodiscard]] inline std::string + to_mermaid(std::span states) + { + std::string out = "stateDiagram-v2\n"; + for (const auto& s : states) { + if (s.initial) { + out += " [*] --> " + s.name + "\n"; + } + } + for (const auto& s : states) { + for (const auto& e : s.edges) { + out += " " + s.name + " --> " + e.target + " : " + e.event; + if (e.guarded) { + out += " [guard]"; + } + out += "\n"; + } + } + return out; + } + } // namespace Detail +} // namespace Void::Fsm diff --git a/include/Void/Fsm/Detail/Reactive.hpp b/include/Void/Fsm/Detail/Reactive.hpp new file mode 100644 index 0000000..b109682 --- /dev/null +++ b/include/Void/Fsm/Detail/Reactive.hpp @@ -0,0 +1,206 @@ +#pragma once + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +// The declarative transition DSL for reactive states, lifted out of the +// Machine template so the core stays small. Every type is parameterised by the +// owning machine's `Derived` (guards/actions take `Derived&`) and `ResultT` +// (finish() carries the machine's result). Machine::Reactive aliases these and +// the engine drives them; see include/Void/Fsm/Machine.hpp. + +namespace Void::Fsm::Detail +{ + namespace Coro = Void::Coro; + + /// One declared transition: event type, optional guard/action, the Step to + /// take, plus names for introspection. + template struct EventEntry { + const std::type_info* type{nullptr}; + std::function guard; + std::function(Derived&, const std::any&)> action; + Step step; + std::string event_name; // for introspection + std::string target_name; // for introspection + }; + + /// A reactive state's full transition table (events + an optional timeout). + template struct TransitionTable { + std::vector> events; + bool has_timeout{false}; + std::chrono::steady_clock::duration timeout_after{}; + Step timeout_step; + std::string timeout_target_name; + }; + + /// Fluent builder for one event row: `on.event().guard(..).action(..) + /// .to()` (or `.finish(v)` / `.fail(msg)`). + template class EventClause + { + public: + + explicit EventClause(TransitionTable& table) + : m_table(&table) + { + } + + EventClause& guard(std::function g) + { + m_guard = std::move(g); + return *this; + } + + EventClause& + action(std::function(Derived&, const E&)> a) + { + m_action = std::move(a); + return *this; + } + + EventClause& action(std::function a) + { + m_action = [a = std::move(a)](Derived& d, + const E& e) -> Coro::Task { + a(d, e); + co_return; + }; + return *this; + } + + template void to() + { + if constexpr (requires { typename Derived::States; }) { + static_assert(Derived::States::template contains(), + "to: S is not in this machine's " + "States<...> list"); + } + commit(Step::transition(typeid(S)), type_name()); + } + + void finish() + requires std::is_void_v + { + commit(Step::success(std::any{}), "(success)"); + } + template + void finish(V&& value) + requires(!std::is_void_v) + { + commit(Step::success(std::any{ResultT(std::forward(value))}), + "(success)"); + } + + void fail(std::string message) + { + commit(Step::failure(FsmError{std::move(message)}), "(fail)"); + } + + private: + + void commit(Step step, std::string target) + { + EventEntry entry; + entry.type = &typeid(E); + if (m_guard) { + entry.guard = [g = std::move(m_guard)](Derived& d, + const std::any& a) { + return g(d, std::any_cast(a)); + }; + } + if (m_action) { + entry.action = + [a = std::move(m_action)]( + Derived& d, + const std::any& any) -> Coro::Task { + co_await a(d, std::any_cast(any)); + }; + } + entry.step = std::move(step); + entry.event_name = type_name(); + entry.target_name = std::move(target); + m_table->events.push_back(std::move(entry)); + } + + TransitionTable* m_table; + std::function m_guard; + std::function(Derived&, const E&)> m_action; + }; + + /// Fluent builder for the timeout row: `on.after(d).to()` / `.fail(..)`. + template class AfterClause + { + public: + + AfterClause(TransitionTable& table, + std::chrono::steady_clock::duration after) + : m_table(&table), m_after(after) + { + } + + template void to() + { + if constexpr (requires { typename Derived::States; }) { + static_assert(Derived::States::template contains(), + "after().to: S not in States<...>"); + } + m_table->has_timeout = true; + m_table->timeout_after = m_after; + m_table->timeout_step = Step::transition(typeid(S)); + m_table->timeout_target_name = type_name(); + } + + void fail(std::string message) + { + m_table->has_timeout = true; + m_table->timeout_after = m_after; + m_table->timeout_step = + Step::failure(FsmError{std::move(message)}); + m_table->timeout_target_name = "(fail)"; + } + + private: + + TransitionTable* m_table; + std::chrono::steady_clock::duration m_after; + }; + + /// Entry point handed to `transitions(TransitionBuilder& on)`. + template class TransitionBuilder + { + public: + + explicit TransitionBuilder(TransitionTable& table) + : m_table(&table) + { + } + + template + [[nodiscard]] EventClause event() + { + return EventClause{*m_table}; + } + + template + [[nodiscard]] AfterClause + after(std::chrono::duration d) + { + return AfterClause{ + *m_table, std::chrono::duration_cast< + std::chrono::steady_clock::duration>(d)}; + } + + private: + + TransitionTable* m_table; + }; +} // namespace Void::Fsm::Detail diff --git a/include/Void/Fsm/Detail/TypeName.hpp b/include/Void/Fsm/Detail/TypeName.hpp new file mode 100644 index 0000000..6035fc5 --- /dev/null +++ b/include/Void/Fsm/Detail/TypeName.hpp @@ -0,0 +1,26 @@ +#pragma once + +#include +#include + +#if __has_include() +#include +#ifndef VOID_HAS_FSM_REFLECTION +#define VOID_HAS_FSM_REFLECTION 1 +#endif +#endif + +namespace Void::Fsm::Detail +{ + /// Stable display name for a type — P2996 `identifier_of` when available + /// (GCC `-freflection`), else the mangled `typeid` name. Used for state / + /// event names in the reactive DSL and introspection. + template [[nodiscard]] inline std::string type_name() + { +#ifdef VOID_HAS_FSM_REFLECTION + return std::string{std::meta::identifier_of(^^T)}; +#else + return typeid(T).name(); +#endif + } +} // namespace Void::Fsm::Detail diff --git a/include/Void/Fsm/Fsm.hpp b/include/Void/Fsm/Fsm.hpp index b3b68ce..f13710e 100644 --- a/include/Void/Fsm/Fsm.hpp +++ b/include/Void/Fsm/Fsm.hpp @@ -1,1196 +1,15 @@ #pragma once -#include -#include -#include -#include -#include -#include -#include - -#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 -{ - /// Compile-time list of a machine's states. Declare it in the derived - /// machine to auto-register every state and enable compile-time - /// validation of next() targets: - /// using States = Void::Fsm::States; - /// The first entry is the initial state unless `using Initial = S;`. - template struct States { - static constexpr std::size_t size = sizeof...(Ss); - - template static constexpr bool contains() - { - return (std::is_same_v || ...); - } - }; - - /// Options for a Machine (namespace scope to dodge the GCC - /// nested-default-arg trap). - struct MachineOptions { - bool own_worker = true; - }; - - /// A transition record handed to observers. - struct Transition { - std::string from; - std::string to; - std::uint64_t step{0}; - }; - - // ── Machine ───────────────────────────────────────── - // - // Inheritance + coroutine workflow FSM, CRTP for typed access. Derive - // it, declare states as nested structs deriving `State`, list them in - // `using States = Fsm::States<...>`, and implement each state's async - // run() to return next() / succeed(...) / fail(...). States reach - // their owning machine (and its data + sub-methods) via self(). - // - // class Login : public Void::Fsm::Machine { - // public: - // int attempts = 0; - // struct Check : State { - // Coro::Task run() override { - // if (++self().attempts > 3) co_return fail("locked"); - // co_return self().service().ok() ? succeed(true) - // : next(); - // } - // }; - // using States = Void::Fsm::States; - // }; - template class Machine - { - public: - - using result_type = ResultT; - using Options = MachineOptions; - using Outcome = std::expected; - - // ── State base ──────────────────────────────────────────────── - class State : public Detail::StateBase - { - public: - - /// Typed access to the owning machine — no static_cast. - [[nodiscard]] Derived& self() const noexcept - { - return *static_cast(m_machine); - } - - [[nodiscard]] Machine& machine() const noexcept - { - return *m_machine; - } - - protected: - - /// Transition to another state. Validated at compile - /// time when the machine declares `using States`. - template [[nodiscard]] Step next() const - { - if constexpr (requires { typename Derived::States; }) { - static_assert( - Derived::States::template contains(), - "next: S is not in this machine's " - "States<...> list"); - } - return Step::transition(typeid(S)); - } - - /// Transition to a state registered dynamically - /// (add()/add_if()), skipping the static check. - template - [[nodiscard]] Step next_dynamic() const - { - return Step::transition(typeid(S)); - } - - /// Route to a fallback state if `step` is a failure, - /// otherwise pass it through — for error policies: - /// co_return next_or(co_await try_work()); - template - [[nodiscard]] Step next_or(Step step) const - { - if (step.kind() == Step::Kind::Fail) { - return next(); - } - return step; - } - - /// Suspend for `duration` (timer-driven), then resume. - template - [[nodiscard]] auto - delay(std::chrono::duration d) const - { - return m_machine->delay(d); - } - - /// Retry an async sub-step up to `times`, waiting - /// `backoff` between attempts. `attempt` returns - /// Coro::Task (true = success). Returns whether it - /// eventually succeeded. - template - [[nodiscard]] Coro::Task - with_retry(int times, - std::chrono::duration - backoff, - Fn attempt) const - { - for (int i = 0; i < times; ++i) { - if (co_await attempt()) { - co_return true; - } - if (i + 1 < times) { - co_await m_machine->delay(backoff); - } - } - co_return false; - } - - [[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))}); - } - - [[nodiscard]] Step fail(std::string message) const - { - return Step::failure(FsmError{std::move(message)}); - } - - template [[nodiscard]] I& service() const - { - return m_machine->template service(); - } - - template [[nodiscard]] auto await_event() const - { - return m_machine->template await_event(); - } - - /// Await E or time out (nullopt on timeout). - template - [[nodiscard]] auto await_event_for( - std::chrono::duration d) const - { - return m_machine->template await_event_for(d); - } - - template - [[nodiscard]] auto run_child(Args&&... args) const - { - return m_machine->template run_child( - std::forward(args)...); - } - - /// Enter a child region (composite sub-state): a nested - /// machine sharing this machine's executor, event mailbox - /// and services. This state's on_enter/on_exit wrap it, and - /// state_path() reports the parent→child chain while it - /// runs. Map the child's Outcome to a sibling transition: - /// auto r = co_await run_region(); - /// co_return r ? next() : next(); - template - [[nodiscard]] auto run_region(Args&&... args) const - { - return m_machine->template run_region( - std::forward(args)...); - } - - /// Await whichever of several event types arrives first, - /// yielding a std::variant. Handles multiple events - /// at one level (e.g. a parent watching Cancel alongside a - /// child region's own events). - template - [[nodiscard]] auto await_any() const - { - return m_machine->template await_any(); - } - - template [[nodiscard]] bool has_state() const - { - return m_machine->template has_state(); - } - - private: - - friend class Machine; - Machine* m_machine{nullptr}; - }; - - // ── reactive (declarative) states ───────────────────────────── - // - // A reactive state declares a transition table instead of an - // imperative run(): it waits for the declared events (or a - // timeout), checks guards in order, runs actions, and - // transitions. Mix freely with imperative State subclasses. - // - // struct Idle : Reactive { - // void transitions(TransitionBuilder& on) override { - // on.event().guard([](Idle& s, const Go& g){...}) - // .action([](Idle& s, const Go&){...}) - // .to(); - // on.event().to(); - // on.after(5s).to(); - // } - // }; - - struct EventEntry { - const std::type_info* type{nullptr}; - std::function guard; - std::function(Derived&, const std::any&)> - action; - Step step; - std::string event_name; // for introspection - std::string target_name; // for introspection - }; - - struct TransitionTable { - std::vector events; - bool has_timeout{false}; - std::chrono::steady_clock::duration timeout_after{}; - Step timeout_step; - std::string timeout_target_name; - }; - - template class EventClause - { - public: - - explicit EventClause(TransitionTable& table) - : m_table(&table) - { - } - - EventClause& - guard(std::function g) - { - m_guard = std::move(g); - return *this; - } - - EventClause& action( - std::function(Derived&, const E&)> a) - { - m_action = std::move(a); - return *this; - } - - EventClause& - action(std::function a) - { - m_action = - [a = std::move(a)](Derived& d, - const E& e) -> Coro::Task { - a(d, e); - co_return; - }; - return *this; - } - - template void to() - { - if constexpr (requires { typename Derived::States; }) { - static_assert( - Derived::States::template contains(), - "to: S is not in this machine's " - "States<...> list"); - } - commit(Step::transition(typeid(S)), - Machine::template state_type_name()); - } - - void finish() - requires std::is_void_v - { - commit(Step::success(std::any{}), "(success)"); - } - template - void finish(V&& value) - requires(!std::is_void_v) - { - commit(Step::success( - std::any{ResultT(std::forward(value))}), - "(success)"); - } - - void fail(std::string message) - { - commit(Step::failure(FsmError{std::move(message)}), - "(fail)"); - } - - private: - - void commit(Step step, std::string target) - { - EventEntry entry; - entry.type = &typeid(E); - if (m_guard) { - entry.guard = [g = std::move(m_guard)]( - Derived& d, const std::any& a) { - return g(d, std::any_cast(a)); - }; - } - if (m_action) { - entry.action = - [a = std::move(m_action)]( - Derived& d, - const std::any& any) -> Coro::Task { - co_await a(d, std::any_cast(any)); - }; - } - entry.step = std::move(step); - entry.event_name = - Machine::template state_type_name(); - entry.target_name = std::move(target); - m_table->events.push_back(std::move(entry)); - } - - TransitionTable* m_table; - std::function m_guard; - std::function(Derived&, const E&)> - m_action; - }; - - class AfterClause - { - public: - - AfterClause(TransitionTable& table, - std::chrono::steady_clock::duration after) - : m_table(&table), m_after(after) - { - } - - template void to() - { - if constexpr (requires { typename Derived::States; }) { - static_assert( - Derived::States::template contains(), - "after().to: S not in States<...>"); - } - m_table->has_timeout = true; - m_table->timeout_after = m_after; - m_table->timeout_step = Step::transition(typeid(S)); - m_table->timeout_target_name = - Machine::template state_type_name(); - } - - void fail(std::string message) - { - m_table->has_timeout = true; - m_table->timeout_after = m_after; - m_table->timeout_step = - Step::failure(FsmError{std::move(message)}); - m_table->timeout_target_name = "(fail)"; - } - - private: - - TransitionTable* m_table; - std::chrono::steady_clock::duration m_after; - }; - - class TransitionBuilder - { - public: - - explicit TransitionBuilder(TransitionTable& table) - : m_table(&table) - { - } - - template [[nodiscard]] EventClause event() - { - return EventClause{*m_table}; - } - - template - [[nodiscard]] AfterClause - after(std::chrono::duration d) - { - return AfterClause{ - *m_table, - std::chrono::duration_cast< - std::chrono::steady_clock::duration>(d)}; - } - - private: - - TransitionTable* m_table; - }; - - class Reactive : public State - { - public: - - [[nodiscard]] Detail::StateKind - kind() const noexcept override - { - return Detail::StateKind::Reactive; - } - - /// Declare this state's event/timeout transitions. - virtual void transitions(TransitionBuilder& on) = 0; - - /// Build this state's table without running it — used by - /// describe()/to_mermaid() for introspection. - void collect(TransitionTable& table) - { - TransitionBuilder builder{table}; - transitions(builder); - } - - Coro::Task run() final - { - TransitionTable table; - collect(table); - std::vector types; - types.reserve(table.events.size()); - for (const auto& e : table.events) { - types.push_back(e.type); - } - for (;;) { - std::optional - deadline; - if (table.has_timeout) { - deadline = std::chrono::steady_clock::now() + - table.timeout_after; - } - auto ev = co_await this->machine().await_any_event( - types, deadline); - if (!ev) { - co_return std::move(table.timeout_step); - } - Derived& d = this->self(); - bool matched = false; - for (auto& e : table.events) { - if (*e.type != *ev->type) { - continue; - } - if (e.guard && !e.guard(d, ev->value)) { - continue; - } - if (e.action) { - co_await e.action(d, ev->value); - } - co_return std::move(e.step); - } - (void)matched; // unmatched event is dropped - } - } - }; - - // ── construction ────────────────────────────────────────────── - explicit Machine(Options options = {}) : m_options(options) - { - if constexpr (requires { typename Derived::States; }) { - register_states(typename Derived::States{}); - if constexpr (requires { typename Derived::Initial; }) { - m_initial = &typeid(typename Derived::Initial); - } else { - m_initial = first_type(typename Derived::States{}); - } - } - } - - virtual ~Machine() { stop(); } - - Machine(const Machine&) = delete; - Machine& operator=(const Machine&) = delete; - - // ── registration ────────────────────────────────────────────── - 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); - } - - 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(); - } - - // ── observability ───────────────────────────────────────────── - /// Register a read-only observer fired on every transition - /// (and on the initial entry). Replaces any prior observer. - void observe(std::function observer) - { - m_observer = std::move(observer); - } - - /// Transition middleware. `before(transition)` fires as a state - /// is entered (after the state changes, before it runs); - /// `after(state_name)` fires once that state finishes running. - /// Interceptors run in registration order — for logging, - /// metrics, validation around transitions. - struct Interceptor { - std::function before; - std::function after; - }; - void add_interceptor(Interceptor interceptor) - { - m_interceptors.push_back(std::move(interceptor)); - } - - // ── 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(); - } - } - - 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; - } - } - } - } - return take_outcome(); - } - - Outcome run_blocking() - { - start(); - return wait(); - } - - 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::array types; - Detail::EventEnvelope env; - - [[nodiscard]] bool await_ready() - { - return ctx->try_take_any(types, env); - } - void await_suspend(std::coroutine_handle<> h) - { - ctx->set_waiter(types, h, &env, nullptr, - std::nullopt); - } - [[nodiscard]] E await_resume() - { - return std::any_cast(std::move(env.value)); - } - }; - return Awaiter{m_ctx.get(), {&typeid(E)}, {}}; - } - - /// Await an event of type E or time out after `duration`; - /// returns std::nullopt on timeout. - template - [[nodiscard]] auto - await_event_for(std::chrono::duration duration) - { - struct Awaiter { - Detail::ExecutionContext* ctx; - std::array types; - Detail::EventEnvelope env; - bool timed_out{false}; - std::chrono::steady_clock::time_point deadline; - - [[nodiscard]] bool await_ready() - { - return ctx->try_take_any(types, env); - } - void await_suspend(std::coroutine_handle<> h) - { - ctx->set_waiter(types, h, &env, &timed_out, - deadline); - } - [[nodiscard]] std::optional await_resume() - { - if (timed_out) { - return std::nullopt; - } - return std::any_cast(std::move(env.value)); - } - }; - return Awaiter{m_ctx.get(), - {&typeid(E)}, - {}, - false, - std::chrono::steady_clock::now() + duration}; - } - - /// Await any of several event types (optional deadline); used - /// by reactive states. Returns the matched envelope or nullopt - /// on timeout. - [[nodiscard]] auto await_any_event( - std::vector types, - std::optional deadline) - { - struct Awaiter { - Detail::ExecutionContext* ctx; - std::vector types; - Detail::EventEnvelope env; - bool timed_out{false}; - std::optional - deadline; - - [[nodiscard]] bool await_ready() - { - return ctx->try_take_any(types, env); - } - void await_suspend(std::coroutine_handle<> h) - { - ctx->set_waiter(types, h, &env, &timed_out, - deadline); - } - [[nodiscard]] std::optional - await_resume() - { - if (timed_out) { - return std::nullopt; - } - return std::move(env); - } - }; - return Awaiter{ - m_ctx.get(), std::move(types), {}, false, deadline}; - } - - /// Typed multi-event await: suspend until one of `Es...` arrives, - /// returning it as std::variant. Lets one state react to - /// several event types (parent-level handling for child regions). - template [[nodiscard]] auto await_any() - { - struct Awaiter { - Detail::ExecutionContext* ctx; - std::array types; - Detail::EventEnvelope env; - - [[nodiscard]] bool await_ready() - { - return ctx->try_take_any(types, env); - } - void await_suspend(std::coroutine_handle<> h) - { - ctx->set_waiter(types, h, &env, nullptr, - std::nullopt); - } - [[nodiscard]] std::variant await_resume() - { - std::optional> out; - ((env.type != nullptr && *env.type == typeid(Es) - ? (out.emplace(std::in_place_type, - std::any_cast( - std::move(env.value))), - true) - : false) || - ...); - return std::move(*out); - } - }; - return Awaiter{m_ctx.get(), {(&typeid(Es))...}, {}}; - } - - /// Suspend for `duration`, then resume (timer-driven). - template - [[nodiscard]] auto delay(std::chrono::duration d) - { - struct Awaiter { - Detail::ExecutionContext* ctx; - std::chrono::steady_clock::time_point deadline; - - [[nodiscard]] bool await_ready() const noexcept - { - return false; - } - void await_suspend(std::coroutine_handle<> h) - { - ctx->add_timer(deadline, [c = ctx, h] { - c->executor().post(h); - }); - } - void await_resume() const noexcept {} - }; - return Awaiter{m_ctx.get(), - std::chrono::steady_clock::now() + d}; - } - - // ── 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(); - } - - /// Composite sub-state: run `Sub` as a child region sharing this - /// machine's executor, event mailbox and services, and expose its - /// active state through this machine's state_path() while it runs - /// (parent→child chain). Returns the child's Outcome, which the - /// caller maps to a sibling transition. The calling state's - /// on_enter/on_exit naturally wrap the region. - template - [[nodiscard]] Coro::Task - run_region(Args&&... args) - { - Sub child{std::forward(args)...}; - child.attach(m_ctx, m_services); - m_region_probe = [&child] { return child.state_path(); }; - auto outcome = co_await child.drive(); - m_region_probe = nullptr; - co_return std::move(outcome); - } - - // ── 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)]; - } - - /// Active state chain (root → leaf). When a child region is - /// running (run_region), its path is appended, so a composite - /// state reports {composite, ...child leaf}. Unlike the lock-free - /// current_state(), the region part is consumer-consistent: read - /// it from within the machine or once it has settled (it is - /// deterministic in embedder/pump mode). - [[nodiscard]] std::vector state_path() const - { - std::vector path; - if (auto s = current_state(); !s.empty()) { - path.push_back(std::move(s)); - } - if (m_region_probe) { - auto sub = m_region_probe(); - path.insert(path.end(), - std::make_move_iterator(sub.begin()), - std::make_move_iterator(sub.end())); - } - return path; - } - - /// All registered state names (registration order). - [[nodiscard]] const std::vector& - state_names() const noexcept - { - return m_names; - } - - // ── introspection / diagram ─────────────────────────────────── - struct EdgeInfo { - std::string event; // event type name, or "(timeout)" - std::string target; // target state, "(success)"/"(fail)" - bool guarded{false}; - }; - struct StateInfo { - std::string name; - bool reactive{false}; - bool initial{false}; - std::vector edges; // declarable edges only - }; - - /// Structural description: every registered state plus the - /// transitions declared by reactive states (imperative states' - /// run()-chosen transitions are not statically knowable, so - /// they appear as nodes without edges). - [[nodiscard]] std::vector describe() - { - std::vector out; - const std::string initial_name = m_initial != nullptr - ? state_name_for(m_initial) - : std::string{}; - for (const auto& name : m_names) { - StateInfo si; - si.name = name; - si.initial = (name == initial_name); - const auto* ti = m_name_to_type.at(name); - auto state = m_factories.at(std::type_index{*ti})(); - si.reactive = state->kind() == Detail::StateKind::Reactive; - if (auto* reactive = dynamic_cast(state.get())) { - TransitionTable table; - reactive->collect(table); - for (const auto& e : table.events) { - si.edges.push_back( - EdgeInfo{e.event_name, e.target_name, - static_cast(e.guard)}); - } - if (table.has_timeout) { - si.edges.push_back(EdgeInfo{ - "(timeout)", table.timeout_target_name, false}); - } - } - out.push_back(std::move(si)); - } - return out; - } - - /// Render describe() as a Mermaid stateDiagram-v2 string. - [[nodiscard]] std::string to_mermaid() - { - std::string out = "stateDiagram-v2\n"; - const auto states = describe(); - for (const auto& s : states) { - if (s.initial) { - out += " [*] --> " + s.name + "\n"; - } - } - for (const auto& s : states) { - for (const auto& e : s.edges) { - out += " " + s.name + " --> " + e.target + " : " + - e.event; - if (e.guarded) { - out += " [guard]"; - } - out += "\n"; - } - } - return out; - } - - // ── 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: - - virtual void on_serialize(Json::Value& /*data*/) const {} - virtual void on_restore(const Json::Value& /*data*/) {} - - /// Called on every transition (and the initial entry). Default - /// logs at debug; override for custom observability. - virtual void on_transition(std::string_view from, - std::string_view to) - { - Void::Log::debug("Fsm", "{} -> {}", - from.empty() ? "(start)" : from, to); - } - - private: - - template - friend class Machine; // run_child reaches child internals - - 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 void register_states(States) - { - (add(), ...); - } - - template - static const std::type_info* first_type(States) - { - return &typeid(First); - } - static const std::type_info* first_type(States<>) - { - return nullptr; - } - - template - [[nodiscard]] static std::string state_type_name() - { -#ifdef VOID_HAS_FSM_REFLECTION - return std::string{std::meta::identifier_of(^^S)}; -#else - return typeid(S).name(); -#endif - } - - 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 - } - - [[nodiscard]] std::string - state_name_for(const std::type_info* type) const - { - if (const auto it = m_index.find(std::type_index{*type}); - it != m_index.end()) { - return m_names[static_cast(it->second)]; - } - return {}; - } - - void set_current(const std::type_info* type) - { - std::string from = current_state(); - if (const auto it = m_index.find(std::type_index{*type}); - it != m_index.end()) { - m_current.store(it->second, std::memory_order_release); - } - std::string to = current_state(); - ++m_step; - on_transition(from, to); - const Transition t{from, to, m_step}; - if (m_observer) { - m_observer(t); - } - for (const auto& interceptor : m_interceptors) { - if (interceptor.before) { - interceptor.before(t); - } - } - } - - void fire_after(std::string_view state) - { - for (const auto& interceptor : m_interceptors) { - if (interceptor.after) { - interceptor.after(state); - } - } - } - - // The state loop: build each state, run on_enter → run → - // on_exit, follow the returned Step. Runs on the 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(); - co_await state->on_enter(); - Step step = co_await state->run(); - co_await state->on_exit(); - fire_after(current_state()); - 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()}; - } - } - } - - 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; - std::function m_observer; - std::vector m_interceptors; - std::uint64_t m_step{0}; - - // Active child region's path provider (run_region); consulted by - // state_path(). Set/cleared on the consumer thread. - std::function()> m_region_probe; - }; - -} // namespace Void::Fsm +// Umbrella header for the FSM module. The implementation is split for +// maintainability: +// - Machine.hpp — the Machine template + States +// list, nested State / Reactive bases, lifecycle, +// events, nesting, persistence. +// - Detail/Reactive.hpp — the declarative transition DSL +// (TransitionBuilder / EventClause / AfterClause). +// - Detail/Awaiter.hpp — the unified event awaiter. +// - Detail/Introspect.hpp — StateInfo / EdgeInfo + to_mermaid. +// - Detail/Engine.{hpp,cpp} — the non-template execution context. +// Include to get the whole machine API as before. + +#include diff --git a/include/Void/Fsm/Machine.hpp b/include/Void/Fsm/Machine.hpp new file mode 100644 index 0000000..a5722d2 --- /dev/null +++ b/include/Void/Fsm/Machine.hpp @@ -0,0 +1,917 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#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 +{ + /// Compile-time list of a machine's states. Declare it in the derived + /// machine to auto-register every state and enable compile-time + /// validation of next() targets: + /// using States = Void::Fsm::States; + /// The first entry is the initial state unless `using Initial = S;`. + template struct States { + static constexpr std::size_t size = sizeof...(Ss); + + template static constexpr bool contains() + { + return (std::is_same_v || ...); + } + }; + + /// Options for a Machine (namespace scope to dodge the GCC + /// nested-default-arg trap). + struct MachineOptions { + bool own_worker = true; + }; + + /// A transition record handed to observers. + struct Transition { + std::string from; + std::string to; + std::uint64_t step{0}; + }; + + // ── Machine ───────────────────────────────────────── + // + // Inheritance + coroutine workflow FSM, CRTP for typed access. Derive + // it, declare states as nested structs deriving `State`, list them in + // `using States = Fsm::States<...>`, and implement each state's async + // run() to return next() / succeed(...) / fail(...). States reach + // their owning machine (and its data + sub-methods) via self(). + // + // class Login : public Void::Fsm::Machine { + // public: + // int attempts = 0; + // struct Check : State { + // Coro::Task run() override { + // if (++self().attempts > 3) co_return fail("locked"); + // co_return self().service().ok() ? succeed(true) + // : next(); + // } + // }; + // using States = Void::Fsm::States; + // }; + template class Machine + { + public: + + using result_type = ResultT; + using Options = MachineOptions; + using Outcome = std::expected; + + // ── State base ──────────────────────────────────────────────── + class State : public Detail::StateBase + { + public: + + /// Typed access to the owning machine — no static_cast. + [[nodiscard]] Derived& self() const noexcept + { + return *static_cast(m_machine); + } + + [[nodiscard]] Machine& machine() const noexcept + { + return *m_machine; + } + + protected: + + /// Transition to another state. Validated at compile + /// time when the machine declares `using States`. + template [[nodiscard]] Step next() const + { + if constexpr (requires { typename Derived::States; }) { + static_assert( + Derived::States::template contains(), + "next: S is not in this machine's " + "States<...> list"); + } + return Step::transition(typeid(S)); + } + + /// Transition to a state registered dynamically + /// (add()/add_if()), skipping the static check. + template + [[nodiscard]] Step next_dynamic() const + { + return Step::transition(typeid(S)); + } + + /// Route to a fallback state if `step` is a failure, + /// otherwise pass it through — for error policies: + /// co_return next_or(co_await try_work()); + template + [[nodiscard]] Step next_or(Step step) const + { + if (step.kind() == Step::Kind::Fail) { + return next(); + } + return step; + } + + /// Suspend for `duration` (timer-driven), then resume. + template + [[nodiscard]] auto + delay(std::chrono::duration d) const + { + return m_machine->delay(d); + } + + /// Retry an async sub-step up to `times`, waiting + /// `backoff` between attempts. `attempt` returns + /// Coro::Task (true = success). Returns whether it + /// eventually succeeded. + template + [[nodiscard]] Coro::Task + with_retry(int times, + std::chrono::duration + backoff, + Fn attempt) const + { + for (int i = 0; i < times; ++i) { + if (co_await attempt()) { + co_return true; + } + if (i + 1 < times) { + co_await m_machine->delay(backoff); + } + } + co_return false; + } + + [[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))}); + } + + [[nodiscard]] Step fail(std::string message) const + { + return Step::failure(FsmError{std::move(message)}); + } + + template [[nodiscard]] I& service() const + { + return m_machine->template service(); + } + + template [[nodiscard]] auto await_event() const + { + return m_machine->template await_event(); + } + + /// Await E or time out (nullopt on timeout). + template + [[nodiscard]] auto await_event_for( + std::chrono::duration d) const + { + return m_machine->template await_event_for(d); + } + + template + [[nodiscard]] auto run_child(Args&&... args) const + { + return m_machine->template run_child( + std::forward(args)...); + } + + /// Enter a child region (composite sub-state): a nested + /// machine sharing this machine's executor, event mailbox + /// and services. This state's on_enter/on_exit wrap it, and + /// state_path() reports the parent→child chain while it + /// runs. Map the child's Outcome to a sibling transition: + /// auto r = co_await run_region(); + /// co_return r ? next() : next(); + template + [[nodiscard]] auto run_region(Args&&... args) const + { + return m_machine->template run_region( + std::forward(args)...); + } + + /// Await whichever of several event types arrives first, + /// yielding a std::variant. Handles multiple events + /// at one level (e.g. a parent watching Cancel alongside a + /// child region's own events). + template + [[nodiscard]] auto await_any() const + { + return m_machine->template await_any(); + } + + template [[nodiscard]] bool has_state() const + { + return m_machine->template has_state(); + } + + private: + + friend class Machine; + Machine* m_machine{nullptr}; + }; + + // ── reactive (declarative) states ───────────────────────────── + // + // A reactive state declares a transition table instead of an + // imperative run(): it waits for the declared events (or a + // timeout), checks guards in order, runs actions, and + // transitions. Mix freely with imperative State subclasses. + // + // struct Idle : Reactive { + // void transitions(TransitionBuilder& on) override { + // on.event().guard([](Idle& s, const Go& g){...}) + // .action([](Idle& s, const Go&){...}) + // .to(); + // on.event().to(); + // on.after(5s).to(); + // } + // }; + + // The declarative transition DSL lives in Detail/Reactive.hpp; + // these aliases give reactive states the ergonomic nested names. + using TransitionTable = Detail::TransitionTable; + using TransitionBuilder = + Detail::TransitionBuilder; + + class Reactive : public State + { + public: + + [[nodiscard]] Detail::StateKind + kind() const noexcept override + { + return Detail::StateKind::Reactive; + } + + /// Declare this state's event/timeout transitions. + virtual void transitions(TransitionBuilder& on) = 0; + + /// Build this state's table without running it — used by + /// describe()/to_mermaid() for introspection. + void collect(TransitionTable& table) + { + TransitionBuilder builder{table}; + transitions(builder); + } + + Coro::Task run() final + { + TransitionTable table; + collect(table); + std::vector types; + types.reserve(table.events.size()); + for (const auto& e : table.events) { + types.push_back(e.type); + } + for (;;) { + std::optional + deadline; + if (table.has_timeout) { + deadline = std::chrono::steady_clock::now() + + table.timeout_after; + } + auto ev = co_await this->machine().await_any_event( + types, deadline); + if (!ev) { + co_return std::move(table.timeout_step); + } + Derived& d = this->self(); + bool matched = false; + for (auto& e : table.events) { + if (*e.type != *ev->type) { + continue; + } + if (e.guard && !e.guard(d, ev->value)) { + continue; + } + if (e.action) { + co_await e.action(d, ev->value); + } + co_return std::move(e.step); + } + (void)matched; // unmatched event is dropped + } + } + }; + + // ── construction ────────────────────────────────────────────── + explicit Machine(Options options = {}) : m_options(options) + { + if constexpr (requires { typename Derived::States; }) { + register_states(typename Derived::States{}); + if constexpr (requires { typename Derived::Initial; }) { + m_initial = &typeid(typename Derived::Initial); + } else { + m_initial = first_type(typename Derived::States{}); + } + } + } + + virtual ~Machine() { stop(); } + + Machine(const Machine&) = delete; + Machine& operator=(const Machine&) = delete; + + // ── registration ────────────────────────────────────────────── + 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); + } + + 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(); + } + + // ── observability ───────────────────────────────────────────── + /// Register a read-only observer fired on every transition + /// (and on the initial entry). Replaces any prior observer. + void observe(std::function observer) + { + m_observer = std::move(observer); + } + + /// Transition middleware. `before(transition)` fires as a state + /// is entered (after the state changes, before it runs); + /// `after(state_name)` fires once that state finishes running. + /// Interceptors run in registration order — for logging, + /// metrics, validation around transitions. + struct Interceptor { + std::function before; + std::function after; + }; + void add_interceptor(Interceptor interceptor) + { + m_interceptors.push_back(std::move(interceptor)); + } + + // ── 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(); + } + } + + 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; + } + } + } + } + return take_outcome(); + } + + Outcome run_blocking() + { + start(); + return wait(); + } + + 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() + { + return Detail::make_event_awaiter( + m_ctx.get(), std::array{&typeid(E)}, std::nullopt, + [](Detail::EventEnvelope&& env, bool) { + return std::any_cast(std::move(env.value)); + }); + } + + /// Await an event of type E or time out after `duration`; + /// returns std::nullopt on timeout. + template + [[nodiscard]] auto + await_event_for(std::chrono::duration duration) + { + return Detail::make_event_awaiter( + m_ctx.get(), std::array{&typeid(E)}, + std::chrono::steady_clock::now() + duration, + [](Detail::EventEnvelope&& env, + bool timed_out) -> std::optional { + if (timed_out) { + return std::nullopt; + } + return std::any_cast(std::move(env.value)); + }); + } + + /// Await any of several event types (optional deadline); used + /// by reactive states. Returns the matched envelope or nullopt + /// on timeout. + [[nodiscard]] auto await_any_event( + std::vector types, + std::optional deadline) + { + return Detail::make_event_awaiter( + m_ctx.get(), std::move(types), deadline, + [](Detail::EventEnvelope&& env, + bool timed_out) -> std::optional { + if (timed_out) { + return std::nullopt; + } + return std::move(env); + }); + } + + /// Typed multi-event await: suspend until one of `Es...` arrives, + /// returning it as std::variant. Lets one state react to + /// several event types (parent-level handling for child regions). + template [[nodiscard]] auto await_any() + { + return Detail::make_event_awaiter( + m_ctx.get(), std::array{(&typeid(Es))...}, std::nullopt, + [](Detail::EventEnvelope&& env, + bool) -> std::variant { + std::optional> out; + ((env.type != nullptr && *env.type == typeid(Es) + ? (out.emplace( + std::in_place_type, + std::any_cast(std::move(env.value))), + true) + : false) || + ...); + return std::move(*out); + }); + } + + /// Suspend for `duration`, then resume (timer-driven). + template + [[nodiscard]] auto delay(std::chrono::duration d) + { + struct Awaiter { + Detail::ExecutionContext* ctx; + std::chrono::steady_clock::time_point deadline; + + [[nodiscard]] bool await_ready() const noexcept + { + return false; + } + void await_suspend(std::coroutine_handle<> h) + { + ctx->add_timer(deadline, [c = ctx, h] { + c->executor().post(h); + }); + } + void await_resume() const noexcept {} + }; + return Awaiter{m_ctx.get(), + std::chrono::steady_clock::now() + d}; + } + + // ── 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(); + } + + /// Composite sub-state: run `Sub` as a child region sharing this + /// machine's executor, event mailbox and services, and expose its + /// active state through this machine's state_path() while it runs + /// (parent→child chain). Returns the child's Outcome, which the + /// caller maps to a sibling transition. The calling state's + /// on_enter/on_exit naturally wrap the region. + template + [[nodiscard]] Coro::Task + run_region(Args&&... args) + { + Sub child{std::forward(args)...}; + child.attach(m_ctx, m_services); + m_region_probe = [&child] { return child.state_path(); }; + auto outcome = co_await child.drive(); + m_region_probe = nullptr; + co_return std::move(outcome); + } + + // ── 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)]; + } + + /// Active state chain (root → leaf). When a child region is + /// running (run_region), its path is appended, so a composite + /// state reports {composite, ...child leaf}. Unlike the lock-free + /// current_state(), the region part is consumer-consistent: read + /// it from within the machine or once it has settled (it is + /// deterministic in embedder/pump mode). + [[nodiscard]] std::vector state_path() const + { + std::vector path; + if (auto s = current_state(); !s.empty()) { + path.push_back(std::move(s)); + } + if (m_region_probe) { + auto sub = m_region_probe(); + path.insert(path.end(), + std::make_move_iterator(sub.begin()), + std::make_move_iterator(sub.end())); + } + return path; + } + + /// All registered state names (registration order). + [[nodiscard]] const std::vector& + state_names() const noexcept + { + return m_names; + } + + // ── introspection / diagram ─────────────────────────────────── + // EdgeInfo / StateInfo are namespace-scope (Detail/Introspect.hpp). + + /// Structural description: every registered state plus the + /// transitions declared by reactive states (imperative states' + /// run()-chosen transitions are not statically knowable, so + /// they appear as nodes without edges). + [[nodiscard]] std::vector describe() + { + std::vector out; + const std::string initial_name = m_initial != nullptr + ? state_name_for(m_initial) + : std::string{}; + for (const auto& name : m_names) { + StateInfo si; + si.name = name; + si.initial = (name == initial_name); + const auto* ti = m_name_to_type.at(name); + auto state = m_factories.at(std::type_index{*ti})(); + si.reactive = state->kind() == Detail::StateKind::Reactive; + if (auto* reactive = dynamic_cast(state.get())) { + TransitionTable table; + reactive->collect(table); + for (const auto& e : table.events) { + si.edges.push_back( + EdgeInfo{e.event_name, e.target_name, + static_cast(e.guard)}); + } + if (table.has_timeout) { + si.edges.push_back(EdgeInfo{ + "(timeout)", table.timeout_target_name, false}); + } + } + out.push_back(std::move(si)); + } + return out; + } + + /// Render describe() as a Mermaid stateDiagram-v2 string. + [[nodiscard]] std::string to_mermaid() + { + const auto states = describe(); + return Detail::to_mermaid(states); + } + + // ── 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: + + virtual void on_serialize(Json::Value& /*data*/) const {} + virtual void on_restore(const Json::Value& /*data*/) {} + + /// Called on every transition (and the initial entry). Default + /// logs at debug; override for custom observability. + virtual void on_transition(std::string_view from, + std::string_view to) + { + Void::Log::debug("Fsm", "{} -> {}", + from.empty() ? "(start)" : from, to); + } + + private: + + template + friend class Machine; // run_child reaches child internals + + 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 void register_states(States) + { + (add(), ...); + } + + template + static const std::type_info* first_type(States) + { + return &typeid(First); + } + static const std::type_info* first_type(States<>) + { + return nullptr; + } + + 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 + } + + [[nodiscard]] std::string + state_name_for(const std::type_info* type) const + { + if (const auto it = m_index.find(std::type_index{*type}); + it != m_index.end()) { + return m_names[static_cast(it->second)]; + } + return {}; + } + + void set_current(const std::type_info* type) + { + std::string from = current_state(); + if (const auto it = m_index.find(std::type_index{*type}); + it != m_index.end()) { + m_current.store(it->second, std::memory_order_release); + } + std::string to = current_state(); + ++m_step; + on_transition(from, to); + const Transition t{from, to, m_step}; + if (m_observer) { + m_observer(t); + } + for (const auto& interceptor : m_interceptors) { + if (interceptor.before) { + interceptor.before(t); + } + } + } + + void fire_after(std::string_view state) + { + for (const auto& interceptor : m_interceptors) { + if (interceptor.after) { + interceptor.after(state); + } + } + } + + // The state loop: build each state, run on_enter → run → + // on_exit, follow the returned Step. Runs on the 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(); + co_await state->on_enter(); + Step step = co_await state->run(); + co_await state->on_exit(); + fire_after(current_state()); + 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()}; + } + } + } + + 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; + std::function m_observer; + std::vector m_interceptors; + std::uint64_t m_step{0}; + + // Active child region's path provider (run_region); consulted by + // state_path(). Set/cleared on the consumer thread. + std::function()> m_region_probe; + }; + +} // namespace Void::Fsm