FSM refactor (1): split the Fsm.hpp monolith into focused headers
Fsm.hpp had grown to ~1200 lines holding everything. Split it behind the
same <Void/Fsm/Fsm.hpp> umbrella (which now just includes Machine.hpp), with
no behaviour change:
- Machine.hpp — the Machine<Derived,ResultT> template: States list, nested
State/Reactive bases, lifecycle, events, nesting, persistence.
- Detail/Reactive.hpp — the declarative transition DSL lifted to standalone
templates (TransitionTable/EventEntry/EventClause/AfterClause/
TransitionBuilder parameterised by Derived/ResultT); Machine::Reactive
aliases TransitionTable/TransitionBuilder.
- Detail/Awaiter.hpp — one EventAwaiter built on
ExecutionContext::{try_take_any,set_waiter}; the four near-identical inline
awaiters (await_event / await_event_for / await_any / await_any_event)
collapse to make_event_awaiter wrappers with per-call projections.
- Detail/Introspect.hpp — namespace-scope StateInfo/EdgeInfo + free
to_mermaid(span<StateInfo>); describe() returns the shared structs,
to_mermaid() delegates.
- Detail/TypeName.hpp — shared Detail::type_name<T>() (P2996 identifier_of,
typeid fallback), replacing the per-class state_type_name helper.
982 green, ASan clean, -Werror Fsm build clean. No test changes needed.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
667045564e
commit
fedc14b0e3
6 files changed
+1269
-1194
No files matched your search
@@ -0,0 +1,58 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Void/Fsm/Detail/Engine.hpp>
|
||||||
|
|
||||||
|
#include <chrono>
|
||||||
|
#include <coroutine>
|
||||||
|
#include <optional>
|
||||||
|
#include <span>
|
||||||
|
#include <typeinfo>
|
||||||
|
#include <utility>
|
||||||
|
|
||||||
|
namespace Void::Fsm::Detail
|
||||||
|
{
|
||||||
|
/// One awaiter for every "wait for an event (optionally with a deadline)"
|
||||||
|
/// operation on a machine. `Storage` is the type-list container (a
|
||||||
|
/// std::array for fixed sets, a std::vector for dynamic ones); `Resume` is
|
||||||
|
/// the projection `(EventEnvelope&&, bool timed_out) -> R` that shapes the
|
||||||
|
/// awaited value (the matched event, an optional on timeout, a variant,
|
||||||
|
/// …). Built on ExecutionContext::{try_take_any,set_waiter}.
|
||||||
|
template <typename Storage, typename Resume> struct EventAwaiter {
|
||||||
|
ExecutionContext* ctx;
|
||||||
|
Storage types;
|
||||||
|
EventEnvelope env;
|
||||||
|
bool timed_out{false};
|
||||||
|
std::optional<std::chrono::steady_clock::time_point> deadline;
|
||||||
|
Resume resume;
|
||||||
|
|
||||||
|
[[nodiscard]] bool await_ready()
|
||||||
|
{
|
||||||
|
return ctx->try_take_any(span(), env);
|
||||||
|
}
|
||||||
|
void await_suspend(std::coroutine_handle<> h)
|
||||||
|
{
|
||||||
|
ctx->set_waiter(span(), h, &env, &timed_out, deadline);
|
||||||
|
}
|
||||||
|
[[nodiscard]] decltype(auto) await_resume()
|
||||||
|
{
|
||||||
|
return resume(std::move(env), timed_out);
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
[[nodiscard]] std::span<const std::type_info* const> span() const
|
||||||
|
{
|
||||||
|
return std::span<const std::type_info* const>{types};
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
template <typename Storage, typename Resume>
|
||||||
|
[[nodiscard]] auto make_event_awaiter(
|
||||||
|
ExecutionContext* ctx, Storage types,
|
||||||
|
std::optional<std::chrono::steady_clock::time_point> deadline,
|
||||||
|
Resume resume)
|
||||||
|
{
|
||||||
|
return EventAwaiter<Storage, Resume>{
|
||||||
|
ctx, std::move(types), {}, false, deadline, std::move(resume)};
|
||||||
|
}
|
||||||
|
} // namespace Void::Fsm::Detail
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#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).
|
||||||
|
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.
|
||||||
|
[[nodiscard]] inline std::string
|
||||||
|
to_mermaid(std::span<const StateInfo> states)
|
||||||
|
{
|
||||||
|
std::string out = "stateDiagram-v2\n";
|
||||||
|
for (const auto& s : states) {
|
||||||
|
if (s.initial) {
|
||||||
|
out += " [*] --> " + s.name + "\n";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
} // namespace Detail
|
||||||
|
} // namespace Void::Fsm
|
||||||
@@ -0,0 +1,206 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Void/Async/Task.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&`) and `ResultT`
|
||||||
|
// (finish() carries the machine's result). 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.
|
||||||
|
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;
|
||||||
|
std::string event_name; // for introspection
|
||||||
|
std::string target_name; // for introspection
|
||||||
|
};
|
||||||
|
|
||||||
|
/// A reactive state's full transition table (events + an optional timeout).
|
||||||
|
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;
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Fluent builder for one event row: `on.event<E>().guard(..).action(..)
|
||||||
|
/// .to<S>()` (or `.finish(v)` / `.fail(msg)`).
|
||||||
|
template <typename Derived, typename ResultT, 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<ResultT>
|
||||||
|
{
|
||||||
|
commit(Step::success(std::any{}), "(success)");
|
||||||
|
}
|
||||||
|
template <typename V>
|
||||||
|
void finish(V&& value)
|
||||||
|
requires(!std::is_void_v<ResultT>)
|
||||||
|
{
|
||||||
|
commit(Step::success(std::any{ResultT(std::forward<V>(value))}),
|
||||||
|
"(success)");
|
||||||
|
}
|
||||||
|
|
||||||
|
void fail(std::string message)
|
||||||
|
{
|
||||||
|
commit(Step::failure(FsmError{std::move(message)}), "(fail)");
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
void commit(Step step, std::string target)
|
||||||
|
{
|
||||||
|
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.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(..)`.
|
||||||
|
template <typename Derived, typename ResultT> 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(std::string message)
|
||||||
|
{
|
||||||
|
m_table->has_timeout = true;
|
||||||
|
m_table->timeout_after = m_after;
|
||||||
|
m_table->timeout_step =
|
||||||
|
Step::failure(FsmError{std::move(message)});
|
||||||
|
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, typename ResultT> class TransitionBuilder
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
|
||||||
|
explicit TransitionBuilder(TransitionTable<Derived>& table)
|
||||||
|
: m_table(&table)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename E>
|
||||||
|
[[nodiscard]] EventClause<Derived, ResultT, E> event()
|
||||||
|
{
|
||||||
|
return EventClause<Derived, ResultT, E>{*m_table};
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename Rep, typename Period>
|
||||||
|
[[nodiscard]] AfterClause<Derived, ResultT>
|
||||||
|
after(std::chrono::duration<Rep, Period> d)
|
||||||
|
{
|
||||||
|
return AfterClause<Derived, ResultT>{
|
||||||
|
*m_table, std::chrono::duration_cast<
|
||||||
|
std::chrono::steady_clock::duration>(d)};
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
TransitionTable<Derived>* m_table;
|
||||||
|
};
|
||||||
|
} // namespace Void::Fsm::Detail
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <string>
|
||||||
|
#include <typeinfo>
|
||||||
|
|
||||||
|
#if __has_include(<meta>)
|
||||||
|
#include <meta>
|
||||||
|
#ifndef VOID_HAS_FSM_REFLECTION
|
||||||
|
#define VOID_HAS_FSM_REFLECTION 1
|
||||||
|
#endif
|
||||||
|
#endif
|
||||||
|
|
||||||
|
namespace Void::Fsm::Detail
|
||||||
|
{
|
||||||
|
/// Stable display name for a type — P2996 `identifier_of` when available
|
||||||
|
/// (GCC `-freflection`), else the mangled `typeid` name. Used for state /
|
||||||
|
/// event names in the reactive DSL and introspection.
|
||||||
|
template <typename T> [[nodiscard]] inline std::string type_name()
|
||||||
|
{
|
||||||
|
#ifdef VOID_HAS_FSM_REFLECTION
|
||||||
|
return std::string{std::meta::identifier_of(^^T)};
|
||||||
|
#else
|
||||||
|
return typeid(T).name();
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
} // namespace Void::Fsm::Detail
|
||||||
+13
-1194
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,917 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Void/Async/Executor.hpp>
|
||||||
|
#include <Void/Async/Task.hpp>
|
||||||
|
#include <Void/Data/Json.hpp>
|
||||||
|
#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/TypeName.hpp>
|
||||||
|
#include <Void/Fsm/Step.hpp>
|
||||||
|
#include <Void/Log/Log.hpp>
|
||||||
|
#include <Void/Service/Registry.hpp>
|
||||||
|
|
||||||
|
#include <any>
|
||||||
|
#include <array>
|
||||||
|
#include <atomic>
|
||||||
|
#include <chrono>
|
||||||
|
#include <coroutine>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <expected>
|
||||||
|
#include <functional>
|
||||||
|
#include <iterator>
|
||||||
|
#include <memory>
|
||||||
|
#include <optional>
|
||||||
|
#include <string>
|
||||||
|
#include <string_view>
|
||||||
|
#include <tuple>
|
||||||
|
#include <type_traits>
|
||||||
|
#include <typeindex>
|
||||||
|
#include <typeinfo>
|
||||||
|
#include <unordered_map>
|
||||||
|
#include <utility>
|
||||||
|
#include <variant>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
#if __has_include(<meta>)
|
||||||
|
#include <meta>
|
||||||
|
#define VOID_HAS_FSM_REFLECTION 1
|
||||||
|
#endif
|
||||||
|
|
||||||
|
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 {
|
||||||
|
bool own_worker = true;
|
||||||
|
};
|
||||||
|
|
||||||
|
/// A transition record handed to observers.
|
||||||
|
struct Transition {
|
||||||
|
std::string from;
|
||||||
|
std::string to;
|
||||||
|
std::uint64_t step{0};
|
||||||
|
};
|
||||||
|
|
||||||
|
// ── Machine<Derived, ResultT> ─────────────────────────────────────────
|
||||||
|
//
|
||||||
|
// Inheritance + coroutine workflow FSM, CRTP for typed access. Derive
|
||||||
|
// it, declare states as nested structs deriving `State`, list them in
|
||||||
|
// `using States = Fsm::States<...>`, and implement each state's async
|
||||||
|
// run() to return next<S>() / succeed(...) / fail(...). States reach
|
||||||
|
// their owning machine (and its data + sub-methods) via self().
|
||||||
|
//
|
||||||
|
// class Login : public Void::Fsm::Machine<Login, bool> {
|
||||||
|
// public:
|
||||||
|
// int attempts = 0;
|
||||||
|
// struct Check : State {
|
||||||
|
// Coro::Task<Step> run() override {
|
||||||
|
// if (++self().attempts > 3) co_return fail("locked");
|
||||||
|
// co_return self().service<IAuth>().ok() ? succeed(true)
|
||||||
|
// : next<Check>();
|
||||||
|
// }
|
||||||
|
// };
|
||||||
|
// using States = Void::Fsm::States<Check>;
|
||||||
|
// };
|
||||||
|
template <typename Derived, typename ResultT = void> class Machine
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
|
||||||
|
using result_type = ResultT;
|
||||||
|
using Options = MachineOptions;
|
||||||
|
using Outcome = std::expected<ResultT, FsmError>;
|
||||||
|
|
||||||
|
// ── State base ────────────────────────────────────────────────
|
||||||
|
class State : public Detail::StateBase
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
|
||||||
|
/// Typed access to the owning machine — no static_cast.
|
||||||
|
[[nodiscard]] Derived& self() const noexcept
|
||||||
|
{
|
||||||
|
return *static_cast<Derived*>(m_machine);
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] Machine& machine() const noexcept
|
||||||
|
{
|
||||||
|
return *m_machine;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected:
|
||||||
|
|
||||||
|
/// Transition to another state. Validated at compile
|
||||||
|
/// time when the machine declares `using States`.
|
||||||
|
template <typename S> [[nodiscard]] Step next() const
|
||||||
|
{
|
||||||
|
if constexpr (requires { typename Derived::States; }) {
|
||||||
|
static_assert(
|
||||||
|
Derived::States::template contains<S>(),
|
||||||
|
"next<S>: S is not in this machine's "
|
||||||
|
"States<...> list");
|
||||||
|
}
|
||||||
|
return Step::transition(typeid(S));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Transition to a state registered dynamically
|
||||||
|
/// (add<S>()/add_if<S>()), skipping the static check.
|
||||||
|
template <typename S>
|
||||||
|
[[nodiscard]] Step next_dynamic() const
|
||||||
|
{
|
||||||
|
return Step::transition(typeid(S));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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
|
||||||
|
{
|
||||||
|
if (step.kind() == Step::Kind::Fail) {
|
||||||
|
return next<S>();
|
||||||
|
}
|
||||||
|
return step;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Suspend for `duration` (timer-driven), then resume.
|
||||||
|
template <typename Rep, typename Period>
|
||||||
|
[[nodiscard]] auto
|
||||||
|
delay(std::chrono::duration<Rep, Period> d) const
|
||||||
|
{
|
||||||
|
return m_machine->delay(d);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Retry an async sub-step up to `times`, waiting
|
||||||
|
/// `backoff` between attempts. `attempt` returns
|
||||||
|
/// Coro::Task<bool> (true = success). Returns whether it
|
||||||
|
/// eventually succeeded.
|
||||||
|
template <typename Rep, typename Period, typename Fn>
|
||||||
|
[[nodiscard]] Coro::Task<bool>
|
||||||
|
with_retry(int times,
|
||||||
|
std::chrono::duration<Rep, Period>
|
||||||
|
backoff,
|
||||||
|
Fn attempt) const
|
||||||
|
{
|
||||||
|
for (int i = 0; i < times; ++i) {
|
||||||
|
if (co_await attempt()) {
|
||||||
|
co_return true;
|
||||||
|
}
|
||||||
|
if (i + 1 < times) {
|
||||||
|
co_await m_machine->delay(backoff);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
co_return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] Step succeed() const
|
||||||
|
requires std::is_void_v<ResultT>
|
||||||
|
{
|
||||||
|
return Step::success(std::any{});
|
||||||
|
}
|
||||||
|
template <typename V>
|
||||||
|
[[nodiscard]] Step succeed(V&& value) const
|
||||||
|
requires(!std::is_void_v<ResultT>)
|
||||||
|
{
|
||||||
|
return Step::success(
|
||||||
|
std::any{ResultT(std::forward<V>(value))});
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] Step fail(std::string message) const
|
||||||
|
{
|
||||||
|
return Step::failure(FsmError{std::move(message)});
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename I> [[nodiscard]] I& service() const
|
||||||
|
{
|
||||||
|
return m_machine->template service<I>();
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename E> [[nodiscard]] auto await_event() const
|
||||||
|
{
|
||||||
|
return m_machine->template await_event<E>();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Await E or time out (nullopt on timeout).
|
||||||
|
template <typename E, typename Rep, typename Period>
|
||||||
|
[[nodiscard]] auto await_event_for(
|
||||||
|
std::chrono::duration<Rep, Period> d) const
|
||||||
|
{
|
||||||
|
return m_machine->template await_event_for<E>(d);
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename Sub, typename... Args>
|
||||||
|
[[nodiscard]] auto run_child(Args&&... args) const
|
||||||
|
{
|
||||||
|
return m_machine->template run_child<Sub>(
|
||||||
|
std::forward<Args>(args)...);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Enter a child region (composite sub-state): a nested
|
||||||
|
/// machine sharing this machine's executor, event mailbox
|
||||||
|
/// and services. This state's on_enter/on_exit wrap it, and
|
||||||
|
/// state_path() reports the parent→child chain while it
|
||||||
|
/// runs. Map the child's Outcome to a sibling transition:
|
||||||
|
/// auto r = co_await run_region<Work>();
|
||||||
|
/// co_return r ? next<Done>() : next<Recover>();
|
||||||
|
template <typename Sub, typename... Args>
|
||||||
|
[[nodiscard]] auto run_region(Args&&... args) const
|
||||||
|
{
|
||||||
|
return m_machine->template run_region<Sub>(
|
||||||
|
std::forward<Args>(args)...);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Await whichever of several event types arrives first,
|
||||||
|
/// yielding a std::variant<Es...>. Handles multiple events
|
||||||
|
/// at one level (e.g. a parent watching Cancel alongside a
|
||||||
|
/// child region's own events).
|
||||||
|
template <typename... Es>
|
||||||
|
[[nodiscard]] auto await_any() const
|
||||||
|
{
|
||||||
|
return m_machine->template await_any<Es...>();
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename S> [[nodiscard]] bool has_state() const
|
||||||
|
{
|
||||||
|
return m_machine->template has_state<S>();
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
friend class Machine;
|
||||||
|
Machine* m_machine{nullptr};
|
||||||
|
};
|
||||||
|
|
||||||
|
// ── reactive (declarative) states ─────────────────────────────
|
||||||
|
//
|
||||||
|
// 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.
|
||||||
|
using TransitionTable = Detail::TransitionTable<Derived>;
|
||||||
|
using TransitionBuilder =
|
||||||
|
Detail::TransitionBuilder<Derived, ResultT>;
|
||||||
|
|
||||||
|
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)
|
||||||
|
{
|
||||||
|
if constexpr (requires { typename Derived::States; }) {
|
||||||
|
register_states(typename Derived::States{});
|
||||||
|
if constexpr (requires { typename Derived::Initial; }) {
|
||||||
|
m_initial = &typeid(typename Derived::Initial);
|
||||||
|
} else {
|
||||||
|
m_initial = first_type(typename Derived::States{});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
virtual ~Machine() { stop(); }
|
||||||
|
|
||||||
|
Machine(const Machine&) = delete;
|
||||||
|
Machine& operator=(const Machine&) = delete;
|
||||||
|
|
||||||
|
// ── registration ──────────────────────────────────────────────
|
||||||
|
template <typename S> void add()
|
||||||
|
{
|
||||||
|
static_assert(std::is_base_of_v<State, S>,
|
||||||
|
"FSM state must derive Machine::State");
|
||||||
|
const std::type_info& ti = typeid(S);
|
||||||
|
const std::type_index key{ti};
|
||||||
|
if (m_factories.contains(key)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const int idx = static_cast<int>(m_names.size());
|
||||||
|
m_index.emplace(key, idx);
|
||||||
|
m_names.push_back(state_name<S>());
|
||||||
|
m_name_to_type.emplace(m_names.back(), &ti);
|
||||||
|
m_factories.emplace(
|
||||||
|
key, [this]() -> std::unique_ptr<Detail::StateBase> {
|
||||||
|
auto s = std::make_unique<S>();
|
||||||
|
s->m_machine = this;
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename S> void initial()
|
||||||
|
{
|
||||||
|
add<S>();
|
||||||
|
m_initial = &typeid(S);
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename S> void add_if(bool condition)
|
||||||
|
{
|
||||||
|
if (condition) {
|
||||||
|
add<S>();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename S> [[nodiscard]] bool has_state() const
|
||||||
|
{
|
||||||
|
return m_factories.contains(std::type_index{typeid(S)});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── service context ───────────────────────────────────────────
|
||||||
|
void set_services(Service::ServiceRegistry& registry) noexcept
|
||||||
|
{
|
||||||
|
m_services = ®istry;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename I> [[nodiscard]] I& service() const
|
||||||
|
{
|
||||||
|
return m_services->template require<I>();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── observability ─────────────────────────────────────────────
|
||||||
|
/// Register a read-only observer fired on every transition
|
||||||
|
/// (and on the initial entry). Replaces any prior observer.
|
||||||
|
void observe(std::function<void(const Transition&)> observer)
|
||||||
|
{
|
||||||
|
m_observer = std::move(observer);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Transition middleware. `before(transition)` fires as a state
|
||||||
|
/// is entered (after the state changes, before it runs);
|
||||||
|
/// `after(state_name)` fires once that state finishes running.
|
||||||
|
/// Interceptors run in registration order — for logging,
|
||||||
|
/// metrics, validation around transitions.
|
||||||
|
struct Interceptor {
|
||||||
|
std::function<void(const Transition&)> before;
|
||||||
|
std::function<void(std::string_view)> after;
|
||||||
|
};
|
||||||
|
void add_interceptor(Interceptor interceptor)
|
||||||
|
{
|
||||||
|
m_interceptors.push_back(std::move(interceptor));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── lifecycle ─────────────────────────────────────────────────
|
||||||
|
void start()
|
||||||
|
{
|
||||||
|
if (m_status.load() != Status::Idle) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!m_ctx) {
|
||||||
|
m_ctx = std::make_shared<Detail::ExecutionContext>();
|
||||||
|
m_owns_ctx = true;
|
||||||
|
}
|
||||||
|
m_status.store(Status::Running);
|
||||||
|
Async::spawn(m_ctx->executor(), driver());
|
||||||
|
if (m_options.own_worker && m_owns_ctx) {
|
||||||
|
m_ctx->start_worker();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Outcome wait()
|
||||||
|
{
|
||||||
|
if (m_ctx) {
|
||||||
|
if (m_options.own_worker && m_owns_ctx) {
|
||||||
|
m_ctx->join();
|
||||||
|
} else {
|
||||||
|
while (!finished()) {
|
||||||
|
if (m_ctx->pump() == 0 && !finished()) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return take_outcome();
|
||||||
|
}
|
||||||
|
|
||||||
|
Outcome run_blocking()
|
||||||
|
{
|
||||||
|
start();
|
||||||
|
return wait();
|
||||||
|
}
|
||||||
|
|
||||||
|
std::size_t pump() { return m_ctx ? m_ctx->pump() : 0; }
|
||||||
|
|
||||||
|
[[nodiscard]] bool finished() const noexcept
|
||||||
|
{
|
||||||
|
const auto s = m_status.load();
|
||||||
|
return s == Status::Succeeded || s == Status::Failed;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] Status status() const noexcept
|
||||||
|
{
|
||||||
|
return m_status.load();
|
||||||
|
}
|
||||||
|
|
||||||
|
void stop()
|
||||||
|
{
|
||||||
|
if (m_owns_ctx && m_ctx) {
|
||||||
|
m_ctx->stop();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── events ────────────────────────────────────────────────────
|
||||||
|
template <typename E> void post(E event)
|
||||||
|
{
|
||||||
|
if (!m_ctx) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
m_ctx->post(Detail::EventEnvelope{&typeid(E),
|
||||||
|
std::any{std::move(event)}});
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename E> [[nodiscard]] auto await_event()
|
||||||
|
{
|
||||||
|
return Detail::make_event_awaiter(
|
||||||
|
m_ctx.get(), std::array{&typeid(E)}, std::nullopt,
|
||||||
|
[](Detail::EventEnvelope&& env, bool) {
|
||||||
|
return std::any_cast<E>(std::move(env.value));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Await an event of type E or time out after `duration`;
|
||||||
|
/// returns std::nullopt on timeout.
|
||||||
|
template <typename E, typename Rep, typename Period>
|
||||||
|
[[nodiscard]] auto
|
||||||
|
await_event_for(std::chrono::duration<Rep, Period> duration)
|
||||||
|
{
|
||||||
|
return Detail::make_event_awaiter(
|
||||||
|
m_ctx.get(), std::array{&typeid(E)},
|
||||||
|
std::chrono::steady_clock::now() + duration,
|
||||||
|
[](Detail::EventEnvelope&& env,
|
||||||
|
bool timed_out) -> std::optional<E> {
|
||||||
|
if (timed_out) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
return std::any_cast<E>(std::move(env.value));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Await any of several event types (optional deadline); used
|
||||||
|
/// by reactive states. Returns the matched envelope or nullopt
|
||||||
|
/// on timeout.
|
||||||
|
[[nodiscard]] auto await_any_event(
|
||||||
|
std::vector<const std::type_info*> types,
|
||||||
|
std::optional<std::chrono::steady_clock::time_point> deadline)
|
||||||
|
{
|
||||||
|
return Detail::make_event_awaiter(
|
||||||
|
m_ctx.get(), std::move(types), deadline,
|
||||||
|
[](Detail::EventEnvelope&& env,
|
||||||
|
bool timed_out) -> std::optional<Detail::EventEnvelope> {
|
||||||
|
if (timed_out) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
return std::move(env);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Typed multi-event await: suspend until one of `Es...` arrives,
|
||||||
|
/// returning it as std::variant<Es...>. Lets one state react to
|
||||||
|
/// several event types (parent-level handling for child regions).
|
||||||
|
template <typename... Es> [[nodiscard]] auto await_any()
|
||||||
|
{
|
||||||
|
return Detail::make_event_awaiter(
|
||||||
|
m_ctx.get(), std::array{(&typeid(Es))...}, std::nullopt,
|
||||||
|
[](Detail::EventEnvelope&& env,
|
||||||
|
bool) -> std::variant<Es...> {
|
||||||
|
std::optional<std::variant<Es...>> out;
|
||||||
|
((env.type != nullptr && *env.type == typeid(Es)
|
||||||
|
? (out.emplace(
|
||||||
|
std::in_place_type<Es>,
|
||||||
|
std::any_cast<Es>(std::move(env.value))),
|
||||||
|
true)
|
||||||
|
: false) ||
|
||||||
|
...);
|
||||||
|
return std::move(*out);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Suspend for `duration`, then resume (timer-driven).
|
||||||
|
template <typename Rep, typename Period>
|
||||||
|
[[nodiscard]] auto delay(std::chrono::duration<Rep, Period> d)
|
||||||
|
{
|
||||||
|
struct Awaiter {
|
||||||
|
Detail::ExecutionContext* ctx;
|
||||||
|
std::chrono::steady_clock::time_point deadline;
|
||||||
|
|
||||||
|
[[nodiscard]] bool await_ready() const noexcept
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
void await_suspend(std::coroutine_handle<> h)
|
||||||
|
{
|
||||||
|
ctx->add_timer(deadline, [c = ctx, h] {
|
||||||
|
c->executor().post(h);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
void await_resume() const noexcept {}
|
||||||
|
};
|
||||||
|
return Awaiter{m_ctx.get(),
|
||||||
|
std::chrono::steady_clock::now() + d};
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── nesting ───────────────────────────────────────────────────
|
||||||
|
template <typename Sub, typename... Args>
|
||||||
|
[[nodiscard]] Coro::Task<typename Sub::Outcome>
|
||||||
|
run_child(Args&&... args)
|
||||||
|
{
|
||||||
|
Sub child{std::forward<Args>(args)...};
|
||||||
|
child.attach(m_ctx, m_services);
|
||||||
|
co_return co_await child.drive();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Composite sub-state: run `Sub` as a child region sharing this
|
||||||
|
/// machine's executor, event mailbox and services, and expose its
|
||||||
|
/// active state through this machine's state_path() while it runs
|
||||||
|
/// (parent→child chain). Returns the child's Outcome, which the
|
||||||
|
/// caller maps to a sibling transition. The calling state's
|
||||||
|
/// on_enter/on_exit naturally wrap the region.
|
||||||
|
template <typename Sub, typename... Args>
|
||||||
|
[[nodiscard]] Coro::Task<typename Sub::Outcome>
|
||||||
|
run_region(Args&&... args)
|
||||||
|
{
|
||||||
|
Sub child{std::forward<Args>(args)...};
|
||||||
|
child.attach(m_ctx, m_services);
|
||||||
|
m_region_probe = [&child] { return child.state_path(); };
|
||||||
|
auto outcome = co_await child.drive();
|
||||||
|
m_region_probe = nullptr;
|
||||||
|
co_return std::move(outcome);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── observation ───────────────────────────────────────────────
|
||||||
|
[[nodiscard]] std::string current_state() const
|
||||||
|
{
|
||||||
|
const int idx = m_current.load(std::memory_order_acquire);
|
||||||
|
if (idx < 0 || idx >= static_cast<int>(m_names.size())) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
return m_names[static_cast<std::size_t>(idx)];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Active state chain (root → leaf). When a child region is
|
||||||
|
/// running (run_region), its path is appended, so a composite
|
||||||
|
/// state reports {composite, ...child leaf}. Unlike the lock-free
|
||||||
|
/// current_state(), the region part is consumer-consistent: read
|
||||||
|
/// it from within the machine or once it has settled (it is
|
||||||
|
/// deterministic in embedder/pump mode).
|
||||||
|
[[nodiscard]] std::vector<std::string> state_path() const
|
||||||
|
{
|
||||||
|
std::vector<std::string> path;
|
||||||
|
if (auto s = current_state(); !s.empty()) {
|
||||||
|
path.push_back(std::move(s));
|
||||||
|
}
|
||||||
|
if (m_region_probe) {
|
||||||
|
auto sub = m_region_probe();
|
||||||
|
path.insert(path.end(),
|
||||||
|
std::make_move_iterator(sub.begin()),
|
||||||
|
std::make_move_iterator(sub.end()));
|
||||||
|
}
|
||||||
|
return path;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// All registered state names (registration order).
|
||||||
|
[[nodiscard]] const std::vector<std::string>&
|
||||||
|
state_names() const noexcept
|
||||||
|
{
|
||||||
|
return m_names;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── introspection / diagram ───────────────────────────────────
|
||||||
|
// EdgeInfo / StateInfo are 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).
|
||||||
|
[[nodiscard]] std::vector<StateInfo> describe()
|
||||||
|
{
|
||||||
|
std::vector<StateInfo> out;
|
||||||
|
const std::string initial_name = m_initial != nullptr
|
||||||
|
? state_name_for(m_initial)
|
||||||
|
: std::string{};
|
||||||
|
for (const auto& name : m_names) {
|
||||||
|
StateInfo si;
|
||||||
|
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);
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Render describe() as a Mermaid stateDiagram-v2 string.
|
||||||
|
[[nodiscard]] std::string to_mermaid()
|
||||||
|
{
|
||||||
|
const auto states = describe();
|
||||||
|
return Detail::to_mermaid(states);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── persistence ───────────────────────────────────────────────
|
||||||
|
[[nodiscard]] Json::Value serialize() const
|
||||||
|
{
|
||||||
|
auto obj = Json::object();
|
||||||
|
obj.as_object().emplace_back("state",
|
||||||
|
Json::Value{current_state()});
|
||||||
|
Json::Value data = Json::object();
|
||||||
|
on_serialize(data);
|
||||||
|
obj.as_object().emplace_back("data", std::move(data));
|
||||||
|
return obj;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] std::expected<void, FsmError>
|
||||||
|
restore(const Json::Value& state)
|
||||||
|
{
|
||||||
|
if (m_status.load() != Status::Idle) {
|
||||||
|
return std::unexpected{
|
||||||
|
FsmError{"restore requires an un-started machine"}};
|
||||||
|
}
|
||||||
|
const auto* st = state.find("state");
|
||||||
|
if (st == nullptr || !st->is_string()) {
|
||||||
|
return std::unexpected{
|
||||||
|
FsmError{"malformed machine state json"}};
|
||||||
|
}
|
||||||
|
const auto it = m_name_to_type.find(st->as_string());
|
||||||
|
if (it == m_name_to_type.end()) {
|
||||||
|
return std::unexpected{
|
||||||
|
FsmError{"unknown state '" + st->as_string() + "'"}};
|
||||||
|
}
|
||||||
|
m_initial = it->second;
|
||||||
|
if (const auto* data = state.find("data")) {
|
||||||
|
on_restore(*data);
|
||||||
|
}
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
protected:
|
||||||
|
|
||||||
|
virtual void on_serialize(Json::Value& /*data*/) const {}
|
||||||
|
virtual void on_restore(const Json::Value& /*data*/) {}
|
||||||
|
|
||||||
|
/// Called on every transition (and the initial entry). Default
|
||||||
|
/// logs at debug; override for custom observability.
|
||||||
|
virtual void on_transition(std::string_view from,
|
||||||
|
std::string_view to)
|
||||||
|
{
|
||||||
|
Void::Log::debug("Fsm", "{} -> {}",
|
||||||
|
from.empty() ? "(start)" : from, to);
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
template <typename, typename>
|
||||||
|
friend class Machine; // run_child reaches child internals
|
||||||
|
|
||||||
|
void attach(std::shared_ptr<Detail::ExecutionContext> ctx,
|
||||||
|
Service::ServiceRegistry* services)
|
||||||
|
{
|
||||||
|
m_ctx = std::move(ctx);
|
||||||
|
m_owns_ctx = false;
|
||||||
|
if (services != nullptr) {
|
||||||
|
m_services = services;
|
||||||
|
}
|
||||||
|
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
|
||||||
|
return std::string{std::meta::identifier_of(^^S)};
|
||||||
|
#else
|
||||||
|
return "state" + std::to_string(m_names.size());
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] std::string
|
||||||
|
state_name_for(const std::type_info* type) const
|
||||||
|
{
|
||||||
|
if (const auto it = m_index.find(std::type_index{*type});
|
||||||
|
it != m_index.end()) {
|
||||||
|
return m_names[static_cast<std::size_t>(it->second)];
|
||||||
|
}
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
void set_current(const std::type_info* type)
|
||||||
|
{
|
||||||
|
std::string from = current_state();
|
||||||
|
if (const auto it = m_index.find(std::type_index{*type});
|
||||||
|
it != m_index.end()) {
|
||||||
|
m_current.store(it->second, std::memory_order_release);
|
||||||
|
}
|
||||||
|
std::string to = current_state();
|
||||||
|
++m_step;
|
||||||
|
on_transition(from, to);
|
||||||
|
const Transition t{from, to, m_step};
|
||||||
|
if (m_observer) {
|
||||||
|
m_observer(t);
|
||||||
|
}
|
||||||
|
for (const auto& interceptor : m_interceptors) {
|
||||||
|
if (interceptor.before) {
|
||||||
|
interceptor.before(t);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void fire_after(std::string_view state)
|
||||||
|
{
|
||||||
|
for (const auto& interceptor : m_interceptors) {
|
||||||
|
if (interceptor.after) {
|
||||||
|
interceptor.after(state);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The state loop: build each state, run on_enter → run →
|
||||||
|
// on_exit, follow the returned Step. Runs on the executor.
|
||||||
|
Coro::Task<Outcome> drive()
|
||||||
|
{
|
||||||
|
const std::type_info* cur = m_initial;
|
||||||
|
if (cur == nullptr) {
|
||||||
|
co_return std::unexpected{FsmError{"no initial state"}};
|
||||||
|
}
|
||||||
|
for (;;) {
|
||||||
|
const auto it = m_factories.find(std::type_index{*cur});
|
||||||
|
if (it == m_factories.end()) {
|
||||||
|
co_return std::unexpected{
|
||||||
|
FsmError{"transition to unregistered state"}};
|
||||||
|
}
|
||||||
|
set_current(cur);
|
||||||
|
auto state = it->second();
|
||||||
|
co_await state->on_enter();
|
||||||
|
Step step = co_await state->run();
|
||||||
|
co_await state->on_exit();
|
||||||
|
fire_after(current_state());
|
||||||
|
switch (step.kind()) {
|
||||||
|
case Step::Kind::Transition:
|
||||||
|
cur = step.target();
|
||||||
|
continue;
|
||||||
|
case Step::Kind::Success:
|
||||||
|
if constexpr (std::is_void_v<ResultT>) {
|
||||||
|
co_return Outcome{};
|
||||||
|
} else {
|
||||||
|
co_return Outcome{std::any_cast<ResultT>(
|
||||||
|
std::move(step.result()))};
|
||||||
|
}
|
||||||
|
case Step::Kind::Fail:
|
||||||
|
co_return std::unexpected{step.error()};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Coro::Task<void> driver()
|
||||||
|
{
|
||||||
|
Outcome outcome = co_await drive();
|
||||||
|
const bool ok = outcome.has_value();
|
||||||
|
m_outcome.emplace(std::move(outcome));
|
||||||
|
m_status.store(ok ? Status::Succeeded : Status::Failed,
|
||||||
|
std::memory_order_release);
|
||||||
|
if (m_owns_ctx) {
|
||||||
|
m_ctx->finish();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Outcome take_outcome()
|
||||||
|
{
|
||||||
|
if (m_outcome.has_value()) {
|
||||||
|
return std::move(*m_outcome);
|
||||||
|
}
|
||||||
|
return std::unexpected{FsmError{"machine did not finish"}};
|
||||||
|
}
|
||||||
|
|
||||||
|
Options m_options;
|
||||||
|
std::shared_ptr<Detail::ExecutionContext> m_ctx;
|
||||||
|
bool m_owns_ctx{false};
|
||||||
|
Service::ServiceRegistry* m_services{nullptr};
|
||||||
|
|
||||||
|
std::unordered_map<
|
||||||
|
std::type_index,
|
||||||
|
std::function<std::unique_ptr<Detail::StateBase>()>>
|
||||||
|
m_factories;
|
||||||
|
std::unordered_map<std::type_index, int> m_index;
|
||||||
|
std::vector<std::string> m_names;
|
||||||
|
std::unordered_map<std::string, const std::type_info*>
|
||||||
|
m_name_to_type;
|
||||||
|
const std::type_info* m_initial{nullptr};
|
||||||
|
|
||||||
|
std::atomic<int> m_current{-1};
|
||||||
|
std::atomic<Status> m_status{Status::Idle};
|
||||||
|
std::optional<Outcome> m_outcome;
|
||||||
|
std::function<void(const Transition&)> m_observer;
|
||||||
|
std::vector<Interceptor> m_interceptors;
|
||||||
|
std::uint64_t m_step{0};
|
||||||
|
|
||||||
|
// Active child region's path provider (run_region); consulted by
|
||||||
|
// state_path(). Set/cleared on the consumer thread.
|
||||||
|
std::function<std::vector<std::string>()> m_region_probe;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace Void::Fsm
|
||||||
Reference in new issue
Block a user