Files
Library/include/Void/Fsm/Detail/Engine.hpp
T
faumarayandClaude Opus 4.8 80293ee56f Add async/resilience/reflection primitives + FSM v2 rewrite
A round of new universal capabilities (all generic — templated/reflection
based, no app coupling), verified by the test suite (1103 passing):

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

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

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

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 15:45:16 +03:00

181 lines
5.4 KiB
C++

#pragma once
#include <Void/Async/Executor.hpp>
#include <Void/Async/MpscQueue.hpp>
#include <Void/Async/Task.hpp>
#include <Void/Fsm/StateKey.hpp>
#include <any>
#include <atomic>
#include <chrono>
#include <coroutine>
#include <cstddef>
#include <cstdint>
#include <deque>
#include <functional>
#include <map>
#include <mutex>
#include <optional>
#include <semaphore>
#include <span>
#include <thread>
#include <typeindex>
#include <typeinfo>
#include <unordered_map>
#include <vector>
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).
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().
virtual Coro::Task<void> on_enter();
virtual Coro::Task<void> on_exit();
};
struct EventEnvelope {
const std::type_info* type{nullptr};
std::any value;
};
/// 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.
class ExecutionContext
{
public:
ExecutionContext() = default;
~ExecutionContext();
ExecutionContext(const ExecutionContext&) = delete;
ExecutionContext& operator=(const ExecutionContext&) = delete;
[[nodiscard]] Async::ManualExecutor& executor() noexcept
{
return m_executor;
}
// ── events (post is the only cross-thread entry point) ────────
void post(EventEnvelope env);
// Mailbox ops — consumer thread only (called from awaiters that
// run on the executor, and from the worker drain).
using TimerId = std::uint64_t;
/// Pop the oldest buffered event whose type is in `types`.
[[nodiscard]] bool
try_take_any(std::span<const std::type_info* const> types,
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(
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);
/// 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_timer(TimerId id);
// ── worker lifecycle ─────────────────────────────────────────
/// Spawn the worker thread (idempotent).
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.
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);
/// Wake the consumer (e.g. to re-check an external jump request).
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;
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};
std::vector<const std::type_info*> types;
std::coroutine_handle<> cont{};
EventEnvelope* slot{nullptr};
bool* timed_out{nullptr};
TimerId timer{0};
[[nodiscard]] bool wants(const std::type_info& t) const
{
for (const auto* ty : types) {
if (*ty == t) {
return true;
}
}
return false;
}
};
// Several waiters can be parked at once (parallel regions, deferred
// events). An event resumes the first (FIFO) that wants its type.
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::counting_semaphore<> m_wakeup{0};
std::atomic<bool> m_sleeping{false};
std::atomic<bool> m_done{false};
std::atomic<bool> m_paused{false};
std::atomic<bool> m_worker_started{false};
std::once_flag m_worker_once;
std::thread m_worker;
};
} // namespace Void::Fsm::Detail