#include #include #include #include namespace Void::Fsm::Detail { namespace { Coro::Task external_pump_task( std::weak_ptr weak_ctx) { if (auto ctx = weak_ctx.lock()) { ctx->run_external_pump_step(); } co_return; } } // namespace Coro::Task StateBase::on_enter() { co_return; } Coro::Task 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(); } 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 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) { auto r = try_post(std::move(env)); if (!r) { Void::Log::warn("Fsm", "dropped user event: {}", r.error().message()); } } Void::Result::Result ExecutionContext::try_post_control(std::function 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(); return {}; } bool ExecutionContext::try_take_any( std::span types, EventEnvelope& out) { for (const auto* ty : types) { const auto it = m_buffers.find(std::type_index{*ty}); if (it != m_buffers.end() && !it->second.empty()) { out.type = ty; out.bytes = it->second.front().bytes; out.value = std::move(it->second.front().value); 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 false; } ExecutionContext::WaiterId ExecutionContext::set_waiter( std::span types, std::coroutine_handle<> cont, EventEnvelope* slot, bool* timed_out, std::optional deadline, ScopeId scope, bool* cancelled) { Waiter w; w.id = m_next_waiter++; w.scope = scope; w.types.assign(types.begin(), types.end()); w.cont = cont; w.slot = slot; w.timed_out = timed_out; w.cancelled = cancelled; w.timer = 0; if (deadline.has_value()) { const WaiterId id = w.id; auto timer_res = try_add_timer( *deadline, [this, id] { 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; } 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; } active_executor().post_completion(cont); return w.id; } } m_waiters.push_back(std::move(w)); return m_waiters.back().id; } void ExecutionContext::cancel_waiter(WaiterId id) { 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> 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::try_add_timer( Time::MonotonicClock::time_point deadline, std::function 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++; m_timers.emplace(id, Timer{deadline, std::move(on_fire), scope}); return id; } ExecutionContext::TimerId ExecutionContext::add_timer(Time::MonotonicClock::time_point deadline, std::function 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) { if (id != 0) { m_timers.erase(id); } } std::optional ExecutionContext::next_deadline() const { std::optional next; for (const auto& [id, timer] : m_timers) { if (!next.has_value() || timer.deadline < *next) { next = timer.deadline; } } return next; } void ExecutionContext::fire_due_timers() { if (m_timers.empty()) { return; } const auto now = m_clock->now(); std::vector> due; for (auto it = m_timers.begin(); it != m_timers.end();) { if (it->second.deadline <= now) { due.push_back(std::move(it->second.on_fire)); it = m_timers.erase(it); } else { ++it; } } for (auto& fn : due) { if (fn) { fn(); } } } void ExecutionContext::deliver(EventEnvelope& env) { for (auto it = m_waiters.begin(); it != m_waiters.end(); ++it) { if (it->wants(*env.type)) { *it->slot = std::move(env); cancel_timer(it->timer); auto cont = it->cont; m_waiters.erase(it); active_executor().post_completion(cont); return; } } if (m_limits.max_deferred_events > 0 && 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) { m_paused.store(paused, std::memory_order_release); wake(); } std::size_t ExecutionContext::pump() { drain_control_queue(); if (m_paused.load(std::memory_order_acquire)) { return 0; } ++m_dispatch_turn; std::size_t work = 0; std::size_t events_this_turn = 0; const auto turn_start = m_clock->now(); fire_due_timers(); 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); ++events_this_turn; ++work; } m_last_turn_events = events_this_turn; drain_control_queue(); if (m_external_executor == nullptr) { work += m_executor.drain(); } fire_due_timers(); drain_control_queue(); 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 { if (m_external_executor != nullptr) { schedule_external_pump(); } if (m_sleeping.exchange(false, std::memory_order_acq_rel)) { m_wakeup.release(); } } void ExecutionContext::start_worker() { if (m_worker_started.load(std::memory_order_acquire)) { return; } std::call_once(m_worker_once, [this] { m_worker = std::thread([this] { run_loop(); }); m_worker_started.store(true, std::memory_order_release); }); } void ExecutionContext::finish() { m_done.store(true, std::memory_order_release); wake(); } void ExecutionContext::stop() { m_done.store(true, std::memory_order_release); wake(); if (m_worker.joinable()) { m_worker.join(); } } void ExecutionContext::join() { if (m_worker.joinable()) { m_worker.join(); } } void ExecutionContext::run_loop() { for (;;) { const bool paused = m_paused.load(std::memory_order_acquire); if (!paused) { pump(); } else { drain_control_queue(); } if (m_done.load(std::memory_order_acquire)) { return; } m_sleeping.store(true, std::memory_order_release); if ((!paused && !m_queue.empty()) || !m_control_queue.empty() || m_done.load(std::memory_order_acquire)) { m_sleeping.store(false, std::memory_order_release); continue; } if (const auto deadline = next_deadline(); !paused && deadline.has_value()) { 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 { m_wakeup.acquire(); } m_sleeping.store(false, std::memory_order_release); } } } // namespace Void::Fsm::Detail