Add async/resilience/reflection primitives + FSM v2 rewrite

A round of new universal capabilities (all generic — templated/reflection
based, no app coupling), verified by the test suite (1103 passing):

Data reflection:
- Reflect.hpp now (de)serializes chrono::duration, chrono::time_point,
  std::variant (tagged), std::array, and non-string-keyed std::map;
  Meta.hpp gains is_time_point_v et al.

Async:
- EventBus gains Mode::Async (worker-thread dispatch + flush()).
- ThreadPool gains a bounded queue, try_submit(), and rejection stats.

New modules / containers:
- Resilience: TokenBucket, KeyedRateLimiter<Key>, CircuitBreaker,
  ResourceMonitor.
- Containers: BufferPool<T> (size-class buffer reuse) and Cache<K,V>
  (per-entry TTL, LRU/LFU/FIFO eviction, hit/miss stats).
- System: process/CPU/memory metrics (Metrics.hpp) and a streaming
  Process API.

Plus FSM v2 (typed Success/Failure, sub-machines, parallel regions,
history states, deferred events), Configuration/Logging reflection
helpers, and the accompanying test suites.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Opus 4.8 committed 2026-06-22 15:45:16 +03:00
1 parent 43b5a81504
commit 80293ee56f
93 files changed
+8500 -3312

No files matched your search

