diff --git a/CLAUDE.md b/CLAUDE.md index 00a0be8..8a146fc 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -147,7 +147,9 @@ Other key points: ### Fsm module (inheritance + coroutine workflow) -`Void::Fsm::Machine` — derive it; declare states as nested structs deriving `State`; each implements `Coro::Task run()` returning `next()` / `succeed(...)` / `fail(...)`. There is no statechart/event-graph; states drive themselves. +`Void::Fsm::Machine` (CRTP) — derive it; declare states as nested structs deriving `State`; each implements `Coro::Task run()` returning `next()` / `succeed(...)` / `fail(...)`. There is no statechart/event-graph; states drive themselves. + +**Typed results.** A machine declares its result types as nested types *reflected by name* — `struct Success {…}` (or `using Success = int;`) and `struct Failure {…}`, each defaulting to `void`. `Outcome = std::expected` (a void failure becomes `std::monostate`); `succeed(Success{…})` / `fail(Failure{…})` carry them (nullary when void). Engine/system faults (no initial state, jump to an unregistered state, a state with no entry) are a **separate `FsmError` channel** — `status()==Faulted`, `system_error()` returns the `FsmError`, never the typed `Failure`. Because `Derived` is incomplete at CRTP base instantiation, the engine stores outcomes type-erased and rebuilds the typed `Outcome` in `wait()`/`run_blocking()` (function templates defaulted on `Derived`); `Detail::SuccessOf`/`FailureOf` resolve the nested types by plain name lookup (`Detail/Result.hpp`). Header layout (include `` — a thin umbrella): `Machine.hpp` (the `Machine` template + `States<>`, nested `State`/`Reactive`/`Continue` bases, lifecycle, events, nesting, persistence); `Detail/Reactive.hpp` (the declarative transition DSL as standalone `Detail::TransitionBuilder`/`EventClause`/`AfterClause`/`TransitionTable` templates, aliased by `Machine::Reactive`); `Detail/Awaiter.hpp` (one `Detail::EventAwaiter` behind `make_event_awaiter`, used by all `await_*`); `Detail/Continuation.hpp` (`Detail::Continuation` = `Continue`, with a `void` specialization); `Detail/Introspect.hpp` (`StateInfo`/`EdgeInfo` + `to_mermaid`); `Detail/Engine.{hpp,cpp}` (the non-template `ExecutionContext` + `StateBase`); `Detail/TypeName.hpp` (`type_name()`). diff --git a/include/Void/Fsm/Detail/Continuation.hpp b/include/Void/Fsm/Detail/Continuation.hpp index acf300f..d46c385 100644 --- a/include/Void/Fsm/Detail/Continuation.hpp +++ b/include/Void/Fsm/Detail/Continuation.hpp @@ -2,86 +2,75 @@ #include #include +#include #include #include +#include #include +#include namespace Void::Fsm::Detail { namespace Coro = Void::Coro; // Base for a state that resumes from a sub-machine launched via - // startMachine(). `StateT` is the owning machine's nested State - // (so the continuation inherits self()/next/fail/...); `SubResult` is the - // sub-machine's result_type. The engine enters this state carrying the + // startMachine(). `StateT` is the owning machine's nested State; + // `Sub` is the launched machine. The engine enters this state carrying the // sub's LaunchResult and calls resume(), which dispatches to on_success / - // on_failure — the FSM "finds on its own which method to call". + // on_failure by the outcome. Machine exposes it as `Continue`. // - // Machine exposes it as `Continue`; users derive it and implement - // on_success(R) (and optionally on_failure). - template - class Continuation : public StateT + // on_success takes the sub's typed Success, on_failure its typed Failure + // (a void result becomes a std::monostate argument). + // + // NOTE: this is the interim Phase-1 form; Phase 2 replaces it with + // signature-inferred ChildSuccess/ChildFailure handlers. + template class Continuation : public StateT { + using Succ = SuccessOf; + using Fail = FailureOf; + using SuccArg = + std::conditional_t, std::monostate, Succ>; + using FailArg = + std::conditional_t, std::monostate, Fail>; + public: Coro::Task resume(LaunchResult lr) final { - if (lr.ok) { + if (lr.kind == LaunchResult::Kind::Failure) { + if constexpr (std::is_void_v) { + co_return co_await on_failure(std::monostate{}); + } else { + co_return co_await on_failure( + std::any_cast(std::move(lr.failure))); + } + } + if constexpr (std::is_void_v) { + co_return co_await on_success(std::monostate{}); + } else { co_return co_await on_success( - std::any_cast(std::move(lr.value))); + std::any_cast(std::move(lr.value))); } - co_return co_await on_failure(std::move(lr.error)); } Coro::Task run() override { - co_return this->fail( - "Continue state entered without a sub-machine result " - "(reach it via startMachine())"); + co_return Step::fault(FsmError{ + "continuation state entered without a sub-machine result " + "(reach it via startMachine())"}); } protected: - /// The sub-machine succeeded with `result`. - virtual Coro::Task on_success(SubResult result) = 0; + virtual Coro::Task on_success(SuccArg result) = 0; - /// The sub-machine failed. Default: fail the parent with the same - /// message; override to recover. - virtual Coro::Task on_failure(FsmError error) + /// Default: a sub-machine failure the parent didn't handle becomes + /// a system fault. Override to recover. + virtual Coro::Task on_failure(FailArg /*error*/) { - co_return this->fail(std::move(error.message)); - } - }; - - // Specialisation for a void-result sub-machine: on_success() takes no - // argument. - template class Continuation : public StateT - { - public: - - Coro::Task resume(LaunchResult lr) final - { - if (lr.ok) { - co_return co_await on_success(); - } - co_return co_await on_failure(std::move(lr.error)); - } - - Coro::Task run() override - { - co_return this->fail( - "Continue state entered without a sub-machine result " - "(reach it via startMachine())"); - } - - protected: - - virtual Coro::Task on_success() = 0; - - virtual Coro::Task on_failure(FsmError error) - { - co_return this->fail(std::move(error.message)); + co_return Step::fault( + FsmError{"unhandled sub-machine failure"}); } }; } // namespace Void::Fsm::Detail diff --git a/include/Void/Fsm/Detail/Reactive.hpp b/include/Void/Fsm/Detail/Reactive.hpp index b109682..de63090 100644 --- a/include/Void/Fsm/Detail/Reactive.hpp +++ b/include/Void/Fsm/Detail/Reactive.hpp @@ -1,6 +1,7 @@ #pragma once #include +#include #include #include @@ -15,9 +16,10 @@ // 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. +// owning machine's `Derived` (guards/actions take `Derived&`); the machine's +// typed Success/Failure (nested types, default void) are reflected from +// `Derived` for finish()/fail(). Machine::Reactive aliases these and the engine +// drives them; see include/Void/Fsm/Machine.hpp. namespace Void::Fsm::Detail { @@ -44,8 +46,8 @@ namespace Void::Fsm::Detail }; /// Fluent builder for one event row: `on.event().guard(..).action(..) - /// .to()` (or `.finish(v)` / `.fail(msg)`). - template class EventClause + /// .to()` (or `.finish(v)` / `.fail(v)`). + template class EventClause { public: @@ -88,21 +90,31 @@ namespace Void::Fsm::Detail } void finish() - requires std::is_void_v + requires std::is_void_v> { commit(Step::success(std::any{}), "(success)"); } template void finish(V&& value) - requires(!std::is_void_v) + requires(!std::is_void_v>) { - commit(Step::success(std::any{ResultT(std::forward(value))}), + commit(Step::success(std::any{ + SuccessOf(std::forward(value))}), "(success)"); } - void fail(std::string message) + void fail() + requires std::is_void_v> { - commit(Step::failure(FsmError{std::move(message)}), "(fail)"); + commit(Step::failure(std::any{}), "(fail)"); + } + template + void fail(V&& value) + requires(!std::is_void_v>) + { + commit(Step::failure(std::any{ + FailureOf{std::forward(value)}}), + "(fail)"); } private: @@ -136,8 +148,8 @@ namespace Void::Fsm::Detail std::function(Derived&, const E&)> m_action; }; - /// Fluent builder for the timeout row: `on.after(d).to()` / `.fail(..)`. - template class AfterClause + /// Fluent builder for the timeout row: `on.after(d).to()` / `.fail(v)`. + template class AfterClause { public: @@ -159,12 +171,22 @@ namespace Void::Fsm::Detail m_table->timeout_target_name = type_name(); } - void fail(std::string message) + void fail() + requires std::is_void_v> { m_table->has_timeout = true; m_table->timeout_after = m_after; - m_table->timeout_step = - Step::failure(FsmError{std::move(message)}); + m_table->timeout_step = Step::failure(std::any{}); + m_table->timeout_target_name = "(fail)"; + } + template + void fail(V&& value) + requires(!std::is_void_v>) + { + m_table->has_timeout = true; + m_table->timeout_after = m_after; + m_table->timeout_step = Step::failure( + std::any{FailureOf{std::forward(value)}}); m_table->timeout_target_name = "(fail)"; } @@ -175,7 +197,7 @@ namespace Void::Fsm::Detail }; /// Entry point handed to `transitions(TransitionBuilder& on)`. - template class TransitionBuilder + template class TransitionBuilder { public: @@ -184,17 +206,16 @@ namespace Void::Fsm::Detail { } - template - [[nodiscard]] EventClause event() + template [[nodiscard]] EventClause event() { - return EventClause{*m_table}; + return EventClause{*m_table}; } template - [[nodiscard]] AfterClause + [[nodiscard]] AfterClause after(std::chrono::duration d) { - return AfterClause{ + return AfterClause{ *m_table, std::chrono::duration_cast< std::chrono::steady_clock::duration>(d)}; } diff --git a/include/Void/Fsm/Detail/Result.hpp b/include/Void/Fsm/Detail/Result.hpp new file mode 100644 index 0000000..1f4833f --- /dev/null +++ b/include/Void/Fsm/Detail/Result.hpp @@ -0,0 +1,52 @@ +#pragma once + +#include +#include +#include +#include + +// A machine declares its result types as nested types reflected *by name* — +// `Success` / `Failure`, either a struct or a `using` alias — each defaulting +// to void: +// struct Login : Machine { +// struct Success { Token token; }; // or: using Success = int; +// struct Failure { int code; }; +// }; +// Resolved by plain dependent-name lookup (the names are fixed, so no P2996 is +// needed), and shaped into the machine Outcome. + +namespace Void::Fsm::Detail +{ + template consteval auto success_probe() + { + if constexpr (requires { typename D::Success; }) { + return std::type_identity{}; + } else { + return std::type_identity{}; + } + } + template consteval auto failure_probe() + { + if constexpr (requires { typename D::Failure; }) { + return std::type_identity{}; + } else { + return std::type_identity{}; + } + } + + /// The machine's success result type (nested `Success`, else void). + template + using SuccessOf = typename decltype(success_probe())::type; + /// The machine's failure result type (nested `Failure`, else void). + template + using FailureOf = typename decltype(failure_probe())::type; + + /// std::expected can't have a void error arm — map void failure to a unit. + template + using ErrArm = std::conditional_t, std::monostate, F>; + + /// The user-facing outcome: typed success value or typed failure value. + /// (Engine/system faults travel a separate FsmError channel, not this.) + template + using OutcomeOf = std::expected, ErrArm>>; +} // namespace Void::Fsm::Detail diff --git a/include/Void/Fsm/Machine.hpp b/include/Void/Fsm/Machine.hpp index 48cbf50..f373316 100644 --- a/include/Void/Fsm/Machine.hpp +++ b/include/Void/Fsm/Machine.hpp @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -89,13 +90,25 @@ namespace Void::Fsm // }; // using States = Void::Fsm::States; // }; - template class Machine + template class Machine { public: - using result_type = ResultT; using Options = MachineOptions; - using Outcome = std::expected; + + // 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 @@ -188,22 +201,36 @@ namespace Void::Fsm co_return false; } + /// Finish with the machine's typed Success result (nested + /// `Success`; nullary when it is void). [[nodiscard]] Step succeed() const - requires std::is_void_v + requires std::is_void_v> { return Step::success(std::any{}); } template [[nodiscard]] Step succeed(V&& value) const - requires(!std::is_void_v) + requires(!std::is_void_v>) { return Step::success( - std::any{ResultT(std::forward(value))}); + std::any{Detail::SuccessOf( + std::forward(value))}); } - [[nodiscard]] Step fail(std::string message) const + /// Finish with the machine's typed Failure result (nested + /// `Failure`; nullary when it is void). + [[nodiscard]] Step fail() const + requires std::is_void_v> { - return Step::failure(FsmError{std::move(message)}); + return Step::failure(std::any{}); + } + template + [[nodiscard]] Step fail(V&& value) const + requires(!std::is_void_v>) + { + return Step::failure( + std::any{Detail::FailureOf{ + std::forward(value)}}); } template [[nodiscard]] I& service() const @@ -265,10 +292,9 @@ namespace Void::Fsm [[nodiscard]] Step startMachine(Args&&... args) const { static_assert( - std::is_base_of_v< - Continue, Next>, + std::is_base_of_v, Next>, "startMachine: Next must derive " - "Continue"); + "Continue"); return m_machine->template start_machine( std::forward(args)...); } @@ -298,8 +324,8 @@ namespace Void::Fsm // Coro::Task on_failure(FsmError e) override { // co_return fail(e.message); } // }; - template - using Continue = Detail::Continuation; + template + using Continue = Detail::Continuation; // ── reactive (declarative) states ───────────────────────────── // @@ -321,8 +347,7 @@ namespace Void::Fsm // 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; + using TransitionBuilder = Detail::TransitionBuilder; class Reactive : public State { @@ -549,7 +574,9 @@ namespace Void::Fsm } } - Outcome wait() + // 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) { @@ -562,13 +589,20 @@ namespace Void::Fsm } } } - return take_outcome(); + return take_outcome(); } - Outcome run_blocking() + template Outcome run_blocking() { start(); - return wait(); + 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; } @@ -576,7 +610,8 @@ namespace Void::Fsm [[nodiscard]] bool finished() const noexcept { const auto s = m_status.load(); - return s == Status::Succeeded || s == Status::Failed; + return s == Status::Succeeded || s == Status::Failed || + s == Status::Faulted; } [[nodiscard]] Status status() const noexcept @@ -605,7 +640,8 @@ namespace Void::Fsm m_ctx.reset(); m_owns_ctx = false; m_current.store(-1, std::memory_order_release); - m_outcome.reset(); + m_result_value.reset(); + m_system_error.reset(); m_pending_result.reset(); m_jump.store(nullptr, std::memory_order_release); m_step = 0; @@ -764,12 +800,13 @@ namespace Void::Fsm // ── nesting ─────────────────────────────────────────────────── template - [[nodiscard]] Coro::Task + [[nodiscard]] Coro::Task> run_child(Args&&... args) { Sub child{std::forward(args)...}; child.attach(m_ctx, m_services); - co_return co_await child.drive(); + co_await child.drive(); + co_return child.template take_outcome(); } /// Composite sub-state: run `Sub` as a child region sharing this @@ -779,15 +816,15 @@ namespace Void::Fsm /// caller maps to a sibling transition. The calling state's /// on_enter/on_exit naturally wrap the region. template - [[nodiscard]] Coro::Task + [[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(); + co_await child.drive(); m_region_probe = nullptr; - co_return std::move(outcome); + co_return child.template take_outcome(); } /// Build a Launch step: run `Sub` (constructed from `args`) on this @@ -805,22 +842,26 @@ namespace Void::Fsm [this, tup = std::make_tuple(std::forward( args)...)]() mutable -> Coro::Task { - auto outcome = co_await std::apply( - [this](auto&&... a) { - return this->template run_child( - std::forward(a)...); - }, - std::move(tup)); + // Run Sub on the shared executor and read its raw result so + // Success / Failure / Fault are all distinguishable. + Sub child = std::make_from_tuple(std::move(tup)); + child.attach(m_ctx, m_services); + co_await child.drive(); LaunchResult lr; - if (outcome.has_value()) { - lr.ok = true; - if constexpr (!std::is_void_v< - typename Sub::result_type>) { - lr.value = std::any{std::move(*outcome)}; - } - } else { - lr.ok = false; - lr.error = std::move(outcome.error()); + 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; }; @@ -962,7 +1003,7 @@ namespace Void::Fsm private: - template + template friend class Machine; // run_child reaches child internals void attach(std::shared_ptr ctx, @@ -1040,13 +1081,26 @@ namespace Void::Fsm } } - // The state loop: build each state, run on_enter → run → - // on_exit, follow the returned Step. Runs on the executor. - Coro::Task drive() + // 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) { - co_return std::unexpected{FsmError{"no initial state"}}; + fault("no initial state"); + co_return; } for (;;) { // Apply an external jump() at this transition boundary. @@ -1058,18 +1112,22 @@ namespace Void::Fsm } const auto it = m_factories.find(std::type_index{*cur}); if (it == m_factories.end()) { - co_return std::unexpected{ - FsmError{"transition to unregistered state"}}; + fault("transition to unregistered state"); + co_return; } set_current(cur); auto state = it->second(); co_await state->on_enter(); // A state entered via startMachine resumes from the sub's - // result (Continue dispatches); otherwise it runs. + // result; otherwise it runs. Step step; if (m_pending_result.has_value()) { LaunchResult pending = std::move(*m_pending_result); m_pending_result.reset(); + if (pending.kind == LaunchResult::Kind::Fault) { + fault(std::move(pending.fault.message)); + co_return; + } step = co_await state->resume(std::move(pending)); } else { step = co_await state->run(); @@ -1081,43 +1139,70 @@ namespace Void::Fsm cur = step.target(); continue; case Step::Kind::Launch: - // Run the sub-machine, stash its result, then enter - // the Next (Continue) state. m_pending_result.emplace( co_await step.run_launch()); 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()))}; - } + m_result_value = std::move(step.payload()); + m_status.store(Status::Succeeded, + std::memory_order_release); + co_return; case Step::Kind::Fail: - co_return std::unexpected{step.error()}; + m_result_value = std::move(step.payload()); + m_status.store(Status::Failed, + std::memory_order_release); + co_return; + case Step::Kind::Fault: + fault(std::any_cast(step.payload()) + .message); + co_return; } } } 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); + co_await drive(); if (m_owns_ctx) { m_ctx->finish(); } } - Outcome take_outcome() + // 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() { - if (m_outcome.has_value()) { - return std::move(*m_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{}}; } - return std::unexpected{FsmError{"machine did not finish"}}; } Options m_options; @@ -1137,7 +1222,10 @@ namespace Void::Fsm std::atomic m_current{-1}; std::atomic m_status{Status::Idle}; - std::optional m_outcome; + // 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}; diff --git a/include/Void/Fsm/Step.hpp b/include/Void/Fsm/Step.hpp index 299d354..9b25764 100644 --- a/include/Void/Fsm/Step.hpp +++ b/include/Void/Fsm/Step.hpp @@ -12,35 +12,40 @@ namespace Void::Fsm { namespace Coro = Void::Coro; + /// An engine/system fault — a programming error in the machine itself (no + /// initial state, transition to an unregistered state, …). Distinct from a + /// machine's typed `Failure` result: faults travel a separate channel + /// (Machine::system_error()), never the Outcome. struct FsmError { std::string message; }; - /// The outcome of a sub-machine launched via startMachine(): - /// `ok` with the result in `value` (a `Sub::result_type`, empty for void), - /// or `!ok` with `error`. Delivered to the Next state's Continue - /// handlers (on_success / on_failure). - struct LaunchResult { - bool ok{false}; - std::any value; - FsmError error; - }; - enum class Status { Idle, // constructed, not started Running, // worker active - Succeeded, // finished with a result - Failed // finished with an error + Succeeded, // finished with a typed Success + Failed, // finished with a typed Failure + Faulted // stopped by a system fault (see system_error()) }; - /// The outcome a state's run() returns: move to another state, finish - /// the machine with a result, or fail. Built only through the State - /// helpers (next() / succeed() / fail()). + /// The outcome of a sub-machine launched via startMachine(): + /// a typed Success value, a typed Failure value, or a system fault. + struct LaunchResult { + enum class Kind { Success, Failure, Fault }; + Kind kind{Kind::Fault}; + std::any value; // Success payload (kind == Success) + std::any failure; // Failure payload (kind == Failure) + FsmError fault; // system fault (kind == Fault) + }; + + /// What a state's entry returns: move to another state, finish with a typed + /// Success / Failure, or launch a sub-machine. Built only through the State + /// helpers (next() / succeed(...) / fail(...) / startMachine). class Step { public: - enum class Kind { Transition, Success, Fail, Launch }; + enum class Kind { Transition, Success, Fail, Launch, Fault }; [[nodiscard]] static Step transition(const std::type_info& target) { @@ -50,9 +55,18 @@ namespace Void::Fsm return s; } - /// Launch a sub-machine, then enter `target` (a Continue state) - /// with the sub's LaunchResult. `launcher` runs the sub and yields - /// its result; the engine awaits it in drive(). + /// Signal a system fault (programming error) — distinct from a + /// typed Failure. Routed to Machine::system_error(). + [[nodiscard]] static Step fault(FsmError error) + { + Step s; + s.m_kind = Kind::Fault; + s.m_payload = std::any{std::move(error)}; + return s; + } + + /// Launch a sub-machine, then enter `target` (a continuation state) + /// with the sub's LaunchResult. [[nodiscard]] static Step launch(const std::type_info& target, std::function()> launcher) @@ -64,19 +78,21 @@ namespace Void::Fsm return s; } - [[nodiscard]] static Step success(std::any result) + /// Finish with a typed Success payload (empty std::any for void). + [[nodiscard]] static Step success(std::any value) { Step s; s.m_kind = Kind::Success; - s.m_result = std::move(result); + s.m_payload = std::move(value); return s; } - [[nodiscard]] static Step failure(FsmError error) + /// Finish with a typed Failure payload (empty std::any for void). + [[nodiscard]] static Step failure(std::any value) { Step s; s.m_kind = Kind::Fail; - s.m_error = std::move(error); + s.m_payload = std::move(value); return s; } @@ -87,12 +103,8 @@ namespace Void::Fsm return m_target; } - [[nodiscard]] std::any& result() noexcept { return m_result; } - - [[nodiscard]] const FsmError& error() const noexcept - { - return m_error; - } + /// The Success or Failure payload (by kind). + [[nodiscard]] std::any& payload() noexcept { return m_payload; } /// Run the sub-machine for a Launch step (yields its LaunchResult). [[nodiscard]] Coro::Task run_launch() @@ -104,8 +116,7 @@ namespace Void::Fsm Kind m_kind{Kind::Fail}; const std::type_info* m_target{nullptr}; - std::any m_result; - FsmError m_error; + std::any m_payload; std::function()> m_launcher; }; diff --git a/src/Fsm/Engine.cpp b/src/Fsm/Engine.cpp index 216c707..4d4d86b 100644 --- a/src/Fsm/Engine.cpp +++ b/src/Fsm/Engine.cpp @@ -10,7 +10,7 @@ namespace Void::Fsm::Detail Coro::Task StateBase::on_exit() { co_return; } Coro::Task StateBase::run() { - co_return Step::failure(FsmError{"state defines no run()"}); + co_return Step::fault(FsmError{"state defines no entry"}); } Coro::Task StateBase::resume(LaunchResult /*result*/) diff --git a/tests/internal/FsmServiceHotReload.cpp b/tests/internal/FsmServiceHotReload.cpp index 83fd64c..a692799 100644 --- a/tests/internal/FsmServiceHotReload.cpp +++ b/tests/internal/FsmServiceHotReload.cpp @@ -37,10 +37,12 @@ namespace // An FSM that drives the plugin-provided ICalc service: each Work step // accumulates and loops until a target total is reached. It resolves // the service every step, so it picks up a reloaded implementation. - class Accumulate : public Void::Fsm::Machine + class Accumulate : public Void::Fsm::Machine { public: + using Success = int; + struct Work : State { Task run() override { diff --git a/tests/standalone/Fsm/Basic.cpp b/tests/standalone/Fsm/Basic.cpp index c2e5c78..b92e4fc 100644 --- a/tests/standalone/Fsm/Basic.cpp +++ b/tests/standalone/Fsm/Basic.cpp @@ -12,10 +12,12 @@ using Void::Fsm::Step; namespace { // A linear workflow: Start -> Work (loops 3x) -> success(count). - class Counter : public Void::Fsm::Machine + class Counter : public Void::Fsm::Machine { public: + using Success = int; + int count = 0; std::vector* log = nullptr; @@ -47,16 +49,19 @@ namespace using States = Void::Fsm::States; Counter() - : Void::Fsm::Machine( + : Void::Fsm::Machine( MachineOptions{.own_worker = false}) { } }; - class Failing : public Void::Fsm::Machine + class Failing : public Void::Fsm::Machine { public: + using Success = int; + using Failure = Void::Fsm::FsmError; + struct Boom : State { Task run() override { co_return fail("kaboom"); } }; @@ -64,7 +69,7 @@ namespace using States = Void::Fsm::States; Failing() - : Void::Fsm::Machine( + : Void::Fsm::Machine( MachineOptions{.own_worker = false}) { } @@ -107,13 +112,13 @@ Void::Testing::Test fsm_pump_drives_to_completion() Void::Testing::Test fsm_void_result_succeeds() { - struct Trivial : Void::Fsm::Machine { + struct Trivial : Void::Fsm::Machine { struct Done : State { Task run() override { co_return succeed(); } }; using States = Void::Fsm::States; Trivial() - : Void::Fsm::Machine( + : Void::Fsm::Machine( MachineOptions{.own_worker = false}) { } @@ -127,7 +132,9 @@ Void::Testing::Test fsm_dynamic_state_registration() { // Dynamic machine: states registered conditionally, addressed with // next_dynamic() (skips the compile-time States<> check). - struct Flow : Void::Fsm::Machine { + struct Flow : Void::Fsm::Machine { + using Success = int; + bool express; struct Express : State { Task run() override { co_return succeed(99); } @@ -145,8 +152,7 @@ Void::Testing::Test fsm_dynamic_state_registration() } }; explicit Flow(bool e) - : Void::Fsm::Machine( - MachineOptions{.own_worker = false}), + : Void::Fsm::Machine(MachineOptions{.own_worker = false}), express(e) { initial(); diff --git a/tests/standalone/Fsm/Concurrency.cpp b/tests/standalone/Fsm/Concurrency.cpp index 4e53b9f..d007264 100644 --- a/tests/standalone/Fsm/Concurrency.cpp +++ b/tests/standalone/Fsm/Concurrency.cpp @@ -22,10 +22,12 @@ namespace // Sums many Tick events delivered from several threads, finishing when // the running total reaches a target. Single consumer (the worker) so // the total is race-free without the FSM holding any lock. - class Summer : public Void::Fsm::Machine + class Summer : public Void::Fsm::Machine { public: + using Success = long long; + long long total = 0; long long target; @@ -42,7 +44,7 @@ namespace }; explicit Summer(long long tgt) - : Void::Fsm::Machine(), target(tgt) + : Void::Fsm::Machine(), target(tgt) { initial(); } @@ -132,7 +134,9 @@ Void::Testing::Test fsm_current_state_reads_never_tear_under_load() Void::Testing::Test fsm_resolves_service_through_context() { - struct Calc : Void::Fsm::Machine { + struct Calc : Void::Fsm::Machine { + using Success = int; + struct Go : State { Task run() override { @@ -140,8 +144,7 @@ Void::Testing::Test fsm_resolves_service_through_context() } }; Calc() - : Void::Fsm::Machine( - MachineOptions{.own_worker = false}) + : Void::Fsm::Machine(MachineOptions{.own_worker = false}) { initial(); } diff --git a/tests/standalone/Fsm/Direct.cpp b/tests/standalone/Fsm/Direct.cpp index cf80f3a..e0ab709 100644 --- a/tests/standalone/Fsm/Direct.cpp +++ b/tests/standalone/Fsm/Direct.cpp @@ -20,10 +20,12 @@ namespace }; // Sums two Add events, posted in one fluent send() call. - class Sum : public Fsm::Machine + class Sum : public Fsm::Machine { public: + using Success = int; + int total = 0; struct Take : State { @@ -55,10 +57,12 @@ namespace { // A and C are not connected by any declared edge; goto_state() jumps // from A to C freely. - class Hop : public Fsm::Machine + class Hop : public Fsm::Machine { public: + using Success = int; + struct A : State { Task run() override { co_return goto_state(); } }; @@ -88,10 +92,12 @@ namespace // Loops in Loop on each Tick; an external jump() redirects at the // next boundary. - class Jumper : public Fsm::Machine + class Jumper : public Fsm::Machine { public: + using Success = int; + struct Loop : State { Task run() override { @@ -104,10 +110,7 @@ namespace }; using States = Fsm::States; - explicit Jumper(MachineOptions o = {}) - : Fsm::Machine(o) - { - } + explicit Jumper(MachineOptions o = {}) : Fsm::Machine(o) {} }; } // namespace @@ -136,10 +139,12 @@ Void::Testing::Test jump_redirects_at_next_boundary() namespace { // Increments a machine-owned counter each run (data survives reset()). - class Counter : public Fsm::Machine + class Counter : public Fsm::Machine { public: + using Success = int; + int runs = 0; struct Once : State { @@ -165,10 +170,12 @@ Void::Testing::Test restart_reruns_the_machine() namespace { - class Pick : public Fsm::Machine + class Pick : public Fsm::Machine { public: + using Success = int; + struct A : State { Task run() override { co_return succeed(1); } }; @@ -194,10 +201,12 @@ Void::Testing::Test restart_at_changes_initial_state() namespace { - class Mut : public Fsm::Machine + class Mut : public Fsm::Machine { public: + using Success = int; + struct A : State { Task run() override { co_return succeed(1); } }; @@ -245,10 +254,12 @@ namespace struct Go { }; - class Sleeper : public Fsm::Machine + class Sleeper : public Fsm::Machine { public: + using Success = int; + struct W : State { Task run() override { diff --git a/tests/standalone/Fsm/Events.cpp b/tests/standalone/Fsm/Events.cpp index 99f48ff..76f2eff 100644 --- a/tests/standalone/Fsm/Events.cpp +++ b/tests/standalone/Fsm/Events.cpp @@ -20,10 +20,12 @@ namespace }; // Waits for Input events, accumulating until a Stop event arrives. - class Accumulator : public Void::Fsm::Machine + class Accumulator : public Void::Fsm::Machine { public: + using Success = int; + int total = 0; std::vector* order = nullptr; @@ -45,7 +47,7 @@ namespace }; explicit Accumulator(bool own_worker) - : Void::Fsm::Machine( + : Void::Fsm::Machine( MachineOptions{.own_worker = own_worker}) { initial(); diff --git a/tests/standalone/Fsm/Hierarchy.cpp b/tests/standalone/Fsm/Hierarchy.cpp index bc162e4..ba7e107 100644 --- a/tests/standalone/Fsm/Hierarchy.cpp +++ b/tests/standalone/Fsm/Hierarchy.cpp @@ -24,10 +24,13 @@ namespace // Child region: waits for either Tick (succeed) or Cancel (fail), // handling both at one level via await_any. - class Work : public Void::Fsm::Machine + class Work : public Void::Fsm::Machine { public: + using Success = std::string; + using Failure = Void::Fsm::FsmError; + struct Waiting : State { Task run() override { @@ -41,17 +44,19 @@ namespace using States = Void::Fsm::States; explicit Work(MachineOptions opts = {}) - : Void::Fsm::Machine(opts) + : Void::Fsm::Machine(opts) { } }; // Parent: a composite Running state enters the Work region and maps its // result — success passes the value through, failure routes to a sibling. - class Job : public Void::Fsm::Machine + class Job : public Void::Fsm::Machine { public: + using Success = std::string; + struct Running : State { Task run() override { @@ -71,7 +76,7 @@ namespace using States = Void::Fsm::States; explicit Job(MachineOptions opts = {}) - : Void::Fsm::Machine(opts) + : Void::Fsm::Machine(opts) { } }; diff --git a/tests/standalone/Fsm/Lifecycle.cpp b/tests/standalone/Fsm/Lifecycle.cpp index f91788e..4f22177 100644 --- a/tests/standalone/Fsm/Lifecycle.cpp +++ b/tests/standalone/Fsm/Lifecycle.cpp @@ -13,10 +13,12 @@ using Void::Fsm::Transition; namespace { // Records enter/run/exit for each state into a shared log. - class Lifecycle : public Void::Fsm::Machine + class Lifecycle : public Void::Fsm::Machine { public: + using Success = int; + std::vector log; struct A : State { @@ -58,7 +60,7 @@ namespace using States = Void::Fsm::States; Lifecycle() - : Void::Fsm::Machine( + : Void::Fsm::Machine( MachineOptions{.own_worker = false}) { } @@ -106,15 +108,14 @@ Void::Testing::Test fsm_state_names_and_path() // run() which fails — confirms the default body exists. Void::Testing::Test fsm_state_without_run_fails() { - struct NoRun : Void::Fsm::Machine { + struct NoRun : Void::Fsm::Machine { struct Stuck : State { Task on_enter() override { co_return; } // no run() override }; using States = Void::Fsm::States; NoRun() - : Void::Fsm::Machine( - MachineOptions{.own_worker = false}) + : Void::Fsm::Machine(MachineOptions{.own_worker = false}) { } } fsm; diff --git a/tests/standalone/Fsm/Nesting.cpp b/tests/standalone/Fsm/Nesting.cpp index 86830dc..a7b8e31 100644 --- a/tests/standalone/Fsm/Nesting.cpp +++ b/tests/standalone/Fsm/Nesting.cpp @@ -11,10 +11,12 @@ using Void::Fsm::Step; namespace { // Child machine: computes a value and succeeds. - class Subtotal : public Void::Fsm::Machine + class Subtotal : public Void::Fsm::Machine { public: + using Success = int; + int seed; struct Compute : State { @@ -26,7 +28,7 @@ namespace }; explicit Subtotal(int s) - : Void::Fsm::Machine( + : Void::Fsm::Machine( MachineOptions{.own_worker = false}), seed(s) { @@ -35,15 +37,18 @@ namespace }; // Child machine that fails. - class FailingChild : public Void::Fsm::Machine + class FailingChild : public Void::Fsm::Machine { public: + using Success = int; + using Failure = Void::Fsm::FsmError; + struct Boom : State { Task run() override { co_return fail("child boom"); } }; FailingChild() - : Void::Fsm::Machine( + : Void::Fsm::Machine( MachineOptions{.own_worker = false}) { initial(); @@ -51,10 +56,13 @@ namespace }; // Parent: enters a child, uses its result to decide the outcome. - class Parent : public Void::Fsm::Machine + class Parent : public Void::Fsm::Machine { public: + using Success = int; + using Failure = Void::Fsm::FsmError; + struct Start : State { Task run() override { @@ -68,17 +76,20 @@ namespace }; Parent() - : Void::Fsm::Machine( + : Void::Fsm::Machine( MachineOptions{.own_worker = false}) { initial(); } }; - class ParentOfFailure : public Void::Fsm::Machine + class ParentOfFailure : public Void::Fsm::Machine { public: + using Success = int; + using Failure = Void::Fsm::FsmError; + struct Start : State { Task run() override { @@ -91,7 +102,7 @@ namespace }; ParentOfFailure() - : Void::Fsm::Machine( + : Void::Fsm::Machine( MachineOptions{.own_worker = false}) { initial(); @@ -121,7 +132,9 @@ Void::Testing::Test fsm_nesting_with_worker_thread() { Parent fsm{}; // embedder by default here // Re-run as worker-driven to exercise the shared executor + worker. - struct WorkerParent : Void::Fsm::Machine { + struct WorkerParent : Void::Fsm::Machine { + using Success = int; + struct Start : State { Task run() override { diff --git a/tests/standalone/Fsm/Policies.cpp b/tests/standalone/Fsm/Policies.cpp index a1fc768..69b32a6 100644 --- a/tests/standalone/Fsm/Policies.cpp +++ b/tests/standalone/Fsm/Policies.cpp @@ -19,10 +19,13 @@ namespace { // Attempt fails the first `fail_n` times, then succeeds. with_retry // keeps trying; next_or routes exhaustion to a fallback. - class Flaky : public Void::Fsm::Machine + class Flaky : public Void::Fsm::Machine { public: + using Success = std::string; + using Failure = Void::Fsm::FsmError; + int fail_n = 0; int attempts = 0; int retries; // how many tries with_retry gets @@ -82,10 +85,12 @@ Void::Testing::Test retry_exhausts_routes_to_fallback() namespace { - class Pipe : public Void::Fsm::Machine + class Pipe : public Void::Fsm::Machine { public: + using Success = int; + struct A : State { Task run() override { co_return next(); } }; @@ -94,8 +99,7 @@ namespace }; using States = Void::Fsm::States; Pipe() - : Void::Fsm::Machine( - MachineOptions{.own_worker = false}) + : Void::Fsm::Machine(MachineOptions{.own_worker = false}) { } }; @@ -145,10 +149,12 @@ namespace struct Cancel { }; - class Flow : public Void::Fsm::Machine + class Flow : public Void::Fsm::Machine { public: + using Success = int; + struct Idle : Reactive { void transitions(TransitionBuilder& on) override { diff --git a/tests/standalone/Fsm/Reactive.cpp b/tests/standalone/Fsm/Reactive.cpp index 76f91aa..34636df 100644 --- a/tests/standalone/Fsm/Reactive.cpp +++ b/tests/standalone/Fsm/Reactive.cpp @@ -22,10 +22,13 @@ namespace // A declarative machine: Idle reacts to events with guards/actions; on // timeout it bails out. - class Gate : public Void::Fsm::Machine + class Gate : public Void::Fsm::Machine { public: + using Success = int; + using Failure = Void::Fsm::FsmError; + int total = 0; std::vector trace; @@ -87,10 +90,12 @@ namespace }; // Imperative state using await_event_for: times out → expired. - class Sleeper : public Void::Fsm::Machine + class Sleeper : public Void::Fsm::Machine { public: + using Success = std::string; + struct Waiting : State { Task run() override { @@ -129,10 +134,12 @@ Void::Testing::Test await_event_for_receives_event() namespace { // Reactive timeout transition (on.after().to<>). - class Deadline : public Void::Fsm::Machine + class Deadline : public Void::Fsm::Machine { public: + using Success = int; + struct Pending : Reactive { void transitions(TransitionBuilder& on) override { diff --git a/tests/standalone/Fsm/Serialize.cpp b/tests/standalone/Fsm/Serialize.cpp index d7da97d..efaa40e 100644 --- a/tests/standalone/Fsm/Serialize.cpp +++ b/tests/standalone/Fsm/Serialize.cpp @@ -13,10 +13,12 @@ namespace { // A machine that parks at a named state and exposes its data for // serialize/restore. - class Pipeline : public Void::Fsm::Machine + class Pipeline : public Void::Fsm::Machine { public: + using Success = int; + struct Data { int processed = 0; std::string stage = "init"; @@ -40,7 +42,7 @@ namespace }; Pipeline() - : Void::Fsm::Machine( + : Void::Fsm::Machine( MachineOptions{.own_worker = false}) { initial(); diff --git a/tests/standalone/Fsm/SubMachine.cpp b/tests/standalone/Fsm/SubMachine.cpp index 2a5d890..7e2aba3 100644 --- a/tests/standalone/Fsm/SubMachine.cpp +++ b/tests/standalone/Fsm/SubMachine.cpp @@ -3,6 +3,7 @@ #include #include +#include using Void::Coro::Task; using Void::Fsm::FsmError; @@ -16,10 +17,13 @@ namespace Fsm = Void::Fsm; namespace { // Sub-machine seeded by constructor arg: doubles `seed`, fails if negative. - class Doubler : public Fsm::Machine + class Doubler : public Fsm::Machine { public: + using Success = int; + using Failure = Void::Fsm::FsmError; + int seed; struct Run : State { @@ -36,10 +40,12 @@ namespace explicit Doubler(int s = 0) : seed(s) {} }; - class Calc : public Fsm::Machine + class Calc : public Fsm::Machine { public: + using Success = std::string; + int input = 0; struct Start : State { @@ -49,7 +55,7 @@ namespace self().input); } }; - struct AfterDouble : Continue { + struct AfterDouble : Continue { Task on_success(int v) override { co_return succeed("doubled:" + std::to_string(v)); @@ -87,7 +93,7 @@ Void::Testing::Test submachine_failure_dispatches_on_failure() namespace { - class Pinger : public Fsm::Machine + class Pinger : public Fsm::Machine { public: @@ -97,18 +103,23 @@ namespace using States = Fsm::States; }; - class Host : public Fsm::Machine + class Host : public Fsm::Machine { public: + using Success = int; + struct Go : State { Task run() override { co_return startMachine(); } }; - struct Done : Continue { - Task on_success() override { co_return succeed(42); } + struct Done : Continue { + Task on_success(std::monostate) override + { + co_return succeed(42); + } }; using States = Fsm::States; }; @@ -127,23 +138,25 @@ Void::Testing::Test submachine_void_result_calls_nullary_on_success() namespace { - class Chain : public Fsm::Machine + class Chain : public Fsm::Machine { public: + using Success = int; + struct A : State { Task run() override { co_return startMachine(3); // 3 -> 6 } }; - struct B : Continue { + struct B : Continue { Task on_success(int v) override { co_return startMachine(v); // 6 -> 12 } }; - struct C : Continue { + struct C : Continue { Task on_success(int v) override { co_return succeed(v); @@ -169,10 +182,12 @@ namespace struct Tick { }; - class WaitSub : public Fsm::Machine + class WaitSub : public Fsm::Machine { public: + using Success = int; + struct W : State { Task run() override { @@ -183,17 +198,19 @@ namespace using States = Fsm::States; }; - class Outer : public Fsm::Machine + class Outer : public Fsm::Machine { public: + using Success = int; + struct Begin : State { Task run() override { co_return startMachine(); } }; - struct Fin : Continue { + struct Fin : Continue { Task on_success(int v) override { co_return succeed(v); diff --git a/tests/standalone/Service/Orchestrator.cpp b/tests/standalone/Service/Orchestrator.cpp index 3ed6da4..3a17033 100644 --- a/tests/standalone/Service/Orchestrator.cpp +++ b/tests/standalone/Service/Orchestrator.cpp @@ -66,10 +66,12 @@ namespace }; // An FSM that bumps the counter service N times then succeeds. - class Worker : public Void::Fsm::Machine + class Worker : public Void::Fsm::Machine { public: + using Success = int; + int times; struct Run : State { @@ -85,7 +87,7 @@ namespace }; explicit Worker(int t) - : Void::Fsm::Machine( + : Void::Fsm::Machine( MachineOptions{.own_worker = false}), times(t) { @@ -110,7 +112,9 @@ Void::Testing::Test orchestrator_launches_and_supervises() { // Worker-backed FSM so the orchestrator's start() spins a worker and // the FSM runs to completion on its own. - struct AsyncWorker : Void::Fsm::Machine { + struct AsyncWorker : Void::Fsm::Machine { + using Success = int; + struct Run : State { Task run() override {