Files
Library/include/Void/Fsm/Machine.hpp
T
faumarayandClaude Opus 4.8 80293ee56f Add async/resilience/reflection primitives + FSM v2 rewrite
A round of new universal capabilities (all generic — templated/reflection
based, no app coupling), verified by the test suite (1103 passing):

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

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

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

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 15:45:16 +03:00

1403 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/Result.hpp>
#include <Void/Fsm/Detail/Roles.hpp>
#include <Void/Fsm/Detail/StateList.hpp>
#include <Void/Fsm/Detail/TypeName.hpp>
#include <Void/Fsm/StateKey.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
{
/// 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
// and declare the states as a nested struct of forward declarations:
// struct States { struct FirstState; struct SecondState; … };
// defined out-of-line (typically in a .cpp), each deriving the single
// `State`. The Machine base auto-registers them by reflecting `States`
// (Detail/StateList.hpp) — the first declared state is the initial one
// unless `using Initial = S;`. All behaviour lives inside a state: the
// engine infers each state's role from its member signatures (entry /
// startup-entry / continuation handlers); states reach their machine (data
// + sub-methods) via self(). Events are handled imperatively inside an
// entry (co_await await_event<E>()) — there is no declarative transition
// table. Result types are the nested `Success`/`Failure` (default void).
//
// // header
// class Login : public Void::Fsm::Machine<Login> {
// public:
// using Success = Token;
// int attempts = 0;
// struct States { struct Check; };
// };
// // source (namespace scope)
// struct Login::States::Check : Login::State { // entry by signature
// Coro::Task<StateKey>> run() {
// if (++self().attempts > 3) co_return fail();
// co_return self().service<IAuth>().ok() ? succeed(Token{})
// : next<Check>();
// }
// };
template <typename Derived> class Machine
{
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 a `States` list.
template <typename S> [[nodiscard]] StateKey next() const
{
if constexpr (requires { typename Derived::States; }) {
static_assert(Detail::states_contains<
typename Derived::States, S>(),
"next<S>: S is not in this machine's "
"States { … } list");
}
return StateKey::transition(typeid(S));
}
/// Transition to a state registered dynamically
/// (add<S>()/add_if<S>()), skipping the static check.
template <typename S>
[[nodiscard]] StateKey next_dynamic() const
{
return StateKey::transition(typeid(S));
}
/// Free jump to any registered state — no declared
/// transition required ("each state can be moved to
/// another state"). Like next_dynamic, skips the
/// States{ … } compile-time check; runtime-fails only if S
/// was never registered.
template <typename S>
[[nodiscard]] StateKey goto_state() const
{
return StateKey::transition(typeid(S));
}
/// Route to a fallback state if `step` is a failure,
/// otherwise pass it through — for error policies:
/// co_return next_or<Recovery>(co_await try_work());
template <typename S>
[[nodiscard]] StateKey next_or(StateKey step) const
{
if (step.kind() == StateKey::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]] StateKey succeed() const
requires std::is_void_v<Detail::SuccessOf<Derived>>
{
return StateKey::success(std::any{});
}
template <typename V>
[[nodiscard]] StateKey succeed(V&& value) const
requires(!std::is_void_v<Detail::SuccessOf<Derived>>)
{
return StateKey::success(
std::any{Detail::SuccessOf<Derived>(
std::forward<V>(value))});
}
/// Finish with the machine's typed Failure result (nested
/// `Failure`; nullary when it is void).
[[nodiscard]] StateKey fail() const
requires std::is_void_v<Detail::FailureOf<Derived>>
{
return StateKey::failure(std::any{});
}
template <typename V>
[[nodiscard]] StateKey fail(V&& value) const
requires(!std::is_void_v<Detail::FailureOf<Derived>>)
{
return StateKey::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`
/// (Sub succeeded) or `ChildFailure` (Sub failed):
/// co_return startMachine<Login, AfterLogin>(seed);
template <typename Sub, typename Next, typename... Args>
[[nodiscard]] StateKey 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
// State/Coro::Task<StateKey>>,
// no params (a startup-data overload may take
// the sub's startup argument);
// - continuation : members taking `ChildSuccess` /
// `ChildFailure` (the sub's typed result, read
// via .as<T>(), after `startMachine<Sub,
// This>`).
//
// Events are handled imperatively inside an entry:
// struct Idle : State { // entry
// Coro::Task<StateKey> run() {
// auto e = co_await await_any<Go, Stop>();
// co_return std::holds_alternative<Go>(e) ? next<Running>()
// : next<Done>(); }
// };
// struct After : State { // continuation
// Coro::Task<StateKey> ok(ChildSuccess s){ ... }
// Coro::Task<StateKey> no(ChildFailure f){ ... } };
// ── construction ──────────────────────────────────────────────
explicit Machine(Options options = {}) : m_options(options)
{
if constexpr (requires { typename Derived::States; }) {
Detail::register_states_from<typename Derived::States>(
*this);
using Init = Detail::InitialStateOf<Derived>;
if constexpr (!std::is_void_v<Init>) {
m_initial = &typeid(Init);
}
}
}
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 (runs the state's entry).
m_drivers.emplace(key, Detail::make_driver<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)});
}
/// 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_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 = &registry;
}
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);
// Own the driver coroutine (rather than detaching it) so a
// machine stopped while parked on an event can destroy the
// suspended frame chain instead of leaking it.
m_driver.emplace(driver());
m_ctx->executor().post(m_driver->handle());
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();
}
// The worker is joined now (no concurrent resume), so destroy
// the owned driver — this cascade-destroys the suspended
// coroutine chain (a machine parked on an event) instead of
// leaking it. Safe on a finished coroutine too.
m_driver.reset();
}
/// 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_driver.reset(); // destroy the (possibly parked) driver chain
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)}});
}
/// Re-post an already type-erased event (used by the reactive loop
/// to re-inject deferred events after a transition).
void repost(Detail::EventEnvelope env)
{
if (m_ctx) {
m_ctx->post(std::move(env));
}
}
/// 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]] StateKey start_machine(Args&&... args)
{
if constexpr (requires { typename Derived::States; }) {
static_assert(
Detail::states_contains<typename Derived::States,
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<StateKey> {
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;
};
StateKey::Dispatch dispatch =
[](Detail::StateBase& base,
LaunchResult lr) -> Coro::Task<StateKey> {
return Detail::dispatch_result<Next, Sub>(
static_cast<Next&>(base), std::move(lr));
};
return StateKey::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 ───────────────────────────────────
// StateInfo is namespace-scope (Detail/Introspect.hpp).
/// Structural description: every registered state (name + whether
/// it is the initial state). Transitions are chosen imperatively
/// inside each state's entry, so they are not statically knowable —
/// the description is node-level (no edges).
[[nodiscard]] std::vector<StateInfo> describe()
{
std::vector<StateInfo> out;
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);
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*/) {}
/// Machine-level entry/exit hooks (default no-ops; override for
/// machine-wide setup/teardown). `on_machine_enter()` runs once
/// before the initial state is entered; `on_machine_exit()` runs
/// once when the machine reaches a terminal outcome (Success,
/// Failure, or a system Fault). Per-state entry/exit lives on the
/// state itself (State::on_enter()/on_exit()).
virtual void on_machine_enter() {}
virtual void on_machine_exit() {}
/// Called on every transition (and the initial entry). Default
/// logs at debug; override for custom observability.
virtual void on_transition(std::string_view from,
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 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;
}
on_machine_enter();
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");
on_machine_exit();
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.
StateKey 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));
on_machine_exit();
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 StateKey::Kind::Transition:
cur = step.target();
continue;
case StateKey::Kind::Launch:
m_pending_result.emplace(
co_await step.run_launch());
m_pending_dispatch = step.take_dispatch();
cur = step.target();
continue;
case StateKey::Kind::Success:
m_result_value = std::move(step.payload());
m_status.store(Status::Succeeded,
std::memory_order_release);
on_machine_exit();
co_return;
case StateKey::Kind::Fail:
m_result_value = std::move(step.payload());
m_status.store(Status::Failed,
std::memory_order_release);
on_machine_exit();
co_return;
case StateKey::Kind::Fault:
fault(std::any_cast<FsmError>(step.payload())
.message);
on_machine_exit();
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 (runs the entry).
std::unordered_map<
std::type_index,
std::function<Coro::Task<StateKey>(Detail::StateBase&)>>
m_drivers;
std::unordered_map<std::type_index, int> m_index;
std::vector<std::string> m_names;
std::unordered_map<std::string, const std::type_info*>
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;
StateKey::Dispatch m_pending_dispatch;
// Seeds the initial state's startup-entry with launch data (set by
// the parent's launcher before driving this machine).
std::function<Coro::Task<StateKey>(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};
// The owned top-level driver coroutine (worker mode). Holding it
// (rather than detaching via Async::spawn) lets stop() destroy the
// suspended frame chain of a machine parked on an event.
std::optional<Coro::Task<void>> m_driver;
};
template <typename Derived> using State = Machine<Derived>::State;
} // namespace Void::Fsm