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 namespace Void::Fsm::Detail
{ {
/// Type-erased state. Concrete states derive Machine<R>::State, which /// How the engine drives a state.
/// derives this; run() is driven by the engine. 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 class StateBase
{ {
public: public:
virtual ~StateBase() = default; 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 { struct EventEnvelope {
+140 -43
View File
@@ -5,17 +5,20 @@
#include <Void/Data/Json.hpp> #include <Void/Data/Json.hpp>
#include <Void/Fsm/Detail/Engine.hpp> #include <Void/Fsm/Detail/Engine.hpp>
#include <Void/Fsm/Step.hpp> #include <Void/Fsm/Step.hpp>
#include <Void/Log/Log.hpp>
#include <Void/Service/Registry.hpp> #include <Void/Service/Registry.hpp>
#include <any> #include <any>
#include <atomic> #include <atomic>
#include <coroutine> #include <coroutine>
#include <cstdint>
#include <expected> #include <expected>
#include <functional> #include <functional>
#include <memory> #include <memory>
#include <optional> #include <optional>
#include <string> #include <string>
#include <string_view> #include <string_view>
#include <tuple>
#include <type_traits> #include <type_traits>
#include <typeindex> #include <typeindex>
#include <typeinfo> #include <typeinfo>
@@ -30,33 +33,54 @@
namespace Void::Fsm 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 /// Options for a Machine (namespace scope to dodge the GCC
/// nested-default-arg trap). /// nested-default-arg trap).
struct MachineOptions { 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; 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 // Inheritance + coroutine workflow FSM, CRTP for typed access. Derive
// nested structs deriving `State`, implement each state's async run() // it, declare states as nested structs deriving `State`, list them in
// to return next<S>() / succeed(...) / fail(...). States may co_await // `using States = Fsm::States<...>`, and implement each state's async
// external events and nest child machines. // 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: // public:
// struct Idle : State { Coro::Task<Step> run() override { // int attempts = 0;
// auto c = co_await await_event<Creds>(); // struct Check : State {
// co_return next<Check>(); } }; // Coro::Task<Step> run() override {
// struct Check : State { Coro::Task<Step> run() override { // if (++self().attempts > 3) co_return fail("locked");
// co_return service<IAuth>().ok() // co_return self().service<IAuth>().ok() ? succeed(true)
// ? succeed(true) : fail("bad creds"); } }; // : next<Check>();
// Login() { initial<Idle>(); add<Check>(); } // }
// };
// using States = Void::Fsm::States<Check>;
// }; // };
template <typename ResultT = void> class Machine template <typename Derived, typename ResultT = void> class Machine
{ {
public: public:
@@ -69,6 +93,12 @@ namespace Void::Fsm
{ {
public: 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 [[nodiscard]] Machine& machine() const noexcept
{ {
return *m_machine; return *m_machine;
@@ -76,13 +106,27 @@ namespace Void::Fsm
protected: 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 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)); return Step::transition(typeid(S));
} }
/// Finish the machine successfully.
[[nodiscard]] Step succeed() const [[nodiscard]] Step succeed() const
requires std::is_void_v<ResultT> requires std::is_void_v<ResultT>
{ {
@@ -96,25 +140,21 @@ namespace Void::Fsm
std::any{ResultT(std::forward<V>(value))}); std::any{ResultT(std::forward<V>(value))});
} }
/// Finish the machine with a failure.
[[nodiscard]] Step fail(std::string message) const [[nodiscard]] Step fail(std::string message) const
{ {
return Step::failure(FsmError{std::move(message)}); return Step::failure(FsmError{std::move(message)});
} }
/// Resolve a service from the injected registry.
template <typename I> [[nodiscard]] I& service() const template <typename I> [[nodiscard]] I& service() const
{ {
return m_machine->template service<I>(); return m_machine->template service<I>();
} }
/// Suspend until an event of type E is posted.
template <typename E> [[nodiscard]] auto await_event() const template <typename E> [[nodiscard]] auto await_event() const
{ {
return m_machine->template await_event<E>(); return m_machine->template await_event<E>();
} }
/// Run a child machine to completion and get its result.
template <typename Sub, typename... Args> template <typename Sub, typename... Args>
[[nodiscard]] auto run_child(Args&&... args) const [[nodiscard]] auto run_child(Args&&... args) const
{ {
@@ -134,14 +174,24 @@ namespace Void::Fsm
}; };
// ── construction ────────────────────────────────────────────── // ── 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(); } virtual ~Machine() { stop(); }
Machine(const Machine&) = delete; Machine(const Machine&) = delete;
Machine& operator=(const Machine&) = delete; Machine& operator=(const Machine&) = delete;
// ── registration (call from the derived ctor) ───────────────── // ── registration ──────────────────────────────────────────────
template <typename S> void add() template <typename S> void add()
{ {
static_assert(std::is_base_of_v<State, S>, static_assert(std::is_base_of_v<State, S>,
@@ -169,7 +219,6 @@ namespace Void::Fsm
m_initial = &typeid(S); m_initial = &typeid(S);
} }
/// Conditionally register a state (dynamic machines).
template <typename S> void add_if(bool condition) template <typename S> void add_if(bool condition)
{ {
if (condition) { if (condition) {
@@ -193,6 +242,14 @@ namespace Void::Fsm
return m_services->template require<I>(); 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 ───────────────────────────────────────────────── // ── lifecycle ─────────────────────────────────────────────────
void start() 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() Outcome wait()
{ {
if (m_ctx) { if (m_ctx) {
@@ -223,7 +275,7 @@ namespace Void::Fsm
} else { } else {
while (!finished()) { while (!finished()) {
if (m_ctx->pump() == 0 && !finished()) { if (m_ctx->pump() == 0 && !finished()) {
break; // parked on an unposted event break;
} }
} }
} }
@@ -231,15 +283,12 @@ namespace Void::Fsm
return take_outcome(); return take_outcome();
} }
/// start() + wait().
Outcome run_blocking() Outcome run_blocking()
{ {
start(); start();
return wait(); 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; } std::size_t pump() { return m_ctx ? m_ctx->pump() : 0; }
[[nodiscard]] bool finished() const noexcept [[nodiscard]] bool finished() const noexcept
@@ -312,6 +361,23 @@ namespace Void::Fsm
return m_names[static_cast<std::size_t>(idx)]; 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 ─────────────────────────────────────────────── // ── persistence ───────────────────────────────────────────────
[[nodiscard]] Json::Value serialize() const [[nodiscard]] Json::Value serialize() const
{ {
@@ -350,17 +416,23 @@ namespace Void::Fsm
protected: 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_serialize(Json::Value& /*data*/) const {}
virtual void on_restore(const Json::Value& /*data*/) {} 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: private:
template <typename> template <typename, typename>
friend class Machine; // run_child reaches child internals friend class Machine; // run_child reaches child internals
// Share a parent's execution context + services (nesting).
void attach(std::shared_ptr<Detail::ExecutionContext> ctx, void attach(std::shared_ptr<Detail::ExecutionContext> ctx,
Service::ServiceRegistry* services) Service::ServiceRegistry* services)
{ {
@@ -372,6 +444,21 @@ namespace Void::Fsm
m_status.store(Status::Running); 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() template <typename S> [[nodiscard]] std::string state_name()
{ {
#ifdef VOID_HAS_FSM_REFLECTION #ifdef VOID_HAS_FSM_REFLECTION
@@ -383,14 +470,22 @@ namespace Void::Fsm
void set_current(const std::type_info* type) void set_current(const std::type_info* type)
{ {
std::string from = current_state();
if (const auto it = m_index.find(std::type_index{*type}); if (const auto it = m_index.find(std::type_index{*type});
it != m_index.end()) { it != m_index.end()) {
m_current.store(it->second, std::memory_order_release); 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 // The state loop: build each state, run on_enter → run →
// returned Step. Runs on the execution context's executor. // on_exit, follow the returned Step. Runs on the executor.
Coro::Task<Outcome> drive() Coro::Task<Outcome> drive()
{ {
const std::type_info* cur = m_initial; const std::type_info* cur = m_initial;
@@ -405,7 +500,9 @@ namespace Void::Fsm
} }
set_current(cur); set_current(cur);
auto state = it->second(); auto state = it->second();
co_await state->on_enter();
Step step = co_await state->run(); Step step = co_await state->run();
co_await state->on_exit();
switch (step.kind()) { switch (step.kind()) {
case Step::Kind::Transition: case Step::Kind::Transition:
cur = step.target(); 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() Coro::Task<void> driver()
{ {
Outcome outcome = co_await drive(); Outcome outcome = co_await drive();
@@ -463,6 +558,8 @@ namespace Void::Fsm
std::atomic<int> m_current{-1}; std::atomic<int> m_current{-1};
std::atomic<Status> m_status{Status::Idle}; std::atomic<Status> m_status{Status::Idle};
std::optional<Outcome> m_outcome; std::optional<Outcome> m_outcome;
std::function<void(const Transition&)> m_observer;
std::uint64_t m_step{0};
}; };
} // namespace Void::Fsm } // namespace Void::Fsm
+8
View File
@@ -5,6 +5,14 @@
namespace Void::Fsm::Detail namespace Void::Fsm::Detail
{ {
// Default state lifecycle hooks.
Coro::Task<void> StateBase::on_enter() { co_return; }
Coro::Task<void> StateBase::on_exit() { co_return; }
Coro::Task<Step> StateBase::run()
{
co_return Step::failure(FsmError{"state defines no run()"});
}
ExecutionContext::~ExecutionContext() { stop(); } ExecutionContext::~ExecutionContext() { stop(); }
void ExecutionContext::post(EventEnvelope env) void ExecutionContext::post(EventEnvelope env)
+1 -1
View File
@@ -37,7 +37,7 @@ namespace
// An FSM that drives the plugin-provided ICalc service: each Work step // An FSM that drives the plugin-provided ICalc service: each Work step
// accumulates and loops until a target total is reached. It resolves // accumulates and loops until a target total is reached. It resolves
// the service every step, so it picks up a reloaded implementation. // the service every step, so it picks up a reloaded implementation.
class Accumulate : public Void::Fsm::Machine<int> class Accumulate : public Void::Fsm::Machine<Accumulate, int>
{ {
public: public:
+27 -45
View File
@@ -12,7 +12,7 @@ using Void::Fsm::Step;
namespace namespace
{ {
// A linear workflow: Start -> Work (loops 3x) -> success(count). // A linear workflow: Start -> Work (loops 3x) -> success(count).
class Counter : public Void::Fsm::Machine<int> class Counter : public Void::Fsm::Machine<Counter, int>
{ {
public: public:
@@ -22,9 +22,8 @@ namespace
struct Start : State { struct Start : State {
Task<Step> run() override Task<Step> run() override
{ {
auto& m = static_cast<Counter&>(machine()); if (self().log) {
if (m.log) { self().log->push_back("start");
m.log->push_back("start");
} }
co_return next<Work>(); co_return next<Work>();
} }
@@ -33,7 +32,7 @@ namespace
struct Work : State { struct Work : State {
Task<Step> run() override Task<Step> run() override
{ {
auto& m = static_cast<Counter&>(machine()); auto& m = self();
++m.count; ++m.count;
if (m.log) { if (m.log) {
m.log->push_back("work" + std::to_string(m.count)); m.log->push_back("work" + std::to_string(m.count));
@@ -45,16 +44,16 @@ namespace
} }
}; };
using States = Void::Fsm::States<Start, Work>;
Counter() Counter()
: Void::Fsm::Machine<int>(MachineOptions{.own_worker = false}) : Void::Fsm::Machine<Counter, int>(
MachineOptions{.own_worker = false})
{ {
initial<Start>();
add<Work>();
} }
}; };
// A workflow that fails. class Failing : public Void::Fsm::Machine<Failing, int>
class Failing : public Void::Fsm::Machine<int>
{ {
public: public:
@@ -62,10 +61,12 @@ namespace
Task<Step> run() override { co_return fail("kaboom"); } Task<Step> run() override { co_return fail("kaboom"); }
}; };
using States = Void::Fsm::States<Boom>;
Failing() Failing()
: Void::Fsm::Machine<int>(MachineOptions{.own_worker = false}) : Void::Fsm::Machine<Failing, int>(
MachineOptions{.own_worker = false})
{ {
initial<Boom>();
} }
}; };
} // namespace } // namespace
@@ -98,42 +99,23 @@ Void::Testing::Test fsm_pump_drives_to_completion()
{ {
Counter fsm; Counter fsm;
fsm.start(); fsm.start();
Void::Testing::expect(!fsm.finished()); // driver queued, not yet run Void::Testing::expect(!fsm.finished());
fsm.pump(); // Start -> Work* -> success fsm.pump();
Void::Testing::expect(fsm.finished()); Void::Testing::expect(fsm.finished());
Void::Testing::expect_eq(*fsm.wait(), 3); Void::Testing::expect_eq(*fsm.wait(), 3);
} }
Void::Testing::Test fsm_transition_to_unregistered_fails()
{
struct Lonely : Void::Fsm::Machine<void> {
struct Other : State {
Task<Step> run() override { co_return succeed(); }
};
struct Start : State {
Task<Step> run() override { co_return next<Other>(); }
};
Lonely()
: Void::Fsm::Machine<void>(MachineOptions{.own_worker = false})
{
initial<Start>(); // Other intentionally not registered
}
} fsm;
const auto outcome = fsm.run_blocking();
Void::Testing::expect(!outcome.has_value());
}
Void::Testing::Test fsm_void_result_succeeds() Void::Testing::Test fsm_void_result_succeeds()
{ {
struct Trivial : Void::Fsm::Machine<void> { struct Trivial : Void::Fsm::Machine<Trivial, void> {
struct Done : State { struct Done : State {
Task<Step> run() override { co_return succeed(); } Task<Step> run() override { co_return succeed(); }
}; };
using States = Void::Fsm::States<Done>;
Trivial() Trivial()
: Void::Fsm::Machine<void>(MachineOptions{.own_worker = false}) : Void::Fsm::Machine<Trivial, void>(
MachineOptions{.own_worker = false})
{ {
initial<Done>();
} }
} fsm; } fsm;
@@ -143,9 +125,9 @@ Void::Testing::Test fsm_void_result_succeeds()
Void::Testing::Test fsm_dynamic_state_registration() Void::Testing::Test fsm_dynamic_state_registration()
{ {
// Two configurations of the same machine type: with and without the // Dynamic machine: states registered conditionally, addressed with
// optional Express state. // next_dynamic<S>() (skips the compile-time States<> check).
struct Flow : Void::Fsm::Machine<int> { struct Flow : Void::Fsm::Machine<Flow, int> {
bool express; bool express;
struct Express : State { struct Express : State {
Task<Step> run() override { co_return succeed(99); } Task<Step> run() override { co_return succeed(99); }
@@ -156,15 +138,15 @@ Void::Testing::Test fsm_dynamic_state_registration()
struct Start : State { struct Start : State {
Task<Step> run() override Task<Step> run() override
{ {
auto& m = static_cast<Flow&>(machine()); if (self().has_state<Express>()) {
if (m.has_state<Express>()) { co_return next_dynamic<Express>();
co_return next<Express>();
} }
co_return next<Normal>(); co_return next_dynamic<Normal>();
} }
}; };
explicit Flow(bool e) explicit Flow(bool e)
: Void::Fsm::Machine<int>(MachineOptions{.own_worker = false}), : Void::Fsm::Machine<Flow, int>(
MachineOptions{.own_worker = false}),
express(e) express(e)
{ {
initial<Start>(); initial<Start>();
+6 -5
View File
@@ -22,7 +22,7 @@ namespace
// Sums many Tick events delivered from several threads, finishing when // Sums many Tick events delivered from several threads, finishing when
// the running total reaches a target. Single consumer (the worker) so // the running total reaches a target. Single consumer (the worker) so
// the total is race-free without the FSM holding any lock. // the total is race-free without the FSM holding any lock.
class Summer : public Void::Fsm::Machine<long long> class Summer : public Void::Fsm::Machine<Summer, long long>
{ {
public: public:
@@ -32,7 +32,7 @@ namespace
struct Run : State { struct Run : State {
Task<Step> run() override Task<Step> run() override
{ {
auto& m = static_cast<Summer&>(machine()); auto& m = self();
while (m.total < m.target) { while (m.total < m.target) {
auto t = co_await await_event<Tick>(); auto t = co_await await_event<Tick>();
m.total += t.n; m.total += t.n;
@@ -42,7 +42,7 @@ namespace
}; };
explicit Summer(long long tgt) explicit Summer(long long tgt)
: Void::Fsm::Machine<long long>(), target(tgt) : Void::Fsm::Machine<Summer, long long>(), target(tgt)
{ {
initial<Run>(); initial<Run>();
} }
@@ -132,7 +132,7 @@ Void::Testing::Test fsm_current_state_reads_never_tear_under_load()
Void::Testing::Test fsm_resolves_service_through_context() Void::Testing::Test fsm_resolves_service_through_context()
{ {
struct Calc : Void::Fsm::Machine<int> { struct Calc : Void::Fsm::Machine<Calc, int> {
struct Go : State { struct Go : State {
Task<Step> run() override Task<Step> run() override
{ {
@@ -140,7 +140,8 @@ Void::Testing::Test fsm_resolves_service_through_context()
} }
}; };
Calc() Calc()
: Void::Fsm::Machine<int>(MachineOptions{.own_worker = false}) : Void::Fsm::Machine<Calc, int>(
MachineOptions{.own_worker = false})
{ {
initial<Go>(); initial<Go>();
} }
+3 -3
View File
@@ -20,7 +20,7 @@ namespace
}; };
// Waits for Input events, accumulating until a Stop event arrives. // Waits for Input events, accumulating until a Stop event arrives.
class Accumulator : public Void::Fsm::Machine<int> class Accumulator : public Void::Fsm::Machine<Accumulator, int>
{ {
public: public:
@@ -30,7 +30,7 @@ namespace
struct Waiting : State { struct Waiting : State {
Task<Step> run() override Task<Step> run() override
{ {
auto& m = static_cast<Accumulator&>(machine()); auto& m = self();
// Two typed mailboxes: pull whichever arrives. // Two typed mailboxes: pull whichever arrives.
auto in = co_await await_event<Input>(); auto in = co_await await_event<Input>();
m.total += in.value; m.total += in.value;
@@ -45,7 +45,7 @@ namespace
}; };
explicit Accumulator(bool own_worker) explicit Accumulator(bool own_worker)
: Void::Fsm::Machine<int>( : Void::Fsm::Machine<Accumulator, int>(
MachineOptions{.own_worker = own_worker}) MachineOptions{.own_worker = own_worker})
{ {
initial<Waiting>(); initial<Waiting>();
+124
View File
@@ -0,0 +1,124 @@
#include <Void/Fsm/Fsm.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <string>
#include <vector>
using Void::Coro::Task;
using Void::Fsm::MachineOptions;
using Void::Fsm::Step;
using Void::Fsm::Transition;
namespace
{
// Records enter/run/exit for each state into a shared log.
class Lifecycle : public Void::Fsm::Machine<Lifecycle, int>
{
public:
std::vector<std::string> log;
struct A : State {
Task<void> on_enter() override
{
self().log.push_back("enter A");
co_return;
}
Task<Step> run() override
{
self().log.push_back("run A");
co_return next<B>();
}
Task<void> on_exit() override
{
self().log.push_back("exit A");
co_return;
}
};
struct B : State {
Task<void> on_enter() override
{
self().log.push_back("enter B");
co_return;
}
Task<Step> run() override
{
self().log.push_back("run B");
co_return succeed(1);
}
Task<void> on_exit() override
{
self().log.push_back("exit B");
co_return;
}
};
using States = Void::Fsm::States<A, B>;
Lifecycle()
: Void::Fsm::Machine<Lifecycle, int>(
MachineOptions{.own_worker = false})
{
}
};
} // namespace
Void::Testing::Test fsm_lifecycle_enter_run_exit_order()
{
Lifecycle fsm;
(void)fsm.run_blocking();
const std::vector<std::string> expected{"enter A", "run A", "exit A",
"enter B", "run B", "exit B"};
Void::Testing::expect(fsm.log == expected);
}
Void::Testing::Test fsm_observer_sees_every_transition()
{
Lifecycle fsm;
std::vector<std::string> edges;
fsm.observe([&](const Transition& t) {
edges.push_back((t.from.empty() ? "*" : t.from) + "->" + t.to);
});
(void)fsm.run_blocking();
// Initial entry (*->A), then A->B.
const std::vector<std::string> expected{"*->A", "A->B"};
Void::Testing::expect(edges == expected);
}
Void::Testing::Test fsm_state_names_and_path()
{
Lifecycle fsm;
const auto& names = fsm.state_names();
Void::Testing::expect_eq(names.size(), std::size_t{2});
Void::Testing::expect_eq(names[0], std::string{"A"});
Void::Testing::expect_eq(names[1], std::string{"B"});
fsm.start();
fsm.pump();
Void::Testing::expect(fsm.finished());
}
// A state defining only on_enter (no run) falls through to the default
// run() which fails — confirms the default body exists.
Void::Testing::Test fsm_state_without_run_fails()
{
struct NoRun : Void::Fsm::Machine<NoRun, void> {
struct Stuck : State {
Task<void> on_enter() override { co_return; }
// no run() override
};
using States = Void::Fsm::States<Stuck>;
NoRun()
: Void::Fsm::Machine<NoRun, void>(
MachineOptions{.own_worker = false})
{
}
} fsm;
const auto outcome = fsm.run_blocking();
Void::Testing::expect(!outcome.has_value());
}
+14 -10
View File
@@ -11,7 +11,7 @@ using Void::Fsm::Step;
namespace namespace
{ {
// Child machine: computes a value and succeeds. // Child machine: computes a value and succeeds.
class Subtotal : public Void::Fsm::Machine<int> class Subtotal : public Void::Fsm::Machine<Subtotal, int>
{ {
public: public:
@@ -20,13 +20,14 @@ namespace
struct Compute : State { struct Compute : State {
Task<Step> run() override Task<Step> run() override
{ {
auto& m = static_cast<Subtotal&>(machine()); auto& m = self();
co_return succeed(m.seed * 10); co_return succeed(m.seed * 10);
} }
}; };
explicit Subtotal(int s) explicit Subtotal(int s)
: Void::Fsm::Machine<int>(MachineOptions{.own_worker = false}), : Void::Fsm::Machine<Subtotal, int>(
MachineOptions{.own_worker = false}),
seed(s) seed(s)
{ {
initial<Compute>(); initial<Compute>();
@@ -34,7 +35,7 @@ namespace
}; };
// Child machine that fails. // Child machine that fails.
class FailingChild : public Void::Fsm::Machine<int> class FailingChild : public Void::Fsm::Machine<FailingChild, int>
{ {
public: public:
@@ -42,14 +43,15 @@ namespace
Task<Step> run() override { co_return fail("child boom"); } Task<Step> run() override { co_return fail("child boom"); }
}; };
FailingChild() FailingChild()
: Void::Fsm::Machine<int>(MachineOptions{.own_worker = false}) : Void::Fsm::Machine<FailingChild, int>(
MachineOptions{.own_worker = false})
{ {
initial<Boom>(); initial<Boom>();
} }
}; };
// Parent: enters a child, uses its result to decide the outcome. // Parent: enters a child, uses its result to decide the outcome.
class Parent : public Void::Fsm::Machine<int> class Parent : public Void::Fsm::Machine<Parent, int>
{ {
public: public:
@@ -66,13 +68,14 @@ namespace
}; };
Parent() Parent()
: Void::Fsm::Machine<int>(MachineOptions{.own_worker = false}) : Void::Fsm::Machine<Parent, int>(
MachineOptions{.own_worker = false})
{ {
initial<Start>(); initial<Start>();
} }
}; };
class ParentOfFailure : public Void::Fsm::Machine<int> class ParentOfFailure : public Void::Fsm::Machine<ParentOfFailure, int>
{ {
public: public:
@@ -88,7 +91,8 @@ namespace
}; };
ParentOfFailure() ParentOfFailure()
: Void::Fsm::Machine<int>(MachineOptions{.own_worker = false}) : Void::Fsm::Machine<ParentOfFailure, int>(
MachineOptions{.own_worker = false})
{ {
initial<Start>(); initial<Start>();
} }
@@ -117,7 +121,7 @@ Void::Testing::Test fsm_nesting_with_worker_thread()
{ {
Parent fsm{}; // embedder by default here Parent fsm{}; // embedder by default here
// Re-run as worker-driven to exercise the shared executor + worker. // Re-run as worker-driven to exercise the shared executor + worker.
struct WorkerParent : Void::Fsm::Machine<int> { struct WorkerParent : Void::Fsm::Machine<WorkerParent, int> {
struct Start : State { struct Start : State {
Task<Step> run() override Task<Step> run() override
{ {
+4 -3
View File
@@ -13,7 +13,7 @@ namespace
{ {
// A machine that parks at a named state and exposes its data for // A machine that parks at a named state and exposes its data for
// serialize/restore. // serialize/restore.
class Pipeline : public Void::Fsm::Machine<int> class Pipeline : public Void::Fsm::Machine<Pipeline, int>
{ {
public: public:
@@ -33,14 +33,15 @@ namespace
struct Process : State { struct Process : State {
Task<Step> run() override Task<Step> run() override
{ {
auto& m = static_cast<Pipeline&>(machine()); auto& m = self();
m.data.processed += 1; m.data.processed += 1;
co_return succeed(m.data.processed); co_return succeed(m.data.processed);
} }
}; };
Pipeline() Pipeline()
: Void::Fsm::Machine<int>(MachineOptions{.own_worker = false}) : Void::Fsm::Machine<Pipeline, int>(
MachineOptions{.own_worker = false})
{ {
initial<Ingest>(); initial<Ingest>();
add<Process>(); add<Process>();
+5 -4
View File
@@ -66,7 +66,7 @@ namespace
}; };
// An FSM that bumps the counter service N times then succeeds. // An FSM that bumps the counter service N times then succeeds.
class Worker : public Void::Fsm::Machine<int> class Worker : public Void::Fsm::Machine<Worker, int>
{ {
public: public:
@@ -75,7 +75,7 @@ namespace
struct Run : State { struct Run : State {
Task<Step> run() override Task<Step> run() override
{ {
auto& m = static_cast<Worker&>(machine()); auto& m = self();
int last = 0; int last = 0;
for (int i = 0; i < m.times; ++i) { for (int i = 0; i < m.times; ++i) {
last = service<ICounter>().inc(); last = service<ICounter>().inc();
@@ -85,7 +85,8 @@ namespace
}; };
explicit Worker(int t) explicit Worker(int t)
: Void::Fsm::Machine<int>(MachineOptions{.own_worker = false}), : Void::Fsm::Machine<Worker, int>(
MachineOptions{.own_worker = false}),
times(t) times(t)
{ {
initial<Run>(); initial<Run>();
@@ -109,7 +110,7 @@ Void::Testing::Test orchestrator_launches_and_supervises()
{ {
// Worker-backed FSM so the orchestrator's start() spins a worker and // Worker-backed FSM so the orchestrator's start() spins a worker and
// the FSM runs to completion on its own. // the FSM runs to completion on its own.
struct AsyncWorker : Void::Fsm::Machine<int> { struct AsyncWorker : Void::Fsm::Machine<AsyncWorker, int> {
struct Run : State { struct Run : State {
Task<Step> run() override Task<Step> run() override
{ {