FSM v2 (A): CRTP typed access, States<> auto-registration, lifecycle, observers

Maintainability core, breaking the state API (all FSM tests migrated):
- Machine<Derived, ResultT> (CRTP). State::self() returns Derived& — drops
  the static_cast<Derived&>(machine()) boilerplate from every state.
- `using States = Fsm::States<...>` auto-registers every state in the base
  ctor (first entry = initial unless `using Initial = S`); no more manual
  add<S>()/initial<S>() for static machines. next<S>() static_asserts S is
  in the list (unregistered targets are now a COMPILE error, not a runtime
  fail); next_dynamic<S>() + add<S>()/add_if<S>() remain for dynamic
  machines.
- Per-state lifecycle: StateBase gains virtual on_enter()/on_exit()
  (Coro::Task<void>, default no-op) run around run(); the engine visit is
  enter -> run -> exit, so entry/exit actions split out of run(). run()
  now has a default (fails) so reactive states (Phase B) needn't define it.
- Observability: virtual on_transition(from,to) (default logs via Void::Log)
  + observe(fn) called on every transition (and the initial entry) with a
  Transition{from,to,step}. state_path()/state_names() added.

Migrated Basic/Events/Nesting/Serialize/Concurrency + the Orchestrator and
service-hot-reload tests to CRTP + self() + States<>; new Lifecycle suite
(enter/run/exit ordering, observer edges, default-run failure). 968 green,
ASan+UBSan clean, -Werror clean.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Fable 5 committed 2026-06-14 01:03:43 +03:00
1 parent 7b6cd7341a
commit e941a48007
11 files changed
+355 -117

No files matched your search

