FSM (4): one signature-inferred State (drops Reactive/Continue bases)
There is now a single state base, `State`. The engine infers each state's
role purely from member signatures via P2996 — no `override`, no
framework-mandated names:
struct Work : State { // entry
Coro::Task<Step> run() { ... }
Coro::Task<Step> run(Cfg c) { ... } // startup-entry (launch data)
};
struct Idle : State { // reactive
void transitions(TransitionBuilder& on) { on.event<Go>().to<Run>(); }
};
struct After : State { // continuation
Coro::Task<Step> ok(ChildSuccess auto s) { use s.value; }
Coro::Task<Step> no(ChildFailure auto f) { use f.value; }
};
- Detail/Roles.hpp: ChildSuccess/ChildFailure concepts over boxes, plus the
reflection selectors (invoke_entry / invoke_startup / invoke_handler /
dispatch_result / has_transitions / make_driver). At add<S>() a per-state
driver thunk is stored (reactive table vs entry, by whether S has a
TransitionBuilder& member); drive() calls it. startMachine<Sub, Next>(data)
builds a Launch step carrying a launcher (injects data into Sub's initial
startup-entry) + a dispatcher (dispatch_result<Next, Sub>) that builds the
ChildSuccess/Failure box and calls Next's matching handler.
- Removed Reactive/Continue<R> bases, StateKind/kind(), StateBase::run/resume
(only on_enter/on_exit remain virtual). Reactive states keep the same DSL.
- Toolchain note: template-for + member splicing fails inside a coroutine
body in this GCC build, so the selectors are non-coroutines returning a
Task<Step> (plain Step wrapped via ready_task). Discovery is
invocability-based — no parameter-type reflection (P3096). Probe-verified.
All FSM tests migrated to the nameless style (SubMachine: Continue ->
ChildSuccess/Failure handlers + startup-entry seeding; reactive states drop
the Reactive base/override). 995 tests (992 green, 3 skipped), ASan clean,
-Werror clean; lone intermittent failure remains the pre-existing racy
plugin hot-reload-under-load test.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
9e9eb838ea
commit
ec9e466d7a
20 files changed
+536
-358
No files matched your search
@@ -147,11 +147,18 @@ Other key points:
|
||||
|
||||
### Fsm module (inheritance + coroutine workflow)
|
||||
|
||||
`Void::Fsm::Machine<Derived>` (CRTP) — derive it; declare states as nested structs deriving `State`; each implements `Coro::Task<Step> run()` returning `next<S>()` / `succeed(...)` / `fail(...)`. There is no statechart/event-graph; states drive themselves.
|
||||
`Void::Fsm::Machine<Derived>` (CRTP) — derive it; declare states as nested structs deriving the **single** base `State`. There is no statechart/event-graph; states drive themselves.
|
||||
|
||||
**One `State`, signature-inferred roles.** There is one base class; the engine infers what each state does **purely from member signatures** via P2996 (`Detail/Roles.hpp`) — no `override`, no framework-mandated names:
|
||||
- **entry** — a member returning `Step`/`Coro::Task<Step>` with no params (`Task<Step> run()`); a **startup-entry** overload takes the launch data (`Task<Step> run(Cfg)`), used when reached via `startMachine` (data routed there, not the constructor).
|
||||
- **reactive** — a member taking `TransitionBuilder&` (`void transitions(TransitionBuilder& on)`); the engine runs its declared table.
|
||||
- **continuation handlers** — two members distinguished by parameter type, `ok(ChildSuccess auto s)` / `no(ChildFailure auto f)` (`s.value`/`f.value` are the sub's typed Success/Failure); the engine picks by the launched sub's outcome.
|
||||
|
||||
Mechanics: at `add<S>()` a `Detail::make_driver<S>()` reflection thunk is stored (reactive table vs entry, chosen by whether `S` has a `TransitionBuilder&` member); `drive()` calls the thunk. `startMachine<Sub, Next>(data…)` (knows `Sub`, `Next`, and the data types) builds a `Launch` step carrying a launcher (runs `Sub`, injecting `data` into its initial state's startup-entry) and a dispatcher (`Detail::dispatch_result<Next, Sub>`) that builds `ChildSuccessBox<…>`/`ChildFailureBox<…>` and calls `Next`'s matching handler. The reflection selectors must **not** be coroutines (`template for` + member splicing fails inside a coroutine body in this GCC build), so they `return` a `Task<Step>` (wrapping plain `Step` via `ready_task`). The discovery is invocability-based — **no parameter-type reflection (P3096)**.
|
||||
|
||||
**Typed results.** A machine declares its result types as nested types *reflected by name* — `struct Success {…}` (or `using Success = int;`) and `struct Failure {…}`, each defaulting to `void`. `Outcome = std::expected<Success, Failure>` (a void failure becomes `std::monostate`); `succeed(Success{…})` / `fail(Failure{…})` carry them (nullary when void). Engine/system faults (no initial state, jump to an unregistered state, a state with no entry) are a **separate `FsmError` channel** — `status()==Faulted`, `system_error()` returns the `FsmError`, never the typed `Failure`. Because `Derived` is incomplete at CRTP base instantiation, the engine stores outcomes type-erased and rebuilds the typed `Outcome` in `wait()`/`run_blocking()` (function templates defaulted on `Derived`); `Detail::SuccessOf`/`FailureOf<Derived>` resolve the nested types by plain name lookup (`Detail/Result.hpp`).
|
||||
|
||||
Header layout (include `<Void/Fsm/Fsm.hpp>` — a thin umbrella): `Machine.hpp` (the `Machine<Derived, ResultT>` template + `States<>`, nested `State`/`Reactive`/`Continue` bases, lifecycle, events, nesting, persistence); `Detail/Reactive.hpp` (the declarative transition DSL as standalone `Detail::TransitionBuilder`/`EventClause`/`AfterClause`/`TransitionTable<Derived,…>` templates, aliased by `Machine::Reactive`); `Detail/Awaiter.hpp` (one `Detail::EventAwaiter` behind `make_event_awaiter`, used by all `await_*`); `Detail/Continuation.hpp` (`Detail::Continuation<State,R>` = `Continue<R>`, with a `void` specialization); `Detail/Introspect.hpp` (`StateInfo`/`EdgeInfo` + `to_mermaid`); `Detail/Engine.{hpp,cpp}` (the non-template `ExecutionContext` + `StateBase`); `Detail/TypeName.hpp` (`type_name<T>()`).
|
||||
Header layout (include `<Void/Fsm/Fsm.hpp>` — a thin umbrella): `Machine.hpp` (the `Machine<Derived>` template + `States<>`, the single nested `State` base, lifecycle, events, nesting, persistence); `Detail/Roles.hpp` (the signature-inference: `ChildSuccess`/`ChildFailure` concepts + boxes, `invoke_entry`/`invoke_startup`/`invoke_handler`/`dispatch_result`/`make_driver`/`has_transitions`); `Detail/Result.hpp` (`SuccessOf`/`FailureOf`/`OutcomeOf<Derived>`); `Detail/Reactive.hpp` (the declarative transition DSL as standalone `Detail::TransitionBuilder`/`EventClause`/`AfterClause`/`TransitionTable<Derived>` templates); `Detail/Awaiter.hpp` (one `Detail::EventAwaiter` behind `make_event_awaiter`, used by all `await_*`); `Detail/Introspect.hpp` (`StateInfo`/`EdgeInfo` + `to_mermaid`); `Detail/Engine.{hpp,cpp}` (the non-template `ExecutionContext` + `StateBase` — only `on_enter`/`on_exit` remain virtual); `Detail/TypeName.hpp` (`type_name<T>()`).
|
||||
|
||||
- **Async by default**: a non-template `Detail::ExecutionContext` (`src/Fsm/Engine.cpp`) owns one `Async::ManualExecutor` + worker thread + a lock-free MPSC event queue + a typed event mailbox. A single consumer (worker, or the embedder via `pump()` when `MachineOptions{.own_worker=false}`) touches all mutable state, so state code is lock-free/single-threaded. `start()`/`run_blocking()`/`wait()` for worker mode; `pump()` for embedder mode (deterministic tests).
|
||||
- **Events**: `co_await await_event<E>()` consumes the oldest queued `E` (typed mailbox), suspending until one arrives; `post<E>(e)` is lock-free from any thread.
|
||||
|
||||
@@ -1,76 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#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;
|
||||
// `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 by the outcome. Machine exposes it as `Continue<Sub>`.
|
||||
//
|
||||
// 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.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<Succ>(std::move(lr.value)));
|
||||
}
|
||||
}
|
||||
|
||||
Coro::Task<Step> run() override
|
||||
{
|
||||
co_return Step::fault(FsmError{
|
||||
"continuation state entered without a sub-machine result "
|
||||
"(reach it via startMachine<Sub, This>())"});
|
||||
}
|
||||
|
||||
protected:
|
||||
|
||||
virtual Coro::Task<Step> on_success(SuccArg result) = 0;
|
||||
|
||||
/// 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 Step::fault(
|
||||
FsmError{"unhandled sub-machine failure"});
|
||||
}
|
||||
};
|
||||
} // namespace Void::Fsm::Detail
|
||||
@@ -26,39 +26,21 @@
|
||||
|
||||
namespace Void::Fsm::Detail
|
||||
{
|
||||
/// 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.
|
||||
/// Type-erased state. Concrete states derive the single Machine<Derived>::
|
||||
/// State base; the engine drives each via a signature-inferred per-state
|
||||
/// thunk (entry / reactive table / continuation handlers).
|
||||
class StateBase
|
||||
{
|
||||
public:
|
||||
|
||||
virtual ~StateBase() = default;
|
||||
|
||||
[[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().
|
||||
/// Optional entry/exit lifecycle hooks (default no-ops). The
|
||||
/// state's behaviour (entry / reactive table / continuation
|
||||
/// handlers) is discovered by signature via a per-state driver
|
||||
/// thunk — there is no virtual 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();
|
||||
|
||||
/// Entered carrying a sub-machine result (from
|
||||
/// startMachine<Sub, This>()). Default ignores it and runs run();
|
||||
/// Continue<R> states override to dispatch on_success / on_failure.
|
||||
virtual Coro::Task<Step> resume(LaunchResult result);
|
||||
};
|
||||
|
||||
struct EventEnvelope {
|
||||
|
||||
@@ -0,0 +1,283 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Async/Task.hpp>
|
||||
#include <Void/Fsm/Detail/Engine.hpp>
|
||||
#include <Void/Fsm/Detail/Reactive.hpp>
|
||||
#include <Void/Fsm/Detail/Result.hpp>
|
||||
#include <Void/Fsm/Step.hpp>
|
||||
|
||||
#include <any>
|
||||
#include <chrono>
|
||||
#include <concepts>
|
||||
#include <optional>
|
||||
#include <type_traits>
|
||||
#include <typeinfo>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#if __has_include(<meta>)
|
||||
#include <meta>
|
||||
#endif
|
||||
|
||||
// Signature-inferred state roles. There is ONE state base (`State`); the engine
|
||||
// discovers what each state does purely from its member signatures via P2996 —
|
||||
// no `override`, no framework-mandated names:
|
||||
// - entry : a member returning Step / Coro::Task<Step>, no params
|
||||
// - startup-entry: the same taking the sub-machine's startup-data argument
|
||||
// - reactive : a member taking TransitionBuilder<D>&
|
||||
// - result handlers (continuation): members taking `ChildSuccess auto` /
|
||||
// `ChildFailure auto` (the boxes below)
|
||||
// All discovery is invocability-based (types known at the generation site), so
|
||||
// no parameter-type reflection (P3096) is required.
|
||||
|
||||
namespace Void::Fsm
|
||||
{
|
||||
// Defined in Machine.hpp; forward-declared so InitialStateOf can pattern
|
||||
// match the state list.
|
||||
template <typename...> struct States;
|
||||
|
||||
/// The success value of a launched sub-machine, handed to a continuation
|
||||
/// handler written `ok(ChildSuccess auto s)` — `s.value` is the sub's
|
||||
/// typed Success (absent for a void-result sub).
|
||||
template <typename T> struct ChildSuccessBox {
|
||||
T value;
|
||||
};
|
||||
template <> struct ChildSuccessBox<void> {
|
||||
};
|
||||
|
||||
/// The failure value of a launched sub-machine (`no(ChildFailure auto f)`;
|
||||
/// `f.value` is the sub's typed Failure, absent for void).
|
||||
template <typename T> struct ChildFailureBox {
|
||||
T value;
|
||||
};
|
||||
template <> struct ChildFailureBox<void> {
|
||||
};
|
||||
|
||||
namespace Detail
|
||||
{
|
||||
template <class> inline constexpr bool is_csucc = false;
|
||||
template <class T>
|
||||
inline constexpr bool is_csucc<ChildSuccessBox<T>> = true;
|
||||
template <class> inline constexpr bool is_cfail = false;
|
||||
template <class T>
|
||||
inline constexpr bool is_cfail<ChildFailureBox<T>> = true;
|
||||
} // namespace Detail
|
||||
|
||||
template <class X>
|
||||
concept ChildSuccess = Detail::is_csucc<std::remove_cvref_t<X>>;
|
||||
template <class X>
|
||||
concept ChildFailure = Detail::is_cfail<std::remove_cvref_t<X>>;
|
||||
|
||||
namespace Detail
|
||||
{
|
||||
namespace Coro = Void::Coro;
|
||||
namespace meta = std::meta;
|
||||
|
||||
/// The owning machine type of a state S (via State::self()).
|
||||
template <typename S>
|
||||
using MachineOf =
|
||||
std::remove_cvref_t<decltype(std::declval<S&>().self())>;
|
||||
|
||||
template <typename> struct first_state_helper;
|
||||
template <typename F, typename... R>
|
||||
struct first_state_helper<States<F, R...>> {
|
||||
using type = F;
|
||||
};
|
||||
|
||||
/// A machine's initial state type: its nested `Initial` if declared,
|
||||
/// else the first entry of `States<...>`.
|
||||
template <typename M> consteval auto initial_state_probe()
|
||||
{
|
||||
if constexpr (requires { typename M::Initial; }) {
|
||||
return std::type_identity<typename M::Initial>{};
|
||||
} else {
|
||||
return std::type_identity<
|
||||
typename first_state_helper<typename M::States>::type>{};
|
||||
}
|
||||
}
|
||||
template <typename M>
|
||||
using InitialStateOf =
|
||||
typename decltype(initial_state_probe<M>())::type;
|
||||
|
||||
/// Wrap a ready Step in a Task. (The reflection selectors below must
|
||||
/// NOT be coroutines — `template for` + member splicing fails inside a
|
||||
/// coroutine body in this build — so they return a Task instead.)
|
||||
inline Coro::Task<Step> ready_task(Step s) { co_return s; }
|
||||
|
||||
// ── entry (0-arg member returning Step / Task<Step>) ──────────────
|
||||
template <typename S> Coro::Task<Step> invoke_entry(S& s)
|
||||
{
|
||||
static constexpr auto members = std::define_static_array(
|
||||
meta::members_of(^^S, meta::access_context::current()));
|
||||
template for (constexpr auto m : members)
|
||||
{
|
||||
if constexpr (requires(S& x) { x.[:m:](); }) {
|
||||
using R = decltype(std::declval<S&>().[:m:]());
|
||||
if constexpr (std::is_same_v<R, Step>) {
|
||||
return ready_task(s.[:m:]());
|
||||
} else if constexpr (std::is_same_v<R, Coro::Task<Step>>) {
|
||||
return s.[:m:]();
|
||||
}
|
||||
}
|
||||
}
|
||||
return ready_task(Step::fault(FsmError{
|
||||
"state has no entry (a no-arg method returning Step)"}));
|
||||
}
|
||||
|
||||
// ── startup-entry (member taking the startup-data argument[s]) ────
|
||||
template <typename S, typename... DataT>
|
||||
Coro::Task<Step> invoke_startup(S& s, DataT... data)
|
||||
{
|
||||
static constexpr auto members = std::define_static_array(
|
||||
meta::members_of(^^S, meta::access_context::current()));
|
||||
template for (constexpr auto m : members)
|
||||
{
|
||||
if constexpr (requires(S& x, DataT... d) { x.[:m:](d...); }) {
|
||||
using R = decltype(std::declval<S&>().[:m:](
|
||||
std::declval<DataT>()...));
|
||||
if constexpr (std::is_same_v<R, Step>) {
|
||||
return ready_task(s.[:m:](std::move(data)...));
|
||||
} else if constexpr (std::is_same_v<R, Coro::Task<Step>>) {
|
||||
return s.[:m:](std::move(data)...);
|
||||
}
|
||||
}
|
||||
}
|
||||
// No data-taking entry: fall back to the plain entry.
|
||||
return invoke_entry(s);
|
||||
}
|
||||
|
||||
// ── continuation handler (member taking a ChildSuccess/Failure box)
|
||||
template <typename S, typename Box>
|
||||
Coro::Task<Step> invoke_handler(S& s, Box box)
|
||||
{
|
||||
static constexpr auto members = std::define_static_array(
|
||||
meta::members_of(^^S, meta::access_context::current()));
|
||||
template for (constexpr auto m : members)
|
||||
{
|
||||
if constexpr (requires(S& x, Box b) { x.[:m:](b); }) {
|
||||
using R =
|
||||
decltype(std::declval<S&>().[:m:](std::declval<Box>()));
|
||||
if constexpr (std::is_same_v<R, Step>) {
|
||||
return ready_task(s.[:m:](std::move(box)));
|
||||
} else if constexpr (std::is_same_v<R, Coro::Task<Step>>) {
|
||||
return s.[:m:](std::move(box));
|
||||
}
|
||||
}
|
||||
}
|
||||
return ready_task(Step::fault(
|
||||
FsmError{"continuation has no handler for this sub-machine "
|
||||
"result (ChildSuccess auto / ChildFailure auto)"}));
|
||||
}
|
||||
|
||||
/// Dispatch a sub-machine's LaunchResult into the Next state's
|
||||
/// signature-matched handler. Knows Next and Sub (so the box types are
|
||||
/// concrete); built at the startMachine call site.
|
||||
template <typename Next, typename Sub>
|
||||
Coro::Task<Step> dispatch_result(Next& s, LaunchResult lr)
|
||||
{
|
||||
using Succ = SuccessOf<Sub>;
|
||||
using Fail = FailureOf<Sub>;
|
||||
if (lr.kind == LaunchResult::Kind::Failure) {
|
||||
ChildFailureBox<Fail> box;
|
||||
if constexpr (!std::is_void_v<Fail>) {
|
||||
box.value = std::any_cast<Fail>(std::move(lr.failure));
|
||||
}
|
||||
return invoke_handler(s, std::move(box));
|
||||
}
|
||||
ChildSuccessBox<Succ> box;
|
||||
if constexpr (!std::is_void_v<Succ>) {
|
||||
box.value = std::any_cast<Succ>(std::move(lr.value));
|
||||
}
|
||||
return invoke_handler(s, std::move(box));
|
||||
}
|
||||
|
||||
// ── reactive (member taking TransitionBuilder<D>&) ────────────────
|
||||
template <typename S> consteval bool has_transitions()
|
||||
{
|
||||
using D = MachineOf<S>;
|
||||
bool found = false;
|
||||
template for (constexpr auto m :
|
||||
std::define_static_array(meta::members_of(
|
||||
^^S, meta::access_context::current())))
|
||||
{
|
||||
if constexpr (requires(S& x, TransitionBuilder<D>& b) {
|
||||
x.[:m:](b);
|
||||
}) {
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
/// Fill `table` from S's transitions-shaped member (if any).
|
||||
template <typename S, typename D>
|
||||
void collect_transitions(S& s, TransitionTable<D>& table)
|
||||
{
|
||||
TransitionBuilder<D> builder{table};
|
||||
static constexpr auto members = std::define_static_array(
|
||||
meta::members_of(^^S, meta::access_context::current()));
|
||||
template for (constexpr auto m : members)
|
||||
{
|
||||
if constexpr (requires(S& x, TransitionBuilder<D>& b) {
|
||||
x.[:m:](b);
|
||||
}) {
|
||||
s.[:m:](builder);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The reactive drive loop (relocated from the old Reactive::run()):
|
||||
/// wait for a declared event or the timeout, check guards in order, run
|
||||
/// the action, transition.
|
||||
template <typename S> Coro::Task<Step> drive_reactive(S& s)
|
||||
{
|
||||
using D = MachineOf<S>;
|
||||
TransitionTable<D> table;
|
||||
collect_transitions(s, table);
|
||||
std::vector<const std::type_info*> types;
|
||||
types.reserve(table.events.size());
|
||||
for (const auto& e : table.events) {
|
||||
types.push_back(e.type);
|
||||
}
|
||||
for (;;) {
|
||||
std::optional<std::chrono::steady_clock::time_point> deadline;
|
||||
if (table.has_timeout) {
|
||||
deadline =
|
||||
std::chrono::steady_clock::now() + table.timeout_after;
|
||||
}
|
||||
auto ev = co_await s.machine().await_any_event(types, deadline);
|
||||
if (!ev) {
|
||||
co_return std::move(table.timeout_step);
|
||||
}
|
||||
D& d = s.self();
|
||||
for (auto& e : table.events) {
|
||||
if (*e.type != *ev->type) {
|
||||
continue;
|
||||
}
|
||||
if (e.guard && !e.guard(d, ev->value)) {
|
||||
continue;
|
||||
}
|
||||
if (e.action) {
|
||||
co_await e.action(d, ev->value);
|
||||
}
|
||||
co_return std::move(e.step);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-state driver thunk built at registration (S is complete):
|
||||
/// reactive states run the table, others run the entry.
|
||||
template <typename S>
|
||||
[[nodiscard]] std::function<Coro::Task<Step>(StateBase&)> make_driver()
|
||||
{
|
||||
return [](StateBase& base) -> Coro::Task<Step> {
|
||||
S& s = static_cast<S&>(base);
|
||||
if constexpr (has_transitions<S>()) {
|
||||
co_return co_await drive_reactive(s);
|
||||
} else {
|
||||
co_return co_await invoke_entry(s);
|
||||
}
|
||||
};
|
||||
}
|
||||
} // namespace Detail
|
||||
} // namespace Void::Fsm
|
||||
+120
-134
@@ -4,11 +4,11 @@
|
||||
#include <Void/Async/Task.hpp>
|
||||
#include <Void/Data/Json.hpp>
|
||||
#include <Void/Fsm/Detail/Awaiter.hpp>
|
||||
#include <Void/Fsm/Detail/Continuation.hpp>
|
||||
#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/Roles.hpp>
|
||||
#include <Void/Fsm/Detail/TypeName.hpp>
|
||||
#include <Void/Fsm/Step.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
@@ -70,21 +70,23 @@ namespace Void::Fsm
|
||||
std::uint64_t step{0};
|
||||
};
|
||||
|
||||
// ── Machine<Derived, ResultT> ─────────────────────────────────────────
|
||||
// ── Machine<Derived> ──────────────────────────────────────────────────
|
||||
//
|
||||
// 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().
|
||||
// Inheritance + coroutine workflow FSM, CRTP for typed access. Derive it,
|
||||
// declare states as nested structs deriving the single `State`, list them
|
||||
// in `using States = Fsm::States<...>`. The engine infers each state's role
|
||||
// from member signatures (entry / reactive table / continuation handlers);
|
||||
// states reach their machine (data + sub-methods) via self(). Result types
|
||||
// are the nested `Success`/`Failure` (default void).
|
||||
//
|
||||
// class Login : public Void::Fsm::Machine<Login, bool> {
|
||||
// class Login : public Void::Fsm::Machine<Login> {
|
||||
// public:
|
||||
// using Success = Token;
|
||||
// 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)
|
||||
// struct Check : State { // entry by signature
|
||||
// Coro::Task<Step> run() {
|
||||
// if (++self().attempts > 3) co_return fail();
|
||||
// co_return self().service<IAuth>().ok() ? succeed(Token{})
|
||||
// : next<Check>();
|
||||
// }
|
||||
// };
|
||||
@@ -282,19 +284,16 @@ namespace Void::Fsm
|
||||
return m_machine->template await_any<Es...>();
|
||||
}
|
||||
|
||||
/// Launch a sub-machine `Sub` (constructed from `args`,
|
||||
/// sharing this machine's executor/events/services), then
|
||||
/// transition to `Next` — which must derive
|
||||
/// Continue<Sub::result_type>. When Sub finishes the engine
|
||||
/// calls Next's on_success(result) or on_failure(error):
|
||||
/// co_return startMachine<Login, AfterLogin>(user, 3);
|
||||
/// Launch a sub-machine `Sub` (startup data routed to its
|
||||
/// initial-state startup-entry; shares this machine's
|
||||
/// executor/events/services), then transition to `Next`.
|
||||
/// When Sub finishes the engine calls Next's signature
|
||||
/// -matched handler — a member taking `ChildSuccess auto`
|
||||
/// (Sub succeeded) or `ChildFailure auto` (Sub failed):
|
||||
/// co_return startMachine<Login, AfterLogin>(seed);
|
||||
template <typename Sub, typename Next, typename... Args>
|
||||
[[nodiscard]] Step startMachine(Args&&... args) const
|
||||
{
|
||||
static_assert(
|
||||
std::is_base_of_v<Continue<Sub>, Next>,
|
||||
"startMachine<Sub, Next>: Next must derive "
|
||||
"Continue<Sub>");
|
||||
return m_machine->template start_machine<Sub, Next>(
|
||||
std::forward<Args>(args)...);
|
||||
}
|
||||
@@ -310,106 +309,33 @@ namespace Void::Fsm
|
||||
Machine* m_machine{nullptr};
|
||||
};
|
||||
|
||||
// ── continuation states ───────────────────────────────────────
|
||||
// ── one State, signature-inferred roles ───────────────────────
|
||||
//
|
||||
// A state that resumes from a launched sub-machine. Reach it with
|
||||
// `co_return startMachine<Sub, Next>(args...)`; the engine runs Sub
|
||||
// then enters Next, dispatching to on_success / on_failure by the
|
||||
// outcome:
|
||||
// There is a single base, `State`. The engine infers what each
|
||||
// state does from member signatures (no `override`, no fixed
|
||||
// names):
|
||||
// - entry : a member returning Step/Coro::Task<Step>,
|
||||
// no params (a startup-data overload may take
|
||||
// the sub's startup argument);
|
||||
// - reactive : a member taking `TransitionBuilder&` (the
|
||||
// declarative table below);
|
||||
// - continuation : members taking `ChildSuccess auto` /
|
||||
// `ChildFailure auto` (the sub's typed result
|
||||
// after `startMachine<Sub, This>()`).
|
||||
//
|
||||
// struct AfterLogin : Continue<bool> { // Sub =
|
||||
// Machine<..,bool>
|
||||
// Coro::Task<Step> on_success(bool ok) override {
|
||||
// co_return ok ? next<Home>() : next<Locked>(); }
|
||||
// Coro::Task<Step> on_failure(FsmError e) override {
|
||||
// co_return fail(e.message); }
|
||||
// };
|
||||
template <typename Sub>
|
||||
using Continue = Detail::Continuation<State, Sub>;
|
||||
|
||||
// ── reactive (declarative) states ─────────────────────────────
|
||||
// struct Idle : State { // reactive
|
||||
// void transitions(TransitionBuilder& on) {
|
||||
// on.event<Go>().to<Running>();
|
||||
// on.after(5s).to<TimedOut>(); } };
|
||||
// struct After : State { // continuation
|
||||
// Coro::Task<Step> ok(ChildSuccess auto s){ ... }
|
||||
// Coro::Task<Step> no(ChildFailure auto f){ ... } };
|
||||
//
|
||||
// A reactive state declares a transition table instead of an
|
||||
// imperative run(): it waits for the declared events (or a
|
||||
// timeout), checks guards in order, runs actions, and
|
||||
// transitions. Mix freely with imperative State subclasses.
|
||||
//
|
||||
// struct Idle : Reactive {
|
||||
// void transitions(TransitionBuilder& on) override {
|
||||
// on.event<Go>().guard([](Idle& s, const Go& g){...})
|
||||
// .action([](Idle& s, const Go&){...})
|
||||
// .to<Running>();
|
||||
// on.event<Stop>().to<Done>();
|
||||
// on.after(5s).to<TimedOut>();
|
||||
// }
|
||||
// };
|
||||
|
||||
// The declarative transition DSL lives in Detail/Reactive.hpp;
|
||||
// these aliases give reactive states the ergonomic nested names.
|
||||
// The declarative DSL lives in Detail/Reactive.hpp; these aliases
|
||||
// give the `transitions(TransitionBuilder&)` member its type.
|
||||
using TransitionTable = Detail::TransitionTable<Derived>;
|
||||
using TransitionBuilder = Detail::TransitionBuilder<Derived>;
|
||||
|
||||
class Reactive : public State
|
||||
{
|
||||
public:
|
||||
|
||||
[[nodiscard]] Detail::StateKind
|
||||
kind() const noexcept override
|
||||
{
|
||||
return Detail::StateKind::Reactive;
|
||||
}
|
||||
|
||||
/// Declare this state's event/timeout transitions.
|
||||
virtual void transitions(TransitionBuilder& on) = 0;
|
||||
|
||||
/// Build this state's table without running it — used by
|
||||
/// describe()/to_mermaid() for introspection.
|
||||
void collect(TransitionTable& table)
|
||||
{
|
||||
TransitionBuilder builder{table};
|
||||
transitions(builder);
|
||||
}
|
||||
|
||||
Coro::Task<Step> run() final
|
||||
{
|
||||
TransitionTable table;
|
||||
collect(table);
|
||||
std::vector<const std::type_info*> types;
|
||||
types.reserve(table.events.size());
|
||||
for (const auto& e : table.events) {
|
||||
types.push_back(e.type);
|
||||
}
|
||||
for (;;) {
|
||||
std::optional<std::chrono::steady_clock::time_point>
|
||||
deadline;
|
||||
if (table.has_timeout) {
|
||||
deadline = std::chrono::steady_clock::now() +
|
||||
table.timeout_after;
|
||||
}
|
||||
auto ev = co_await this->machine().await_any_event(
|
||||
types, deadline);
|
||||
if (!ev) {
|
||||
co_return std::move(table.timeout_step);
|
||||
}
|
||||
Derived& d = this->self();
|
||||
bool matched = false;
|
||||
for (auto& e : table.events) {
|
||||
if (*e.type != *ev->type) {
|
||||
continue;
|
||||
}
|
||||
if (e.guard && !e.guard(d, ev->value)) {
|
||||
continue;
|
||||
}
|
||||
if (e.action) {
|
||||
co_await e.action(d, ev->value);
|
||||
}
|
||||
co_return std::move(e.step);
|
||||
}
|
||||
(void)matched; // unmatched event is dropped
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// ── construction ──────────────────────────────────────────────
|
||||
explicit Machine(Options options = {}) : m_options(options)
|
||||
{
|
||||
@@ -448,6 +374,20 @@ namespace Void::Fsm
|
||||
s->m_machine = this;
|
||||
return s;
|
||||
});
|
||||
// Signature-inferred driver thunk (entry or reactive table).
|
||||
m_drivers.emplace(key, Detail::make_driver<S>());
|
||||
// describe() collector: fills a table if S is reactive.
|
||||
m_collectors.emplace(
|
||||
key,
|
||||
[](Detail::StateBase& base,
|
||||
TransitionTable& table) -> bool {
|
||||
if constexpr (Detail::has_transitions<S>()) {
|
||||
Detail::collect_transitions(static_cast<S&>(base),
|
||||
table);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
template <typename S> void initial()
|
||||
@@ -495,6 +435,8 @@ namespace Void::Fsm
|
||||
m_name_to_type.erase(m_names[static_cast<std::size_t>(idx)]);
|
||||
m_names.erase(m_names.begin() + idx);
|
||||
m_factories.erase(key);
|
||||
m_drivers.erase(key);
|
||||
m_collectors.erase(key);
|
||||
m_index.erase(idxIt);
|
||||
// Re-pack the indices of states that followed S.
|
||||
for (auto& [k, v] : m_index) {
|
||||
@@ -838,14 +780,24 @@ namespace Void::Fsm
|
||||
Derived::States::template contains<Next>(),
|
||||
"startMachine<Sub, Next>: Next is not in States<...>");
|
||||
}
|
||||
using Init = Detail::InitialStateOf<Sub>;
|
||||
auto launcher =
|
||||
[this,
|
||||
tup = std::make_tuple(std::forward<Args>(
|
||||
args)...)]() mutable -> Coro::Task<LaunchResult> {
|
||||
// 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));
|
||||
[this, ... data = std::forward<Args>(
|
||||
args)]() mutable -> Coro::Task<LaunchResult> {
|
||||
// Run Sub on the shared executor. Startup data (if any) is
|
||||
// delivered to Sub's initial-state startup-entry via an
|
||||
// injector, not the constructor.
|
||||
Sub child;
|
||||
child.attach(m_ctx, m_services);
|
||||
if constexpr (sizeof...(Args) > 0) {
|
||||
child.m_startup_injector =
|
||||
[... d = std::move(data)](
|
||||
Detail::StateBase& base) mutable
|
||||
-> Coro::Task<Step> {
|
||||
return Detail::invoke_startup<Init>(
|
||||
static_cast<Init&>(base), std::move(d)...);
|
||||
};
|
||||
}
|
||||
co_await child.drive();
|
||||
LaunchResult lr;
|
||||
switch (child.m_status.load(std::memory_order_acquire)) {
|
||||
@@ -865,7 +817,14 @@ namespace Void::Fsm
|
||||
}
|
||||
co_return lr;
|
||||
};
|
||||
return Step::launch(typeid(Next), std::move(launcher));
|
||||
Step::Dispatch dispatch =
|
||||
[](Detail::StateBase& base,
|
||||
LaunchResult lr) -> Coro::Task<Step> {
|
||||
return Detail::dispatch_result<Next, Sub>(
|
||||
static_cast<Next&>(base), std::move(lr));
|
||||
};
|
||||
return Step::launch(typeid(Next), std::move(launcher),
|
||||
std::move(dispatch));
|
||||
}
|
||||
|
||||
// ── observation ───────────────────────────────────────────────
|
||||
@@ -924,11 +883,11 @@ namespace Void::Fsm
|
||||
si.name = name;
|
||||
si.initial = (name == initial_name);
|
||||
const auto* ti = m_name_to_type.at(name);
|
||||
auto state = m_factories.at(std::type_index{*ti})();
|
||||
si.reactive = state->kind() == Detail::StateKind::Reactive;
|
||||
if (auto* reactive = dynamic_cast<Reactive*>(state.get())) {
|
||||
TransitionTable table;
|
||||
reactive->collect(table);
|
||||
const std::type_index key{*ti};
|
||||
auto state = m_factories.at(key)();
|
||||
TransitionTable table;
|
||||
si.reactive = m_collectors.at(key)(*state, table);
|
||||
if (si.reactive) {
|
||||
for (const auto& e : table.events) {
|
||||
si.edges.push_back(
|
||||
EdgeInfo{e.event_name, e.target_name,
|
||||
@@ -1102,6 +1061,7 @@ namespace Void::Fsm
|
||||
fault("no initial state");
|
||||
co_return;
|
||||
}
|
||||
bool first = true;
|
||||
for (;;) {
|
||||
// Apply an external jump<S>() at this transition boundary.
|
||||
if (const auto* j =
|
||||
@@ -1109,6 +1069,7 @@ namespace Void::Fsm
|
||||
j != nullptr) {
|
||||
cur = j;
|
||||
m_pending_result.reset();
|
||||
m_pending_dispatch = nullptr;
|
||||
}
|
||||
const auto it = m_factories.find(std::type_index{*cur});
|
||||
if (it == m_factories.end()) {
|
||||
@@ -1118,20 +1079,29 @@ namespace Void::Fsm
|
||||
set_current(cur);
|
||||
auto state = it->second();
|
||||
co_await state->on_enter();
|
||||
// A state entered via startMachine resumes from the sub's
|
||||
// result; otherwise it runs.
|
||||
// Decide how the state runs: a launched sub's result (via
|
||||
// the bound dispatcher), the startup injector for the first
|
||||
// state, or the signature-inferred driver thunk.
|
||||
Step step;
|
||||
if (m_pending_result.has_value()) {
|
||||
if (m_pending_dispatch) {
|
||||
LaunchResult pending = std::move(*m_pending_result);
|
||||
auto dispatch = std::move(m_pending_dispatch);
|
||||
m_pending_result.reset();
|
||||
m_pending_dispatch = nullptr;
|
||||
if (pending.kind == LaunchResult::Kind::Fault) {
|
||||
fault(std::move(pending.fault.message));
|
||||
co_return;
|
||||
}
|
||||
step = co_await state->resume(std::move(pending));
|
||||
step = co_await dispatch(*state, std::move(pending));
|
||||
} else if (first && m_startup_injector) {
|
||||
auto inject = std::move(m_startup_injector);
|
||||
m_startup_injector = nullptr;
|
||||
step = co_await inject(*state);
|
||||
} else {
|
||||
step = co_await state->run();
|
||||
step = co_await m_drivers.at(std::type_index{*cur})(
|
||||
*state);
|
||||
}
|
||||
first = false;
|
||||
co_await state->on_exit();
|
||||
fire_after(current_state());
|
||||
switch (step.kind()) {
|
||||
@@ -1141,6 +1111,7 @@ namespace Void::Fsm
|
||||
case Step::Kind::Launch:
|
||||
m_pending_result.emplace(
|
||||
co_await step.run_launch());
|
||||
m_pending_dispatch = step.take_dispatch();
|
||||
cur = step.target();
|
||||
continue;
|
||||
case Step::Kind::Success:
|
||||
@@ -1214,6 +1185,15 @@ namespace Void::Fsm
|
||||
std::type_index,
|
||||
std::function<std::unique_ptr<Detail::StateBase>()>>
|
||||
m_factories;
|
||||
// Per-state signature-inferred driver thunk (entry / reactive).
|
||||
std::unordered_map<std::type_index, std::function<Coro::Task<Step>(
|
||||
Detail::StateBase&)>>
|
||||
m_drivers;
|
||||
// Per-state describe() collector (reactive table, if any).
|
||||
std::unordered_map<
|
||||
std::type_index,
|
||||
std::function<bool(Detail::StateBase&, TransitionTable&)>>
|
||||
m_collectors;
|
||||
std::unordered_map<std::type_index, int> m_index;
|
||||
std::vector<std::string> m_names;
|
||||
std::unordered_map<std::string, const std::type_info*>
|
||||
@@ -1235,8 +1215,14 @@ namespace Void::Fsm
|
||||
std::function<std::vector<std::string>()> m_region_probe;
|
||||
|
||||
// Set by a Launch step's sub-machine result; consumed by the next
|
||||
// state's resume() (a Continue<R> dispatch).
|
||||
// state via the bound dispatcher below.
|
||||
std::optional<LaunchResult> m_pending_result;
|
||||
Step::Dispatch m_pending_dispatch;
|
||||
|
||||
// Seeds the initial state's startup-entry with launch data (set by
|
||||
// the parent's launcher before driving this machine).
|
||||
std::function<Coro::Task<Step>(Detail::StateBase&)>
|
||||
m_startup_injector;
|
||||
|
||||
// External jump request (jump<S>()); applied by drive() at the
|
||||
// next transition boundary.
|
||||
|
||||
@@ -12,6 +12,11 @@ namespace Void::Fsm
|
||||
{
|
||||
namespace Coro = Void::Coro;
|
||||
|
||||
namespace Detail
|
||||
{
|
||||
class StateBase;
|
||||
}
|
||||
|
||||
/// 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
|
||||
@@ -65,16 +70,23 @@ namespace Void::Fsm
|
||||
return s;
|
||||
}
|
||||
|
||||
/// A bound dispatcher: given the entered Next state and the sub's
|
||||
/// LaunchResult, calls Next's signature-matched handler.
|
||||
using Dispatch = std::function<Coro::Task<Step>(Detail::StateBase&,
|
||||
LaunchResult)>;
|
||||
|
||||
/// Launch a sub-machine, then enter `target` (a continuation state)
|
||||
/// with the sub's LaunchResult.
|
||||
/// with the sub's LaunchResult, dispatched via `dispatch`.
|
||||
[[nodiscard]] static Step
|
||||
launch(const std::type_info& target,
|
||||
std::function<Coro::Task<LaunchResult>()> launcher)
|
||||
std::function<Coro::Task<LaunchResult>()> launcher,
|
||||
Dispatch dispatch)
|
||||
{
|
||||
Step s;
|
||||
s.m_kind = Kind::Launch;
|
||||
s.m_target = ⌖
|
||||
s.m_launcher = std::move(launcher);
|
||||
s.m_dispatch = std::move(dispatch);
|
||||
return s;
|
||||
}
|
||||
|
||||
@@ -112,12 +124,19 @@ namespace Void::Fsm
|
||||
return m_launcher();
|
||||
}
|
||||
|
||||
/// Take the bound dispatcher for a Launch step.
|
||||
[[nodiscard]] Dispatch take_dispatch()
|
||||
{
|
||||
return std::move(m_dispatch);
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
Kind m_kind{Kind::Fail};
|
||||
const std::type_info* m_target{nullptr};
|
||||
std::any m_payload;
|
||||
std::function<Coro::Task<LaunchResult>()> m_launcher;
|
||||
Dispatch m_dispatch;
|
||||
};
|
||||
|
||||
} // namespace Void::Fsm
|
||||
+2
-12
@@ -5,20 +5,10 @@
|
||||
namespace Void::Fsm::Detail
|
||||
{
|
||||
|
||||
// Default state lifecycle hooks.
|
||||
// Default state lifecycle hooks (no-ops). The state's behaviour is driven
|
||||
// by a per-state, signature-inferred thunk built at registration.
|
||||
Coro::Task<void> StateBase::on_enter() { co_return; }
|
||||
Coro::Task<void> StateBase::on_exit() { co_return; }
|
||||
Coro::Task<Step> StateBase::run()
|
||||
{
|
||||
co_return Step::fault(FsmError{"state defines no entry"});
|
||||
}
|
||||
|
||||
Coro::Task<Step> StateBase::resume(LaunchResult /*result*/)
|
||||
{
|
||||
// A plain state entered with a pending sub-machine result just runs;
|
||||
// Continue<R> overrides this to dispatch on_success / on_failure.
|
||||
co_return co_await run();
|
||||
}
|
||||
|
||||
ExecutionContext::~ExecutionContext() { stop(); }
|
||||
|
||||
|
||||
@@ -44,7 +44,7 @@ namespace
|
||||
using Success = int;
|
||||
|
||||
struct Work : State {
|
||||
Task<Step> run() override
|
||||
Task<Step> run()
|
||||
{
|
||||
auto& svc = service<VoidTest::ICalc>();
|
||||
const int total = svc.accumulate(1);
|
||||
|
||||
@@ -22,7 +22,7 @@ namespace
|
||||
std::vector<std::string>* log = nullptr;
|
||||
|
||||
struct Start : State {
|
||||
Task<Step> run() override
|
||||
Task<Step> run()
|
||||
{
|
||||
if (self().log) {
|
||||
self().log->push_back("start");
|
||||
@@ -32,7 +32,7 @@ namespace
|
||||
};
|
||||
|
||||
struct Work : State {
|
||||
Task<Step> run() override
|
||||
Task<Step> run()
|
||||
{
|
||||
auto& m = self();
|
||||
++m.count;
|
||||
@@ -63,7 +63,7 @@ namespace
|
||||
using Failure = Void::Fsm::FsmError;
|
||||
|
||||
struct Boom : State {
|
||||
Task<Step> run() override { co_return fail("kaboom"); }
|
||||
Task<Step> run() { co_return fail("kaboom"); }
|
||||
};
|
||||
|
||||
using States = Void::Fsm::States<Boom>;
|
||||
@@ -114,7 +114,7 @@ Void::Testing::Test fsm_void_result_succeeds()
|
||||
{
|
||||
struct Trivial : Void::Fsm::Machine<Trivial> {
|
||||
struct Done : State {
|
||||
Task<Step> run() override { co_return succeed(); }
|
||||
Task<Step> run() { co_return succeed(); }
|
||||
};
|
||||
using States = Void::Fsm::States<Done>;
|
||||
Trivial()
|
||||
@@ -137,13 +137,13 @@ Void::Testing::Test fsm_dynamic_state_registration()
|
||||
|
||||
bool express;
|
||||
struct Express : State {
|
||||
Task<Step> run() override { co_return succeed(99); }
|
||||
Task<Step> run() { co_return succeed(99); }
|
||||
};
|
||||
struct Normal : State {
|
||||
Task<Step> run() override { co_return succeed(1); }
|
||||
Task<Step> run() { co_return succeed(1); }
|
||||
};
|
||||
struct Start : State {
|
||||
Task<Step> run() override
|
||||
Task<Step> run()
|
||||
{
|
||||
if (self().has_state<Express>()) {
|
||||
co_return next_dynamic<Express>();
|
||||
|
||||
@@ -32,7 +32,7 @@ namespace
|
||||
long long target;
|
||||
|
||||
struct Run : State {
|
||||
Task<Step> run() override
|
||||
Task<Step> run()
|
||||
{
|
||||
auto& m = self();
|
||||
while (m.total < m.target) {
|
||||
@@ -138,7 +138,7 @@ Void::Testing::Test fsm_resolves_service_through_context()
|
||||
using Success = int;
|
||||
|
||||
struct Go : State {
|
||||
Task<Step> run() override
|
||||
Task<Step> run()
|
||||
{
|
||||
co_return succeed(service<IDoubler>().twice(21));
|
||||
}
|
||||
|
||||
@@ -29,7 +29,7 @@ namespace
|
||||
int total = 0;
|
||||
|
||||
struct Take : State {
|
||||
Task<Step> run() override
|
||||
Task<Step> run()
|
||||
{
|
||||
auto a = co_await await_event<Add>();
|
||||
self().total += a.n;
|
||||
@@ -64,13 +64,13 @@ namespace
|
||||
using Success = int;
|
||||
|
||||
struct A : State {
|
||||
Task<Step> run() override { co_return goto_state<C>(); }
|
||||
Task<Step> run() { co_return goto_state<C>(); }
|
||||
};
|
||||
struct B : State {
|
||||
Task<Step> run() override { co_return succeed(1); }
|
||||
Task<Step> run() { co_return succeed(1); }
|
||||
};
|
||||
struct C : State {
|
||||
Task<Step> run() override { co_return succeed(3); }
|
||||
Task<Step> run() { co_return succeed(3); }
|
||||
};
|
||||
using States = Fsm::States<A, B, C>;
|
||||
};
|
||||
@@ -99,14 +99,14 @@ namespace
|
||||
using Success = int;
|
||||
|
||||
struct Loop : State {
|
||||
Task<Step> run() override
|
||||
Task<Step> run()
|
||||
{
|
||||
co_await await_event<Tick>();
|
||||
co_return next<Loop>();
|
||||
}
|
||||
};
|
||||
struct Done : State {
|
||||
Task<Step> run() override { co_return succeed(99); }
|
||||
Task<Step> run() { co_return succeed(99); }
|
||||
};
|
||||
using States = Fsm::States<Loop, Done>;
|
||||
|
||||
@@ -148,10 +148,7 @@ namespace
|
||||
int runs = 0;
|
||||
|
||||
struct Once : State {
|
||||
Task<Step> run() override
|
||||
{
|
||||
co_return succeed(++self().runs);
|
||||
}
|
||||
Task<Step> run() { co_return succeed(++self().runs); }
|
||||
};
|
||||
using States = Fsm::States<Once>;
|
||||
};
|
||||
@@ -177,10 +174,10 @@ namespace
|
||||
using Success = int;
|
||||
|
||||
struct A : State {
|
||||
Task<Step> run() override { co_return succeed(1); }
|
||||
Task<Step> run() { co_return succeed(1); }
|
||||
};
|
||||
struct B : State {
|
||||
Task<Step> run() override { co_return succeed(2); }
|
||||
Task<Step> run() { co_return succeed(2); }
|
||||
};
|
||||
using States = Fsm::States<A, B>; // initial = A
|
||||
};
|
||||
@@ -208,17 +205,17 @@ namespace
|
||||
using Success = int;
|
||||
|
||||
struct A : State {
|
||||
Task<Step> run() override { co_return succeed(1); }
|
||||
Task<Step> run() { co_return succeed(1); }
|
||||
};
|
||||
struct B : State {
|
||||
Task<Step> run() override { co_return succeed(2); }
|
||||
Task<Step> run() { co_return succeed(2); }
|
||||
};
|
||||
struct C : State {
|
||||
Task<Step> run() override { co_return succeed(3); }
|
||||
Task<Step> run() { co_return succeed(3); }
|
||||
};
|
||||
// Not in States<> — added via replace<>.
|
||||
struct Extra : State {
|
||||
Task<Step> run() override { co_return succeed(7); }
|
||||
Task<Step> run() { co_return succeed(7); }
|
||||
};
|
||||
using States = Fsm::States<A, B, C>;
|
||||
};
|
||||
@@ -261,7 +258,7 @@ namespace
|
||||
using Success = int;
|
||||
|
||||
struct W : State {
|
||||
Task<Step> run() override
|
||||
Task<Step> run()
|
||||
{
|
||||
co_await await_event<Go>();
|
||||
co_return succeed(5);
|
||||
|
||||
@@ -30,7 +30,7 @@ namespace
|
||||
std::vector<int>* order = nullptr;
|
||||
|
||||
struct Waiting : State {
|
||||
Task<Step> run() override
|
||||
Task<Step> run()
|
||||
{
|
||||
auto& m = self();
|
||||
// Two typed mailboxes: pull whichever arrives.
|
||||
|
||||
@@ -32,7 +32,7 @@ namespace
|
||||
using Failure = Void::Fsm::FsmError;
|
||||
|
||||
struct Waiting : State {
|
||||
Task<Step> run() override
|
||||
Task<Step> run()
|
||||
{
|
||||
auto ev = co_await await_any<Tick, Cancel>();
|
||||
if (std::holds_alternative<Cancel>(ev)) {
|
||||
@@ -58,7 +58,7 @@ namespace
|
||||
using Success = std::string;
|
||||
|
||||
struct Running : State {
|
||||
Task<Step> run() override
|
||||
Task<Step> run()
|
||||
{
|
||||
auto r = co_await run_region<Work>();
|
||||
if (r.has_value()) {
|
||||
@@ -68,7 +68,7 @@ namespace
|
||||
}
|
||||
};
|
||||
struct Aborted : State {
|
||||
Task<Step> run() override
|
||||
Task<Step> run()
|
||||
{
|
||||
co_return succeed(std::string{"aborted"});
|
||||
}
|
||||
|
||||
@@ -27,7 +27,7 @@ namespace
|
||||
self().log.push_back("enter A");
|
||||
co_return;
|
||||
}
|
||||
Task<Step> run() override
|
||||
Task<Step> run()
|
||||
{
|
||||
self().log.push_back("run A");
|
||||
co_return next<B>();
|
||||
@@ -45,7 +45,7 @@ namespace
|
||||
self().log.push_back("enter B");
|
||||
co_return;
|
||||
}
|
||||
Task<Step> run() override
|
||||
Task<Step> run()
|
||||
{
|
||||
self().log.push_back("run B");
|
||||
co_return succeed(1);
|
||||
|
||||
@@ -20,7 +20,7 @@ namespace
|
||||
int seed;
|
||||
|
||||
struct Compute : State {
|
||||
Task<Step> run() override
|
||||
Task<Step> run()
|
||||
{
|
||||
auto& m = self();
|
||||
co_return succeed(m.seed * 10);
|
||||
@@ -45,7 +45,7 @@ namespace
|
||||
using Failure = Void::Fsm::FsmError;
|
||||
|
||||
struct Boom : State {
|
||||
Task<Step> run() override { co_return fail("child boom"); }
|
||||
Task<Step> run() { co_return fail("child boom"); }
|
||||
};
|
||||
FailingChild()
|
||||
: Void::Fsm::Machine<FailingChild>(
|
||||
@@ -64,7 +64,7 @@ namespace
|
||||
using Failure = Void::Fsm::FsmError;
|
||||
|
||||
struct Start : State {
|
||||
Task<Step> run() override
|
||||
Task<Step> run()
|
||||
{
|
||||
auto a = co_await run_child<Subtotal>(3); // 30
|
||||
auto b = co_await run_child<Subtotal>(4); // 40
|
||||
@@ -91,7 +91,7 @@ namespace
|
||||
using Failure = Void::Fsm::FsmError;
|
||||
|
||||
struct Start : State {
|
||||
Task<Step> run() override
|
||||
Task<Step> run()
|
||||
{
|
||||
auto r = co_await run_child<FailingChild>();
|
||||
if (!r.has_value()) {
|
||||
@@ -136,7 +136,7 @@ Void::Testing::Test fsm_nesting_with_worker_thread()
|
||||
using Success = int;
|
||||
|
||||
struct Start : State {
|
||||
Task<Step> run() override
|
||||
Task<Step> run()
|
||||
{
|
||||
auto a = co_await run_child<Subtotal>(5); // 50
|
||||
co_return succeed(a.value_or(-1));
|
||||
|
||||
@@ -31,7 +31,7 @@ namespace
|
||||
int retries; // how many tries with_retry gets
|
||||
|
||||
struct Try : State {
|
||||
Task<Step> run() override
|
||||
Task<Step> run()
|
||||
{
|
||||
auto& m = self();
|
||||
const bool ok = co_await with_retry(
|
||||
@@ -46,7 +46,7 @@ namespace
|
||||
};
|
||||
|
||||
struct Fallback : State {
|
||||
Task<Step> run() override
|
||||
Task<Step> run()
|
||||
{
|
||||
co_return succeed(std::string{"fallback"});
|
||||
}
|
||||
@@ -92,10 +92,10 @@ namespace
|
||||
using Success = int;
|
||||
|
||||
struct A : State {
|
||||
Task<Step> run() override { co_return next<B>(); }
|
||||
Task<Step> run() { co_return next<B>(); }
|
||||
};
|
||||
struct B : State {
|
||||
Task<Step> run() override { co_return succeed(1); }
|
||||
Task<Step> run() { co_return succeed(1); }
|
||||
};
|
||||
using States = Void::Fsm::States<A, B>;
|
||||
Pipe()
|
||||
@@ -155,8 +155,8 @@ namespace
|
||||
|
||||
using Success = int;
|
||||
|
||||
struct Idle : Reactive {
|
||||
void transitions(TransitionBuilder& on) override
|
||||
struct Idle : State {
|
||||
void transitions(TransitionBuilder& on)
|
||||
{
|
||||
on.event<Go>()
|
||||
.guard([](Flow&, const Go&) { return true; })
|
||||
@@ -166,10 +166,10 @@ namespace
|
||||
}
|
||||
};
|
||||
struct Active : State {
|
||||
Task<Step> run() override { co_return next<Done>(); }
|
||||
Task<Step> run() { co_return next<Done>(); }
|
||||
};
|
||||
struct Done : State {
|
||||
Task<Step> run() override { co_return succeed(0); }
|
||||
Task<Step> run() { co_return succeed(0); }
|
||||
};
|
||||
using States = Void::Fsm::States<Idle, Active, Done>;
|
||||
Flow() {}
|
||||
|
||||
@@ -32,8 +32,8 @@ namespace
|
||||
int total = 0;
|
||||
std::vector<std::string> trace;
|
||||
|
||||
struct Idle : Reactive {
|
||||
void transitions(TransitionBuilder& on) override
|
||||
struct Idle : State {
|
||||
void transitions(TransitionBuilder& on)
|
||||
{
|
||||
// Guarded: only positive amounts advance.
|
||||
on.event<Go>()
|
||||
@@ -52,10 +52,7 @@ namespace
|
||||
|
||||
// Imperative terminal state: reports the accumulated total.
|
||||
struct Done : State {
|
||||
Task<Step> run() override
|
||||
{
|
||||
co_return succeed(self().total);
|
||||
}
|
||||
Task<Step> run() { co_return succeed(self().total); }
|
||||
};
|
||||
|
||||
using States = Void::Fsm::States<Idle, Done>;
|
||||
@@ -97,7 +94,7 @@ namespace
|
||||
using Success = std::string;
|
||||
|
||||
struct Waiting : State {
|
||||
Task<Step> run() override
|
||||
Task<Step> run()
|
||||
{
|
||||
auto w = co_await await_event_for<Wake>(15ms);
|
||||
if (w.has_value()) {
|
||||
@@ -140,18 +137,18 @@ namespace
|
||||
|
||||
using Success = int;
|
||||
|
||||
struct Pending : Reactive {
|
||||
void transitions(TransitionBuilder& on) override
|
||||
struct Pending : State {
|
||||
void transitions(TransitionBuilder& on)
|
||||
{
|
||||
on.event<Wake>().template to<Resolved>();
|
||||
on.after(15ms).template to<Expired>();
|
||||
}
|
||||
};
|
||||
struct Resolved : State {
|
||||
Task<Step> run() override { co_return succeed(1); }
|
||||
Task<Step> run() { co_return succeed(1); }
|
||||
};
|
||||
struct Expired : State {
|
||||
Task<Step> run() override { co_return succeed(2); }
|
||||
Task<Step> run() { co_return succeed(2); }
|
||||
};
|
||||
using States = Void::Fsm::States<Pending, Resolved, Expired>;
|
||||
Deadline() {}
|
||||
|
||||
@@ -26,14 +26,14 @@ namespace
|
||||
Data data;
|
||||
|
||||
struct Ingest : State {
|
||||
Task<Step> run() override
|
||||
Task<Step> run()
|
||||
{
|
||||
co_await await_event<int>(); // park here
|
||||
co_return next<Process>();
|
||||
}
|
||||
};
|
||||
struct Process : State {
|
||||
Task<Step> run() override
|
||||
Task<Step> run()
|
||||
{
|
||||
auto& m = self();
|
||||
m.data.processed += 1;
|
||||
|
||||
@@ -3,20 +3,25 @@
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <string>
|
||||
#include <variant>
|
||||
|
||||
using Void::Coro::Task;
|
||||
using Void::Fsm::ChildFailure;
|
||||
using Void::Fsm::ChildSuccess;
|
||||
using Void::Fsm::FsmError;
|
||||
using Void::Fsm::Step;
|
||||
namespace Fsm = Void::Fsm;
|
||||
|
||||
// startMachine<Sub, Next>(args...) launches a full sub-FSM on the parent's
|
||||
// shared executor/events/services, then enters Next — a Continue<Sub::result>
|
||||
// state — and the engine dispatches to on_success / on_failure by the outcome.
|
||||
// startMachine<Sub, Next>(data) launches a full sub-FSM on the parent's shared
|
||||
// executor/events/services (startup data routed to Sub's initial-state
|
||||
// startup-entry), then enters Next. The engine dispatches the sub's typed
|
||||
// outcome to Next's signature-matched handler — a member taking
|
||||
// `ChildSuccess auto` (success) or `ChildFailure auto` (failure). No override,
|
||||
// no fixed names.
|
||||
|
||||
namespace
|
||||
{
|
||||
// Sub-machine seeded by constructor arg: doubles `seed`, fails if negative.
|
||||
// Sub-machine seeded via its startup-entry (run(int)): doubles the seed,
|
||||
// fails (typed FsmError) if negative.
|
||||
class Doubler : public Fsm::Machine<Doubler>
|
||||
{
|
||||
public:
|
||||
@@ -24,20 +29,16 @@ namespace
|
||||
using Success = int;
|
||||
using Failure = Void::Fsm::FsmError;
|
||||
|
||||
int seed;
|
||||
|
||||
struct Run : State {
|
||||
Task<Step> run() override
|
||||
Task<Step> run(int seed)
|
||||
{
|
||||
if (self().seed < 0) {
|
||||
if (seed < 0) {
|
||||
co_return fail("negative");
|
||||
}
|
||||
co_return succeed(self().seed * 2);
|
||||
co_return succeed(seed * 2);
|
||||
}
|
||||
};
|
||||
using States = Fsm::States<Run>;
|
||||
|
||||
explicit Doubler(int s = 0) : seed(s) {}
|
||||
};
|
||||
|
||||
class Calc : public Fsm::Machine<Calc>
|
||||
@@ -49,20 +50,20 @@ namespace
|
||||
int input = 0;
|
||||
|
||||
struct Start : State {
|
||||
Task<Step> run() override
|
||||
Task<Step> run()
|
||||
{
|
||||
co_return startMachine<Doubler, AfterDouble>(
|
||||
self().input);
|
||||
}
|
||||
};
|
||||
struct AfterDouble : Continue<Doubler> {
|
||||
Task<Step> on_success(int v) override
|
||||
struct AfterDouble : State {
|
||||
Task<Step> ok(ChildSuccess auto s)
|
||||
{
|
||||
co_return succeed("doubled:" + std::to_string(v));
|
||||
co_return succeed("doubled:" + std::to_string(s.value));
|
||||
}
|
||||
Task<Step> on_failure(FsmError e) override
|
||||
Task<Step> no(ChildFailure auto f)
|
||||
{
|
||||
co_return succeed("failed:" + e.message);
|
||||
co_return succeed("failed:" + f.value.message);
|
||||
}
|
||||
};
|
||||
using States = Fsm::States<Start, AfterDouble>;
|
||||
@@ -98,7 +99,7 @@ namespace
|
||||
public:
|
||||
|
||||
struct Ping : State {
|
||||
Task<Step> run() override { co_return succeed(); }
|
||||
Task<Step> run() { co_return succeed(); }
|
||||
};
|
||||
using States = Fsm::States<Ping>;
|
||||
};
|
||||
@@ -110,23 +111,18 @@ namespace
|
||||
using Success = int;
|
||||
|
||||
struct Go : State {
|
||||
Task<Step> run() override
|
||||
{
|
||||
co_return startMachine<Pinger, Done>();
|
||||
}
|
||||
Task<Step> run() { co_return startMachine<Pinger, Done>(); }
|
||||
};
|
||||
struct Done : Continue<Pinger> {
|
||||
Task<Step> on_success(std::monostate) override
|
||||
{
|
||||
co_return succeed(42);
|
||||
}
|
||||
struct Done : State {
|
||||
// void-result sub: ChildSuccess box has no value.
|
||||
Task<Step> ok(ChildSuccess auto) { co_return succeed(42); }
|
||||
};
|
||||
using States = Fsm::States<Go, Done>;
|
||||
};
|
||||
} // namespace
|
||||
|
||||
// @tag integration
|
||||
Void::Testing::Test submachine_void_result_calls_nullary_on_success()
|
||||
Void::Testing::Test submachine_void_result_calls_success_handler()
|
||||
{
|
||||
Host fsm;
|
||||
const auto outcome = fsm.run_blocking();
|
||||
@@ -134,7 +130,7 @@ Void::Testing::Test submachine_void_result_calls_nullary_on_success()
|
||||
Void::Testing::expect_eq(*outcome, 42);
|
||||
}
|
||||
|
||||
// ── chained startMachine (a Continue state launches another) ─────────────────
|
||||
// ── chained startMachine (a continuation state launches another) ─────────────
|
||||
|
||||
namespace
|
||||
{
|
||||
@@ -145,21 +141,21 @@ namespace
|
||||
using Success = int;
|
||||
|
||||
struct A : State {
|
||||
Task<Step> run() override
|
||||
Task<Step> run()
|
||||
{
|
||||
co_return startMachine<Doubler, B>(3); // 3 -> 6
|
||||
}
|
||||
};
|
||||
struct B : Continue<Doubler> {
|
||||
Task<Step> on_success(int v) override
|
||||
struct B : State {
|
||||
Task<Step> ok(ChildSuccess auto s)
|
||||
{
|
||||
co_return startMachine<Doubler, C>(v); // 6 -> 12
|
||||
co_return startMachine<Doubler, C>(s.value); // 6 -> 12
|
||||
}
|
||||
};
|
||||
struct C : Continue<Doubler> {
|
||||
Task<Step> on_success(int v) override
|
||||
struct C : State {
|
||||
Task<Step> ok(ChildSuccess auto s)
|
||||
{
|
||||
co_return succeed(v);
|
||||
co_return succeed(s.value);
|
||||
}
|
||||
};
|
||||
using States = Fsm::States<A, B, C>;
|
||||
@@ -167,7 +163,7 @@ namespace
|
||||
} // namespace
|
||||
|
||||
// @tag integration
|
||||
Void::Testing::Test submachine_chains_through_continue_states()
|
||||
Void::Testing::Test submachine_chains_through_continuation_states()
|
||||
{
|
||||
Chain fsm;
|
||||
const auto outcome = fsm.run_blocking();
|
||||
@@ -189,7 +185,7 @@ namespace
|
||||
using Success = int;
|
||||
|
||||
struct W : State {
|
||||
Task<Step> run() override
|
||||
Task<Step> run()
|
||||
{
|
||||
co_await await_event<Tick>();
|
||||
co_return succeed(7);
|
||||
@@ -205,15 +201,12 @@ namespace
|
||||
using Success = int;
|
||||
|
||||
struct Begin : State {
|
||||
Task<Step> run() override
|
||||
{
|
||||
co_return startMachine<WaitSub, Fin>();
|
||||
}
|
||||
Task<Step> run() { co_return startMachine<WaitSub, Fin>(); }
|
||||
};
|
||||
struct Fin : Continue<WaitSub> {
|
||||
Task<Step> on_success(int v) override
|
||||
struct Fin : State {
|
||||
Task<Step> ok(ChildSuccess auto s)
|
||||
{
|
||||
co_return succeed(v);
|
||||
co_return succeed(s.value);
|
||||
}
|
||||
};
|
||||
using States = Fsm::States<Begin, Fin>;
|
||||
|
||||
@@ -75,7 +75,7 @@ namespace
|
||||
int times;
|
||||
|
||||
struct Run : State {
|
||||
Task<Step> run() override
|
||||
Task<Step> run()
|
||||
{
|
||||
auto& m = self();
|
||||
int last = 0;
|
||||
@@ -116,7 +116,7 @@ Void::Testing::Test orchestrator_launches_and_supervises()
|
||||
using Success = int;
|
||||
|
||||
struct Run : State {
|
||||
Task<Step> run() override
|
||||
Task<Step> run()
|
||||
{
|
||||
int last = 0;
|
||||
for (int i = 0; i < 5; ++i) {
|
||||
|
||||
Reference in new issue
Block a user