303 lines
8.3 KiB
C++
303 lines
8.3 KiB
C++
#pragma once
|
|
|
|
#include <Void/Async/Executor.hpp>
|
|
#include <Void/Async/Task.hpp>
|
|
#include <Void/Core/Meta.hpp>
|
|
#include <Void/Data/Json.hpp>
|
|
#include <Void/Functional/Error.hpp>
|
|
#include <Void/Functional/Result.hpp>
|
|
#include <Void/Time/Clock.hpp>
|
|
|
|
#include <any>
|
|
#include <chrono>
|
|
#include <concepts>
|
|
#include <cstddef>
|
|
#include <cstdint>
|
|
#include <functional>
|
|
#include <string>
|
|
#include <string_view>
|
|
#include <type_traits>
|
|
#include <typeinfo>
|
|
#include <utility>
|
|
|
|
namespace Void::Fsm
|
|
{
|
|
namespace Coro = Void::Coro;
|
|
|
|
namespace Detail
|
|
{
|
|
class StateBase;
|
|
}
|
|
|
|
/// An engine/system fault — a programming error in the machine itself (no
|
|
/// initial state, transition to an unregistered state, …). Distinct from a
|
|
/// machine's typed `Failure` result: faults travel a separate channel
|
|
/// (Machine::system_error()), never the Outcome.
|
|
struct FsmError {
|
|
std::string message;
|
|
};
|
|
|
|
enum class Status {
|
|
Idle, // constructed, not started
|
|
Running, // worker active
|
|
Succeeded, // finished with a typed Success
|
|
Failed, // finished with a typed Failure
|
|
Faulted // stopped by a system fault (see system_error())
|
|
};
|
|
|
|
/// Canonical shared predicate identifying every terminal Status value.
|
|
[[nodiscard]] constexpr bool terminal(Status s) noexcept
|
|
{
|
|
return s == Status::Succeeded || s == Status::Failed ||
|
|
s == Status::Faulted;
|
|
}
|
|
|
|
/// Why a machine finished (preserving Status values while distinguishing
|
|
/// cooperative cancellation and deadline expiration from application
|
|
/// outcomes and system faults).
|
|
enum class TerminationReason : std::uint8_t {
|
|
none = 0,
|
|
succeeded,
|
|
failed,
|
|
faulted,
|
|
cancelled,
|
|
timed_out
|
|
};
|
|
|
|
enum class FsmErrorCode : std::int32_t {
|
|
none = 0,
|
|
invalid_argument = 1,
|
|
invalid_state = 2,
|
|
not_found = 3,
|
|
overloaded = 4,
|
|
cancelled = 5,
|
|
timeout = 6,
|
|
limit_exceeded = 7,
|
|
fault = 8,
|
|
checkpoint_rejected = 9,
|
|
schema_mismatch = 10,
|
|
migration_failed = 11,
|
|
service_unavailable = 12,
|
|
internal = 13
|
|
};
|
|
|
|
[[nodiscard]] inline Void::Result::Error
|
|
make_fsm_error(FsmErrorCode code, std::string message = {})
|
|
{
|
|
using Void::Result::Error;
|
|
using Void::Result::ErrorCode;
|
|
using Void::Result::ErrorKind;
|
|
|
|
ErrorKind kind = ErrorKind::internal;
|
|
switch (code) {
|
|
case FsmErrorCode::none:
|
|
kind = ErrorKind::internal;
|
|
break;
|
|
case FsmErrorCode::invalid_argument:
|
|
kind = ErrorKind::invalid_argument;
|
|
break;
|
|
case FsmErrorCode::invalid_state:
|
|
case FsmErrorCode::checkpoint_rejected:
|
|
kind = ErrorKind::conflict;
|
|
break;
|
|
case FsmErrorCode::not_found:
|
|
case FsmErrorCode::service_unavailable:
|
|
kind = ErrorKind::not_found;
|
|
break;
|
|
case FsmErrorCode::overloaded:
|
|
kind = ErrorKind::overloaded;
|
|
break;
|
|
case FsmErrorCode::cancelled:
|
|
kind = ErrorKind::cancelled;
|
|
break;
|
|
case FsmErrorCode::timeout:
|
|
kind = ErrorKind::timeout;
|
|
break;
|
|
case FsmErrorCode::limit_exceeded:
|
|
kind = ErrorKind::exhausted;
|
|
break;
|
|
case FsmErrorCode::schema_mismatch:
|
|
case FsmErrorCode::migration_failed:
|
|
kind = ErrorKind::corrupt;
|
|
break;
|
|
case FsmErrorCode::fault:
|
|
case FsmErrorCode::internal:
|
|
kind = ErrorKind::internal;
|
|
break;
|
|
}
|
|
return Error{kind, std::move(message),
|
|
ErrorCode{Void::Result::kFsmErrorDomain,
|
|
static_cast<std::int32_t>(code)}};
|
|
}
|
|
|
|
/// Explicit resource and scheduling bounds for FSM execution.
|
|
struct FsmLimits {
|
|
std::size_t max_mailbox_events{1024};
|
|
std::size_t max_mailbox_bytes{std::size_t{4} * 1024 * 1024};
|
|
std::size_t max_deferred_events{256};
|
|
std::size_t max_timers{1024};
|
|
std::size_t max_child_regions{128};
|
|
std::size_t max_hierarchy_depth{32};
|
|
std::size_t max_retained_transitions{256};
|
|
std::size_t max_checkpoint_bytes{std::size_t{4} * 1024 * 1024};
|
|
std::size_t max_events_per_turn{64};
|
|
std::chrono::nanoseconds max_turn_duration{
|
|
std::chrono::milliseconds{1}};
|
|
std::size_t max_control_messages{256};
|
|
};
|
|
|
|
/// Explicit borrowed execution binding passed to Machine::run().
|
|
struct ExecutionBinding {
|
|
Async::Executor* executor{nullptr};
|
|
const Time::MonotonicClock* clock{
|
|
&Time::SystemMonotonicClock::instance()};
|
|
FsmLimits limits{};
|
|
};
|
|
|
|
/// Versioned boundary checkpoint capturing machine identity, schema,
|
|
/// durable state ID, optional application safe-point resume label, and
|
|
/// serialized application state.
|
|
struct Checkpoint {
|
|
static constexpr std::uint32_t kFormatVersion = 1;
|
|
std::uint32_t format_version{kFormatVersion};
|
|
std::string machine_type;
|
|
std::uint32_t application_schema{1};
|
|
std::uint64_t transition_sequence{0};
|
|
std::string state_id;
|
|
std::string resume_label;
|
|
Json::Value state;
|
|
};
|
|
|
|
/// Annotation tag specifying a durable state ID (`[[= Void::Fsm::StateId{"..."}]]`).
|
|
struct StateId {
|
|
Void::Meta::Str value;
|
|
};
|
|
|
|
/// Byte-size accounting helper for typed event admission into bounded
|
|
/// FSM mailboxes.
|
|
template <typename E>
|
|
[[nodiscard]] constexpr std::size_t event_payload_bytes(const E& e) noexcept
|
|
{
|
|
if constexpr (requires {
|
|
{
|
|
e.payload_bytes()
|
|
} -> std::convertible_to<std::size_t>;
|
|
}) {
|
|
return static_cast<std::size_t>(e.payload_bytes());
|
|
} else if constexpr (std::is_same_v<std::remove_cvref_t<E>,
|
|
std::string>) {
|
|
return sizeof(E) + e.size();
|
|
} else {
|
|
return sizeof(E);
|
|
}
|
|
}
|
|
|
|
/// The outcome of a sub-machine launched via startMachine<Sub, Next>():
|
|
/// a typed Success value, a typed Failure value, or a system fault.
|
|
struct LaunchResult {
|
|
enum class Kind { Success, Failure, Fault };
|
|
Kind kind{Kind::Fault};
|
|
std::any value; // Success payload (kind == Success)
|
|
std::any failure; // Failure payload (kind == Failure)
|
|
FsmError fault; // system fault (kind == Fault)
|
|
};
|
|
|
|
/// What a state's entry returns: move to another state, finish with a typed
|
|
/// Success / Failure, or launch a sub-machine. Built only through the State
|
|
/// helpers (next<S>() / succeed(...) / fail(...) / startMachine).
|
|
class StateKey
|
|
{
|
|
public:
|
|
|
|
enum class Kind { Transition, Success, Fail, Launch, Fault };
|
|
|
|
[[nodiscard]] static StateKey
|
|
transition(const std::type_info& target)
|
|
{
|
|
StateKey s;
|
|
s.m_kind = Kind::Transition;
|
|
s.m_target = ⌖
|
|
return s;
|
|
}
|
|
|
|
/// Signal a system fault (programming error) — distinct from a
|
|
/// typed Failure. Routed to Machine::system_error().
|
|
[[nodiscard]] static StateKey fault(FsmError error)
|
|
{
|
|
StateKey s;
|
|
s.m_kind = Kind::Fault;
|
|
s.m_payload = std::any{std::move(error)};
|
|
return s;
|
|
}
|
|
|
|
/// A bound dispatcher: given the entered Next state and the sub's
|
|
/// LaunchResult, calls Next's signature-matched handler.
|
|
using Dispatch = std::function<Coro::Task<StateKey>(
|
|
Detail::StateBase&, LaunchResult)>;
|
|
|
|
/// Launch a sub-machine, then enter `target` (a continuation state)
|
|
/// with the sub's LaunchResult, dispatched via `dispatch`.
|
|
[[nodiscard]] static StateKey
|
|
launch(const std::type_info& target,
|
|
std::function<Coro::Task<LaunchResult>()> launcher,
|
|
Dispatch dispatch)
|
|
{
|
|
StateKey s;
|
|
s.m_kind = Kind::Launch;
|
|
s.m_target = ⌖
|
|
s.m_launcher = std::move(launcher);
|
|
s.m_dispatch = std::move(dispatch);
|
|
return s;
|
|
}
|
|
|
|
/// Finish with a typed Success payload (empty std::any for void).
|
|
[[nodiscard]] static StateKey success(std::any value)
|
|
{
|
|
StateKey s;
|
|
s.m_kind = Kind::Success;
|
|
s.m_payload = std::move(value);
|
|
return s;
|
|
}
|
|
|
|
/// Finish with a typed Failure payload (empty std::any for void).
|
|
[[nodiscard]] static StateKey failure(std::any value)
|
|
{
|
|
StateKey s;
|
|
s.m_kind = Kind::Fail;
|
|
s.m_payload = std::move(value);
|
|
return s;
|
|
}
|
|
|
|
[[nodiscard]] Kind kind() const noexcept { return m_kind; }
|
|
|
|
[[nodiscard]] const std::type_info* target() const noexcept
|
|
{
|
|
return m_target;
|
|
}
|
|
|
|
/// The Success or Failure payload (by kind).
|
|
[[nodiscard]] std::any& payload() noexcept { return m_payload; }
|
|
|
|
/// Run the sub-machine for a Launch step (yields its LaunchResult).
|
|
[[nodiscard]] Coro::Task<LaunchResult> run_launch()
|
|
{
|
|
return m_launcher();
|
|
}
|
|
|
|
/// Take the bound dispatcher for a Launch step.
|
|
[[nodiscard]] Dispatch take_dispatch()
|
|
{
|
|
return std::move(m_dispatch);
|
|
}
|
|
|
|
private:
|
|
|
|
Kind m_kind{Kind::Fail};
|
|
const std::type_info* m_target{nullptr};
|
|
std::any m_payload;
|
|
std::function<Coro::Task<LaunchResult>()> m_launcher;
|
|
Dispatch m_dispatch;
|
|
};
|
|
|
|
} // namespace Void::Fsm
|