Add async/resilience/reflection primitives + FSM v2 rewrite

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

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

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

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

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

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

No files matched your search

+112 -151
View File
@@ -6,11 +6,11 @@
#include <Void/Fsm/Detail/Awaiter.hpp>
#include <Void/Fsm/Detail/Engine.hpp>
#include <Void/Fsm/Detail/Introspect.hpp>
#include <Void/Fsm/Detail/Reactive.hpp>
#include <Void/Fsm/Detail/Result.hpp>
#include <Void/Fsm/Detail/Roles.hpp>
#include <Void/Fsm/Detail/StateList.hpp>
#include <Void/Fsm/Detail/TypeName.hpp>
#include <Void/Fsm/Step.hpp>
#include <Void/Fsm/StateKey.hpp>
#include <Void/Log/Log.hpp>
#include <Void/Service/Registry.hpp>
@@ -43,20 +43,6 @@
namespace Void::Fsm
{
/// Compile-time list of a machine's states. Declare it in the derived
/// machine to auto-register every state and enable compile-time
/// validation of next<S>() targets:
/// using States = Void::Fsm::States<Idle, Running, Done>;
/// The first entry is the initial state unless `using Initial = S;`.
template <typename... Ss> struct States {
static constexpr std::size_t size = sizeof...(Ss);
template <typename S> static constexpr bool contains()
{
return (std::is_same_v<S, Ss> || ...);
}
};
/// Options for a Machine (namespace scope to dodge the GCC
/// nested-default-arg trap).
struct MachineOptions {
@@ -76,25 +62,33 @@ namespace Void::Fsm
// ── Machine<Derived> ──────────────────────────────────────────────────
//
// Inheritance + coroutine workflow FSM, CRTP for typed access. Derive it,
// declare states as nested structs deriving the single `State`, list them
// in `using States = Fsm::States<...>`. The engine infers each state's role
// from member signatures (entry / reactive table / continuation handlers);
// states reach their machine (data + sub-methods) via self(). Result types
// are the nested `Success`/`Failure` (default void).
// Inheritance + coroutine workflow FSM, CRTP for typed access. Derive it
// and declare the states as a nested struct of forward declarations:
// struct States { struct FirstState; struct SecondState; … };
// defined out-of-line (typically in a .cpp), each deriving the single
// `State`. The Machine base auto-registers them by reflecting `States`
// (Detail/StateList.hpp) — the first declared state is the initial one
// unless `using Initial = S;`. All behaviour lives inside a state: the
// engine infers each state's role from its member signatures (entry /
// startup-entry / continuation handlers); states reach their machine (data
// + sub-methods) via self(). Events are handled imperatively inside an
// entry (co_await await_event<E>()) — there is no declarative transition
// table. Result types are the nested `Success`/`Failure` (default void).
//
// // header
// class Login : public Void::Fsm::Machine<Login> {
// public:
// using Success = Token;
// int attempts = 0;
// struct Check : State { // entry by signature
// Coro::Task<Step> run() {
// if (++self().attempts > 3) co_return fail();
// co_return self().service<IAuth>().ok() ? succeed(Token{})
// : next<Check>();
// }
// };
// using States = Void::Fsm::States<Check>;
// struct States { struct Check; };
// };
// // source (namespace scope)
// struct Login::States::Check : Login::State { // entry by signature
// Coro::Task<StateKey>> run() {
// if (++self().attempts > 3) co_return fail();
// co_return self().service<IAuth>().ok() ? succeed(Token{})
// : next<Check>();
// }
// };
template <typename Derived> class Machine
{
@@ -135,43 +129,44 @@ namespace Void::Fsm
protected:
/// Transition to another state. Validated at compile
/// time when the machine declares `using States`.
template <typename S> [[nodiscard]] Step next() const
/// time when the machine declares a `States` list.
template <typename S> [[nodiscard]] StateKey next() const
{
if constexpr (requires { typename Derived::States; }) {
static_assert(
Derived::States::template contains<S>(),
"next<S>: S is not in this machine's "
"States<...> list");
static_assert(Detail::states_contains<
typename Derived::States, S>(),
"next<S>: S is not in this machine's "
"States { … } list");
}
return Step::transition(typeid(S));
return StateKey::transition(typeid(S));
}
/// Transition to a state registered dynamically
/// (add<S>()/add_if<S>()), skipping the static check.
template <typename S>
[[nodiscard]] Step next_dynamic() const
[[nodiscard]] StateKey next_dynamic() const
{
return Step::transition(typeid(S));
return StateKey::transition(typeid(S));
}
/// Free jump to any registered state — no declared
/// transition required ("each state can be moved to
/// another state"). Like next_dynamic, skips the
/// States<...> compile-time check; runtime-fails only if S
/// States{ … } compile-time check; runtime-fails only if S
/// was never registered.
template <typename S> [[nodiscard]] Step goto_state() const
template <typename S>
[[nodiscard]] StateKey goto_state() const
{
return Step::transition(typeid(S));
return StateKey::transition(typeid(S));
}
/// Route to a fallback state if `step` is a failure,
/// otherwise pass it through — for error policies:
/// co_return next_or<Recovery>(co_await try_work());
template <typename S>
[[nodiscard]] Step next_or(Step step) const
[[nodiscard]] StateKey next_or(StateKey step) const
{
if (step.kind() == Step::Kind::Fail) {
if (step.kind() == StateKey::Kind::Fail) {
return next<S>();
}
return step;
@@ -209,32 +204,32 @@ namespace Void::Fsm
/// Finish with the machine's typed Success result (nested
/// `Success`; nullary when it is void).
[[nodiscard]] Step succeed() const
[[nodiscard]] StateKey succeed() const
requires std::is_void_v<Detail::SuccessOf<Derived>>
{
return Step::success(std::any{});
return StateKey::success(std::any{});
}
template <typename V>
[[nodiscard]] Step succeed(V&& value) const
[[nodiscard]] StateKey succeed(V&& value) const
requires(!std::is_void_v<Detail::SuccessOf<Derived>>)
{
return Step::success(
return StateKey::success(
std::any{Detail::SuccessOf<Derived>(
std::forward<V>(value))});
}
/// Finish with the machine's typed Failure result (nested
/// `Failure`; nullary when it is void).
[[nodiscard]] Step fail() const
[[nodiscard]] StateKey fail() const
requires std::is_void_v<Detail::FailureOf<Derived>>
{
return Step::failure(std::any{});
return StateKey::failure(std::any{});
}
template <typename V>
[[nodiscard]] Step fail(V&& value) const
[[nodiscard]] StateKey fail(V&& value) const
requires(!std::is_void_v<Detail::FailureOf<Derived>>)
{
return Step::failure(
return StateKey::failure(
std::any{Detail::FailureOf<Derived>{
std::forward<V>(value)}});
}
@@ -311,11 +306,11 @@ namespace Void::Fsm
/// initial-state startup-entry; shares this machine's
/// executor/events/services), then transition to `Next`.
/// When Sub finishes the engine calls Next's signature
/// -matched handler — a member taking `ChildSuccess auto`
/// (Sub succeeded) or `ChildFailure auto` (Sub failed):
/// -matched handler — a member taking `ChildSuccess`
/// (Sub succeeded) or `ChildFailure` (Sub failed):
/// co_return startMachine<Login, AfterLogin>(seed);
template <typename Sub, typename Next, typename... Args>
[[nodiscard]] Step startMachine(Args&&... args) const
[[nodiscard]] StateKey startMachine(Args&&... args) const
{
return m_machine->template start_machine<Sub, Next>(
std::forward<Args>(args)...);
@@ -337,37 +332,35 @@ namespace Void::Fsm
// There is a single base, `State`. The engine infers what each
// state does from member signatures (no `override`, no fixed
// names):
// - entry : a member returning Step/Coro::Task<Step>,
// - entry : a member returning
// State/Coro::Task<StateKey>>,
// no params (a startup-data overload may take
// the sub's startup argument);
// - reactive : a member taking `TransitionBuilder&` (the
// declarative table below);
// - continuation : members taking `ChildSuccess auto` /
// `ChildFailure auto` (the sub's typed result
// after `startMachine<Sub, This>()`).
// - continuation : members taking `ChildSuccess` /
// `ChildFailure` (the sub's typed result, read
// via .as<T>(), after `startMachine<Sub,
// This>`).
//
// struct Idle : State { // reactive
// void transitions(TransitionBuilder& on) {
// on.event<Go>().to<Running>();
// on.after(5s).to<TimedOut>(); } };
// Events are handled imperatively inside an entry:
// struct Idle : State { // entry
// Coro::Task<StateKey> run() {
// auto e = co_await await_any<Go, Stop>();
// co_return std::holds_alternative<Go>(e) ? next<Running>()
// : next<Done>(); }
// };
// struct After : State { // continuation
// Coro::Task<Step> ok(ChildSuccess auto s){ ... }
// Coro::Task<Step> no(ChildFailure auto f){ ... } };
//
// The declarative DSL lives in Detail/Reactive.hpp; these aliases
// give the `transitions(TransitionBuilder&)` member its type.
using TransitionTable = Detail::TransitionTable<Derived>;
using TransitionBuilder = Detail::TransitionBuilder<Derived>;
// Coro::Task<StateKey> ok(ChildSuccess s){ ... }
// Coro::Task<StateKey> no(ChildFailure f){ ... } };
// ── construction ──────────────────────────────────────────────
explicit Machine(Options options = {}) : m_options(options)
{
if constexpr (requires { typename Derived::States; }) {
register_states(typename Derived::States{});
if constexpr (requires { typename Derived::Initial; }) {
m_initial = &typeid(typename Derived::Initial);
} else {
m_initial = first_type(typename Derived::States{});
Detail::register_states_from<typename Derived::States>(
*this);
using Init = Detail::InitialStateOf<Derived>;
if constexpr (!std::is_void_v<Init>) {
m_initial = &typeid(Init);
}
}
}
@@ -397,20 +390,8 @@ namespace Void::Fsm
s->m_machine = this;
return s;
});
// Signature-inferred driver thunk (entry or reactive table).
// Signature-inferred driver thunk (runs the state's entry).
m_drivers.emplace(key, Detail::make_driver<S>());
// describe() collector: fills a table if S is reactive.
m_collectors.emplace(
key,
[](Detail::StateBase& base,
TransitionTable& table) -> bool {
if constexpr (Detail::has_transitions<S>()) {
Detail::collect_transitions(static_cast<S&>(base),
table);
return true;
}
return false;
});
}
template <typename S> void initial()
@@ -459,7 +440,6 @@ namespace Void::Fsm
m_names.erase(m_names.begin() + idx);
m_factories.erase(key);
m_drivers.erase(key);
m_collectors.erase(key);
m_index.erase(idxIt);
// Re-pack the indices of states that followed S.
for (auto& [k, v] : m_index) {
@@ -973,12 +953,13 @@ namespace Void::Fsm
/// machine's shared executor, then enter `Next` carrying Sub's
/// outcome as a LaunchResult. Reached via State::startMachine.
template <typename Sub, typename Next, typename... Args>
[[nodiscard]] Step start_machine(Args&&... args)
[[nodiscard]] StateKey start_machine(Args&&... args)
{
if constexpr (requires { typename Derived::States; }) {
static_assert(
Derived::States::template contains<Next>(),
"startMachine<Sub, Next>: Next is not in States<...>");
Detail::states_contains<typename Derived::States,
Next>(),
"startMachine<Sub, Next>: Next is not in States { … }");
}
using Init = Detail::InitialStateOf<Sub>;
auto launcher =
@@ -993,7 +974,7 @@ namespace Void::Fsm
child.m_startup_injector =
[... d = std::move(data)](
Detail::StateBase& base) mutable
-> Coro::Task<Step> {
-> Coro::Task<StateKey> {
return Detail::invoke_startup<Init>(
static_cast<Init&>(base), std::move(d)...);
};
@@ -1017,14 +998,14 @@ namespace Void::Fsm
}
co_return lr;
};
Step::Dispatch dispatch =
StateKey::Dispatch dispatch =
[](Detail::StateBase& base,
LaunchResult lr) -> Coro::Task<Step> {
LaunchResult lr) -> Coro::Task<StateKey> {
return Detail::dispatch_result<Next, Sub>(
static_cast<Next&>(base), std::move(lr));
};
return Step::launch(typeid(Next), std::move(launcher),
std::move(dispatch));
return StateKey::launch(typeid(Next), std::move(launcher),
std::move(dispatch));
}
// ── observation ───────────────────────────────────────────────
@@ -1066,12 +1047,12 @@ namespace Void::Fsm
}
// ── introspection / diagram ───────────────────────────────────
// EdgeInfo / StateInfo are namespace-scope (Detail/Introspect.hpp).
// StateInfo is namespace-scope (Detail/Introspect.hpp).
/// Structural description: every registered state plus the
/// transitions declared by reactive states (imperative states'
/// run()-chosen transitions are not statically knowable, so
/// they appear as nodes without edges).
/// Structural description: every registered state (name + whether
/// it is the initial state). Transitions are chosen imperatively
/// inside each state's entry, so they are not statically knowable —
/// the description is node-level (no edges).
[[nodiscard]] std::vector<StateInfo> describe()
{
std::vector<StateInfo> out;
@@ -1082,22 +1063,6 @@ namespace Void::Fsm
StateInfo si;
si.name = name;
si.initial = (name == initial_name);
const auto* ti = m_name_to_type.at(name);
const std::type_index key{*ti};
auto state = m_factories.at(key)();
TransitionTable table;
si.reactive = m_collectors.at(key)(*state, table);
if (si.reactive) {
for (const auto& e : table.events) {
si.edges.push_back(
EdgeInfo{e.event_name, e.target_name,
static_cast<bool>(e.guard)});
}
if (table.has_timeout) {
si.edges.push_back(EdgeInfo{
"(timeout)", table.timeout_target_name, false});
}
}
out.push_back(std::move(si));
}
return out;
@@ -1151,6 +1116,15 @@ namespace Void::Fsm
virtual void on_serialize(Json::Value& /*data*/) const {}
virtual void on_restore(const Json::Value& /*data*/) {}
/// Machine-level entry/exit hooks (default no-ops; override for
/// machine-wide setup/teardown). `on_machine_enter()` runs once
/// before the initial state is entered; `on_machine_exit()` runs
/// once when the machine reaches a terminal outcome (Success,
/// Failure, or a system Fault). Per-state entry/exit lives on the
/// state itself (State::on_enter()/on_exit()).
virtual void on_machine_enter() {}
virtual void on_machine_exit() {}
/// Called on every transition (and the initial entry). Default
/// logs at debug; override for custom observability.
virtual void on_transition(std::string_view from,
@@ -1176,21 +1150,6 @@ namespace Void::Fsm
m_status.store(Status::Running);
}
template <typename... Ss> void register_states(States<Ss...>)
{
(add<Ss>(), ...);
}
template <typename First, typename... Rest>
static const std::type_info* first_type(States<First, Rest...>)
{
return &typeid(First);
}
static const std::type_info* first_type(States<>)
{
return nullptr;
}
template <typename S> [[nodiscard]] std::string state_name()
{
#ifdef VOID_HAS_FSM_REFLECTION
@@ -1261,6 +1220,7 @@ namespace Void::Fsm
fault("no initial state");
co_return;
}
on_machine_enter();
bool first = true;
for (;;) {
// Apply an external jump<S>() at this transition boundary.
@@ -1274,6 +1234,7 @@ namespace Void::Fsm
const auto it = m_factories.find(std::type_index{*cur});
if (it == m_factories.end()) {
fault("transition to unregistered state");
on_machine_exit();
co_return;
}
set_current(cur);
@@ -1282,7 +1243,7 @@ namespace Void::Fsm
// Decide how the state runs: a launched sub's result (via
// the bound dispatcher), the startup injector for the first
// state, or the signature-inferred driver thunk.
Step step;
StateKey step;
if (m_pending_dispatch) {
LaunchResult pending = std::move(*m_pending_result);
auto dispatch = std::move(m_pending_dispatch);
@@ -1290,6 +1251,7 @@ namespace Void::Fsm
m_pending_dispatch = nullptr;
if (pending.kind == LaunchResult::Kind::Fault) {
fault(std::move(pending.fault.message));
on_machine_exit();
co_return;
}
step = co_await dispatch(*state, std::move(pending));
@@ -1305,28 +1267,31 @@ namespace Void::Fsm
co_await state->on_exit();
fire_after(current_state());
switch (step.kind()) {
case Step::Kind::Transition:
case StateKey::Kind::Transition:
cur = step.target();
continue;
case Step::Kind::Launch:
case StateKey::Kind::Launch:
m_pending_result.emplace(
co_await step.run_launch());
m_pending_dispatch = step.take_dispatch();
cur = step.target();
continue;
case Step::Kind::Success:
case StateKey::Kind::Success:
m_result_value = std::move(step.payload());
m_status.store(Status::Succeeded,
std::memory_order_release);
on_machine_exit();
co_return;
case Step::Kind::Fail:
case StateKey::Kind::Fail:
m_result_value = std::move(step.payload());
m_status.store(Status::Failed,
std::memory_order_release);
on_machine_exit();
co_return;
case Step::Kind::Fault:
case StateKey::Kind::Fault:
fault(std::any_cast<FsmError>(step.payload())
.message);
on_machine_exit();
co_return;
}
}
@@ -1385,15 +1350,11 @@ namespace Void::Fsm
std::type_index,
std::function<std::unique_ptr<Detail::StateBase>()>>
m_factories;
// Per-state signature-inferred driver thunk (entry / reactive).
std::unordered_map<std::type_index, std::function<Coro::Task<Step>(
Detail::StateBase&)>>
m_drivers;
// Per-state describe() collector (reactive table, if any).
// Per-state signature-inferred driver thunk (runs the entry).
std::unordered_map<
std::type_index,
std::function<bool(Detail::StateBase&, TransitionTable&)>>
m_collectors;
std::function<Coro::Task<StateKey>(Detail::StateBase&)>>
m_drivers;
std::unordered_map<std::type_index, int> m_index;
std::vector<std::string> m_names;
std::unordered_map<std::string, const std::type_info*>
@@ -1421,11 +1382,11 @@ namespace Void::Fsm
// Set by a Launch step's sub-machine result; consumed by the next
// state via the bound dispatcher below.
std::optional<LaunchResult> m_pending_result;
Step::Dispatch m_pending_dispatch;
StateKey::Dispatch m_pending_dispatch;
// Seeds the initial state's startup-entry with launch data (set by
// the parent's launcher before driving this machine).
std::function<Coro::Task<Step>(Detail::StateBase&)>
std::function<Coro::Task<StateKey>(Detail::StateBase&)>
m_startup_injector;
// External jump request (jump<S>()); applied by drive() at the
@@ -1437,5 +1398,5 @@ namespace Void::Fsm
// suspended frame chain of a machine parked on an event.
std::optional<Coro::Task<void>> m_driver;
};
template <typename Derived> using State = Machine<Derived>::State;
} // namespace Void::Fsm