+1 -1
View File
@@ -3,7 +3,7 @@
#include <Void/Async/Executor.hpp>
#include <Void/Async/MpscQueue.hpp>
#include <Void/Async/Task.hpp>
#include <Void/Fsm/Step.hpp>
#include <Void/Fsm/StateKey.hpp>
#include <any>
#include <atomic>
+6 -20
View File
@@ -2,29 +2,21 @@
#include <span>
#include <string>
#include <vector>
namespace Void::Fsm
{
/// A declarable transition edge (from a reactive state's table).
struct EdgeInfo {
std::string event; // event type name, or "(timeout)"
std::string target; // target state, "(success)"/"(fail)"
bool guarded{false};
};
/// A registered state plus the edges that are statically knowable
/// (reactive states only; imperative run()-chosen edges are not).
/// A registered state. Behaviour (and therefore transitions) is chosen
/// imperatively inside each state's entry, so edges are not statically
/// knowable — the description is node-level.
struct StateInfo {
std::string name;
bool reactive{false};
bool initial{false};
std::vector<EdgeInfo> edges;
};
namespace Detail
{
/// Render a state description as a Mermaid `stateDiagram-v2` string.
/// Render a state description as a Mermaid `stateDiagram-v2` string:
/// the initial marker plus one node per registered state.
[[nodiscard]] inline std::string
to_mermaid(std::span<const StateInfo> states)
{
@@ -35,13 +27,7 @@ namespace Void::Fsm
}
}
for (const auto& s : states) {
for (const auto& e : s.edges) {
out += " " + s.name + " --> " + e.target + " : " + e.event;
if (e.guarded) {
out += " [guard]";
}
out += "\n";
}
out += " " + s.name + "\n";
}
return out;
}
-271
View File
@@ -1,271 +0,0 @@
#pragma once
#include <Void/Async/Task.hpp>
#include <Void/Fsm/Detail/Result.hpp>
#include <Void/Fsm/Detail/TypeName.hpp>
#include <Void/Fsm/Step.hpp>
#include <any>
#include <chrono>
#include <functional>
#include <string>
#include <type_traits>
#include <typeinfo>
#include <utility>
#include <vector>
// The declarative transition DSL for reactive states, lifted out of the
// Machine template so the core stays small. Every type is parameterised by the
// owning machine's `Derived` (guards/actions take `Derived&`); the machine's
// typed Success/Failure (nested types, default void) are reflected from
// `Derived` for finish()/fail(). Machine::Reactive aliases these and the engine
// drives them; see include/Void/Fsm/Machine.hpp.
namespace Void::Fsm::Detail
{
namespace Coro = Void::Coro;
/// One declared transition: event type, optional guard/action, the Step to
/// take, plus names for introspection. An `internal` entry runs its action
/// and stays in the state (no exit/enter/transition).
template <typename Derived> struct EventEntry {
const std::type_info* type{nullptr};
std::function<bool(Derived&, const std::any&)> guard;
std::function<Coro::Task<void>(Derived&, const std::any&)> action;
Step step;
bool internal{false};
std::string event_name; // for introspection
std::string target_name; // for introspection
};
/// A reactive state's full transition table (events + an optional timeout,
/// deferred event types, and entry/exit actions).
template <typename Derived> struct TransitionTable {
std::vector<EventEntry<Derived>> events;
bool has_timeout{false};
std::chrono::steady_clock::duration timeout_after{};
Step timeout_step;
std::string timeout_target_name;
// Event types deferred while in this state (held, re-posted on the
// next transition) instead of dropped.
std::vector<const std::type_info*> deferred;
// Entry/exit actions (run by the reactive loop around the state).
std::function<Coro::Task<void>(Derived&)> enter_action;
std::function<Coro::Task<void>(Derived&)> exit_action;
};
/// Fluent builder for one event row: `on.event<E>().guard(..).action(..)
/// .to<S>()` (or `.finish(v)` / `.fail(v)`).
template <typename Derived, typename E> class EventClause
{
public:
explicit EventClause(TransitionTable<Derived>& table)
: m_table(&table)
{
}
EventClause& guard(std::function<bool(Derived&, const E&)> g)
{
m_guard = std::move(g);
return *this;
}
EventClause&
action(std::function<Coro::Task<void>(Derived&, const E&)> a)
{
m_action = std::move(a);
return *this;
}
EventClause& action(std::function<void(Derived&, const E&)> a)
{
m_action = [a = std::move(a)](Derived& d,
const E& e) -> Coro::Task<void> {
a(d, e);
co_return;
};
return *this;
}
template <typename S> void to()
{
if constexpr (requires { typename Derived::States; }) {
static_assert(Derived::States::template contains<S>(),
"to<S>: S is not in this machine's "
"States<...> list");
}
commit(Step::transition(typeid(S)), type_name<S>());
}
void finish()
requires std::is_void_v<SuccessOf<Derived>>
{
commit(Step::success(std::any{}), "(success)");
}
template <typename V>
void finish(V&& value)
requires(!std::is_void_v<SuccessOf<Derived>>)
{
commit(Step::success(std::any{
SuccessOf<Derived>(std::forward<V>(value))}),
"(success)");
}
void fail()
requires std::is_void_v<FailureOf<Derived>>
{
commit(Step::failure(std::any{}), "(fail)");
}
template <typename V>
void fail(V&& value)
requires(!std::is_void_v<FailureOf<Derived>>)
{
commit(Step::failure(std::any{
FailureOf<Derived>{std::forward<V>(value)}}),
"(fail)");
}
/// Internal transition: run `fn` on the event but stay in the
/// state (no exit/enter, no transition).
void internal(std::function<void(Derived&, const E&)> fn)
{
action(std::move(fn));
commit(Step::success(std::any{}), "(internal)", true);
}
private:
void commit(Step step, std::string target, bool is_internal = false)
{
EventEntry<Derived> entry;
entry.type = &typeid(E);
if (m_guard) {
entry.guard = [g = std::move(m_guard)](Derived& d,
const std::any& a) {
return g(d, std::any_cast<const E&>(a));
};
}
if (m_action) {
entry.action =
[a = std::move(m_action)](
Derived& d,
const std::any& any) -> Coro::Task<void> {
co_await a(d, std::any_cast<const E&>(any));
};
}
entry.step = std::move(step);
entry.internal = is_internal;
entry.event_name = type_name<E>();
entry.target_name = std::move(target);
m_table->events.push_back(std::move(entry));
}
TransitionTable<Derived>* m_table;
std::function<bool(Derived&, const E&)> m_guard;
std::function<Coro::Task<void>(Derived&, const E&)> m_action;
};
/// Fluent builder for the timeout row: `on.after(d).to<S>()` / `.fail(v)`.
template <typename Derived> class AfterClause
{
public:
AfterClause(TransitionTable<Derived>& table,
std::chrono::steady_clock::duration after)
: m_table(&table), m_after(after)
{
}
template <typename S> void to()
{
if constexpr (requires { typename Derived::States; }) {
static_assert(Derived::States::template contains<S>(),
"after().to<S>: S not in States<...>");
}
m_table->has_timeout = true;
m_table->timeout_after = m_after;
m_table->timeout_step = Step::transition(typeid(S));
m_table->timeout_target_name = type_name<S>();
}
void fail()
requires std::is_void_v<FailureOf<Derived>>
{
m_table->has_timeout = true;
m_table->timeout_after = m_after;
m_table->timeout_step = Step::failure(std::any{});
m_table->timeout_target_name = "(fail)";
}
template <typename V>
void fail(V&& value)
requires(!std::is_void_v<FailureOf<Derived>>)
{
m_table->has_timeout = true;
m_table->timeout_after = m_after;
m_table->timeout_step = Step::failure(
std::any{FailureOf<Derived>{std::forward<V>(value)}});
m_table->timeout_target_name = "(fail)";
}
private:
TransitionTable<Derived>* m_table;
std::chrono::steady_clock::duration m_after;
};
/// Entry point handed to `transitions(TransitionBuilder& on)`.
template <typename Derived> class TransitionBuilder
{
public:
explicit TransitionBuilder(TransitionTable<Derived>& table)
: m_table(&table)
{
}
template <typename E> [[nodiscard]] EventClause<Derived, E> event()
{
return EventClause<Derived, E>{*m_table};
}
template <typename Rep, typename Period>
[[nodiscard]] AfterClause<Derived>
after(std::chrono::duration<Rep, Period> d)
{
return AfterClause<Derived>{
*m_table, std::chrono::duration_cast<
std::chrono::steady_clock::duration>(d)};
}
/// Defer event `E` while in this state: hold it (don't drop) and
/// re-post it after the next transition (UML deferred events).
template <typename E> void defer()
{
m_table->deferred.push_back(&typeid(E));
}
/// Entry action — run when the state is entered (before it waits).
void enter(std::function<void(Derived&)> fn)
{
m_table->enter_action =
[fn = std::move(fn)](Derived& d) -> Coro::Task<void> {
fn(d);
co_return;
};
}
/// Exit action — run when the state is left (on any transition).
void exit(std::function<void(Derived&)> fn)
{
m_table->exit_action =
[fn = std::move(fn)](Derived& d) -> Coro::Task<void> {
fn(d);
co_return;
};
}
private:
TransitionTable<Derived>* m_table;
};
} // namespace Void::Fsm::Detail
+109 -210
View File
@@ -1,10 +1,12 @@
#pragma once
#include <Void/Async/Task.hpp>
#include <Void/Core/Meta.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 <Void/Fsm/Detail/StateList.hpp>
#include <Void/Fsm/Machine.hpp>
#include <Void/Fsm/StateKey.hpp>
#include <algorithm>
#include <any>
@@ -23,122 +25,137 @@
// 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
// - entry : a member returning State / Coro::Task<StateKey>>, 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)
// - result handlers (continuation): members taking `ChildSuccess` /
// `ChildFailure` (the type-erased result structs below)
// All discovery is invocability-based (types known at the generation site), so
// no parameter-type reflection (P3096) is required.
// no parameter-type reflection (P3096) is required. Event handling is
// imperative inside an entry (co_await await_event<E>()), so there is no
// reactive role.
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> {
/// handler written `ok(ChildSuccess s)`. The sub's typed Success is read
/// with `s.as<T>()` (the value is empty for a void-result sub).
struct ChildSuccess {
std::any value;
template <typename T> [[nodiscard]] T as() const
{
return std::any_cast<T>(value);
}
};
/// 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> {
/// The failure value of a launched sub-machine, handed to `no(ChildFailure
/// f)`. The sub's typed Failure is read with `f.as<T>()` (empty for void).
struct ChildFailure {
std::any value;
template <typename T> [[nodiscard]] T as() const
{
return std::any_cast<T>(value);
}
};
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>>;
/// Marker to designate a state's entry when several members match the entry
/// signature: annotate the chosen one `[[= Void::Fsm::entry]]`. Unmarked,
/// the first-declared matching member is used.
inline constexpr struct EntryTag {
} entry;
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())>;
// InitialStateOf / FirstStateOf live in Detail/StateList.hpp (they
// reflect the nested `struct States { … }`).
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()
/// True if member `m` carries the `[[= Void::Fsm::entry]]` annotation.
/// Routed through the shared Void::Meta annotation helper.
consteval bool is_entry_marked(meta::info m)
{
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>{};
}
return Void::Meta::has_annotation<EntryTag>(m);
}
template <typename M>
using InitialStateOf =
typename decltype(initial_state_probe<M>())::type;
/// Wrap a ready Step in a Task. (The reflection selectors below must
/// Wrap a ready State 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; }
inline Coro::Task<StateKey> ready_task(StateKey s) { co_return s; }
// ── entry (0-arg member returning Step / Task<Step>) ──────────────
template <typename S> Coro::Task<Step> invoke_entry(S& s)
// ── entry (0-arg member returning StateKey / Task<StateKey>) ──────
// When several members match, one annotated `[[= Fsm::entry]]` wins;
// otherwise the first-declared match is used.
template <typename S> Coro::Task<StateKey> invoke_entry(S& s)
{
static constexpr auto members = std::define_static_array(
meta::members_of(^^S, meta::access_context::current()));
// Pass 1: a member annotated [[= Fsm::entry]] takes precedence.
template for (constexpr auto m : members)
{
if constexpr (requires(S& x) { x.[:m:](); }) {
if constexpr (is_entry_marked(m) &&
requires(S& x) { x.[:m:](); }) {
using R = decltype(std::declval<S&>().[:m:]());
if constexpr (std::is_same_v<R, Step>) {
if constexpr (std::is_same_v<R, StateKey>) {
return ready_task(s.[:m:]());
} else if constexpr (std::is_same_v<R, Coro::Task<Step>>) {
} else if constexpr (std::is_same_v<R,
Coro::Task<StateKey>>) {
return s.[:m:]();
}
}
}
return ready_task(Step::fault(FsmError{
"state has no entry (a no-arg method returning Step)"}));
// Pass 2: the first-declared matching member.
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, StateKey>) {
return ready_task(s.[:m:]());
} else if constexpr (std::is_same_v<R,
Coro::Task<StateKey>>) {
return s.[:m:]();
}
}
}
return ready_task(StateKey::fault(FsmError{
"state has no entry (a no-arg method returning StateKey)"}));
}
// ── startup-entry (member taking the startup-data argument[s]) ────
// Same precedence as invoke_entry: an annotated `[[= Fsm::entry]]`
// data-taking member wins, else the first-declared one; if none takes
// the data, fall back to the plain (nullary) entry.
template <typename S, typename... DataT>
Coro::Task<Step> invoke_startup(S& s, DataT... data)
Coro::Task<StateKey> invoke_startup(S& s, DataT... data)
{
static constexpr auto members = std::define_static_array(
meta::members_of(^^S, meta::access_context::current()));
// Pass 1: an annotated data-taking member takes precedence.
template for (constexpr auto m : members)
{
if constexpr (is_entry_marked(m) &&
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, StateKey>) {
return ready_task(s.[:m:](std::move(data)...));
} else if constexpr (std::is_same_v<R,
Coro::Task<StateKey>>) {
return s.[:m:](std::move(data)...);
}
}
}
// Pass 2: the first-declared data-taking member.
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>) {
if constexpr (std::is_same_v<R, StateKey>) {
return ready_task(s.[:m:](std::move(data)...));
} else if constexpr (std::is_same_v<R, Coro::Task<Step>>) {
} else if constexpr (std::is_same_v<R,
Coro::Task<StateKey>>) {
return s.[:m:](std::move(data)...);
}
}
@@ -149,7 +166,7 @@ namespace Void::Fsm
// ── continuation handler (member taking a ChildSuccess/Failure box)
template <typename S, typename Box>
Coro::Task<Step> invoke_handler(S& s, Box box)
Coro::Task<StateKey> invoke_handler(S& s, Box box)
{
static constexpr auto members = std::define_static_array(
meta::members_of(^^S, meta::access_context::current()));
@@ -158,161 +175,43 @@ namespace Void::Fsm
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>) {
if constexpr (std::is_same_v<R, StateKey>) {
return ready_task(s.[:m:](std::move(box)));
} else if constexpr (std::is_same_v<R, Coro::Task<Step>>) {
} else if constexpr (std::is_same_v<R,
Coro::Task<StateKey>>) {
return s.[:m:](std::move(box));
}
}
}
return ready_task(Step::fault(
return ready_task(StateKey::fault(
FsmError{"continuation has no handler for this sub-machine "
"result (ChildSuccess auto / ChildFailure auto)"}));
"result (ChildSuccess / ChildFailure)"}));
}
/// 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.
/// signature-matched handler (`ok(ChildSuccess)` / `no(ChildFailure)`).
/// The typed payload rides type-erased in the result struct's `value`;
/// the handler reads it with `.as<T>()`. (Sub is retained in the
/// signature so the call site stays `dispatch_result<Next, Sub>`.)
template <typename Next, typename Sub>
Coro::Task<Step> dispatch_result(Next& s, LaunchResult lr)
Coro::Task<StateKey> 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));
return invoke_handler(s, ChildFailure{std::move(lr.failure)});
}
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));
return invoke_handler(s, ChildSuccess{std::move(lr.value)});
}
// ── 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);
// Await the declared event types *and* the deferred ones (so a
// deferred event wakes us to be held, not dropped).
std::vector<const std::type_info*> types;
types.reserve(table.events.size() + table.deferred.size());
for (const auto& e : table.events) {
types.push_back(e.type);
}
for (const auto* dt : table.deferred) {
types.push_back(dt);
}
D& d = s.self();
if (table.enter_action) {
co_await table.enter_action(d);
}
// Events deferred while here, re-posted on exit.
std::vector<EventEnvelope> held;
auto leave = [&](Step step) -> Coro::Task<Step> {
if (table.exit_action) {
co_await table.exit_action(d);
}
for (auto& h : held) {
s.machine().repost(std::move(h));
}
co_return std::move(step);
};
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 co_await leave(std::move(table.timeout_step));
}
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);
}
matched = true;
if (!e.internal) {
co_return co_await leave(std::move(e.step));
}
break; // internal: handled, stay in the state
}
if (!matched) {
// No entry took it: hold if deferred, else drop.
const bool is_deferred = std::any_of(
table.deferred.begin(), table.deferred.end(),
[&](const std::type_info* t) {
return *t == *ev->type;
});
if (is_deferred) {
held.push_back(std::move(*ev));
}
}
}
}
/// Per-state driver thunk built at registration (S is complete):
/// reactive states run the table, others run the entry.
/// Per-state driver thunk built at registration (S is complete): run
/// the state's entry. Event handling, timeouts, guards and deferral are
/// all expressed imperatively inside the entry (await_event / await_any
/// / await_event_for / delay), so there is no separate reactive driver.
template <typename S>
[[nodiscard]] std::function<Coro::Task<Step>(StateBase&)> make_driver()
[[nodiscard]] std::function<Coro::Task<StateKey>(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);
}
return [](StateBase& base) -> Coro::Task<StateKey> {
co_return co_await invoke_entry(static_cast<S&>(base));
};
}
} // namespace Detail
+102
View File
@@ -0,0 +1,102 @@
#pragma once
#include <Void/Fsm/Detail/Engine.hpp>
#include <concepts>
#include <meta>
#include <type_traits>
// State-list reflection helpers. A machine declares its states as a nested
// struct of forward declarations:
// struct States { struct Idle; struct Run; struct Done; };
// defined out-of-line in the .cpp, and the Machine base auto-registers them by
// reflecting `members_of(^^States)` — the first nested state is the initial one
// unless the machine declares `using Initial = S;`. These helpers replace the
// old `Fsm::States<Ss...>` template: the list is now an ordinary struct whose
// nested state types are enumerated via P2996 (already a hard dependency of the
// module — see Detail/Roles.hpp).
namespace Void::Fsm::Detail
{
namespace meta = std::meta;
/// True if reflection `m` names a nested type that is one of this machine's
/// states (a class deriving StateBase) — filters out the
/// injected-class-name and any non-state members.
template <meta::info M> consteval bool is_state_member()
{
if constexpr (meta::is_type(M)) {
using S = typename[:M:];
return std::is_class_v<S> && std::derived_from<S, StateBase>;
} else {
return false;
}
}
/// Reflection of the first state member of `StatesT` (declaration order),
/// or
/// `^^void` when the list has none.
template <typename StatesT> consteval meta::info first_state_member()
{
template for (constexpr auto m :
std::define_static_array(meta::members_of(
^^StatesT, meta::access_context::current())))
{
if constexpr (is_state_member<m>()) {
return m;
}
}
return ^^void;
}
/// The first declared state type of `StatesT` (void if empty).
template <typename StatesT>
using FirstStateOf = typename[:first_state_member<StatesT>():];
/// A machine's initial state type: its nested `Initial` if declared, else
/// the first member of its `States` list.
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<FirstStateOf<typename M::States>>{};
}
}
template <typename M>
using InitialStateOf = typename decltype(initial_state_probe<M>())::type;
/// Compile-time membership test: is `S` one of `StatesT`'s state members?
/// Drives the next<S>() / startMachine<,Next>() target validation.
template <typename StatesT, typename S> consteval bool states_contains()
{
bool found = false;
template for (constexpr auto m :
std::define_static_array(meta::members_of(
^^StatesT, meta::access_context::current())))
{
if constexpr (is_state_member<m>()) {
if constexpr (std::is_same_v<typename[:m:], S>) {
found = true;
}
}
}
return found;
}
/// Register every state member of `StatesT` on `machine` (declaration order
/// = registration order). Instantiated from the derived machine's .cpp
/// constructor, where the out-of-line state definitions are complete.
template <typename StatesT, typename M>
void register_states_from(M& machine)
{
template for (constexpr auto m :
std::define_static_array(meta::members_of(
^^StatesT, meta::access_context::current())))
{
if constexpr (is_state_member<m>()) {
machine.template add<typename[:m:]>();
}
}
}
} // namespace Void::Fsm::Detail
+7 -6
View File
@@ -2,13 +2,14 @@
// Umbrella header for the FSM module. The implementation is split for
// maintainability:
// - Machine.hpp — the Machine<Derived, ResultT> template + States
// list, nested State / Reactive bases, lifecycle,
// events, nesting, persistence.
// - Detail/Reactive.hpp — the declarative transition DSL
// (TransitionBuilder / EventClause / AfterClause).
// - Machine.hpp — the Machine<Derived> template, the nested State
// base, lifecycle, events, nesting, persistence.
// - Detail/StateList.hpp — reflection over the nested `struct States { … }`
// (auto-registration, initial-state, membership).
// - Detail/Roles.hpp — signature-inferred state roles (entry,
// startup-entry, continuation handlers).
// - Detail/Awaiter.hpp — the unified event awaiter.
// - Detail/Introspect.hpp — StateInfo / EdgeInfo + to_mermaid.
// - Detail/Introspect.hpp — StateInfo + to_mermaid (node-level diagram).
// - Detail/Engine.{hpp,cpp} — the non-template execution context.
// Include <Void/Fsm/Fsm.hpp> to get the whole machine API as before.
+112 -151
View File
@@ -6,11 +6,11 @@
#include <Void/Fsm/Detail/Awaiter.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/StateList.hpp>
#include <Void/Fsm/Detail/TypeName.hpp>
#include <Void/Fsm/Step.hpp>
#include <Void/Fsm/StateKey.hpp>
#include <Void/Log/Log.hpp>
#include <Void/Service/Registry.hpp>
@@ -43,20 +43,6 @@
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 {
@@ -76,25 +62,33 @@ namespace Void::Fsm
// ── Machine<Derived> ──────────────────────────────────────────────────
//
// 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).
// Inheritance + coroutine workflow FSM, CRTP for typed access. Derive it
// and declare the states as a nested struct of forward declarations:
// struct States { struct FirstState; struct SecondState; … };
// defined out-of-line (typically in a .cpp), each deriving the single
// `State`. The Machine base auto-registers them by reflecting `States`
// (Detail/StateList.hpp) — the first declared state is the initial one
// unless `using Initial = S;`. All behaviour lives inside a state: the
// engine infers each state's role from its member signatures (entry /
// startup-entry / continuation handlers); states reach their machine (data
// + sub-methods) via self(). Events are handled imperatively inside an
// entry (co_await await_event<E>()) — there is no declarative transition
// table. Result types are the nested `Success`/`Failure` (default void).
//
// // header
// class Login : public Void::Fsm::Machine<Login> {
// public:
// using Success = Token;
// int attempts = 0;
// 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>();
// }
// };
// using States = Void::Fsm::States<Check>;
// struct States { struct Check; };
// };
// // source (namespace scope)
// struct Login::States::Check : Login::State { // entry by signature
// Coro::Task<StateKey>> run() {
// if (++self().attempts > 3) co_return fail();
// co_return self().service<IAuth>().ok() ? succeed(Token{})
// : next<Check>();
// }
// };
template <typename Derived> class Machine
{
@@ -135,43 +129,44 @@ namespace Void::Fsm
protected:
/// Transition to another state. Validated at compile
/// time when the machine declares `using States`.
template <typename S> [[nodiscard]] Step next() const
/// time when the machine declares a `States` list.
template <typename S> [[nodiscard]] StateKey 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");
static_assert(Detail::states_contains<
typename Derived::States, S>(),
"next<S>: S is not in this machine's "
"States { … } list");
}
return Step::transition(typeid(S));
return StateKey::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
[[nodiscard]] StateKey next_dynamic() const
{
return Step::transition(typeid(S));
return StateKey::transition(typeid(S));
}
/// Free jump to any registered state — no declared
/// transition required ("each state can be moved to
/// another state"). Like next_dynamic, skips the
/// States<...> compile-time check; runtime-fails only if S
/// States{ … } compile-time check; runtime-fails only if S
/// was never registered.
template <typename S> [[nodiscard]] Step goto_state() const
template <typename S>
[[nodiscard]] StateKey goto_state() const
{
return Step::transition(typeid(S));
return StateKey::transition(typeid(S));
}
/// Route to a fallback state if `step` is a failure,
/// otherwise pass it through — for error policies:
/// co_return next_or<Recovery>(co_await try_work());
template <typename S>
[[nodiscard]] Step next_or(Step step) const
[[nodiscard]] StateKey next_or(StateKey step) const
{
if (step.kind() == Step::Kind::Fail) {
if (step.kind() == StateKey::Kind::Fail) {
return next<S>();
}
return step;
@@ -209,32 +204,32 @@ namespace Void::Fsm
/// Finish with the machine's typed Success result (nested
/// `Success`; nullary when it is void).
[[nodiscard]] Step succeed() const
[[nodiscard]] StateKey succeed() const
requires std::is_void_v<Detail::SuccessOf<Derived>>
{
return Step::success(std::any{});
return StateKey::success(std::any{});
}
template <typename V>
[[nodiscard]] Step succeed(V&& value) const
[[nodiscard]] StateKey succeed(V&& value) const
requires(!std::is_void_v<Detail::SuccessOf<Derived>>)
{
return Step::success(
return StateKey::success(
std::any{Detail::SuccessOf<Derived>(
std::forward<V>(value))});
}
/// Finish with the machine's typed Failure result (nested
/// `Failure`; nullary when it is void).
[[nodiscard]] Step fail() const
[[nodiscard]] StateKey fail() const
requires std::is_void_v<Detail::FailureOf<Derived>>
{
return Step::failure(std::any{});
return StateKey::failure(std::any{});
}
template <typename V>
[[nodiscard]] Step fail(V&& value) const
[[nodiscard]] StateKey fail(V&& value) const
requires(!std::is_void_v<Detail::FailureOf<Derived>>)
{
return Step::failure(
return StateKey::failure(
std::any{Detail::FailureOf<Derived>{
std::forward<V>(value)}});
}
@@ -311,11 +306,11 @@ namespace Void::Fsm
/// 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):
/// -matched handler — a member taking `ChildSuccess`
/// (Sub succeeded) or `ChildFailure` (Sub failed):
/// co_return startMachine<Login, AfterLogin>(seed);
template <typename Sub, typename Next, typename... Args>
[[nodiscard]] Step startMachine(Args&&... args) const
[[nodiscard]] StateKey startMachine(Args&&... args) const
{
return m_machine->template start_machine<Sub, Next>(
std::forward<Args>(args)...);
@@ -337,37 +332,35 @@ namespace Void::Fsm
// 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>,
// - entry : a member returning
// State/Coro::Task<StateKey>>,
// 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>()`).
// - continuation : members taking `ChildSuccess` /
// `ChildFailure` (the sub's typed result, read
// via .as<T>(), after `startMachine<Sub,
// This>`).
//
// struct Idle : State { // reactive
// void transitions(TransitionBuilder& on) {
// on.event<Go>().to<Running>();
// on.after(5s).to<TimedOut>(); } };
// Events are handled imperatively inside an entry:
// struct Idle : State { // entry
// Coro::Task<StateKey> run() {
// auto e = co_await await_any<Go, Stop>();
// co_return std::holds_alternative<Go>(e) ? next<Running>()
// : next<Done>(); }
// };
// struct After : State { // continuation
// Coro::Task<Step> ok(ChildSuccess auto s){ ... }
// Coro::Task<Step> no(ChildFailure auto f){ ... } };
//
// 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>;
// Coro::Task<StateKey> ok(ChildSuccess s){ ... }
// Coro::Task<StateKey> no(ChildFailure f){ ... } };
// ── construction ──────────────────────────────────────────────
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{});
Detail::register_states_from<typename Derived::States>(
*this);
using Init = Detail::InitialStateOf<Derived>;
if constexpr (!std::is_void_v<Init>) {
m_initial = &typeid(Init);
}
}
}
@@ -397,20 +390,8 @@ namespace Void::Fsm
s->m_machine = this;
return s;
});
// Signature-inferred driver thunk (entry or reactive table).
// Signature-inferred driver thunk (runs the state's entry).
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()
@@ -459,7 +440,6 @@ namespace Void::Fsm
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) {
@@ -973,12 +953,13 @@ namespace Void::Fsm
/// machine's shared executor, then enter `Next` carrying Sub's
/// outcome as a LaunchResult. Reached via State::startMachine.
template <typename Sub, typename Next, typename... Args>
[[nodiscard]] Step start_machine(Args&&... args)
[[nodiscard]] StateKey start_machine(Args&&... args)
{
if constexpr (requires { typename Derived::States; }) {
static_assert(
Derived::States::template contains<Next>(),
"startMachine<Sub, Next>: Next is not in States<...>");
Detail::states_contains<typename Derived::States,
Next>(),
"startMachine<Sub, Next>: Next is not in States { … }");
}
using Init = Detail::InitialStateOf<Sub>;
auto launcher =
@@ -993,7 +974,7 @@ namespace Void::Fsm
child.m_startup_injector =
[... d = std::move(data)](
Detail::StateBase& base) mutable
-> Coro::Task<Step> {
-> Coro::Task<StateKey> {
return Detail::invoke_startup<Init>(
static_cast<Init&>(base), std::move(d)...);
};
@@ -1017,14 +998,14 @@ namespace Void::Fsm
}
co_return lr;
};
Step::Dispatch dispatch =
StateKey::Dispatch dispatch =
[](Detail::StateBase& base,
LaunchResult lr) -> Coro::Task<Step> {
LaunchResult lr) -> Coro::Task<StateKey> {
return Detail::dispatch_result<Next, Sub>(
static_cast<Next&>(base), std::move(lr));
};
return Step::launch(typeid(Next), std::move(launcher),
std::move(dispatch));
return StateKey::launch(typeid(Next), std::move(launcher),
std::move(dispatch));
}
// ── observation ───────────────────────────────────────────────
@@ -1066,12 +1047,12 @@ namespace Void::Fsm
}
// ── introspection / diagram ───────────────────────────────────
// EdgeInfo / StateInfo are namespace-scope (Detail/Introspect.hpp).
// StateInfo is namespace-scope (Detail/Introspect.hpp).
/// Structural description: every registered state plus the
/// transitions declared by reactive states (imperative states'
/// run()-chosen transitions are not statically knowable, so
/// they appear as nodes without edges).
/// Structural description: every registered state (name + whether
/// it is the initial state). Transitions are chosen imperatively
/// inside each state's entry, so they are not statically knowable —
/// the description is node-level (no edges).
[[nodiscard]] std::vector<StateInfo> describe()
{
std::vector<StateInfo> out;
@@ -1082,22 +1063,6 @@ namespace Void::Fsm
StateInfo si;
si.name = name;
si.initial = (name == initial_name);
const auto* ti = m_name_to_type.at(name);
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,
static_cast<bool>(e.guard)});
}
if (table.has_timeout) {
si.edges.push_back(EdgeInfo{
"(timeout)", table.timeout_target_name, false});
}
}
out.push_back(std::move(si));
}
return out;
@@ -1151,6 +1116,15 @@ namespace Void::Fsm
virtual void on_serialize(Json::Value& /*data*/) const {}
virtual void on_restore(const Json::Value& /*data*/) {}
/// Machine-level entry/exit hooks (default no-ops; override for
/// machine-wide setup/teardown). `on_machine_enter()` runs once
/// before the initial state is entered; `on_machine_exit()` runs
/// once when the machine reaches a terminal outcome (Success,
/// Failure, or a system Fault). Per-state entry/exit lives on the
/// state itself (State::on_enter()/on_exit()).
virtual void on_machine_enter() {}
virtual void on_machine_exit() {}
/// Called on every transition (and the initial entry). Default
/// logs at debug; override for custom observability.
virtual void on_transition(std::string_view from,
@@ -1176,21 +1150,6 @@ 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
@@ -1261,6 +1220,7 @@ namespace Void::Fsm
fault("no initial state");
co_return;
}
on_machine_enter();
bool first = true;
for (;;) {
// Apply an external jump<S>() at this transition boundary.
@@ -1274,6 +1234,7 @@ namespace Void::Fsm
const auto it = m_factories.find(std::type_index{*cur});
if (it == m_factories.end()) {
fault("transition to unregistered state");
on_machine_exit();
co_return;
}
set_current(cur);
@@ -1282,7 +1243,7 @@ namespace Void::Fsm
// 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;
StateKey step;
if (m_pending_dispatch) {
LaunchResult pending = std::move(*m_pending_result);
auto dispatch = std::move(m_pending_dispatch);
@@ -1290,6 +1251,7 @@ namespace Void::Fsm
m_pending_dispatch = nullptr;
if (pending.kind == LaunchResult::Kind::Fault) {
fault(std::move(pending.fault.message));
on_machine_exit();
co_return;
}
step = co_await dispatch(*state, std::move(pending));
@@ -1305,28 +1267,31 @@ namespace Void::Fsm
co_await state->on_exit();
fire_after(current_state());
switch (step.kind()) {
case Step::Kind::Transition:
case StateKey::Kind::Transition:
cur = step.target();
continue;
case Step::Kind::Launch:
case StateKey::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:
case StateKey::Kind::Success:
m_result_value = std::move(step.payload());
m_status.store(Status::Succeeded,
std::memory_order_release);
on_machine_exit();
co_return;
case Step::Kind::Fail:
case StateKey::Kind::Fail:
m_result_value = std::move(step.payload());
m_status.store(Status::Failed,
std::memory_order_release);
on_machine_exit();
co_return;
case Step::Kind::Fault:
case StateKey::Kind::Fault:
fault(std::any_cast<FsmError>(step.payload())
.message);
on_machine_exit();
co_return;
}
}
@@ -1385,15 +1350,11 @@ 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).
// Per-state signature-inferred driver thunk (runs the entry).
std::unordered_map<
std::type_index,
std::function<bool(Detail::StateBase&, TransitionTable&)>>
m_collectors;
std::function<Coro::Task<StateKey>(Detail::StateBase&)>>
m_drivers;
std::unordered_map<std::type_index, int> m_index;
std::vector<std::string> m_names;
std::unordered_map<std::string, const std::type_info*>
@@ -1421,11 +1382,11 @@ namespace Void::Fsm
// Set by a Launch step's sub-machine result; consumed by the next
// state via the bound dispatcher below.
std::optional<LaunchResult> m_pending_result;
Step::Dispatch m_pending_dispatch;
StateKey::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&)>
std::function<Coro::Task<StateKey>(Detail::StateBase&)>
m_startup_injector;
// External jump request (jump<S>()); applied by drive() at the
@@ -1437,5 +1398,5 @@ namespace Void::Fsm
// suspended frame chain of a machine parked on an event.
std::optional<Coro::Task<void>> m_driver;
};
template <typename Derived> using State = Machine<Derived>::State;
} // namespace Void::Fsm
+1 -1
View File
@@ -1,6 +1,6 @@
#pragma once
#include <Void/Fsm/Step.hpp>
#include <Void/Fsm/StateKey.hpp>
#include <Void/Service/Registry.hpp>
#include <cstddef>
@@ -46,15 +46,16 @@ namespace Void::Fsm
/// What a state's entry returns: move to another state, finish with a typed
/// Success / Failure, or launch a sub-machine. Built only through the State
/// helpers (next<S>() / succeed(...) / fail(...) / startMachine).
class Step
class StateKey
{
public:
enum class Kind { Transition, Success, Fail, Launch, Fault };
[[nodiscard]] static Step transition(const std::type_info& target)
[[nodiscard]] static StateKey
transition(const std::type_info& target)
{
Step s;
StateKey s;
s.m_kind = Kind::Transition;
s.m_target = &target;
return s;
@@ -62,9 +63,9 @@ namespace Void::Fsm
/// Signal a system fault (programming error) — distinct from a
/// typed Failure. Routed to Machine::system_error().
[[nodiscard]] static Step fault(FsmError error)
[[nodiscard]] static StateKey fault(FsmError error)
{
Step s;
StateKey s;
s.m_kind = Kind::Fault;
s.m_payload = std::any{std::move(error)};
return s;
@@ -72,17 +73,17 @@ namespace Void::Fsm
/// 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)>;
using Dispatch = std::function<Coro::Task<StateKey>(
Detail::StateBase&, LaunchResult)>;
/// Launch a sub-machine, then enter `target` (a continuation state)
/// with the sub's LaunchResult, dispatched via `dispatch`.
[[nodiscard]] static Step
[[nodiscard]] static StateKey
launch(const std::type_info& target,
std::function<Coro::Task<LaunchResult>()> launcher,
Dispatch dispatch)
{
Step s;
StateKey s;
s.m_kind = Kind::Launch;
s.m_target = &target;
s.m_launcher = std::move(launcher);
@@ -91,18 +92,18 @@ namespace Void::Fsm
}
/// Finish with a typed Success payload (empty std::any for void).
[[nodiscard]] static Step success(std::any value)
[[nodiscard]] static StateKey success(std::any value)
{
Step s;
StateKey s;
s.m_kind = Kind::Success;
s.m_payload = std::move(value);
return s;
}
/// Finish with a typed Failure payload (empty std::any for void).
[[nodiscard]] static Step failure(std::any value)
[[nodiscard]] static StateKey failure(std::any value)
{
Step s;
StateKey s;
s.m_kind = Kind::Fail;
s.m_payload = std::move(value);
return s;