FSM: typed Success/Failure result model (reflected nested types)

A machine is now Machine<Derived> (dropping the ResultT template param) and
declares its result types as nested types reflected *by name* — Success and
Failure (a struct or a using-alias), each defaulting to void:

    class Login : public Machine<Login> {
      using Success = Token;     // or a nested struct; default void
      struct Failure { int code; };
    };

- Outcome = std::expected<Success, Failure> (void failure -> std::monostate
  error arm). succeed(Success{...}) / fail(Failure{...}) carry the typed
  values (nullary when void). Resolved by plain dependent-name lookup
  (Detail/Result.hpp), no P2996.
- Engine/system faults (no initial state, unregistered target, no entry)
  travel a SEPARATE FsmError channel: status()==Faulted + system_error(),
  never the typed Failure. New Step::Kind::Fault carries it.
- CRTP wrinkle: Derived is incomplete at base instantiation, so the engine
  stores the result type-erased (std::any) and rebuilds the typed Outcome in
  wait()/run_blocking()/take_outcome() — function templates defaulted on
  Derived. run_child/run_region/start_machine reconstruct OutcomeOf<Sub> at
  the boundary (Sub is complete).
- Step carries Success/Failure payloads as std::any; the reactive DSL
  (finish/fail) and Continue<Sub> are reparameterised off the nested types.

Interim: Continue<Sub> keeps the named on_success/on_failure form (Phase 2
replaces it with signature-inferred ChildSuccess/ChildFailure). All FSM
tests migrated to the nested-type form. 995 tests (992 green, 3 skipped),
ASan clean, -Werror clean; the lone intermittent failure is the
pre-existing racy plugin hot-reload-under-load test (flaky on HEAD too).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Fable 5 committed 2026-06-14 21:14:43 +03:00
1 parent 7c7c590d79
commit 9e9eb838ea
20 files changed
+487 -245

No files matched your search