+23 -3
View File
@@ -19,14 +19,34 @@
namespace Void::Fsm::Detail
{
/// Type-erased state. Concrete states derive Machine<R>::State, which
/// derives this; run() is driven by the engine.
/// How the engine drives a state.
enum class StateKind {
Imperative, // defines run() returning a Step
Reactive // defines a transition table (Phase B)
};
/// Type-erased state. Concrete states derive Machine<Derived,R>::State
/// (or ::Reactive); the engine drives the lifecycle: on_enter → run →
/// on_exit, following the Step that run() returns.
class StateBase
{
public:
virtual ~StateBase() = default;
virtual Coro::Task<Step> run() = 0;
[[nodiscard]] virtual StateKind kind() const noexcept
{
return StateKind::Imperative;
}
/// Entry/exit hooks. Default no-ops; states may override either
/// or both to split behaviour out of run().
virtual Coro::Task<void> on_enter();
virtual Coro::Task<void> on_exit();
/// Main body. Default fails (a state must define run() unless it
/// is reactive, in which case the engine uses its table).
virtual Coro::Task<Step> run();
};
struct EventEnvelope {
+140 -43
View File
@@ -5,17 +5,20 @@
#include <Void/Data/Json.hpp>
#include <Void/Fsm/Detail/Engine.hpp>
#include <Void/Fsm/Step.hpp>
#include <Void/Log/Log.hpp>
#include <Void/Service/Registry.hpp>
#include <any>
#include <atomic>
#include <coroutine>
#include <cstdint>
#include <expected>
#include <functional>
#include <memory>
#include <optional>
#include <string>
#include <string_view>
#include <tuple>
#include <type_traits>
#include <typeindex>
#include <typeinfo>
@@ -30,33 +33,54 @@
namespace Void::Fsm
{
/// Compile-time list of a machine's states. Declare it in the derived
/// machine to auto-register every state and enable compile-time
/// validation of next<S>() targets:
/// using States = Void::Fsm::States<Idle, Running, Done>;
/// The first entry is the initial state unless `using Initial = S;`.
template <typename... Ss> struct States {
static constexpr std::size_t size = sizeof...(Ss);
template <typename S> static constexpr bool contains()
{
return (std::is_same_v<S, Ss> || ...);
}
};
/// Options for a Machine (namespace scope to dodge the GCC
/// nested-default-arg trap).
struct MachineOptions {
/// Spawn a worker thread on start(). When false, drive the machine
/// yourself with pump() (deterministic; used by most tests and by
/// nested children, which share the parent's worker).
bool own_worker = true;
};
// ── Machine<ResultT> ──────────────────────────────────────────────────
/// A transition record handed to observers.
struct Transition {
std::string from;
std::string to;
std::uint64_t step{0};
};
// ── Machine<Derived, ResultT> ─────────────────────────────────────────
//
// Inheritance + coroutine workflow FSM. Derive it, declare states as
// nested structs deriving `State`, implement each state's async run()
// to return next<S>() / succeed(...) / fail(...). States may co_await
// external events and nest child machines.
// Inheritance + coroutine workflow FSM, CRTP for typed access. Derive
// it, declare states as nested structs deriving `State`, list them in
// `using States = Fsm::States<...>`, and implement each state's async
// run() to return next<S>() / succeed(...) / fail(...). States reach
// their owning machine (and its data + sub-methods) via self().
//
// class Login : public Void::Fsm::Machine<bool> {
// class Login : public Void::Fsm::Machine<Login, bool> {
// public:
// struct Idle : State { Coro::Task<Step> run() override {
// auto c = co_await await_event<Creds>();
// co_return next<Check>(); } };
// struct Check : State { Coro::Task<Step> run() override {
// co_return service<IAuth>().ok()
// ? succeed(true) : fail("bad creds"); } };
// Login() { initial<Idle>(); add<Check>(); }
// int attempts = 0;
// struct Check : State {
// Coro::Task<Step> run() override {
// if (++self().attempts > 3) co_return fail("locked");
// co_return self().service<IAuth>().ok() ? succeed(true)
// : next<Check>();
// }
// };
// using States = Void::Fsm::States<Check>;
// };
template <typename ResultT = void> class Machine
template <typename Derived, typename ResultT = void> class Machine
{
public:
@@ -69,6 +93,12 @@ namespace Void::Fsm
{
public:
/// Typed access to the owning machine — no static_cast.
[[nodiscard]] Derived& self() const noexcept
{
return *static_cast<Derived*>(m_machine);
}
[[nodiscard]] Machine& machine() const noexcept
{
return *m_machine;
@@ -76,13 +106,27 @@ namespace Void::Fsm
protected:
/// Transition to another registered state.
/// Transition to another state. Validated at compile
/// time when the machine declares `using States`.
template <typename S> [[nodiscard]] Step next() const
{
if constexpr (requires { typename Derived::States; }) {
static_assert(
Derived::States::template contains<S>(),
"next<S>: S is not in this machine's "
"States<...> list");
}
return Step::transition(typeid(S));
}
/// Transition to a state registered dynamically
/// (add<S>()/add_if<S>()), skipping the static check.
template <typename S>
[[nodiscard]] Step next_dynamic() const
{
return Step::transition(typeid(S));
}
/// Finish the machine successfully.
[[nodiscard]] Step succeed() const
requires std::is_void_v<ResultT>
{
@@ -96,25 +140,21 @@ namespace Void::Fsm
std::any{ResultT(std::forward<V>(value))});
}
/// Finish the machine with a failure.
[[nodiscard]] Step fail(std::string message) const
{
return Step::failure(FsmError{std::move(message)});
}
/// Resolve a service from the injected registry.
template <typename I> [[nodiscard]] I& service() const
{
return m_machine->template service<I>();
}
/// Suspend until an event of type E is posted.
template <typename E> [[nodiscard]] auto await_event() const
{
return m_machine->template await_event<E>();
}
/// Run a child machine to completion and get its result.
template <typename Sub, typename... Args>
[[nodiscard]] auto run_child(Args&&... args) const
{
@@ -134,14 +174,24 @@ namespace Void::Fsm
};
// ── construction ──────────────────────────────────────────────
explicit Machine(Options options = {}) : m_options(options) {}
explicit Machine(Options options = {}) : m_options(options)
{
if constexpr (requires { typename Derived::States; }) {
register_states(typename Derived::States{});
if constexpr (requires { typename Derived::Initial; }) {
m_initial = &typeid(typename Derived::Initial);
} else {
m_initial = first_type(typename Derived::States{});
}
}
}
virtual ~Machine() { stop(); }
Machine(const Machine&) = delete;
Machine& operator=(const Machine&) = delete;
// ── registration (call from the derived ctor) ─────────────────
// ── registration ──────────────────────────────────────────────
template <typename S> void add()
{
static_assert(std::is_base_of_v<State, S>,
@@ -169,7 +219,6 @@ namespace Void::Fsm
m_initial = &typeid(S);
}
/// Conditionally register a state (dynamic machines).
template <typename S> void add_if(bool condition)
{
if (condition) {
@@ -193,6 +242,14 @@ namespace Void::Fsm
return m_services->template require<I>();
}
// ── observability ─────────────────────────────────────────────
/// Register a read-only observer fired on every transition
/// (and on the initial entry). Replaces any prior observer.
void observe(std::function<void(const Transition&)> observer)
{
m_observer = std::move(observer);
}
// ── lifecycle ─────────────────────────────────────────────────
void start()
{
@@ -210,11 +267,6 @@ namespace Void::Fsm
}
}
/// Block until the machine finishes, returning its outcome.
/// With a worker, joins it. In embedder mode, drives the
/// machine to completion (returns early if it parks waiting
/// for an event that never arrives). Do not call from the
/// worker thread.
Outcome wait()
{
if (m_ctx) {
@@ -223,7 +275,7 @@ namespace Void::Fsm
} else {
while (!finished()) {
if (m_ctx->pump() == 0 && !finished()) {
break; // parked on an unposted event
break;
}
}
}
@@ -231,15 +283,12 @@ namespace Void::Fsm
return take_outcome();
}
/// start() + wait().
Outcome run_blocking()
{
start();
return wait();
}
/// Drive a worker-less machine: deliver events + run ready
/// coroutines. Returns work done. Single consumer only.
std::size_t pump() { return m_ctx ? m_ctx->pump() : 0; }
[[nodiscard]] bool finished() const noexcept
@@ -312,6 +361,23 @@ namespace Void::Fsm
return m_names[static_cast<std::size_t>(idx)];
}
/// Active state chain (root → leaf). Currently a single entry;
/// hierarchy (Phase D) extends it.
[[nodiscard]] std::vector<std::string> state_path() const
{
if (auto s = current_state(); !s.empty()) {
return {std::move(s)};
}
return {};
}
/// All registered state names (registration order).
[[nodiscard]] const std::vector<std::string>&
state_names() const noexcept
{
return m_names;
}
// ── persistence ───────────────────────────────────────────────
[[nodiscard]] Json::Value serialize() const
{
@@ -350,17 +416,23 @@ namespace Void::Fsm
protected:
/// Override to snapshot derived FSM data into the "data" object
/// of serialize(), and to restore it.
virtual void on_serialize(Json::Value& /*data*/) const {}
virtual void on_restore(const Json::Value& /*data*/) {}
/// 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 <typename>
template <typename, typename>
friend class Machine; // run_child reaches child internals
// Share a parent's execution context + services (nesting).
void attach(std::shared_ptr<Detail::ExecutionContext> ctx,
Service::ServiceRegistry* services)
{
@@ -372,6 +444,21 @@ namespace Void::Fsm
m_status.store(Status::Running);
}
template <typename... Ss> void register_states(States<Ss...>)
{
(add<Ss>(), ...);
}
template <typename First, typename... Rest>
static const std::type_info* first_type(States<First, Rest...>)
{
return &typeid(First);
}
static const std::type_info* first_type(States<>)
{
return nullptr;
}
template <typename S> [[nodiscard]] std::string state_name()
{
#ifdef VOID_HAS_FSM_REFLECTION
@@ -383,14 +470,22 @@ namespace Void::Fsm
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);
if (m_observer) {
m_observer(
Transition{std::move(from), std::move(to), m_step});
}
}
// The state loop. Builds each state, runs it, follows the
// returned Step. Runs on the execution context's executor.
// The state loop: build each state, run on_enter → run →
// on_exit, follow the returned Step. Runs on the executor.
Coro::Task<Outcome> drive()
{
const std::type_info* cur = m_initial;
@@ -405,7 +500,9 @@ namespace Void::Fsm
}
set_current(cur);
auto state = it->second();
co_await state->on_enter();
Step step = co_await state->run();
co_await state->on_exit();
switch (step.kind()) {
case Step::Kind::Transition:
cur = step.target();
@@ -423,8 +520,6 @@ namespace Void::Fsm
}
}
// Top-level driver: drives to completion, records the outcome,
// and signals the worker to wind down.
Coro::Task<void> driver()
{
Outcome outcome = co_await drive();
@@ -463,6 +558,8 @@ namespace Void::Fsm
std::atomic<int> m_current{-1};
std::atomic<Status> m_status{Status::Idle};
std::optional<Outcome> m_outcome;
std::function<void(const Transition&)> m_observer;
std::uint64_t m_step{0};
};
} // namespace Void::Fsm