Files
Library/include/Void/Fsm/Detail/Roles.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

219 lines
7.9 KiB
C++

#pragma once
#include <Void/Async/Task.hpp>
#include <Void/Core/Meta.hpp>
#include <Void/Fsm/Detail/Engine.hpp>
#include <Void/Fsm/Detail/Result.hpp>
#include <Void/Fsm/Detail/StateList.hpp>
#include <Void/Fsm/Machine.hpp>
#include <Void/Fsm/StateKey.hpp>
#include <algorithm>
#include <any>
#include <chrono>
#include <concepts>
#include <optional>
#include <type_traits>
#include <typeinfo>
#include <utility>
#include <vector>
#if __has_include(<meta>)
#include <meta>
#endif
// Signature-inferred state roles. There is ONE state base (`State`); the engine
// discovers what each state does purely from its member signatures via P2996 —
// no `override`, no framework-mandated names:
// - entry : a member returning State / Coro::Task<StateKey>>, no
// params
// - startup-entry: the same taking the sub-machine's startup-data argument
// - result handlers (continuation): members taking `ChildSuccess` /
// `ChildFailure` (the type-erased result structs below)
// All discovery is invocability-based (types known at the generation site), so
// no parameter-type reflection (P3096) is required. Event handling is
// imperative inside an entry (co_await await_event<E>()), so there is no
// reactive role.
namespace Void::Fsm
{
/// The success value of a launched sub-machine, handed to a continuation
/// handler written `ok(ChildSuccess s)`. The sub's typed Success is read
/// with `s.as<T>()` (the value is empty for a void-result sub).
struct ChildSuccess {
std::any value;
template <typename T> [[nodiscard]] T as() const
{
return std::any_cast<T>(value);
}
};
/// The failure value of a launched sub-machine, handed to `no(ChildFailure
/// f)`. The sub's typed Failure is read with `f.as<T>()` (empty for void).
struct ChildFailure {
std::any value;
template <typename T> [[nodiscard]] T as() const
{
return std::any_cast<T>(value);
}
};
/// Marker to designate a state's entry when several members match the entry
/// signature: annotate the chosen one `[[= Void::Fsm::entry]]`. Unmarked,
/// the first-declared matching member is used.
inline constexpr struct EntryTag {
} entry;
namespace Detail
{
namespace Coro = Void::Coro;
namespace meta = std::meta;
// InitialStateOf / FirstStateOf live in Detail/StateList.hpp (they
// reflect the nested `struct States { … }`).
/// True if member `m` carries the `[[= Void::Fsm::entry]]` annotation.
/// Routed through the shared Void::Meta annotation helper.
consteval bool is_entry_marked(meta::info m)
{
return Void::Meta::has_annotation<EntryTag>(m);
}
/// Wrap a ready State in a Task. (The reflection selectors below must
/// NOT be coroutines — `template for` + member splicing fails inside a
/// coroutine body in this build — so they return a Task instead.)
inline Coro::Task<StateKey> ready_task(StateKey s) { co_return s; }
// ── entry (0-arg member returning StateKey / Task<StateKey>) ──────
// When several members match, one annotated `[[= Fsm::entry]]` wins;
// otherwise the first-declared match is used.
template <typename S> Coro::Task<StateKey> invoke_entry(S& s)
{
static constexpr auto members = std::define_static_array(
meta::members_of(^^S, meta::access_context::current()));
// Pass 1: a member annotated [[= Fsm::entry]] takes precedence.
template for (constexpr auto m : members)
{
if constexpr (is_entry_marked(m) &&
requires(S& x) { x.[:m:](); }) {
using R = decltype(std::declval<S&>().[:m:]());
if constexpr (std::is_same_v<R, StateKey>) {
return ready_task(s.[:m:]());
} else if constexpr (std::is_same_v<R,
Coro::Task<StateKey>>) {
return s.[:m:]();
}
}
}
// Pass 2: the first-declared matching member.
template for (constexpr auto m : members)
{
if constexpr (requires(S& x) { x.[:m:](); }) {
using R = decltype(std::declval<S&>().[:m:]());
if constexpr (std::is_same_v<R, StateKey>) {
return ready_task(s.[:m:]());
} else if constexpr (std::is_same_v<R,
Coro::Task<StateKey>>) {
return s.[:m:]();
}
}
}
return ready_task(StateKey::fault(FsmError{
"state has no entry (a no-arg method returning StateKey)"}));
}
// ── startup-entry (member taking the startup-data argument[s]) ────
// Same precedence as invoke_entry: an annotated `[[= Fsm::entry]]`
// data-taking member wins, else the first-declared one; if none takes
// the data, fall back to the plain (nullary) entry.
template <typename S, typename... DataT>
Coro::Task<StateKey> invoke_startup(S& s, DataT... data)
{
static constexpr auto members = std::define_static_array(
meta::members_of(^^S, meta::access_context::current()));
// Pass 1: an annotated data-taking member takes precedence.
template for (constexpr auto m : members)
{
if constexpr (is_entry_marked(m) &&
requires(S& x, DataT... d) { x.[:m:](d...); }) {
using R = decltype(std::declval<S&>().[:m:](
std::declval<DataT>()...));
if constexpr (std::is_same_v<R, StateKey>) {
return ready_task(s.[:m:](std::move(data)...));
} else if constexpr (std::is_same_v<R,
Coro::Task<StateKey>>) {
return s.[:m:](std::move(data)...);
}
}
}
// Pass 2: the first-declared data-taking member.
template for (constexpr auto m : members)
{
if constexpr (requires(S& x, DataT... d) { x.[:m:](d...); }) {
using R = decltype(std::declval<S&>().[:m:](
std::declval<DataT>()...));
if constexpr (std::is_same_v<R, StateKey>) {
return ready_task(s.[:m:](std::move(data)...));
} else if constexpr (std::is_same_v<R,
Coro::Task<StateKey>>) {
return s.[:m:](std::move(data)...);
}
}
}
// No data-taking entry: fall back to the plain entry.
return invoke_entry(s);
}
// ── continuation handler (member taking a ChildSuccess/Failure box)
template <typename S, typename Box>
Coro::Task<StateKey> invoke_handler(S& s, Box box)
{
static constexpr auto members = std::define_static_array(
meta::members_of(^^S, meta::access_context::current()));
template for (constexpr auto m : members)
{
if constexpr (requires(S& x, Box b) { x.[:m:](b); }) {
using R =
decltype(std::declval<S&>().[:m:](std::declval<Box>()));
if constexpr (std::is_same_v<R, StateKey>) {
return ready_task(s.[:m:](std::move(box)));
} else if constexpr (std::is_same_v<R,
Coro::Task<StateKey>>) {
return s.[:m:](std::move(box));
}
}
}
return ready_task(StateKey::fault(
FsmError{"continuation has no handler for this sub-machine "
"result (ChildSuccess / ChildFailure)"}));
}
/// Dispatch a sub-machine's LaunchResult into the Next state's
/// signature-matched handler (`ok(ChildSuccess)` / `no(ChildFailure)`).
/// The typed payload rides type-erased in the result struct's `value`;
/// the handler reads it with `.as<T>()`. (Sub is retained in the
/// signature so the call site stays `dispatch_result<Next, Sub>`.)
template <typename Next, typename Sub>
Coro::Task<StateKey> dispatch_result(Next& s, LaunchResult lr)
{
if (lr.kind == LaunchResult::Kind::Failure) {
return invoke_handler(s, ChildFailure{std::move(lr.failure)});
}
return invoke_handler(s, ChildSuccess{std::move(lr.value)});
}
/// Per-state driver thunk built at registration (S is complete): run
/// the state's entry. Event handling, timeouts, guards and deferral are
/// all expressed imperatively inside the entry (await_event / await_any
/// / await_event_for / delay), so there is no separate reactive driver.
template <typename S>
[[nodiscard]] std::function<Coro::Task<StateKey>(StateBase&)>
make_driver()
{
return [](StateBase& base) -> Coro::Task<StateKey> {
co_return co_await invoke_entry(static_cast<S&>(base));
};
}
} // namespace Detail
} // namespace Void::Fsm