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
+468
View File
@@ -0,0 +1,468 @@
#pragma once
#include <Void/Async/Executor.hpp>
#include <Void/Async/Task.hpp>
#include <Void/Data/Json.hpp>
#include <Void/Fsm/Detail/Engine.hpp>
#include <Void/Fsm/Step.hpp>
#include <Void/Service/Registry.hpp>
#include <any>
#include <atomic>
#include <coroutine>
#include <expected>
#include <functional>
#include <memory>
#include <optional>
#include <string>
#include <string_view>
#include <type_traits>
#include <typeindex>
#include <typeinfo>
#include <unordered_map>
#include <utility>
#include <vector>
#if __has_include(<meta>)
#include <meta>
#define VOID_HAS_FSM_REFLECTION 1
#endif
namespace Void::Fsm
{
/// Options for a Machine (namespace scope to dodge the GCC
/// nested-default-arg trap).
struct MachineOptions {
/// Spawn a worker thread on start(). When false, drive the machine
/// yourself with pump() (deterministic; used by most tests and by
/// nested children, which share the parent's worker).
bool own_worker = true;
};
// ── Machine<ResultT> ──────────────────────────────────────────────────
//
// Inheritance + coroutine workflow FSM. Derive it, declare states as
// nested structs deriving `State`, implement each state's async run()
// to return next<S>() / succeed(...) / fail(...). States may co_await
// external events and nest child machines.
//
// class Login : public Void::Fsm::Machine<bool> {
// public:
// struct Idle : State { Coro::Task<Step> run() override {
// auto c = co_await await_event<Creds>();
// co_return next<Check>(); } };
// struct Check : State { Coro::Task<Step> run() override {
// co_return service<IAuth>().ok()
// ? succeed(true) : fail("bad creds"); } };
// Login() { initial<Idle>(); add<Check>(); }
// };
template <typename ResultT = void> class Machine
{
public:
using result_type = ResultT;
using Options = MachineOptions;
using Outcome = std::expected<ResultT, FsmError>;
// ── State base ────────────────────────────────────────────────
class State : public Detail::StateBase
{
public:
[[nodiscard]] Machine& machine() const noexcept
{
return *m_machine;
}
protected:
/// Transition to another registered state.
template <typename S> [[nodiscard]] Step next() const
{
return Step::transition(typeid(S));
}
/// Finish the machine successfully.
[[nodiscard]] Step succeed() const
requires std::is_void_v<ResultT>
{
return Step::success(std::any{});
}
template <typename V>
[[nodiscard]] Step succeed(V&& value) const
requires(!std::is_void_v<ResultT>)
{
return Step::success(
std::any{ResultT(std::forward<V>(value))});
}
/// Finish the machine with a failure.
[[nodiscard]] Step fail(std::string message) const
{
return Step::failure(FsmError{std::move(message)});
}
/// Resolve a service from the injected registry.
template <typename I> [[nodiscard]] I& service() const
{
return m_machine->template service<I>();
}
/// Suspend until an event of type E is posted.
template <typename E> [[nodiscard]] auto await_event() const
{
return m_machine->template await_event<E>();
}
/// Run a child machine to completion and get its result.
template <typename Sub, typename... Args>
[[nodiscard]] auto run_child(Args&&... args) const
{
return m_machine->template run_child<Sub>(
std::forward<Args>(args)...);
}
template <typename S> [[nodiscard]] bool has_state() const
{
return m_machine->template has_state<S>();
}
private:
friend class Machine;
Machine* m_machine{nullptr};
};
// ── construction ──────────────────────────────────────────────
explicit Machine(Options options = {}) : m_options(options) {}
virtual ~Machine() { stop(); }
Machine(const Machine&) = delete;
Machine& operator=(const Machine&) = delete;
// ── registration (call from the derived ctor) ─────────────────
template <typename S> void add()
{
static_assert(std::is_base_of_v<State, S>,
"FSM state must derive Machine::State");
const std::type_info& ti = typeid(S);
const std::type_index key{ti};
if (m_factories.contains(key)) {
return;
}
const int idx = static_cast<int>(m_names.size());
m_index.emplace(key, idx);
m_names.push_back(state_name<S>());
m_name_to_type.emplace(m_names.back(), &ti);
m_factories.emplace(
key, [this]() -> std::unique_ptr<Detail::StateBase> {
auto s = std::make_unique<S>();
s->m_machine = this;
return s;
});
}
template <typename S> void initial()
{
add<S>();
m_initial = &typeid(S);
}
/// Conditionally register a state (dynamic machines).
template <typename S> void add_if(bool condition)
{
if (condition) {
add<S>();
}
}
template <typename S> [[nodiscard]] bool has_state() const
{
return m_factories.contains(std::type_index{typeid(S)});
}
// ── service context ───────────────────────────────────────────
void set_services(Service::ServiceRegistry& registry) noexcept
{
m_services = &registry;
}
template <typename I> [[nodiscard]] I& service() const
{
return m_services->template require<I>();
}
// ── lifecycle ─────────────────────────────────────────────────
void start()
{
if (m_status.load() != Status::Idle) {
return;
}
if (!m_ctx) {
m_ctx = std::make_shared<Detail::ExecutionContext>();
m_owns_ctx = true;
}
m_status.store(Status::Running);
Async::spawn(m_ctx->executor(), driver());
if (m_options.own_worker && m_owns_ctx) {
m_ctx->start_worker();
}
}
/// Block until the machine finishes, returning its outcome.
/// With a worker, joins it. In embedder mode, drives the
/// machine to completion (returns early if it parks waiting
/// for an event that never arrives). Do not call from the
/// worker thread.
Outcome wait()
{
if (m_ctx) {
if (m_options.own_worker && m_owns_ctx) {
m_ctx->join();
} else {
while (!finished()) {
if (m_ctx->pump() == 0 && !finished()) {
break; // parked on an unposted event
}
}
}
}
return take_outcome();
}
/// start() + wait().
Outcome run_blocking()
{
start();
return wait();
}
/// Drive a worker-less machine: deliver events + run ready
/// coroutines. Returns work done. Single consumer only.
std::size_t pump() { return m_ctx ? m_ctx->pump() : 0; }
[[nodiscard]] bool finished() const noexcept
{
const auto s = m_status.load();
return s == Status::Succeeded || s == Status::Failed;
}
[[nodiscard]] Status status() const noexcept
{
return m_status.load();
}
void stop()
{
if (m_owns_ctx && m_ctx) {
m_ctx->stop();
}
}
// ── events ────────────────────────────────────────────────────
template <typename E> void post(E event)
{
if (!m_ctx) {
return;
}
m_ctx->post(Detail::EventEnvelope{&typeid(E),
std::any{std::move(event)}});
}
template <typename E> [[nodiscard]] auto await_event()
{
struct Awaiter {
Detail::ExecutionContext* ctx;
std::any slot;
[[nodiscard]] bool await_ready()
{
return ctx->try_take(typeid(E), slot);
}
void await_suspend(std::coroutine_handle<> h)
{
ctx->set_waiter(typeid(E), h, &slot);
}
[[nodiscard]] E await_resume()
{
return std::any_cast<E>(std::move(slot));
}
};
return Awaiter{m_ctx.get(), {}};
}
// ── nesting ───────────────────────────────────────────────────
template <typename Sub, typename... Args>
[[nodiscard]] Coro::Task<typename Sub::Outcome>
run_child(Args&&... args)
{
Sub child{std::forward<Args>(args)...};
child.attach(m_ctx, m_services);
co_return co_await child.drive();
}
// ── observation ───────────────────────────────────────────────
[[nodiscard]] std::string current_state() const
{
const int idx = m_current.load(std::memory_order_acquire);
if (idx < 0 || idx >= static_cast<int>(m_names.size())) {
return {};
}
return m_names[static_cast<std::size_t>(idx)];
}
// ── persistence ───────────────────────────────────────────────
[[nodiscard]] Json::Value serialize() const
{
auto obj = Json::object();
obj.as_object().emplace_back("state",
Json::Value{current_state()});
Json::Value data = Json::object();
on_serialize(data);
obj.as_object().emplace_back("data", std::move(data));
return obj;
}
[[nodiscard]] std::expected<void, FsmError>
restore(const Json::Value& state)
{
if (m_status.load() != Status::Idle) {
return std::unexpected{
FsmError{"restore requires an un-started machine"}};
}
const auto* st = state.find("state");
if (st == nullptr || !st->is_string()) {
return std::unexpected{
FsmError{"malformed machine state json"}};
}
const auto it = m_name_to_type.find(st->as_string());
if (it == m_name_to_type.end()) {
return std::unexpected{
FsmError{"unknown state '" + st->as_string() + "'"}};
}
m_initial = it->second;
if (const auto* data = state.find("data")) {
on_restore(*data);
}
return {};
}
protected:
/// Override to snapshot derived FSM data into the "data" object
/// of serialize(), and to restore it.
virtual void on_serialize(Json::Value& /*data*/) const {}
virtual void on_restore(const Json::Value& /*data*/) {}
private:
template <typename>
friend class Machine; // run_child reaches child internals
// Share a parent's execution context + services (nesting).
void attach(std::shared_ptr<Detail::ExecutionContext> ctx,
Service::ServiceRegistry* services)
{
m_ctx = std::move(ctx);
m_owns_ctx = false;
if (services != nullptr) {
m_services = services;
}
m_status.store(Status::Running);
}
template <typename S> [[nodiscard]] std::string state_name()
{
#ifdef VOID_HAS_FSM_REFLECTION
return std::string{std::meta::identifier_of(^^S)};
#else
return "state" + std::to_string(m_names.size());
#endif
}
void set_current(const std::type_info* type)
{
if (const auto it = m_index.find(std::type_index{*type});
it != m_index.end()) {
m_current.store(it->second, std::memory_order_release);
}
}
// The state loop. Builds each state, runs it, follows the
// returned Step. Runs on the execution context's executor.
Coro::Task<Outcome> drive()
{
const std::type_info* cur = m_initial;
if (cur == nullptr) {
co_return std::unexpected{FsmError{"no initial state"}};
}
for (;;) {
const auto it = m_factories.find(std::type_index{*cur});
if (it == m_factories.end()) {
co_return std::unexpected{
FsmError{"transition to unregistered state"}};
}
set_current(cur);
auto state = it->second();
Step step = co_await state->run();
switch (step.kind()) {
case Step::Kind::Transition:
cur = step.target();
continue;
case Step::Kind::Success:
if constexpr (std::is_void_v<ResultT>) {
co_return Outcome{};
} else {
co_return Outcome{std::any_cast<ResultT>(
std::move(step.result()))};
}
case Step::Kind::Fail:
co_return std::unexpected{step.error()};
}
}
}
// Top-level driver: drives to completion, records the outcome,
// and signals the worker to wind down.
Coro::Task<void> driver()
{
Outcome outcome = co_await drive();
const bool ok = outcome.has_value();
m_outcome.emplace(std::move(outcome));
m_status.store(ok ? Status::Succeeded : Status::Failed,
std::memory_order_release);
if (m_owns_ctx) {
m_ctx->finish();
}
}
Outcome take_outcome()
{
if (m_outcome.has_value()) {
return std::move(*m_outcome);
}
return std::unexpected{FsmError{"machine did not finish"}};
}
Options m_options;
std::shared_ptr<Detail::ExecutionContext> m_ctx;
bool m_owns_ctx{false};
Service::ServiceRegistry* m_services{nullptr};
std::unordered_map<
std::type_index,
std::function<std::unique_ptr<Detail::StateBase>()>>
m_factories;
std::unordered_map<std::type_index, int> m_index;
std::vector<std::string> m_names;
std::unordered_map<std::string, const std::type_info*>
m_name_to_type;
const std::type_info* m_initial{nullptr};
std::atomic<int> m_current{-1};
std::atomic<Status> m_status{Status::Idle};
std::optional<Outcome> m_outcome;
};
} // namespace Void::Fsm
+76
View File
@@ -0,0 +1,76 @@
#pragma once
#include <any>
#include <string>
#include <typeinfo>
#include <utility>
namespace Void::Fsm
{
struct FsmError {
std::string message;
};
enum class Status {
Idle, // constructed, not started
Running, // worker active
Succeeded, // finished with a result
Failed // finished with an error
};
/// The outcome a state's run() returns: move to another state, finish
/// the machine with a result, or fail. Built only through the State
/// helpers (next<S>() / succeed() / fail()).
class Step
{
public:
enum class Kind { Transition, Success, Fail };
[[nodiscard]] static Step transition(const std::type_info& target)
{
Step s;
s.m_kind = Kind::Transition;
s.m_target = &target;
return s;
}
[[nodiscard]] static Step success(std::any result)
{
Step s;
s.m_kind = Kind::Success;
s.m_result = std::move(result);
return s;
}
[[nodiscard]] static Step failure(FsmError error)
{
Step s;
s.m_kind = Kind::Fail;
s.m_error = std::move(error);
return s;
}
[[nodiscard]] Kind kind() const noexcept { return m_kind; }
[[nodiscard]] const std::type_info* target() const noexcept
{
return m_target;
}
[[nodiscard]] std::any& result() noexcept { return m_result; }
[[nodiscard]] const FsmError& error() const noexcept
{
return m_error;
}
private:
Kind m_kind{Kind::Fail};
const std::type_info* m_target{nullptr};
std::any m_result;
FsmError m_error;
};
} // namespace Void::Fsm
+127
View File
@@ -0,0 +1,127 @@
#pragma once
#include <Void/Service/Service.hpp>
#include <memory>
#include <mutex>
#include <shared_mutex>
#include <stdexcept>
#include <string>
#include <type_traits>
#include <typeindex>
#include <unordered_map>
#include <vector>
namespace Void::Service
{
/// Type-keyed service container: providers register an implementation
/// against an interface type, consumers resolve by that interface and
/// never name the concrete type — the core of the dependency-inversion
/// the orchestrator and FSMs rely on.
///
/// registry.provide<IClock>(std::make_shared<SystemClock>());
/// auto& clock = registry.require<IClock>(); // no SystemClock dep
///
/// Thread-safe. Reads (get/require/has) take a shared lock; they are
/// the hot path for running FSMs resolving services per step.
class ServiceRegistry
{
public:
ServiceRegistry() = default;
ServiceRegistry(const ServiceRegistry&) = delete;
ServiceRegistry& operator=(const ServiceRegistry&) = delete;
/// Register (or replace) the implementation for interface I.
/// If I derives IService, the instance joins the lifecycle.
template <typename I> void provide(std::shared_ptr<I> impl)
{
Entry entry;
entry.impl = std::shared_ptr<void>(impl, impl.get());
if constexpr (std::is_base_of_v<IService, I>) {
entry.service = static_cast<IService*>(impl.get());
} else {
// The interface I doesn't derive IService, but the
// concrete implementation might — recover the lifecycle
// aspect by cross-cast.
entry.service = dynamic_cast<IService*>(impl.get());
}
const std::type_index key{typeid(I)};
std::unique_lock lock{m_mutex};
if (!m_services.contains(key)) {
m_order.push_back(key);
}
m_services.insert_or_assign(key, std::move(entry));
}
/// Resolve I, or nullptr if not provided.
template <typename I> [[nodiscard]] std::shared_ptr<I> get() const
{
std::shared_lock lock{m_mutex};
const auto it = m_services.find(std::type_index{typeid(I)});
if (it == m_services.end()) {
return nullptr;
}
return std::static_pointer_cast<I>(it->second.impl);
}
/// Resolve I; throws std::runtime_error if not provided.
template <typename I> [[nodiscard]] I& require() const
{
auto p = get<I>();
if (!p) {
throw std::runtime_error(
std::string{"ServiceRegistry: no service for '"} +
typeid(I).name() + "'");
}
return *p;
}
template <typename I> [[nodiscard]] bool has() const
{
std::shared_lock lock{m_mutex};
return m_services.contains(std::type_index{typeid(I)});
}
/// Call on_start() on every lifecycle service, registration
/// order.
void start_all()
{
std::shared_lock lock{m_mutex};
for (const auto& key : m_order) {
if (auto* s = m_services.at(key).service) {
s->on_start();
}
}
}
/// Call on_stop() on every lifecycle service, reverse order.
void stop_all()
{
std::shared_lock lock{m_mutex};
for (auto it = m_order.rbegin(); it != m_order.rend(); ++it) {
if (auto* s = m_services.at(*it).service) {
s->on_stop();
}
}
}
[[nodiscard]] std::size_t size() const
{
std::shared_lock lock{m_mutex};
return m_services.size();
}
private:
struct Entry {
std::shared_ptr<void> impl;
IService* service = nullptr; // non-null iff I : IService
};
mutable std::shared_mutex m_mutex;
std::unordered_map<std::type_index, Entry> m_services;
std::vector<std::type_index> m_order;
};
} // namespace Void::Service
+27
View File
@@ -0,0 +1,27 @@
#pragma once
#include <string_view>
namespace Void::Service
{
/// Base for services resolved through a ServiceRegistry by interface
/// type. Consumers depend only on an interface (which may but need not
/// derive IService); implementing IService additionally opts the
/// service into registry-driven lifecycle (start_all/stop_all).
class IService
{
public:
virtual ~IService() = default;
[[nodiscard]] virtual std::string_view service_name() const = 0;
/// Called by ServiceRegistry::start_all(), in registration
/// order.
virtual void on_start() {}
/// Called by ServiceRegistry::stop_all(), in reverse order.
virtual void on_stop() {}
};
} // namespace Void::Service