Add Service registry and rewrite Fsm as an inheritance/coroutine workflow

Service module (Void::Service):
- IService base (service_name + on_start/on_stop lifecycle).
- ServiceRegistry: type-keyed container — provide<I>(impl), get<I>()
  (nullptr if absent), require<I>() (throws), has<I>(), start_all/
  stop_all. Consumers depend only on the interface I and resolve at
  runtime (dependency inversion); a concrete that derives IService is
  recovered for lifecycle via dynamic_cast even when registered under a
  plain interface. shared_mutex; reads are the hot path.

New Void::Fsm — a single inheritance + coroutine workflow FSM replacing
the deleted statechart/compile-time FSMs:
- Derive Machine<ResultT>; declare states as nested structs deriving
  State; each implements Coro::Task<Step> run() returning next<S>() /
  succeed(...) / fail(...).
- Async by default: a non-template Detail::ExecutionContext owns one
  ManualExecutor + worker thread + a lock-free MPSC event queue + a typed
  event mailbox; a single consumer touches all mutable state so state
  code is lock-free/single-threaded. Embedder mode (own_worker=false)
  drives via pump() for deterministic tests.
- Events: co_await await_event<E>() consumes the oldest queued E (typed
  mailbox), suspending until one arrives; post<E>(e) is lock-free from
  any thread.
- Nesting: co_await run_child<Sub>(args...) runs a child on the same
  executor (shared events/services) and yields its Outcome.
- Dynamic: add<S>() / add_if<S>(cond) register states; next<unregistered>
  fails; has_state<S>() lets states branch.
- Services: set_services(registry); state.service<I>() resolves through
  the injected context.
- Observation: current_state() is a lock-free atomic-index read of an
  immutable name table (P2996 identifier_of, fallback to indexed names).
- Persistence: serialize() captures {state name, on_serialize data};
  restore() on an un-started machine resumes at the named state.

26 new tests (Service registry; FSM basic/success/fail, events incl.
cross-thread worker + order, nesting incl. failure propagation,
serialize/restore, dynamic registration, service resolution, and a
6-producer x 5k concurrent-post stress + lock-free current_state reader
check). 960 green, ASan+UBSan clean, stable across 10 runs, -Werror clean.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Fable 5 committed 2026-06-14 00:39:05 +03:00
1 parent 04cf1998bd
commit cfeaf93a53
14 files changed
+1744

No files matched your search

+111
View File
@@ -0,0 +1,111 @@
#pragma once
#include <Void/Async/Executor.hpp>
#include <Void/Async/MpscQueue.hpp>
#include <Void/Async/Task.hpp>
#include <Void/Fsm/Step.hpp>
#include <any>
#include <atomic>
#include <coroutine>
#include <cstddef>
#include <deque>
#include <mutex>
#include <semaphore>
#include <thread>
#include <typeindex>
#include <typeinfo>
#include <unordered_map>
namespace Void::Fsm::Detail
{
/// Type-erased state. Concrete states derive Machine<R>::State, which
/// derives this; run() is driven by the engine.
class StateBase
{
public:
virtual ~StateBase() = default;
virtual Coro::Task<Step> run() = 0;
};
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).
[[nodiscard]] bool try_take(const std::type_info& type,
std::any& out);
void set_waiter(const std::type_info& type,
std::coroutine_handle<> cont, std::any* slot);
// ── 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.
std::size_t pump();
private:
void deliver(EventEnvelope& env);
void run_loop();
void wake() noexcept;
Async::ManualExecutor m_executor;
Async::MpscQueue<EventEnvelope> m_queue;
std::unordered_map<std::type_index, std::deque<std::any>> m_buffers;
struct Waiter {
const std::type_info* type{nullptr};
std::coroutine_handle<> cont{};
std::any* slot{nullptr};
};
Waiter m_waiter;
std::counting_semaphore<> m_wakeup{0};
std::atomic<bool> m_sleeping{false};
std::atomic<bool> m_done{false};
std::atomic<bool> m_worker_started{false};
std::once_flag m_worker_once;
std::thread m_worker;
};
} // namespace Void::Fsm::Detail