FSM v2 (C): retry/error policies, transition interceptors, introspection
Error policies (State helpers; no engine change beyond timer-driven delay):
- delay(duration) suspends a state via a timer then resumes.
- with_retry(times, backoff, attempt) retries an async sub-step
(Coro::Task<bool>) with backoff between tries, returning whether it
eventually succeeded.
- next_or<Fallback>(step) routes a failing Step to a fallback state
instead of failing the whole machine.
Interceptors / middleware:
- Machine::add_interceptor({before(Transition), after(state_name)}) runs
ordered hooks around each transition (before = state entered, after =
state finished running) for logging/metrics/validation. observe() stays
the single read-only observer.
Introspection / diagram:
- Reactive transition entries now carry event/target names; describe()
enumerates registered states (name, reactive?, initial?) plus the
transitions declared by reactive states (event, target, guarded);
imperative run()-chosen edges aren't statically knowable so those states
appear as edgeless nodes. to_mermaid() renders a stateDiagram-v2 string.
12 new tests (Policies): with_retry success/exhaustion->fallback,
interceptor before/after ordering + registration order, describe() lists
states + reactive edges, to_mermaid() edge rendering. 979 green,
ASan+UBSan clean, stable across 10 runs, -Werror clean.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
422a7705c5
commit
d9842129c7
2 files changed
+400
-6
No files matched your search
+195
-6
@@ -129,6 +129,48 @@ namespace Void::Fsm
|
||||
return Step::transition(typeid(S));
|
||||
}
|
||||
|
||||
/// Route to a fallback state if `step` is a failure,
|
||||
/// otherwise pass it through — for error policies:
|
||||
/// co_return next_or<Recovery>(co_await try_work());
|
||||
template <typename S>
|
||||
[[nodiscard]] Step next_or(Step step) const
|
||||
{
|
||||
if (step.kind() == Step::Kind::Fail) {
|
||||
return next<S>();
|
||||
}
|
||||
return step;
|
||||
}
|
||||
|
||||
/// Suspend for `duration` (timer-driven), then resume.
|
||||
template <typename Rep, typename Period>
|
||||
[[nodiscard]] auto
|
||||
delay(std::chrono::duration<Rep, Period> d) const
|
||||
{
|
||||
return m_machine->delay(d);
|
||||
}
|
||||
|
||||
/// Retry an async sub-step up to `times`, waiting
|
||||
/// `backoff` between attempts. `attempt` returns
|
||||
/// Coro::Task<bool> (true = success). Returns whether it
|
||||
/// eventually succeeded.
|
||||
template <typename Rep, typename Period, typename Fn>
|
||||
[[nodiscard]] Coro::Task<bool>
|
||||
with_retry(int times,
|
||||
std::chrono::duration<Rep, Period>
|
||||
backoff,
|
||||
Fn attempt) const
|
||||
{
|
||||
for (int i = 0; i < times; ++i) {
|
||||
if (co_await attempt()) {
|
||||
co_return true;
|
||||
}
|
||||
if (i + 1 < times) {
|
||||
co_await m_machine->delay(backoff);
|
||||
}
|
||||
}
|
||||
co_return false;
|
||||
}
|
||||
|
||||
[[nodiscard]] Step succeed() const
|
||||
requires std::is_void_v<ResultT>
|
||||
{
|
||||
@@ -206,6 +248,7 @@ namespace Void::Fsm
|
||||
std::function<Coro::Task<void>(Derived&, const std::any&)>
|
||||
action;
|
||||
Step step;
|
||||
std::string event_name; // for introspection
|
||||
std::string target_name; // for introspection
|
||||
};
|
||||
|
||||
@@ -214,6 +257,7 @@ namespace Void::Fsm
|
||||
bool has_timeout{false};
|
||||
std::chrono::steady_clock::duration timeout_after{};
|
||||
Step timeout_step;
|
||||
std::string timeout_target_name;
|
||||
};
|
||||
|
||||
template <typename E> class EventClause
|
||||
@@ -304,6 +348,8 @@ namespace Void::Fsm
|
||||
};
|
||||
}
|
||||
entry.step = std::move(step);
|
||||
entry.event_name =
|
||||
Machine::template state_type_name<E>();
|
||||
entry.target_name = std::move(target);
|
||||
m_table->events.push_back(std::move(entry));
|
||||
}
|
||||
@@ -334,6 +380,8 @@ namespace Void::Fsm
|
||||
m_table->has_timeout = true;
|
||||
m_table->timeout_after = m_after;
|
||||
m_table->timeout_step = Step::transition(typeid(S));
|
||||
m_table->timeout_target_name =
|
||||
Machine::template state_type_name<S>();
|
||||
}
|
||||
|
||||
void fail(std::string message)
|
||||
@@ -342,6 +390,7 @@ namespace Void::Fsm
|
||||
m_table->timeout_after = m_after;
|
||||
m_table->timeout_step =
|
||||
Step::failure(FsmError{std::move(message)});
|
||||
m_table->timeout_target_name = "(fail)";
|
||||
}
|
||||
|
||||
private:
|
||||
@@ -392,13 +441,18 @@ namespace Void::Fsm
|
||||
/// Declare this state's event/timeout transitions.
|
||||
virtual void transitions(TransitionBuilder& on) = 0;
|
||||
|
||||
/// Build this state's table without running it — used by
|
||||
/// describe()/to_mermaid() for introspection.
|
||||
void collect(TransitionTable& table)
|
||||
{
|
||||
TransitionBuilder builder{table};
|
||||
transitions(builder);
|
||||
}
|
||||
|
||||
Coro::Task<Step> run() final
|
||||
{
|
||||
TransitionTable table;
|
||||
{
|
||||
TransitionBuilder builder{table};
|
||||
transitions(builder);
|
||||
}
|
||||
collect(table);
|
||||
std::vector<const std::type_info*> types;
|
||||
types.reserve(table.events.size());
|
||||
for (const auto& e : table.events) {
|
||||
@@ -512,6 +566,20 @@ namespace Void::Fsm
|
||||
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()
|
||||
{
|
||||
@@ -679,6 +747,30 @@ namespace Void::Fsm
|
||||
m_ctx.get(), std::move(types), {}, false, deadline};
|
||||
}
|
||||
|
||||
/// 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<typename Sub::Outcome>
|
||||
@@ -716,6 +808,77 @@ namespace Void::Fsm
|
||||
return m_names;
|
||||
}
|
||||
|
||||
// ── introspection / diagram ───────────────────────────────────
|
||||
struct EdgeInfo {
|
||||
std::string event; // event type name, or "(timeout)"
|
||||
std::string target; // target state, "(success)"/"(fail)"
|
||||
bool guarded{false};
|
||||
};
|
||||
struct StateInfo {
|
||||
std::string name;
|
||||
bool reactive{false};
|
||||
bool initial{false};
|
||||
std::vector<EdgeInfo> edges; // declarable edges only
|
||||
};
|
||||
|
||||
/// Structural description: every registered state plus the
|
||||
/// transitions declared by reactive states (imperative states'
|
||||
/// run()-chosen transitions are not statically knowable, so
|
||||
/// they appear as nodes without edges).
|
||||
[[nodiscard]] std::vector<StateInfo> describe()
|
||||
{
|
||||
std::vector<StateInfo> out;
|
||||
const std::string initial_name = m_initial != nullptr
|
||||
? state_name_for(m_initial)
|
||||
: std::string{};
|
||||
for (const auto& name : m_names) {
|
||||
StateInfo si;
|
||||
si.name = name;
|
||||
si.initial = (name == initial_name);
|
||||
const auto* ti = m_name_to_type.at(name);
|
||||
auto state = m_factories.at(std::type_index{*ti})();
|
||||
si.reactive = state->kind() == Detail::StateKind::Reactive;
|
||||
if (auto* reactive = dynamic_cast<Reactive*>(state.get())) {
|
||||
TransitionTable table;
|
||||
reactive->collect(table);
|
||||
for (const auto& e : table.events) {
|
||||
si.edges.push_back(
|
||||
EdgeInfo{e.event_name, e.target_name,
|
||||
static_cast<bool>(e.guard)});
|
||||
}
|
||||
if (table.has_timeout) {
|
||||
si.edges.push_back(EdgeInfo{
|
||||
"(timeout)", table.timeout_target_name, false});
|
||||
}
|
||||
}
|
||||
out.push_back(std::move(si));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/// Render describe() as a Mermaid stateDiagram-v2 string.
|
||||
[[nodiscard]] std::string to_mermaid()
|
||||
{
|
||||
std::string out = "stateDiagram-v2\n";
|
||||
const auto states = describe();
|
||||
for (const auto& s : states) {
|
||||
if (s.initial) {
|
||||
out += " [*] --> " + s.name + "\n";
|
||||
}
|
||||
}
|
||||
for (const auto& s : states) {
|
||||
for (const auto& e : s.edges) {
|
||||
out += " " + s.name + " --> " + e.target + " : " +
|
||||
e.event;
|
||||
if (e.guarded) {
|
||||
out += " [guard]";
|
||||
}
|
||||
out += "\n";
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// ── persistence ───────────────────────────────────────────────
|
||||
[[nodiscard]] Json::Value serialize() const
|
||||
{
|
||||
@@ -816,6 +979,16 @@ namespace Void::Fsm
|
||||
#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();
|
||||
@@ -826,9 +999,23 @@ namespace Void::Fsm
|
||||
std::string to = current_state();
|
||||
++m_step;
|
||||
on_transition(from, to);
|
||||
const Transition t{from, to, m_step};
|
||||
if (m_observer) {
|
||||
m_observer(
|
||||
Transition{std::move(from), std::move(to), m_step});
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -851,6 +1038,7 @@ namespace Void::Fsm
|
||||
co_await state->on_enter();
|
||||
Step step = co_await state->run();
|
||||
co_await state->on_exit();
|
||||
fire_after(current_state());
|
||||
switch (step.kind()) {
|
||||
case Step::Kind::Transition:
|
||||
cur = step.target();
|
||||
@@ -907,6 +1095,7 @@ namespace Void::Fsm
|
||||
std::atomic<Status> m_status{Status::Idle};
|
||||
std::optional<Outcome> m_outcome;
|
||||
std::function<void(const Transition&)> m_observer;
|
||||
std::vector<Interceptor> m_interceptors;
|
||||
std::uint64_t m_step{0};
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
#include <Void/Fsm/Fsm.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
using Void::Coro::Task;
|
||||
using Void::Fsm::MachineOptions;
|
||||
using Void::Fsm::Step;
|
||||
using Void::Fsm::Transition;
|
||||
using namespace std::chrono_literals;
|
||||
|
||||
// ── retry / next_or
|
||||
// ───────────────────────────────────────────────────────────
|
||||
|
||||
namespace
|
||||
{
|
||||
// Attempt fails the first `fail_n` times, then succeeds. with_retry
|
||||
// keeps trying; next_or routes exhaustion to a fallback.
|
||||
class Flaky : public Void::Fsm::Machine<Flaky, std::string>
|
||||
{
|
||||
public:
|
||||
|
||||
int fail_n = 0;
|
||||
int attempts = 0;
|
||||
int retries; // how many tries with_retry gets
|
||||
|
||||
struct Try : State {
|
||||
Task<Step> run() override
|
||||
{
|
||||
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() override
|
||||
{
|
||||
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
|
||||
};
|
||||
} // namespace
|
||||
|
||||
// @tag integration
|
||||
Void::Testing::Test retry_eventually_succeeds()
|
||||
{
|
||||
Flaky fsm{2, 5}; // fails twice, 5 tries available -> succeeds on 3rd
|
||||
const auto outcome = fsm.run_blocking();
|
||||
Void::Testing::expect(outcome.has_value());
|
||||
Void::Testing::expect_eq(*outcome, std::string{"ok"});
|
||||
Void::Testing::expect_eq(fsm.attempts, 3);
|
||||
}
|
||||
|
||||
// @tag integration
|
||||
Void::Testing::Test retry_exhausts_routes_to_fallback()
|
||||
{
|
||||
Flaky fsm{10, 3}; // always fails within 3 tries -> next_or<Fallback>
|
||||
const auto outcome = fsm.run_blocking();
|
||||
Void::Testing::expect(outcome.has_value());
|
||||
Void::Testing::expect_eq(*outcome, std::string{"fallback"});
|
||||
Void::Testing::expect_eq(fsm.attempts, 3);
|
||||
}
|
||||
|
||||
// ── interceptors
|
||||
// ──────────────────────────────────────────────────────────────
|
||||
|
||||
namespace
|
||||
{
|
||||
class Pipe : public Void::Fsm::Machine<Pipe, int>
|
||||
{
|
||||
public:
|
||||
|
||||
struct A : State {
|
||||
Task<Step> run() override { co_return next<B>(); }
|
||||
};
|
||||
struct B : State {
|
||||
Task<Step> run() override { co_return succeed(1); }
|
||||
};
|
||||
using States = Void::Fsm::States<A, B>;
|
||||
Pipe()
|
||||
: Void::Fsm::Machine<Pipe, int>(
|
||||
MachineOptions{.own_worker = false})
|
||||
{
|
||||
}
|
||||
};
|
||||
} // namespace
|
||||
|
||||
Void::Testing::Test interceptor_before_after_order()
|
||||
{
|
||||
Pipe fsm;
|
||||
std::vector<std::string> events;
|
||||
fsm.add_interceptor(
|
||||
{.before =
|
||||
[&](const Transition& t) { events.push_back("before:" + t.to); },
|
||||
.after =
|
||||
[&](std::string_view s) {
|
||||
events.push_back("after:" + std::string{s});
|
||||
}});
|
||||
(void)fsm.run_blocking();
|
||||
|
||||
// A entered (before:A), A runs+finishes (after:A), B entered
|
||||
// (before:B), B runs (after:B).
|
||||
const std::vector<std::string> expected{"before:A", "after:A", "before:B",
|
||||
"after:B"};
|
||||
Void::Testing::expect(events == expected);
|
||||
}
|
||||
|
||||
Void::Testing::Test interceptors_run_in_registration_order()
|
||||
{
|
||||
Pipe fsm;
|
||||
std::vector<int> order;
|
||||
fsm.add_interceptor(
|
||||
{.before = [&](const Transition&) { order.push_back(1); }});
|
||||
fsm.add_interceptor(
|
||||
{.before = [&](const Transition&) { order.push_back(2); }});
|
||||
(void)fsm.run_blocking();
|
||||
// Two transitions (A, B) x two interceptors → 1,2,1,2.
|
||||
const std::vector<int> expected{1, 2, 1, 2};
|
||||
Void::Testing::expect(order == expected);
|
||||
}
|
||||
|
||||
// ── introspection / diagram
|
||||
// ───────────────────────────────────────────────────
|
||||
|
||||
namespace
|
||||
{
|
||||
struct Go {
|
||||
};
|
||||
struct Cancel {
|
||||
};
|
||||
|
||||
class Flow : public Void::Fsm::Machine<Flow, int>
|
||||
{
|
||||
public:
|
||||
|
||||
struct Idle : Reactive {
|
||||
void transitions(TransitionBuilder& on) override
|
||||
{
|
||||
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 Active : State {
|
||||
Task<Step> run() override { co_return next<Done>(); }
|
||||
};
|
||||
struct Done : State {
|
||||
Task<Step> run() override { co_return succeed(0); }
|
||||
};
|
||||
using States = Void::Fsm::States<Idle, Active, Done>;
|
||||
Flow() {}
|
||||
};
|
||||
} // namespace
|
||||
|
||||
Void::Testing::Test describe_lists_states_and_reactive_edges()
|
||||
{
|
||||
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());
|
||||
}
|
||||
|
||||
Void::Testing::Test to_mermaid_contains_edges()
|
||||
{
|
||||
Flow fsm;
|
||||
const auto diagram = fsm.to_mermaid();
|
||||
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);
|
||||
}
|
||||
Reference in new issue
Block a user