#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 #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 { bool own_worker = true; }; /// How a run_region() re-enters: from Sub's initial state, or resume /// at the sub-state it last reached (shallow history). enum class Resume { Initial, History }; /// 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 // and declare the states as a nested struct of forward declarations: // struct States { struct FirstState; struct SecondState; … }; // defined out-of-line (typically in a .cpp), each deriving the single // `State`. The Machine base auto-registers them by reflecting `States` // (Detail/StateList.hpp) — the first declared state is the initial one // unless `using Initial = S;`. All behaviour lives inside a state: the // engine infers each state's role from its member signatures (entry / // startup-entry / continuation handlers); states reach their machine (data // + sub-methods) via self(). Events are handled imperatively inside an // entry (co_await await_event()) — there is no declarative transition // table. Result types are the nested `Success`/`Failure` (default void). // // // header // class Login : public Void::Fsm::Machine { // public: // using Success = Token; // int attempts = 0; // struct States { struct Check; }; // }; // // source (namespace scope) // struct Login::States::Check : Login::State { // entry by signature // Coro::Task> run() { // if (++self().attempts > 3) co_return fail(); // co_return self().service().ok() ? succeed(Token{}) // : next(); // } // }; template class Machine { public: using Options = MachineOptions; // Result types are reflected by name from Derived's nested // `Success`/`Failure` (default void). Because Derived is incomplete // at base instantiation (CRTP), they cannot appear in member // signatures or data members — only inside function templates / // bodies, where Derived is complete. So these are alias *templates* // (lazily resolved), the engine stores outcomes type-erased, and // the typed Outcome is rebuilt in wait()/take_outcome(). template using Success = Detail::SuccessOf; template using Failure = Detail::FailureOf; template using Outcome = Detail::OutcomeOf; // ── 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 a `States` list. template [[nodiscard]] StateKey next() const { if constexpr (requires { typename Derived::States; }) { static_assert(Detail::states_contains< typename Derived::States, S>(), "next: S is not in this machine's " "States { … } list"); } return StateKey::transition(typeid(S)); } /// Transition to a state registered dynamically /// (add()/add_if()), skipping the static check. template [[nodiscard]] StateKey next_dynamic() const { return StateKey::transition(typeid(S)); } /// Free jump to any registered state — no declared /// transition required ("each state can be moved to /// another state"). Like next_dynamic, skips the /// States{ … } compile-time check; runtime-fails only if S /// was never registered. template [[nodiscard]] StateKey goto_state() const { return StateKey::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]] StateKey next_or(StateKey step) const { if (step.kind() == StateKey::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; } /// Finish with the machine's typed Success result (nested /// `Success`; nullary when it is void). [[nodiscard]] StateKey succeed() const requires std::is_void_v> { return StateKey::success(std::any{}); } template [[nodiscard]] StateKey succeed(V&& value) const requires(!std::is_void_v>) { return StateKey::success( std::any{Detail::SuccessOf( std::forward(value))}); } /// Finish with the machine's typed Failure result (nested /// `Failure`; nullary when it is void). [[nodiscard]] StateKey fail() const requires std::is_void_v> { return StateKey::failure(std::any{}); } template [[nodiscard]] StateKey fail(V&& value) const requires(!std::is_void_v>) { return StateKey::failure( std::any{Detail::FailureOf{ std::forward(value)}}); } 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(Resume resume = Resume::Initial) const { return m_machine->template run_region(resume); } /// Orthogonal regions: run `Subs...` concurrently on the /// shared executor and join all, yielding a /// std::tuple (children share events/ /// services; map the tuple to a sibling transition). template [[nodiscard]] auto run_parallel() const { return m_machine->template run_parallel(); } /// Race orthogonal regions: resolve on the first to finish, /// yielding std::variant (losers keep /// running cooperatively). template [[nodiscard]] auto run_parallel_any() const { return m_machine->template run_parallel_any(); } /// 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(); } /// Launch a sub-machine `Sub` (startup data routed to its /// initial-state startup-entry; shares this machine's /// executor/events/services), then transition to `Next`. /// When Sub finishes the engine calls Next's signature /// -matched handler — a member taking `ChildSuccess` /// (Sub succeeded) or `ChildFailure` (Sub failed): /// co_return startMachine(seed); template [[nodiscard]] StateKey startMachine(Args&&... args) const { return m_machine->template start_machine( std::forward(args)...); } template [[nodiscard]] bool has_state() const { return m_machine->template has_state(); } private: friend class Machine; Machine* m_machine{nullptr}; }; // ── one State, signature-inferred roles ─────────────────────── // // There is a single base, `State`. The engine infers what each // state does from member signatures (no `override`, no fixed // names): // - entry : a member returning // State/Coro::Task>, // no params (a startup-data overload may take // the sub's startup argument); // - continuation : members taking `ChildSuccess` / // `ChildFailure` (the sub's typed result, read // via .as(), after `startMachine`). // // Events are handled imperatively inside an entry: // struct Idle : State { // entry // Coro::Task run() { // auto e = co_await await_any(); // co_return std::holds_alternative(e) ? next() // : next(); } // }; // struct After : State { // continuation // Coro::Task ok(ChildSuccess s){ ... } // Coro::Task no(ChildFailure f){ ... } }; // ── construction ────────────────────────────────────────────── explicit Machine(Options options = {}) : m_options(options) { if constexpr (requires { typename Derived::States; }) { Detail::register_states_from( *this); using Init = Detail::InitialStateOf; if constexpr (!std::is_void_v) { m_initial = &typeid(Init); } } } 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; }); // Signature-inferred driver thunk (runs the state's entry). m_drivers.emplace(key, Detail::make_driver()); } 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)}); } /// Make `S` the initial state (registers it if needed). Idle-only. template void set_initial() { if (m_status.load() != Status::Idle) { return; } add(); m_initial = &typeid(S); } /// Unregister a state. Idle-only (running indices are fixed). If it /// was the initial state, the initial falls back to the first /// remaining state (or none). template void remove() { if (m_status.load() != Status::Idle) { return; } const std::type_index key{typeid(S)}; const auto idxIt = m_index.find(key); if (idxIt == m_index.end()) { return; } const int idx = idxIt->second; m_name_to_type.erase(m_names[static_cast(idx)]); m_names.erase(m_names.begin() + idx); m_factories.erase(key); m_drivers.erase(key); m_index.erase(idxIt); // Re-pack the indices of states that followed S. for (auto& [k, v] : m_index) { if (v > idx) { --v; } } if (m_initial == &typeid(S)) { m_initial = m_names.empty() ? nullptr : m_name_to_type.at(m_names.front()); } } /// Swap state `S` for `T`, preserving the initial pointer if S was /// it. Idle-only. template void replace() { if (m_status.load() != Status::Idle) { return; } const bool was_initial = (m_initial == &typeid(S)); remove(); add(); if (was_initial) { m_initial = &typeid(T); } } // ── 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); // Own the driver coroutine (rather than detaching it) so a // machine stopped while parked on an event can destroy the // suspended frame chain instead of leaking it. m_driver.emplace(driver()); m_ctx->executor().post(m_driver->handle()); if (m_options.own_worker && m_owns_ctx) { m_ctx->start_worker(); } } // Function templates so the typed Outcome resolves where Derived is // complete (CRTP). Call sites stay `fsm.wait()` / `run_blocking()`. template 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(); } template Outcome run_blocking() { start(); return wait(); } /// The system fault (if any) — a programming error caught by the /// engine, separate from a typed Failure result. [[nodiscard]] std::optional system_error() const { return m_system_error; } 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 || s == Status::Faulted; } [[nodiscard]] Status status() const noexcept { return m_status.load(); } void stop() { if (m_owns_ctx && m_ctx) { m_ctx->stop(); } // The worker is joined now (no concurrent resume), so destroy // the owned driver — this cascade-destroys the suspended // coroutine chain (a machine parked on an event) instead of // leaking it. Safe on a finished coroutine too. m_driver.reset(); } /// Return a finished (or idle) machine to Idle so it can run /// again: drops the owned execution context, clears the /// outcome/current-state/jump. No-op while Running. void reset() { if (m_status.load() == Status::Running) { return; } if (m_owns_ctx && m_ctx) { m_ctx->stop(); } m_driver.reset(); // destroy the (possibly parked) driver chain m_ctx.reset(); m_owns_ctx = false; m_current.store(-1, std::memory_order_release); m_result_value.reset(); m_system_error.reset(); m_pending_result.reset(); m_jump.store(nullptr, std::memory_order_release); m_step = 0; m_status.store(Status::Idle, std::memory_order_release); } /// reset() then start() from the initial state. void restart() { reset(); start(); } /// reset(), make `S` the initial state, then start(). template void restart_at() { reset(); m_initial = &typeid(S); start(); } /// Pause / resume event processing (best-effort: a state already /// running finishes; further progress waits). Events posted while /// paused buffer until resume(). void pause() { if (m_ctx) { m_ctx->set_paused(true); } } void resume() { if (m_ctx) { m_ctx->set_paused(false); } } // ── events ──────────────────────────────────────────────────── template void post(E event) { if (!m_ctx) { return; } m_ctx->post(Detail::EventEnvelope{&typeid(E), std::any{std::move(event)}}); } /// Re-post an already type-erased event (used by the reactive loop /// to re-inject deferred events after a transition). void repost(Detail::EventEnvelope env) { if (m_ctx) { m_ctx->post(std::move(env)); } } /// Fluent post: send one or several events in one call. /// fsm.send(Go{5}); fsm.send(Go{5}, Stop{}); template void send(Es&&... events) { (post(std::forward(events)), ...); } /// Request a jump to any registered state `S` from outside the /// machine. Race-safe; applied at the next transition boundary /// (a running state isn't preempted — coroutines aren't /// interruptible mid-flight). template void jump() { m_jump.store(&typeid(S), std::memory_order_release); if (m_ctx) { m_ctx->nudge(); } } 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_await child.drive(); co_return child.template take_outcome(); } /// 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(Resume resume = Resume::Initial) { Sub child; // History: resume at the sub-state this region last reached. // restore() must run before attach() (which marks Running). if (resume == Resume::History) { const auto it = m_region_history.find(std::type_index{typeid(Sub)}); if (it != m_region_history.end()) { (void)child.restore(it->second); } } child.attach(m_ctx, m_services); m_region_probe = [&child] { return child.state_path(); }; co_await child.drive(); m_region_probe = nullptr; // Snapshot the leaf it reached for a later History re-entry. m_region_history[std::type_index{typeid(Sub)}] = child.serialize(); co_return child.template take_outcome(); } /// Orthogonal regions: run `Subs...` concurrently on the shared /// executor (interleaved — when one parks on an event, another /// runs) and join all, yielding a tuple of their Outcomes. Children /// are default-constructed and share this machine's /// events/services. template [[nodiscard]] Coro::Task...>> run_parallel() { auto children = std::make_unique>(); std::apply( [&](auto&... c) { (c.attach(m_ctx, m_services), ...); }, *children); struct Latch { int remaining; std::coroutine_handle<> waiter{}; Async::Executor* exec; void arrive() { if (--remaining == 0 && waiter) { exec->post(waiter); } } }; auto latch = std::make_shared( static_cast(sizeof...(Subs)), std::coroutine_handle<>{}, &m_ctx->executor()); std::apply( [&](auto&... c) { (Async::spawn(m_ctx->executor(), [](auto& child, std::shared_ptr l) -> Coro::Task { co_await child.drive(); l->arrive(); }(c, latch)), ...); }, *children); struct Awaiter { std::shared_ptr latch; [[nodiscard]] bool await_ready() const noexcept { return latch->remaining == 0; } void await_suspend(std::coroutine_handle<> h) const { latch->waiter = h; } void await_resume() const noexcept {} }; co_await Awaiter{latch}; co_return std::apply( [](auto&... c) { return std::tuple...>{ c.template take_outcome()...}; }, *children); } /// Like run_parallel but resolves on the **first** child to finish, /// yielding a std::variant holding the winner's /// outcome. The losers keep running cooperatively (coroutines /// aren't preemptible) — the children are kept alive by the spawned /// tasks until they finish, so a loser parked forever leaks its /// frame until the machine stops. Document at call sites. template [[nodiscard]] Coro::Task...>> run_parallel_any() { // Shared so losers (which outlive this call) keep it alive. auto children = std::make_shared>(); std::apply( [&](auto&... c) { (c.attach(m_ctx, m_services), ...); }, *children); struct Latch { int first{-1}; std::coroutine_handle<> waiter{}; Async::Executor* exec; void arrive(int idx) { if (first < 0) { first = idx; if (waiter) { exec->post(waiter); } } } }; auto latch = std::make_shared( -1, std::coroutine_handle<>{}, &m_ctx->executor()); int idx = 0; std::apply( [&](auto&... c) { ( [&] { const int my = idx++; Async::spawn( m_ctx->executor(), [](auto& child, std::shared_ptr> keep, std::shared_ptr l, int i) -> Coro::Task { co_await child.drive(); l->arrive(i); (void)keep; }(c, children, latch, my)); }(), ...); }, *children); struct Awaiter { std::shared_ptr latch; [[nodiscard]] bool await_ready() const noexcept { return latch->first >= 0; } void await_suspend(std::coroutine_handle<> h) const { latch->waiter = h; } void await_resume() const noexcept {} }; co_await Awaiter{latch}; const auto winner = static_cast(latch->first); co_return [&](std::index_sequence) -> std::variant...> { std::variant...> v; ((I == winner ? (void)(v.template emplace( std::get(*children) .template take_outcome())) : void()), ...); return v; }(std::index_sequence_for{}); } /// Build a Launch step: run `Sub` (constructed from `args`) on this /// machine's shared executor, then enter `Next` carrying Sub's /// outcome as a LaunchResult. Reached via State::startMachine. template [[nodiscard]] StateKey start_machine(Args&&... args) { if constexpr (requires { typename Derived::States; }) { static_assert( Detail::states_contains(), "startMachine: Next is not in States { … }"); } using Init = Detail::InitialStateOf; auto launcher = [this, ... data = std::forward( args)]() mutable -> Coro::Task { // Run Sub on the shared executor. Startup data (if any) is // delivered to Sub's initial-state startup-entry via an // injector, not the constructor. Sub child; child.attach(m_ctx, m_services); if constexpr (sizeof...(Args) > 0) { child.m_startup_injector = [... d = std::move(data)]( Detail::StateBase& base) mutable -> Coro::Task { return Detail::invoke_startup( static_cast(base), std::move(d)...); }; } co_await child.drive(); LaunchResult lr; switch (child.m_status.load(std::memory_order_acquire)) { case Status::Succeeded: lr.kind = LaunchResult::Kind::Success; lr.value = std::move(child.m_result_value); break; case Status::Failed: lr.kind = LaunchResult::Kind::Failure; lr.failure = std::move(child.m_result_value); break; default: lr.kind = LaunchResult::Kind::Fault; lr.fault = child.m_system_error.value_or( FsmError{"sub-machine fault"}); break; } co_return lr; }; StateKey::Dispatch dispatch = [](Detail::StateBase& base, LaunchResult lr) -> Coro::Task { return Detail::dispatch_result( static_cast(base), std::move(lr)); }; return StateKey::launch(typeid(Next), std::move(launcher), std::move(dispatch)); } // ── 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 ─────────────────────────────────── // StateInfo is namespace-scope (Detail/Introspect.hpp). /// Structural description: every registered state (name + whether /// it is the initial state). Transitions are chosen imperatively /// inside each state's entry, so they are not statically knowable — /// the description is node-level (no 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); 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*/) {} /// Machine-level entry/exit hooks (default no-ops; override for /// machine-wide setup/teardown). `on_machine_enter()` runs once /// before the initial state is entered; `on_machine_exit()` runs /// once when the machine reaches a terminal outcome (Success, /// Failure, or a system Fault). Per-state entry/exit lives on the /// state itself (State::on_enter()/on_exit()). virtual void on_machine_enter() {} virtual void on_machine_exit() {} /// 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 [[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); } } } // Record a system fault (programming error) — separate from a // typed Failure result. Sets status Faulted + system_error. void fault(std::string message) { m_system_error = FsmError{std::move(message)}; Void::Log::error("Fsm", "system fault: {}", m_system_error->message); m_status.store(Status::Faulted, std::memory_order_release); } // The state loop. Type-erased: stores the Success/Failure payload // in m_result_value and sets m_status; the typed Outcome is rebuilt // in take_outcome() where Derived is complete. Runs on the // executor. Coro::Task drive() { const std::type_info* cur = m_initial; if (cur == nullptr) { fault("no initial state"); co_return; } on_machine_enter(); bool first = true; for (;;) { // Apply an external jump() at this transition boundary. if (const auto* j = m_jump.exchange(nullptr, std::memory_order_acq_rel); j != nullptr) { cur = j; m_pending_result.reset(); m_pending_dispatch = nullptr; } const auto it = m_factories.find(std::type_index{*cur}); if (it == m_factories.end()) { fault("transition to unregistered state"); on_machine_exit(); co_return; } set_current(cur); auto state = it->second(); co_await state->on_enter(); // Decide how the state runs: a launched sub's result (via // the bound dispatcher), the startup injector for the first // state, or the signature-inferred driver thunk. StateKey step; if (m_pending_dispatch) { LaunchResult pending = std::move(*m_pending_result); auto dispatch = std::move(m_pending_dispatch); m_pending_result.reset(); m_pending_dispatch = nullptr; if (pending.kind == LaunchResult::Kind::Fault) { fault(std::move(pending.fault.message)); on_machine_exit(); co_return; } step = co_await dispatch(*state, std::move(pending)); } else if (first && m_startup_injector) { auto inject = std::move(m_startup_injector); m_startup_injector = nullptr; step = co_await inject(*state); } else { step = co_await m_drivers.at(std::type_index{*cur})( *state); } first = false; co_await state->on_exit(); fire_after(current_state()); switch (step.kind()) { case StateKey::Kind::Transition: cur = step.target(); continue; case StateKey::Kind::Launch: m_pending_result.emplace( co_await step.run_launch()); m_pending_dispatch = step.take_dispatch(); cur = step.target(); continue; case StateKey::Kind::Success: m_result_value = std::move(step.payload()); m_status.store(Status::Succeeded, std::memory_order_release); on_machine_exit(); co_return; case StateKey::Kind::Fail: m_result_value = std::move(step.payload()); m_status.store(Status::Failed, std::memory_order_release); on_machine_exit(); co_return; case StateKey::Kind::Fault: fault(std::any_cast(step.payload()) .message); on_machine_exit(); co_return; } } } Coro::Task driver() { co_await drive(); if (m_owns_ctx) { m_ctx->finish(); } } // Rebuild the typed Outcome from the type-erased result. Function // template so SuccessOf/FailureOf resolve where Derived is // complete. A system fault yields a default-constructed error arm // (consult system_error()). template Outcome take_outcome() { using Succ = Detail::SuccessOf; using Fail = Detail::FailureOf; using Err = Detail::ErrArm; switch (m_status.load(std::memory_order_acquire)) { case Status::Succeeded: if constexpr (std::is_void_v) { return Outcome{}; } else { return Outcome{ std::any_cast(m_result_value)}; } case Status::Failed: if constexpr (std::is_void_v) { return Outcome{std::unexpect, std::monostate{}}; } else { return Outcome{ std::unexpect, std::any_cast(m_result_value)}; } default: // Faulted / not finished static_assert( std::is_default_constructible_v, "a machine with a non-default-constructible " "Failure " "cannot represent a system fault in its Outcome; " "check system_error()"); return Outcome{std::unexpect, Err{}}; } } 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; // Per-state signature-inferred driver thunk (runs the entry). std::unordered_map< std::type_index, std::function(Detail::StateBase&)>> m_drivers; 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}; // Type-erased finished result (Success or Failure payload), rebuilt // typed in take_outcome(); system faults in m_system_error. std::any m_result_value; std::optional m_system_error; 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; // Per-region-type snapshot of the leaf last reached, for // Resume::History re-entry. std::unordered_map m_region_history; // Set by a Launch step's sub-machine result; consumed by the next // state via the bound dispatcher below. std::optional m_pending_result; StateKey::Dispatch m_pending_dispatch; // Seeds the initial state's startup-entry with launch data (set by // the parent's launcher before driving this machine). std::function(Detail::StateBase&)> m_startup_injector; // External jump request (jump()); applied by drive() at the // next transition boundary. std::atomic m_jump{nullptr}; // The owned top-level driver coroutine (worker mode). Holding it // (rather than detaching via Async::spawn) lets stop() destroy the // suspended frame chain of a machine parked on an event. std::optional> m_driver; }; template using State = Machine::State; } // namespace Void::Fsm