Files
Library/include/Void/Fsm/Machine.hpp
T

2517 lines
74 KiB
C++

#pragma once
#include <Void/Async/Executor.hpp>
#include <Void/Async/Operation.hpp>
#include <Void/Async/Task.hpp>
#include <Void/Data/Json.hpp>
#include <Void/Fsm/Detail/Awaiter.hpp>
#include <Void/Fsm/Detail/Engine.hpp>
#include <Void/Fsm/Detail/Introspect.hpp>
#include <Void/Fsm/Detail/Result.hpp>
#include <Void/Fsm/Detail/Roles.hpp>
#include <Void/Fsm/Detail/StateList.hpp>
#include <Void/Fsm/Detail/TypeName.hpp>
#include <Void/Fsm/StateKey.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Log/Log.hpp>
#include <Void/Service/Registry.hpp>
#include <Void/Time/Clock.hpp>
#include <algorithm>
#include <any>
#include <array>
#include <atomic>
#include <chrono>
#include <coroutine>
#include <cstdint>
#include <deque>
#include <exception>
#include <expected>
#include <functional>
#include <iterator>
#include <memory>
#include <mutex>
#include <optional>
#include <stdexcept>
#include <stop_token>
#include <string>
#include <string_view>
#include <tuple>
#include <type_traits>
#include <typeindex>
#include <typeinfo>
#include <unordered_map>
#include <utility>
#include <variant>
#include <vector>
#if __has_include(<meta>)
#include <meta>
#define VOID_HAS_FSM_REFLECTION 1
#endif
namespace Void::Fsm
{
namespace Detail
{
struct CancelledException final : std::exception {
const char* what() const noexcept override
{
return "fsm operation cancelled";
}
};
struct YieldAwaiter {
Async::Executor* exec{nullptr};
[[nodiscard]] bool await_ready() const noexcept
{
return exec == nullptr;
}
void await_suspend(std::coroutine_handle<> h) const
{
exec->post(h);
}
void await_resume() const noexcept {}
};
struct LatchResumeAwaiter {
bool ready{false};
std::function<void(std::coroutine_handle<>)> arm{};
[[nodiscard]] bool await_ready() const noexcept { return ready; }
void await_suspend(std::coroutine_handle<> h) const
{
arm(h);
}
void await_resume() const noexcept {}
};
[[nodiscard]] inline std::size_t
estimate_checkpoint_bytes(const Checkpoint& cp)
{
return cp.machine_type.size() + cp.state_id.size() +
cp.resume_label.size() +
Void::Json::serialize(cp.state).size() + 64;
}
} // namespace Detail
/// Options for a Machine (namespace scope to dodge the GCC
/// nested-default-arg trap).
struct MachineOptions {
bool own_worker = true;
};
/// How a run_region<Sub>() re-enters: from Sub's initial state, or resume
/// at the sub-state it last reached (shallow history).
enum class Resume { Initial, History };
/// A transition record handed to observers and stored in bounded history.
struct Transition {
std::string from;
std::string to;
std::uint64_t step{0};
};
// ── Machine<Derived> ──────────────────────────────────────────────────
template <typename Derived> class Machine
{
public:
using Options = MachineOptions;
template <typename D = Derived>
using Success = Detail::SuccessOf<D>;
template <typename D = Derived>
using Failure = Detail::FailureOf<D>;
template <typename D = Derived>
using Outcome = Detail::OutcomeOf<D>;
using MigrationFn = std::function<Void::Result::Result<void>(
std::uint32_t from_schema, std::uint32_t to_schema,
Json::Value& data, std::string& state_id)>;
// ── State base ────────────────────────────────────────────────
class State : public Detail::StateBase
{
public:
[[nodiscard]] Derived& self() const noexcept
{
return *static_cast<Derived*>(m_machine);
}
[[nodiscard]] Machine& machine() const noexcept
{
return *m_machine;
}
protected:
template <typename S> [[nodiscard]] StateKey next() const
{
if constexpr (requires { typename Derived::States; }) {
static_assert(Detail::states_contains<
typename Derived::States, S>(),
"next<S>: S is not in this machine's "
"States { … } list");
}
return StateKey::transition(typeid(S));
}
template <typename S>
[[nodiscard]] StateKey next_dynamic() const
{
return StateKey::transition(typeid(S));
}
template <typename S>
[[nodiscard]] StateKey goto_state() const
{
return StateKey::transition(typeid(S));
}
template <typename S>
[[nodiscard]] StateKey next_or(StateKey step) const
{
if (step.kind() == StateKey::Kind::Fail) {
return next<S>();
}
return step;
}
template <typename Rep, typename Period>
[[nodiscard]] auto
delay(std::chrono::duration<Rep, Period> d) const
{
return m_machine->delay(d);
}
template <typename Rep, typename Period>
[[nodiscard]] auto delay_cancellable(
std::chrono::duration<Rep, Period> d,
Async::OperationOptions opts = {}) const
{
return m_machine->delay_cancellable(d, std::move(opts));
}
template <typename Rep, typename Period, typename Fn>
[[nodiscard]] Coro::Task<bool>
with_retry(int times,
std::chrono::duration<Rep, Period> backoff,
Fn attempt) const
{
for (int i = 0; i < times; ++i) {
if (co_await attempt()) {
co_return true;
}
if (i + 1 < times) {
co_await m_machine->delay(backoff);
}
}
co_return false;
}
[[nodiscard]] StateKey succeed() const
requires std::is_void_v<Detail::SuccessOf<Derived>>
{
return StateKey::success(std::any{});
}
template <typename V>
[[nodiscard]] StateKey succeed(V&& value) const
requires(!std::is_void_v<Detail::SuccessOf<Derived>>)
{
return StateKey::success(
std::any{Detail::SuccessOf<Derived>(
std::forward<V>(value))});
}
[[nodiscard]] StateKey fail() const
requires std::is_void_v<Detail::FailureOf<Derived>>
{
return StateKey::failure(std::any{});
}
template <typename V>
[[nodiscard]] StateKey fail(V&& value) const
requires(!std::is_void_v<Detail::FailureOf<Derived>>)
{
return StateKey::failure(
std::any{Detail::FailureOf<Derived>{
std::forward<V>(value)}});
}
template <typename I> [[nodiscard]] I& service() const
{
return m_machine->template service<I>();
}
/// Resolve a service handle that keeps the provider alive
/// across coroutine suspension / hot reload.
template <typename I>
[[nodiscard]] Void::Result::Result<Service::ServiceHandle<I>>
acquire_service() const
{
return m_machine->template acquire_service<I>();
}
[[nodiscard]] std::stop_token state_stop_token() const noexcept
{
return m_machine->state_stop_token();
}
template <typename E> [[nodiscard]] auto await_event() const
{
return m_machine->template await_event<E>();
}
template <typename E, typename Rep, typename Period>
[[nodiscard]] auto await_event_for(
std::chrono::duration<Rep, Period> d) const
{
return m_machine->template await_event_for<E>(d);
}
template <typename E>
[[nodiscard]] auto await_event_cancellable(
Async::OperationOptions opts = {}) const
{
return m_machine->template await_event_cancellable<E>(
std::move(opts));
}
[[nodiscard]] Coro::Task<void>
safe_point(std::string_view resume_label = {}) const
{
return m_machine->safe_point(resume_label);
}
[[nodiscard]] std::string_view
restored_resume_label() const noexcept
{
return m_machine->restored_resume_label();
}
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 Sub>
[[nodiscard]] auto
run_region(Resume resume = Resume::Initial) const
{
return m_machine->template run_region<Sub>(resume);
}
template <typename... Subs>
[[nodiscard]] auto run_parallel() const
{
return m_machine->template run_parallel<Subs...>();
}
template <typename... Subs>
[[nodiscard]] auto run_parallel_any() const
{
return m_machine->template run_parallel_any<Subs...>();
}
template <typename... Subs>
[[nodiscard]] auto run_parallel_structured() const
{
return m_machine
->template run_parallel_structured<Subs...>();
}
template <typename... Subs>
[[nodiscard]] auto run_parallel_any_structured() const
{
return m_machine
->template run_parallel_any_structured<Subs...>();
}
template <typename... Es>
[[nodiscard]] auto await_any() const
{
return m_machine->template await_any<Es...>();
}
template <typename Sub, typename Next, typename... Args>
[[nodiscard]] StateKey startMachine(Args&&... args) const
{
return m_machine->template start_machine<Sub, Next>(
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)
{
if constexpr (requires { typename Derived::States; }) {
Detail::register_states_from<typename Derived::States>(
*this);
using Init = Detail::InitialStateOf<Derived>;
if constexpr (!std::is_void_v<Init>) {
m_initial = &typeid(Init);
}
}
}
virtual ~Machine() { stop(); }
Machine(const Machine&) = delete;
Machine& operator=(const Machine&) = delete;
// ── registration & durable identities ─────────────────────────
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);
std::string durable = default_state_id<S>(m_names.back());
m_type_to_id.emplace(key, durable);
if (!m_id_to_type.contains(durable)) {
m_id_to_type.emplace(std::move(durable), &ti);
}
m_factories.emplace(
key, [this]() -> std::unique_ptr<Detail::StateBase> {
auto s = std::make_unique<S>();
s->m_machine = this;
return s;
});
m_drivers.emplace(key, Detail::make_driver<S>());
}
template <typename S> void initial()
{
add<S>();
m_initial = &typeid(S);
}
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)});
}
template <typename S> void set_initial()
{
if (m_status.load(std::memory_order_acquire) != Status::Idle) {
return;
}
add<S>();
m_initial = &typeid(S);
}
template <typename S> void remove()
{
if (m_status.load(std::memory_order_acquire) != Status::Idle) {
return;
}
const std::type_index key{typeid(S)};
const auto idxIt = m_index.find(key);
if (idxIt == m_index.end()) {
return;
}
const int idx = idxIt->second;
m_name_to_type.erase(m_names[static_cast<std::size_t>(idx)]);
if (const auto idIt = m_type_to_id.find(key);
idIt != m_type_to_id.end()) {
m_id_to_type.erase(idIt->second);
m_type_to_id.erase(idIt);
}
m_names.erase(m_names.begin() + idx);
m_factories.erase(key);
m_drivers.erase(key);
m_index.erase(idxIt);
for (auto& [k, v] : m_index) {
if (v > idx) {
--v;
}
}
if (m_initial == &typeid(S)) {
m_initial = m_names.empty()
? nullptr
: m_name_to_type.at(m_names.front());
}
}
template <typename S, typename T> void replace()
{
if (m_status.load(std::memory_order_acquire) != Status::Idle) {
return;
}
const bool was_initial = (m_initial == &typeid(S));
remove<S>();
add<T>();
if (was_initial) {
m_initial = &typeid(T);
}
}
/// Assign an explicit durable state identifier (used in checkpoints)
/// while Idle. Rejects empty or colliding IDs.
template <typename S>
[[nodiscard]] Void::Result::Result<void>
register_state_id(std::string durable_id)
{
if (m_status.load(std::memory_order_acquire) != Status::Idle) {
return Void::Result::fail(make_fsm_error(
FsmErrorCode::invalid_state,
"register_state_id requires Idle machine"));
}
if (durable_id.empty()) {
return Void::Result::fail(make_fsm_error(
FsmErrorCode::invalid_argument,
"register_state_id: empty id"));
}
const std::type_index key{typeid(S)};
if (!m_factories.contains(key)) {
return Void::Result::fail(make_fsm_error(
FsmErrorCode::not_found,
"register_state_id: state not registered"));
}
if (const auto existing = m_id_to_type.find(durable_id);
existing != m_id_to_type.end() &&
existing->second != &typeid(S)) {
return Void::Result::fail(make_fsm_error(
FsmErrorCode::invalid_argument,
"register_state_id: duplicate durable id '" +
durable_id + "'"));
}
if (const auto prev = m_type_to_id.find(key);
prev != m_type_to_id.end()) {
m_id_to_type.erase(prev->second);
}
m_id_to_type.insert_or_assign(durable_id, &typeid(S));
m_type_to_id.insert_or_assign(key, std::move(durable_id));
return {};
}
void set_machine_identity(std::string machine_type,
std::uint32_t application_schema = 1)
{
if (m_status.load(std::memory_order_acquire) != Status::Idle) {
return;
}
m_machine_type = std::move(machine_type);
m_application_schema = application_schema;
}
void set_limits(FsmLimits limits)
{
if (m_status.load(std::memory_order_acquire) != Status::Idle) {
return;
}
m_limits = limits;
m_has_explicit_limits = true;
}
// ── 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>();
}
template <typename I>
[[nodiscard]] Void::Result::Result<Service::ServiceHandle<I>>
acquire_service() const
{
if (m_services == nullptr) {
return Void::Result::fail(make_fsm_error(
FsmErrorCode::service_unavailable,
"Machine::acquire_service: no ServiceRegistry bound"));
}
auto r = m_services->template acquire<I>();
if (!r) {
return Void::Result::fail(make_fsm_error(
FsmErrorCode::service_unavailable,
r.error().message()));
}
return r;
}
// ── observability ─────────────────────────────────────────────
void observe(std::function<void(const Transition&)> observer)
{
std::lock_guard lk{m_obs_mu};
m_observer = std::move(observer);
}
struct Interceptor {
std::function<void(const Transition&)> before;
std::function<void(std::string_view)> after;
};
void add_interceptor(Interceptor interceptor)
{
std::lock_guard lk{m_obs_mu};
m_interceptors.push_back(std::move(interceptor));
}
[[nodiscard]] std::vector<Transition> transition_history() const
{
std::lock_guard lk{m_obs_mu};
return {m_transition_history.begin(),
m_transition_history.end()};
}
[[nodiscard]] std::vector<std::string> observer_errors() const
{
std::lock_guard lk{m_obs_mu};
return m_observer_errors;
}
// ── lifecycle ─────────────────────────────────────────────────
void start()
{
if (m_status.load(std::memory_order_acquire) != Status::Idle) {
return;
}
if (!m_ctx) {
FsmLimits start_limits = m_limits;
if (!m_has_explicit_limits) {
start_limits.max_mailbox_events = 0;
start_limits.max_mailbox_bytes = 0;
start_limits.max_deferred_events = 0;
}
m_ctx = std::make_shared<Detail::ExecutionContext>(
&Time::SystemMonotonicClock::instance(), start_limits,
nullptr);
m_owns_ctx = true;
}
m_termination_reason.store(TerminationReason::none,
std::memory_order_release);
m_root_stop.emplace();
m_root_timeout.store(false, std::memory_order_release);
m_status.store(Status::Running, std::memory_order_release);
m_driver.emplace(driver());
m_ctx->executor().post(m_driver->handle());
if (m_options.own_worker && m_owns_ctx) {
m_ctx->start_worker();
}
}
/// Explicit structured async execution on borrowed executor & clock.
template <typename D = Derived>
[[nodiscard]] Coro::Task<Void::Result::Result<Outcome<D>>>
run(ExecutionBinding binding,
Async::OperationOptions opts = {})
{
if (m_status.load(std::memory_order_acquire) != Status::Idle) {
co_return Void::Result::fail(make_fsm_error(
FsmErrorCode::invalid_state,
"Machine::run: machine must be Idle"));
}
if (binding.limits.max_events_per_turn == 0 ||
binding.limits.max_mailbox_events == 0 ||
binding.limits.max_hierarchy_depth == 0 ||
binding.limits.max_child_regions == 0) {
co_return Void::Result::fail(make_fsm_error(
FsmErrorCode::invalid_argument,
"Machine::run: limits must be non-zero"));
}
const auto* clk = binding.clock != nullptr
? binding.clock
: &Time::SystemMonotonicClock::instance();
if (opts.stop.stop_requested()) {
m_termination_reason.store(TerminationReason::cancelled,
std::memory_order_release);
finish_with_fault("cancelled before start", false);
co_return Void::Result::fail(make_fsm_error(
FsmErrorCode::cancelled,
"Machine::run: cancelled before start"));
}
if (opts.deadline.has_value() && clk->now() >= *opts.deadline) {
m_termination_reason.store(TerminationReason::timed_out,
std::memory_order_release);
finish_with_fault("deadline expired before start", false);
co_return Void::Result::fail(make_fsm_error(
FsmErrorCode::timeout,
"Machine::run: deadline expired before start"));
}
m_limits = binding.limits;
m_ctx = std::make_shared<Detail::ExecutionContext>(
clk, binding.limits, binding.executor);
m_owns_ctx = true;
m_termination_reason.store(TerminationReason::none,
std::memory_order_release);
m_root_timeout.store(false, std::memory_order_release);
m_root_stop.emplace();
std::optional<std::stop_callback<std::function<void()>>>
ext_stop_cb;
if (opts.stop.stop_possible()) {
ext_stop_cb.emplace(opts.stop, [this] {
if (m_root_stop) {
m_root_stop->request_stop();
}
});
}
Detail::ExecutionContext::TimerId deadline_timer = 0;
if (opts.deadline.has_value()) {
auto t = m_ctx->try_add_timer(*opts.deadline, [this] {
m_root_timeout.store(true, std::memory_order_release);
if (m_root_stop) {
m_root_stop->request_stop();
}
});
if (t) {
deadline_timer = *t;
}
}
m_status.store(Status::Running, std::memory_order_release);
co_await drive();
if (deadline_timer != 0 && m_ctx) {
m_ctx->cancel_timer(deadline_timer);
}
ext_stop_cb.reset();
if (m_owns_ctx && m_ctx) {
m_ctx->finish();
}
const auto st = m_status.load(std::memory_order_acquire);
const auto reason =
m_termination_reason.load(std::memory_order_acquire);
if (reason == TerminationReason::timed_out ||
m_root_timeout.load(std::memory_order_acquire)) {
co_return Void::Result::fail(make_fsm_error(
FsmErrorCode::timeout,
m_system_error ? m_system_error->message
: std::string{"fsm run timed out"}));
}
if (reason == TerminationReason::cancelled) {
co_return Void::Result::fail(make_fsm_error(
FsmErrorCode::cancelled,
m_system_error ? m_system_error->message
: std::string{"fsm run cancelled"}));
}
if (st == Status::Faulted) {
co_return Void::Result::fail(make_fsm_error(
FsmErrorCode::fault,
m_system_error ? m_system_error->message
: std::string{"fsm system fault"}));
}
co_return take_outcome<D>();
}
template <typename D = Derived> Outcome<D> 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;
}
}
}
}
return take_outcome<D>();
}
template <typename D = Derived> Outcome<D> run_blocking()
{
start();
return wait<D>();
}
[[nodiscard]] std::optional<FsmError> system_error() const
{
return m_system_error;
}
std::size_t pump() { return m_ctx ? m_ctx->pump() : 0; }
[[nodiscard]] bool finished() const noexcept
{
return terminal(m_status.load(std::memory_order_acquire));
}
[[nodiscard]] Status status() const noexcept
{
return m_status.load(std::memory_order_acquire);
}
[[nodiscard]] TerminationReason
termination_reason() const noexcept
{
return m_termination_reason.load(std::memory_order_acquire);
}
[[nodiscard]] Detail::ExecutionContext*
execution_context() noexcept
{
return m_ctx.get();
}
[[nodiscard]] Detail::ExecutionContext::ScopeId
active_scope() const noexcept
{
return m_active_scope;
}
void stop()
{
if (m_root_stop) {
m_root_stop->request_stop();
}
if (m_owns_ctx && m_ctx) {
m_ctx->stop();
}
m_driver.reset();
}
void reset()
{
if (m_status.load(std::memory_order_acquire) == Status::Running) {
return;
}
if (m_owns_ctx && m_ctx) {
m_ctx->stop();
}
m_driver.reset();
m_ctx.reset();
m_owns_ctx = false;
m_current.store(-1, std::memory_order_release);
m_result_value.reset();
m_system_error.reset();
m_pending_result.reset();
m_pending_dispatch = nullptr;
m_jump.store(nullptr, std::memory_order_release);
m_step = 0;
m_restored_resume_label.clear();
m_root_stop.reset();
m_root_timeout.store(false, std::memory_order_release);
m_termination_reason.store(TerminationReason::none,
std::memory_order_release);
{
std::lock_guard lk{m_obs_mu};
m_transition_history.clear();
m_observer_errors.clear();
}
m_pending_checkpoints.clear();
m_status.store(Status::Idle, std::memory_order_release);
}
void restart()
{
reset();
start();
}
template <typename S> void restart_at()
{
reset();
m_initial = &typeid(S);
start();
}
void pause()
{
if (m_ctx) {
m_ctx->set_paused(true);
}
}
void resume()
{
if (m_ctx) {
m_ctx->set_paused(false);
}
}
// ── events ────────────────────────────────────────────────────
template <typename E>
[[nodiscard]] Void::Result::Result<void>
try_post(E event, Async::OperationOptions opts = {})
{
if (opts.stop.stop_requested()) {
return Void::Result::fail(make_fsm_error(
FsmErrorCode::cancelled,
"Machine::try_post: cancelled"));
}
if (!m_ctx) {
return Void::Result::fail(make_fsm_error(
FsmErrorCode::invalid_state,
"Machine::try_post: machine not started"));
}
if (opts.deadline.has_value() &&
m_ctx->clock().now() >= *opts.deadline) {
return Void::Result::fail(make_fsm_error(
FsmErrorCode::timeout,
"Machine::try_post: deadline expired"));
}
const std::size_t bytes = event_payload_bytes(event);
return m_ctx->try_post(Detail::EventEnvelope{
&typeid(E), std::any{std::move(event)}, bytes});
}
template <typename E> void post(E event)
{
if (!m_ctx) {
return;
}
const std::size_t bytes = event_payload_bytes(event);
m_ctx->post(Detail::EventEnvelope{
&typeid(E), std::any{std::move(event)}, bytes});
}
void repost(Detail::EventEnvelope env)
{
if (m_ctx) {
m_ctx->post(std::move(env));
}
}
template <typename... Es> void send(Es&&... events)
{
(post(std::forward<Es>(events)), ...);
}
template <typename S> void jump()
{
m_jump.store(&typeid(S), std::memory_order_release);
if (m_ctx) {
(void)m_ctx->try_post_control([] {});
m_ctx->nudge();
}
}
[[nodiscard]] std::stop_token state_stop_token() const noexcept
{
if (m_active_state_stop != nullptr) {
return m_active_state_stop->get_token();
}
if (m_root_stop.has_value()) {
return m_root_stop->get_token();
}
return {};
}
template <typename E> [[nodiscard]] auto await_event()
{
const std::stop_token st = state_stop_token();
return Detail::make_event_awaiter(
m_ctx.get(), std::array{&typeid(E)}, std::nullopt,
[](Detail::EventEnvelope&& env, bool, bool cancelled) {
if (cancelled) {
throw Detail::CancelledException{};
}
return std::any_cast<E>(std::move(env.value));
},
m_active_scope, st);
}
template <typename E, typename Rep, typename Period>
[[nodiscard]] auto
await_event_for(std::chrono::duration<Rep, Period> duration)
{
const auto now = m_ctx != nullptr
? m_ctx->clock().now()
: std::chrono::steady_clock::now();
const std::stop_token st = state_stop_token();
return Detail::make_event_awaiter(
m_ctx.get(), std::array{&typeid(E)}, now + duration,
[](Detail::EventEnvelope&& env, bool timed_out,
bool cancelled) -> std::optional<E> {
if (cancelled) {
throw Detail::CancelledException{};
}
if (timed_out) {
return std::nullopt;
}
return std::any_cast<E>(std::move(env.value));
},
m_active_scope, st);
}
template <typename E>
[[nodiscard]] auto
await_event_cancellable(Async::OperationOptions opts = {})
{
return Detail::make_event_awaiter(
m_ctx.get(), std::array{&typeid(E)}, opts.deadline,
[](Detail::EventEnvelope&& env, bool timed_out,
bool cancelled) -> Void::Result::Result<E> {
if (cancelled) {
return Void::Result::fail(make_fsm_error(
FsmErrorCode::cancelled,
"await_event_cancellable: cancelled"));
}
if (timed_out) {
return Void::Result::fail(make_fsm_error(
FsmErrorCode::timeout,
"await_event_cancellable: deadline expired"));
}
return std::any_cast<E>(std::move(env.value));
},
m_active_scope, state_stop_token(), opts.stop);
}
[[nodiscard]] auto await_any_event(
std::vector<const std::type_info*> types,
std::optional<Time::MonotonicClock::time_point> deadline)
{
return Detail::make_event_awaiter(
m_ctx.get(), std::move(types), deadline,
[](Detail::EventEnvelope&& env, bool timed_out,
bool cancelled) -> std::optional<Detail::EventEnvelope> {
if (cancelled) {
throw Detail::CancelledException{};
}
if (timed_out) {
return std::nullopt;
}
return std::move(env);
},
m_active_scope, state_stop_token());
}
template <typename... Es> [[nodiscard]] auto await_any()
{
return Detail::make_event_awaiter(
m_ctx.get(), std::array{(&typeid(Es))...}, std::nullopt,
[](Detail::EventEnvelope&& env, bool,
bool cancelled) -> std::variant<Es...> {
if (cancelled) {
throw Detail::CancelledException{};
}
std::optional<std::variant<Es...>> out;
((env.type != nullptr && *env.type == typeid(Es)
? (out.emplace(
std::in_place_type<Es>,
std::any_cast<Es>(std::move(env.value))),
true)
: false) ||
...);
return std::move(*out);
},
m_active_scope, state_stop_token());
}
template <typename Rep, typename Period>
[[nodiscard]] auto delay(std::chrono::duration<Rep, Period> d)
{
const auto now = m_ctx != nullptr
? m_ctx->clock().now()
: std::chrono::steady_clock::now();
return Detail::make_event_awaiter(
m_ctx.get(), std::array<const std::type_info*, 0>{},
now + d,
[](Detail::EventEnvelope&&, bool, bool cancelled) {
if (cancelled) {
throw Detail::CancelledException{};
}
},
m_active_scope, state_stop_token());
}
template <typename Rep, typename Period>
[[nodiscard]] auto delay_cancellable(
std::chrono::duration<Rep, Period> d,
Async::OperationOptions opts = {})
{
const auto now = m_ctx != nullptr
? m_ctx->clock().now()
: std::chrono::steady_clock::now();
auto deadline = now + d;
if (opts.deadline.has_value() && *opts.deadline < deadline) {
deadline = *opts.deadline;
}
return Detail::make_event_awaiter(
m_ctx.get(), std::array<const std::type_info*, 0>{},
deadline,
[](Detail::EventEnvelope&&, bool,
bool cancelled) -> Void::Result::Result<void> {
if (cancelled) {
return Void::Result::fail(make_fsm_error(
FsmErrorCode::cancelled,
"delay_cancellable: cancelled"));
}
return {};
},
m_active_scope, state_stop_token(), opts.stop);
}
/// Application-declared safe point inside a running state: yields
/// one turn to let pending checkpoint requests serialize cleanly.
[[nodiscard]] Coro::Task<void>
safe_point(std::string_view resume_label = {})
{
if (m_ctx == nullptr) {
co_return;
}
co_await Detail::YieldAwaiter{&m_ctx->active_executor()};
m_ctx->drain_control_queue();
fulfill_pending_checkpoints(current_durable_id(),
std::string{resume_label});
}
[[nodiscard]] const std::string&
restored_resume_label() const noexcept
{
return m_restored_resume_label;
}
// ── nesting ───────────────────────────────────────────────────
template <typename Sub, typename... Args>
[[nodiscard]] Coro::Task<Detail::OutcomeOf<Sub>>
run_child(Args&&... args)
{
Sub child{std::forward<Args>(args)...};
child.attach(m_ctx, m_services, m_depth + 1, m_active_state_stop);
co_await child.drive();
co_return child.template take_outcome<Sub>();
}
template <typename Sub>
[[nodiscard]] Coro::Task<Detail::OutcomeOf<Sub>>
run_region(Resume resume = Resume::Initial)
{
Sub child;
if (resume == Resume::History) {
const auto it =
m_region_history.find(std::type_index{typeid(Sub)});
if (it != m_region_history.end()) {
(void)child.restore(it->second);
}
}
child.attach(m_ctx, m_services, m_depth + 1, m_active_state_stop);
m_region_probe = [&child] { return child.state_path(); };
co_await child.drive();
m_region_probe = nullptr;
m_region_history[std::type_index{typeid(Sub)}] =
child.serialize();
co_return child.template take_outcome<Sub>();
}
template <typename... Subs>
[[nodiscard]] Coro::Task<std::tuple<Detail::OutcomeOf<Subs>...>>
run_parallel()
{
auto children = std::make_unique<std::tuple<Subs...>>();
std::apply(
[&](auto&... c) {
(c.attach(m_ctx, m_services, m_depth + 1,
m_active_state_stop),
...);
},
*children);
struct Latch {
int remaining;
std::coroutine_handle<> waiter{};
Async::Executor* exec;
void arrive(std::size_t, Status,
std::optional<FsmError>)
{
if (--remaining == 0 && waiter) {
exec->post_completion(waiter);
}
}
};
auto latch = std::make_shared<Latch>(
static_cast<int>(sizeof...(Subs)),
std::coroutine_handle<>{}, &m_ctx->active_executor());
std::size_t idx = 0;
std::apply(
[&](auto&... c) {
(Async::spawn(
m_ctx->active_executor(),
drive_child_task(&c, latch, idx++)),
...);
},
*children);
co_await Detail::LatchResumeAwaiter{
latch->remaining == 0,
[latch](std::coroutine_handle<> h) { latch->waiter = h; }};
co_return std::apply(
[](auto&... c) {
return std::tuple<Detail::OutcomeOf<Subs>...>{
c.template take_outcome<Subs>()...};
},
*children);
}
template <typename... Subs>
[[nodiscard]] Coro::Task<std::variant<Detail::OutcomeOf<Subs>...>>
run_parallel_any()
{
auto children = std::make_shared<std::tuple<Subs...>>();
std::apply(
[&](auto&... c) {
(c.attach(m_ctx, m_services, m_depth + 1,
m_active_state_stop),
...);
},
*children);
struct Latch {
int first{-1};
std::coroutine_handle<> waiter{};
Async::Executor* exec;
std::shared_ptr<std::tuple<Subs...>> keep;
void arrive(std::size_t idx, Status,
std::optional<FsmError>)
{
if (first < 0) {
first = static_cast<int>(idx);
if (waiter) {
exec->post_completion(waiter);
}
}
}
};
auto latch = std::make_shared<Latch>(
-1, std::coroutine_handle<>{}, &m_ctx->active_executor(),
children);
std::size_t idx = 0;
std::apply(
[&](auto&... c) {
(Async::spawn(
m_ctx->active_executor(),
drive_child_task(&c, latch, idx++)),
...);
},
*children);
co_await Detail::LatchResumeAwaiter{
latch->first >= 0,
[latch](std::coroutine_handle<> h) { latch->waiter = h; }};
const auto winner = static_cast<std::size_t>(latch->first);
co_return [&]<std::size_t... I>(std::index_sequence<I...>)
-> std::variant<Detail::OutcomeOf<Subs>...> {
std::variant<Detail::OutcomeOf<Subs>...> v;
((I == winner ? (void)(v.template emplace<I>(
std::get<I>(*children)
.template take_outcome<Subs>()))
: void()),
...);
return v;
}(std::index_sequence_for<Subs...>{});
}
/// Structured parallel-all: enforces hierarchy depth and live child
/// region limits, stops siblings on any child system Fault, and
/// ALWAYS joins every child before returning.
template <typename... Subs>
[[nodiscard]] Coro::Task<Void::Result::Result<
std::tuple<Detail::OutcomeOf<Subs>...>>>
run_parallel_structured()
{
constexpr std::size_t n = sizeof...(Subs);
static_assert(n > 0, "run_parallel_structured needs >= 1 sub");
if (m_ctx == nullptr) {
co_return Void::Result::fail(make_fsm_error(
FsmErrorCode::invalid_state,
"run_parallel_structured: no active ExecutionContext"));
}
if (m_depth + 1 > m_ctx->limits().max_hierarchy_depth) {
co_return Void::Result::fail(make_fsm_error(
FsmErrorCode::limit_exceeded,
"run_parallel_structured: max_hierarchy_depth exceeded"));
}
if (!m_ctx->try_acquire_child_regions(n)) {
co_return Void::Result::fail(make_fsm_error(
FsmErrorCode::limit_exceeded,
"run_parallel_structured: max_child_regions exceeded"));
}
struct RegionGuard {
Detail::ExecutionContext* ctx;
std::size_t count;
~RegionGuard() { ctx->release_child_regions(count); }
} guard{m_ctx.get(), n};
std::stop_source group_stop;
std::optional<std::stop_callback<std::function<void()>>> link;
if (state_stop_token().stop_possible()) {
link.emplace(state_stop_token(),
[&group_stop] { group_stop.request_stop(); });
}
auto children = std::make_shared<std::tuple<Subs...>>();
std::apply(
[&](auto&... c) {
(c.attach(m_ctx, m_services, m_depth + 1, &group_stop),
...);
},
*children);
struct Latch {
std::size_t remaining;
std::coroutine_handle<> waiter{};
Async::Executor* exec;
std::stop_source* stop_src;
std::shared_ptr<void> keep_alive;
std::optional<FsmError> fault{};
void arrive(std::size_t, Status st,
std::optional<FsmError> err)
{
if (st == Status::Faulted && !fault.has_value()) {
fault = err.value_or(
FsmError{"parallel child faulted"});
if (stop_src != nullptr) {
stop_src->request_stop();
}
}
if (--remaining == 0 && waiter) {
exec->post_completion(waiter);
}
}
};
auto latch = std::make_shared<Latch>(
n, std::coroutine_handle<>{}, &m_ctx->active_executor(),
&group_stop, children);
std::size_t idx = 0;
std::apply(
[&](auto&... c) {
(Async::spawn(
m_ctx->active_executor(),
drive_child_task(&c, latch, idx++)),
...);
},
*children);
co_await Detail::LatchResumeAwaiter{
latch->remaining == 0,
[latch](std::coroutine_handle<> h) { latch->waiter = h; }};
link.reset();
if (latch->fault.has_value()) {
co_return Void::Result::fail(make_fsm_error(
FsmErrorCode::fault, latch->fault->message));
}
co_return std::apply(
[](auto&... c) {
return std::tuple<Detail::OutcomeOf<Subs>...>{
c.template take_outcome<Subs>()...};
},
*children);
}
/// Structured race-any: picks earliest finisher with deterministic
/// child-declaration-order tie-break within the same dispatch turn,
/// requests stop on all losers, and ALWAYS joins EVERY loser before
/// returning. Application Failure can win; system Fault is returned
/// as supervisory error.
template <typename... Subs>
[[nodiscard]] Coro::Task<Void::Result::Result<
std::variant<Detail::OutcomeOf<Subs>...>>>
run_parallel_any_structured()
{
constexpr std::size_t n = sizeof...(Subs);
static_assert(n > 0,
"run_parallel_any_structured needs >= 1 sub");
if (m_ctx == nullptr) {
co_return Void::Result::fail(make_fsm_error(
FsmErrorCode::invalid_state,
"run_parallel_any_structured: no active ExecutionContext"));
}
if (m_depth + 1 > m_ctx->limits().max_hierarchy_depth) {
co_return Void::Result::fail(make_fsm_error(
FsmErrorCode::limit_exceeded,
"run_parallel_any_structured: max_hierarchy_depth exceeded"));
}
if (!m_ctx->try_acquire_child_regions(n)) {
co_return Void::Result::fail(make_fsm_error(
FsmErrorCode::limit_exceeded,
"run_parallel_any_structured: max_child_regions exceeded"));
}
struct RegionGuard {
Detail::ExecutionContext* ctx;
std::size_t count;
~RegionGuard() { ctx->release_child_regions(count); }
} guard{m_ctx.get(), n};
std::stop_source race_stop;
std::optional<std::stop_callback<std::function<void()>>> link;
if (state_stop_token().stop_possible()) {
link.emplace(state_stop_token(),
[&race_stop] { race_stop.request_stop(); });
}
auto children = std::make_shared<std::tuple<Subs...>>();
std::apply(
[&](auto&... c) {
(c.attach(m_ctx, m_services, m_depth + 1, &race_stop),
...);
},
*children);
struct Latch {
std::size_t remaining;
bool woke_first{false};
std::coroutine_handle<> waiter{};
Detail::ExecutionContext* ctx;
Async::Executor* exec;
std::shared_ptr<void> keep_alive;
std::array<bool, n> completed{};
std::array<std::uint64_t, n> turns{};
std::array<Status, n> statuses{};
std::array<std::optional<FsmError>, n> faults{};
void arrive(std::size_t idx, Status st,
std::optional<FsmError> err)
{
completed[idx] = true;
turns[idx] = ctx->dispatch_turn();
statuses[idx] = st;
faults[idx] = std::move(err);
--remaining;
if (!woke_first) {
woke_first = true;
if (waiter) {
auto w = std::exchange(waiter, {});
exec->post_completion(w);
}
} else if (remaining == 0 && waiter) {
auto w = std::exchange(waiter, {});
exec->post_completion(w);
}
}
[[nodiscard]] std::size_t pick_winner() const noexcept
{
std::uint64_t min_turn =
std::numeric_limits<std::uint64_t>::max();
for (std::size_t i = 0; i < n; ++i) {
if (completed[i] && turns[i] < min_turn) {
min_turn = turns[i];
}
}
for (std::size_t i = 0; i < n; ++i) {
if (completed[i] && turns[i] == min_turn) {
return i;
}
}
return 0;
}
};
auto latch = std::make_shared<Latch>(
n, false, std::coroutine_handle<>{}, m_ctx.get(),
&m_ctx->active_executor(), children);
std::size_t idx = 0;
std::apply(
[&](auto&... c) {
(Async::spawn(
m_ctx->active_executor(),
drive_child_task(&c, latch, idx++)),
...);
},
*children);
// Wait until at least one child has completed.
co_await Detail::LatchResumeAwaiter{
latch->woke_first,
[latch](std::coroutine_handle<> h) { latch->waiter = h; }};
// Select deterministic winner (earliest turn, declaration
// order tie-break), then cancel and join EVERY loser.
const std::size_t winner = latch->pick_winner();
race_stop.request_stop();
co_await Detail::LatchResumeAwaiter{
latch->remaining == 0,
[latch](std::coroutine_handle<> h) { latch->waiter = h; }};
link.reset();
if (latch->statuses[winner] == Status::Faulted) {
co_return Void::Result::fail(make_fsm_error(
FsmErrorCode::fault,
latch->faults[winner]
? latch->faults[winner]->message
: std::string{"winning race child faulted"}));
}
co_return [&]<std::size_t... I>(std::index_sequence<I...>)
-> std::variant<Detail::OutcomeOf<Subs>...> {
std::variant<Detail::OutcomeOf<Subs>...> v;
((I == winner ? (void)(v.template emplace<I>(
std::get<I>(*children)
.template take_outcome<Subs>()))
: void()),
...);
return v;
}(std::index_sequence_for<Subs...>{});
}
template <typename Sub, typename Next, typename... Args>
[[nodiscard]] StateKey start_machine(Args&&... args)
{
if constexpr (requires { typename Derived::States; }) {
static_assert(
Detail::states_contains<typename Derived::States,
Next>(),
"startMachine<Sub, Next>: Next is not in States { … }");
}
using Init = Detail::InitialStateOf<Sub>;
auto launcher =
[this, ... data = std::forward<Args>(
args)]() mutable -> Coro::Task<LaunchResult> {
Sub child;
child.attach(m_ctx, m_services, m_depth + 1,
m_active_state_stop);
if constexpr (sizeof...(Args) > 0) {
child.m_startup_injector =
[... d = std::move(data)](
Detail::StateBase& base) mutable
-> Coro::Task<StateKey> {
return Detail::invoke_startup<Init>(
static_cast<Init&>(base), std::move(d)...);
};
}
co_await child.drive();
LaunchResult lr;
switch (child.m_status.load(std::memory_order_acquire)) {
case Status::Succeeded:
lr.kind = LaunchResult::Kind::Success;
lr.value = std::move(child.m_result_value);
break;
case Status::Failed:
lr.kind = LaunchResult::Kind::Failure;
lr.failure = std::move(child.m_result_value);
break;
default:
lr.kind = LaunchResult::Kind::Fault;
lr.fault = child.m_system_error.value_or(
FsmError{"sub-machine fault"});
break;
}
co_return lr;
};
StateKey::Dispatch dispatch =
[](Detail::StateBase& base,
LaunchResult lr) -> Coro::Task<StateKey> {
return Detail::dispatch_result<Next, Sub>(
static_cast<Next&>(base), std::move(lr));
};
return StateKey::launch(typeid(Next), std::move(launcher),
std::move(dispatch));
}
// ── 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)];
}
[[nodiscard]] std::vector<std::string> state_path() const
{
std::vector<std::string> path;
if (auto s = current_state(); !s.empty()) {
path.push_back(std::move(s));
}
if (m_region_probe) {
auto sub = m_region_probe();
path.insert(path.end(),
std::make_move_iterator(sub.begin()),
std::make_move_iterator(sub.end()));
}
return path;
}
[[nodiscard]] const std::vector<std::string>&
state_names() const noexcept
{
return m_names;
}
[[nodiscard]] std::vector<StateInfo> describe()
{
std::vector<StateInfo> out;
const std::string initial_name = m_initial != nullptr
? state_name_for(m_initial)
: std::string{};
for (const auto& name : m_names) {
StateInfo si;
si.name = name;
si.initial = (name == initial_name);
out.push_back(std::move(si));
}
return out;
}
[[nodiscard]] std::string to_mermaid()
{
const auto states = describe();
return Detail::to_mermaid(states);
}
// ── legacy persistence & boundary checkpoints ─────────────────
[[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(std::memory_order_acquire) != 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 {};
}
/// Request a bounded checkpoint at the next clean state boundary
/// or application safe_point(). Never captures mid-turn live frames.
[[nodiscard]] Coro::Task<Void::Result::Result<Checkpoint>>
request_checkpoint(Async::OperationOptions opts = {})
{
if (opts.stop.stop_requested()) {
co_return Void::Result::fail(make_fsm_error(
FsmErrorCode::cancelled,
"request_checkpoint: cancelled before scheduling"));
}
const auto st = m_status.load(std::memory_order_acquire);
if (st == Status::Idle) {
co_return build_checkpoint(
m_initial != nullptr ? durable_id_for(m_initial)
: std::string{},
m_restored_resume_label);
}
if (terminal(st) || m_ctx == nullptr) {
co_return Void::Result::fail(make_fsm_error(
FsmErrorCode::checkpoint_rejected,
"request_checkpoint: machine is already terminal"));
}
if (opts.deadline.has_value() &&
m_ctx->clock().now() >= *opts.deadline) {
co_return Void::Result::fail(make_fsm_error(
FsmErrorCode::timeout,
"request_checkpoint: deadline already expired"));
}
struct RequestState {
bool settled{false};
Void::Result::Result<Checkpoint> result{
Void::Result::fail(make_fsm_error(
FsmErrorCode::internal, "unsettled"))};
std::coroutine_handle<> waiter{};
Async::Executor* exec{nullptr};
Detail::ExecutionContext::TimerId timer{0};
};
auto req = std::make_shared<RequestState>();
req->exec = &m_ctx->active_executor();
std::optional<std::stop_callback<std::function<void()>>> stop_cb;
if (opts.stop.stop_possible()) {
stop_cb.emplace(opts.stop, [ctx = m_ctx.get(), req] {
(void)ctx->try_post_control([req] {
if (req->settled) return;
req->settled = true;
req->result = Void::Result::fail(make_fsm_error(
FsmErrorCode::cancelled,
"request_checkpoint: cancelled"));
if (req->waiter) {
req->exec->post_completion(req->waiter);
}
});
});
}
auto pending_entry = PendingCheckpoint{
.settle =
[ctx = m_ctx.get(), req](
Void::Result::Result<Checkpoint> r) {
if (req->settled) return false;
req->settled = true;
if (req->timer != 0) {
ctx->cancel_timer(req->timer);
req->timer = 0;
}
req->result = std::move(r);
if (req->waiter) {
req->exec->post_completion(req->waiter);
}
return true;
},
.is_done = [req] { return req->settled; }};
auto post_res = m_ctx->try_post_control(
[this, ctx = m_ctx.get(), req, opts,
entry = std::move(pending_entry)]() mutable {
if (req->settled) {
return;
}
if (terminal(m_status.load(std::memory_order_acquire))) {
req->settled = true;
req->result = Void::Result::fail(make_fsm_error(
FsmErrorCode::checkpoint_rejected,
"request_checkpoint: machine finished before boundary"));
if (req->waiter) {
req->exec->post_completion(req->waiter);
}
return;
}
if (opts.deadline.has_value()) {
auto t = ctx->try_add_timer(
*opts.deadline, [req] {
if (req->settled) return;
req->settled = true;
req->result =
Void::Result::fail(make_fsm_error(
FsmErrorCode::timeout,
"request_checkpoint: boundary not reached before deadline"));
if (req->waiter) {
req->exec->post_completion(req->waiter);
}
});
if (t) {
req->timer = *t;
}
}
m_pending_checkpoints.push_back(std::move(entry));
});
if (!post_res) {
stop_cb.reset();
co_return Void::Result::fail(post_res.error());
}
co_await Detail::LatchResumeAwaiter{
req->settled,
[req](std::coroutine_handle<> h) { req->waiter = h; }};
stop_cb.reset();
co_return std::move(req->result);
}
/// Validate-then-commit restore from a boundary Checkpoint while
/// Idle. Any schema, ID, limit, or migration error leaves this
/// machine completely unchanged.
[[nodiscard]] Void::Result::Result<void>
restore_checkpoint(const Checkpoint& cp,
MigrationFn migrator = nullptr)
{
if (m_status.load(std::memory_order_acquire) != Status::Idle) {
return Void::Result::fail(make_fsm_error(
FsmErrorCode::invalid_state,
"restore_checkpoint requires Idle machine"));
}
if (cp.format_version != Checkpoint::kFormatVersion) {
return Void::Result::fail(make_fsm_error(
FsmErrorCode::schema_mismatch,
"restore_checkpoint: unsupported checkpoint format version"));
}
if (!m_machine_type.empty() && !cp.machine_type.empty() &&
cp.machine_type != m_machine_type) {
return Void::Result::fail(make_fsm_error(
FsmErrorCode::schema_mismatch,
"restore_checkpoint: machine_type mismatch"));
}
if (m_limits.max_checkpoint_bytes > 0 &&
Detail::estimate_checkpoint_bytes(cp) >
m_limits.max_checkpoint_bytes) {
return Void::Result::fail(make_fsm_error(
FsmErrorCode::limit_exceeded,
"restore_checkpoint: checkpoint exceeds max_checkpoint_bytes"));
}
Json::Value candidate_data = cp.state;
std::string candidate_state_id = cp.state_id;
if (cp.application_schema != m_application_schema) {
if (!migrator) {
return Void::Result::fail(make_fsm_error(
FsmErrorCode::schema_mismatch,
"restore_checkpoint: schema mismatch and no migrator"));
}
try {
auto mr = migrator(cp.application_schema,
m_application_schema, candidate_data,
candidate_state_id);
if (!mr) {
return Void::Result::fail(make_fsm_error(
FsmErrorCode::migration_failed,
mr.error().message()));
}
} catch (const std::exception& ex) {
return Void::Result::fail(make_fsm_error(
FsmErrorCode::migration_failed,
std::string{"restore_checkpoint migrator threw: "} +
ex.what()));
} catch (...) {
return Void::Result::fail(make_fsm_error(
FsmErrorCode::migration_failed,
"restore_checkpoint migrator threw unknown exception"));
}
}
const auto idIt = m_id_to_type.find(candidate_state_id);
if (idIt == m_id_to_type.end()) {
return Void::Result::fail(make_fsm_error(
FsmErrorCode::not_found,
"restore_checkpoint: unknown durable state_id '" +
candidate_state_id + "'"));
}
try {
auto vr = on_validate_restore(candidate_data);
if (!vr) {
return Void::Result::fail(make_fsm_error(
FsmErrorCode::migration_failed,
vr.error().message()));
}
} catch (const std::exception& ex) {
return Void::Result::fail(make_fsm_error(
FsmErrorCode::migration_failed,
std::string{"restore_checkpoint validator threw: "} +
ex.what()));
} catch (...) {
return Void::Result::fail(make_fsm_error(
FsmErrorCode::migration_failed,
"restore_checkpoint validator threw unknown exception"));
}
Json::Value rollback_snapshot = Json::object();
bool has_rollback = false;
try {
on_serialize(rollback_snapshot);
has_rollback = true;
} catch (...) {
}
try {
on_restore(candidate_data);
} catch (const std::exception& ex) {
if (has_rollback) {
try {
on_restore(rollback_snapshot);
} catch (...) {
}
}
return Void::Result::fail(make_fsm_error(
FsmErrorCode::migration_failed,
std::string{"restore_checkpoint on_restore threw: "} +
ex.what()));
} catch (...) {
if (has_rollback) {
try {
on_restore(rollback_snapshot);
} catch (...) {
}
}
return Void::Result::fail(make_fsm_error(
FsmErrorCode::migration_failed,
"restore_checkpoint on_restore threw unknown exception"));
}
m_initial = idIt->second;
m_restored_resume_label = cp.resume_label;
m_step = cp.transition_sequence;
return {};
}
/// Explicit legacy `{state, data}` reader mapping old state names
/// through an optional migration map into bounded restore_checkpoint.
[[nodiscard]] Void::Result::Result<void>
restore_legacy_checkpoint(
const Json::Value& legacy_json,
const std::unordered_map<std::string, std::string>&
state_id_map = {},
MigrationFn migrator = nullptr)
{
const auto* st = legacy_json.find("state");
if (st == nullptr || !st->is_string()) {
return Void::Result::fail(make_fsm_error(
FsmErrorCode::schema_mismatch,
"restore_legacy_checkpoint: malformed state field"));
}
std::string mapped_id = st->as_string();
if (const auto it = state_id_map.find(mapped_id);
it != state_id_map.end()) {
mapped_id = it->second;
} else if (const auto nIt = m_name_to_type.find(mapped_id);
nIt != m_name_to_type.end()) {
mapped_id = durable_id_for(nIt->second);
}
Checkpoint cp;
cp.format_version = Checkpoint::kFormatVersion;
cp.machine_type = m_machine_type;
cp.application_schema = 1;
if (const auto* sv = legacy_json.find("application_schema");
sv != nullptr && sv->is_int()) {
cp.application_schema =
static_cast<std::uint32_t>(sv->as_int());
}
cp.state_id = std::move(mapped_id);
if (const auto* data = legacy_json.find("data")) {
cp.state = *data;
} else {
cp.state = Json::object();
}
return restore_checkpoint(cp, std::move(migrator));
}
protected:
virtual void on_serialize(Json::Value& /*data*/) const {}
virtual void on_restore(const Json::Value& /*data*/) {}
[[nodiscard]] virtual Void::Result::Result<void>
on_validate_restore(const Json::Value& /*data*/) const
{
return {};
}
virtual void on_machine_enter() {}
virtual void on_machine_exit() {}
virtual void on_transition(std::string_view from,
std::string_view to)
{
Void::Log::debug("Fsm", "{} -> {}",
from.empty() ? "(start)" : from, to);
}
private:
template <typename> friend class Machine;
struct PendingCheckpoint {
std::function<bool(Void::Result::Result<Checkpoint>)>
settle;
std::function<bool()> is_done;
};
template <typename Sub, typename LatchT>
static Coro::Task<void> drive_child_task(
Sub* child, std::shared_ptr<LatchT> latch, std::size_t idx)
{
co_await child->drive();
latch->arrive(idx, child->status(), child->system_error());
}
void attach(std::shared_ptr<Detail::ExecutionContext> ctx,
Service::ServiceRegistry* services,
std::size_t depth = 1,
std::stop_source* parent_stop = nullptr)
{
m_ctx = std::move(ctx);
m_owns_ctx = false;
m_depth = depth;
if (m_ctx != nullptr) {
m_limits = m_ctx->limits();
}
if (services != nullptr) {
m_services = services;
}
m_termination_reason.store(TerminationReason::none,
std::memory_order_release);
m_root_stop.emplace();
m_parent_stop_link.reset();
if (parent_stop != nullptr) {
m_parent_stop_link.emplace(
parent_stop->get_token(), [this] {
if (m_root_stop) {
m_root_stop->request_stop();
}
});
}
m_status.store(Status::Running, std::memory_order_release);
}
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
}
template <typename S>
[[nodiscard]] static std::string
default_state_id(const std::string& fallback_name)
{
#ifdef VOID_HAS_FSM_REFLECTION
constexpr auto id_ann =
Void::Meta::annotation_of<StateId>(^^S);
if constexpr (id_ann.has_value()) {
if (!id_ann->value.view().empty()) {
return std::string{id_ann->value.view()};
}
}
#endif
return fallback_name;
}
[[nodiscard]] std::string
state_name_for(const std::type_info* type) const
{
if (const auto it = m_index.find(std::type_index{*type});
it != m_index.end()) {
return m_names[static_cast<std::size_t>(it->second)];
}
return {};
}
[[nodiscard]] std::string
durable_id_for(const std::type_info* type) const
{
if (type == nullptr) {
return {};
}
if (const auto it = m_type_to_id.find(std::type_index{*type});
it != m_type_to_id.end()) {
return it->second;
}
return state_name_for(type);
}
[[nodiscard]] std::string current_durable_id() const
{
const int idx = m_current.load(std::memory_order_acquire);
if (idx < 0 || idx >= static_cast<int>(m_names.size())) {
return {};
}
if (const auto nIt =
m_name_to_type.find(m_names[static_cast<std::size_t>(idx)]);
nIt != m_name_to_type.end()) {
return durable_id_for(nIt->second);
}
return m_names[static_cast<std::size_t>(idx)];
}
[[nodiscard]] Void::Result::Result<Checkpoint>
build_checkpoint(std::string state_id,
std::string resume_label = {}) const
{
Checkpoint cp;
cp.format_version = Checkpoint::kFormatVersion;
cp.machine_type = m_machine_type;
cp.application_schema = m_application_schema;
cp.transition_sequence = m_step;
cp.state_id = std::move(state_id);
cp.resume_label = std::move(resume_label);
Json::Value data = Json::object();
try {
on_serialize(data);
} catch (const std::exception& ex) {
return Void::Result::fail(make_fsm_error(
FsmErrorCode::checkpoint_rejected,
std::string{"on_serialize threw: "} + ex.what()));
} catch (...) {
return Void::Result::fail(make_fsm_error(
FsmErrorCode::checkpoint_rejected,
"on_serialize threw unknown exception"));
}
cp.state = std::move(data);
if (m_limits.max_checkpoint_bytes > 0 &&
Detail::estimate_checkpoint_bytes(cp) >
m_limits.max_checkpoint_bytes) {
return Void::Result::fail(make_fsm_error(
FsmErrorCode::limit_exceeded,
"checkpoint exceeds max_checkpoint_bytes"));
}
return cp;
}
void fulfill_pending_checkpoints(const std::string& next_state_id,
const std::string& resume_label)
{
if (m_pending_checkpoints.empty()) {
return;
}
auto pending = std::move(m_pending_checkpoints);
m_pending_checkpoints.clear();
for (auto& p : pending) {
if (p.is_done && p.is_done()) {
continue;
}
(void)p.settle(build_checkpoint(next_state_id, resume_label));
}
}
void reject_pending_checkpoints(const Void::Result::Error& err)
{
if (m_pending_checkpoints.empty()) {
return;
}
auto pending = std::move(m_pending_checkpoints);
m_pending_checkpoints.clear();
for (auto& p : pending) {
if (p.is_done && p.is_done()) {
continue;
}
(void)p.settle(Void::Result::fail(err));
}
}
void record_observer_error(std::string msg)
{
std::lock_guard lk{m_obs_mu};
m_observer_errors.push_back(std::move(msg));
}
void set_current(const std::type_info* type)
{
std::string from = current_state();
if (const auto it = m_index.find(std::type_index{*type});
it != m_index.end()) {
m_current.store(it->second, std::memory_order_release);
}
std::string to = current_state();
++m_step;
const Transition t{from, to, m_step};
std::function<void(const Transition&)> observer_copy;
std::vector<Interceptor> interceptors_copy;
{
std::lock_guard lk{m_obs_mu};
if (m_limits.max_retained_transitions > 0) {
m_transition_history.push_back(t);
while (m_transition_history.size() >
m_limits.max_retained_transitions) {
m_transition_history.pop_front();
}
}
observer_copy = m_observer;
interceptors_copy = m_interceptors;
}
try {
on_transition(from, to);
} catch (const std::exception& ex) {
record_observer_error(
std::string{"on_transition: "} + ex.what());
} catch (...) {
record_observer_error("on_transition: unknown exception");
}
if (observer_copy) {
try {
observer_copy(t);
} catch (const std::exception& ex) {
record_observer_error(
std::string{"observer: "} + ex.what());
} catch (...) {
record_observer_error("observer: unknown exception");
}
}
for (const auto& interceptor : interceptors_copy) {
if (interceptor.before) {
try {
interceptor.before(t);
} catch (const std::exception& ex) {
record_observer_error(
std::string{"interceptor.before: "} +
ex.what());
} catch (...) {
record_observer_error(
"interceptor.before: unknown exception");
}
}
}
}
void fire_after(std::string_view state)
{
std::vector<Interceptor> interceptors_copy;
{
std::lock_guard lk{m_obs_mu};
interceptors_copy = m_interceptors;
}
for (const auto& interceptor : interceptors_copy) {
if (interceptor.after) {
try {
interceptor.after(state);
} catch (const std::exception& ex) {
record_observer_error(
std::string{"interceptor.after: "} +
ex.what());
} catch (...) {
record_observer_error(
"interceptor.after: unknown exception");
}
}
}
}
void finish_with_fault(std::string message, bool call_machine_exit)
{
m_system_error = FsmError{std::move(message)};
if (m_termination_reason.load(std::memory_order_acquire) ==
TerminationReason::none) {
m_termination_reason.store(TerminationReason::faulted,
std::memory_order_release);
}
Void::Log::error("Fsm", "system fault: {}",
m_system_error->message);
reject_pending_checkpoints(make_fsm_error(
FsmErrorCode::checkpoint_rejected,
"machine faulted before checkpoint boundary"));
if (call_machine_exit) {
on_machine_exit();
}
m_parent_stop_link.reset();
// Publish terminal status strictly last so polling/joining
// threads synchronize after all virtual hooks and field writes.
m_status.store(Status::Faulted, std::memory_order_release);
}
Coro::Task<void> drive()
{
const std::type_info* cur = m_initial;
if (cur == nullptr) {
finish_with_fault("no initial state", false);
co_return;
}
on_machine_enter();
bool first = true;
for (;;) {
if (m_root_stop && m_root_stop->stop_requested()) {
m_termination_reason.store(
m_root_timeout.load(std::memory_order_acquire)
? TerminationReason::timed_out
: TerminationReason::cancelled,
std::memory_order_release);
finish_with_fault(
m_root_timeout.load(std::memory_order_acquire)
? "deadline expired"
: "cancelled",
true);
co_return;
}
if (const auto* j =
m_jump.exchange(nullptr, std::memory_order_acq_rel);
j != nullptr) {
cur = j;
m_pending_result.reset();
m_pending_dispatch = nullptr;
}
const auto it = m_factories.find(std::type_index{*cur});
if (it == m_factories.end()) {
finish_with_fault("transition to unregistered state",
true);
co_return;
}
// Boundary checkpoint right before next state enters and
// causes effects (note: during initial entry this captures
// clean entry state).
if (m_ctx != nullptr) {
m_ctx->drain_control_queue();
}
fulfill_pending_checkpoints(durable_id_for(cur), {});
set_current(cur);
auto state = it->second();
const auto state_scope = m_ctx->allocate_scope();
std::stop_source state_stop;
std::optional<std::stop_callback<std::function<void()>>>
root_to_state;
if (m_root_stop.has_value()) {
root_to_state.emplace(
m_root_stop->get_token(),
[&state_stop] { state_stop.request_stop(); });
}
m_active_scope = state_scope;
m_active_state_stop = &state_stop;
StateKey step;
bool body_failed = false;
bool body_cancelled = false;
std::string body_error;
try {
co_await state->on_enter();
if (m_pending_dispatch) {
LaunchResult pending = std::move(*m_pending_result);
auto dispatch = std::move(m_pending_dispatch);
m_pending_result.reset();
m_pending_dispatch = nullptr;
if (pending.kind == LaunchResult::Kind::Fault) {
body_failed = true;
body_error = std::move(pending.fault.message);
} else {
step = co_await dispatch(*state,
std::move(pending));
}
} else if (first && m_startup_injector) {
auto inject = std::move(m_startup_injector);
m_startup_injector = nullptr;
step = co_await inject(*state);
} else {
step = co_await m_drivers.at(std::type_index{*cur})(
*state);
}
} catch (const Detail::CancelledException&) {
body_cancelled = true;
} catch (const std::exception& ex) {
body_failed = true;
body_error = ex.what();
} catch (...) {
body_failed = true;
body_error = "state execution threw unknown exception";
}
first = false;
// Scope exit before on_exit() and state destruction: stop
// child scope, cancel waiters, and purge timers.
m_active_state_stop = nullptr;
state_stop.request_stop();
root_to_state.reset();
if (m_ctx != nullptr) {
m_ctx->cancel_scope(state_scope);
m_ctx->purge_scope(state_scope);
}
m_active_scope = Detail::ExecutionContext::kNoScope;
bool exit_failed = false;
std::string exit_error;
try {
co_await state->on_exit();
} catch (const std::exception& ex) {
exit_failed = true;
exit_error =
std::string{"on_exit threw: "} + ex.what();
} catch (...) {
exit_failed = true;
exit_error = "on_exit threw unknown exception";
}
state.reset();
fire_after(current_state());
if (exit_failed) {
finish_with_fault(std::move(exit_error), true);
co_return;
}
if (body_cancelled ||
(m_root_stop && m_root_stop->stop_requested())) {
m_termination_reason.store(
m_root_timeout.load(std::memory_order_acquire)
? TerminationReason::timed_out
: TerminationReason::cancelled,
std::memory_order_release);
finish_with_fault(
m_root_timeout.load(std::memory_order_acquire)
? "deadline expired"
: "cancelled",
true);
co_return;
}
if (body_failed) {
finish_with_fault(std::move(body_error), true);
co_return;
}
switch (step.kind()) {
case StateKey::Kind::Transition:
cur = step.target();
continue;
case StateKey::Kind::Launch:
m_pending_result.emplace(
co_await step.run_launch());
m_pending_dispatch = step.take_dispatch();
cur = step.target();
continue;
case StateKey::Kind::Success:
m_result_value = std::move(step.payload());
m_termination_reason.store(
TerminationReason::succeeded,
std::memory_order_release);
reject_pending_checkpoints(make_fsm_error(
FsmErrorCode::checkpoint_rejected,
"machine succeeded before checkpoint boundary"));
on_machine_exit();
m_parent_stop_link.reset();
m_status.store(Status::Succeeded,
std::memory_order_release);
co_return;
case StateKey::Kind::Fail:
m_result_value = std::move(step.payload());
m_termination_reason.store(
TerminationReason::failed,
std::memory_order_release);
reject_pending_checkpoints(make_fsm_error(
FsmErrorCode::checkpoint_rejected,
"machine failed before checkpoint boundary"));
on_machine_exit();
m_parent_stop_link.reset();
m_status.store(Status::Failed,
std::memory_order_release);
co_return;
case StateKey::Kind::Fault:
finish_with_fault(
std::any_cast<FsmError>(step.payload()).message,
true);
co_return;
}
}
}
Coro::Task<void> driver()
{
const bool owns = m_owns_ctx;
auto ctx = m_ctx;
co_await drive();
if (owns && ctx) {
ctx->finish();
}
}
template <typename D = Derived> Outcome<D> take_outcome()
{
using Succ = Detail::SuccessOf<D>;
using Fail = Detail::FailureOf<D>;
using Err = Detail::ErrArm<Fail>;
switch (m_status.load(std::memory_order_acquire)) {
case Status::Succeeded:
if constexpr (std::is_void_v<Succ>) {
return Outcome<D>{};
} else {
return Outcome<D>{
std::any_cast<Succ>(m_result_value)};
}
case Status::Failed:
if constexpr (std::is_void_v<Fail>) {
return Outcome<D>{std::unexpect, std::monostate{}};
} else {
return Outcome<D>{
std::unexpect,
std::any_cast<Fail>(m_result_value)};
}
default:
static_assert(
std::is_default_constructible_v<Err>,
"a machine with a non-default-constructible "
"Failure "
"cannot represent a system fault in its Outcome; "
"check system_error()");
return Outcome<D>{std::unexpect, Err{}};
}
}
Options m_options;
FsmLimits m_limits{};
bool m_has_explicit_limits{false};
std::size_t m_depth{0};
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,
std::function<Coro::Task<StateKey>(Detail::StateBase&)>>
m_drivers;
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;
std::unordered_map<std::type_index, std::string> m_type_to_id;
std::unordered_map<std::string, const std::type_info*> m_id_to_type;
const std::type_info* m_initial{nullptr};
std::string m_machine_type;
std::uint32_t m_application_schema{1};
std::string m_restored_resume_label;
std::atomic<int> m_current{-1};
std::atomic<Status> m_status{Status::Idle};
std::atomic<TerminationReason> m_termination_reason{
TerminationReason::none};
std::any m_result_value;
std::optional<FsmError> m_system_error;
mutable std::mutex m_obs_mu;
std::function<void(const Transition&)> m_observer;
std::vector<Interceptor> m_interceptors;
std::deque<Transition> m_transition_history;
std::vector<std::string> m_observer_errors;
std::uint64_t m_step{0};
std::function<std::vector<std::string>()> m_region_probe;
std::unordered_map<std::type_index, Json::Value> m_region_history;
std::optional<LaunchResult> m_pending_result;
StateKey::Dispatch m_pending_dispatch;
std::function<Coro::Task<StateKey>(Detail::StateBase&)>
m_startup_injector;
std::atomic<const std::type_info*> m_jump{nullptr};
std::optional<std::stop_source> m_root_stop;
std::optional<std::stop_callback<std::function<void()>>>
m_parent_stop_link;
std::atomic<bool> m_root_timeout{false};
Detail::ExecutionContext::ScopeId m_active_scope{
Detail::ExecutionContext::kNoScope};
std::stop_source* m_active_state_stop{nullptr};
std::vector<PendingCheckpoint> m_pending_checkpoints;
std::optional<Coro::Task<void>> m_driver;
};
template <typename Derived> using State = Machine<Derived>::State;
} // namespace Void::Fsm