268 lines
7.7 KiB
C++
268 lines
7.7 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 <Void/Functional/Result.hpp>
|
|
#include <Void/Time/Clock.hpp>
|
|
|
|
#include <any>
|
|
#include <atomic>
|
|
#include <chrono>
|
|
#include <coroutine>
|
|
#include <cstddef>
|
|
#include <cstdint>
|
|
#include <deque>
|
|
#include <functional>
|
|
#include <map>
|
|
#include <memory>
|
|
#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 / continuation handlers).
|
|
class StateBase
|
|
{
|
|
public:
|
|
|
|
virtual ~StateBase() = default;
|
|
|
|
/// Optional entry/exit lifecycle hooks (default no-ops).
|
|
virtual Coro::Task<void> on_enter();
|
|
virtual Coro::Task<void> on_exit();
|
|
};
|
|
|
|
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 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:
|
|
|
|
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;
|
|
ExecutionContext& operator=(const ExecutionContext&) = delete;
|
|
|
|
[[nodiscard]] Async::ManualExecutor& executor() noexcept
|
|
{
|
|
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();
|
|
}
|
|
|
|
[[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);
|
|
|
|
// ── 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
|
|
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, 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<Time::MonotonicClock::time_point> deadline,
|
|
ScopeId scope = kNoScope, bool* cancelled = nullptr);
|
|
|
|
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 / pump lifecycle ──────────────────────────────────
|
|
void start_worker();
|
|
void finish();
|
|
void stop();
|
|
void join();
|
|
[[nodiscard]] bool finished() const noexcept
|
|
{
|
|
return m_done.load(std::memory_order_acquire);
|
|
}
|
|
|
|
/// 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();
|
|
|
|
/// Called on external executor threads via scheduled task.
|
|
void run_external_pump_step();
|
|
|
|
void set_paused(bool paused);
|
|
void nudge() { wake(); }
|
|
|
|
private:
|
|
|
|
struct BufferedEvent {
|
|
std::any value;
|
|
std::size_t bytes{0};
|
|
};
|
|
|
|
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
|
|
{
|
|
for (const auto* ty : types) {
|
|
if (*ty == t) {
|
|
return true;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
};
|
|
|
|
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};
|
|
|
|
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};
|
|
std::once_flag m_worker_once;
|
|
std::thread m_worker;
|
|
};
|
|
|
|
} // namespace Void::Fsm::Detail
|