+40 -51
View File
@@ -2,86 +2,75 @@
#include <Void/Async/Task.hpp>
#include <Void/Fsm/Detail/Engine.hpp>
#include <Void/Fsm/Detail/Result.hpp>
#include <Void/Fsm/Step.hpp>
#include <any>
#include <type_traits>
#include <utility>
#include <variant>
namespace Void::Fsm::Detail
{
namespace Coro = Void::Coro;
// Base for a state that resumes from a sub-machine launched via
// startMachine<Sub, This>(). `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<Sub, This>(). `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<Sub>`.
//
// Machine exposes it as `Continue<R>`; users derive it and implement
// on_success(R) (and optionally on_failure).
template <typename StateT, typename SubResult>
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 <typename StateT, typename Sub> class Continuation : public StateT
{
using Succ = SuccessOf<Sub>;
using Fail = FailureOf<Sub>;
using SuccArg =
std::conditional_t<std::is_void_v<Succ>, std::monostate, Succ>;
using FailArg =
std::conditional_t<std::is_void_v<Fail>, std::monostate, Fail>;
public:
Coro::Task<Step> resume(LaunchResult lr) final
{
if (lr.ok) {
if (lr.kind == LaunchResult::Kind::Failure) {
if constexpr (std::is_void_v<Fail>) {
co_return co_await on_failure(std::monostate{});
} else {
co_return co_await on_failure(
std::any_cast<Fail>(std::move(lr.failure)));
}
}
if constexpr (std::is_void_v<Succ>) {
co_return co_await on_success(std::monostate{});
} else {
co_return co_await on_success(
std::any_cast<SubResult>(std::move(lr.value)));
std::any_cast<Succ>(std::move(lr.value)));
}
co_return co_await on_failure(std::move(lr.error));
}
Coro::Task<Step> run() override
{
co_return this->fail(
"Continue<R> state entered without a sub-machine result "
"(reach it via startMachine<Sub, This>())");
co_return Step::fault(FsmError{
"continuation state entered without a sub-machine result "
"(reach it via startMachine<Sub, This>())"});
}
protected:
/// The sub-machine succeeded with `result`.
virtual Coro::Task<Step> on_success(SubResult result) = 0;
virtual Coro::Task<Step> on_success(SuccArg result) = 0;
/// The sub-machine failed. Default: fail the parent with the same
/// message; override to recover.
virtual Coro::Task<Step> on_failure(FsmError error)
/// Default: a sub-machine failure the parent didn't handle becomes
/// a system fault. Override to recover.
virtual Coro::Task<Step> 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 <typename StateT> class Continuation<StateT, void> : public StateT
{
public:
Coro::Task<Step> 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<Step> run() override
{
co_return this->fail(
"Continue<void> state entered without a sub-machine result "
"(reach it via startMachine<Sub, This>())");
}
protected:
virtual Coro::Task<Step> on_success() = 0;
virtual Coro::Task<Step> 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
+42 -21
View File
@@ -1,6 +1,7 @@
#pragma once
#include <Void/Async/Task.hpp>
#include <Void/Fsm/Detail/Result.hpp>
#include <Void/Fsm/Detail/TypeName.hpp>
#include <Void/Fsm/Step.hpp>
@@ -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<E>().guard(..).action(..)
/// .to<S>()` (or `.finish(v)` / `.fail(msg)`).
template <typename Derived, typename ResultT, typename E> class EventClause
/// .to<S>()` (or `.finish(v)` / `.fail(v)`).
template <typename Derived, typename E> class EventClause
{
public:
@@ -88,21 +90,31 @@ namespace Void::Fsm::Detail
}
void finish()
requires std::is_void_v<ResultT>
requires std::is_void_v<SuccessOf<Derived>>
{
commit(Step::success(std::any{}), "(success)");
}
template <typename V>
void finish(V&& value)
requires(!std::is_void_v<ResultT>)
requires(!std::is_void_v<SuccessOf<Derived>>)
{
commit(Step::success(std::any{ResultT(std::forward<V>(value))}),
commit(Step::success(std::any{
SuccessOf<Derived>(std::forward<V>(value))}),
"(success)");
}
void fail(std::string message)
void fail()
requires std::is_void_v<FailureOf<Derived>>
{
commit(Step::failure(FsmError{std::move(message)}), "(fail)");
commit(Step::failure(std::any{}), "(fail)");
}
template <typename V>
void fail(V&& value)
requires(!std::is_void_v<FailureOf<Derived>>)
{
commit(Step::failure(std::any{
FailureOf<Derived>{std::forward<V>(value)}}),
"(fail)");
}
private:
@@ -136,8 +148,8 @@ namespace Void::Fsm::Detail
std::function<Coro::Task<void>(Derived&, const E&)> m_action;
};
/// Fluent builder for the timeout row: `on.after(d).to<S>()` / `.fail(..)`.
template <typename Derived, typename ResultT> class AfterClause
/// Fluent builder for the timeout row: `on.after(d).to<S>()` / `.fail(v)`.
template <typename Derived> class AfterClause
{
public:
@@ -159,12 +171,22 @@ namespace Void::Fsm::Detail
m_table->timeout_target_name = type_name<S>();
}
void fail(std::string message)
void fail()
requires std::is_void_v<FailureOf<Derived>>
{
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 <typename V>
void fail(V&& value)
requires(!std::is_void_v<FailureOf<Derived>>)
{
m_table->has_timeout = true;
m_table->timeout_after = m_after;
m_table->timeout_step = Step::failure(
std::any{FailureOf<Derived>{std::forward<V>(value)}});
m_table->timeout_target_name = "(fail)";
}
@@ -175,7 +197,7 @@ namespace Void::Fsm::Detail
};
/// Entry point handed to `transitions(TransitionBuilder& on)`.
template <typename Derived, typename ResultT> class TransitionBuilder
template <typename Derived> class TransitionBuilder
{
public:
@@ -184,17 +206,16 @@ namespace Void::Fsm::Detail
{
}
template <typename E>
[[nodiscard]] EventClause<Derived, ResultT, E> event()
template <typename E> [[nodiscard]] EventClause<Derived, E> event()
{
return EventClause<Derived, ResultT, E>{*m_table};
return EventClause<Derived, E>{*m_table};
}
template <typename Rep, typename Period>
[[nodiscard]] AfterClause<Derived, ResultT>
[[nodiscard]] AfterClause<Derived>
after(std::chrono::duration<Rep, Period> d)
{
return AfterClause<Derived, ResultT>{
return AfterClause<Derived>{
*m_table, std::chrono::duration_cast<
std::chrono::steady_clock::duration>(d)};
}
+52
View File
@@ -0,0 +1,52 @@
#pragma once
#include <expected>
#include <type_traits>
#include <utility>
#include <variant>
// 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<Login> {
// 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 <typename D> consteval auto success_probe()
{
if constexpr (requires { typename D::Success; }) {
return std::type_identity<typename D::Success>{};
} else {
return std::type_identity<void>{};
}
}
template <typename D> consteval auto failure_probe()
{
if constexpr (requires { typename D::Failure; }) {
return std::type_identity<typename D::Failure>{};
} else {
return std::type_identity<void>{};
}
}
/// The machine's success result type (nested `Success`, else void).
template <typename D>
using SuccessOf = typename decltype(success_probe<D>())::type;
/// The machine's failure result type (nested `Failure`, else void).
template <typename D>
using FailureOf = typename decltype(failure_probe<D>())::type;
/// std::expected can't have a void error arm — map void failure to a unit.
template <typename F>
using ErrArm = std::conditional_t<std::is_void_v<F>, 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 <typename D>
using OutcomeOf = std::expected<SuccessOf<D>, ErrArm<FailureOf<D>>>;
} // namespace Void::Fsm::Detail
+156 -68
View File
@@ -8,6 +8,7 @@
#include <Void/Fsm/Detail/Engine.hpp>
#include <Void/Fsm/Detail/Introspect.hpp>
#include <Void/Fsm/Detail/Reactive.hpp>
#include <Void/Fsm/Detail/Result.hpp>
#include <Void/Fsm/Detail/TypeName.hpp>
#include <Void/Fsm/Step.hpp>
#include <Void/Log/Log.hpp>
@@ -89,13 +90,25 @@ namespace Void::Fsm
// };
// using States = Void::Fsm::States<Check>;
// };
template <typename Derived, typename ResultT = void> class Machine
template <typename Derived> class Machine
{
public:
using result_type = ResultT;
using Options = MachineOptions;
using Outcome = std::expected<ResultT, FsmError>;
// 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 <typename D = Derived>
using Success = Detail::SuccessOf<D>;
template <typename D = Derived>
using Failure = Detail::FailureOf<D>;
template <typename D = Derived>
using Outcome = Detail::OutcomeOf<D>;
// ── 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<ResultT>
requires std::is_void_v<Detail::SuccessOf<Derived>>
{
return Step::success(std::any{});
}
template <typename V>
[[nodiscard]] Step succeed(V&& value) const
requires(!std::is_void_v<ResultT>)
requires(!std::is_void_v<Detail::SuccessOf<Derived>>)
{
return Step::success(
std::any{ResultT(std::forward<V>(value))});
std::any{Detail::SuccessOf<Derived>(
std::forward<V>(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<Detail::FailureOf<Derived>>
{
return Step::failure(FsmError{std::move(message)});
return Step::failure(std::any{});
}
template <typename V>
[[nodiscard]] Step fail(V&& value) const
requires(!std::is_void_v<Detail::FailureOf<Derived>>)
{
return Step::failure(
std::any{Detail::FailureOf<Derived>{
std::forward<V>(value)}});
}
template <typename I> [[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<typename Sub::result_type>, Next>,
std::is_base_of_v<Continue<Sub>, Next>,
"startMachine<Sub, Next>: Next must derive "
"Continue<Sub::result_type>");
"Continue<Sub>");
return m_machine->template start_machine<Sub, Next>(
std::forward<Args>(args)...);
}
@@ -298,8 +324,8 @@ namespace Void::Fsm
// Coro::Task<Step> on_failure(FsmError e) override {
// co_return fail(e.message); }
// };
template <typename SubResult>
using Continue = Detail::Continuation<State, SubResult>;
template <typename Sub>
using Continue = Detail::Continuation<State, Sub>;
// ── 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<Derived>;
using TransitionBuilder =
Detail::TransitionBuilder<Derived, ResultT>;
using TransitionBuilder = Detail::TransitionBuilder<Derived>;
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 <typename D = Derived> Outcome<D> 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<D>();
}
Outcome run_blocking()
template <typename D = Derived> Outcome<D> run_blocking()
{
start();
return wait();
return wait<D>();
}
/// The system fault (if any) — a programming error caught by the
/// engine, separate from a typed Failure result.
[[nodiscard]] std::optional<FsmError> 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 <typename Sub, typename... Args>
[[nodiscard]] Coro::Task<typename Sub::Outcome>
[[nodiscard]] Coro::Task<Detail::OutcomeOf<Sub>>
run_child(Args&&... args)
{
Sub child{std::forward<Args>(args)...};
child.attach(m_ctx, m_services);
co_return co_await child.drive();
co_await child.drive();
co_return child.template take_outcome<Sub>();
}
/// 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 <typename Sub, typename... Args>
[[nodiscard]] Coro::Task<typename Sub::Outcome>
[[nodiscard]] Coro::Task<Detail::OutcomeOf<Sub>>
run_region(Args&&... args)
{
Sub child{std::forward<Args>(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<Sub>();
}
/// 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>(
args)...)]() mutable -> Coro::Task<LaunchResult> {
auto outcome = co_await std::apply(
[this](auto&&... a) {
return this->template run_child<Sub>(
std::forward<decltype(a)>(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<Sub>(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 <typename, typename>
template <typename>
friend class Machine; // run_child reaches child internals
void attach(std::shared_ptr<Detail::ExecutionContext> 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<Outcome> 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<void> 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<S>() 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<R> 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<R>) state.
m_pending_result.emplace(
co_await step.run_launch());
cur = step.target();
continue;
case Step::Kind::Success:
if constexpr (std::is_void_v<ResultT>) {
co_return Outcome{};
} else {
co_return Outcome{std::any_cast<ResultT>(
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<FsmError>(step.payload())
.message);
co_return;
}
}
}
Coro::Task<void> 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<Derived> resolve where Derived is
// complete. A system fault yields a default-constructed error arm
// (consult system_error()).
template <typename D = Derived> Outcome<D> take_outcome()
{
if (m_outcome.has_value()) {
return std::move(*m_outcome);
using Succ = Detail::SuccessOf<D>;
using Fail = Detail::FailureOf<D>;
using Err = Detail::ErrArm<Fail>;
switch (m_status.load(std::memory_order_acquire)) {
case Status::Succeeded:
if constexpr (std::is_void_v<Succ>) {
return Outcome<D>{};
} else {
return Outcome<D>{
std::any_cast<Succ>(m_result_value)};
}
case Status::Failed:
if constexpr (std::is_void_v<Fail>) {
return Outcome<D>{std::unexpect, std::monostate{}};
} else {
return Outcome<D>{
std::unexpect,
std::any_cast<Fail>(m_result_value)};
}
default: // Faulted / not finished
static_assert(
std::is_default_constructible_v<Err>,
"a machine with a non-default-constructible "
"Failure "
"cannot represent a system fault in its Outcome; "
"check system_error()");
return Outcome<D>{std::unexpect, Err{}};
}
return std::unexpected{FsmError{"machine did not finish"}};
}
Options m_options;
@@ -1137,7 +1222,10 @@ namespace Void::Fsm
std::atomic<int> m_current{-1};
std::atomic<Status> m_status{Status::Idle};
std::optional<Outcome> 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<FsmError> m_system_error;
std::function<void(const Transition&)> m_observer;
std::vector<Interceptor> m_interceptors;
std::uint64_t m_step{0};
+42 -31
View File
@@ -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<Sub, Next>():
/// `ok` with the result in `value` (a `Sub::result_type`, empty for void),
/// or `!ok` with `error`. Delivered to the Next state's Continue<R>
/// 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<S>() / succeed() / fail()).
/// The outcome of a sub-machine launched via startMachine<Sub, Next>():
/// 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<S>() / 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<R> 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<Coro::Task<LaunchResult>()> 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<LaunchResult> 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<Coro::Task<LaunchResult>()> m_launcher;
};