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:
1 parent
7b6cd7341a
commit
e941a48007
11 files changed
+355
-117
No files matched your search
@@ -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
@@ -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
|
||||
@@ -5,6 +5,14 @@
|
||||
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(); }
|
||||
|
||||
void ExecutionContext::post(EventEnvelope env)
|
||||
|
||||
@@ -37,7 +37,7 @@ 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<int>
|
||||
class Accumulate : public Void::Fsm::Machine<Accumulate, int>
|
||||
{
|
||||
public:
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ using Void::Fsm::Step;
|
||||
namespace
|
||||
{
|
||||
// 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:
|
||||
|
||||
@@ -22,9 +22,8 @@ namespace
|
||||
struct Start : State {
|
||||
Task<Step> run() override
|
||||
{
|
||||
auto& m = static_cast<Counter&>(machine());
|
||||
if (m.log) {
|
||||
m.log->push_back("start");
|
||||
if (self().log) {
|
||||
self().log->push_back("start");
|
||||
}
|
||||
co_return next<Work>();
|
||||
}
|
||||
@@ -33,7 +32,7 @@ namespace
|
||||
struct Work : State {
|
||||
Task<Step> run() override
|
||||
{
|
||||
auto& m = static_cast<Counter&>(machine());
|
||||
auto& m = self();
|
||||
++m.count;
|
||||
if (m.log) {
|
||||
m.log->push_back("work" + std::to_string(m.count));
|
||||
@@ -45,16 +44,16 @@ namespace
|
||||
}
|
||||
};
|
||||
|
||||
using States = Void::Fsm::States<Start, Work>;
|
||||
|
||||
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<int>
|
||||
class Failing : public Void::Fsm::Machine<Failing, int>
|
||||
{
|
||||
public:
|
||||
|
||||
@@ -62,10 +61,12 @@ namespace
|
||||
Task<Step> run() override { co_return fail("kaboom"); }
|
||||
};
|
||||
|
||||
using States = Void::Fsm::States<Boom>;
|
||||
|
||||
Failing()
|
||||
: Void::Fsm::Machine<int>(MachineOptions{.own_worker = false})
|
||||
: Void::Fsm::Machine<Failing, int>(
|
||||
MachineOptions{.own_worker = false})
|
||||
{
|
||||
initial<Boom>();
|
||||
}
|
||||
};
|
||||
} // namespace
|
||||
@@ -98,42 +99,23 @@ Void::Testing::Test fsm_pump_drives_to_completion()
|
||||
{
|
||||
Counter fsm;
|
||||
fsm.start();
|
||||
Void::Testing::expect(!fsm.finished()); // driver queued, not yet run
|
||||
fsm.pump(); // Start -> Work* -> success
|
||||
Void::Testing::expect(!fsm.finished());
|
||||
fsm.pump();
|
||||
Void::Testing::expect(fsm.finished());
|
||||
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()
|
||||
{
|
||||
struct Trivial : Void::Fsm::Machine<void> {
|
||||
struct Trivial : Void::Fsm::Machine<Trivial, void> {
|
||||
struct Done : State {
|
||||
Task<Step> run() override { co_return succeed(); }
|
||||
};
|
||||
using States = Void::Fsm::States<Done>;
|
||||
Trivial()
|
||||
: Void::Fsm::Machine<void>(MachineOptions{.own_worker = false})
|
||||
: Void::Fsm::Machine<Trivial, void>(
|
||||
MachineOptions{.own_worker = false})
|
||||
{
|
||||
initial<Done>();
|
||||
}
|
||||
} fsm;
|
||||
|
||||
@@ -143,9 +125,9 @@ Void::Testing::Test fsm_void_result_succeeds()
|
||||
|
||||
Void::Testing::Test fsm_dynamic_state_registration()
|
||||
{
|
||||
// Two configurations of the same machine type: with and without the
|
||||
// optional Express state.
|
||||
struct Flow : Void::Fsm::Machine<int> {
|
||||
// Dynamic machine: states registered conditionally, addressed with
|
||||
// next_dynamic<S>() (skips the compile-time States<> check).
|
||||
struct Flow : Void::Fsm::Machine<Flow, int> {
|
||||
bool express;
|
||||
struct Express : State {
|
||||
Task<Step> run() override { co_return succeed(99); }
|
||||
@@ -156,15 +138,15 @@ Void::Testing::Test fsm_dynamic_state_registration()
|
||||
struct Start : State {
|
||||
Task<Step> run() override
|
||||
{
|
||||
auto& m = static_cast<Flow&>(machine());
|
||||
if (m.has_state<Express>()) {
|
||||
co_return next<Express>();
|
||||
if (self().has_state<Express>()) {
|
||||
co_return next_dynamic<Express>();
|
||||
}
|
||||
co_return next<Normal>();
|
||||
co_return next_dynamic<Normal>();
|
||||
}
|
||||
};
|
||||
explicit Flow(bool e)
|
||||
: Void::Fsm::Machine<int>(MachineOptions{.own_worker = false}),
|
||||
: Void::Fsm::Machine<Flow, int>(
|
||||
MachineOptions{.own_worker = false}),
|
||||
express(e)
|
||||
{
|
||||
initial<Start>();
|
||||
|
||||
@@ -22,7 +22,7 @@ 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<long long>
|
||||
class Summer : public Void::Fsm::Machine<Summer, long long>
|
||||
{
|
||||
public:
|
||||
|
||||
@@ -32,7 +32,7 @@ namespace
|
||||
struct Run : State {
|
||||
Task<Step> run() override
|
||||
{
|
||||
auto& m = static_cast<Summer&>(machine());
|
||||
auto& m = self();
|
||||
while (m.total < m.target) {
|
||||
auto t = co_await await_event<Tick>();
|
||||
m.total += t.n;
|
||||
@@ -42,7 +42,7 @@ namespace
|
||||
};
|
||||
|
||||
explicit Summer(long long tgt)
|
||||
: Void::Fsm::Machine<long long>(), target(tgt)
|
||||
: Void::Fsm::Machine<Summer, long long>(), target(tgt)
|
||||
{
|
||||
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()
|
||||
{
|
||||
struct Calc : Void::Fsm::Machine<int> {
|
||||
struct Calc : Void::Fsm::Machine<Calc, int> {
|
||||
struct Go : State {
|
||||
Task<Step> run() override
|
||||
{
|
||||
@@ -140,7 +140,8 @@ Void::Testing::Test fsm_resolves_service_through_context()
|
||||
}
|
||||
};
|
||||
Calc()
|
||||
: Void::Fsm::Machine<int>(MachineOptions{.own_worker = false})
|
||||
: Void::Fsm::Machine<Calc, int>(
|
||||
MachineOptions{.own_worker = false})
|
||||
{
|
||||
initial<Go>();
|
||||
}
|
||||
|
||||
@@ -20,7 +20,7 @@ namespace
|
||||
};
|
||||
|
||||
// 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:
|
||||
|
||||
@@ -30,7 +30,7 @@ namespace
|
||||
struct Waiting : State {
|
||||
Task<Step> run() override
|
||||
{
|
||||
auto& m = static_cast<Accumulator&>(machine());
|
||||
auto& m = self();
|
||||
// Two typed mailboxes: pull whichever arrives.
|
||||
auto in = co_await await_event<Input>();
|
||||
m.total += in.value;
|
||||
@@ -45,7 +45,7 @@ namespace
|
||||
};
|
||||
|
||||
explicit Accumulator(bool own_worker)
|
||||
: Void::Fsm::Machine<int>(
|
||||
: Void::Fsm::Machine<Accumulator, int>(
|
||||
MachineOptions{.own_worker = own_worker})
|
||||
{
|
||||
initial<Waiting>();
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
@@ -11,7 +11,7 @@ using Void::Fsm::Step;
|
||||
namespace
|
||||
{
|
||||
// Child machine: computes a value and succeeds.
|
||||
class Subtotal : public Void::Fsm::Machine<int>
|
||||
class Subtotal : public Void::Fsm::Machine<Subtotal, int>
|
||||
{
|
||||
public:
|
||||
|
||||
@@ -20,13 +20,14 @@ namespace
|
||||
struct Compute : State {
|
||||
Task<Step> run() override
|
||||
{
|
||||
auto& m = static_cast<Subtotal&>(machine());
|
||||
auto& m = self();
|
||||
co_return succeed(m.seed * 10);
|
||||
}
|
||||
};
|
||||
|
||||
explicit Subtotal(int s)
|
||||
: Void::Fsm::Machine<int>(MachineOptions{.own_worker = false}),
|
||||
: Void::Fsm::Machine<Subtotal, int>(
|
||||
MachineOptions{.own_worker = false}),
|
||||
seed(s)
|
||||
{
|
||||
initial<Compute>();
|
||||
@@ -34,7 +35,7 @@ namespace
|
||||
};
|
||||
|
||||
// Child machine that fails.
|
||||
class FailingChild : public Void::Fsm::Machine<int>
|
||||
class FailingChild : public Void::Fsm::Machine<FailingChild, int>
|
||||
{
|
||||
public:
|
||||
|
||||
@@ -42,14 +43,15 @@ namespace
|
||||
Task<Step> run() override { co_return fail("child boom"); }
|
||||
};
|
||||
FailingChild()
|
||||
: Void::Fsm::Machine<int>(MachineOptions{.own_worker = false})
|
||||
: Void::Fsm::Machine<FailingChild, int>(
|
||||
MachineOptions{.own_worker = false})
|
||||
{
|
||||
initial<Boom>();
|
||||
}
|
||||
};
|
||||
|
||||
// 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:
|
||||
|
||||
@@ -66,13 +68,14 @@ namespace
|
||||
};
|
||||
|
||||
Parent()
|
||||
: Void::Fsm::Machine<int>(MachineOptions{.own_worker = false})
|
||||
: Void::Fsm::Machine<Parent, int>(
|
||||
MachineOptions{.own_worker = false})
|
||||
{
|
||||
initial<Start>();
|
||||
}
|
||||
};
|
||||
|
||||
class ParentOfFailure : public Void::Fsm::Machine<int>
|
||||
class ParentOfFailure : public Void::Fsm::Machine<ParentOfFailure, int>
|
||||
{
|
||||
public:
|
||||
|
||||
@@ -88,7 +91,8 @@ namespace
|
||||
};
|
||||
|
||||
ParentOfFailure()
|
||||
: Void::Fsm::Machine<int>(MachineOptions{.own_worker = false})
|
||||
: Void::Fsm::Machine<ParentOfFailure, int>(
|
||||
MachineOptions{.own_worker = false})
|
||||
{
|
||||
initial<Start>();
|
||||
}
|
||||
@@ -117,7 +121,7 @@ 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<int> {
|
||||
struct WorkerParent : Void::Fsm::Machine<WorkerParent, int> {
|
||||
struct Start : State {
|
||||
Task<Step> run() override
|
||||
{
|
||||
|
||||
@@ -13,7 +13,7 @@ namespace
|
||||
{
|
||||
// A machine that parks at a named state and exposes its data for
|
||||
// serialize/restore.
|
||||
class Pipeline : public Void::Fsm::Machine<int>
|
||||
class Pipeline : public Void::Fsm::Machine<Pipeline, int>
|
||||
{
|
||||
public:
|
||||
|
||||
@@ -33,14 +33,15 @@ namespace
|
||||
struct Process : State {
|
||||
Task<Step> run() override
|
||||
{
|
||||
auto& m = static_cast<Pipeline&>(machine());
|
||||
auto& m = self();
|
||||
m.data.processed += 1;
|
||||
co_return succeed(m.data.processed);
|
||||
}
|
||||
};
|
||||
|
||||
Pipeline()
|
||||
: Void::Fsm::Machine<int>(MachineOptions{.own_worker = false})
|
||||
: Void::Fsm::Machine<Pipeline, int>(
|
||||
MachineOptions{.own_worker = false})
|
||||
{
|
||||
initial<Ingest>();
|
||||
add<Process>();
|
||||
|
||||
@@ -66,7 +66,7 @@ namespace
|
||||
};
|
||||
|
||||
// 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:
|
||||
|
||||
@@ -75,7 +75,7 @@ namespace
|
||||
struct Run : State {
|
||||
Task<Step> run() override
|
||||
{
|
||||
auto& m = static_cast<Worker&>(machine());
|
||||
auto& m = self();
|
||||
int last = 0;
|
||||
for (int i = 0; i < m.times; ++i) {
|
||||
last = service<ICounter>().inc();
|
||||
@@ -85,7 +85,8 @@ namespace
|
||||
};
|
||||
|
||||
explicit Worker(int t)
|
||||
: Void::Fsm::Machine<int>(MachineOptions{.own_worker = false}),
|
||||
: Void::Fsm::Machine<Worker, int>(
|
||||
MachineOptions{.own_worker = false}),
|
||||
times(t)
|
||||
{
|
||||
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
|
||||
// the FSM runs to completion on its own.
|
||||
struct AsyncWorker : Void::Fsm::Machine<int> {
|
||||
struct AsyncWorker : Void::Fsm::Machine<AsyncWorker, int> {
|
||||
struct Run : State {
|
||||
Task<Step> run() override
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user