feat(fsm): structured scopes, race-loser join, boundary checkpoints, and bounded supervision

This commit is contained in:
faumaray committed 2026-11-26 16:51:35 +03:00
1 parent 1dc51d5c43
commit ef5312c4b3
11 files changed
+3819 -541

No files matched your search

+81 -18
View File
@@ -1,41 +1,90 @@
#pragma once
#include <Void/Fsm/Detail/Engine.hpp>
#include <Void/Time/Clock.hpp>
#include <chrono>
#include <coroutine>
#include <optional>
#include <span>
#include <stop_token>
#include <typeinfo>
#include <utility>
namespace Void::Fsm::Detail
{
/// One awaiter for every "wait for an event (optionally with a deadline)"
/// operation on a machine. `Storage` is the type-list container (a
/// std::array for fixed sets, a std::vector for dynamic ones); `Resume` is
/// the projection `(EventEnvelope&&, bool timed_out) -> R` that shapes the
/// awaited value (the matched event, an optional on timeout, a variant,
/// …). Built on ExecutionContext::{try_take_any,set_waiter}.
struct WaiterCancelFn {
ExecutionContext* ctx{nullptr};
ExecutionContext::WaiterId waiter_id{0};
void operator()() const
{
if (ctx != nullptr && waiter_id != 0) {
(void)ctx->try_post_control(
[c = ctx, wid = waiter_id] { c->cancel_waiter(wid); });
}
}
};
/// Unified awaiter for awaiting an event (or event set), optional timeout
/// on injected clock, and cooperative stop cancellation across both
/// per-state scope stop and caller-supplied OperationOptions stop tokens.
template <typename Storage, typename Resume> struct EventAwaiter {
ExecutionContext* ctx;
Storage types;
EventEnvelope env;
ExecutionContext* ctx{nullptr};
Storage types{};
EventEnvelope env{};
bool timed_out{false};
std::optional<std::chrono::steady_clock::time_point> deadline;
Resume resume;
bool cancelled{false};
std::optional<Time::MonotonicClock::time_point> deadline{};
Resume resume{};
ExecutionContext::ScopeId scope{ExecutionContext::kNoScope};
std::stop_token scope_stop{};
std::stop_token user_stop{};
ExecutionContext::WaiterId waiter_id{0};
std::optional<std::stop_callback<WaiterCancelFn>> scope_cb{};
std::optional<std::stop_callback<WaiterCancelFn>> user_cb{};
[[nodiscard]] bool await_ready()
{
return ctx->try_take_any(span(), env);
if (scope_stop.stop_requested() || user_stop.stop_requested()) {
cancelled = true;
return true;
}
if (ctx != nullptr && !types.empty() &&
ctx->try_take_any(span(), env)) {
return true;
}
if (deadline.has_value() && ctx != nullptr &&
ctx->clock().now() >= *deadline) {
timed_out = true;
return true;
}
return false;
}
void await_suspend(std::coroutine_handle<> h)
{
ctx->set_waiter(span(), h, &env, &timed_out, deadline);
waiter_id = ctx->set_waiter(span(), h, &env, &timed_out,
deadline, scope, &cancelled);
if (scope_stop.stop_possible()) {
scope_cb.emplace(scope_stop,
WaiterCancelFn{ctx, waiter_id});
}
if (user_stop.stop_possible()) {
user_cb.emplace(user_stop, WaiterCancelFn{ctx, waiter_id});
}
}
[[nodiscard]] decltype(auto) await_resume()
decltype(auto) await_resume()
{
return resume(std::move(env), timed_out);
scope_cb.reset();
user_cb.reset();
if constexpr (std::is_invocable_v<Resume&, EventEnvelope&&,
bool, bool>) {
return resume(std::move(env), timed_out, cancelled);
} else {
return resume(std::move(env), timed_out);
}
}
private:
@@ -49,10 +98,24 @@ namespace Void::Fsm::Detail
template <typename Storage, typename Resume>
[[nodiscard]] auto make_event_awaiter(
ExecutionContext* ctx, Storage types,
std::optional<std::chrono::steady_clock::time_point> deadline,
Resume resume)
std::optional<Time::MonotonicClock::time_point> deadline,
Resume resume,
ExecutionContext::ScopeId scope = ExecutionContext::kNoScope,
std::stop_token scope_stop = {}, std::stop_token user_stop = {})
{
return EventAwaiter<Storage, Resume>{
ctx, std::move(types), {}, false, deadline, std::move(resume)};
ctx,
std::move(types),
{},
false,
false,
deadline,
std::move(resume),
scope,
std::move(scope_stop),
std::move(user_stop),
0,
std::nullopt,
std::nullopt};
}
} // namespace Void::Fsm::Detail
+141 -54
View File
@@ -4,6 +4,8 @@
#include <Void/Async/MpscQueue.hpp>
#include <Void/Async/Task.hpp>
#include <Void/Fsm/StateKey.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Time/Clock.hpp>
#include <any>
#include <atomic>
@@ -14,6 +16,7 @@
#include <deque>
#include <functional>
#include <map>
#include <memory>
#include <mutex>
#include <optional>
#include <semaphore>
@@ -28,17 +31,14 @@ namespace Void::Fsm::Detail
{
/// Type-erased state. Concrete states derive the single Machine<Derived>::
/// State base; the engine drives each via a signature-inferred per-state
/// thunk (entry / reactive table / continuation handlers).
/// thunk (entry / continuation handlers).
class StateBase
{
public:
virtual ~StateBase() = default;
/// Optional entry/exit lifecycle hooks (default no-ops). The
/// state's behaviour (entry / reactive table / continuation
/// handlers) is discovered by signature via a per-state driver
/// thunk — there is no virtual run().
/// Optional entry/exit lifecycle hooks (default no-ops).
virtual Coro::Task<void> on_enter();
virtual Coro::Task<void> on_exit();
};
@@ -46,18 +46,28 @@ namespace Void::Fsm::Detail
struct EventEnvelope {
const std::type_info* type{nullptr};
std::any value;
std::size_t bytes{0};
};
/// Shared execution substrate for a machine and any machines it nests:
/// one executor + one worker thread + one typed event mailbox. A single
/// consumer (the worker, or the embedder via pump()) touches all
/// mailbox state, so state code runs lock-free and single-threaded;
/// cross-thread post() only enqueues.
/// one logical strand (owned worker, embedder pump(), or borrowed external
/// executor) + bounded event mailbox + reserved control lane + Clock-driven
/// timers. Cross-thread posts enqueue owned envelopes; only the active
/// consumer strand touches waiter/timer/buffer tables.
class ExecutionContext
: public std::enable_shared_from_this<ExecutionContext>
{
public:
ExecutionContext() = default;
using TimerId = std::uint64_t;
using WaiterId = std::uint64_t;
using ScopeId = std::uint64_t;
static constexpr ScopeId kNoScope = 0;
explicit ExecutionContext(
const Time::MonotonicClock* clock = nullptr,
FsmLimits limits = {},
Async::Executor* external_executor = nullptr);
~ExecutionContext();
ExecutionContext(const ExecutionContext&) = delete;
@@ -67,14 +77,61 @@ namespace Void::Fsm::Detail
{
return m_executor;
}
[[nodiscard]] Async::Executor& active_executor() noexcept
{
return m_external_executor != nullptr
? *m_external_executor
: static_cast<Async::Executor&>(m_executor);
}
[[nodiscard]] const Time::MonotonicClock& clock() const noexcept
{
return *m_clock;
}
[[nodiscard]] const FsmLimits& limits() const noexcept
{
return m_limits;
}
[[nodiscard]] std::uint64_t dispatch_turn() const noexcept
{
return m_dispatch_turn;
}
[[nodiscard]] std::size_t last_turn_events() const noexcept
{
return m_last_turn_events;
}
[[nodiscard]] std::size_t queued_events() const noexcept
{
return m_queued_events.load(std::memory_order_acquire);
}
[[nodiscard]] std::size_t queued_bytes() const noexcept
{
return m_queued_bytes.load(std::memory_order_acquire);
}
[[nodiscard]] std::size_t active_child_regions() const noexcept
{
return m_active_child_regions.load(std::memory_order_acquire);
}
[[nodiscard]] std::size_t timer_count() const noexcept
{
return m_timers.size();
}
// ── events (post is the only cross-thread entry point) ────────
[[nodiscard]] bool
try_acquire_child_regions(std::size_t count) noexcept;
void release_child_regions(std::size_t count) noexcept;
// ── events & control (thread-safe entry points) ──────────────
[[nodiscard]] Void::Result::Result<void>
try_post(EventEnvelope env);
void post(EventEnvelope env);
[[nodiscard]] Void::Result::Result<void>
try_post_control(std::function<void()> fn);
// Mailbox ops — consumer thread only (called from awaiters that
// run on the executor, and from the worker drain).
using TimerId = std::uint64_t;
// ── strand-only scope/waiter/timer APIs ──────────────────────
[[nodiscard]] ScopeId allocate_scope() noexcept
{
return m_next_scope.fetch_add(1, std::memory_order_relaxed);
}
/// Pop the oldest buffered event whose type is in `types`.
[[nodiscard]] bool
@@ -82,68 +139,66 @@ namespace Void::Fsm::Detail
EventEnvelope& out);
/// Suspend until an event of one of `types` arrives, or (if
/// `deadline` is set) the deadline passes. `slot` receives the
/// matched event; `*timed_out` is set true on timeout.
void set_waiter(
/// `deadline` is set) the deadline passes, or the waiter/scope is
/// cancelled.
WaiterId set_waiter(
std::span<const std::type_info* const> types,
std::coroutine_handle<> cont, EventEnvelope* slot,
bool* timed_out,
std::optional<std::chrono::steady_clock::time_point> deadline);
std::optional<Time::MonotonicClock::time_point> deadline,
ScopeId scope = kNoScope, bool* cancelled = nullptr);
/// Schedule `on_fire` at `deadline`. Returns an id for
/// cancel_timer.
TimerId add_timer(std::chrono::steady_clock::time_point deadline,
std::function<void()>
on_fire);
void cancel_waiter(WaiterId id);
void cancel_scope(ScopeId scope);
void purge_scope(ScopeId scope);
void drain_control_queue();
/// Schedule `on_fire` at `deadline` (enforces max_timers).
[[nodiscard]] Void::Result::Result<TimerId>
try_add_timer(Time::MonotonicClock::time_point deadline,
std::function<void()> on_fire,
ScopeId scope = kNoScope);
TimerId add_timer(Time::MonotonicClock::time_point deadline,
std::function<void()> on_fire,
ScopeId scope = kNoScope);
void cancel_timer(TimerId id);
// ── worker lifecycle ─────────────────────────────────────────
/// Spawn the worker thread (idempotent).
// ── worker / pump lifecycle ──────────────────────────────────
void start_worker();
/// Mark finished and wake the worker so it can exit.
void finish();
/// Stop and join the worker.
void stop();
/// Join the worker without forcing finish (waits for the
/// driver to finish() on its own).
void join();
[[nodiscard]] bool finished() const noexcept
{
return m_done.load(std::memory_order_acquire);
}
/// Embedder-driven step: deliver queued events + run ready
/// coroutines. Returns work done count. Single consumer only.
/// A no-op (returns 0) while paused.
/// Embedder-driven step: drain control lane, fire due timers on
/// injected clock, deliver up to max_events_per_turn /
/// max_turn_duration user events, and drain internal executor.
std::size_t pump();
/// Pause / resume event processing. While paused the worker stops
/// draining (and pump() is a no-op); posted events buffer.
void set_paused(bool paused);
/// Called on external executor threads via scheduled task.
void run_external_pump_step();
/// Wake the consumer (e.g. to re-check an external jump request).
void set_paused(bool paused);
void nudge() { wake(); }
private:
void deliver(EventEnvelope& env);
void run_loop();
void wake() noexcept;
void fire_due_timers();
[[nodiscard]] std::optional<std::chrono::steady_clock::time_point>
next_deadline() const;
struct BufferedEvent {
std::any value;
std::size_t bytes{0};
};
Async::ManualExecutor m_executor;
Async::MpscQueue<EventEnvelope> m_queue;
std::unordered_map<std::type_index, std::deque<std::any>> m_buffers;
using WaiterId = std::uint64_t;
struct Waiter {
WaiterId id{0};
ScopeId scope{kNoScope};
std::vector<const std::type_info*> types;
std::coroutine_handle<> cont{};
EventEnvelope* slot{nullptr};
bool* timed_out{nullptr};
bool* cancelled{nullptr};
TimerId timer{0};
[[nodiscard]] bool wants(const std::type_info& t) const
@@ -156,20 +211,52 @@ namespace Void::Fsm::Detail
return false;
}
};
// Several waiters can be parked at once (parallel regions, deferred
// events). An event resumes the first (FIFO) that wants its type.
struct Timer {
Time::MonotonicClock::time_point deadline;
std::function<void()> on_fire;
ScopeId scope{kNoScope};
};
void deliver(EventEnvelope& env);
void run_loop();
void wake() noexcept;
void schedule_external_pump() noexcept;
void fire_due_timers();
[[nodiscard]] std::optional<Time::MonotonicClock::time_point>
next_deadline() const;
const Time::MonotonicClock* m_clock;
FsmLimits m_limits;
Async::Executor* m_external_executor{nullptr};
Async::ManualExecutor m_executor;
Async::MpscQueue<EventEnvelope> m_queue;
std::atomic<std::size_t> m_queued_events{0};
std::atomic<std::size_t> m_queued_bytes{0};
Async::MpscQueue<std::function<void()>> m_control_queue;
std::atomic<std::size_t> m_queued_control{0};
std::unordered_map<std::type_index, std::deque<BufferedEvent>>
m_buffers;
std::size_t m_buffered_events{0};
std::size_t m_buffered_bytes{0};
std::vector<Waiter> m_waiters;
WaiterId m_next_waiter{1};
struct Timer {
std::chrono::steady_clock::time_point deadline;
std::function<void()> on_fire;
};
std::map<TimerId, Timer> m_timers;
TimerId m_next_timer{1};
std::atomic<ScopeId> m_next_scope{1};
std::atomic<std::size_t> m_active_child_regions{0};
std::uint64_t m_dispatch_turn{0};
std::size_t m_last_turn_events{0};
std::counting_semaphore<> m_wakeup{0};
std::atomic<bool> m_sleeping{false};
std::atomic<bool> m_pump_scheduled{false};
std::atomic<bool> m_done{false};
std::atomic<bool> m_paused{false};
std::atomic<bool> m_worker_started{false};
+1500 -387
View File
File diff suppressed because it is too large. Load diff
+400 -41
View File
@@ -1,27 +1,73 @@
#pragma once
#include <Void/Fsm/StateKey.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Service/Registry.hpp>
#include <Void/Time/Clock.hpp>
#include <atomic>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <memory>
#include <mutex>
#include <optional>
#include <string>
#include <utility>
#include <vector>
namespace Void::Fsm
{
enum class SupervisionMode : std::uint8_t {
StopOnFault = 0,
BoundedRestart
};
struct SupervisionPolicy {
SupervisionMode mode{SupervisionMode::StopOnFault};
std::size_t max_restarts{3};
std::chrono::nanoseconds restart_window{std::chrono::seconds{60}};
std::chrono::nanoseconds initial_backoff{
std::chrono::milliseconds{10}};
};
struct OrchestratorLimits {
std::size_t max_supervised{1024};
};
struct SupervisionEvent {
enum class Kind : std::uint8_t {
Launched = 0,
RestartScheduled,
Restarted,
Released,
Exhausted
};
Kind kind{Kind::Launched};
Status status{Status::Idle};
TerminationReason reason{TerminationReason::none};
std::size_t restarts{0};
std::string detail{};
};
namespace Detail
{
// Type-erased supervised FSM. Models wrap a concrete Machine<R>
// subclass; the orchestrator only needs lifecycle + status.
// subclass; the orchestrator drives lifecycle, status, and bounded
// restart.
class FsmConcept
{
public:
virtual ~FsmConcept() = default;
virtual void stop() = 0;
virtual void restart() = 0;
[[nodiscard]] virtual Status status() const = 0;
[[nodiscard]] virtual TerminationReason
termination_reason() const = 0;
[[nodiscard]] virtual std::optional<FsmError>
system_error() const = 0;
};
template <typename F> class FsmModel final : public FsmConcept
@@ -34,10 +80,21 @@ namespace Void::Fsm
}
void stop() override { m_fsm->stop(); }
void restart() override { m_fsm->restart(); }
[[nodiscard]] Status status() const override
{
return m_fsm->status();
}
[[nodiscard]] TerminationReason
termination_reason() const override
{
return m_fsm->termination_reason();
}
[[nodiscard]] std::optional<FsmError>
system_error() const override
{
return m_fsm->system_error();
}
[[nodiscard]] F& get() noexcept { return *m_fsm; }
@@ -45,10 +102,27 @@ namespace Void::Fsm
std::unique_ptr<F> m_fsm;
};
struct SupervisedEntry {
std::shared_ptr<FsmConcept> model;
SupervisionPolicy policy{};
std::vector<Time::MonotonicClock::time_point>
restart_timestamps;
std::optional<Time::MonotonicClock::time_point>
next_restart_at;
std::atomic<std::size_t> restarts{0};
mutable std::mutex evidence_mu;
bool released{false};
Status final_status{Status::Idle};
TerminationReason final_reason{TerminationReason::none};
std::optional<FsmError> final_error{};
};
} // namespace Detail
/// A non-owning supervision handle to a launched FSM: query status and
/// stop it. The Orchestrator owns the FSM's lifetime.
/// Owning handle to a supervised FSM instance: holds a shared_ptr so
/// immutable termination evidence and any still-required cleanup ownership
/// survive even after the Orchestrator releases a finished entry from
/// active supervision.
class FsmHandle
{
public:
@@ -57,48 +131,92 @@ namespace Void::Fsm
void stop() const
{
if (m_impl) {
m_impl->stop();
if (m_entry && m_entry->model) {
m_entry->model->stop();
}
}
[[nodiscard]] Status status() const
{
return m_impl ? m_impl->status() : Status::Idle;
if (!m_entry) {
return Status::Idle;
}
std::lock_guard lk{m_entry->evidence_mu};
if (m_entry->released) {
return m_entry->final_status;
}
return m_entry->model ? m_entry->model->status() : Status::Idle;
}
[[nodiscard]] bool finished() const
[[nodiscard]] bool finished() const { return terminal(status()); }
[[nodiscard]] TerminationReason termination_reason() const
{
const auto s = status();
return s == Status::Succeeded || s == Status::Failed;
if (!m_entry) {
return TerminationReason::none;
}
std::lock_guard lk{m_entry->evidence_mu};
if (m_entry->released) {
return m_entry->final_reason;
}
return m_entry->model ? m_entry->model->termination_reason()
: TerminationReason::none;
}
[[nodiscard]] std::optional<FsmError> system_error() const
{
if (!m_entry) {
return std::nullopt;
}
std::lock_guard lk{m_entry->evidence_mu};
if (m_entry->released) {
return m_entry->final_error;
}
return m_entry->model ? m_entry->model->system_error()
: std::nullopt;
}
[[nodiscard]] std::size_t restart_count() const noexcept
{
return m_entry
? m_entry->restarts.load(std::memory_order_acquire)
: 0;
}
[[nodiscard]] explicit operator bool() const noexcept
{
return m_impl != nullptr;
return m_entry != nullptr && m_entry->model != nullptr;
}
private:
friend class Orchestrator;
explicit FsmHandle(std::shared_ptr<Detail::FsmConcept> impl)
: m_impl(std::move(impl))
explicit FsmHandle(std::shared_ptr<Detail::SupervisedEntry> entry)
: m_entry(std::move(entry))
{
}
std::shared_ptr<Detail::FsmConcept> m_impl;
std::shared_ptr<Detail::SupervisedEntry> m_entry;
};
// ── Orchestrator ──────────────────────────────────────────────────────
// Owns a ServiceRegistry and supervises a set of FSM instances. Each
// launched FSM is injected with the registry as its context, so its
// states resolve dependencies by interface (no concrete coupling), and
// is started immediately. stop_all() winds everything down.
class Orchestrator
{
public:
Orchestrator() = default;
using ObserverCallback =
std::function<void(const SupervisionEvent&)>;
explicit Orchestrator(
const Time::MonotonicClock* clock = nullptr,
OrchestratorLimits limits = {}) noexcept
: m_clock(clock != nullptr
? clock
: &Time::SystemMonotonicClock::instance()),
m_limits(limits)
{
}
~Orchestrator() { stop_all(); }
Orchestrator(const Orchestrator&) = delete;
@@ -109,8 +227,6 @@ namespace Void::Fsm
return m_registry;
}
/// Call on_start() on lifecycle services. Call before launching
/// FSMs that expect started services.
void start_services()
{
m_registry.start_all();
@@ -118,36 +234,177 @@ namespace Void::Fsm
m_services_stopped = false;
}
/// Construct F, inject the registry, start it, and supervise.
/// F must derive Fsm::Machine<...> (provides set_services /
/// start / stop / status).
template <typename F, typename... Args>
[[nodiscard]] Void::Result::Result<FsmHandle>
try_launch(SupervisionPolicy policy, Args&&... args)
{
std::vector<ObserverCallback> observers_copy;
std::shared_ptr<Detail::SupervisedEntry> entry;
{
reap_finished_and_notify();
std::lock_guard lock{m_mutex};
if (m_limits.max_supervised > 0 &&
m_entries.size() >= m_limits.max_supervised) {
return Void::Result::fail(make_fsm_error(
FsmErrorCode::limit_exceeded,
"Orchestrator: max_supervised limit reached"));
}
auto fsm =
std::make_unique<F>(std::forward<Args>(args)...);
fsm->set_services(m_registry);
fsm->start();
auto model =
std::make_shared<Detail::FsmModel<F>>(std::move(fsm));
entry = std::make_shared<Detail::SupervisedEntry>();
entry->model = std::move(model);
entry->policy = policy;
m_entries.push_back(entry);
}
notify_observers(SupervisionEvent{
.kind = SupervisionEvent::Kind::Launched,
.status = entry->model->status(),
.reason = entry->model->termination_reason(),
.restarts = 0,
.detail = {}});
return FsmHandle{std::move(entry)};
}
template <typename F, typename... Args>
FsmHandle launch(Args&&... args)
{
auto fsm = std::make_unique<F>(std::forward<Args>(args)...);
fsm->set_services(m_registry);
fsm->start();
auto model =
std::make_shared<Detail::FsmModel<F>>(std::move(fsm));
std::lock_guard lock{m_mutex};
m_running.push_back(model);
return FsmHandle{model};
auto r = try_launch<F>(SupervisionPolicy{},
std::forward<Args>(args)...);
return r ? *r : FsmHandle{};
}
/// Stop and release every supervised FSM, then stop services.
void stop_all()
/// Drive supervision rules (bounded restarts with injected Time
/// backoff, and releasing terminal entries while handles keep
/// immutable evidence). Returns actions taken (restarts + releases).
std::size_t supervise_step()
{
std::vector<std::shared_ptr<Detail::FsmConcept>> running;
std::vector<SupervisionEvent> events;
std::vector<std::shared_ptr<Detail::SupervisedEntry>>
to_restart;
const auto now = m_clock->now();
{
std::lock_guard lock{m_mutex};
running.swap(m_running);
for (auto it = m_entries.begin(); it != m_entries.end();) {
auto& e = *it;
const auto st = e->model->status();
if (!terminal(st)) {
++it;
continue;
}
if (e->policy.mode == SupervisionMode::BoundedRestart &&
st == Status::Faulted) {
std::erase_if(
e->restart_timestamps, [&](const auto ts) {
return (now - ts) >=
e->policy.restart_window;
});
if (e->restart_timestamps.size() <
e->policy.max_restarts) {
if (!e->next_restart_at.has_value()) {
const std::size_t attempt =
e->restart_timestamps.size();
const auto shift =
attempt < 16 ? attempt : 16;
const auto backoff =
e->policy.initial_backoff *
(std::size_t{1} << shift);
e->next_restart_at = now + backoff;
events.push_back(SupervisionEvent{
.kind = SupervisionEvent::Kind::
RestartScheduled,
.status = st,
.reason =
e->model->termination_reason(),
.restarts = e->restarts.load(
std::memory_order_acquire),
.detail = e->model->system_error()
? e->model->system_error()
->message
: std::string{}});
++it;
continue;
}
if (now < *e->next_restart_at) {
++it;
continue;
}
e->restart_timestamps.push_back(now);
e->next_restart_at.reset();
e->restarts.fetch_add(
1, std::memory_order_acq_rel);
to_restart.push_back(e);
++it;
continue;
}
snapshot_released_evidence(*e);
events.push_back(SupervisionEvent{
.kind = SupervisionEvent::Kind::Exhausted,
.status = e->final_status,
.reason = e->final_reason,
.restarts =
e->restarts.load(std::memory_order_acquire),
.detail =
e->final_error
? e->final_error->message
: std::string{"restart budget exhausted"}});
it = m_entries.erase(it);
continue;
}
snapshot_released_evidence(*e);
events.push_back(SupervisionEvent{
.kind = SupervisionEvent::Kind::Released,
.status = e->final_status,
.reason = e->final_reason,
.restarts =
e->restarts.load(std::memory_order_acquire),
.detail = e->final_error ? e->final_error->message
: std::string{}});
it = m_entries.erase(it);
}
}
for (auto& m : running) {
m->stop();
for (auto& e : to_restart) {
e->model->restart();
events.push_back(SupervisionEvent{
.kind = SupervisionEvent::Kind::Restarted,
.status = e->model->status(),
.reason = e->model->termination_reason(),
.restarts = e->restarts.load(std::memory_order_acquire),
.detail = {}});
}
const std::size_t count = events.size();
for (const auto& ev : events) {
notify_observers(ev);
}
return count;
}
/// Release finished stop-on-fault (or non-faulted) entries from
/// active supervision while existing handles retain evidence.
std::size_t reap_finished() { return reap_finished_and_notify(); }
void stop_all()
{
std::vector<std::shared_ptr<Detail::SupervisedEntry>> running;
{
std::lock_guard lock{m_mutex};
running.swap(m_entries);
}
for (auto& e : running) {
e->model->stop();
snapshot_released_evidence(*e);
}
running.clear();
// Balance start_services() exactly once (stop_all may run
// explicitly and again from the destructor).
if (m_services_started && !m_services_stopped) {
m_registry.stop_all();
m_services_stopped = true;
@@ -157,16 +414,118 @@ namespace Void::Fsm
[[nodiscard]] std::size_t running_count() const
{
std::lock_guard lock{m_mutex};
return m_running.size();
return m_entries.size();
}
std::size_t observe_supervision(ObserverCallback cb)
{
std::lock_guard lock{m_obs_mu};
const std::size_t id = m_next_obs_id++;
m_observers.emplace_back(id, std::move(cb));
return id;
}
void remove_supervision_observer(std::size_t id)
{
std::lock_guard lock{m_obs_mu};
std::erase_if(m_observers, [id](const auto& pair) {
return pair.first == id;
});
}
[[nodiscard]] std::vector<std::string> observer_errors() const
{
std::lock_guard lock{m_obs_mu};
return m_observer_errors;
}
private:
static void
snapshot_released_evidence(Detail::SupervisedEntry& entry)
{
std::lock_guard elk{entry.evidence_mu};
if (entry.released) {
return;
}
entry.final_status = entry.model->status();
entry.final_reason = entry.model->termination_reason();
entry.final_error = entry.model->system_error();
entry.released = true;
}
std::size_t reap_finished_and_notify()
{
std::vector<SupervisionEvent> events;
{
std::lock_guard lock{m_mutex};
for (auto it = m_entries.begin(); it != m_entries.end();) {
auto& e = *it;
const auto st = e->model->status();
if (!terminal(st)) {
++it;
continue;
}
if (e->policy.mode == SupervisionMode::BoundedRestart &&
st == Status::Faulted) {
++it;
continue;
}
snapshot_released_evidence(*e);
events.push_back(SupervisionEvent{
.kind = SupervisionEvent::Kind::Released,
.status = e->final_status,
.reason = e->final_reason,
.restarts =
e->restarts.load(std::memory_order_acquire),
.detail = e->final_error ? e->final_error->message
: std::string{}});
it = m_entries.erase(it);
}
}
for (const auto& ev : events) {
notify_observers(ev);
}
return events.size();
}
void notify_observers(const SupervisionEvent& ev)
{
std::vector<ObserverCallback> copy;
{
std::lock_guard lock{m_obs_mu};
copy.reserve(m_observers.size());
for (const auto& [id, fn] : m_observers) {
if (fn) {
copy.push_back(fn);
}
}
}
for (const auto& fn : copy) {
try {
fn(ev);
} catch (const std::exception& ex) {
std::lock_guard lock{m_obs_mu};
m_observer_errors.push_back(ex.what());
} catch (...) {
std::lock_guard lock{m_obs_mu};
m_observer_errors.push_back("observer threw unknown");
}
}
}
const Time::MonotonicClock* m_clock;
OrchestratorLimits m_limits{};
Service::ServiceRegistry m_registry;
mutable std::mutex m_mutex;
std::vector<std::shared_ptr<Detail::FsmConcept>> m_running;
std::vector<std::shared_ptr<Detail::SupervisedEntry>> m_entries;
bool m_services_started{false};
bool m_services_stopped{false};
mutable std::mutex m_obs_mu;
std::vector<std::pair<std::size_t, ObserverCallback>> m_observers;
std::vector<std::string> m_observer_errors;
std::size_t m_next_obs_id{1};
};
} // namespace Void::Fsm
+159
View File
@@ -1,10 +1,22 @@
#pragma once
#include <Void/Async/Executor.hpp>
#include <Void/Async/Task.hpp>
#include <Void/Core/Meta.hpp>
#include <Void/Data/Json.hpp>
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Time/Clock.hpp>
#include <any>
#include <chrono>
#include <concepts>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <string>
#include <string_view>
#include <type_traits>
#include <typeinfo>
#include <utility>
@@ -33,6 +45,153 @@ namespace Void::Fsm
Faulted // stopped by a system fault (see system_error())
};
/// Canonical shared predicate identifying every terminal Status value.
[[nodiscard]] constexpr bool terminal(Status s) noexcept
{
return s == Status::Succeeded || s == Status::Failed ||
s == Status::Faulted;
}
/// Why a machine finished (preserving Status values while distinguishing
/// cooperative cancellation and deadline expiration from application
/// outcomes and system faults).
enum class TerminationReason : std::uint8_t {
none = 0,
succeeded,
failed,
faulted,
cancelled,
timed_out
};
enum class FsmErrorCode : std::int32_t {
none = 0,
invalid_argument = 1,
invalid_state = 2,
not_found = 3,
overloaded = 4,
cancelled = 5,
timeout = 6,
limit_exceeded = 7,
fault = 8,
checkpoint_rejected = 9,
schema_mismatch = 10,
migration_failed = 11,
service_unavailable = 12,
internal = 13
};
[[nodiscard]] inline Void::Result::Error
make_fsm_error(FsmErrorCode code, std::string message = {})
{
using Void::Result::Error;
using Void::Result::ErrorCode;
using Void::Result::ErrorKind;
ErrorKind kind = ErrorKind::internal;
switch (code) {
case FsmErrorCode::none:
kind = ErrorKind::internal;
break;
case FsmErrorCode::invalid_argument:
kind = ErrorKind::invalid_argument;
break;
case FsmErrorCode::invalid_state:
case FsmErrorCode::checkpoint_rejected:
kind = ErrorKind::conflict;
break;
case FsmErrorCode::not_found:
case FsmErrorCode::service_unavailable:
kind = ErrorKind::not_found;
break;
case FsmErrorCode::overloaded:
kind = ErrorKind::overloaded;
break;
case FsmErrorCode::cancelled:
kind = ErrorKind::cancelled;
break;
case FsmErrorCode::timeout:
kind = ErrorKind::timeout;
break;
case FsmErrorCode::limit_exceeded:
kind = ErrorKind::exhausted;
break;
case FsmErrorCode::schema_mismatch:
case FsmErrorCode::migration_failed:
kind = ErrorKind::corrupt;
break;
case FsmErrorCode::fault:
case FsmErrorCode::internal:
kind = ErrorKind::internal;
break;
}
return Error{kind, std::move(message),
ErrorCode{Void::Result::kFsmErrorDomain,
static_cast<std::int32_t>(code)}};
}
/// Explicit resource and scheduling bounds for FSM execution.
struct FsmLimits {
std::size_t max_mailbox_events{1024};
std::size_t max_mailbox_bytes{std::size_t{4} * 1024 * 1024};
std::size_t max_deferred_events{256};
std::size_t max_timers{1024};
std::size_t max_child_regions{128};
std::size_t max_hierarchy_depth{32};
std::size_t max_retained_transitions{256};
std::size_t max_checkpoint_bytes{std::size_t{4} * 1024 * 1024};
std::size_t max_events_per_turn{64};
std::chrono::nanoseconds max_turn_duration{
std::chrono::milliseconds{1}};
std::size_t max_control_messages{256};
};
/// Explicit borrowed execution binding passed to Machine::run().
struct ExecutionBinding {
Async::Executor* executor{nullptr};
const Time::MonotonicClock* clock{
&Time::SystemMonotonicClock::instance()};
FsmLimits limits{};
};
/// Versioned boundary checkpoint capturing machine identity, schema,
/// durable state ID, optional application safe-point resume label, and
/// serialized application state.
struct Checkpoint {
static constexpr std::uint32_t kFormatVersion = 1;
std::uint32_t format_version{kFormatVersion};
std::string machine_type;
std::uint32_t application_schema{1};
std::uint64_t transition_sequence{0};
std::string state_id;
std::string resume_label;
Json::Value state;
};
/// Annotation tag specifying a durable state ID (`[[= Void::Fsm::StateId{"..."}]]`).
struct StateId {
Void::Meta::Str value;
};
/// Byte-size accounting helper for typed event admission into bounded
/// FSM mailboxes.
template <typename E>
[[nodiscard]] constexpr std::size_t event_payload_bytes(const E& e) noexcept
{
if constexpr (requires {
{
e.payload_bytes()
} -> std::convertible_to<std::size_t>;
}) {
return static_cast<std::size_t>(e.payload_bytes());
} else if constexpr (std::is_same_v<std::remove_cvref_t<E>,
std::string>) {
return sizeof(E) + e.size();
} else {
return sizeof(E);
}
}
/// The outcome of a sub-machine launched via startMachine<Sub, Next>():
/// a typed Success value, a typed Failure value, or a system fault.
struct LaunchResult {