A composite region can resume at the sub-state it last reached instead of
restarting from its initial state (shallow history), reusing the existing
serialize()/restore():
co_await run_region<Work>(); // Initial (default)
co_await run_region<Work>(Resume::History); // resume where it left off
- New Resume{Initial, History} enum. On region exit the engine snapshots the
child's serialize() keyed by region type into the parent
(m_region_history); on a History re-entry it restore()s that snapshot
before driving. restore() runs before attach() (attach marks the child
Running, and restore requires Idle).
- run_region no longer forwards constructor args (children are
default-constructed, like run_parallel); the only prior caller passed
none.
2 new tests (History): a History re-entry resumes at the last leaf (skips
the earlier states); a plain Initial re-entry restarts from the top. 1000
tests (997 green, 3 skipped). History/Hierarchy/Parallel ASan-clean.
Known pre-existing issue (NOT from this change): the Serialize suite leaks
under ASan because two tests start a machine that parks on an event then
stop() without it finishing — the parked coroutine frame is never
destroyed. Confirmed present at the pre-epic baseline (7c7c590); it is an
engine-lifetime issue (machine stopped while parked), orthogonal to the FSM
feature work, and left for a separate fix.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
1418 lines
45 KiB
C++
1418 lines
45 KiB
C++
#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/Result.hpp>
|
|
#include <Void/Fsm/Detail/Roles.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;
|
|
};
|
|
|
|
/// How a run_region<Sub>() re-enters: from Sub's initial state, or resume
|
|
/// at the sub-state it last reached (shallow history).
|
|
enum class Resume { Initial, History };
|
|
|
|
/// A transition record handed to observers.
|
|
struct Transition {
|
|
std::string from;
|
|
std::string to;
|
|
std::uint64_t step{0};
|
|
};
|
|
|
|
// ── 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).
|
|
//
|
|
// 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>;
|
|
// };
|
|
template <typename Derived> class Machine
|
|
{
|
|
public:
|
|
|
|
using Options = MachineOptions;
|
|
|
|
// Result types are reflected by name from Derived's nested
|
|
// `Success`/`Failure` (default void). Because Derived is incomplete
|
|
// at base instantiation (CRTP), they cannot appear in member
|
|
// signatures or data members — only inside function templates /
|
|
// bodies, where Derived is complete. So these are alias *templates*
|
|
// (lazily resolved), the engine stores outcomes type-erased, and
|
|
// the typed Outcome is rebuilt in wait()/take_outcome().
|
|
template <typename D = Derived>
|
|
using Success = Detail::SuccessOf<D>;
|
|
template <typename D = Derived>
|
|
using Failure = Detail::FailureOf<D>;
|
|
template <typename D = Derived>
|
|
using Outcome = Detail::OutcomeOf<D>;
|
|
|
|
// ── 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));
|
|
}
|
|
|
|
/// 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
|
|
/// was never registered.
|
|
template <typename S> [[nodiscard]] Step goto_state() 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;
|
|
}
|
|
|
|
/// Finish with the machine's typed Success result (nested
|
|
/// `Success`; nullary when it is void).
|
|
[[nodiscard]] Step succeed() const
|
|
requires std::is_void_v<Detail::SuccessOf<Derived>>
|
|
{
|
|
return Step::success(std::any{});
|
|
}
|
|
template <typename V>
|
|
[[nodiscard]] Step succeed(V&& value) const
|
|
requires(!std::is_void_v<Detail::SuccessOf<Derived>>)
|
|
{
|
|
return Step::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
|
|
requires std::is_void_v<Detail::FailureOf<Derived>>
|
|
{
|
|
return Step::failure(std::any{});
|
|
}
|
|
template <typename V>
|
|
[[nodiscard]] Step fail(V&& value) const
|
|
requires(!std::is_void_v<Detail::FailureOf<Derived>>)
|
|
{
|
|
return Step::failure(
|
|
std::any{Detail::FailureOf<Derived>{
|
|
std::forward<V>(value)}});
|
|
}
|
|
|
|
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>
|
|
[[nodiscard]] auto
|
|
run_region(Resume resume = Resume::Initial) const
|
|
{
|
|
return m_machine->template run_region<Sub>(resume);
|
|
}
|
|
|
|
/// Orthogonal regions: run `Subs...` concurrently on the
|
|
/// shared executor and join all, yielding a
|
|
/// std::tuple<Subs::Outcome...> (children share events/
|
|
/// services; map the tuple to a sibling transition).
|
|
template <typename... Subs>
|
|
[[nodiscard]] auto run_parallel() const
|
|
{
|
|
return m_machine->template run_parallel<Subs...>();
|
|
}
|
|
|
|
/// Race orthogonal regions: resolve on the first to finish,
|
|
/// yielding std::variant<Subs::Outcome...> (losers keep
|
|
/// running cooperatively).
|
|
template <typename... Subs>
|
|
[[nodiscard]] auto run_parallel_any() const
|
|
{
|
|
return m_machine->template run_parallel_any<Subs...>();
|
|
}
|
|
|
|
/// 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...>();
|
|
}
|
|
|
|
/// Launch a sub-machine `Sub` (startup data routed to its
|
|
/// initial-state startup-entry; shares this machine's
|
|
/// executor/events/services), then transition to `Next`.
|
|
/// When Sub finishes the engine calls Next's signature
|
|
/// -matched handler — a member taking `ChildSuccess auto`
|
|
/// (Sub succeeded) or `ChildFailure auto` (Sub failed):
|
|
/// co_return startMachine<Login, AfterLogin>(seed);
|
|
template <typename Sub, typename Next, typename... Args>
|
|
[[nodiscard]] Step startMachine(Args&&... args) const
|
|
{
|
|
return m_machine->template start_machine<Sub, Next>(
|
|
std::forward<Args>(args)...);
|
|
}
|
|
|
|
template <typename S> [[nodiscard]] bool has_state() const
|
|
{
|
|
return m_machine->template has_state<S>();
|
|
}
|
|
|
|
private:
|
|
|
|
friend class Machine;
|
|
Machine* m_machine{nullptr};
|
|
};
|
|
|
|
// ── one State, signature-inferred roles ───────────────────────
|
|
//
|
|
// There is a single base, `State`. The engine infers what each
|
|
// state does from member signatures (no `override`, no fixed
|
|
// names):
|
|
// - entry : a member returning Step/Coro::Task<Step>,
|
|
// no params (a startup-data overload may take
|
|
// the sub's startup argument);
|
|
// - reactive : a member taking `TransitionBuilder&` (the
|
|
// declarative table below);
|
|
// - continuation : members taking `ChildSuccess auto` /
|
|
// `ChildFailure auto` (the sub's typed result
|
|
// after `startMachine<Sub, This>()`).
|
|
//
|
|
// struct Idle : State { // reactive
|
|
// void transitions(TransitionBuilder& on) {
|
|
// on.event<Go>().to<Running>();
|
|
// on.after(5s).to<TimedOut>(); } };
|
|
// struct After : State { // continuation
|
|
// Coro::Task<Step> ok(ChildSuccess auto s){ ... }
|
|
// Coro::Task<Step> no(ChildFailure auto f){ ... } };
|
|
//
|
|
// 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>;
|
|
|
|
// ── 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;
|
|
});
|
|
// Signature-inferred driver thunk (entry or reactive table).
|
|
m_drivers.emplace(key, Detail::make_driver<S>());
|
|
// describe() collector: fills a table if S is reactive.
|
|
m_collectors.emplace(
|
|
key,
|
|
[](Detail::StateBase& base,
|
|
TransitionTable& table) -> bool {
|
|
if constexpr (Detail::has_transitions<S>()) {
|
|
Detail::collect_transitions(static_cast<S&>(base),
|
|
table);
|
|
return true;
|
|
}
|
|
return false;
|
|
});
|
|
}
|
|
|
|
template <typename S> void initial()
|
|
{
|
|
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)});
|
|
}
|
|
|
|
/// Make `S` the initial state (registers it if needed). Idle-only.
|
|
template <typename S> void set_initial()
|
|
{
|
|
if (m_status.load() != Status::Idle) {
|
|
return;
|
|
}
|
|
add<S>();
|
|
m_initial = &typeid(S);
|
|
}
|
|
|
|
/// Unregister a state. Idle-only (running indices are fixed). If it
|
|
/// was the initial state, the initial falls back to the first
|
|
/// remaining state (or none).
|
|
template <typename S> void remove()
|
|
{
|
|
if (m_status.load() != Status::Idle) {
|
|
return;
|
|
}
|
|
const std::type_index key{typeid(S)};
|
|
const auto idxIt = m_index.find(key);
|
|
if (idxIt == m_index.end()) {
|
|
return;
|
|
}
|
|
const int idx = idxIt->second;
|
|
m_name_to_type.erase(m_names[static_cast<std::size_t>(idx)]);
|
|
m_names.erase(m_names.begin() + idx);
|
|
m_factories.erase(key);
|
|
m_drivers.erase(key);
|
|
m_collectors.erase(key);
|
|
m_index.erase(idxIt);
|
|
// Re-pack the indices of states that followed S.
|
|
for (auto& [k, v] : m_index) {
|
|
if (v > idx) {
|
|
--v;
|
|
}
|
|
}
|
|
if (m_initial == &typeid(S)) {
|
|
m_initial = m_names.empty()
|
|
? nullptr
|
|
: m_name_to_type.at(m_names.front());
|
|
}
|
|
}
|
|
|
|
/// Swap state `S` for `T`, preserving the initial pointer if S was
|
|
/// it. Idle-only.
|
|
template <typename S, typename T> void replace()
|
|
{
|
|
if (m_status.load() != Status::Idle) {
|
|
return;
|
|
}
|
|
const bool was_initial = (m_initial == &typeid(S));
|
|
remove<S>();
|
|
add<T>();
|
|
if (was_initial) {
|
|
m_initial = &typeid(T);
|
|
}
|
|
}
|
|
|
|
// ── 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();
|
|
}
|
|
}
|
|
|
|
// Function templates so the typed Outcome resolves where Derived is
|
|
// complete (CRTP). Call sites stay `fsm.wait()` / `run_blocking()`.
|
|
template <typename D = Derived> Outcome<D> 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<D>();
|
|
}
|
|
|
|
template <typename D = Derived> Outcome<D> run_blocking()
|
|
{
|
|
start();
|
|
return wait<D>();
|
|
}
|
|
|
|
/// The system fault (if any) — a programming error caught by the
|
|
/// engine, separate from a typed Failure result.
|
|
[[nodiscard]] std::optional<FsmError> system_error() const
|
|
{
|
|
return m_system_error;
|
|
}
|
|
|
|
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 ||
|
|
s == Status::Faulted;
|
|
}
|
|
|
|
[[nodiscard]] Status status() const noexcept
|
|
{
|
|
return m_status.load();
|
|
}
|
|
|
|
void stop()
|
|
{
|
|
if (m_owns_ctx && m_ctx) {
|
|
m_ctx->stop();
|
|
}
|
|
}
|
|
|
|
/// Return a finished (or idle) machine to Idle so it can run
|
|
/// again: drops the owned execution context, clears the
|
|
/// outcome/current-state/jump. No-op while Running.
|
|
void reset()
|
|
{
|
|
if (m_status.load() == Status::Running) {
|
|
return;
|
|
}
|
|
if (m_owns_ctx && m_ctx) {
|
|
m_ctx->stop();
|
|
}
|
|
m_ctx.reset();
|
|
m_owns_ctx = false;
|
|
m_current.store(-1, std::memory_order_release);
|
|
m_result_value.reset();
|
|
m_system_error.reset();
|
|
m_pending_result.reset();
|
|
m_jump.store(nullptr, std::memory_order_release);
|
|
m_step = 0;
|
|
m_status.store(Status::Idle, std::memory_order_release);
|
|
}
|
|
|
|
/// reset() then start() from the initial state.
|
|
void restart()
|
|
{
|
|
reset();
|
|
start();
|
|
}
|
|
|
|
/// reset(), make `S` the initial state, then start().
|
|
template <typename S> void restart_at()
|
|
{
|
|
reset();
|
|
m_initial = &typeid(S);
|
|
start();
|
|
}
|
|
|
|
/// Pause / resume event processing (best-effort: a state already
|
|
/// running finishes; further progress waits). Events posted while
|
|
/// paused buffer until resume().
|
|
void pause()
|
|
{
|
|
if (m_ctx) {
|
|
m_ctx->set_paused(true);
|
|
}
|
|
}
|
|
void resume()
|
|
{
|
|
if (m_ctx) {
|
|
m_ctx->set_paused(false);
|
|
}
|
|
}
|
|
|
|
// ── events ────────────────────────────────────────────────────
|
|
template <typename E> void post(E event)
|
|
{
|
|
if (!m_ctx) {
|
|
return;
|
|
}
|
|
m_ctx->post(Detail::EventEnvelope{&typeid(E),
|
|
std::any{std::move(event)}});
|
|
}
|
|
|
|
/// Fluent post: send one or several events in one call.
|
|
/// fsm.send(Go{5}); fsm.send(Go{5}, Stop{});
|
|
template <typename... Es> void send(Es&&... events)
|
|
{
|
|
(post(std::forward<Es>(events)), ...);
|
|
}
|
|
|
|
/// Request a jump to any registered state `S` from outside the
|
|
/// machine. Race-safe; applied at the next transition boundary
|
|
/// (a running state isn't preempted — coroutines aren't
|
|
/// interruptible mid-flight).
|
|
template <typename S> void jump()
|
|
{
|
|
m_jump.store(&typeid(S), std::memory_order_release);
|
|
if (m_ctx) {
|
|
m_ctx->nudge();
|
|
}
|
|
}
|
|
|
|
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<Detail::OutcomeOf<Sub>>
|
|
run_child(Args&&... args)
|
|
{
|
|
Sub child{std::forward<Args>(args)...};
|
|
child.attach(m_ctx, m_services);
|
|
co_await child.drive();
|
|
co_return child.template take_outcome<Sub>();
|
|
}
|
|
|
|
/// 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>
|
|
[[nodiscard]] Coro::Task<Detail::OutcomeOf<Sub>>
|
|
run_region(Resume resume = Resume::Initial)
|
|
{
|
|
Sub child;
|
|
// History: resume at the sub-state this region last reached.
|
|
// restore() must run before attach() (which marks Running).
|
|
if (resume == Resume::History) {
|
|
const auto it =
|
|
m_region_history.find(std::type_index{typeid(Sub)});
|
|
if (it != m_region_history.end()) {
|
|
(void)child.restore(it->second);
|
|
}
|
|
}
|
|
child.attach(m_ctx, m_services);
|
|
m_region_probe = [&child] { return child.state_path(); };
|
|
co_await child.drive();
|
|
m_region_probe = nullptr;
|
|
// Snapshot the leaf it reached for a later History re-entry.
|
|
m_region_history[std::type_index{typeid(Sub)}] =
|
|
child.serialize();
|
|
co_return child.template take_outcome<Sub>();
|
|
}
|
|
|
|
/// Orthogonal regions: run `Subs...` concurrently on the shared
|
|
/// executor (interleaved — when one parks on an event, another
|
|
/// runs) and join all, yielding a tuple of their Outcomes. Children
|
|
/// are default-constructed and share this machine's
|
|
/// events/services.
|
|
template <typename... Subs>
|
|
[[nodiscard]] Coro::Task<std::tuple<Detail::OutcomeOf<Subs>...>>
|
|
run_parallel()
|
|
{
|
|
auto children = std::make_unique<std::tuple<Subs...>>();
|
|
std::apply(
|
|
[&](auto&... c) { (c.attach(m_ctx, m_services), ...); },
|
|
*children);
|
|
|
|
struct Latch {
|
|
int remaining;
|
|
std::coroutine_handle<> waiter{};
|
|
Async::Executor* exec;
|
|
void arrive()
|
|
{
|
|
if (--remaining == 0 && waiter) {
|
|
exec->post(waiter);
|
|
}
|
|
}
|
|
};
|
|
auto latch = std::make_shared<Latch>(
|
|
static_cast<int>(sizeof...(Subs)),
|
|
std::coroutine_handle<>{}, &m_ctx->executor());
|
|
|
|
std::apply(
|
|
[&](auto&... c) {
|
|
(Async::spawn(m_ctx->executor(),
|
|
[](auto& child, std::shared_ptr<Latch> l)
|
|
-> Coro::Task<void> {
|
|
co_await child.drive();
|
|
l->arrive();
|
|
}(c, latch)),
|
|
...);
|
|
},
|
|
*children);
|
|
|
|
struct Awaiter {
|
|
std::shared_ptr<Latch> latch;
|
|
[[nodiscard]] bool await_ready() const noexcept
|
|
{
|
|
return latch->remaining == 0;
|
|
}
|
|
void await_suspend(std::coroutine_handle<> h) const
|
|
{
|
|
latch->waiter = h;
|
|
}
|
|
void await_resume() const noexcept {}
|
|
};
|
|
co_await Awaiter{latch};
|
|
|
|
co_return std::apply(
|
|
[](auto&... c) {
|
|
return std::tuple<Detail::OutcomeOf<Subs>...>{
|
|
c.template take_outcome<Subs>()...};
|
|
},
|
|
*children);
|
|
}
|
|
|
|
/// Like run_parallel but resolves on the **first** child to finish,
|
|
/// yielding a std::variant<Subs::Outcome...> holding the winner's
|
|
/// outcome. The losers keep running cooperatively (coroutines
|
|
/// aren't preemptible) — the children are kept alive by the spawned
|
|
/// tasks until they finish, so a loser parked forever leaks its
|
|
/// frame until the machine stops. Document at call sites.
|
|
template <typename... Subs>
|
|
[[nodiscard]] Coro::Task<std::variant<Detail::OutcomeOf<Subs>...>>
|
|
run_parallel_any()
|
|
{
|
|
// Shared so losers (which outlive this call) keep it alive.
|
|
auto children = std::make_shared<std::tuple<Subs...>>();
|
|
std::apply(
|
|
[&](auto&... c) { (c.attach(m_ctx, m_services), ...); },
|
|
*children);
|
|
|
|
struct Latch {
|
|
int first{-1};
|
|
std::coroutine_handle<> waiter{};
|
|
Async::Executor* exec;
|
|
void arrive(int idx)
|
|
{
|
|
if (first < 0) {
|
|
first = idx;
|
|
if (waiter) {
|
|
exec->post(waiter);
|
|
}
|
|
}
|
|
}
|
|
};
|
|
auto latch = std::make_shared<Latch>(
|
|
-1, std::coroutine_handle<>{}, &m_ctx->executor());
|
|
|
|
int idx = 0;
|
|
std::apply(
|
|
[&](auto&... c) {
|
|
(
|
|
[&] {
|
|
const int my = idx++;
|
|
Async::spawn(
|
|
m_ctx->executor(),
|
|
[](auto& child,
|
|
std::shared_ptr<std::tuple<Subs...>>
|
|
keep,
|
|
std::shared_ptr<Latch>
|
|
l,
|
|
int i) -> Coro::Task<void> {
|
|
co_await child.drive();
|
|
l->arrive(i);
|
|
(void)keep;
|
|
}(c, children, latch, my));
|
|
}(),
|
|
...);
|
|
},
|
|
*children);
|
|
|
|
struct Awaiter {
|
|
std::shared_ptr<Latch> latch;
|
|
[[nodiscard]] bool await_ready() const noexcept
|
|
{
|
|
return latch->first >= 0;
|
|
}
|
|
void await_suspend(std::coroutine_handle<> h) const
|
|
{
|
|
latch->waiter = h;
|
|
}
|
|
void await_resume() const noexcept {}
|
|
};
|
|
co_await Awaiter{latch};
|
|
|
|
const auto winner = static_cast<std::size_t>(latch->first);
|
|
co_return [&]<std::size_t... I>(std::index_sequence<I...>)
|
|
-> std::variant<Detail::OutcomeOf<Subs>...> {
|
|
std::variant<Detail::OutcomeOf<Subs>...> v;
|
|
((I == winner ? (void)(v.template emplace<I>(
|
|
std::get<I>(*children)
|
|
.template take_outcome<Subs>()))
|
|
: void()),
|
|
...);
|
|
return v;
|
|
}(std::index_sequence_for<Subs...>{});
|
|
}
|
|
|
|
/// Build a Launch step: run `Sub` (constructed from `args`) on this
|
|
/// 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)
|
|
{
|
|
if constexpr (requires { typename Derived::States; }) {
|
|
static_assert(
|
|
Derived::States::template contains<Next>(),
|
|
"startMachine<Sub, Next>: Next is not in States<...>");
|
|
}
|
|
using Init = Detail::InitialStateOf<Sub>;
|
|
auto launcher =
|
|
[this, ... data = std::forward<Args>(
|
|
args)]() mutable -> Coro::Task<LaunchResult> {
|
|
// Run Sub on the shared executor. Startup data (if any) is
|
|
// delivered to Sub's initial-state startup-entry via an
|
|
// injector, not the constructor.
|
|
Sub child;
|
|
child.attach(m_ctx, m_services);
|
|
if constexpr (sizeof...(Args) > 0) {
|
|
child.m_startup_injector =
|
|
[... d = std::move(data)](
|
|
Detail::StateBase& base) mutable
|
|
-> Coro::Task<Step> {
|
|
return Detail::invoke_startup<Init>(
|
|
static_cast<Init&>(base), std::move(d)...);
|
|
};
|
|
}
|
|
co_await child.drive();
|
|
LaunchResult lr;
|
|
switch (child.m_status.load(std::memory_order_acquire)) {
|
|
case Status::Succeeded:
|
|
lr.kind = LaunchResult::Kind::Success;
|
|
lr.value = std::move(child.m_result_value);
|
|
break;
|
|
case Status::Failed:
|
|
lr.kind = LaunchResult::Kind::Failure;
|
|
lr.failure = std::move(child.m_result_value);
|
|
break;
|
|
default:
|
|
lr.kind = LaunchResult::Kind::Fault;
|
|
lr.fault = child.m_system_error.value_or(
|
|
FsmError{"sub-machine fault"});
|
|
break;
|
|
}
|
|
co_return lr;
|
|
};
|
|
Step::Dispatch dispatch =
|
|
[](Detail::StateBase& base,
|
|
LaunchResult lr) -> Coro::Task<Step> {
|
|
return Detail::dispatch_result<Next, Sub>(
|
|
static_cast<Next&>(base), std::move(lr));
|
|
};
|
|
return Step::launch(typeid(Next), std::move(launcher),
|
|
std::move(dispatch));
|
|
}
|
|
|
|
// ── observation ───────────────────────────────────────────────
|
|
[[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);
|
|
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;
|
|
}
|
|
|
|
/// 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>
|
|
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);
|
|
}
|
|
}
|
|
}
|
|
|
|
// Record a system fault (programming error) — separate from a
|
|
// typed Failure result. Sets status Faulted + system_error.
|
|
void fault(std::string message)
|
|
{
|
|
m_system_error = FsmError{std::move(message)};
|
|
Void::Log::error("Fsm", "system fault: {}",
|
|
m_system_error->message);
|
|
m_status.store(Status::Faulted, std::memory_order_release);
|
|
}
|
|
|
|
// The state loop. Type-erased: stores the Success/Failure payload
|
|
// in m_result_value and sets m_status; the typed Outcome is rebuilt
|
|
// in take_outcome() where Derived is complete. Runs on the
|
|
// executor.
|
|
Coro::Task<void> drive()
|
|
{
|
|
const std::type_info* cur = m_initial;
|
|
if (cur == nullptr) {
|
|
fault("no initial state");
|
|
co_return;
|
|
}
|
|
bool first = true;
|
|
for (;;) {
|
|
// Apply an external jump<S>() at this transition boundary.
|
|
if (const auto* j =
|
|
m_jump.exchange(nullptr, std::memory_order_acq_rel);
|
|
j != nullptr) {
|
|
cur = j;
|
|
m_pending_result.reset();
|
|
m_pending_dispatch = nullptr;
|
|
}
|
|
const auto it = m_factories.find(std::type_index{*cur});
|
|
if (it == m_factories.end()) {
|
|
fault("transition to unregistered state");
|
|
co_return;
|
|
}
|
|
set_current(cur);
|
|
auto state = it->second();
|
|
co_await state->on_enter();
|
|
// Decide how the state runs: a launched sub's result (via
|
|
// the bound dispatcher), the startup injector for the first
|
|
// state, or the signature-inferred driver thunk.
|
|
Step step;
|
|
if (m_pending_dispatch) {
|
|
LaunchResult pending = std::move(*m_pending_result);
|
|
auto dispatch = std::move(m_pending_dispatch);
|
|
m_pending_result.reset();
|
|
m_pending_dispatch = nullptr;
|
|
if (pending.kind == LaunchResult::Kind::Fault) {
|
|
fault(std::move(pending.fault.message));
|
|
co_return;
|
|
}
|
|
step = co_await dispatch(*state, std::move(pending));
|
|
} else if (first && m_startup_injector) {
|
|
auto inject = std::move(m_startup_injector);
|
|
m_startup_injector = nullptr;
|
|
step = co_await inject(*state);
|
|
} else {
|
|
step = co_await m_drivers.at(std::type_index{*cur})(
|
|
*state);
|
|
}
|
|
first = false;
|
|
co_await state->on_exit();
|
|
fire_after(current_state());
|
|
switch (step.kind()) {
|
|
case Step::Kind::Transition:
|
|
cur = step.target();
|
|
continue;
|
|
case Step::Kind::Launch:
|
|
m_pending_result.emplace(
|
|
co_await step.run_launch());
|
|
m_pending_dispatch = step.take_dispatch();
|
|
cur = step.target();
|
|
continue;
|
|
case Step::Kind::Success:
|
|
m_result_value = std::move(step.payload());
|
|
m_status.store(Status::Succeeded,
|
|
std::memory_order_release);
|
|
co_return;
|
|
case Step::Kind::Fail:
|
|
m_result_value = std::move(step.payload());
|
|
m_status.store(Status::Failed,
|
|
std::memory_order_release);
|
|
co_return;
|
|
case Step::Kind::Fault:
|
|
fault(std::any_cast<FsmError>(step.payload())
|
|
.message);
|
|
co_return;
|
|
}
|
|
}
|
|
}
|
|
|
|
Coro::Task<void> driver()
|
|
{
|
|
co_await drive();
|
|
if (m_owns_ctx) {
|
|
m_ctx->finish();
|
|
}
|
|
}
|
|
|
|
// Rebuild the typed Outcome from the type-erased result. Function
|
|
// template so SuccessOf/FailureOf<Derived> resolve where Derived is
|
|
// complete. A system fault yields a default-constructed error arm
|
|
// (consult system_error()).
|
|
template <typename D = Derived> Outcome<D> take_outcome()
|
|
{
|
|
using Succ = Detail::SuccessOf<D>;
|
|
using Fail = Detail::FailureOf<D>;
|
|
using Err = Detail::ErrArm<Fail>;
|
|
switch (m_status.load(std::memory_order_acquire)) {
|
|
case Status::Succeeded:
|
|
if constexpr (std::is_void_v<Succ>) {
|
|
return Outcome<D>{};
|
|
} else {
|
|
return Outcome<D>{
|
|
std::any_cast<Succ>(m_result_value)};
|
|
}
|
|
case Status::Failed:
|
|
if constexpr (std::is_void_v<Fail>) {
|
|
return Outcome<D>{std::unexpect, std::monostate{}};
|
|
} else {
|
|
return Outcome<D>{
|
|
std::unexpect,
|
|
std::any_cast<Fail>(m_result_value)};
|
|
}
|
|
default: // Faulted / not finished
|
|
static_assert(
|
|
std::is_default_constructible_v<Err>,
|
|
"a machine with a non-default-constructible "
|
|
"Failure "
|
|
"cannot represent a system fault in its Outcome; "
|
|
"check system_error()");
|
|
return Outcome<D>{std::unexpect, Err{}};
|
|
}
|
|
}
|
|
|
|
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;
|
|
// Per-state signature-inferred driver thunk (entry / reactive).
|
|
std::unordered_map<std::type_index, std::function<Coro::Task<Step>(
|
|
Detail::StateBase&)>>
|
|
m_drivers;
|
|
// Per-state describe() collector (reactive table, if any).
|
|
std::unordered_map<
|
|
std::type_index,
|
|
std::function<bool(Detail::StateBase&, TransitionTable&)>>
|
|
m_collectors;
|
|
std::unordered_map<std::type_index, int> m_index;
|
|
std::vector<std::string> m_names;
|
|
std::unordered_map<std::string, const std::type_info*>
|
|
m_name_to_type;
|
|
const std::type_info* m_initial{nullptr};
|
|
|
|
std::atomic<int> m_current{-1};
|
|
std::atomic<Status> m_status{Status::Idle};
|
|
// Type-erased finished result (Success or Failure payload), rebuilt
|
|
// typed in take_outcome(); system faults in m_system_error.
|
|
std::any m_result_value;
|
|
std::optional<FsmError> m_system_error;
|
|
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;
|
|
|
|
// Per-region-type snapshot of the leaf last reached, for
|
|
// Resume::History re-entry.
|
|
std::unordered_map<std::type_index, Json::Value> m_region_history;
|
|
|
|
// 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;
|
|
|
|
// Seeds the initial state's startup-entry with launch data (set by
|
|
// the parent's launcher before driving this machine).
|
|
std::function<Coro::Task<Step>(Detail::StateBase&)>
|
|
m_startup_injector;
|
|
|
|
// External jump request (jump<S>()); applied by drive() at the
|
|
// next transition boundary.
|
|
std::atomic<const std::type_info*> m_jump{nullptr};
|
|
};
|
|
|
|
} // namespace Void::Fsm
|