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

+38 -35
View File
@@ -7,7 +7,8 @@
using Void::Coro::Task;
using Void::Fsm::MachineOptions;
using Void::Fsm::Step;
using Void::Fsm::State;
using Void::Fsm::StateKey;
namespace
{
@@ -21,33 +22,34 @@ namespace
int count = 0;
std::vector<std::string>* log = nullptr;
struct Start : State {
Task<Step> run()
{
if (self().log) {
self().log->push_back("start");
}
co_return next<Work>();
}
};
struct States {
struct Start : State {
Task<StateKey> start()
{
if (self().log) {
self().log->push_back("start");
}
co_return next<Work>();
}
};
struct Work : State {
Task<Step> run()
{
auto& m = self();
++m.count;
if (m.log) {
m.log->push_back("work" + std::to_string(m.count));
}
if (m.count >= 3) {
co_return succeed(m.count);
}
co_return next<Work>();
}
struct Work : State {
Task<StateKey> run()
{
auto& m = self();
++m.count;
if (m.log) {
m.log->push_back("work" +
std::to_string(m.count));
}
if (m.count >= 3) {
co_return succeed(m.count);
}
co_return next<Work>();
}
};
};
using States = Void::Fsm::States<Start, Work>;
Counter()
: Void::Fsm::Machine<Counter>(
MachineOptions{.own_worker = false})
@@ -62,12 +64,12 @@ namespace
using Success = int;
using Failure = Void::Fsm::FsmError;
struct Boom : State {
Task<Step> run() { co_return fail("kaboom"); }
struct States {
struct Boom : State {
Task<StateKey> run() { co_return fail("kaboom"); }
};
};
using States = Void::Fsm::States<Boom>;
Failing()
: Void::Fsm::Machine<Failing>(
MachineOptions{.own_worker = false})
@@ -113,10 +115,11 @@ Void::Testing::Test fsm_pump_drives_to_completion()
Void::Testing::Test fsm_void_result_succeeds()
{
struct Trivial : Void::Fsm::Machine<Trivial> {
struct Done : State {
Task<Step> run() { co_return succeed(); }
struct States {
struct Done : State {
Task<StateKey> run() { co_return succeed(); }
};
};
using States = Void::Fsm::States<Done>;
Trivial()
: Void::Fsm::Machine<Trivial>(
MachineOptions{.own_worker = false})
@@ -137,13 +140,13 @@ Void::Testing::Test fsm_dynamic_state_registration()
bool express;
struct Express : State {
Task<Step> run() { co_return succeed(99); }
Task<StateKey> run() { co_return succeed(99); }
};
struct Normal : State {
Task<Step> run() { co_return succeed(1); }
Task<StateKey> run() { co_return succeed(1); }
};
struct Start : State {
Task<Step> run()
Task<StateKey> run()
{
if (self().has_state<Express>()) {
co_return next_dynamic<Express>();
+4 -3
View File
@@ -11,7 +11,8 @@
using Void::Coro::Task;
using Void::Fsm::MachineOptions;
using Void::Fsm::Step;
using Void::Fsm::State;
using Void::Fsm::StateKey;
namespace
{
@@ -32,7 +33,7 @@ namespace
long long target;
struct Run : State {
Task<Step> run()
Task<StateKey> run()
{
auto& m = self();
while (m.total < m.target) {
@@ -138,7 +139,7 @@ Void::Testing::Test fsm_resolves_service_through_context()
using Success = int;
struct Go : State {
Task<Step> run()
Task<StateKey> run()
{
co_return succeed(service<IDoubler>().twice(21));
}
+59 -45
View File
@@ -3,15 +3,20 @@
#include <Void/Testing/Test.hpp>
#include <string>
#include <variant>
#include <vector>
using Void::Coro::Task;
using Void::Fsm::Step;
using Void::Fsm::State;
using Void::Fsm::StateKey;
namespace Fsm = Void::Fsm;
// Phase-6 reactive DSL: deferred events (held + replayed after a transition),
// entry/exit actions (on.enter/on.exit), and internal transitions (handle an
// event without leaving the state).
// Imperative equivalents of the old reactive extras:
// - deferred events : an event a state does not await stays buffered in the
// typed mailbox and is consumed by a later state — defer
// is automatic, no declaration needed.
// - entry/exit actions: the first/last lines of run().
// - internal transition: handle an event in a loop without leaving the state.
namespace
{
@@ -20,8 +25,8 @@ namespace
struct Done {
};
// Busy defers Click (held, not dropped) and runs enter/exit actions; on
// Done it transitions to Idle, which then handles the replayed Click.
// Busy awaits only Done; a Click posted meanwhile stays buffered (deferred)
// and is handled by Idle. enter/exit are the first/last lines of run().
class Flow : public Fsm::Machine<Flow>
{
public:
@@ -29,29 +34,29 @@ namespace
using Success = int;
std::vector<std::string> log;
struct Busy : State {
void transitions(TransitionBuilder& on)
{
on.enter([](Flow& m) { m.log.push_back("enter"); });
on.exit([](Flow& m) { m.log.push_back("exit"); });
on.template defer<Click>();
on.template event<Done>().template to<Idle>();
}
struct States {
struct Busy : State {
Task<StateKey> run()
{
auto& m = self();
m.log.push_back("enter");
co_await await_event<Done>(); // Click buffered
m.log.push_back("exit");
co_return next<Idle>();
}
};
struct Idle : State {
Task<StateKey> run()
{
co_await await_event<Click>(); // buffered Click
self().log.push_back("click");
co_return next<End>();
}
};
struct End : State {
Task<StateKey> run() { co_return succeed(1); }
};
};
struct Idle : State {
void transitions(TransitionBuilder& on)
{
on.template event<Click>()
.action([](Flow& m, const Click&) {
m.log.push_back("click");
})
.template to<End>();
}
};
struct End : State {
Task<Step> run() { co_return succeed(1); }
};
using States = Fsm::States<Busy, Idle, End>;
};
} // namespace
@@ -60,12 +65,12 @@ Void::Testing::Test deferred_event_replays_after_transition()
{
Flow fsm;
fsm.start();
fsm.send(Click{}); // deferred while in Busy (not dropped)
fsm.send(Done{}); // Busy -> Idle; the held Click is replayed -> End
fsm.send(Click{}); // not awaited in Busy → stays buffered (not dropped)
fsm.send(Done{}); // Busy -> Idle; Idle consumes the buffered Click -> End
const auto outcome = fsm.wait();
Void::Testing::expect(outcome.has_value());
Void::Testing::expect_eq(*outcome, 1);
// enter/exit actions fired around Busy; the deferred Click was handled.
// enter/exit ran around Busy; the buffered Click was handled in Idle.
const std::vector<std::string> expected{"enter", "exit", "click"};
Void::Testing::expect(fsm.log == expected);
}
@@ -79,8 +84,8 @@ namespace
struct Stop {
};
// Counter handles Tick internally (no exit/enter, no transition); Stop
// leaves with the accumulated count.
// Counter handles Tick internally (loop, no re-entry); Stop leaves with the
// accumulated count.
class Counter : public Fsm::Machine<Counter>
{
public:
@@ -89,19 +94,28 @@ namespace
int ticks = 0;
int enters = 0;
struct Run : State {
void transitions(TransitionBuilder& on)
{
on.enter([](Counter& m) { ++m.enters; });
on.template event<Tick>().internal(
[](Counter& m, const Tick&) { ++m.ticks; });
on.template event<Stop>().template to<Done>();
}
struct States {
struct Run : State {
Task<StateKey> run()
{
auto& m = self();
++m.enters; // entered exactly once
for (;;) {
auto ev = co_await await_any<Tick, Stop>();
if (std::holds_alternative<Stop>(ev)) {
co_return next<Done>();
}
++m.ticks; // internal: handled, stay here
}
}
};
struct Done : State {
Task<StateKey> run()
{
co_return succeed(self().ticks);
}
};
};
struct Done : State {
Task<Step> run() { co_return succeed(self().ticks); }
};
using States = Fsm::States<Run, Done>;
};
} // namespace
+78 -66
View File
@@ -7,7 +7,8 @@
using Void::Coro::Task;
using Void::Fsm::MachineOptions;
using Void::Fsm::Step;
using Void::Fsm::State;
using Void::Fsm::StateKey;
namespace Fsm = Void::Fsm;
using namespace std::chrono_literals;
@@ -28,17 +29,18 @@ namespace
int total = 0;
struct Take : State {
Task<Step> run()
{
auto a = co_await await_event<Add>();
self().total += a.n;
auto b = co_await await_event<Add>();
self().total += b.n;
co_return succeed(self().total);
}
struct States {
struct Take : State {
Task<StateKey> run()
{
auto a = co_await await_event<Add>();
self().total += a.n;
auto b = co_await await_event<Add>();
self().total += b.n;
co_return succeed(self().total);
}
};
};
using States = Fsm::States<Take>;
};
} // namespace
@@ -63,16 +65,17 @@ namespace
using Success = int;
struct A : State {
Task<Step> run() { co_return goto_state<C>(); }
struct States {
struct A : State {
Task<StateKey> run() { co_return goto_state<C>(); }
};
struct B : State {
Task<StateKey> run() { co_return succeed(1); }
};
struct C : State {
Task<StateKey> run() { co_return succeed(3); }
};
};
struct B : State {
Task<Step> run() { co_return succeed(1); }
};
struct C : State {
Task<Step> run() { co_return succeed(3); }
};
using States = Fsm::States<A, B, C>;
};
} // namespace
@@ -98,17 +101,18 @@ namespace
using Success = int;
struct Loop : State {
Task<Step> run()
{
co_await await_event<Tick>();
co_return next<Loop>();
}
struct States {
struct Loop : State {
Task<StateKey> run()
{
co_await await_event<Tick>();
co_return next<Loop>();
}
};
struct Done : State {
Task<StateKey> run() { co_return succeed(99); }
};
};
struct Done : State {
Task<Step> run() { co_return succeed(99); }
};
using States = Fsm::States<Loop, Done>;
explicit Jumper(MachineOptions o = {}) : Fsm::Machine<Jumper>(o) {}
};
@@ -124,7 +128,7 @@ Void::Testing::Test jump_redirects_at_next_boundary()
while (fsm.pump() > 0) {
} // Loop -> next<Loop> -> park again
fsm.jump<Jumper::Done>(); // request a jump
fsm.jump<Jumper::States::Done>(); // request a jump
fsm.send(Tick{});
while (fsm.pump() > 0) {
} // Loop finishes -> boundary applies the jump -> Done
@@ -147,10 +151,14 @@ namespace
int runs = 0;
struct Once : State {
Task<Step> run() { co_return succeed(++self().runs); }
struct States {
struct Once : State {
Task<StateKey> run()
{
co_return succeed(++self().runs);
}
};
};
using States = Fsm::States<Once>;
};
} // namespace
@@ -173,13 +181,14 @@ namespace
using Success = int;
struct A : State {
Task<Step> run() { co_return succeed(1); }
};
struct B : State {
Task<Step> run() { co_return succeed(2); }
};
using States = Fsm::States<A, B>; // initial = A
struct States {
struct A : State {
Task<StateKey> run() { co_return succeed(1); }
};
struct B : State {
Task<StateKey> run() { co_return succeed(2); }
};
}; // initial = A
};
} // namespace
@@ -189,7 +198,7 @@ Void::Testing::Test restart_at_changes_initial_state()
Pick fsm;
const auto first = fsm.run_blocking();
Void::Testing::expect_eq(*first, 1); // A
fsm.restart_at<Pick::B>();
fsm.restart_at<Pick::States::B>();
const auto second = fsm.wait();
Void::Testing::expect_eq(*second, 2); // B
}
@@ -204,32 +213,33 @@ namespace
using Success = int;
struct A : State {
Task<Step> run() { co_return succeed(1); }
struct States {
struct A : State {
Task<StateKey> run() { co_return succeed(1); }
};
struct B : State {
Task<StateKey> run() { co_return succeed(2); }
};
struct C : State {
Task<StateKey> run() { co_return succeed(3); }
};
};
struct B : State {
Task<Step> run() { co_return succeed(2); }
};
struct C : State {
Task<Step> run() { co_return succeed(3); }
};
// Not in States<> — added via replace<>.
// Not in States — added via replace<>.
struct Extra : State {
Task<Step> run() { co_return succeed(7); }
Task<StateKey> run() { co_return succeed(7); }
};
using States = Fsm::States<A, B, C>;
};
} // namespace
Void::Testing::Test remove_and_set_initial_before_start()
{
Mut fsm;
Void::Testing::expect(fsm.has_state<Mut::C>());
fsm.remove<Mut::C>();
Void::Testing::expect(!fsm.has_state<Mut::C>());
Void::Testing::expect(fsm.has_state<Mut::States::C>());
fsm.remove<Mut::States::C>();
Void::Testing::expect(!fsm.has_state<Mut::States::C>());
Void::Testing::expect_eq(fsm.describe().size(), std::size_t{2});
fsm.set_initial<Mut::B>();
fsm.set_initial<Mut::States::B>();
const auto outcome = fsm.run_blocking();
Void::Testing::expect_eq(*outcome, 2);
}
@@ -237,8 +247,9 @@ Void::Testing::Test remove_and_set_initial_before_start()
Void::Testing::Test replace_swaps_a_state_and_keeps_initial()
{
Mut fsm;
fsm.replace<Mut::A, Mut::Extra>(); // A was initial -> Extra becomes initial
Void::Testing::expect(!fsm.has_state<Mut::A>());
// A was initial -> Extra becomes initial.
fsm.replace<Mut::States::A, Mut::Extra>();
Void::Testing::expect(!fsm.has_state<Mut::States::A>());
Void::Testing::expect(fsm.has_state<Mut::Extra>());
const auto outcome = fsm.run_blocking();
Void::Testing::expect_eq(*outcome, 7);
@@ -257,14 +268,15 @@ namespace
using Success = int;
struct W : State {
Task<Step> run()
{
co_await await_event<Go>();
co_return succeed(5);
}
struct States {
struct W : State {
Task<StateKey> run()
{
co_await await_event<Go>();
co_return succeed(5);
}
};
};
using States = Fsm::States<W>;
};
} // namespace
+136
View File
@@ -0,0 +1,136 @@
#include <Void/Fsm/Fsm.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
using Void::Coro::Task;
using Void::Fsm::ChildSuccess;
using Void::Fsm::State;
using Void::Fsm::StateKey;
namespace Fsm = Void::Fsm;
// A state's entry is inferred by signature (a 0-arg member returning StateKey /
// Task<StateKey>). When several members match, one annotated
// `[[= Void::Fsm::entry]]` is preferred; otherwise the first-declared wins. A
// startup-data overload run(Cfg) is selected when the machine is launched with
// data, and the nullary entry otherwise.
namespace
{
// Two nullary entry candidates; the annotated one is chosen even though it
// is not declared first.
class Annotated : public Fsm::Machine<Annotated>
{
public:
using Success = int;
struct States {
struct Pick : State {
Task<StateKey> first() // declared first
{
co_return succeed(1);
}
[[= Fsm::entry]] Task<StateKey> chosen()
{
co_return succeed(2);
}
};
};
};
// Two nullary entry candidates, none annotated → first-declared wins.
class FirstWins : public Fsm::Machine<FirstWins>
{
public:
using Success = int;
struct States {
struct Pick : State {
Task<StateKey> first() { co_return succeed(1); }
Task<StateKey> second() { co_return succeed(2); }
};
};
};
} // namespace
// @tag integration
Void::Testing::Test annotated_entry_beats_first_declared()
{
Annotated fsm;
const auto outcome = fsm.run_blocking();
Void::Testing::expect(outcome.has_value());
Void::Testing::expect_eq(*outcome, 2); // the [[= Fsm::entry]] member ran
}
// @tag integration
Void::Testing::Test first_declared_entry_wins_without_annotation()
{
FirstWins fsm;
const auto outcome = fsm.run_blocking();
Void::Testing::expect(outcome.has_value());
Void::Testing::expect_eq(*outcome, 1); // first-declared ran
}
// ── startup-data overload selection ─────────────────────────────────────────
namespace
{
// Begin has both a nullary entry and a startup-data overload. The right one
// is picked by whether the machine was launched with data.
class Seeded : public Fsm::Machine<Seeded>
{
public:
using Success = int;
struct States {
struct Begin : State {
Task<StateKey> run() // no startup data
{
co_return succeed(0);
}
Task<StateKey> run(int seed) // with startup data
{
co_return succeed(seed);
}
};
};
};
class Launcher : public Fsm::Machine<Launcher>
{
public:
using Success = int;
struct States {
struct Go : State {
Task<StateKey> run()
{
co_return startMachine<Seeded, After>(7);
}
};
struct After : State {
Task<StateKey> ok(ChildSuccess s)
{
co_return succeed(s.as<int>());
}
};
};
};
} // namespace
// @tag integration
Void::Testing::Test startup_entry_used_when_launched_with_data()
{
Launcher fsm; // Seeded launched via startMachine<Seeded, After>(7)
const auto outcome = fsm.run_blocking();
Void::Testing::expect(outcome.has_value());
Void::Testing::expect_eq(*outcome, 7); // run(int) selected
}
// @tag integration
Void::Testing::Test nullary_entry_used_without_startup_data()
{
Seeded fsm; // started normally, no startup data
const auto outcome = fsm.run_blocking();
Void::Testing::expect(outcome.has_value());
Void::Testing::expect_eq(*outcome, 0); // run() selected
}
+3 -2
View File
@@ -9,7 +9,8 @@
using Void::Coro::Task;
using Void::Fsm::MachineOptions;
using Void::Fsm::Step;
using Void::Fsm::State;
using Void::Fsm::StateKey;
namespace
{
@@ -30,7 +31,7 @@ namespace
std::vector<int>* order = nullptr;
struct Waiting : State {
Task<Step> run()
Task<StateKey> run()
{
auto& m = self();
// Two typed mailboxes: pull whichever arrives.
+30 -27
View File
@@ -8,7 +8,8 @@
using Void::Coro::Task;
using Void::Fsm::MachineOptions;
using Void::Fsm::Step;
using Void::Fsm::State;
using Void::Fsm::StateKey;
// Composite sub-states: a parent state runs a child region (run_region) that
// shares the parent's executor, event mailbox and services. The child's
@@ -31,17 +32,18 @@ namespace
using Success = std::string;
using Failure = Void::Fsm::FsmError;
struct Waiting : State {
Task<Step> run()
{
auto ev = co_await await_any<Tick, Cancel>();
if (std::holds_alternative<Cancel>(ev)) {
co_return fail("cancelled");
}
co_return succeed(std::string{"ticked"});
}
struct States {
struct Waiting : State {
Task<StateKey> run()
{
auto ev = co_await await_any<Tick, Cancel>();
if (std::holds_alternative<Cancel>(ev)) {
co_return fail("cancelled");
}
co_return succeed(std::string{"ticked"});
}
};
};
using States = Void::Fsm::States<Waiting>;
explicit Work(MachineOptions opts = {})
: Void::Fsm::Machine<Work>(opts)
@@ -57,23 +59,24 @@ namespace
using Success = std::string;
struct Running : State {
Task<Step> run()
{
auto r = co_await run_region<Work>();
if (r.has_value()) {
co_return succeed(*r);
}
co_return next<Aborted>();
}
struct States {
struct Running : State {
Task<StateKey> run()
{
auto r = co_await run_region<Work>();
if (r.has_value()) {
co_return succeed(*r);
}
co_return next<Aborted>();
}
};
struct Aborted : State {
Task<StateKey> run()
{
co_return succeed(std::string{"aborted"});
}
};
};
struct Aborted : State {
Task<Step> run()
{
co_return succeed(std::string{"aborted"});
}
};
using States = Void::Fsm::States<Running, Aborted>;
explicit Job(MachineOptions opts = {})
: Void::Fsm::Machine<Job>(opts)
+33 -28
View File
@@ -4,7 +4,8 @@
using Void::Coro::Task;
using Void::Fsm::Resume;
using Void::Fsm::Step;
using Void::Fsm::State;
using Void::Fsm::StateKey;
namespace Fsm = Void::Fsm;
// run_region<Sub>(Resume::History) re-enters a region at the sub-state it last
@@ -23,17 +24,18 @@ namespace
using Success = int;
struct A : State {
Task<Step> run()
{
++g_a_runs;
co_return next<B>();
}
struct States {
struct A : State {
Task<StateKey> run()
{
++g_a_runs;
co_return next<B>();
}
};
struct B : State {
Task<StateKey> run() { co_return succeed(2); }
};
};
struct B : State {
Task<Step> run() { co_return succeed(2); }
};
using States = Fsm::States<A, B>;
};
class Host : public Fsm::Machine<Host>
@@ -42,16 +44,18 @@ namespace
using Success = int;
struct Run : State {
Task<Step> run()
{
co_await run_region<Region>(); // Initial: A then B
co_await run_region<Region>(
Resume::History); // History: B only
co_return succeed(g_a_runs);
}
struct States {
struct Run : State {
Task<StateKey> run()
{
co_await run_region<Region>(); // Initial: A
// then B
co_await run_region<Region>(
Resume::History); // History: B only
co_return succeed(g_a_runs);
}
};
};
using States = Fsm::States<Run>;
};
} // namespace
@@ -73,15 +77,16 @@ Void::Testing::Test initial_reentry_restarts_from_the_top()
// Two plain (Initial) entries run A both times.
struct H2 : Fsm::Machine<H2> {
using Success = int;
struct Run : State {
Task<Step> run()
{
co_await run_region<Region>();
co_await run_region<Region>(); // Initial again
co_return succeed(g_a_runs);
}
struct States {
struct Run : State {
Task<StateKey> run()
{
co_await run_region<Region>();
co_await run_region<Region>(); // Initial again
co_return succeed(g_a_runs);
}
};
};
using States = Fsm::States<Run>;
};
H2 fsm;
const auto outcome = fsm.run_blocking();
+42 -40
View File
@@ -7,7 +7,8 @@
using Void::Coro::Task;
using Void::Fsm::MachineOptions;
using Void::Fsm::Step;
using Void::Fsm::State;
using Void::Fsm::StateKey;
using Void::Fsm::Transition;
namespace
@@ -21,44 +22,44 @@ namespace
std::vector<std::string> log;
struct A : State {
Task<void> on_enter() override
{
self().log.push_back("enter A");
co_return;
}
Task<Step> run()
{
self().log.push_back("run A");
co_return next<B>();
}
Task<void> on_exit() override
{
self().log.push_back("exit A");
co_return;
}
};
struct States {
struct A : State {
Task<void> on_enter() override
{
self().log.push_back("enter A");
co_return;
}
Task<StateKey> run()
{
self().log.push_back("run A");
co_return next<B>();
}
Task<void> on_exit() override
{
self().log.push_back("exit A");
co_return;
}
};
struct B : State {
Task<void> on_enter() override
{
self().log.push_back("enter B");
co_return;
}
Task<Step> run()
{
self().log.push_back("run B");
co_return succeed(1);
}
Task<void> on_exit() override
{
self().log.push_back("exit B");
co_return;
}
struct B : State {
Task<void> on_enter() override
{
self().log.push_back("enter B");
co_return;
}
Task<StateKey> run()
{
self().log.push_back("run B");
co_return succeed(1);
}
Task<void> on_exit() override
{
self().log.push_back("exit B");
co_return;
}
};
};
using States = Void::Fsm::States<A, B>;
Lifecycle()
: Void::Fsm::Machine<Lifecycle>(
MachineOptions{.own_worker = false})
@@ -109,11 +110,12 @@ Void::Testing::Test fsm_state_names_and_path()
Void::Testing::Test fsm_state_without_run_fails()
{
struct NoRun : Void::Fsm::Machine<NoRun> {
struct Stuck : State {
Task<void> on_enter() override { co_return; }
// no run() override
struct States {
struct Stuck : State {
Task<void> on_enter() override { co_return; }
// no run() override
};
};
using States = Void::Fsm::States<Stuck>;
NoRun()
: Void::Fsm::Machine<NoRun>(MachineOptions{.own_worker = false})
{
+7 -6
View File
@@ -6,7 +6,8 @@
using Void::Coro::Task;
using Void::Fsm::MachineOptions;
using Void::Fsm::Step;
using Void::Fsm::State;
using Void::Fsm::StateKey;
namespace
{
@@ -20,7 +21,7 @@ namespace
int seed;
struct Compute : State {
Task<Step> run()
Task<StateKey> run()
{
auto& m = self();
co_return succeed(m.seed * 10);
@@ -45,7 +46,7 @@ namespace
using Failure = Void::Fsm::FsmError;
struct Boom : State {
Task<Step> run() { co_return fail("child boom"); }
Task<StateKey> run() { co_return fail("child boom"); }
};
FailingChild()
: Void::Fsm::Machine<FailingChild>(
@@ -64,7 +65,7 @@ namespace
using Failure = Void::Fsm::FsmError;
struct Start : State {
Task<Step> run()
Task<StateKey> run()
{
auto a = co_await run_child<Subtotal>(3); // 30
auto b = co_await run_child<Subtotal>(4); // 40
@@ -91,7 +92,7 @@ namespace
using Failure = Void::Fsm::FsmError;
struct Start : State {
Task<Step> run()
Task<StateKey> run()
{
auto r = co_await run_child<FailingChild>();
if (!r.has_value()) {
@@ -136,7 +137,7 @@ Void::Testing::Test fsm_nesting_with_worker_thread()
using Success = int;
struct Start : State {
Task<Step> run()
Task<StateKey> run()
{
auto a = co_await run_child<Subtotal>(5); // 50
co_return succeed(a.value_or(-1));
+46 -37
View File
@@ -3,7 +3,8 @@
#include <Void/Testing/Test.hpp>
using Void::Coro::Task;
using Void::Fsm::Step;
using Void::Fsm::StateKey;
using Void::Fsm::State;
namespace Fsm = Void::Fsm;
// Orthogonal regions: run_parallel<A, B>() runs both sub-machines concurrently
@@ -22,14 +23,15 @@ namespace
public:
using Success = int;
struct W : State {
Task<Step> run()
{
co_await await_event<GoLeft>();
co_return succeed(1);
}
struct States {
struct W : State {
Task<StateKey> run()
{
co_await await_event<GoLeft>();
co_return succeed(1);
}
};
};
using States = Fsm::States<W>;
};
class Right : public Fsm::Machine<Right>
@@ -37,14 +39,15 @@ namespace
public:
using Success = int;
struct W : State {
Task<Step> run()
{
co_await await_event<GoRight>();
co_return succeed(2);
}
struct States {
struct W : State {
Task<StateKey> run()
{
co_await await_event<GoRight>();
co_return succeed(2);
}
};
};
using States = Fsm::States<W>;
};
// Joins both children: their results sum to 3.
@@ -53,15 +56,17 @@ namespace
public:
using Success = int;
struct Run : State {
Task<Step> run()
{
auto [a, b] = co_await run_parallel<Left, Right>();
co_return succeed((a.has_value() ? *a : 0) +
(b.has_value() ? *b : 0));
}
struct States {
struct Run : State {
Task<StateKey> run()
{
auto [a, b] =
co_await run_parallel<Left, Right>();
co_return succeed((a.has_value() ? *a : 0) +
(b.has_value() ? *b : 0));
}
};
};
using States = Fsm::States<Run>;
explicit Both(Fsm::MachineOptions o = {}) : Fsm::Machine<Both>(o) {}
};
@@ -107,21 +112,25 @@ namespace
public:
using Success = int;
struct Run : State {
Task<Step> run()
{
auto v = co_await run_parallel_any<Left, Right>();
// index 1 == Right (value 2); index 0 == Left (value 1)
if (v.index() == 1 && std::get<1>(v).has_value()) {
co_return succeed(100 + *std::get<1>(v));
}
if (v.index() == 0 && std::get<0>(v).has_value()) {
co_return succeed(*std::get<0>(v));
}
co_return succeed(-1);
}
struct States {
struct Run : State {
Task<StateKey> run()
{
auto v =
co_await run_parallel_any<Left, Right>();
// index 1 == Right (2); index 0 == Left (1)
if (v.index() == 1 &&
std::get<1>(v).has_value()) {
co_return succeed(100 + *std::get<1>(v));
}
if (v.index() == 0 &&
std::get<0>(v).has_value()) {
co_return succeed(*std::get<0>(v));
}
co_return succeed(-1);
}
};
};
using States = Fsm::States<Run>;
explicit Race(Fsm::MachineOptions o = {}) : Fsm::Machine<Race>(o) {}
};
+64 -64
View File
@@ -4,11 +4,14 @@
#include <chrono>
#include <string>
#include <variant>
#include <vector>
#include <iostream>
using Void::Coro::Task;
using Void::Fsm::MachineOptions;
using Void::Fsm::Step;
using Void::Fsm::State;
using Void::Fsm::StateKey;
using Void::Fsm::Transition;
using namespace std::chrono_literals;
@@ -30,30 +33,30 @@ namespace
int attempts = 0;
int retries; // how many tries with_retry gets
struct Try : State {
Task<Step> run()
{
auto& m = self();
const bool ok = co_await with_retry(
m.retries, 1ms, [&m]() -> Task<bool> {
++m.attempts;
co_return m.attempts > m.fail_n;
});
co_return next_or<Fallback>(
ok ? succeed(std::string{"ok"})
: fail("exhausted"));
}
};
struct States {
struct Try : State {
Task<StateKey> run()
{
auto& m = self();
const bool ok = co_await with_retry(
m.retries, 1ms, [&m]() -> Task<bool> {
++m.attempts;
co_return m.attempts > m.fail_n;
});
co_return next_or<Fallback>(
ok ? succeed(std::string{"ok"})
: fail("exhausted"));
}
};
struct Fallback : State {
Task<Step> run()
{
co_return succeed(std::string{"fallback"});
}
struct Fallback : State {
Task<StateKey> run()
{
co_return succeed(std::string{"fallback"});
}
};
};
using States = Void::Fsm::States<Try, Fallback>;
explicit Flaky(int fails, int tries) : fail_n(fails), retries(tries)
{
} // own worker
@@ -91,13 +94,14 @@ namespace
using Success = int;
struct A : State {
Task<Step> run() { co_return next<B>(); }
struct States {
struct A : State {
Task<StateKey> run() { co_return next<B>(); }
};
struct B : State {
Task<StateKey> run() { co_return succeed(1); }
};
};
struct B : State {
Task<Step> run() { co_return succeed(1); }
};
using States = Void::Fsm::States<A, B>;
Pipe()
: Void::Fsm::Machine<Pipe>(MachineOptions{.own_worker = false})
{
@@ -149,63 +153,59 @@ namespace
struct Cancel {
};
// Imperative event handling: Idle awaits Go or Cancel and routes.
class Flow : public Void::Fsm::Machine<Flow>
{
public:
using Success = int;
struct Idle : State {
void transitions(TransitionBuilder& on)
{
on.event<Go>()
.guard([](Flow&, const Go&) { return true; })
.template to<Active>();
on.event<Cancel>().template to<Done>();
on.after(1h).template to<Done>();
}
struct States {
struct Idle : State {
Task<StateKey> run()
{
auto ev = co_await await_any<Go, Cancel>();
co_return std::holds_alternative<Go>(ev)
? next<Active>()
: next<Done>();
}
};
struct Active : State {
Task<StateKey> run() { co_return next<Done>(); }
};
struct Done : State {
Task<StateKey> run() { co_return succeed(0); }
};
};
struct Active : State {
Task<Step> run() { co_return next<Done>(); }
};
struct Done : State {
Task<Step> run() { co_return succeed(0); }
};
using States = Void::Fsm::States<Idle, Active, Done>;
Flow() {}
};
} // namespace
Void::Testing::Test describe_lists_states_and_reactive_edges()
// describe() is node-level: behaviour (and therefore transitions) is chosen
// imperatively inside each state's entry, so edges are not statically knowable.
Void::Testing::Test describe_lists_states_node_level()
{
Flow fsm;
const auto states = fsm.describe();
Void::Testing::expect_eq(states.size(), std::size_t{3});
// Idle is reactive + initial, with Go/Cancel/timeout edges.
const auto& idle = states[0];
Void::Testing::expect_eq(idle.name, std::string{"Idle"});
Void::Testing::expect(idle.reactive);
Void::Testing::expect(idle.initial);
Void::Testing::expect_eq(idle.edges.size(), std::size_t{3});
Void::Testing::expect_eq(idle.edges[0].event, std::string{"Go"});
Void::Testing::expect_eq(idle.edges[0].target, std::string{"Active"});
Void::Testing::expect(idle.edges[0].guarded);
Void::Testing::expect_eq(idle.edges[2].event, std::string{"(timeout)"});
// Active is imperative → no declarable edges.
Void::Testing::expect(!states[1].reactive);
Void::Testing::expect(states[1].edges.empty());
// Registration order; Idle is the initial state.
Void::Testing::expect_eq(states[0].name, std::string{"Idle"});
Void::Testing::expect(states[0].initial);
Void::Testing::expect_eq(states[1].name, std::string{"Active"});
Void::Testing::expect(!states[1].initial);
Void::Testing::expect_eq(states[2].name, std::string{"Done"});
}
Void::Testing::Test to_mermaid_contains_edges()
Void::Testing::Test to_mermaid_lists_nodes_and_initial()
{
Flow fsm;
const auto diagram = fsm.to_mermaid();
std::cout << diagram << std::endl;
Void::Testing::expect(diagram.find("stateDiagram-v2") != std::string::npos);
Void::Testing::expect(diagram.find("[*] --> Idle") != std::string::npos);
Void::Testing::expect(diagram.find("Idle --> Active : Go [guard]") !=
std::string::npos);
Void::Testing::expect(diagram.find("Idle --> Done : Cancel") !=
std::string::npos);
// One node per registered state.
Void::Testing::expect(diagram.find("\n Idle\n") != std::string::npos);
Void::Testing::expect(diagram.find("\n Active\n") != std::string::npos);
Void::Testing::expect(diagram.find("\n Done\n") != std::string::npos);
}
+61 -51
View File
@@ -5,11 +5,13 @@
#include <chrono>
#include <string>
#include <thread>
#include <variant>
#include <vector>
using Void::Coro::Task;
using Void::Fsm::MachineOptions;
using Void::Fsm::Step;
using Void::Fsm::State;
using Void::Fsm::StateKey;
using namespace std::chrono_literals;
namespace
@@ -20,8 +22,9 @@ namespace
struct Stop {
};
// A declarative machine: Idle reacts to events with guards/actions; on
// timeout it bails out.
// Imperative event handling: Idle loops, awaiting either Go or Stop. A Go
// only advances when positive (the guard, now a plain `if`); Stop leaves to
// Done. Internal handling = stay in the loop (no transition).
class Gate : public Void::Fsm::Machine<Gate>
{
public:
@@ -32,42 +35,46 @@ namespace
int total = 0;
std::vector<std::string> trace;
struct Idle : State {
void transitions(TransitionBuilder& on)
{
// Guarded: only positive amounts advance.
on.event<Go>()
.guard(
[](Gate&, const Go& g) { return g.amount > 0; })
.action([](Gate& m, const Go& g) {
m.total += g.amount;
m.trace.push_back("go" +
std::to_string(g.amount));
})
.template to<Idle>();
on.event<Stop>().template to<Done>();
on.after(10s).fail("idle timeout");
}
};
struct States {
struct Idle : State {
Task<StateKey> run()
{
auto& m = self();
for (;;) {
auto ev = co_await await_any<Go, Stop>();
if (std::holds_alternative<Stop>(ev)) {
co_return next<Done>();
}
const Go g = std::get<Go>(ev);
if (g.amount > 0) { // guard
m.total += g.amount;
m.trace.push_back(
"go" + std::to_string(g.amount));
}
}
}
};
// Imperative terminal state: reports the accumulated total.
struct Done : State {
Task<Step> run() { co_return succeed(self().total); }
// Imperative terminal state: reports the accumulated total.
struct Done : State {
Task<StateKey> run()
{
co_return succeed(self().total);
}
};
};
using States = Void::Fsm::States<Idle, Done>;
Gate() {} // own worker
};
} // namespace
// Mixes a reactive (declarative, guarded) state with an imperative one.
// Imperative event loop with a guard and an accumulating action.
Void::Testing::Test reactive_guard_and_action()
{
Gate fsm;
fsm.start();
fsm.post(Go{5});
fsm.post(Go{-1}); // blocked by guard, dropped
fsm.post(Go{-1}); // blocked by the guard, ignored
fsm.post(Go{3});
fsm.post(Stop{}); // -> Done -> succeed(total)
@@ -93,17 +100,18 @@ namespace
using Success = std::string;
struct Waiting : State {
Task<Step> run()
{
auto w = co_await await_event_for<Wake>(15ms);
if (w.has_value()) {
co_return succeed(std::string{"woken"});
}
co_return succeed(std::string{"timed_out"});
}
struct States {
struct Waiting : State {
Task<StateKey> run()
{
auto w = co_await await_event_for<Wake>(15ms);
if (w.has_value()) {
co_return succeed(std::string{"woken"});
}
co_return succeed(std::string{"timed_out"});
}
};
};
using States = Void::Fsm::States<Waiting>;
Sleeper() {} // own worker
};
} // namespace
@@ -130,27 +138,29 @@ Void::Testing::Test await_event_for_receives_event()
namespace
{
// Reactive timeout transition (on.after().to<>).
// Timeout transition expressed imperatively (await_event_for → branch).
class Deadline : public Void::Fsm::Machine<Deadline>
{
public:
using Success = int;
struct Pending : State {
void transitions(TransitionBuilder& on)
{
on.event<Wake>().template to<Resolved>();
on.after(15ms).template to<Expired>();
}
struct States {
struct Pending : State {
Task<StateKey> run()
{
auto w = co_await await_event_for<Wake>(15ms);
co_return w.has_value() ? next<Resolved>()
: next<Expired>();
}
};
struct Resolved : State {
Task<StateKey> run() { co_return succeed(1); }
};
struct Expired : State {
Task<StateKey> run() { co_return succeed(2); }
};
};
struct Resolved : State {
Task<Step> run() { co_return succeed(1); }
};
struct Expired : State {
Task<Step> run() { co_return succeed(2); }
};
using States = Void::Fsm::States<Pending, Resolved, Expired>;
Deadline() {}
};
} // namespace
+4 -3
View File
@@ -7,7 +7,8 @@
using Void::Coro::Task;
using Void::Fsm::MachineOptions;
using Void::Fsm::Step;
using Void::Fsm::State;
using Void::Fsm::StateKey;
namespace
{
@@ -26,14 +27,14 @@ namespace
Data data;
struct Ingest : State {
Task<Step> run()
Task<StateKey> run()
{
co_await await_event<int>(); // park here
co_return next<Process>();
}
};
struct Process : State {
Task<Step> run()
Task<StateKey> run()
{
auto& m = self();
m.data.processed += 1;
+99
View File
@@ -0,0 +1,99 @@
#include <Void/Fsm/Fsm.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <string>
#include <variant>
using Void::Coro::Task;
using Void::Fsm::State;
using Void::Fsm::StateKey;
namespace Fsm = Void::Fsm;
// Demonstrates the header/source split the module is designed for: the machine
// declares its states as forward declarations inside `struct States { … };`
// (this block is what would live in a header), and the states are *realised*
// out-of-line at namespace scope (this is what would live in a .cpp). The base
// auto-registers them by reflecting `States`; no behaviour is written outside a
// state. The constructor is also defined out-of-line, after the realisations,
// so the states are complete when the base registers them.
namespace
{
struct Charge {
int amount;
};
struct Dispense {
};
// ── "header" part ──────────────────────────────────────────────────────
class Vending : public Fsm::Machine<Vending>
{
public:
using Success = int; // dispensed credit
int credit = 0;
struct States {
struct Idle; // first => initial
struct Collecting;
struct Done;
};
Vending(); // realised below, after the states
};
} // namespace
// ── "source" part: state realisations (namespace scope) ─────────────────────
struct Vending::States::Idle : Vending::State {
Task<StateKey> run()
{
co_await await_event<Charge>(); // first coin -> start collecting
co_return next<Collecting>();
}
};
struct Vending::States::Collecting : Vending::State {
Task<StateKey> run()
{
auto& m = self();
for (;;) {
auto ev = co_await await_any<Charge, Dispense>();
if (std::holds_alternative<Dispense>(ev)) {
co_return next<Done>();
}
m.credit += std::get<Charge>(ev).amount;
}
}
};
struct Vending::States::Done : Vending::State {
Task<StateKey> run() { co_return succeed(self().credit); }
};
Vending::Vending() = default; // base registers Idle/Collecting/Done from States
// @tag integration
Void::Testing::Test split_machine_runs_with_out_of_line_states()
{
Vending fsm;
fsm.start();
fsm.send(Charge{10}); // Idle -> Collecting (first coin counted there too?)
fsm.send(Charge{5}, Charge{10});
fsm.send(Dispense{});
const auto outcome = fsm.wait();
Void::Testing::expect(outcome.has_value());
// Idle consumes the first Charge to leave; Collecting sums 5 + 10 = 15.
Void::Testing::expect_eq(*outcome, 15);
}
Void::Testing::Test split_machine_auto_registers_states_in_order()
{
Vending fsm;
const auto& names = fsm.state_names();
Void::Testing::expect_eq(names.size(), std::size_t{3});
Void::Testing::expect_eq(names[0], std::string{"Idle"}); // initial
Void::Testing::expect_eq(names[1], std::string{"Collecting"});
Void::Testing::expect_eq(names[2], std::string{"Done"});
}
+94 -74
View File
@@ -8,15 +8,16 @@ using Void::Coro::Task;
using Void::Fsm::ChildFailure;
using Void::Fsm::ChildSuccess;
using Void::Fsm::FsmError;
using Void::Fsm::Step;
using Void::Fsm::State;
using Void::Fsm::StateKey;
namespace Fsm = Void::Fsm;
// startMachine<Sub, Next>(data) launches a full sub-FSM on the parent's shared
// executor/events/services (startup data routed to Sub's initial-state
// startup-entry), then enters Next. The engine dispatches the sub's typed
// outcome to Next's signature-matched handler — a member taking
// `ChildSuccess auto` (success) or `ChildFailure auto` (failure). No override,
// no fixed names.
// outcome to Next's signature-matched handler — a member taking `ChildSuccess`
// (success) or `ChildFailure` (failure); the typed value is read with
// `.as<T>()`. No override, no fixed names.
namespace
{
@@ -29,16 +30,17 @@ namespace
using Success = int;
using Failure = Void::Fsm::FsmError;
struct Run : State {
Task<Step> run(int seed)
{
if (seed < 0) {
co_return fail("negative");
}
co_return succeed(seed * 2);
}
struct States {
struct Run : State {
Task<StateKey> run(int seed)
{
if (seed < 0) {
co_return fail("negative");
}
co_return succeed(seed * 2);
}
};
};
using States = Fsm::States<Run>;
};
class Calc : public Fsm::Machine<Calc>
@@ -49,24 +51,27 @@ namespace
int input = 0;
struct Start : State {
Task<Step> run()
{
co_return startMachine<Doubler, AfterDouble>(
self().input);
}
struct States {
struct Start : State {
Task<StateKey> run()
{
co_return startMachine<Doubler, AfterDouble>(
self().input);
}
};
struct AfterDouble : State {
Task<StateKey> ok(ChildSuccess s)
{
co_return succeed("doubled:" +
std::to_string(s.as<int>()));
}
Task<StateKey> no(ChildFailure f)
{
co_return succeed("failed:" +
f.as<FsmError>().message);
}
};
};
struct AfterDouble : State {
Task<Step> ok(ChildSuccess auto s)
{
co_return succeed("doubled:" + std::to_string(s.value));
}
Task<Step> no(ChildFailure auto f)
{
co_return succeed("failed:" + f.value.message);
}
};
using States = Fsm::States<Start, AfterDouble>;
explicit Calc(int in) : input(in) {}
};
@@ -98,10 +103,11 @@ namespace
{
public:
struct Ping : State {
Task<Step> run() { co_return succeed(); }
struct States {
struct Ping : State {
Task<StateKey> run() { co_return succeed(); }
};
};
using States = Fsm::States<Ping>;
};
class Host : public Fsm::Machine<Host>
@@ -110,14 +116,21 @@ namespace
using Success = int;
struct Go : State {
Task<Step> run() { co_return startMachine<Pinger, Done>(); }
struct States {
struct Go : State {
Task<StateKey> run()
{
co_return startMachine<Pinger, Done>();
}
};
struct Done : State {
// void-result sub: ChildSuccess box has no value.
Task<StateKey> ok(ChildSuccess)
{
co_return succeed(42);
}
};
};
struct Done : State {
// void-result sub: ChildSuccess box has no value.
Task<Step> ok(ChildSuccess auto) { co_return succeed(42); }
};
using States = Fsm::States<Go, Done>;
};
} // namespace
@@ -140,25 +153,27 @@ namespace
using Success = int;
struct A : State {
Task<Step> run()
{
co_return startMachine<Doubler, B>(3); // 3 -> 6
}
struct States {
struct A : State {
Task<StateKey> run()
{
co_return startMachine<Doubler, B>(3); // 3 -> 6
}
};
struct B : State {
Task<StateKey> ok(ChildSuccess s)
{
// 6 -> 12
co_return startMachine<Doubler, C>(s.as<int>());
}
};
struct C : State {
Task<StateKey> ok(ChildSuccess s)
{
co_return succeed(s.as<int>());
}
};
};
struct B : State {
Task<Step> ok(ChildSuccess auto s)
{
co_return startMachine<Doubler, C>(s.value); // 6 -> 12
}
};
struct C : State {
Task<Step> ok(ChildSuccess auto s)
{
co_return succeed(s.value);
}
};
using States = Fsm::States<A, B, C>;
};
} // namespace
@@ -184,14 +199,15 @@ namespace
using Success = int;
struct W : State {
Task<Step> run()
{
co_await await_event<Tick>();
co_return succeed(7);
}
struct States {
struct W : State {
Task<StateKey> run()
{
co_await await_event<Tick>();
co_return succeed(7);
}
};
};
using States = Fsm::States<W>;
};
class Outer : public Fsm::Machine<Outer>
@@ -200,16 +216,20 @@ namespace
using Success = int;
struct Begin : State {
Task<Step> run() { co_return startMachine<WaitSub, Fin>(); }
struct States {
struct Begin : State {
Task<StateKey> run()
{
co_return startMachine<WaitSub, Fin>();
}
};
struct Fin : State {
Task<StateKey> ok(ChildSuccess s)
{
co_return succeed(s.as<int>());
}
};
};
struct Fin : State {
Task<Step> ok(ChildSuccess auto s)
{
co_return succeed(s.value);
}
};
using States = Fsm::States<Begin, Fin>;
};
} // namespace