feat(fsm): structured scopes, race-loser join, boundary checkpoints, and bounded supervision
This commit is contained in:
1 parent
1dc51d5c43
commit
ef5312c4b3
11 files changed
+3819
-541
No files matched your search
@@ -1,41 +1,90 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <Void/Fsm/Detail/Engine.hpp>
|
#include <Void/Fsm/Detail/Engine.hpp>
|
||||||
|
#include <Void/Time/Clock.hpp>
|
||||||
|
|
||||||
#include <chrono>
|
#include <chrono>
|
||||||
#include <coroutine>
|
#include <coroutine>
|
||||||
#include <optional>
|
#include <optional>
|
||||||
#include <span>
|
#include <span>
|
||||||
|
#include <stop_token>
|
||||||
#include <typeinfo>
|
#include <typeinfo>
|
||||||
#include <utility>
|
#include <utility>
|
||||||
|
|
||||||
namespace Void::Fsm::Detail
|
namespace Void::Fsm::Detail
|
||||||
{
|
{
|
||||||
/// One awaiter for every "wait for an event (optionally with a deadline)"
|
struct WaiterCancelFn {
|
||||||
/// operation on a machine. `Storage` is the type-list container (a
|
ExecutionContext* ctx{nullptr};
|
||||||
/// std::array for fixed sets, a std::vector for dynamic ones); `Resume` is
|
ExecutionContext::WaiterId waiter_id{0};
|
||||||
/// the projection `(EventEnvelope&&, bool timed_out) -> R` that shapes the
|
|
||||||
/// awaited value (the matched event, an optional on timeout, a variant,
|
void operator()() const
|
||||||
/// …). Built on ExecutionContext::{try_take_any,set_waiter}.
|
{
|
||||||
|
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 {
|
template <typename Storage, typename Resume> struct EventAwaiter {
|
||||||
ExecutionContext* ctx;
|
ExecutionContext* ctx{nullptr};
|
||||||
Storage types;
|
Storage types{};
|
||||||
EventEnvelope env;
|
EventEnvelope env{};
|
||||||
bool timed_out{false};
|
bool timed_out{false};
|
||||||
std::optional<std::chrono::steady_clock::time_point> deadline;
|
bool cancelled{false};
|
||||||
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{};
|
||||||
|
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()
|
[[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)
|
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:
|
private:
|
||||||
@@ -49,10 +98,24 @@ namespace Void::Fsm::Detail
|
|||||||
template <typename Storage, typename Resume>
|
template <typename Storage, typename Resume>
|
||||||
[[nodiscard]] auto make_event_awaiter(
|
[[nodiscard]] auto make_event_awaiter(
|
||||||
ExecutionContext* ctx, Storage types,
|
ExecutionContext* ctx, Storage types,
|
||||||
std::optional<std::chrono::steady_clock::time_point> deadline,
|
std::optional<Time::MonotonicClock::time_point> deadline,
|
||||||
Resume resume)
|
Resume resume,
|
||||||
|
ExecutionContext::ScopeId scope = ExecutionContext::kNoScope,
|
||||||
|
std::stop_token scope_stop = {}, std::stop_token user_stop = {})
|
||||||
{
|
{
|
||||||
return EventAwaiter<Storage, Resume>{
|
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
|
} // namespace Void::Fsm::Detail
|
||||||
@@ -4,6 +4,8 @@
|
|||||||
#include <Void/Async/MpscQueue.hpp>
|
#include <Void/Async/MpscQueue.hpp>
|
||||||
#include <Void/Async/Task.hpp>
|
#include <Void/Async/Task.hpp>
|
||||||
#include <Void/Fsm/StateKey.hpp>
|
#include <Void/Fsm/StateKey.hpp>
|
||||||
|
#include <Void/Functional/Result.hpp>
|
||||||
|
#include <Void/Time/Clock.hpp>
|
||||||
|
|
||||||
#include <any>
|
#include <any>
|
||||||
#include <atomic>
|
#include <atomic>
|
||||||
@@ -14,6 +16,7 @@
|
|||||||
#include <deque>
|
#include <deque>
|
||||||
#include <functional>
|
#include <functional>
|
||||||
#include <map>
|
#include <map>
|
||||||
|
#include <memory>
|
||||||
#include <mutex>
|
#include <mutex>
|
||||||
#include <optional>
|
#include <optional>
|
||||||
#include <semaphore>
|
#include <semaphore>
|
||||||
@@ -28,17 +31,14 @@ namespace Void::Fsm::Detail
|
|||||||
{
|
{
|
||||||
/// Type-erased state. Concrete states derive the single Machine<Derived>::
|
/// Type-erased state. Concrete states derive the single Machine<Derived>::
|
||||||
/// State base; the engine drives each via a signature-inferred per-state
|
/// State base; the engine drives each via a signature-inferred per-state
|
||||||
/// thunk (entry / reactive table / continuation handlers).
|
/// thunk (entry / continuation handlers).
|
||||||
class StateBase
|
class StateBase
|
||||||
{
|
{
|
||||||
public:
|
public:
|
||||||
|
|
||||||
virtual ~StateBase() = default;
|
virtual ~StateBase() = default;
|
||||||
|
|
||||||
/// Optional entry/exit lifecycle hooks (default no-ops). The
|
/// Optional entry/exit lifecycle hooks (default no-ops).
|
||||||
/// state's behaviour (entry / reactive table / continuation
|
|
||||||
/// handlers) is discovered by signature via a per-state driver
|
|
||||||
/// thunk — there is no virtual run().
|
|
||||||
virtual Coro::Task<void> on_enter();
|
virtual Coro::Task<void> on_enter();
|
||||||
virtual Coro::Task<void> on_exit();
|
virtual Coro::Task<void> on_exit();
|
||||||
};
|
};
|
||||||
@@ -46,18 +46,28 @@ namespace Void::Fsm::Detail
|
|||||||
struct EventEnvelope {
|
struct EventEnvelope {
|
||||||
const std::type_info* type{nullptr};
|
const std::type_info* type{nullptr};
|
||||||
std::any value;
|
std::any value;
|
||||||
|
std::size_t bytes{0};
|
||||||
};
|
};
|
||||||
|
|
||||||
/// Shared execution substrate for a machine and any machines it nests:
|
/// Shared execution substrate for a machine and any machines it nests:
|
||||||
/// one executor + one worker thread + one typed event mailbox. A single
|
/// one logical strand (owned worker, embedder pump(), or borrowed external
|
||||||
/// consumer (the worker, or the embedder via pump()) touches all
|
/// executor) + bounded event mailbox + reserved control lane + Clock-driven
|
||||||
/// mailbox state, so state code runs lock-free and single-threaded;
|
/// timers. Cross-thread posts enqueue owned envelopes; only the active
|
||||||
/// cross-thread post() only enqueues.
|
/// consumer strand touches waiter/timer/buffer tables.
|
||||||
class ExecutionContext
|
class ExecutionContext
|
||||||
|
: public std::enable_shared_from_this<ExecutionContext>
|
||||||
{
|
{
|
||||||
public:
|
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();
|
||||||
|
|
||||||
ExecutionContext(const ExecutionContext&) = delete;
|
ExecutionContext(const ExecutionContext&) = delete;
|
||||||
@@ -67,14 +77,61 @@ namespace Void::Fsm::Detail
|
|||||||
{
|
{
|
||||||
return m_executor;
|
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);
|
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
|
// ── strand-only scope/waiter/timer APIs ──────────────────────
|
||||||
// run on the executor, and from the worker drain).
|
[[nodiscard]] ScopeId allocate_scope() noexcept
|
||||||
|
{
|
||||||
using TimerId = std::uint64_t;
|
return m_next_scope.fetch_add(1, std::memory_order_relaxed);
|
||||||
|
}
|
||||||
|
|
||||||
/// Pop the oldest buffered event whose type is in `types`.
|
/// Pop the oldest buffered event whose type is in `types`.
|
||||||
[[nodiscard]] bool
|
[[nodiscard]] bool
|
||||||
@@ -82,68 +139,66 @@ namespace Void::Fsm::Detail
|
|||||||
EventEnvelope& out);
|
EventEnvelope& out);
|
||||||
|
|
||||||
/// Suspend until an event of one of `types` arrives, or (if
|
/// Suspend until an event of one of `types` arrives, or (if
|
||||||
/// `deadline` is set) the deadline passes. `slot` receives the
|
/// `deadline` is set) the deadline passes, or the waiter/scope is
|
||||||
/// matched event; `*timed_out` is set true on timeout.
|
/// cancelled.
|
||||||
void set_waiter(
|
WaiterId set_waiter(
|
||||||
std::span<const std::type_info* const> types,
|
std::span<const std::type_info* const> types,
|
||||||
std::coroutine_handle<> cont, EventEnvelope* slot,
|
std::coroutine_handle<> cont, EventEnvelope* slot,
|
||||||
bool* timed_out,
|
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
|
void cancel_waiter(WaiterId id);
|
||||||
/// cancel_timer.
|
void cancel_scope(ScopeId scope);
|
||||||
TimerId add_timer(std::chrono::steady_clock::time_point deadline,
|
void purge_scope(ScopeId scope);
|
||||||
std::function<void()>
|
void drain_control_queue();
|
||||||
on_fire);
|
|
||||||
|
/// 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);
|
void cancel_timer(TimerId id);
|
||||||
|
|
||||||
// ── worker lifecycle ─────────────────────────────────────────
|
// ── worker / pump lifecycle ──────────────────────────────────
|
||||||
/// Spawn the worker thread (idempotent).
|
|
||||||
void start_worker();
|
void start_worker();
|
||||||
/// Mark finished and wake the worker so it can exit.
|
|
||||||
void finish();
|
void finish();
|
||||||
/// Stop and join the worker.
|
|
||||||
void stop();
|
void stop();
|
||||||
/// Join the worker without forcing finish (waits for the
|
|
||||||
/// driver to finish() on its own).
|
|
||||||
void join();
|
void join();
|
||||||
[[nodiscard]] bool finished() const noexcept
|
[[nodiscard]] bool finished() const noexcept
|
||||||
{
|
{
|
||||||
return m_done.load(std::memory_order_acquire);
|
return m_done.load(std::memory_order_acquire);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Embedder-driven step: deliver queued events + run ready
|
/// Embedder-driven step: drain control lane, fire due timers on
|
||||||
/// coroutines. Returns work done count. Single consumer only.
|
/// injected clock, deliver up to max_events_per_turn /
|
||||||
/// A no-op (returns 0) while paused.
|
/// max_turn_duration user events, and drain internal executor.
|
||||||
std::size_t pump();
|
std::size_t pump();
|
||||||
|
|
||||||
/// Pause / resume event processing. While paused the worker stops
|
/// Called on external executor threads via scheduled task.
|
||||||
/// draining (and pump() is a no-op); posted events buffer.
|
void run_external_pump_step();
|
||||||
void set_paused(bool paused);
|
|
||||||
|
|
||||||
/// Wake the consumer (e.g. to re-check an external jump request).
|
void set_paused(bool paused);
|
||||||
void nudge() { wake(); }
|
void nudge() { wake(); }
|
||||||
|
|
||||||
private:
|
private:
|
||||||
|
|
||||||
void deliver(EventEnvelope& env);
|
struct BufferedEvent {
|
||||||
void run_loop();
|
std::any value;
|
||||||
void wake() noexcept;
|
std::size_t bytes{0};
|
||||||
void fire_due_timers();
|
};
|
||||||
[[nodiscard]] std::optional<std::chrono::steady_clock::time_point>
|
|
||||||
next_deadline() const;
|
|
||||||
|
|
||||||
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 {
|
struct Waiter {
|
||||||
WaiterId id{0};
|
WaiterId id{0};
|
||||||
|
ScopeId scope{kNoScope};
|
||||||
std::vector<const std::type_info*> types;
|
std::vector<const std::type_info*> types;
|
||||||
std::coroutine_handle<> cont{};
|
std::coroutine_handle<> cont{};
|
||||||
EventEnvelope* slot{nullptr};
|
EventEnvelope* slot{nullptr};
|
||||||
bool* timed_out{nullptr};
|
bool* timed_out{nullptr};
|
||||||
|
bool* cancelled{nullptr};
|
||||||
TimerId timer{0};
|
TimerId timer{0};
|
||||||
|
|
||||||
[[nodiscard]] bool wants(const std::type_info& t) const
|
[[nodiscard]] bool wants(const std::type_info& t) const
|
||||||
@@ -156,20 +211,52 @@ namespace Void::Fsm::Detail
|
|||||||
return false;
|
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;
|
std::vector<Waiter> m_waiters;
|
||||||
WaiterId m_next_waiter{1};
|
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;
|
std::map<TimerId, Timer> m_timers;
|
||||||
TimerId m_next_timer{1};
|
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::counting_semaphore<> m_wakeup{0};
|
||||||
std::atomic<bool> m_sleeping{false};
|
std::atomic<bool> m_sleeping{false};
|
||||||
|
std::atomic<bool> m_pump_scheduled{false};
|
||||||
std::atomic<bool> m_done{false};
|
std::atomic<bool> m_done{false};
|
||||||
std::atomic<bool> m_paused{false};
|
std::atomic<bool> m_paused{false};
|
||||||
std::atomic<bool> m_worker_started{false};
|
std::atomic<bool> m_worker_started{false};
|
||||||
|
|||||||
+1500
-387
File diff suppressed because it is too large.
Load diff
@@ -1,27 +1,73 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <Void/Fsm/StateKey.hpp>
|
#include <Void/Fsm/StateKey.hpp>
|
||||||
|
#include <Void/Functional/Result.hpp>
|
||||||
#include <Void/Service/Registry.hpp>
|
#include <Void/Service/Registry.hpp>
|
||||||
|
#include <Void/Time/Clock.hpp>
|
||||||
|
|
||||||
|
#include <atomic>
|
||||||
|
#include <chrono>
|
||||||
#include <cstddef>
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <functional>
|
||||||
#include <memory>
|
#include <memory>
|
||||||
#include <mutex>
|
#include <mutex>
|
||||||
|
#include <optional>
|
||||||
|
#include <string>
|
||||||
#include <utility>
|
#include <utility>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
namespace Void::Fsm
|
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
|
namespace Detail
|
||||||
{
|
{
|
||||||
// Type-erased supervised FSM. Models wrap a concrete Machine<R>
|
// 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
|
class FsmConcept
|
||||||
{
|
{
|
||||||
public:
|
public:
|
||||||
|
|
||||||
virtual ~FsmConcept() = default;
|
virtual ~FsmConcept() = default;
|
||||||
virtual void stop() = 0;
|
virtual void stop() = 0;
|
||||||
|
virtual void restart() = 0;
|
||||||
[[nodiscard]] virtual Status status() const = 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
|
template <typename F> class FsmModel final : public FsmConcept
|
||||||
@@ -34,10 +80,21 @@ namespace Void::Fsm
|
|||||||
}
|
}
|
||||||
|
|
||||||
void stop() override { m_fsm->stop(); }
|
void stop() override { m_fsm->stop(); }
|
||||||
|
void restart() override { m_fsm->restart(); }
|
||||||
[[nodiscard]] Status status() const override
|
[[nodiscard]] Status status() const override
|
||||||
{
|
{
|
||||||
return m_fsm->status();
|
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; }
|
[[nodiscard]] F& get() noexcept { return *m_fsm; }
|
||||||
|
|
||||||
@@ -45,10 +102,27 @@ namespace Void::Fsm
|
|||||||
|
|
||||||
std::unique_ptr<F> m_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
|
} // namespace Detail
|
||||||
|
|
||||||
/// A non-owning supervision handle to a launched FSM: query status and
|
/// Owning handle to a supervised FSM instance: holds a shared_ptr so
|
||||||
/// stop it. The Orchestrator owns the FSM's lifetime.
|
/// immutable termination evidence and any still-required cleanup ownership
|
||||||
|
/// survive even after the Orchestrator releases a finished entry from
|
||||||
|
/// active supervision.
|
||||||
class FsmHandle
|
class FsmHandle
|
||||||
{
|
{
|
||||||
public:
|
public:
|
||||||
@@ -57,48 +131,92 @@ namespace Void::Fsm
|
|||||||
|
|
||||||
void stop() const
|
void stop() const
|
||||||
{
|
{
|
||||||
if (m_impl) {
|
if (m_entry && m_entry->model) {
|
||||||
m_impl->stop();
|
m_entry->model->stop();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
[[nodiscard]] Status status() const
|
[[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();
|
if (!m_entry) {
|
||||||
return s == Status::Succeeded || s == Status::Failed;
|
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
|
[[nodiscard]] explicit operator bool() const noexcept
|
||||||
{
|
{
|
||||||
return m_impl != nullptr;
|
return m_entry != nullptr && m_entry->model != nullptr;
|
||||||
}
|
}
|
||||||
|
|
||||||
private:
|
private:
|
||||||
|
|
||||||
friend class Orchestrator;
|
friend class Orchestrator;
|
||||||
explicit FsmHandle(std::shared_ptr<Detail::FsmConcept> impl)
|
explicit FsmHandle(std::shared_ptr<Detail::SupervisedEntry> entry)
|
||||||
: m_impl(std::move(impl))
|
: m_entry(std::move(entry))
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
|
|
||||||
std::shared_ptr<Detail::FsmConcept> m_impl;
|
std::shared_ptr<Detail::SupervisedEntry> m_entry;
|
||||||
};
|
};
|
||||||
|
|
||||||
// ── Orchestrator ──────────────────────────────────────────────────────
|
// ── 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
|
class Orchestrator
|
||||||
{
|
{
|
||||||
public:
|
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() { stop_all(); }
|
||||||
|
|
||||||
Orchestrator(const Orchestrator&) = delete;
|
Orchestrator(const Orchestrator&) = delete;
|
||||||
@@ -109,8 +227,6 @@ namespace Void::Fsm
|
|||||||
return m_registry;
|
return m_registry;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Call on_start() on lifecycle services. Call before launching
|
|
||||||
/// FSMs that expect started services.
|
|
||||||
void start_services()
|
void start_services()
|
||||||
{
|
{
|
||||||
m_registry.start_all();
|
m_registry.start_all();
|
||||||
@@ -118,36 +234,177 @@ namespace Void::Fsm
|
|||||||
m_services_stopped = false;
|
m_services_stopped = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Construct F, inject the registry, start it, and supervise.
|
template <typename F, typename... Args>
|
||||||
/// F must derive Fsm::Machine<...> (provides set_services /
|
[[nodiscard]] Void::Result::Result<FsmHandle>
|
||||||
/// start / stop / status).
|
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>
|
template <typename F, typename... Args>
|
||||||
FsmHandle launch(Args&&... args)
|
FsmHandle launch(Args&&... args)
|
||||||
{
|
{
|
||||||
auto fsm = std::make_unique<F>(std::forward<Args>(args)...);
|
auto r = try_launch<F>(SupervisionPolicy{},
|
||||||
fsm->set_services(m_registry);
|
std::forward<Args>(args)...);
|
||||||
fsm->start();
|
return r ? *r : FsmHandle{};
|
||||||
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};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Stop and release every supervised FSM, then stop services.
|
/// Drive supervision rules (bounded restarts with injected Time
|
||||||
void stop_all()
|
/// 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};
|
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();
|
running.clear();
|
||||||
// Balance start_services() exactly once (stop_all may run
|
|
||||||
// explicitly and again from the destructor).
|
|
||||||
if (m_services_started && !m_services_stopped) {
|
if (m_services_started && !m_services_stopped) {
|
||||||
m_registry.stop_all();
|
m_registry.stop_all();
|
||||||
m_services_stopped = true;
|
m_services_stopped = true;
|
||||||
@@ -157,16 +414,118 @@ namespace Void::Fsm
|
|||||||
[[nodiscard]] std::size_t running_count() const
|
[[nodiscard]] std::size_t running_count() const
|
||||||
{
|
{
|
||||||
std::lock_guard lock{m_mutex};
|
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:
|
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;
|
Service::ServiceRegistry m_registry;
|
||||||
mutable std::mutex m_mutex;
|
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_started{false};
|
||||||
bool m_services_stopped{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
|
} // namespace Void::Fsm
|
||||||
@@ -1,10 +1,22 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
|
#include <Void/Async/Executor.hpp>
|
||||||
#include <Void/Async/Task.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 <any>
|
||||||
|
#include <chrono>
|
||||||
|
#include <concepts>
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
#include <functional>
|
#include <functional>
|
||||||
#include <string>
|
#include <string>
|
||||||
|
#include <string_view>
|
||||||
|
#include <type_traits>
|
||||||
#include <typeinfo>
|
#include <typeinfo>
|
||||||
#include <utility>
|
#include <utility>
|
||||||
|
|
||||||
@@ -33,6 +45,153 @@ namespace Void::Fsm
|
|||||||
Faulted // stopped by a system fault (see system_error())
|
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>():
|
/// The outcome of a sub-machine launched via startMachine<Sub, Next>():
|
||||||
/// a typed Success value, a typed Failure value, or a system fault.
|
/// a typed Success value, a typed Failure value, or a system fault.
|
||||||
struct LaunchResult {
|
struct LaunchResult {
|
||||||
|
|||||||
+361
-40
@@ -1,22 +1,152 @@
|
|||||||
#include <Void/Fsm/Detail/Engine.hpp>
|
#include <Void/Fsm/Detail/Engine.hpp>
|
||||||
|
#include <Void/Log/Log.hpp>
|
||||||
|
|
||||||
#include <algorithm>
|
#include <algorithm>
|
||||||
#include <utility>
|
#include <utility>
|
||||||
|
|
||||||
namespace Void::Fsm::Detail
|
namespace Void::Fsm::Detail
|
||||||
{
|
{
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
Coro::Task<void> external_pump_task(
|
||||||
|
std::weak_ptr<ExecutionContext> weak_ctx)
|
||||||
|
{
|
||||||
|
if (auto ctx = weak_ctx.lock()) {
|
||||||
|
ctx->run_external_pump_step();
|
||||||
|
}
|
||||||
|
co_return;
|
||||||
|
}
|
||||||
|
} // namespace
|
||||||
|
|
||||||
// Default state lifecycle hooks (no-ops). The state's behaviour is driven
|
|
||||||
// by a per-state, signature-inferred thunk built at registration.
|
|
||||||
Coro::Task<void> StateBase::on_enter() { co_return; }
|
Coro::Task<void> StateBase::on_enter() { co_return; }
|
||||||
Coro::Task<void> StateBase::on_exit() { co_return; }
|
Coro::Task<void> StateBase::on_exit() { co_return; }
|
||||||
|
|
||||||
|
ExecutionContext::ExecutionContext(const Time::MonotonicClock* clock,
|
||||||
|
FsmLimits limits,
|
||||||
|
Async::Executor* external_executor)
|
||||||
|
: m_clock(clock != nullptr ? clock
|
||||||
|
: &Time::SystemMonotonicClock::instance()),
|
||||||
|
m_limits(limits), m_external_executor(external_executor)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
ExecutionContext::~ExecutionContext() { stop(); }
|
ExecutionContext::~ExecutionContext() { stop(); }
|
||||||
|
|
||||||
|
bool ExecutionContext::try_acquire_child_regions(std::size_t count) noexcept
|
||||||
|
{
|
||||||
|
if (count == 0) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
std::size_t cur =
|
||||||
|
m_active_child_regions.load(std::memory_order_acquire);
|
||||||
|
for (;;) {
|
||||||
|
if (count > m_limits.max_child_regions ||
|
||||||
|
cur > m_limits.max_child_regions - count) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (m_active_child_regions.compare_exchange_weak(
|
||||||
|
cur, cur + count, std::memory_order_acq_rel,
|
||||||
|
std::memory_order_acquire)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void ExecutionContext::release_child_regions(std::size_t count) noexcept
|
||||||
|
{
|
||||||
|
if (count == 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
m_active_child_regions.fetch_sub(count, std::memory_order_acq_rel);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<void> ExecutionContext::try_post(EventEnvelope env)
|
||||||
|
{
|
||||||
|
if (m_done.load(std::memory_order_acquire)) {
|
||||||
|
return Void::Result::fail(make_fsm_error(
|
||||||
|
FsmErrorCode::invalid_state,
|
||||||
|
"ExecutionContext::try_post: context stopped"));
|
||||||
|
}
|
||||||
|
|
||||||
|
const std::size_t bytes = env.bytes;
|
||||||
|
std::size_t cur_ev = m_queued_events.load(std::memory_order_acquire);
|
||||||
|
for (;;) {
|
||||||
|
if (m_limits.max_mailbox_events > 0 &&
|
||||||
|
cur_ev >= m_limits.max_mailbox_events) {
|
||||||
|
return Void::Result::fail(make_fsm_error(
|
||||||
|
FsmErrorCode::overloaded,
|
||||||
|
"ExecutionContext::try_post: mailbox event limit reached"));
|
||||||
|
}
|
||||||
|
if (m_queued_events.compare_exchange_weak(
|
||||||
|
cur_ev, cur_ev + 1, std::memory_order_acq_rel,
|
||||||
|
std::memory_order_acquire)) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
std::size_t cur_bytes = m_queued_bytes.load(std::memory_order_acquire);
|
||||||
|
for (;;) {
|
||||||
|
if (m_limits.max_mailbox_bytes > 0 &&
|
||||||
|
(bytes > m_limits.max_mailbox_bytes ||
|
||||||
|
cur_bytes > m_limits.max_mailbox_bytes - bytes)) {
|
||||||
|
m_queued_events.fetch_sub(1, std::memory_order_acq_rel);
|
||||||
|
return Void::Result::fail(make_fsm_error(
|
||||||
|
FsmErrorCode::overloaded,
|
||||||
|
"ExecutionContext::try_post: mailbox byte limit reached"));
|
||||||
|
}
|
||||||
|
if (m_queued_bytes.compare_exchange_weak(
|
||||||
|
cur_bytes, cur_bytes + bytes, std::memory_order_acq_rel,
|
||||||
|
std::memory_order_acquire)) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
m_queue.push(std::move(env));
|
||||||
|
wake();
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
void ExecutionContext::post(EventEnvelope env)
|
void ExecutionContext::post(EventEnvelope env)
|
||||||
{
|
{
|
||||||
m_queue.push(std::move(env));
|
auto r = try_post(std::move(env));
|
||||||
|
if (!r) {
|
||||||
|
Void::Log::warn("Fsm", "dropped user event: {}",
|
||||||
|
r.error().message());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<void>
|
||||||
|
ExecutionContext::try_post_control(std::function<void()> fn)
|
||||||
|
{
|
||||||
|
if (!fn) {
|
||||||
|
return Void::Result::fail(make_fsm_error(
|
||||||
|
FsmErrorCode::invalid_argument,
|
||||||
|
"ExecutionContext::try_post_control: empty callback"));
|
||||||
|
}
|
||||||
|
if (m_done.load(std::memory_order_acquire)) {
|
||||||
|
return Void::Result::fail(make_fsm_error(
|
||||||
|
FsmErrorCode::invalid_state,
|
||||||
|
"ExecutionContext::try_post_control: context stopped"));
|
||||||
|
}
|
||||||
|
|
||||||
|
std::size_t cur = m_queued_control.load(std::memory_order_acquire);
|
||||||
|
for (;;) {
|
||||||
|
if (m_limits.max_control_messages > 0 &&
|
||||||
|
cur >= m_limits.max_control_messages) {
|
||||||
|
return Void::Result::fail(make_fsm_error(
|
||||||
|
FsmErrorCode::overloaded,
|
||||||
|
"ExecutionContext::try_post_control: control lane limit reached"));
|
||||||
|
}
|
||||||
|
if (m_queued_control.compare_exchange_weak(
|
||||||
|
cur, cur + 1, std::memory_order_acq_rel,
|
||||||
|
std::memory_order_acquire)) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
m_control_queue.push(std::move(fn));
|
||||||
wake();
|
wake();
|
||||||
|
return {};
|
||||||
}
|
}
|
||||||
|
|
||||||
bool ExecutionContext::try_take_any(
|
bool ExecutionContext::try_take_any(
|
||||||
@@ -26,57 +156,170 @@ namespace Void::Fsm::Detail
|
|||||||
const auto it = m_buffers.find(std::type_index{*ty});
|
const auto it = m_buffers.find(std::type_index{*ty});
|
||||||
if (it != m_buffers.end() && !it->second.empty()) {
|
if (it != m_buffers.end() && !it->second.empty()) {
|
||||||
out.type = ty;
|
out.type = ty;
|
||||||
out.value = std::move(it->second.front());
|
out.bytes = it->second.front().bytes;
|
||||||
|
out.value = std::move(it->second.front().value);
|
||||||
it->second.pop_front();
|
it->second.pop_front();
|
||||||
|
if (m_buffered_events > 0) {
|
||||||
|
--m_buffered_events;
|
||||||
|
}
|
||||||
|
m_buffered_bytes -= std::min(m_buffered_bytes, out.bytes);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
void ExecutionContext::set_waiter(
|
ExecutionContext::WaiterId ExecutionContext::set_waiter(
|
||||||
std::span<const std::type_info* const> types,
|
std::span<const std::type_info* const> types,
|
||||||
std::coroutine_handle<> cont, EventEnvelope* slot, bool* timed_out,
|
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, bool* cancelled)
|
||||||
{
|
{
|
||||||
Waiter w;
|
Waiter w;
|
||||||
w.id = m_next_waiter++;
|
w.id = m_next_waiter++;
|
||||||
|
w.scope = scope;
|
||||||
w.types.assign(types.begin(), types.end());
|
w.types.assign(types.begin(), types.end());
|
||||||
w.cont = cont;
|
w.cont = cont;
|
||||||
w.slot = slot;
|
w.slot = slot;
|
||||||
w.timed_out = timed_out;
|
w.timed_out = timed_out;
|
||||||
|
w.cancelled = cancelled;
|
||||||
w.timer = 0;
|
w.timer = 0;
|
||||||
if (deadline.has_value()) {
|
if (deadline.has_value()) {
|
||||||
const WaiterId id = w.id;
|
const WaiterId id = w.id;
|
||||||
w.timer = add_timer(*deadline, [this, id] {
|
auto timer_res = try_add_timer(
|
||||||
// Timeout: resume that waiter (if still parked) with timed_out.
|
*deadline,
|
||||||
const auto it =
|
[this, id] {
|
||||||
std::find_if(m_waiters.begin(), m_waiters.end(),
|
const auto it = std::find_if(
|
||||||
[id](const Waiter& x) { return x.id == id; });
|
m_waiters.begin(), m_waiters.end(),
|
||||||
if (it == m_waiters.end()) {
|
[id](const Waiter& x) { return x.id == id; });
|
||||||
return;
|
if (it == m_waiters.end()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (it->timed_out != nullptr) {
|
||||||
|
*it->timed_out = true;
|
||||||
|
}
|
||||||
|
auto cont2 = it->cont;
|
||||||
|
m_waiters.erase(it);
|
||||||
|
active_executor().post_completion(cont2);
|
||||||
|
},
|
||||||
|
scope);
|
||||||
|
if (timer_res) {
|
||||||
|
w.timer = *timer_res;
|
||||||
|
} else {
|
||||||
|
// Fail safe rather than hanging forever if timer table is
|
||||||
|
// saturated.
|
||||||
|
if (timed_out != nullptr) {
|
||||||
|
*timed_out = true;
|
||||||
}
|
}
|
||||||
if (it->timed_out != nullptr) {
|
active_executor().post_completion(cont);
|
||||||
*it->timed_out = true;
|
return w.id;
|
||||||
}
|
}
|
||||||
auto cont2 = it->cont;
|
|
||||||
m_waiters.erase(it);
|
|
||||||
m_executor.post(cont2);
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
m_waiters.push_back(std::move(w));
|
m_waiters.push_back(std::move(w));
|
||||||
|
return m_waiters.back().id;
|
||||||
}
|
}
|
||||||
|
|
||||||
ExecutionContext::TimerId ExecutionContext::add_timer(
|
void ExecutionContext::cancel_waiter(WaiterId id)
|
||||||
std::chrono::steady_clock::time_point deadline,
|
|
||||||
std::function<void()>
|
|
||||||
on_fire)
|
|
||||||
{
|
{
|
||||||
|
const auto it =
|
||||||
|
std::find_if(m_waiters.begin(), m_waiters.end(),
|
||||||
|
[id](const Waiter& x) { return x.id == id; });
|
||||||
|
if (it == m_waiters.end()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
cancel_timer(it->timer);
|
||||||
|
if (it->cancelled != nullptr) {
|
||||||
|
*it->cancelled = true;
|
||||||
|
} else if (it->timed_out != nullptr) {
|
||||||
|
*it->timed_out = true;
|
||||||
|
}
|
||||||
|
auto cont = it->cont;
|
||||||
|
m_waiters.erase(it);
|
||||||
|
if (cont) {
|
||||||
|
active_executor().post_completion(cont);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void ExecutionContext::cancel_scope(ScopeId scope)
|
||||||
|
{
|
||||||
|
if (scope == kNoScope) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
std::vector<std::coroutine_handle<>> to_resume;
|
||||||
|
for (auto it = m_waiters.begin(); it != m_waiters.end();) {
|
||||||
|
if (it->scope == scope) {
|
||||||
|
cancel_timer(it->timer);
|
||||||
|
if (it->cancelled != nullptr) {
|
||||||
|
*it->cancelled = true;
|
||||||
|
} else if (it->timed_out != nullptr) {
|
||||||
|
*it->timed_out = true;
|
||||||
|
}
|
||||||
|
if (it->cont) {
|
||||||
|
to_resume.push_back(it->cont);
|
||||||
|
}
|
||||||
|
it = m_waiters.erase(it);
|
||||||
|
} else {
|
||||||
|
++it;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (auto it = m_timers.begin(); it != m_timers.end();) {
|
||||||
|
if (it->second.scope == scope) {
|
||||||
|
it = m_timers.erase(it);
|
||||||
|
} else {
|
||||||
|
++it;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (auto h : to_resume) {
|
||||||
|
active_executor().post_completion(h);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void ExecutionContext::purge_scope(ScopeId scope)
|
||||||
|
{
|
||||||
|
if (scope == kNoScope) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (auto it = m_waiters.begin(); it != m_waiters.end();) {
|
||||||
|
if (it->scope == scope) {
|
||||||
|
cancel_timer(it->timer);
|
||||||
|
it = m_waiters.erase(it);
|
||||||
|
} else {
|
||||||
|
++it;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (auto it = m_timers.begin(); it != m_timers.end();) {
|
||||||
|
if (it->second.scope == scope) {
|
||||||
|
it = m_timers.erase(it);
|
||||||
|
} else {
|
||||||
|
++it;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<ExecutionContext::TimerId>
|
||||||
|
ExecutionContext::try_add_timer(
|
||||||
|
Time::MonotonicClock::time_point deadline,
|
||||||
|
std::function<void()> on_fire, ScopeId scope)
|
||||||
|
{
|
||||||
|
if (m_limits.max_timers > 0 && m_timers.size() >= m_limits.max_timers) {
|
||||||
|
return Void::Result::fail(make_fsm_error(
|
||||||
|
FsmErrorCode::limit_exceeded,
|
||||||
|
"ExecutionContext::try_add_timer: max_timers reached"));
|
||||||
|
}
|
||||||
const TimerId id = m_next_timer++;
|
const TimerId id = m_next_timer++;
|
||||||
m_timers.emplace(id, Timer{deadline, std::move(on_fire)});
|
m_timers.emplace(id, Timer{deadline, std::move(on_fire), scope});
|
||||||
return id;
|
return id;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
ExecutionContext::TimerId
|
||||||
|
ExecutionContext::add_timer(Time::MonotonicClock::time_point deadline,
|
||||||
|
std::function<void()> on_fire,
|
||||||
|
ScopeId scope)
|
||||||
|
{
|
||||||
|
auto r = try_add_timer(deadline, std::move(on_fire), scope);
|
||||||
|
return r ? *r : 0;
|
||||||
|
}
|
||||||
|
|
||||||
void ExecutionContext::cancel_timer(TimerId id)
|
void ExecutionContext::cancel_timer(TimerId id)
|
||||||
{
|
{
|
||||||
if (id != 0) {
|
if (id != 0) {
|
||||||
@@ -84,10 +327,10 @@ namespace Void::Fsm::Detail
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
std::optional<std::chrono::steady_clock::time_point>
|
std::optional<Time::MonotonicClock::time_point>
|
||||||
ExecutionContext::next_deadline() const
|
ExecutionContext::next_deadline() const
|
||||||
{
|
{
|
||||||
std::optional<std::chrono::steady_clock::time_point> next;
|
std::optional<Time::MonotonicClock::time_point> next;
|
||||||
for (const auto& [id, timer] : m_timers) {
|
for (const auto& [id, timer] : m_timers) {
|
||||||
if (!next.has_value() || timer.deadline < *next) {
|
if (!next.has_value() || timer.deadline < *next) {
|
||||||
next = timer.deadline;
|
next = timer.deadline;
|
||||||
@@ -101,7 +344,7 @@ namespace Void::Fsm::Detail
|
|||||||
if (m_timers.empty()) {
|
if (m_timers.empty()) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const auto now = std::chrono::steady_clock::now();
|
const auto now = m_clock->now();
|
||||||
std::vector<std::function<void()>> due;
|
std::vector<std::function<void()>> due;
|
||||||
for (auto it = m_timers.begin(); it != m_timers.end();) {
|
for (auto it = m_timers.begin(); it != m_timers.end();) {
|
||||||
if (it->second.deadline <= now) {
|
if (it->second.deadline <= now) {
|
||||||
@@ -120,20 +363,36 @@ namespace Void::Fsm::Detail
|
|||||||
|
|
||||||
void ExecutionContext::deliver(EventEnvelope& env)
|
void ExecutionContext::deliver(EventEnvelope& env)
|
||||||
{
|
{
|
||||||
// Route to the first parked waiter (FIFO) that wants this type — lets
|
|
||||||
// it receive the event without ever sitting in a buffer.
|
|
||||||
for (auto it = m_waiters.begin(); it != m_waiters.end(); ++it) {
|
for (auto it = m_waiters.begin(); it != m_waiters.end(); ++it) {
|
||||||
if (it->wants(*env.type)) {
|
if (it->wants(*env.type)) {
|
||||||
*it->slot = std::move(env);
|
*it->slot = std::move(env);
|
||||||
cancel_timer(it->timer);
|
cancel_timer(it->timer);
|
||||||
auto cont = it->cont;
|
auto cont = it->cont;
|
||||||
m_waiters.erase(it);
|
m_waiters.erase(it);
|
||||||
m_executor.post(cont);
|
active_executor().post_completion(cont);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Otherwise buffer for a later await.
|
if (m_limits.max_deferred_events > 0 &&
|
||||||
m_buffers[std::type_index{*env.type}].push_back(std::move(env.value));
|
m_buffered_events >= m_limits.max_deferred_events) {
|
||||||
|
Void::Log::warn("Fsm",
|
||||||
|
"dropping deferred event: max_deferred_events reached");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
m_buffered_events += 1;
|
||||||
|
m_buffered_bytes += env.bytes;
|
||||||
|
m_buffers[std::type_index{*env.type}].push_back(
|
||||||
|
BufferedEvent{std::move(env.value), env.bytes});
|
||||||
|
}
|
||||||
|
|
||||||
|
void ExecutionContext::drain_control_queue()
|
||||||
|
{
|
||||||
|
while (auto fn = m_control_queue.try_pop()) {
|
||||||
|
m_queued_control.fetch_sub(1, std::memory_order_acq_rel);
|
||||||
|
if (*fn) {
|
||||||
|
(*fn)();
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void ExecutionContext::set_paused(bool paused)
|
void ExecutionContext::set_paused(bool paused)
|
||||||
@@ -144,22 +403,81 @@ namespace Void::Fsm::Detail
|
|||||||
|
|
||||||
std::size_t ExecutionContext::pump()
|
std::size_t ExecutionContext::pump()
|
||||||
{
|
{
|
||||||
|
drain_control_queue();
|
||||||
if (m_paused.load(std::memory_order_acquire)) {
|
if (m_paused.load(std::memory_order_acquire)) {
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
++m_dispatch_turn;
|
||||||
std::size_t work = 0;
|
std::size_t work = 0;
|
||||||
|
std::size_t events_this_turn = 0;
|
||||||
|
const auto turn_start = m_clock->now();
|
||||||
|
|
||||||
fire_due_timers();
|
fire_due_timers();
|
||||||
while (auto env = m_queue.try_pop()) {
|
|
||||||
|
while (events_this_turn < m_limits.max_events_per_turn) {
|
||||||
|
if (m_limits.max_turn_duration.count() > 0 &&
|
||||||
|
events_this_turn > 0 &&
|
||||||
|
(m_clock->now() - turn_start) >= m_limits.max_turn_duration) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
auto env = m_queue.try_pop();
|
||||||
|
if (!env) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
m_queued_events.fetch_sub(1, std::memory_order_acq_rel);
|
||||||
|
m_queued_bytes.fetch_sub(env->bytes, std::memory_order_acq_rel);
|
||||||
deliver(*env);
|
deliver(*env);
|
||||||
|
++events_this_turn;
|
||||||
++work;
|
++work;
|
||||||
}
|
}
|
||||||
work += m_executor.drain();
|
m_last_turn_events = events_this_turn;
|
||||||
|
|
||||||
|
drain_control_queue();
|
||||||
|
if (m_external_executor == nullptr) {
|
||||||
|
work += m_executor.drain();
|
||||||
|
}
|
||||||
fire_due_timers();
|
fire_due_timers();
|
||||||
|
drain_control_queue();
|
||||||
return work;
|
return work;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void ExecutionContext::run_external_pump_step()
|
||||||
|
{
|
||||||
|
if (m_done.load(std::memory_order_acquire)) {
|
||||||
|
m_pump_scheduled.store(false, std::memory_order_release);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
m_pump_scheduled.store(false, std::memory_order_seq_cst);
|
||||||
|
(void)pump();
|
||||||
|
if (!m_done.load(std::memory_order_acquire) &&
|
||||||
|
(!m_control_queue.empty() ||
|
||||||
|
(!m_paused.load(std::memory_order_acquire) && !m_queue.empty()))) {
|
||||||
|
schedule_external_pump();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void ExecutionContext::schedule_external_pump() noexcept
|
||||||
|
{
|
||||||
|
if (m_external_executor == nullptr ||
|
||||||
|
m_done.load(std::memory_order_acquire)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
auto weak = weak_from_this();
|
||||||
|
if (weak.expired()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!m_pump_scheduled.exchange(true, std::memory_order_acq_rel)) {
|
||||||
|
Async::spawn(*m_external_executor,
|
||||||
|
external_pump_task(std::move(weak)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
void ExecutionContext::wake() noexcept
|
void ExecutionContext::wake() noexcept
|
||||||
{
|
{
|
||||||
|
if (m_external_executor != nullptr) {
|
||||||
|
schedule_external_pump();
|
||||||
|
}
|
||||||
if (m_sleeping.exchange(false, std::memory_order_acq_rel)) {
|
if (m_sleeping.exchange(false, std::memory_order_acq_rel)) {
|
||||||
m_wakeup.release();
|
m_wakeup.release();
|
||||||
}
|
}
|
||||||
@@ -204,22 +522,25 @@ namespace Void::Fsm::Detail
|
|||||||
const bool paused = m_paused.load(std::memory_order_acquire);
|
const bool paused = m_paused.load(std::memory_order_acquire);
|
||||||
if (!paused) {
|
if (!paused) {
|
||||||
pump();
|
pump();
|
||||||
|
} else {
|
||||||
|
drain_control_queue();
|
||||||
}
|
}
|
||||||
if (m_done.load(std::memory_order_acquire)) {
|
if (m_done.load(std::memory_order_acquire)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
m_sleeping.store(true, std::memory_order_release);
|
m_sleeping.store(true, std::memory_order_release);
|
||||||
// Queued events only count as wakeable work when not paused.
|
if ((!paused && !m_queue.empty()) || !m_control_queue.empty() ||
|
||||||
if ((!paused && !m_queue.empty()) ||
|
|
||||||
m_done.load(std::memory_order_acquire)) {
|
m_done.load(std::memory_order_acquire)) {
|
||||||
m_sleeping.store(false, std::memory_order_release);
|
m_sleeping.store(false, std::memory_order_release);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
// Park until woken (post/resume/finish), or — when running — until
|
|
||||||
// the earliest timer is due. Paused: no timers, wait to resume.
|
|
||||||
if (const auto deadline = next_deadline();
|
if (const auto deadline = next_deadline();
|
||||||
!paused && deadline.has_value()) {
|
!paused && deadline.has_value()) {
|
||||||
(void)m_wakeup.try_acquire_until(*deadline);
|
if (m_clock == &Time::SystemMonotonicClock::instance()) {
|
||||||
|
(void)m_wakeup.try_acquire_until(*deadline);
|
||||||
|
} else {
|
||||||
|
(void)m_wakeup.try_acquire_for(std::chrono::milliseconds{1});
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
m_wakeup.acquire();
|
m_wakeup.acquire();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,3 @@
|
|||||||
void_add_module(Fsm
|
void_add_module(Fsm
|
||||||
INTERNAL_DEPS Async Core Data Functional Log Service
|
INTERNAL_DEPS Async Core Data Functional Time Log Service
|
||||||
)
|
)
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
cmake_minimum_required(VERSION 4.0)
|
||||||
|
project(VoidFsmOnlyConsumer LANGUAGES CXX)
|
||||||
|
|
||||||
|
find_package(Void CONFIG REQUIRED COMPONENTS Fsm)
|
||||||
|
|
||||||
|
add_executable(void_fsm_only_consumer main.cpp)
|
||||||
|
target_link_libraries(void_fsm_only_consumer PRIVATE Void::Fsm)
|
||||||
|
target_compile_features(void_fsm_only_consumer PRIVATE cxx_std_26)
|
||||||
|
|
||||||
|
enable_testing()
|
||||||
|
add_test(NAME FsmOnlyConsumer COMMAND void_fsm_only_consumer)
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
#include <Void/Async/Executor.hpp>
|
||||||
|
#include <Void/Async/Task.hpp>
|
||||||
|
#include <Void/Fsm/Fsm.hpp>
|
||||||
|
#include <Void/Fsm/Orchestrator.hpp>
|
||||||
|
#include <Void/Time/Clock.hpp>
|
||||||
|
|
||||||
|
#include <optional>
|
||||||
|
|
||||||
|
struct ConsumerMachine : public Void::Fsm::Machine<ConsumerMachine> {
|
||||||
|
using Success = int;
|
||||||
|
|
||||||
|
struct States {
|
||||||
|
struct Start : State {
|
||||||
|
Void::Coro::Task<Void::Fsm::StateKey> run()
|
||||||
|
{
|
||||||
|
co_return succeed(42);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
Void::Coro::Task<void> drive_consumer_fsm(
|
||||||
|
Void::Fsm::ExecutionBinding binding,
|
||||||
|
std::optional<Void::Result::Result<ConsumerMachine::Outcome<>>>* out)
|
||||||
|
{
|
||||||
|
ConsumerMachine fsm;
|
||||||
|
*out = co_await fsm.run(binding);
|
||||||
|
}
|
||||||
|
|
||||||
|
int main()
|
||||||
|
{
|
||||||
|
if (!Void::Fsm::terminal(Void::Fsm::Status::Faulted)) {
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
Void::Async::ManualExecutor exec;
|
||||||
|
Void::Time::ManualClock clock;
|
||||||
|
std::optional<Void::Result::Result<ConsumerMachine::Outcome<>>> out;
|
||||||
|
Void::Async::spawn(
|
||||||
|
exec,
|
||||||
|
drive_consumer_fsm(
|
||||||
|
{.executor = &exec, .clock = &clock}, &out));
|
||||||
|
(void)exec.drain();
|
||||||
|
if (!out.has_value() || !out->has_value() || !out->value().has_value()) {
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
return out->value().value() == 42 ? 0 : 3;
|
||||||
|
}
|
||||||
@@ -282,6 +282,16 @@ if(_has_configuration_async)
|
|||||||
-DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE)
|
-DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE)
|
||||||
endif()
|
endif()
|
||||||
|
|
||||||
|
has_modules(_has_fsm Fsm Async Core Data Functional Time Log Service)
|
||||||
|
if(_has_fsm)
|
||||||
|
run_consumer(FsmOnly "${install_prefix}" "FsmOnly"
|
||||||
|
-DCMAKE_DISABLE_FIND_PACKAGE_Boost=TRUE
|
||||||
|
-DCMAKE_DISABLE_FIND_PACKAGE_LibArchive=TRUE
|
||||||
|
-DCMAKE_DISABLE_FIND_PACKAGE_OpenSSL=TRUE
|
||||||
|
-DCMAKE_DISABLE_FIND_PACKAGE_PkgConfig=TRUE
|
||||||
|
-DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE)
|
||||||
|
endif()
|
||||||
|
|
||||||
# Foundation consumer with Core-formatting bridge and zero external packages.
|
# Foundation consumer with Core-formatting bridge and zero external packages.
|
||||||
has_modules(_has_foundation Math Text Time Functional Binary FunctionalCoreFormatting Memory Core)
|
has_modules(_has_foundation Math Text Time Functional Binary FunctionalCoreFormatting Memory Core)
|
||||||
if(_has_foundation)
|
if(_has_foundation)
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user