Remove the two old FSMs ahead of the inheritance-based rewrite
Deletes the compile-time Void::StateMachine and the builder-based runtime Void::Fsm (Definition/Machine/Event/PluginBehavior + their standalone tests, the FSM behaviour plugins, and the FSM x Plugin integration test and its CMake wiring). The general-purpose Plugin module and its stateful hot-reload tests are untouched. Both are being replaced by a single inheritance + coroutine workflow FSM (next phase). 936 tests green (51 old FSM/StateMachine tests removed). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
6b5f61f00a
commit
04cf1998bd
20 files changed
+3
-3793
No files matched your search
@@ -47,8 +47,7 @@ VoidLibrary is a C++26 modular shared library organized as **umbrella modules**
|
||||
| `Configuration` | SHARED | Config, Env + Argparse |
|
||||
| `Stacktrace` | SHARED | Boost.Stacktrace capture, color helpers (kept separate to isolate the Boost dep) |
|
||||
| `Plugin` | SHARED | dlopen loader + manager, C ABI, hot reload (see below) |
|
||||
| `StateMachine` | INTERFACE | compile-time variant-based FSM |
|
||||
| `Fsm` | SHARED | runtime hierarchical FSM (see below) |
|
||||
| `Fsm` | SHARED | inheritance + coroutine workflow FSM (see below) |
|
||||
| `Testing` / `TestingMock` | STATIC / INTERFACE | test + mock frameworks |
|
||||
|
||||
`include/Void/Detail/` (e.g. `Enum.hpp` — P2996 enum reflection) is not a module; it is header-only and reachable from every module via the shared include root.
|
||||
@@ -136,19 +135,9 @@ Other key points:
|
||||
|
||||
`Configuration::Config`: flat string store with dotted keys. Sources (overlay-composable, last wins): `from_env`, `from_env_prefix("APP_")` (`__`→`.`, lowercased), `from_file` (KEY=VALUE), `from_ini`, `from_json` (flattened), `from_args` (`--key=value`). Typed access `get_as<T>` / `get_or_as<T>` (numbers, bool spellings, enums by name via reflection, chrono durations like "250ms"). `subtree(prefix)` strips a prefix. `Bind.hpp`: `bind<T>(cfg, prefix)` fills an aggregate via P2996 (defaults = schema). `Watch.hpp`: `ConfigWatch` reloads a file on change with per-key diff (debounced polling via `FileSystem::FileWatcher` in `System`).
|
||||
|
||||
### Fsm module (runtime FSM)
|
||||
### Fsm module
|
||||
|
||||
`Void::Fsm` — full-featured runtime state machine, distinct from the compile-time `StateMachine`:
|
||||
|
||||
- **Definition**: `Builder` declares states by name (`state("a", parent)` — hierarchical), events (`event("go")` or from enums via reflection), `initial`, `parallel` (orthogonal regions), `history(Shallow|Deep)`, `defer`, `timeout(state, ms, event)`, `transition(from, on, to).guard(...).action(...)`, `internal(in, on)`. `build()` validates into an immutable `shared_ptr<const MachineDef>`. Names are the stable identity; ids are per-definition.
|
||||
- **Actions** are `std::function<Coro::Task<void>(Machine&, const Event&)>` (sync lambdas via `SyncAction` overloads). The run-to-completion step finishes only when the action's coroutine completes; the worker drives it on its own `ManualExecutor`.
|
||||
- **Concurrency (MPSC)**: `post()` is lock-free from any thread (Vyukov queue + park semaphore); exactly one consumer — the owned worker (`start()` returns once the initial configuration is entered) or the embedder via `run_pending()` when constructed with `MachineOptions{.own_worker = false}` (the deterministic mode used by most tests; note `send_wait`/queued `serialize_state` would self-deadlock there — they're for the worker mode). Observation (`current()`, `is_in`) is a seqlock read of a trivially-copyable `StateSnapshot` (≤16 active leaves).
|
||||
- **send paths**: `co_await machine.send(ev[, &executor])` resolves with `SendResult{Handled,Deferred,Unhandled,Dropped}` after the step; `send_wait` blocks; resumption defaults to the machine worker.
|
||||
- **Hot swap**: `swap_definition(def)` applies between steps. If every active leaf name exists in the new def, the configuration is adopted without re-running entry actions (seamless); otherwise the machine re-enters the initial configuration. History is remapped by name.
|
||||
- **Persistence**: `serialize_state()` → JSON with leaf/history *names*; `restore_state(json)` on a stopped machine re-activates silently (no entry actions).
|
||||
- History records are snapshotted at exit time in `perform_transition` (not incrementally) — keep it that way; incremental recording accumulates stale leaves.
|
||||
|
||||
**FSM behaviours from plugins** (`Fsm/PluginBehavior.hpp`): a plugin implements `IFsmBehaviorPack::register_into(Builder&)` and exports `extern "C" IFsmBehaviorPack* void_plugin_fsm_behaviors()`. The host resolves it via `PluginManager::raw_symbol(name, kFsmBehaviorsSymbol)`, calls `build_machine_def(pack)`, and on `on_reloaded` rebuilds + `swap_definition` — same state names ⇒ the running machine keeps its configuration. Plugin-provided actions are `std::function`s whose code lives in the `.so`; keep a `PluginHandle` pinned and rely on `dlclose_on_swap=false` so the code pages stay mapped under in-flight coroutine frames. See `tests/internal/FsmPluginHotReload.cpp`.
|
||||
`Void::Fsm` is being rewritten as an inheritance + coroutine workflow FSM (states as nested structs, async `run` returning next-state/success/fail, events, nesting, dynamic registration). Documented when it lands.
|
||||
|
||||
### Plugin module (hot reload)
|
||||
|
||||
|
||||
@@ -1,323 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Async/Task.hpp>
|
||||
#include <Void/Detail/Enum.hpp>
|
||||
#include <Void/Fsm/Event.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <expected>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <type_traits>
|
||||
#include <unordered_map>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Fsm
|
||||
{
|
||||
class Machine;
|
||||
|
||||
/// Guards run synchronously on the machine worker; keep them cheap.
|
||||
using Guard = std::function<bool(const Machine&, const Event&)>;
|
||||
|
||||
/// Actions may be coroutines: the run-to-completion step finishes only
|
||||
/// when the returned task completes (events arriving meanwhile queue).
|
||||
using Action = std::function<Coro::Task<void>(Machine&, const Event&)>;
|
||||
|
||||
/// Plain function convenience form, wrapped into an Action.
|
||||
using SyncAction = std::function<void(Machine&, const Event&)>;
|
||||
|
||||
enum class History : std::uint8_t { None, Shallow, Deep };
|
||||
|
||||
struct DefError {
|
||||
std::string message;
|
||||
};
|
||||
|
||||
/// Lightweight handle to a state being defined / addressed.
|
||||
class StateRef
|
||||
{
|
||||
public:
|
||||
|
||||
constexpr StateRef() = default;
|
||||
constexpr explicit StateRef(StateId id) : m_id(id) {}
|
||||
|
||||
[[nodiscard]] constexpr StateId id() const noexcept { return m_id; }
|
||||
|
||||
[[nodiscard]] constexpr bool valid() const noexcept
|
||||
{
|
||||
return m_id != kInvalidState;
|
||||
}
|
||||
|
||||
constexpr bool operator==(const StateRef&) const = default;
|
||||
|
||||
private:
|
||||
|
||||
StateId m_id{kInvalidState};
|
||||
};
|
||||
|
||||
// ── MachineDef ────────────────────────────────────────────────────────
|
||||
// Immutable, flattened machine description produced by Builder::build.
|
||||
// Shared by Machines via shared_ptr; hot-swap replaces the pointer.
|
||||
class MachineDef
|
||||
{
|
||||
public:
|
||||
|
||||
struct Timeout {
|
||||
std::chrono::milliseconds after{};
|
||||
EventId fires{kInvalidEvent};
|
||||
};
|
||||
|
||||
struct StateNode {
|
||||
std::string name;
|
||||
StateId parent{kInvalidState};
|
||||
std::vector<StateId> children;
|
||||
StateId initial{kInvalidState}; // composites only
|
||||
bool parallel{false};
|
||||
History history{History::None};
|
||||
Action entry; // may be empty
|
||||
Action exit; // may be empty
|
||||
std::vector<EventId> deferred;
|
||||
std::optional<Timeout> timeout;
|
||||
int depth{0};
|
||||
};
|
||||
|
||||
struct TransitionDef {
|
||||
StateId from{kInvalidState};
|
||||
EventId on{kInvalidEvent};
|
||||
StateId to{kInvalidState}; // kInvalidState => internal
|
||||
Guard guard; // may be empty (always true)
|
||||
Action action; // may be empty
|
||||
bool internal{false};
|
||||
};
|
||||
|
||||
[[nodiscard]] const StateNode& state(StateId id) const
|
||||
{
|
||||
return m_states[id];
|
||||
}
|
||||
|
||||
[[nodiscard]] std::size_t state_count() const noexcept
|
||||
{
|
||||
return m_states.size();
|
||||
}
|
||||
|
||||
/// Transitions leaving `from`, in definition order.
|
||||
[[nodiscard]] const std::vector<std::size_t>&
|
||||
transitions_from(StateId from) const
|
||||
{
|
||||
return m_transitions_by_state[from];
|
||||
}
|
||||
|
||||
[[nodiscard]] const TransitionDef&
|
||||
transition(std::size_t index) const
|
||||
{
|
||||
return m_transitions[index];
|
||||
}
|
||||
|
||||
[[nodiscard]] std::optional<StateId>
|
||||
state_id(std::string_view name) const
|
||||
{
|
||||
const auto it = m_state_ids.find(std::string{name});
|
||||
if (it == m_state_ids.end()) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return it->second;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::optional<EventId>
|
||||
event_id(std::string_view name) const
|
||||
{
|
||||
const auto it = m_event_ids.find(std::string{name});
|
||||
if (it == m_event_ids.end()) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return it->second;
|
||||
}
|
||||
|
||||
/// Enum overload: matches the enumerator's identifier name.
|
||||
template <typename E>
|
||||
requires std::is_enum_v<E>
|
||||
[[nodiscard]] std::optional<EventId> event_id(E e) const
|
||||
{
|
||||
#ifdef VOID_HAS_ENUM_REFLECTION
|
||||
return event_id(Void::Detail::enum_name(e));
|
||||
#else
|
||||
(void)e;
|
||||
return std::nullopt;
|
||||
#endif
|
||||
}
|
||||
|
||||
[[nodiscard]] std::string_view event_name(EventId id) const
|
||||
{
|
||||
return m_event_names[id];
|
||||
}
|
||||
|
||||
[[nodiscard]] std::size_t event_count() const noexcept
|
||||
{
|
||||
return m_event_names.size();
|
||||
}
|
||||
|
||||
/// True if `ancestor` is `state` or one of its ancestors.
|
||||
[[nodiscard]] bool is_ancestor_or_self(StateId ancestor,
|
||||
StateId state) const;
|
||||
|
||||
/// Lowest common ancestor of two states.
|
||||
[[nodiscard]] StateId lca(StateId a, StateId b) const;
|
||||
|
||||
private:
|
||||
|
||||
friend class Builder;
|
||||
friend class TransitionBuilder;
|
||||
|
||||
std::vector<StateNode> m_states;
|
||||
std::vector<TransitionDef> m_transitions;
|
||||
std::vector<std::vector<std::size_t>> m_transitions_by_state;
|
||||
std::unordered_map<std::string, StateId> m_state_ids;
|
||||
std::unordered_map<std::string, EventId> m_event_ids;
|
||||
std::vector<std::string> m_event_names;
|
||||
};
|
||||
|
||||
// ── TransitionBuilder ─────────────────────────────────────────────────
|
||||
class Builder;
|
||||
|
||||
class TransitionBuilder
|
||||
{
|
||||
public:
|
||||
|
||||
TransitionBuilder& guard(Guard g);
|
||||
TransitionBuilder& action(Action a);
|
||||
TransitionBuilder& action(SyncAction a);
|
||||
|
||||
private:
|
||||
|
||||
friend class Builder;
|
||||
TransitionBuilder(Builder& builder, std::size_t index)
|
||||
: m_builder(&builder), m_index(index)
|
||||
{
|
||||
}
|
||||
|
||||
Builder* m_builder;
|
||||
std::size_t m_index;
|
||||
};
|
||||
|
||||
// ── Builder ───────────────────────────────────────────────────────────
|
||||
// Fluent definition of states, transitions, and behaviors. build()
|
||||
// validates and produces an immutable MachineDef.
|
||||
class Builder
|
||||
{
|
||||
public:
|
||||
|
||||
Builder();
|
||||
|
||||
/// The implicit root pseudo-state (parent of all top-level
|
||||
/// states).
|
||||
[[nodiscard]] static constexpr StateRef root() noexcept
|
||||
{
|
||||
return StateRef{kRootState};
|
||||
}
|
||||
|
||||
/// Declare (or look up) a state. Names are globally unique.
|
||||
StateRef state(std::string_view name, StateRef parent = root());
|
||||
|
||||
/// Declare (or look up) an event by name.
|
||||
EventId event(std::string_view name);
|
||||
|
||||
/// Declare an event from an enum value's identifier.
|
||||
template <typename E>
|
||||
requires std::is_enum_v<E>
|
||||
EventId event(E e)
|
||||
{
|
||||
#ifdef VOID_HAS_ENUM_REFLECTION
|
||||
return event(Void::Detail::enum_name(e));
|
||||
#else
|
||||
static_assert(std::is_enum_v<E> && false,
|
||||
"enum events require P2996 reflection");
|
||||
#endif
|
||||
}
|
||||
|
||||
/// Declare one leaf state per enumerator of E under `parent`.
|
||||
template <typename E>
|
||||
requires std::is_enum_v<E>
|
||||
Builder& states_from_enum(StateRef parent = root())
|
||||
{
|
||||
#ifdef VOID_HAS_ENUM_REFLECTION
|
||||
static constexpr auto enumerators =
|
||||
std::define_static_array(std::meta::enumerators_of(^^E));
|
||||
template for (constexpr auto e : enumerators)
|
||||
{
|
||||
(void)state(std::meta::identifier_of(e), parent);
|
||||
}
|
||||
return *this;
|
||||
#else
|
||||
static_assert(std::is_enum_v<E> && false,
|
||||
"states_from_enum requires P2996 reflection");
|
||||
#endif
|
||||
}
|
||||
|
||||
/// Resolve an already-declared state by enum value.
|
||||
template <typename E>
|
||||
requires std::is_enum_v<E>
|
||||
StateRef state_of(E e)
|
||||
{
|
||||
#ifdef VOID_HAS_ENUM_REFLECTION
|
||||
return state(Void::Detail::enum_name(e));
|
||||
#else
|
||||
static_assert(std::is_enum_v<E> && false,
|
||||
"enum states require P2996 reflection");
|
||||
#endif
|
||||
}
|
||||
|
||||
/// Mark `child` as the initial state of its parent.
|
||||
Builder& initial(StateRef child);
|
||||
|
||||
/// Mark a composite as a parallel (orthogonal-region) holder:
|
||||
/// entering it activates every child region simultaneously.
|
||||
Builder& parallel(StateRef composite);
|
||||
|
||||
Builder& on_entry(StateRef state, Action action);
|
||||
Builder& on_entry(StateRef state, SyncAction action);
|
||||
Builder& on_exit(StateRef state, Action action);
|
||||
Builder& on_exit(StateRef state, SyncAction action);
|
||||
|
||||
/// Remember the last active substate(s) of `composite` and
|
||||
/// restore them when it is re-entered.
|
||||
Builder& history(StateRef composite, History kind);
|
||||
|
||||
/// While `state` is active, events with `id` are stashed and
|
||||
/// re-injected after the next state change.
|
||||
Builder& defer(StateRef state, EventId id);
|
||||
|
||||
/// After `after` continuously active in `state`, synthesize
|
||||
/// the `fires` event.
|
||||
Builder& timeout(StateRef state,
|
||||
std::chrono::milliseconds after,
|
||||
EventId fires);
|
||||
|
||||
/// External transition. Returns a fluent handle for attaching
|
||||
/// .guard() / .action().
|
||||
TransitionBuilder transition(StateRef from, EventId on,
|
||||
StateRef to);
|
||||
|
||||
/// Internal transition: action fires without exit/entry.
|
||||
TransitionBuilder internal(StateRef in, EventId on);
|
||||
|
||||
/// Validate and produce the immutable definition.
|
||||
[[nodiscard]] std::expected<std::shared_ptr<const MachineDef>,
|
||||
DefError>
|
||||
build();
|
||||
|
||||
private:
|
||||
|
||||
friend class TransitionBuilder;
|
||||
|
||||
MachineDef m_def; // built up in place
|
||||
bool m_consumed{false}; // build() may only be called once
|
||||
};
|
||||
|
||||
/// Wrap a plain function into a coroutine Action.
|
||||
[[nodiscard]] Action wrap_sync(SyncAction fn);
|
||||
|
||||
} // namespace Void::Fsm
|
||||
@@ -1,42 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <any>
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
|
||||
namespace Void::Fsm
|
||||
{
|
||||
/// Interned identifiers. Both are assigned by the Builder; names are
|
||||
/// the stable identity (they survive definition swaps and serialize
|
||||
/// into hot-reload state), ids are the fast runtime currency.
|
||||
using StateId = std::uint32_t;
|
||||
using EventId = std::uint32_t;
|
||||
|
||||
inline constexpr StateId kInvalidState = ~StateId{0};
|
||||
inline constexpr EventId kInvalidEvent = ~EventId{0};
|
||||
|
||||
/// The root pseudo-state always has id 0.
|
||||
inline constexpr StateId kRootState = 0;
|
||||
|
||||
/// A type-erased event instance. The payload is optional; guards and
|
||||
/// actions retrieve it with std::any_cast against the type they
|
||||
/// expect.
|
||||
struct Event {
|
||||
EventId id{kInvalidEvent};
|
||||
std::any payload{};
|
||||
};
|
||||
|
||||
/// Outcome of one run-to-completion step for a posted event.
|
||||
enum class SendResult : std::uint8_t {
|
||||
Handled, // at least one transition fired
|
||||
Deferred, // stashed by an active state's defer list
|
||||
Unhandled, // no active state had a matching transition
|
||||
Dropped // machine stopped before processing
|
||||
};
|
||||
|
||||
struct FsmError {
|
||||
std::string message;
|
||||
};
|
||||
|
||||
} // namespace Void::Fsm
|
||||
@@ -1,273 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Async/Executor.hpp>
|
||||
#include <Void/Async/MpscQueue.hpp>
|
||||
#include <Void/Data/Json.hpp>
|
||||
#include <Void/Data/Reflect.hpp>
|
||||
#include <Void/Fsm/Definition.hpp>
|
||||
#include <Void/Fsm/Event.hpp>
|
||||
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <coroutine>
|
||||
#include <cstdint>
|
||||
#include <expected>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <semaphore>
|
||||
#include <thread>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Fsm
|
||||
{
|
||||
/// Lock-free observable snapshot of the active configuration. Holds
|
||||
/// the active *leaf* states (compositions are implied by ancestry);
|
||||
/// fixed-size so the seqlock copy is trivial.
|
||||
struct StateSnapshot {
|
||||
static constexpr std::size_t kMaxLeaves = 16;
|
||||
|
||||
std::array<StateId, kMaxLeaves> leaves{};
|
||||
std::uint32_t leaf_count{0};
|
||||
std::uint64_t step{0}; // run-to-completion step counter
|
||||
bool running{false};
|
||||
|
||||
[[nodiscard]] bool contains(StateId id) const noexcept
|
||||
{
|
||||
for (std::uint32_t i = 0; i < leaf_count; ++i) {
|
||||
if (leaves[i] == id) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
// ── Machine ───────────────────────────────────────────────────────────
|
||||
// Runtime engine driving one MachineDef.
|
||||
//
|
||||
// Concurrency model (MPSC): any thread may post()/send(); exactly one
|
||||
// consumer — the owned worker thread (default) or the embedding thread
|
||||
// via run_one()/run_pending() — executes run-to-completion steps. All
|
||||
// mutable machine state is owned by that consumer; observers read a
|
||||
// seqlock-protected snapshot.
|
||||
//
|
||||
// Hot path costs: post() = wait-free queue push (+ a semaphore release
|
||||
// only when the worker parked); current()/is_in() = seqlock read,
|
||||
// retry on contention; no mutexes anywhere on these paths.
|
||||
struct MachineOptions {
|
||||
/// Spawn a worker thread in start(). When false the embedder
|
||||
/// drives the machine with run_pending().
|
||||
bool own_worker = true;
|
||||
};
|
||||
|
||||
class Machine
|
||||
{
|
||||
public:
|
||||
|
||||
using Options = MachineOptions;
|
||||
|
||||
explicit Machine(std::shared_ptr<const MachineDef> def,
|
||||
Options options = {});
|
||||
|
||||
/// Stops the machine (drains nothing; pending events are
|
||||
/// dropped) and joins the worker.
|
||||
~Machine();
|
||||
|
||||
Machine(const Machine&) = delete;
|
||||
Machine& operator=(const Machine&) = delete;
|
||||
Machine(Machine&&) = delete;
|
||||
Machine& operator=(Machine&&) = delete;
|
||||
|
||||
// ── lifecycle ─────────────────────────────────────────────────
|
||||
|
||||
/// Enter the initial configuration (entry actions run on the
|
||||
/// consumer). With own_worker the worker starts here.
|
||||
void start();
|
||||
|
||||
/// Process queued events, then stop. Joins the worker.
|
||||
void stop();
|
||||
|
||||
[[nodiscard]] bool running() const noexcept;
|
||||
|
||||
// ── event submission (any thread) ─────────────────────────────
|
||||
|
||||
/// Fire-and-forget. Lock-free. Returns false if the machine
|
||||
/// is not accepting events (not started or stopped).
|
||||
bool post(Event event);
|
||||
|
||||
template <typename E>
|
||||
requires std::is_enum_v<E>
|
||||
bool post(E e, std::any payload = {})
|
||||
{
|
||||
const auto def = definition();
|
||||
const auto id = def->event_id(e);
|
||||
if (!id.has_value()) {
|
||||
return false;
|
||||
}
|
||||
return post(Event{*id, std::move(payload)});
|
||||
}
|
||||
|
||||
/// Awaitable submission: co_await machine.send(ev) resumes
|
||||
/// after the event's run-to-completion step with its result.
|
||||
/// Resumption runs on the machine's consumer thread unless a
|
||||
/// resume executor is given.
|
||||
class SendAwaitable
|
||||
{
|
||||
public:
|
||||
|
||||
[[nodiscard]] bool await_ready() const noexcept
|
||||
{
|
||||
return m_result.has_value();
|
||||
}
|
||||
|
||||
void await_suspend(std::coroutine_handle<> h);
|
||||
|
||||
[[nodiscard]] SendResult await_resume() const noexcept
|
||||
{
|
||||
return m_result.value_or(SendResult::Dropped);
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
friend class Machine;
|
||||
SendAwaitable(Machine& machine, Event event,
|
||||
Async::Executor* resume_on)
|
||||
: m_machine(&machine), m_event(std::move(event)),
|
||||
m_resume_on(resume_on)
|
||||
{
|
||||
}
|
||||
|
||||
Machine* m_machine;
|
||||
Event m_event;
|
||||
Async::Executor* m_resume_on;
|
||||
std::optional<SendResult> m_result;
|
||||
};
|
||||
|
||||
[[nodiscard]] SendAwaitable
|
||||
send(Event event, Async::Executor* resume_on = nullptr)
|
||||
{
|
||||
return SendAwaitable{*this, std::move(event), resume_on};
|
||||
}
|
||||
|
||||
/// Blocking submission: returns once the event's step ran.
|
||||
SendResult send_wait(Event event);
|
||||
|
||||
// ── observation (any thread, lock-free) ───────────────────────
|
||||
|
||||
[[nodiscard]] StateSnapshot current() const noexcept;
|
||||
|
||||
/// True if `state` (leaf or composite) is in the active
|
||||
/// configuration.
|
||||
[[nodiscard]] bool is_in(StateId state) const;
|
||||
[[nodiscard]] bool is_in(std::string_view state) const;
|
||||
|
||||
[[nodiscard]] std::shared_ptr<const MachineDef> definition() const
|
||||
{
|
||||
return m_def.load(std::memory_order_acquire);
|
||||
}
|
||||
|
||||
// ── hot swap / persistence ────────────────────────────────────
|
||||
|
||||
/// Replace the definition between run-to-completion steps.
|
||||
/// Active states are re-mapped by name; the queue keeps
|
||||
/// flowing. States whose names vanished fall back to the new
|
||||
/// definition's initial configuration for that region.
|
||||
void swap_definition(std::shared_ptr<const MachineDef> def);
|
||||
|
||||
/// Serialize the active configuration + history (by state
|
||||
/// name) for hot-reload / persistence. Processed as a control
|
||||
/// step on the consumer; safe from any thread while running.
|
||||
[[nodiscard]] Json::Value serialize_state();
|
||||
|
||||
/// Restore a configuration produced by serialize_state()
|
||||
/// (optionally migrated). Must be called before start().
|
||||
[[nodiscard]] std::expected<void, FsmError>
|
||||
restore_state(const Json::Value& state);
|
||||
|
||||
// ── embedder-driven mode (own_worker = false) ─────────────────
|
||||
|
||||
/// Process queued events/control work; returns the number of
|
||||
/// envelopes handled. Single consumer only.
|
||||
std::size_t run_pending();
|
||||
|
||||
/// Block the calling thread (the consumer) until `until`
|
||||
/// returns true, processing events as they arrive. Intended
|
||||
/// for tests and simple embedders.
|
||||
void run_until(const std::function<bool()>& until);
|
||||
|
||||
private:
|
||||
|
||||
struct Envelope; // Event + completion plumbing
|
||||
struct HistoryRecord {
|
||||
std::vector<StateId> leaves; // deep: leaves; shallow: child
|
||||
};
|
||||
|
||||
// consumer-side core
|
||||
void consumer_loop();
|
||||
std::size_t drain_once();
|
||||
bool handle_envelope(Envelope& env);
|
||||
SendResult dispatch_event(const Event& event);
|
||||
void enter_initial_configuration();
|
||||
void perform_transition(const MachineDef::TransitionDef& t,
|
||||
StateId source_leaf,
|
||||
const Event& event);
|
||||
void enter_target(StateId lca, StateId target, const Event& event);
|
||||
void descend_into(StateId state, const Event& event);
|
||||
void exit_to_lca(StateId leaf, StateId lca, const Event& event);
|
||||
void exit_single(StateId state, const Event& event);
|
||||
void enter_single(StateId state, const Event& event);
|
||||
void run_action(const Action& action, const Event& event);
|
||||
void publish_snapshot();
|
||||
void rearm_timers();
|
||||
void fire_due_timers();
|
||||
void reinject_deferred();
|
||||
[[nodiscard]] std::optional<std::chrono::steady_clock::time_point>
|
||||
next_deadline() const;
|
||||
void apply_swap(std::shared_ptr<const MachineDef> next);
|
||||
std::vector<std::string> active_leaf_names() const;
|
||||
|
||||
void wake_consumer() noexcept;
|
||||
|
||||
// immutable-ish shared state
|
||||
std::atomic<std::shared_ptr<const MachineDef>> m_def;
|
||||
Options m_options;
|
||||
|
||||
// MPSC queue + parking
|
||||
Async::MpscQueue<Envelope*> m_queue;
|
||||
std::counting_semaphore<> m_wakeup{0};
|
||||
std::atomic<bool> m_sleeping{false};
|
||||
std::atomic<bool> m_accepting{false};
|
||||
std::atomic<bool> m_stop{false};
|
||||
std::thread m_worker;
|
||||
|
||||
// seqlock snapshot
|
||||
mutable std::atomic<std::uint64_t> m_seq{0};
|
||||
StateSnapshot m_snapshot{};
|
||||
|
||||
// ── consumer-owned state (no synchronization) ─────────────────
|
||||
std::shared_ptr<const MachineDef> m_active_def;
|
||||
std::vector<bool> m_active; // by StateId
|
||||
std::vector<StateId> m_leaves; // active leaves, region order
|
||||
std::unordered_map<StateId, HistoryRecord> m_history;
|
||||
std::vector<Envelope*> m_deferred; // stashed events
|
||||
bool m_deferred_dirty{false}; // re-inject after change
|
||||
std::uint64_t m_step{0};
|
||||
Async::ManualExecutor m_executor; // drives coroutine actions
|
||||
|
||||
struct TimerArm {
|
||||
StateId state;
|
||||
std::chrono::steady_clock::time_point deadline;
|
||||
EventId fires;
|
||||
std::uint64_t generation;
|
||||
};
|
||||
std::vector<TimerArm> m_timers;
|
||||
std::vector<std::uint64_t> m_activation; // per state
|
||||
|
||||
// configuration captured by restore_state(), applied silently
|
||||
// (no entry actions) when start() runs
|
||||
std::optional<Json::Value> m_pending_restore;
|
||||
};
|
||||
|
||||
} // namespace Void::Fsm
|
||||
@@ -1,53 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Fsm/Definition.hpp>
|
||||
|
||||
#include <expected>
|
||||
#include <memory>
|
||||
|
||||
namespace Void::Fsm
|
||||
{
|
||||
// ── IFsmBehaviorPack ──────────────────────────────────────────────────
|
||||
// A plugin exposes FSM states/events/guards/actions by implementing
|
||||
// this interface and returning it from the optional C entry point
|
||||
//
|
||||
// extern "C" Void::Fsm::IFsmBehaviorPack* void_plugin_fsm_behaviors();
|
||||
//
|
||||
// The host calls register_into(builder) while assembling a machine
|
||||
// definition, then build()s it. Because the actions/guards the pack
|
||||
// installs are std::functions whose code lives in the plugin .so, the
|
||||
// machine (and its MachineDef) must not outlive the plugin: keep a
|
||||
// Plugin::PluginHandle pinned for the machine's lifetime, and rely on
|
||||
// PluginManager's dlclose_on_swap=false so the code pages stay mapped
|
||||
// across reloads. See tests/internal/FsmPluginHotReload.cpp.
|
||||
//
|
||||
// The interface is a same-compiler C++ ABI (like IPlugin): the host and
|
||||
// plugin must be built with the same toolchain, which they are within
|
||||
// this project.
|
||||
class IFsmBehaviorPack
|
||||
{
|
||||
public:
|
||||
|
||||
virtual ~IFsmBehaviorPack() = default;
|
||||
|
||||
/// Declare this pack's states, events, and transitions on the
|
||||
/// builder. Called once per machine-definition build.
|
||||
virtual void register_into(Builder& builder) = 0;
|
||||
};
|
||||
|
||||
using fsm_behaviors_fn = IFsmBehaviorPack* (*)();
|
||||
|
||||
inline constexpr const char* kFsmBehaviorsSymbol =
|
||||
"void_plugin_fsm_behaviors";
|
||||
|
||||
/// Build an immutable machine definition from a behaviour pack.
|
||||
[[nodiscard]] inline std::expected<std::shared_ptr<const MachineDef>,
|
||||
DefError>
|
||||
build_machine_def(IFsmBehaviorPack& pack)
|
||||
{
|
||||
Builder builder;
|
||||
pack.register_into(builder);
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
} // namespace Void::Fsm
|
||||
@@ -1,209 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <concepts>
|
||||
#include <functional>
|
||||
#include <optional>
|
||||
#include <stdexcept>
|
||||
#include <string_view>
|
||||
#include <type_traits>
|
||||
#include <variant>
|
||||
|
||||
namespace Void::StateMachine
|
||||
{
|
||||
|
||||
// ── Concepts ──────────────────────────────────────────────────────────────────
|
||||
|
||||
template <typename S>
|
||||
concept State = std::is_default_constructible_v<S>;
|
||||
|
||||
template <typename E>
|
||||
concept Event = std::copyable<E>;
|
||||
|
||||
// ── Transition helper ─────────────────────────────────────────────────────────
|
||||
// A transition<From, Ev, To> captures one arc: From --[Ev]--> To.
|
||||
// The user specializes `transitions` for their state machine type.
|
||||
|
||||
template <typename From, typename Ev, typename To>
|
||||
struct Transition
|
||||
{
|
||||
using from = From;
|
||||
using event = Ev;
|
||||
using to = To;
|
||||
};
|
||||
|
||||
// ── StateMachine ──────────────────────────────────────────────────────────────
|
||||
//
|
||||
// Template parameters:
|
||||
// States — type list of all states, first element is the initial state
|
||||
// Transitions — type list of Transition<F,E,T> arcs
|
||||
//
|
||||
// Usage:
|
||||
// using MyFSM = StateMachine<
|
||||
// std::tuple<Idle, Running, Done>,
|
||||
// std::tuple<
|
||||
// Transition<Idle, StartEvent, Running>,
|
||||
// Transition<Running, StopEvent, Done>
|
||||
// >
|
||||
// >;
|
||||
|
||||
template <typename StatesTuple, typename TransitionsTuple>
|
||||
class StateMachine;
|
||||
|
||||
namespace Detail
|
||||
{
|
||||
|
||||
// Collect all states from the transitions tuple
|
||||
template <typename... Ts>
|
||||
struct StateVariantOf;
|
||||
|
||||
template <typename... States>
|
||||
struct StateVariantOf<std::tuple<States...>>
|
||||
{
|
||||
using type = std::variant<States...>;
|
||||
};
|
||||
|
||||
// Does the Transition list contain a matching arc?
|
||||
template <typename CurrentState, typename Ev, typename TransTuple>
|
||||
struct FindTransition;
|
||||
|
||||
template <typename CS, typename Ev>
|
||||
struct FindTransition<CS, Ev, std::tuple<>>
|
||||
{
|
||||
using to = void; // no match
|
||||
};
|
||||
|
||||
template <typename CS, typename Ev, typename Head, typename... Tail>
|
||||
struct FindTransition<CS, Ev, std::tuple<Head, Tail...>>
|
||||
{
|
||||
using to = std::conditional_t<
|
||||
std::is_same_v<typename Head::from, CS> &&
|
||||
std::is_same_v<typename Head::event, Ev>,
|
||||
typename Head::to,
|
||||
typename FindTransition<CS, Ev, std::tuple<Tail...>>::to>;
|
||||
};
|
||||
|
||||
} // namespace Detail
|
||||
|
||||
template <typename... States, typename... Transitions>
|
||||
class StateMachine<std::tuple<States...>, std::tuple<Transitions...>>
|
||||
{
|
||||
public:
|
||||
using StateVariant = std::variant<States...>;
|
||||
using TransitionTuple = std::tuple<Transitions...>;
|
||||
|
||||
StateMachine() = default;
|
||||
|
||||
// Current state index (0-based, matches variant index).
|
||||
[[nodiscard]] std::size_t state_index() const noexcept
|
||||
{
|
||||
return state_.index();
|
||||
}
|
||||
|
||||
// True if current state is S.
|
||||
template <typename S>
|
||||
[[nodiscard]] bool is() const noexcept
|
||||
{
|
||||
return std::holds_alternative<S>(state_);
|
||||
}
|
||||
|
||||
// Access current state as S (throws std::bad_variant_access if wrong).
|
||||
template <typename S>
|
||||
[[nodiscard]] const S& as() const
|
||||
{
|
||||
return std::get<S>(state_);
|
||||
}
|
||||
|
||||
template <typename S>
|
||||
[[nodiscard]] S& as()
|
||||
{
|
||||
return std::get<S>(state_);
|
||||
}
|
||||
|
||||
// Try to access state, returns nullptr if wrong state.
|
||||
template <typename S>
|
||||
[[nodiscard]] const S* try_as() const noexcept
|
||||
{
|
||||
return std::get_if<S>(&state_);
|
||||
}
|
||||
|
||||
// Send an event. Returns true if a transition was found and taken.
|
||||
template <typename Ev>
|
||||
bool send(const Ev& ev)
|
||||
{
|
||||
bool transitioned = false;
|
||||
std::visit(
|
||||
[&]<typename CurState>(CurState& cur) {
|
||||
using To =
|
||||
typename Detail::FindTransition<CurState, Ev,
|
||||
TransitionTuple>::to;
|
||||
if constexpr (!std::is_void_v<To>) {
|
||||
on_exit(cur);
|
||||
state_ = To{};
|
||||
on_enter(std::get<To>(state_), ev);
|
||||
transitioned = true;
|
||||
}
|
||||
},
|
||||
state_);
|
||||
return transitioned;
|
||||
}
|
||||
|
||||
// Register a callback fired when entering state S.
|
||||
template <typename S, std::invocable<const S&> F>
|
||||
void on_enter(F&& f)
|
||||
{
|
||||
// Store as type-erased function in a small array indexed by variant alt.
|
||||
entry_callbacks_[variant_index_of<S>()] =
|
||||
[fn = std::forward<F>(f)](const StateVariant& v) {
|
||||
fn(std::get<S>(v));
|
||||
};
|
||||
}
|
||||
|
||||
// Register a callback fired when leaving state S.
|
||||
template <typename S, std::invocable<const S&> F>
|
||||
void on_exit(F&& f)
|
||||
{
|
||||
exit_callbacks_[variant_index_of<S>()] =
|
||||
[fn = std::forward<F>(f)](const StateVariant& v) {
|
||||
fn(std::get<S>(v));
|
||||
};
|
||||
}
|
||||
|
||||
private:
|
||||
template <typename S>
|
||||
static constexpr std::size_t variant_index_of() noexcept
|
||||
{
|
||||
return []<std::size_t... Is>(std::index_sequence<Is...>) {
|
||||
std::size_t idx = 0;
|
||||
((std::is_same_v<S, States> ? (idx = Is, true) : false) || ...);
|
||||
return idx;
|
||||
}(std::index_sequence_for<States...>{});
|
||||
}
|
||||
|
||||
template <typename S>
|
||||
void on_exit(const S& s)
|
||||
{
|
||||
const auto idx = variant_index_of<S>();
|
||||
if (exit_callbacks_[idx]) {
|
||||
StateVariant tmp = s;
|
||||
exit_callbacks_[idx](tmp);
|
||||
}
|
||||
}
|
||||
|
||||
template <typename S, typename Ev>
|
||||
void on_enter(const S& s, const Ev&)
|
||||
{
|
||||
const auto idx = variant_index_of<S>();
|
||||
if (entry_callbacks_[idx]) {
|
||||
StateVariant tmp = s;
|
||||
entry_callbacks_[idx](tmp);
|
||||
}
|
||||
}
|
||||
|
||||
StateVariant state_{std::in_place_index<0>};
|
||||
std::function<void(const StateVariant&)>
|
||||
entry_callbacks_[sizeof...(States)]{};
|
||||
std::function<void(const StateVariant&)>
|
||||
exit_callbacks_[sizeof...(States)]{};
|
||||
};
|
||||
|
||||
} // namespace Void::StateMachine
|
||||
@@ -1,269 +0,0 @@
|
||||
#include <Void/Fsm/Definition.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
|
||||
#include <format>
|
||||
|
||||
namespace Void::Fsm
|
||||
{
|
||||
|
||||
// ── helpers ───────────────────────────────────────────────────────────
|
||||
|
||||
Action wrap_sync(SyncAction fn)
|
||||
{
|
||||
if (!fn) {
|
||||
return {};
|
||||
}
|
||||
return [fn = std::move(fn)](Machine& m,
|
||||
const Event& e) -> Coro::Task<void> {
|
||||
fn(m, e);
|
||||
co_return;
|
||||
};
|
||||
}
|
||||
|
||||
// ── MachineDef ────────────────────────────────────────────────────────
|
||||
|
||||
bool MachineDef::is_ancestor_or_self(StateId ancestor, StateId state) const
|
||||
{
|
||||
StateId cur = state;
|
||||
while (cur != kInvalidState) {
|
||||
if (cur == ancestor) {
|
||||
return true;
|
||||
}
|
||||
cur = m_states[cur].parent;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
StateId MachineDef::lca(StateId a, StateId b) const
|
||||
{
|
||||
// Equalize depths, then climb together.
|
||||
StateId x = a;
|
||||
StateId y = b;
|
||||
while (m_states[x].depth > m_states[y].depth) {
|
||||
x = m_states[x].parent;
|
||||
}
|
||||
while (m_states[y].depth > m_states[x].depth) {
|
||||
y = m_states[y].parent;
|
||||
}
|
||||
while (x != y) {
|
||||
x = m_states[x].parent;
|
||||
y = m_states[y].parent;
|
||||
}
|
||||
return x;
|
||||
}
|
||||
|
||||
// ── Builder ───────────────────────────────────────────────────────────
|
||||
|
||||
Builder::Builder()
|
||||
{
|
||||
// State 0 is the implicit root.
|
||||
MachineDef::StateNode root;
|
||||
root.name = "";
|
||||
root.parent = kInvalidState;
|
||||
root.depth = 0;
|
||||
m_def.m_states.push_back(std::move(root));
|
||||
m_def.m_state_ids.emplace("", kRootState);
|
||||
}
|
||||
|
||||
StateRef Builder::state(std::string_view name, StateRef parent)
|
||||
{
|
||||
if (const auto it = m_def.m_state_ids.find(std::string{name});
|
||||
it != m_def.m_state_ids.end()) {
|
||||
return StateRef{it->second};
|
||||
}
|
||||
const auto id = static_cast<StateId>(m_def.m_states.size());
|
||||
MachineDef::StateNode node;
|
||||
node.name = std::string{name};
|
||||
node.parent = parent.valid() ? parent.id() : kRootState;
|
||||
node.depth = m_def.m_states[node.parent].depth + 1;
|
||||
m_def.m_states.push_back(std::move(node));
|
||||
m_def.m_states[parent.valid() ? parent.id() : kRootState]
|
||||
.children.push_back(id);
|
||||
m_def.m_state_ids.emplace(std::string{name}, id);
|
||||
return StateRef{id};
|
||||
}
|
||||
|
||||
EventId Builder::event(std::string_view name)
|
||||
{
|
||||
if (const auto it = m_def.m_event_ids.find(std::string{name});
|
||||
it != m_def.m_event_ids.end()) {
|
||||
return it->second;
|
||||
}
|
||||
const auto id = static_cast<EventId>(m_def.m_event_names.size());
|
||||
m_def.m_event_names.emplace_back(name);
|
||||
m_def.m_event_ids.emplace(std::string{name}, id);
|
||||
return id;
|
||||
}
|
||||
|
||||
Builder& Builder::initial(StateRef child)
|
||||
{
|
||||
const auto parent = m_def.m_states[child.id()].parent;
|
||||
m_def.m_states[parent].initial = child.id();
|
||||
return *this;
|
||||
}
|
||||
|
||||
Builder& Builder::parallel(StateRef composite)
|
||||
{
|
||||
m_def.m_states[composite.id()].parallel = true;
|
||||
return *this;
|
||||
}
|
||||
|
||||
Builder& Builder::on_entry(StateRef state, Action action)
|
||||
{
|
||||
m_def.m_states[state.id()].entry = std::move(action);
|
||||
return *this;
|
||||
}
|
||||
|
||||
Builder& Builder::on_entry(StateRef state, SyncAction action)
|
||||
{
|
||||
return on_entry(state, wrap_sync(std::move(action)));
|
||||
}
|
||||
|
||||
Builder& Builder::on_exit(StateRef state, Action action)
|
||||
{
|
||||
m_def.m_states[state.id()].exit = std::move(action);
|
||||
return *this;
|
||||
}
|
||||
|
||||
Builder& Builder::on_exit(StateRef state, SyncAction action)
|
||||
{
|
||||
return on_exit(state, wrap_sync(std::move(action)));
|
||||
}
|
||||
|
||||
Builder& Builder::history(StateRef composite, History kind)
|
||||
{
|
||||
m_def.m_states[composite.id()].history = kind;
|
||||
return *this;
|
||||
}
|
||||
|
||||
Builder& Builder::defer(StateRef state, EventId id)
|
||||
{
|
||||
m_def.m_states[state.id()].deferred.push_back(id);
|
||||
return *this;
|
||||
}
|
||||
|
||||
Builder& Builder::timeout(StateRef state,
|
||||
std::chrono::milliseconds after,
|
||||
EventId fires)
|
||||
{
|
||||
m_def.m_states[state.id()].timeout = MachineDef::Timeout{after, fires};
|
||||
return *this;
|
||||
}
|
||||
|
||||
TransitionBuilder Builder::transition(StateRef from, EventId on,
|
||||
StateRef to)
|
||||
{
|
||||
MachineDef::TransitionDef t;
|
||||
t.from = from.id();
|
||||
t.on = on;
|
||||
t.to = to.id();
|
||||
t.internal = false;
|
||||
m_def.m_transitions.push_back(std::move(t));
|
||||
return TransitionBuilder{*this, m_def.m_transitions.size() - 1};
|
||||
}
|
||||
|
||||
TransitionBuilder Builder::internal(StateRef in, EventId on)
|
||||
{
|
||||
MachineDef::TransitionDef t;
|
||||
t.from = in.id();
|
||||
t.on = on;
|
||||
t.to = kInvalidState;
|
||||
t.internal = true;
|
||||
m_def.m_transitions.push_back(std::move(t));
|
||||
return TransitionBuilder{*this, m_def.m_transitions.size() - 1};
|
||||
}
|
||||
|
||||
TransitionBuilder& TransitionBuilder::guard(Guard g)
|
||||
{
|
||||
m_builder->m_def.m_transitions[m_index].guard = std::move(g);
|
||||
return *this;
|
||||
}
|
||||
|
||||
TransitionBuilder& TransitionBuilder::action(Action a)
|
||||
{
|
||||
m_builder->m_def.m_transitions[m_index].action = std::move(a);
|
||||
return *this;
|
||||
}
|
||||
|
||||
TransitionBuilder& TransitionBuilder::action(SyncAction a)
|
||||
{
|
||||
return action(wrap_sync(std::move(a)));
|
||||
}
|
||||
|
||||
std::expected<std::shared_ptr<const MachineDef>, DefError> Builder::build()
|
||||
{
|
||||
if (m_consumed) {
|
||||
return std::unexpected{DefError{"Builder::build() called twice"}};
|
||||
}
|
||||
|
||||
auto& def = m_def;
|
||||
|
||||
// Every composite (state with children) that is entered must know
|
||||
// where to go: an initial child — parallel composites enter all
|
||||
// children instead. Default a single-child composite's initial.
|
||||
for (StateId id = 0; id < def.m_states.size(); ++id) {
|
||||
auto& node = def.m_states[id];
|
||||
if (node.children.empty()) {
|
||||
if (node.parallel) {
|
||||
return std::unexpected{DefError{
|
||||
std::format("parallel state '{}' has no child regions",
|
||||
node.name)}};
|
||||
}
|
||||
if (id == kRootState) {
|
||||
return std::unexpected{DefError{"machine has no states"}};
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (node.parallel) {
|
||||
continue;
|
||||
}
|
||||
if (node.initial == kInvalidState) {
|
||||
if (node.children.size() == 1) {
|
||||
node.initial = node.children.front();
|
||||
} else if (id == kRootState) {
|
||||
// Convention: the first declared top-level state.
|
||||
node.initial = node.children.front();
|
||||
} else {
|
||||
return std::unexpected{DefError{std::format(
|
||||
"composite state '{}' needs initial()", node.name)}};
|
||||
}
|
||||
}
|
||||
if (!def.is_ancestor_or_self(id, node.initial) ||
|
||||
node.initial == id) {
|
||||
return std::unexpected{DefError{std::format(
|
||||
"initial of '{}' is not a descendant", node.name)}};
|
||||
}
|
||||
}
|
||||
|
||||
// Transition sanity.
|
||||
for (const auto& t : def.m_transitions) {
|
||||
if (t.from == kInvalidState || t.from >= def.m_states.size()) {
|
||||
return std::unexpected{
|
||||
DefError{"transition from unknown state"}};
|
||||
}
|
||||
if (!t.internal &&
|
||||
(t.to == kInvalidState || t.to >= def.m_states.size())) {
|
||||
return std::unexpected{DefError{"transition to unknown state"}};
|
||||
}
|
||||
if (t.on == kInvalidEvent || t.on >= def.m_event_names.size()) {
|
||||
return std::unexpected{DefError{"transition on unknown event"}};
|
||||
}
|
||||
}
|
||||
|
||||
// Index transitions by source state, in definition order.
|
||||
def.m_transitions_by_state.assign(def.m_states.size(), {});
|
||||
for (std::size_t i = 0; i < def.m_transitions.size(); ++i) {
|
||||
def.m_transitions_by_state[def.m_transitions[i].from].push_back(i);
|
||||
}
|
||||
|
||||
m_consumed = true;
|
||||
auto out = std::make_shared<MachineDef>(std::move(m_def));
|
||||
Void::Log::debug("Fsm",
|
||||
"built definition: {} states, {} events, "
|
||||
"{} transitions",
|
||||
out->m_states.size(), out->m_event_names.size(),
|
||||
out->m_transitions.size());
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace Void::Fsm
|
||||
@@ -1,946 +0,0 @@
|
||||
#include <Void/Fsm/Machine.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cassert>
|
||||
|
||||
namespace Void::Fsm
|
||||
{
|
||||
|
||||
// ── Envelope ──────────────────────────────────────────────────────────
|
||||
// One queued unit of work. Allocated by producers, freed by the
|
||||
// consumer (or by the destructor for never-processed envelopes).
|
||||
struct Machine::Envelope {
|
||||
enum class Kind : std::uint8_t {
|
||||
Event,
|
||||
Swap,
|
||||
Serialize,
|
||||
StopMarker
|
||||
};
|
||||
|
||||
Kind kind{Kind::Event};
|
||||
Event event{};
|
||||
|
||||
// completion plumbing (all optional)
|
||||
std::optional<SendResult>* result_slot{nullptr};
|
||||
std::coroutine_handle<> continuation{};
|
||||
Async::Executor* resume_on{nullptr};
|
||||
std::binary_semaphore* done{nullptr};
|
||||
|
||||
// control payloads
|
||||
std::shared_ptr<const MachineDef> new_def{};
|
||||
Json::Value* out_json{nullptr};
|
||||
|
||||
void complete(SendResult result)
|
||||
{
|
||||
if (result_slot != nullptr) {
|
||||
*result_slot = result;
|
||||
}
|
||||
if (done != nullptr) {
|
||||
done->release();
|
||||
}
|
||||
if (continuation) {
|
||||
auto h = continuation;
|
||||
continuation = {};
|
||||
if (resume_on != nullptr) {
|
||||
resume_on->post(h);
|
||||
} else {
|
||||
h.resume();
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// ── construction / lifecycle ──────────────────────────────────────────
|
||||
|
||||
Machine::Machine(std::shared_ptr<const MachineDef> def, Options options)
|
||||
: m_def(std::move(def)), m_options(options)
|
||||
{
|
||||
}
|
||||
|
||||
Machine::~Machine()
|
||||
{
|
||||
stop();
|
||||
// Free anything still queued (posted before stop or never run).
|
||||
while (auto env = m_queue.try_pop()) {
|
||||
(*env)->complete(SendResult::Dropped);
|
||||
delete *env;
|
||||
}
|
||||
for (auto* env : m_deferred) {
|
||||
delete env;
|
||||
}
|
||||
m_deferred.clear();
|
||||
}
|
||||
|
||||
void Machine::start()
|
||||
{
|
||||
if (m_accepting.load(std::memory_order_acquire)) {
|
||||
return;
|
||||
}
|
||||
m_stop.store(false, std::memory_order_release);
|
||||
m_accepting.store(true, std::memory_order_release);
|
||||
|
||||
if (m_options.own_worker) {
|
||||
// start() returns only once the initial configuration is
|
||||
// entered (entry actions included) — observers immediately
|
||||
// see a coherent snapshot.
|
||||
std::binary_semaphore ready{0};
|
||||
m_worker = std::thread([this, &ready] {
|
||||
enter_initial_configuration();
|
||||
ready.release();
|
||||
consumer_loop();
|
||||
});
|
||||
ready.acquire();
|
||||
} else {
|
||||
enter_initial_configuration();
|
||||
}
|
||||
}
|
||||
|
||||
void Machine::stop()
|
||||
{
|
||||
if (!m_accepting.exchange(false, std::memory_order_acq_rel)) {
|
||||
// Never started or already stopped; still join a worker that
|
||||
// may be winding down.
|
||||
if (m_worker.joinable()) {
|
||||
m_worker.join();
|
||||
}
|
||||
return;
|
||||
}
|
||||
m_stop.store(true, std::memory_order_release);
|
||||
wake_consumer();
|
||||
if (m_worker.joinable()) {
|
||||
m_worker.join();
|
||||
} else {
|
||||
// Embedder-driven: process the backlog on this (consumer)
|
||||
// thread before declaring the machine stopped.
|
||||
drain_once();
|
||||
}
|
||||
StateSnapshot snap = m_snapshot;
|
||||
snap.running = false;
|
||||
m_seq.fetch_add(1, std::memory_order_acq_rel);
|
||||
m_snapshot = snap;
|
||||
m_seq.fetch_add(1, std::memory_order_release);
|
||||
}
|
||||
|
||||
bool Machine::running() const noexcept { return current().running; }
|
||||
|
||||
// ── submission ────────────────────────────────────────────────────────
|
||||
|
||||
bool Machine::post(Event event)
|
||||
{
|
||||
if (!m_accepting.load(std::memory_order_acquire)) {
|
||||
return false;
|
||||
}
|
||||
auto* env = new Envelope{};
|
||||
env->event = std::move(event);
|
||||
m_queue.push(env);
|
||||
wake_consumer();
|
||||
return true;
|
||||
}
|
||||
|
||||
void Machine::SendAwaitable::await_suspend(std::coroutine_handle<> h)
|
||||
{
|
||||
if (!m_machine->m_accepting.load(std::memory_order_acquire)) {
|
||||
m_result = SendResult::Dropped;
|
||||
h.resume();
|
||||
return;
|
||||
}
|
||||
auto* env = new Envelope{};
|
||||
env->event = std::move(m_event);
|
||||
env->result_slot = &m_result;
|
||||
env->continuation = h;
|
||||
env->resume_on = m_resume_on;
|
||||
m_machine->m_queue.push(env);
|
||||
m_machine->wake_consumer();
|
||||
}
|
||||
|
||||
SendResult Machine::send_wait(Event event)
|
||||
{
|
||||
if (!m_accepting.load(std::memory_order_acquire)) {
|
||||
return SendResult::Dropped;
|
||||
}
|
||||
std::optional<SendResult> result;
|
||||
std::binary_semaphore done{0};
|
||||
auto* env = new Envelope{};
|
||||
env->event = std::move(event);
|
||||
env->result_slot = &result;
|
||||
env->done = &done;
|
||||
m_queue.push(env);
|
||||
wake_consumer();
|
||||
done.acquire();
|
||||
return result.value_or(SendResult::Dropped);
|
||||
}
|
||||
|
||||
// ── observation ───────────────────────────────────────────────────────
|
||||
|
||||
StateSnapshot Machine::current() const noexcept
|
||||
{
|
||||
// Seqlock read: retry while a write is in flight or raced us.
|
||||
for (;;) {
|
||||
const auto before = m_seq.load(std::memory_order_acquire);
|
||||
if ((before & 1U) != 0U) {
|
||||
continue;
|
||||
}
|
||||
StateSnapshot snap = m_snapshot;
|
||||
std::atomic_thread_fence(std::memory_order_acquire);
|
||||
if (m_seq.load(std::memory_order_relaxed) == before) {
|
||||
return snap;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool Machine::is_in(StateId state) const
|
||||
{
|
||||
const auto snap = current();
|
||||
if (snap.contains(state)) {
|
||||
return true;
|
||||
}
|
||||
const auto def = definition();
|
||||
for (std::uint32_t i = 0; i < snap.leaf_count; ++i) {
|
||||
if (def->is_ancestor_or_self(state, snap.leaves[i])) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool Machine::is_in(std::string_view state) const
|
||||
{
|
||||
const auto def = definition();
|
||||
const auto id = def->state_id(state);
|
||||
return id.has_value() && is_in(*id);
|
||||
}
|
||||
|
||||
// ── hot swap / persistence ────────────────────────────────────────────
|
||||
|
||||
void Machine::swap_definition(std::shared_ptr<const MachineDef> def)
|
||||
{
|
||||
if (!m_accepting.load(std::memory_order_acquire)) {
|
||||
// Not running: take effect immediately for the next start().
|
||||
m_def.store(std::move(def), std::memory_order_release);
|
||||
return;
|
||||
}
|
||||
auto* env = new Envelope{};
|
||||
env->kind = Envelope::Kind::Swap;
|
||||
env->new_def = std::move(def);
|
||||
m_queue.push(env);
|
||||
wake_consumer();
|
||||
}
|
||||
|
||||
Json::Value Machine::serialize_state()
|
||||
{
|
||||
if (!m_accepting.load(std::memory_order_acquire) ||
|
||||
!m_options.own_worker) {
|
||||
// Quiescent machine, or embedder-driven: the caller is (or
|
||||
// stands in for) the consumer — read directly. Queueing here
|
||||
// would deadlock with nobody to drain.
|
||||
Json::Value out;
|
||||
Envelope env;
|
||||
env.kind = Envelope::Kind::Serialize;
|
||||
env.out_json = &out;
|
||||
(void)handle_envelope(env);
|
||||
return out;
|
||||
}
|
||||
Json::Value out;
|
||||
std::binary_semaphore done{0};
|
||||
auto* env = new Envelope{};
|
||||
env->kind = Envelope::Kind::Serialize;
|
||||
env->out_json = &out;
|
||||
env->done = &done;
|
||||
m_queue.push(env);
|
||||
wake_consumer();
|
||||
done.acquire();
|
||||
return out;
|
||||
}
|
||||
|
||||
std::expected<void, FsmError>
|
||||
Machine::restore_state(const Json::Value& state)
|
||||
{
|
||||
if (m_accepting.load(std::memory_order_acquire)) {
|
||||
return std::unexpected{
|
||||
FsmError{"restore_state requires a stopped machine"}};
|
||||
}
|
||||
if (!state.is_object() || state.find("leaves") == nullptr) {
|
||||
return std::unexpected{FsmError{"malformed machine state json"}};
|
||||
}
|
||||
m_pending_restore = state;
|
||||
return {};
|
||||
}
|
||||
|
||||
// ── consumer internals ────────────────────────────────────────────────
|
||||
|
||||
void Machine::wake_consumer() noexcept
|
||||
{
|
||||
if (m_sleeping.exchange(false, std::memory_order_acq_rel)) {
|
||||
m_wakeup.release();
|
||||
}
|
||||
}
|
||||
|
||||
void Machine::consumer_loop()
|
||||
{
|
||||
for (;;) {
|
||||
drain_once();
|
||||
|
||||
if (m_stop.load(std::memory_order_acquire) && m_queue.empty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
m_sleeping.store(true, std::memory_order_release);
|
||||
if (!m_queue.empty() || m_stop.load(std::memory_order_acquire)) {
|
||||
m_sleeping.store(false, std::memory_order_release);
|
||||
continue;
|
||||
}
|
||||
if (const auto deadline = next_deadline(); deadline.has_value()) {
|
||||
(void)m_wakeup.try_acquire_until(*deadline);
|
||||
} else {
|
||||
m_wakeup.acquire();
|
||||
}
|
||||
m_sleeping.store(false, std::memory_order_release);
|
||||
}
|
||||
}
|
||||
|
||||
std::size_t Machine::run_pending() { return drain_once(); }
|
||||
|
||||
void Machine::run_until(const std::function<bool()>& until)
|
||||
{
|
||||
while (!until()) {
|
||||
if (drain_once() == 0) {
|
||||
fire_due_timers();
|
||||
std::this_thread::yield();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::size_t Machine::drain_once()
|
||||
{
|
||||
std::size_t handled = 0;
|
||||
fire_due_timers();
|
||||
if (m_deferred_dirty) {
|
||||
reinject_deferred();
|
||||
}
|
||||
while (auto env = m_queue.try_pop()) {
|
||||
if (handle_envelope(**env)) {
|
||||
delete *env;
|
||||
}
|
||||
++handled;
|
||||
fire_due_timers();
|
||||
if (m_deferred_dirty) {
|
||||
reinject_deferred();
|
||||
}
|
||||
}
|
||||
return handled;
|
||||
}
|
||||
|
||||
// Returns true if the envelope should be freed by the caller (false:
|
||||
// ownership moved to the deferred stash).
|
||||
bool Machine::handle_envelope(Envelope& env)
|
||||
{
|
||||
switch (env.kind) {
|
||||
case Envelope::Kind::Swap:
|
||||
apply_swap(std::move(env.new_def));
|
||||
return true;
|
||||
|
||||
case Envelope::Kind::Serialize:
|
||||
{
|
||||
auto obj = Json::object();
|
||||
auto& o = obj.as_object();
|
||||
o.emplace_back("__fsm", Json::Value{1});
|
||||
auto leaves = Json::array();
|
||||
for (const auto& name : active_leaf_names()) {
|
||||
leaves.as_array().emplace_back(name);
|
||||
}
|
||||
o.emplace_back("leaves", std::move(leaves));
|
||||
auto hist = Json::object();
|
||||
if (m_active_def) {
|
||||
for (const auto& [state, record] : m_history) {
|
||||
auto arr = Json::array();
|
||||
for (const auto leaf : record.leaves) {
|
||||
arr.as_array().emplace_back(
|
||||
m_active_def->state(leaf).name);
|
||||
}
|
||||
hist.as_object().emplace_back(
|
||||
m_active_def->state(state).name,
|
||||
std::move(arr));
|
||||
}
|
||||
}
|
||||
o.emplace_back("history", std::move(hist));
|
||||
o.emplace_back("step",
|
||||
Json::Value{static_cast<double>(m_step)});
|
||||
if (env.out_json != nullptr) {
|
||||
*env.out_json = std::move(obj);
|
||||
}
|
||||
env.complete(SendResult::Handled);
|
||||
return true;
|
||||
}
|
||||
|
||||
case Envelope::Kind::StopMarker:
|
||||
return true;
|
||||
|
||||
case Envelope::Kind::Event:
|
||||
break;
|
||||
}
|
||||
|
||||
const auto result = dispatch_event(env.event);
|
||||
env.complete(result);
|
||||
if (result == SendResult::Deferred) {
|
||||
m_deferred.push_back(&env);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
SendResult Machine::dispatch_event(const Event& event)
|
||||
{
|
||||
const auto& def = *m_active_def;
|
||||
bool handled = false;
|
||||
bool deferrable = false;
|
||||
|
||||
// Copy: transitions mutate m_leaves while we iterate regions.
|
||||
const auto leaves = m_leaves;
|
||||
for (const StateId leaf : leaves) {
|
||||
if (leaf >= m_active.size() || !m_active[leaf]) {
|
||||
continue; // region was exited by an earlier transition
|
||||
}
|
||||
|
||||
const MachineDef::TransitionDef* chosen = nullptr;
|
||||
for (StateId cur = leaf; cur != kInvalidState && chosen == nullptr;
|
||||
cur = def.state(cur).parent) {
|
||||
for (const auto index : def.transitions_from(cur)) {
|
||||
const auto& t = def.transition(index);
|
||||
if (t.on != event.id) {
|
||||
continue;
|
||||
}
|
||||
if (t.guard && !t.guard(*this, event)) {
|
||||
continue;
|
||||
}
|
||||
chosen = &t;
|
||||
break;
|
||||
}
|
||||
if (chosen == nullptr) {
|
||||
const auto& node = def.state(cur);
|
||||
if (std::find(node.deferred.begin(),
|
||||
node.deferred.end(),
|
||||
event.id) != node.deferred.end()) {
|
||||
deferrable = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (chosen != nullptr) {
|
||||
perform_transition(*chosen, leaf, event);
|
||||
handled = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (handled) {
|
||||
++m_step;
|
||||
m_deferred_dirty = true;
|
||||
publish_snapshot();
|
||||
return SendResult::Handled;
|
||||
}
|
||||
if (deferrable) {
|
||||
return SendResult::Deferred;
|
||||
}
|
||||
return SendResult::Unhandled;
|
||||
}
|
||||
|
||||
void Machine::perform_transition(const MachineDef::TransitionDef& t,
|
||||
StateId /*source_leaf*/,
|
||||
const Event& event)
|
||||
{
|
||||
const auto& def = *m_active_def;
|
||||
|
||||
if (t.internal) {
|
||||
run_action(t.action, event);
|
||||
return;
|
||||
}
|
||||
|
||||
StateId boundary = def.lca(t.from, t.to);
|
||||
if (boundary == t.from || boundary == t.to) {
|
||||
// Self-transitions and ancestor/descendant targets exit (at
|
||||
// least) the `from`/`to` state itself.
|
||||
boundary = def.state(boundary).parent;
|
||||
if (boundary == kInvalidState) {
|
||||
boundary = kRootState;
|
||||
}
|
||||
}
|
||||
|
||||
// The child of `boundary` containing the transition source: the
|
||||
// whole active subtree under it exits.
|
||||
StateId branch = t.from;
|
||||
while (def.state(branch).parent != boundary) {
|
||||
branch = def.state(branch).parent;
|
||||
}
|
||||
|
||||
// Snapshot history for every composite about to be exited — the
|
||||
// record must reflect the configuration at the moment of exit,
|
||||
// not accumulate across earlier transitions.
|
||||
for (StateId s = 0; s < m_active.size(); ++s) {
|
||||
if (!m_active[s] || !def.is_ancestor_or_self(branch, s)) {
|
||||
continue;
|
||||
}
|
||||
const auto& node = def.state(s);
|
||||
if (node.history == History::None) {
|
||||
continue;
|
||||
}
|
||||
HistoryRecord record;
|
||||
if (node.history == History::Shallow) {
|
||||
for (const auto child : node.children) {
|
||||
if (m_active[child]) {
|
||||
record.leaves.push_back(child);
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else { // Deep
|
||||
for (const auto leaf : m_leaves) {
|
||||
if (m_active[leaf] && def.is_ancestor_or_self(s, leaf)) {
|
||||
record.leaves.push_back(leaf);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!record.leaves.empty()) {
|
||||
m_history[s] = std::move(record);
|
||||
}
|
||||
}
|
||||
|
||||
// Exit phase — innermost first, per active leaf chain.
|
||||
const auto leaves = m_leaves;
|
||||
for (const StateId leaf : leaves) {
|
||||
if (leaf >= m_active.size() || !m_active[leaf]) {
|
||||
continue;
|
||||
}
|
||||
if (!def.is_ancestor_or_self(branch, leaf)) {
|
||||
continue;
|
||||
}
|
||||
exit_to_lca(leaf, boundary, event);
|
||||
}
|
||||
|
||||
run_action(t.action, event);
|
||||
enter_target(boundary, t.to, event);
|
||||
}
|
||||
|
||||
void Machine::exit_to_lca(StateId leaf, StateId lca, const Event& event)
|
||||
{
|
||||
for (StateId cur = leaf; cur != lca && cur != kInvalidState;
|
||||
cur = m_active_def->state(cur).parent) {
|
||||
if (m_active[cur]) {
|
||||
exit_single(cur, event);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void Machine::exit_single(StateId state, const Event& event)
|
||||
{
|
||||
const auto& node = m_active_def->state(state);
|
||||
run_action(node.exit, event);
|
||||
m_active[state] = false;
|
||||
++m_activation[state]; // invalidates armed timers
|
||||
std::erase(m_leaves, state);
|
||||
}
|
||||
|
||||
void Machine::enter_target(StateId lca, StateId target, const Event& event)
|
||||
{
|
||||
const auto& def = *m_active_def;
|
||||
// Path lca(exclusive) → target, outermost first.
|
||||
std::vector<StateId> path;
|
||||
for (StateId cur = target; cur != lca && cur != kInvalidState;
|
||||
cur = def.state(cur).parent) {
|
||||
path.push_back(cur);
|
||||
}
|
||||
for (auto it = path.rbegin(); it != path.rend(); ++it) {
|
||||
if (!m_active[*it]) {
|
||||
enter_single(*it, event);
|
||||
}
|
||||
}
|
||||
descend_into(target, event);
|
||||
}
|
||||
|
||||
void Machine::descend_into(StateId state, const Event& event)
|
||||
{
|
||||
const auto& def = *m_active_def;
|
||||
const auto& node = def.state(state);
|
||||
|
||||
if (node.children.empty()) {
|
||||
if (std::find(m_leaves.begin(), m_leaves.end(), state) ==
|
||||
m_leaves.end()) {
|
||||
m_leaves.push_back(state);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (node.parallel) {
|
||||
for (const auto child : node.children) {
|
||||
enter_single(child, event);
|
||||
descend_into(child, event);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (node.history != History::None) {
|
||||
if (const auto it = m_history.find(state);
|
||||
it != m_history.end() && !it->second.leaves.empty()) {
|
||||
// Keep the record — UML history persists; the next exit
|
||||
// of this composite overwrites it anyway.
|
||||
const auto record = it->second;
|
||||
if (node.history == History::Shallow) {
|
||||
const auto child = record.leaves.front();
|
||||
enter_single(child, event);
|
||||
descend_into(child, event);
|
||||
} else { // Deep: re-activate each recorded leaf chain
|
||||
for (const auto leaf : record.leaves) {
|
||||
std::vector<StateId> path;
|
||||
for (StateId cur = leaf;
|
||||
cur != state && cur != kInvalidState;
|
||||
cur = def.state(cur).parent) {
|
||||
path.push_back(cur);
|
||||
}
|
||||
for (auto it2 = path.rbegin(); it2 != path.rend();
|
||||
++it2) {
|
||||
if (!m_active[*it2]) {
|
||||
enter_single(*it2, event);
|
||||
}
|
||||
}
|
||||
if (std::find(m_leaves.begin(), m_leaves.end(), leaf) ==
|
||||
m_leaves.end()) {
|
||||
m_leaves.push_back(leaf);
|
||||
}
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const auto child = node.initial;
|
||||
enter_single(child, event);
|
||||
descend_into(child, event);
|
||||
}
|
||||
|
||||
void Machine::enter_single(StateId state, const Event& event)
|
||||
{
|
||||
const auto& node = m_active_def->state(state);
|
||||
m_active[state] = true;
|
||||
++m_activation[state];
|
||||
if (node.timeout.has_value()) {
|
||||
m_timers.push_back(TimerArm{
|
||||
state, std::chrono::steady_clock::now() + node.timeout->after,
|
||||
node.timeout->fires, m_activation[state]});
|
||||
}
|
||||
run_action(node.entry, event);
|
||||
}
|
||||
|
||||
void Machine::run_action(const Action& action, const Event& event)
|
||||
{
|
||||
if (!action) {
|
||||
return;
|
||||
}
|
||||
// Drive the coroutine to completion on this consumer thread; the
|
||||
// run-to-completion step does not finish until the action does.
|
||||
// External resumptions arrive through m_executor.post (thread-
|
||||
// safe), so awaiting cross-thread work cannot deadlock — it just
|
||||
// stalls this machine (inherent to RTC semantics).
|
||||
bool finished = false;
|
||||
Async::spawn(m_executor,
|
||||
[](const Action& a, Machine& m, const Event& e,
|
||||
bool& done) -> Coro::Task<void> {
|
||||
co_await a(m, e);
|
||||
done = true;
|
||||
}(action, *this, event, finished));
|
||||
while (!finished) {
|
||||
if (!m_executor.run_one()) {
|
||||
std::this_thread::yield();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void Machine::enter_initial_configuration()
|
||||
{
|
||||
m_active_def = m_def.load(std::memory_order_acquire);
|
||||
m_active.assign(m_active_def->state_count(), false);
|
||||
m_activation.assign(m_active_def->state_count(), 0);
|
||||
m_leaves.clear();
|
||||
m_timers.clear();
|
||||
m_history.clear();
|
||||
m_active[kRootState] = true;
|
||||
|
||||
if (m_pending_restore.has_value()) {
|
||||
const auto& def = *m_active_def;
|
||||
const auto& state = *m_pending_restore;
|
||||
|
||||
// History first (so future re-entries see it).
|
||||
if (const auto* hist = state.find("history");
|
||||
hist != nullptr && hist->is_object()) {
|
||||
for (const auto& [name, arr] : hist->as_object()) {
|
||||
const auto id = def.state_id(name);
|
||||
if (!id.has_value() || !arr.is_array()) {
|
||||
continue;
|
||||
}
|
||||
HistoryRecord record;
|
||||
for (const auto& leaf_name : arr.as_array()) {
|
||||
if (const auto leaf =
|
||||
def.state_id(leaf_name.as_string());
|
||||
leaf.has_value()) {
|
||||
record.leaves.push_back(*leaf);
|
||||
}
|
||||
}
|
||||
if (!record.leaves.empty()) {
|
||||
m_history.emplace(*id, std::move(record));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Activate recorded leaf chains silently (no entry actions —
|
||||
// the configuration is being *restored*, not entered).
|
||||
bool any = false;
|
||||
if (const auto* leaves = state.find("leaves");
|
||||
leaves != nullptr && leaves->is_array()) {
|
||||
for (const auto& leaf_name : leaves->as_array()) {
|
||||
const auto id = def.state_id(leaf_name.as_string());
|
||||
if (!id.has_value()) {
|
||||
Void::Log::warn("Fsm",
|
||||
"restore: unknown state '{}' skipped",
|
||||
leaf_name.as_string());
|
||||
continue;
|
||||
}
|
||||
for (StateId cur = *id; cur != kInvalidState;
|
||||
cur = def.state(cur).parent) {
|
||||
m_active[cur] = true;
|
||||
}
|
||||
m_leaves.push_back(*id);
|
||||
any = true;
|
||||
}
|
||||
}
|
||||
m_pending_restore.reset();
|
||||
if (any) {
|
||||
// Arm timers for restored states.
|
||||
for (const auto leaf : m_leaves) {
|
||||
for (StateId cur = leaf; cur != kInvalidState;
|
||||
cur = def.state(cur).parent) {
|
||||
const auto& node = def.state(cur);
|
||||
if (node.timeout.has_value()) {
|
||||
++m_activation[cur];
|
||||
m_timers.push_back(TimerArm{
|
||||
cur,
|
||||
std::chrono::steady_clock::now() +
|
||||
node.timeout->after,
|
||||
node.timeout->fires, m_activation[cur]});
|
||||
}
|
||||
}
|
||||
}
|
||||
publish_snapshot();
|
||||
return;
|
||||
}
|
||||
Void::Log::warn("Fsm", "restore matched no states; entering "
|
||||
"initial configuration");
|
||||
}
|
||||
|
||||
descend_into(kRootState, Event{});
|
||||
++m_step;
|
||||
publish_snapshot();
|
||||
}
|
||||
|
||||
void Machine::publish_snapshot()
|
||||
{
|
||||
StateSnapshot snap;
|
||||
snap.leaf_count = 0;
|
||||
for (const auto leaf : m_leaves) {
|
||||
if (snap.leaf_count < StateSnapshot::kMaxLeaves) {
|
||||
snap.leaves[snap.leaf_count++] = leaf;
|
||||
}
|
||||
}
|
||||
snap.step = m_step;
|
||||
snap.running = m_accepting.load(std::memory_order_acquire);
|
||||
|
||||
m_seq.fetch_add(1, std::memory_order_acq_rel); // odd: write begins
|
||||
m_snapshot = snap;
|
||||
m_seq.fetch_add(1, std::memory_order_release); // even: write ends
|
||||
}
|
||||
|
||||
void Machine::rearm_timers()
|
||||
{
|
||||
// Prune stale arms (state exited or re-activated since).
|
||||
std::erase_if(m_timers, [this](const TimerArm& arm) {
|
||||
return arm.state >= m_active.size() || !m_active[arm.state] ||
|
||||
m_activation[arm.state] != arm.generation;
|
||||
});
|
||||
}
|
||||
|
||||
void Machine::fire_due_timers()
|
||||
{
|
||||
if (m_timers.empty() || !m_active_def) {
|
||||
return;
|
||||
}
|
||||
const auto now = std::chrono::steady_clock::now();
|
||||
// Collect due, valid arms first — dispatch mutates m_timers.
|
||||
std::vector<EventId> due;
|
||||
std::erase_if(m_timers, [&](const TimerArm& arm) {
|
||||
const bool stale = arm.state >= m_active.size() ||
|
||||
!m_active[arm.state] ||
|
||||
m_activation[arm.state] != arm.generation;
|
||||
if (stale) {
|
||||
return true;
|
||||
}
|
||||
if (arm.deadline <= now) {
|
||||
due.push_back(arm.fires);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
for (const auto id : due) {
|
||||
(void)dispatch_event(Event{id, {}});
|
||||
}
|
||||
}
|
||||
|
||||
std::optional<std::chrono::steady_clock::time_point>
|
||||
Machine::next_deadline() const
|
||||
{
|
||||
std::optional<std::chrono::steady_clock::time_point> next;
|
||||
for (const auto& arm : m_timers) {
|
||||
if (arm.state < m_active.size() && m_active[arm.state] &&
|
||||
m_activation[arm.state] == arm.generation) {
|
||||
if (!next.has_value() || arm.deadline < *next) {
|
||||
next = arm.deadline;
|
||||
}
|
||||
}
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
void Machine::reinject_deferred()
|
||||
{
|
||||
m_deferred_dirty = false;
|
||||
if (m_deferred.empty()) {
|
||||
return;
|
||||
}
|
||||
// Completion already ran when the event was first deferred; these
|
||||
// envelopes only carry the event now. Process in FIFO order ahead
|
||||
// of the queue; still-deferred ones go back to the stash.
|
||||
auto pending = std::move(m_deferred);
|
||||
m_deferred.clear();
|
||||
for (auto* env : pending) {
|
||||
const auto result = dispatch_event(env->event);
|
||||
if (result == SendResult::Deferred) {
|
||||
m_deferred.push_back(env);
|
||||
} else {
|
||||
delete env;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<std::string> Machine::active_leaf_names() const
|
||||
{
|
||||
std::vector<std::string> names;
|
||||
if (!m_active_def) {
|
||||
return names;
|
||||
}
|
||||
names.reserve(m_leaves.size());
|
||||
for (const auto leaf : m_leaves) {
|
||||
names.push_back(m_active_def->state(leaf).name);
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
void Machine::apply_swap(std::shared_ptr<const MachineDef> next)
|
||||
{
|
||||
if (!next) {
|
||||
return;
|
||||
}
|
||||
const auto old_def = m_active_def;
|
||||
const auto old_leaves = active_leaf_names();
|
||||
|
||||
// Remap history records by name before switching defs.
|
||||
std::vector<std::pair<std::string, std::vector<std::string>>>
|
||||
old_history;
|
||||
if (old_def) {
|
||||
for (const auto& [state, record] : m_history) {
|
||||
std::vector<std::string> leaves;
|
||||
for (const auto leaf : record.leaves) {
|
||||
leaves.push_back(old_def->state(leaf).name);
|
||||
}
|
||||
old_history.emplace_back(old_def->state(state).name,
|
||||
std::move(leaves));
|
||||
}
|
||||
}
|
||||
|
||||
m_def.store(next, std::memory_order_release);
|
||||
m_active_def = std::move(next);
|
||||
m_active.assign(m_active_def->state_count(), false);
|
||||
m_activation.assign(m_active_def->state_count(), 0);
|
||||
m_leaves.clear();
|
||||
m_timers.clear();
|
||||
m_history.clear();
|
||||
m_active[kRootState] = true;
|
||||
|
||||
for (const auto& [name, leaves] : old_history) {
|
||||
const auto id = m_active_def->state_id(name);
|
||||
if (!id.has_value()) {
|
||||
continue;
|
||||
}
|
||||
HistoryRecord record;
|
||||
for (const auto& leaf_name : leaves) {
|
||||
if (const auto leaf = m_active_def->state_id(leaf_name);
|
||||
leaf.has_value()) {
|
||||
record.leaves.push_back(*leaf);
|
||||
}
|
||||
}
|
||||
if (!record.leaves.empty()) {
|
||||
m_history.emplace(*id, std::move(record));
|
||||
}
|
||||
}
|
||||
|
||||
bool all_mapped = !old_leaves.empty();
|
||||
for (const auto& name : old_leaves) {
|
||||
const auto id = m_active_def->state_id(name);
|
||||
if (!id.has_value()) {
|
||||
all_mapped = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (all_mapped) {
|
||||
// Seamless adoption: same state names — activate the mapped
|
||||
// chains without re-running entry actions.
|
||||
const auto& def = *m_active_def;
|
||||
for (const auto& name : old_leaves) {
|
||||
const auto id = *def.state_id(name);
|
||||
for (StateId cur = id; cur != kInvalidState;
|
||||
cur = def.state(cur).parent) {
|
||||
m_active[cur] = true;
|
||||
}
|
||||
// The state may have grown children in the new def.
|
||||
if (def.state(id).children.empty()) {
|
||||
m_leaves.push_back(id);
|
||||
} else {
|
||||
descend_into(id, Event{});
|
||||
}
|
||||
// Re-arm timers along the chain.
|
||||
for (StateId cur = id; cur != kInvalidState;
|
||||
cur = def.state(cur).parent) {
|
||||
const auto& node = def.state(cur);
|
||||
if (node.timeout.has_value() && m_active[cur] &&
|
||||
m_activation[cur] == 0) {
|
||||
++m_activation[cur];
|
||||
m_timers.push_back(
|
||||
TimerArm{cur,
|
||||
std::chrono::steady_clock::now() +
|
||||
node.timeout->after,
|
||||
node.timeout->fires, m_activation[cur]});
|
||||
}
|
||||
}
|
||||
}
|
||||
Void::Log::info("Fsm",
|
||||
"definition swapped seamlessly "
|
||||
"({} active leaves kept)",
|
||||
m_leaves.size());
|
||||
} else {
|
||||
Void::Log::warn("Fsm", "definition swap changed the active "
|
||||
"state set; entering initial "
|
||||
"configuration");
|
||||
descend_into(kRootState, Event{});
|
||||
}
|
||||
|
||||
++m_step;
|
||||
m_deferred_dirty = true; // new def may consume stashed events
|
||||
publish_snapshot();
|
||||
}
|
||||
|
||||
} // namespace Void::Fsm
|
||||
@@ -1,3 +0,0 @@
|
||||
void_add_module(Fsm
|
||||
INTERNAL_DEPS Functional Data
|
||||
)
|
||||
@@ -1 +0,0 @@
|
||||
void_add_module(StateMachine)
|
||||
@@ -116,22 +116,4 @@ if(TARGET Void::Plugin)
|
||||
target_include_directories(VoidTests PRIVATE
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/plugins")
|
||||
add_dependencies(VoidTests VoidStatefulPluginV1 VoidStatefulPluginV2)
|
||||
|
||||
# FSM behaviour plugins (states/actions provided by a plugin) for the
|
||||
# FSM x Plugin hot-reload integration test. Same state names across
|
||||
# versions so swap_definition adopts the live configuration.
|
||||
if(TARGET Void::Fsm)
|
||||
add_library(VoidFsmPluginV1 SHARED
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/plugins/FsmPluginV1.cpp")
|
||||
add_library(VoidFsmPluginV2 SHARED
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/plugins/FsmPluginV2.cpp")
|
||||
foreach(_fp VoidFsmPluginV1 VoidFsmPluginV2)
|
||||
target_link_libraries(${_fp} PRIVATE Void::Plugin Void::Fsm)
|
||||
endforeach()
|
||||
target_compile_definitions(VoidTests PRIVATE
|
||||
"VOID_FSM_PLUGIN_V1_PATH=\"$<TARGET_FILE:VoidFsmPluginV1>\""
|
||||
"VOID_FSM_PLUGIN_V2_PATH=\"$<TARGET_FILE:VoidFsmPluginV2>\""
|
||||
)
|
||||
add_dependencies(VoidTests VoidFsmPluginV1 VoidFsmPluginV2)
|
||||
endif()
|
||||
endif()
|
||||
@@ -1,158 +0,0 @@
|
||||
#include <Void/Fsm/Machine.hpp>
|
||||
#include <Void/Fsm/PluginBehavior.hpp>
|
||||
#include <Void/Plugin/Manager.hpp>
|
||||
#include <Void/System/TempDir.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <filesystem>
|
||||
#include <memory>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
#if defined(VOID_FSM_PLUGIN_V1_PATH) && defined(VOID_FSM_PLUGIN_V2_PATH) && \
|
||||
__has_include(<dlfcn.h>)
|
||||
|
||||
using namespace Void::Fsm;
|
||||
using Void::Plugin::PluginManager;
|
||||
|
||||
namespace
|
||||
{
|
||||
void install(const std::filesystem::path& src,
|
||||
const std::filesystem::path& dst)
|
||||
{
|
||||
auto staging = dst;
|
||||
staging += ".incoming";
|
||||
std::filesystem::copy_file(
|
||||
src, staging, std::filesystem::copy_options::overwrite_existing);
|
||||
std::filesystem::rename(staging, dst);
|
||||
}
|
||||
|
||||
// Build a machine definition from the plugin's behaviour pack.
|
||||
std::shared_ptr<const MachineDef> def_from(const PluginManager& mgr)
|
||||
{
|
||||
auto* sym = reinterpret_cast<fsm_behaviors_fn>(
|
||||
mgr.raw_symbol("FsmPlugin", kFsmBehaviorsSymbol));
|
||||
Void::Testing::expect(sym != nullptr);
|
||||
if (sym == nullptr) {
|
||||
return nullptr;
|
||||
}
|
||||
auto built = build_machine_def(*sym());
|
||||
Void::Testing::expect(built.has_value());
|
||||
return built.value_or(nullptr);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
// A machine whose states and actions come entirely from a plugin keeps
|
||||
// running across a plugin reload: the new definition is built from the
|
||||
// reloaded behaviour pack and swapped in between run-to-completion steps.
|
||||
Void::Testing::Test internal_fsm_plugin_definition_swap()
|
||||
{
|
||||
Void::FileSystem::TempDir tmp{"void_fsmplugin"};
|
||||
const auto so = tmp.path() / "fsm.so";
|
||||
std::filesystem::copy_file(VOID_FSM_PLUGIN_V1_PATH, so);
|
||||
|
||||
PluginManager mgr;
|
||||
Void::Testing::expect(mgr.load(so).has_value());
|
||||
|
||||
auto def = def_from(mgr);
|
||||
Void::Testing::expect(def != nullptr);
|
||||
|
||||
Machine machine{def, MachineOptions{.own_worker = false}};
|
||||
machine.start();
|
||||
machine.post(Event{*def->event_id("start"), {}});
|
||||
machine.run_pending();
|
||||
Void::Testing::expect(machine.is_in("busy"));
|
||||
|
||||
// Reload to v2 (adds a "skip" transition; same state names) and swap
|
||||
// the definition in. The machine keeps its active "busy" leaf.
|
||||
install(VOID_FSM_PLUGIN_V2_PATH, so);
|
||||
Void::Testing::expect(mgr.reload("FsmPlugin").has_value());
|
||||
auto def2 = def_from(mgr);
|
||||
Void::Testing::expect(def2 != nullptr);
|
||||
machine.swap_definition(def2);
|
||||
machine.run_pending();
|
||||
Void::Testing::expect(machine.is_in("busy")); // configuration survived
|
||||
|
||||
// Finish the v1 cycle, then exercise the v2-only "skip" transition.
|
||||
machine.post(Event{*def2->event_id("finish"), {}});
|
||||
machine.run_pending();
|
||||
Void::Testing::expect(machine.is_in("done"));
|
||||
machine.post(Event{*def2->event_id("reset"), {}});
|
||||
machine.run_pending();
|
||||
Void::Testing::expect(machine.is_in("idle"));
|
||||
machine.post(Event{*def2->event_id("skip"), {}}); // new in v2
|
||||
machine.run_pending();
|
||||
Void::Testing::expect(machine.is_in("done"));
|
||||
}
|
||||
|
||||
// @tag stress, concurrency
|
||||
Void::Testing::Test internal_fsm_plugin_hot_reload_under_load()
|
||||
{
|
||||
Void::FileSystem::TempDir tmp{"void_fsmplugin"};
|
||||
const auto so = tmp.path() / "fsm.so";
|
||||
std::filesystem::copy_file(VOID_FSM_PLUGIN_V1_PATH, so);
|
||||
|
||||
PluginManager mgr;
|
||||
Void::Testing::expect(mgr.load(so).has_value());
|
||||
auto def = def_from(mgr);
|
||||
|
||||
// Worker-driven machine; the plugin's .so stays mapped (the manager's
|
||||
// dlclose_on_swap=false) so its action code remains valid for frames
|
||||
// in flight. Pin a handle for the machine's lifetime as belt-and-
|
||||
// suspenders against the .so unmapping.
|
||||
auto pin = mgr.acquire("FsmPlugin");
|
||||
Void::Testing::expect(static_cast<bool>(pin));
|
||||
|
||||
Machine machine{def};
|
||||
machine.start();
|
||||
|
||||
const auto start = *def->event_id("start");
|
||||
const auto finish = *def->event_id("finish");
|
||||
const auto reset = *def->event_id("reset");
|
||||
|
||||
std::atomic<bool> stop{false};
|
||||
std::atomic<long long> posts{0};
|
||||
std::vector<std::thread> producers;
|
||||
producers.reserve(4);
|
||||
for (int p = 0; p < 4; ++p) {
|
||||
producers.emplace_back([&] {
|
||||
while (!stop.load(std::memory_order_relaxed)) {
|
||||
machine.post(Event{start, {}});
|
||||
machine.post(Event{finish, {}});
|
||||
machine.post(Event{reset, {}});
|
||||
posts.fetch_add(3, std::memory_order_relaxed);
|
||||
std::this_thread::yield();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Rebuild + swap the definition repeatedly while events flow.
|
||||
for (int i = 0; i < 5; ++i) {
|
||||
const char* src =
|
||||
(i % 2 == 0) ? VOID_FSM_PLUGIN_V2_PATH : VOID_FSM_PLUGIN_V1_PATH;
|
||||
install(src, so);
|
||||
Void::Testing::expect(mgr.reload("FsmPlugin").has_value());
|
||||
machine.swap_definition(def_from(mgr));
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds{3});
|
||||
}
|
||||
|
||||
stop.store(true);
|
||||
for (auto& t : producers) {
|
||||
t.join();
|
||||
}
|
||||
|
||||
// Drain and confirm the machine is still coherent: exactly one of the
|
||||
// three leaves is active.
|
||||
(void)machine.send_wait(Event{reset, {}});
|
||||
const int active = static_cast<int>(machine.is_in("idle")) +
|
||||
static_cast<int>(machine.is_in("busy")) +
|
||||
static_cast<int>(machine.is_in("done"));
|
||||
Void::Testing::expect_eq(active, 1);
|
||||
Void::Testing::expect(posts.load() > 0);
|
||||
machine.stop();
|
||||
}
|
||||
|
||||
#endif // FSM plugins available
|
||||
@@ -1,70 +0,0 @@
|
||||
#include <Void/Fsm/Definition.hpp>
|
||||
#include <Void/Fsm/PluginBehavior.hpp>
|
||||
#include <Void/Plugin/Plugin.hpp>
|
||||
|
||||
#include <atomic>
|
||||
#include <string_view>
|
||||
|
||||
// FSM behaviour plugin, v1. Defines a 3-state cycle (idle -> busy -> done
|
||||
// -> idle) and counts how many times its action ran. v2 keeps the same
|
||||
// state/event names so the host can swap_definition seamlessly.
|
||||
|
||||
namespace
|
||||
{
|
||||
std::atomic<int> g_action_runs{0};
|
||||
|
||||
class FsmPlugin final : public Void::Plugin::IPlugin,
|
||||
public Void::Fsm::IFsmBehaviorPack
|
||||
{
|
||||
public:
|
||||
|
||||
[[nodiscard]] std::string_view name() const noexcept override
|
||||
{
|
||||
return "FsmPlugin";
|
||||
}
|
||||
|
||||
void register_into(Void::Fsm::Builder& b) override
|
||||
{
|
||||
using namespace Void::Fsm;
|
||||
auto idle = b.state("idle");
|
||||
auto busy = b.state("busy");
|
||||
auto done = b.state("done");
|
||||
b.initial(idle);
|
||||
const auto start = b.event("start");
|
||||
const auto finish = b.event("finish");
|
||||
const auto reset = b.event("reset");
|
||||
b.transition(idle, start, busy)
|
||||
.action(SyncAction{[](Machine&, const Event&) {
|
||||
g_action_runs.fetch_add(1, std::memory_order_relaxed);
|
||||
}});
|
||||
b.transition(busy, finish, done);
|
||||
b.transition(done, reset, idle);
|
||||
}
|
||||
};
|
||||
} // namespace
|
||||
|
||||
extern "C" {
|
||||
|
||||
void* void_plugin_create() { return new FsmPlugin; }
|
||||
|
||||
void void_plugin_destroy(void* p) { delete static_cast<FsmPlugin*>(p); }
|
||||
|
||||
Void::Plugin::PluginInfo void_plugin_info()
|
||||
{
|
||||
return {
|
||||
.abi_version = Void::Plugin::ABI_VERSION,
|
||||
.name = "FsmPlugin",
|
||||
.plugin_version = "1.0.0",
|
||||
.description = "FSM behaviour plugin (v1)",
|
||||
};
|
||||
}
|
||||
|
||||
// Stateless factory: returns a fresh pack the host uses only during
|
||||
// definition build. It does not need to be the IPlugin instance.
|
||||
Void::Fsm::IFsmBehaviorPack* void_plugin_fsm_behaviors()
|
||||
{
|
||||
static FsmPlugin pack;
|
||||
return &pack;
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
@@ -1,71 +0,0 @@
|
||||
#include <Void/Fsm/Definition.hpp>
|
||||
#include <Void/Fsm/PluginBehavior.hpp>
|
||||
#include <Void/Plugin/Plugin.hpp>
|
||||
|
||||
#include <atomic>
|
||||
#include <string_view>
|
||||
|
||||
// FSM behaviour plugin, v2. Same state/event names as v1 (so the host
|
||||
// adopts the active configuration seamlessly on swap_definition) plus a
|
||||
// new "skip" transition idle -> done that proves the reloaded behaviour
|
||||
// is live.
|
||||
|
||||
namespace
|
||||
{
|
||||
std::atomic<int> g_action_runs{0};
|
||||
|
||||
class FsmPlugin final : public Void::Plugin::IPlugin,
|
||||
public Void::Fsm::IFsmBehaviorPack
|
||||
{
|
||||
public:
|
||||
|
||||
[[nodiscard]] std::string_view name() const noexcept override
|
||||
{
|
||||
return "FsmPlugin";
|
||||
}
|
||||
|
||||
void register_into(Void::Fsm::Builder& b) override
|
||||
{
|
||||
using namespace Void::Fsm;
|
||||
auto idle = b.state("idle");
|
||||
auto busy = b.state("busy");
|
||||
auto done = b.state("done");
|
||||
b.initial(idle);
|
||||
const auto start = b.event("start");
|
||||
const auto finish = b.event("finish");
|
||||
const auto reset = b.event("reset");
|
||||
const auto skip = b.event("skip"); // new in v2
|
||||
b.transition(idle, start, busy)
|
||||
.action(SyncAction{[](Machine&, const Event&) {
|
||||
g_action_runs.fetch_add(1, std::memory_order_relaxed);
|
||||
}});
|
||||
b.transition(busy, finish, done);
|
||||
b.transition(done, reset, idle);
|
||||
b.transition(idle, skip, done); // new behaviour
|
||||
}
|
||||
};
|
||||
} // namespace
|
||||
|
||||
extern "C" {
|
||||
|
||||
void* void_plugin_create() { return new FsmPlugin; }
|
||||
|
||||
void void_plugin_destroy(void* p) { delete static_cast<FsmPlugin*>(p); }
|
||||
|
||||
Void::Plugin::PluginInfo void_plugin_info()
|
||||
{
|
||||
return {
|
||||
.abi_version = Void::Plugin::ABI_VERSION,
|
||||
.name = "FsmPlugin",
|
||||
.plugin_version = "2.0.0",
|
||||
.description = "FSM behaviour plugin (v2)",
|
||||
};
|
||||
}
|
||||
|
||||
Void::Fsm::IFsmBehaviorPack* void_plugin_fsm_behaviors()
|
||||
{
|
||||
static FsmPlugin pack;
|
||||
return &pack;
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
@@ -1,247 +0,0 @@
|
||||
#include <Void/Fsm/Definition.hpp>
|
||||
#include <Void/Fsm/Machine.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
using namespace Void::Fsm;
|
||||
|
||||
namespace
|
||||
{
|
||||
// Embedder-driven machine (no worker thread): post + run_pending make
|
||||
// the tests fully deterministic.
|
||||
struct Bench {
|
||||
std::shared_ptr<const MachineDef> def;
|
||||
std::unique_ptr<Machine> machine;
|
||||
std::vector<std::string> log;
|
||||
|
||||
explicit Bench(Builder& b)
|
||||
{
|
||||
auto built = b.build();
|
||||
Void::Testing::expect(built.has_value());
|
||||
def = *built;
|
||||
machine = std::make_unique<Machine>(
|
||||
def, MachineOptions{.own_worker = false});
|
||||
}
|
||||
|
||||
SendResult step(EventId ev)
|
||||
{
|
||||
machine->post(Event{ev, {}});
|
||||
machine->run_pending();
|
||||
return SendResult::Handled; // result checked via send paths
|
||||
}
|
||||
};
|
||||
} // namespace
|
||||
|
||||
Void::Testing::Test basic_initial_state_entered_on_start()
|
||||
{
|
||||
Builder b;
|
||||
auto idle = b.state("idle");
|
||||
auto run = b.state("running");
|
||||
b.initial(idle);
|
||||
(void)run;
|
||||
|
||||
Bench bench{b};
|
||||
bench.machine->start();
|
||||
Void::Testing::expect(bench.machine->is_in("idle"));
|
||||
Void::Testing::expect(!bench.machine->is_in("running"));
|
||||
Void::Testing::expect(bench.machine->running());
|
||||
}
|
||||
|
||||
Void::Testing::Test basic_transition_changes_state()
|
||||
{
|
||||
Builder b;
|
||||
auto idle = b.state("idle");
|
||||
auto run = b.state("running");
|
||||
b.initial(idle);
|
||||
const auto go = b.event("go");
|
||||
b.transition(idle, go, run);
|
||||
|
||||
Bench bench{b};
|
||||
bench.machine->start();
|
||||
bench.machine->post(Event{go, {}});
|
||||
bench.machine->run_pending();
|
||||
|
||||
Void::Testing::expect(bench.machine->is_in("running"));
|
||||
Void::Testing::expect(!bench.machine->is_in("idle"));
|
||||
}
|
||||
|
||||
Void::Testing::Test basic_entry_exit_and_action_ordering()
|
||||
{
|
||||
std::vector<std::string> log;
|
||||
Builder b;
|
||||
auto a = b.state("a");
|
||||
auto c = b.state("c");
|
||||
b.initial(a);
|
||||
const auto go = b.event("go");
|
||||
b.on_entry(a, SyncAction{[&](Machine&, const Event&) {
|
||||
log.push_back("enter a");
|
||||
}});
|
||||
b.on_exit(a, SyncAction{[&](Machine&, const Event&) {
|
||||
log.push_back("exit a");
|
||||
}});
|
||||
b.on_entry(c, SyncAction{[&](Machine&, const Event&) {
|
||||
log.push_back("enter c");
|
||||
}});
|
||||
b.transition(a, go, c).action(SyncAction{
|
||||
[&](Machine&, const Event&) { log.push_back("action"); }});
|
||||
|
||||
Bench bench{b};
|
||||
bench.machine->start();
|
||||
bench.machine->post(Event{go, {}});
|
||||
bench.machine->run_pending();
|
||||
|
||||
const std::vector<std::string> expected{"enter a", "exit a", "action",
|
||||
"enter c"};
|
||||
Void::Testing::expect(log == expected);
|
||||
}
|
||||
|
||||
Void::Testing::Test basic_guard_blocks_and_allows()
|
||||
{
|
||||
Builder b;
|
||||
auto a = b.state("a");
|
||||
auto c = b.state("c");
|
||||
b.initial(a);
|
||||
const auto go = b.event("go");
|
||||
bool open = false;
|
||||
b.transition(a, go, c).guard(
|
||||
[&](const Machine&, const Event&) { return open; });
|
||||
|
||||
Bench bench{b};
|
||||
bench.machine->start();
|
||||
|
||||
bench.machine->post(Event{go, {}});
|
||||
bench.machine->run_pending();
|
||||
Void::Testing::expect(bench.machine->is_in("a"));
|
||||
|
||||
open = true;
|
||||
bench.machine->post(Event{go, {}});
|
||||
bench.machine->run_pending();
|
||||
Void::Testing::expect(bench.machine->is_in("c"));
|
||||
}
|
||||
|
||||
Void::Testing::Test basic_internal_transition_no_exit_entry()
|
||||
{
|
||||
std::vector<std::string> log;
|
||||
Builder b;
|
||||
auto a = b.state("a");
|
||||
b.initial(a);
|
||||
const auto tick = b.event("tick");
|
||||
b.on_entry(a, SyncAction{[&](Machine&, const Event&) {
|
||||
log.push_back("enter");
|
||||
}});
|
||||
b.on_exit(a, SyncAction{[&](Machine&, const Event&) {
|
||||
log.push_back("exit");
|
||||
}});
|
||||
b.internal(a, tick).action(SyncAction{
|
||||
[&](Machine&, const Event&) { log.push_back("internal"); }});
|
||||
|
||||
Bench bench{b};
|
||||
bench.machine->start();
|
||||
bench.machine->post(Event{tick, {}});
|
||||
bench.machine->run_pending();
|
||||
|
||||
const std::vector<std::string> expected{"enter", "internal"};
|
||||
Void::Testing::expect(log == expected);
|
||||
Void::Testing::expect(bench.machine->is_in("a"));
|
||||
}
|
||||
|
||||
Void::Testing::Test basic_self_transition_exits_and_reenters()
|
||||
{
|
||||
std::vector<std::string> log;
|
||||
Builder b;
|
||||
auto a = b.state("a");
|
||||
b.initial(a);
|
||||
const auto reset = b.event("reset");
|
||||
b.on_entry(a, SyncAction{[&](Machine&, const Event&) {
|
||||
log.push_back("enter");
|
||||
}});
|
||||
b.on_exit(a, SyncAction{[&](Machine&, const Event&) {
|
||||
log.push_back("exit");
|
||||
}});
|
||||
b.transition(a, reset, a);
|
||||
|
||||
Bench bench{b};
|
||||
bench.machine->start();
|
||||
bench.machine->post(Event{reset, {}});
|
||||
bench.machine->run_pending();
|
||||
|
||||
const std::vector<std::string> expected{"enter", "exit", "enter"};
|
||||
Void::Testing::expect(log == expected);
|
||||
}
|
||||
|
||||
Void::Testing::Test basic_payload_reaches_action()
|
||||
{
|
||||
int received = 0;
|
||||
Builder b;
|
||||
auto a = b.state("a");
|
||||
auto c = b.state("c");
|
||||
b.initial(a);
|
||||
const auto go = b.event("go");
|
||||
b.transition(a, go, c).action(
|
||||
SyncAction{[&](Machine&, const Event& e) {
|
||||
received = std::any_cast<int>(e.payload);
|
||||
}});
|
||||
|
||||
Bench bench{b};
|
||||
bench.machine->start();
|
||||
bench.machine->post(Event{go, 42});
|
||||
bench.machine->run_pending();
|
||||
Void::Testing::expect_eq(received, 42);
|
||||
}
|
||||
|
||||
Void::Testing::Test basic_unhandled_event_keeps_state()
|
||||
{
|
||||
Builder b;
|
||||
auto a = b.state("a");
|
||||
b.initial(a);
|
||||
const auto noop = b.event("noop");
|
||||
(void)noop;
|
||||
|
||||
Bench bench{b};
|
||||
bench.machine->start();
|
||||
bench.machine->post(Event{noop, {}});
|
||||
bench.machine->run_pending();
|
||||
Void::Testing::expect(bench.machine->is_in("a"));
|
||||
}
|
||||
|
||||
Void::Testing::Test basic_post_rejected_before_start_and_after_stop()
|
||||
{
|
||||
Builder b;
|
||||
auto a = b.state("a");
|
||||
b.initial(a);
|
||||
const auto go = b.event("go");
|
||||
|
||||
Bench bench{b};
|
||||
Void::Testing::expect(!bench.machine->post(Event{go, {}}));
|
||||
bench.machine->start();
|
||||
Void::Testing::expect(bench.machine->post(Event{go, {}}));
|
||||
bench.machine->run_pending();
|
||||
bench.machine->stop();
|
||||
Void::Testing::expect(!bench.machine->post(Event{go, {}}));
|
||||
Void::Testing::expect(!bench.machine->running());
|
||||
}
|
||||
|
||||
Void::Testing::Test builder_rejects_composite_without_initial()
|
||||
{
|
||||
Builder b;
|
||||
auto parent = b.state("parent");
|
||||
(void)b.state("c1", parent);
|
||||
(void)b.state("c2", parent);
|
||||
b.initial(parent); // parent initial of root, but no initial child
|
||||
auto built = b.build();
|
||||
Void::Testing::expect(!built.has_value());
|
||||
}
|
||||
|
||||
Void::Testing::Test builder_defaults_first_top_level_as_initial()
|
||||
{
|
||||
Builder b;
|
||||
(void)b.state("first");
|
||||
(void)b.state("second");
|
||||
|
||||
Bench bench{b};
|
||||
bench.machine->start();
|
||||
Void::Testing::expect(bench.machine->is_in("first"));
|
||||
}
|
||||
@@ -1,221 +0,0 @@
|
||||
#include <Void/Fsm/Definition.hpp>
|
||||
#include <Void/Fsm/Machine.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <atomic>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
using namespace Void::Fsm;
|
||||
|
||||
#ifdef VOID_HAS_ENUM_REFLECTION
|
||||
|
||||
namespace
|
||||
{
|
||||
enum class Phase { Ping, Pong };
|
||||
enum class Signal { Flip };
|
||||
} // namespace
|
||||
|
||||
Void::Testing::Test enum_reflection_builds_states_and_events()
|
||||
{
|
||||
Builder b;
|
||||
b.states_from_enum<Phase>();
|
||||
b.initial(b.state_of(Phase::Ping));
|
||||
const auto flip = b.event(Signal::Flip);
|
||||
b.transition(b.state_of(Phase::Ping), flip, b.state_of(Phase::Pong));
|
||||
b.transition(b.state_of(Phase::Pong), flip, b.state_of(Phase::Ping));
|
||||
|
||||
auto def = b.build();
|
||||
Void::Testing::expect(def.has_value());
|
||||
Void::Testing::expect((*def)->state_id("Ping").has_value());
|
||||
Void::Testing::expect((*def)->event_id("Flip").has_value());
|
||||
|
||||
Machine m{*def, MachineOptions{.own_worker = false}};
|
||||
m.start();
|
||||
Void::Testing::expect(m.is_in("Ping"));
|
||||
|
||||
Void::Testing::expect(m.post(Signal::Flip));
|
||||
m.run_pending();
|
||||
Void::Testing::expect(m.is_in("Pong"));
|
||||
|
||||
// Serialized state uses enumerator names — stable across reloads.
|
||||
const auto json = m.serialize_state();
|
||||
Void::Testing::expect_eq(json["leaves"][0].as_string(),
|
||||
std::string{"Pong"});
|
||||
}
|
||||
|
||||
#endif // VOID_HAS_ENUM_REFLECTION
|
||||
|
||||
// @tag stress, concurrency
|
||||
Void::Testing::Test concurrent_posts_all_processed_in_producer_order()
|
||||
{
|
||||
constexpr int producers = 8;
|
||||
constexpr int per_producer = 10'000;
|
||||
|
||||
// counter state with an internal self-loop that consumes "bump"
|
||||
// events carrying {producer, seq} payloads.
|
||||
struct Payload {
|
||||
int producer;
|
||||
int seq;
|
||||
};
|
||||
|
||||
std::vector<int> next_seq(producers, 0);
|
||||
std::atomic<long long> handled{0};
|
||||
bool order_ok = true;
|
||||
|
||||
Builder b;
|
||||
auto counting = b.state("counting");
|
||||
b.initial(counting);
|
||||
const auto bump = b.event("bump");
|
||||
b.internal(counting, bump)
|
||||
.action(SyncAction{[&](Machine&, const Event& e) {
|
||||
const auto p = std::any_cast<Payload>(e.payload);
|
||||
// Per-producer FIFO must hold (single consumer).
|
||||
if (next_seq[static_cast<std::size_t>(p.producer)] != p.seq) {
|
||||
order_ok = false;
|
||||
}
|
||||
++next_seq[static_cast<std::size_t>(p.producer)];
|
||||
++handled;
|
||||
}});
|
||||
|
||||
auto def = b.build();
|
||||
Void::Testing::expect(def.has_value());
|
||||
Machine m{*def}; // own worker
|
||||
m.start();
|
||||
|
||||
std::atomic<bool> go{false};
|
||||
std::vector<std::thread> threads;
|
||||
threads.reserve(producers);
|
||||
for (int p = 0; p < producers; ++p) {
|
||||
threads.emplace_back([&m, &go, bump, p] {
|
||||
go.wait(false);
|
||||
for (int i = 0; i < per_producer; ++i) {
|
||||
while (!m.post(Event{bump, Payload{p, i}})) {
|
||||
std::this_thread::yield();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
go = true;
|
||||
go.notify_all();
|
||||
for (auto& t : threads) {
|
||||
t.join();
|
||||
}
|
||||
|
||||
// Everything posted before this send_wait is processed before it.
|
||||
(void)m.send_wait(Event{bump, Payload{0, per_producer}});
|
||||
++next_seq[0]; // account for the flush event
|
||||
|
||||
m.stop();
|
||||
Void::Testing::expect_eq(
|
||||
handled.load(),
|
||||
static_cast<long long>(producers) * per_producer + 1);
|
||||
Void::Testing::expect(order_ok);
|
||||
}
|
||||
|
||||
// @tag stress, concurrency
|
||||
Void::Testing::Test snapshot_reads_never_tear_under_load()
|
||||
{
|
||||
Builder b;
|
||||
auto ping = b.state("ping");
|
||||
auto pong = b.state("pong");
|
||||
b.initial(ping);
|
||||
const auto flip = b.event("flip");
|
||||
b.transition(ping, flip, pong);
|
||||
b.transition(pong, flip, ping);
|
||||
|
||||
auto def = b.build();
|
||||
Void::Testing::expect(def.has_value());
|
||||
Machine m{*def};
|
||||
m.start();
|
||||
|
||||
std::atomic<bool> stop{false};
|
||||
std::atomic<long long> reads{0};
|
||||
bool sane = true;
|
||||
|
||||
std::vector<std::thread> readers;
|
||||
readers.reserve(4);
|
||||
for (int r = 0; r < 4; ++r) {
|
||||
readers.emplace_back([&] {
|
||||
while (!stop.load(std::memory_order_relaxed)) {
|
||||
const auto snap = m.current();
|
||||
// Exactly one leaf, and it is one of the two states.
|
||||
if (snap.leaf_count != 1) {
|
||||
sane = false;
|
||||
}
|
||||
++reads;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
for (int i = 0; i < 20'000; ++i) {
|
||||
m.post(Event{flip, {}});
|
||||
}
|
||||
(void)m.send_wait(Event{flip, {}});
|
||||
|
||||
stop = true;
|
||||
for (auto& t : readers) {
|
||||
t.join();
|
||||
}
|
||||
m.stop();
|
||||
|
||||
Void::Testing::expect(sane);
|
||||
Void::Testing::expect(reads.load() > 0);
|
||||
}
|
||||
|
||||
// @tag stress, concurrency
|
||||
Void::Testing::Test hot_swap_under_sustained_load()
|
||||
{
|
||||
auto make = [](bool variant) {
|
||||
Builder b;
|
||||
auto ping = b.state("ping");
|
||||
auto pong = b.state("pong");
|
||||
b.initial(ping);
|
||||
const auto flip = b.event("flip");
|
||||
b.transition(ping, flip, pong);
|
||||
b.transition(pong, flip, ping);
|
||||
if (variant) {
|
||||
// identical topology, extra no-op event
|
||||
(void)b.event("extra");
|
||||
}
|
||||
auto def = b.build();
|
||||
Void::Testing::expect(def.has_value());
|
||||
return *def;
|
||||
};
|
||||
|
||||
Machine m{make(false)};
|
||||
m.start();
|
||||
|
||||
std::atomic<bool> stop{false};
|
||||
std::vector<std::thread> producers;
|
||||
producers.reserve(4);
|
||||
const auto flip = *m.definition()->event_id("flip");
|
||||
for (int p = 0; p < 4; ++p) {
|
||||
producers.emplace_back([&m, &stop, flip] {
|
||||
while (!stop.load(std::memory_order_relaxed)) {
|
||||
(void)m.post(Event{flip, {}});
|
||||
// Pace producers so the backlog stays bounded — the test
|
||||
// exercises swap-under-load, not queue growth.
|
||||
std::this_thread::yield();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
for (int i = 0; i < 50; ++i) {
|
||||
m.swap_definition(make(i % 2 == 1));
|
||||
std::this_thread::sleep_for(std::chrono::microseconds{200});
|
||||
}
|
||||
|
||||
stop = true;
|
||||
for (auto& t : producers) {
|
||||
t.join();
|
||||
}
|
||||
(void)m.send_wait(Event{flip, {}});
|
||||
|
||||
// Machine is still coherent: exactly one of the two states active.
|
||||
const bool in_ping = m.is_in("ping");
|
||||
const bool in_pong = m.is_in("pong");
|
||||
Void::Testing::expect(in_ping != in_pong);
|
||||
m.stop();
|
||||
}
|
||||
@@ -1,336 +0,0 @@
|
||||
#include <Void/Fsm/Definition.hpp>
|
||||
#include <Void/Fsm/Machine.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
using namespace Void::Fsm;
|
||||
|
||||
// ── deferred events ───────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test defer_stashes_until_state_change()
|
||||
{
|
||||
int handled = 0;
|
||||
Builder b;
|
||||
auto busy = b.state("busy");
|
||||
auto idle = b.state("idle");
|
||||
b.initial(busy);
|
||||
const auto job = b.event("job");
|
||||
const auto done = b.event("done");
|
||||
b.defer(busy, job);
|
||||
b.transition(busy, done, idle);
|
||||
b.internal(idle, job).action(
|
||||
SyncAction{[&](Machine&, const Event&) { ++handled; }});
|
||||
|
||||
auto def = b.build();
|
||||
Void::Testing::expect(def.has_value());
|
||||
Machine m{*def, MachineOptions{.own_worker = false}};
|
||||
m.start();
|
||||
|
||||
m.post(Event{job, {}}); // deferred in busy
|
||||
m.post(Event{job, {}}); // deferred in busy
|
||||
m.run_pending();
|
||||
Void::Testing::expect_eq(handled, 0);
|
||||
|
||||
m.post(Event{done, {}}); // busy -> idle, deferred jobs re-inject
|
||||
m.run_pending();
|
||||
Void::Testing::expect_eq(handled, 2);
|
||||
}
|
||||
|
||||
Void::Testing::Test defer_keeps_fifo_order()
|
||||
{
|
||||
std::vector<int> seen;
|
||||
Builder b;
|
||||
auto busy = b.state("busy");
|
||||
auto idle = b.state("idle");
|
||||
b.initial(busy);
|
||||
const auto job = b.event("job");
|
||||
const auto done = b.event("done");
|
||||
b.defer(busy, job);
|
||||
b.transition(busy, done, idle);
|
||||
b.internal(idle, job).action(
|
||||
SyncAction{[&](Machine&, const Event& e) {
|
||||
seen.push_back(std::any_cast<int>(e.payload));
|
||||
}});
|
||||
|
||||
auto def = b.build();
|
||||
Void::Testing::expect(def.has_value());
|
||||
Machine m{*def, MachineOptions{.own_worker = false}};
|
||||
m.start();
|
||||
m.post(Event{job, 1});
|
||||
m.post(Event{job, 2});
|
||||
m.post(Event{job, 3});
|
||||
m.post(Event{done, {}});
|
||||
m.run_pending();
|
||||
|
||||
const std::vector<int> expected{1, 2, 3};
|
||||
Void::Testing::expect(seen == expected);
|
||||
}
|
||||
|
||||
// ── orthogonal regions ────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test parallel_enters_all_regions()
|
||||
{
|
||||
Builder b;
|
||||
auto sys = b.state("sys");
|
||||
auto net = b.state("net", sys);
|
||||
auto net_d = b.state("net_down", net);
|
||||
auto net_u = b.state("net_up", net);
|
||||
auto disk = b.state("disk", sys);
|
||||
auto d_ok = b.state("disk_ok", disk);
|
||||
auto d_bad = b.state("disk_bad", disk);
|
||||
b.initial(sys);
|
||||
b.parallel(sys);
|
||||
b.initial(net_d);
|
||||
b.initial(d_ok);
|
||||
(void)net_u;
|
||||
(void)d_bad;
|
||||
|
||||
auto def = b.build();
|
||||
Void::Testing::expect(def.has_value());
|
||||
Machine m{*def, MachineOptions{.own_worker = false}};
|
||||
m.start();
|
||||
|
||||
Void::Testing::expect(m.is_in("net_down"));
|
||||
Void::Testing::expect(m.is_in("disk_ok"));
|
||||
Void::Testing::expect_eq(m.current().leaf_count, std::uint32_t{2});
|
||||
}
|
||||
|
||||
Void::Testing::Test parallel_regions_react_independently()
|
||||
{
|
||||
Builder b;
|
||||
auto sys = b.state("sys");
|
||||
auto net = b.state("net", sys);
|
||||
auto net_d = b.state("net_down", net);
|
||||
auto net_u = b.state("net_up", net);
|
||||
auto disk = b.state("disk", sys);
|
||||
auto d_ok = b.state("disk_ok", disk);
|
||||
auto d_bad = b.state("disk_bad", disk);
|
||||
b.initial(sys);
|
||||
b.parallel(sys);
|
||||
b.initial(net_d);
|
||||
b.initial(d_ok);
|
||||
const auto net_event = b.event("net_restored");
|
||||
const auto disk_event = b.event("disk_failed");
|
||||
b.transition(net_d, net_event, net_u);
|
||||
b.transition(d_ok, disk_event, d_bad);
|
||||
|
||||
auto def = b.build();
|
||||
Void::Testing::expect(def.has_value());
|
||||
Machine m{*def, MachineOptions{.own_worker = false}};
|
||||
m.start();
|
||||
|
||||
m.post(Event{net_event, {}});
|
||||
m.run_pending();
|
||||
Void::Testing::expect(m.is_in("net_up"));
|
||||
Void::Testing::expect(m.is_in("disk_ok")); // untouched
|
||||
|
||||
m.post(Event{disk_event, {}});
|
||||
m.run_pending();
|
||||
Void::Testing::expect(m.is_in("net_up"));
|
||||
Void::Testing::expect(m.is_in("disk_bad"));
|
||||
}
|
||||
|
||||
Void::Testing::Test parallel_one_event_can_fire_in_both_regions()
|
||||
{
|
||||
Builder b;
|
||||
auto sys = b.state("sys");
|
||||
auto r1 = b.state("r1", sys);
|
||||
auto a1 = b.state("a1", r1);
|
||||
auto b1 = b.state("b1", r1);
|
||||
auto r2 = b.state("r2", sys);
|
||||
auto a2 = b.state("a2", r2);
|
||||
auto b2 = b.state("b2", r2);
|
||||
b.initial(sys);
|
||||
b.parallel(sys);
|
||||
b.initial(a1);
|
||||
b.initial(a2);
|
||||
const auto flip = b.event("flip");
|
||||
b.transition(a1, flip, b1);
|
||||
b.transition(a2, flip, b2);
|
||||
|
||||
auto def = b.build();
|
||||
Void::Testing::expect(def.has_value());
|
||||
Machine m{*def, MachineOptions{.own_worker = false}};
|
||||
m.start();
|
||||
m.post(Event{flip, {}});
|
||||
m.run_pending();
|
||||
|
||||
Void::Testing::expect(m.is_in("b1"));
|
||||
Void::Testing::expect(m.is_in("b2"));
|
||||
}
|
||||
|
||||
// ── timers ────────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test timeout_fires_after_duration()
|
||||
{
|
||||
Builder b;
|
||||
auto waiting = b.state("waiting");
|
||||
auto expired = b.state("expired");
|
||||
b.initial(waiting);
|
||||
const auto timeout_ev = b.event("timed_out");
|
||||
b.timeout(waiting, std::chrono::milliseconds{20}, timeout_ev);
|
||||
b.transition(waiting, timeout_ev, expired);
|
||||
|
||||
auto def = b.build();
|
||||
Void::Testing::expect(def.has_value());
|
||||
Machine m{*def, MachineOptions{.own_worker = false}};
|
||||
m.start();
|
||||
|
||||
m.run_pending();
|
||||
Void::Testing::expect(m.is_in("waiting")); // not yet
|
||||
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds{30});
|
||||
m.run_pending();
|
||||
Void::Testing::expect(m.is_in("expired"));
|
||||
}
|
||||
|
||||
Void::Testing::Test timeout_cancelled_by_leaving_state()
|
||||
{
|
||||
Builder b;
|
||||
auto waiting = b.state("waiting");
|
||||
auto active = b.state("active");
|
||||
auto expired = b.state("expired");
|
||||
b.initial(waiting);
|
||||
const auto timeout_ev = b.event("timed_out");
|
||||
const auto go = b.event("go");
|
||||
b.timeout(waiting, std::chrono::milliseconds{20}, timeout_ev);
|
||||
b.transition(waiting, timeout_ev, expired);
|
||||
b.transition(waiting, go, active);
|
||||
|
||||
auto def = b.build();
|
||||
Void::Testing::expect(def.has_value());
|
||||
Machine m{*def, MachineOptions{.own_worker = false}};
|
||||
m.start();
|
||||
|
||||
m.post(Event{go, {}});
|
||||
m.run_pending();
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds{30});
|
||||
m.run_pending();
|
||||
Void::Testing::expect(m.is_in("active")); // timer was disarmed
|
||||
}
|
||||
|
||||
// @tag integration
|
||||
Void::Testing::Test timeout_with_own_worker_thread()
|
||||
{
|
||||
Builder b;
|
||||
auto waiting = b.state("waiting");
|
||||
auto expired = b.state("expired");
|
||||
b.initial(waiting);
|
||||
const auto timeout_ev = b.event("timed_out");
|
||||
b.timeout(waiting, std::chrono::milliseconds{15}, timeout_ev);
|
||||
b.transition(waiting, timeout_ev, expired);
|
||||
|
||||
auto def = b.build();
|
||||
Void::Testing::expect(def.has_value());
|
||||
Machine m{*def}; // own worker
|
||||
m.start();
|
||||
|
||||
for (int i = 0; i < 200 && !m.is_in("expired"); ++i) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds{5});
|
||||
}
|
||||
Void::Testing::expect(m.is_in("expired"));
|
||||
m.stop();
|
||||
}
|
||||
|
||||
// ── coroutine actions / awaitable send ────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test coro_action_completes_within_step()
|
||||
{
|
||||
std::vector<std::string> log;
|
||||
Builder b;
|
||||
auto a = b.state("a");
|
||||
auto c = b.state("c");
|
||||
b.initial(a);
|
||||
const auto go = b.event("go");
|
||||
b.transition(a, go, c).action(
|
||||
Action{[&](Machine&, const Event&) -> Void::Coro::Task<void> {
|
||||
log.push_back("action begin");
|
||||
auto inner = []() -> Void::Coro::Task<int> { co_return 7; };
|
||||
const int v = co_await inner();
|
||||
log.push_back("inner " + std::to_string(v));
|
||||
log.push_back("action end");
|
||||
}});
|
||||
b.on_entry(c, SyncAction{[&](Machine&, const Event&) {
|
||||
log.push_back("enter c");
|
||||
}});
|
||||
|
||||
auto def = b.build();
|
||||
Void::Testing::expect(def.has_value());
|
||||
Machine m{*def, MachineOptions{.own_worker = false}};
|
||||
m.start();
|
||||
m.post(Event{go, {}});
|
||||
m.run_pending();
|
||||
|
||||
const std::vector<std::string> expected{
|
||||
"action begin", "inner 7", "action end", "enter c"};
|
||||
Void::Testing::expect(log == expected);
|
||||
}
|
||||
|
||||
// @tag integration
|
||||
Void::Testing::Test send_wait_returns_step_result()
|
||||
{
|
||||
Builder b;
|
||||
auto a = b.state("a");
|
||||
auto c = b.state("c");
|
||||
b.initial(a);
|
||||
const auto go = b.event("go");
|
||||
const auto noop = b.event("noop");
|
||||
b.transition(a, go, c);
|
||||
|
||||
auto def = b.build();
|
||||
Void::Testing::expect(def.has_value());
|
||||
Machine m{*def}; // worker drives; send_wait blocks the caller
|
||||
m.start();
|
||||
|
||||
Void::Testing::expect(m.send_wait(Event{go, {}}) ==
|
||||
SendResult::Handled);
|
||||
Void::Testing::expect(m.is_in("c"));
|
||||
Void::Testing::expect(m.send_wait(Event{noop, {}}) ==
|
||||
SendResult::Unhandled);
|
||||
m.stop();
|
||||
Void::Testing::expect(m.send_wait(Event{go, {}}) ==
|
||||
SendResult::Dropped);
|
||||
}
|
||||
|
||||
// @tag integration
|
||||
Void::Testing::Test co_await_send_resolves_with_result()
|
||||
{
|
||||
Builder b;
|
||||
auto a = b.state("a");
|
||||
auto c = b.state("c");
|
||||
b.initial(a);
|
||||
const auto go = b.event("go");
|
||||
b.transition(a, go, c);
|
||||
|
||||
auto def = b.build();
|
||||
Void::Testing::expect(def.has_value());
|
||||
Machine m{*def};
|
||||
m.start();
|
||||
|
||||
std::optional<SendResult> result;
|
||||
Void::Async::ManualExecutor ex;
|
||||
Void::Async::spawn(
|
||||
ex,
|
||||
[](Machine& machine, Void::Async::Executor& resume_on,
|
||||
std::optional<SendResult>& out) -> Void::Coro::Task<void> {
|
||||
out = co_await machine.send(
|
||||
Event{*machine.definition()->event_id("go"), {}},
|
||||
&resume_on);
|
||||
}(m, ex, result));
|
||||
|
||||
// Drain until the awaitable resumes us back on `ex` with the result.
|
||||
for (int i = 0; i < 500 && !result.has_value(); ++i) {
|
||||
if (ex.drain() == 0) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds{1});
|
||||
}
|
||||
}
|
||||
Void::Testing::expect(result.has_value());
|
||||
Void::Testing::expect(*result == SendResult::Handled);
|
||||
Void::Testing::expect(m.is_in("c"));
|
||||
m.stop();
|
||||
}
|
||||
@@ -1,239 +0,0 @@
|
||||
#include <Void/Fsm/Definition.hpp>
|
||||
#include <Void/Fsm/Machine.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
using namespace Void::Fsm;
|
||||
|
||||
namespace
|
||||
{
|
||||
struct Trace {
|
||||
std::vector<std::string> log;
|
||||
|
||||
SyncAction enter(std::string name)
|
||||
{
|
||||
return [this, name](Machine&, const Event&) {
|
||||
log.push_back("+" + name);
|
||||
};
|
||||
}
|
||||
|
||||
SyncAction exit(std::string name)
|
||||
{
|
||||
return [this, name](Machine&, const Event&) {
|
||||
log.push_back("-" + name);
|
||||
};
|
||||
}
|
||||
};
|
||||
} // namespace
|
||||
|
||||
Void::Testing::Test hierarchy_descends_into_nested_initial()
|
||||
{
|
||||
Trace t;
|
||||
Builder b;
|
||||
auto outer = b.state("outer");
|
||||
auto inner = b.state("inner", outer);
|
||||
auto deep = b.state("deep", inner);
|
||||
b.initial(outer);
|
||||
b.initial(inner);
|
||||
b.initial(deep);
|
||||
b.on_entry(outer, t.enter("outer"));
|
||||
b.on_entry(inner, t.enter("inner"));
|
||||
b.on_entry(deep, t.enter("deep"));
|
||||
|
||||
auto def = b.build();
|
||||
Void::Testing::expect(def.has_value());
|
||||
Machine m{*def, MachineOptions{.own_worker = false}};
|
||||
m.start();
|
||||
|
||||
const std::vector<std::string> expected{"+outer", "+inner", "+deep"};
|
||||
Void::Testing::expect(t.log == expected);
|
||||
Void::Testing::expect(m.is_in("outer"));
|
||||
Void::Testing::expect(m.is_in("inner"));
|
||||
Void::Testing::expect(m.is_in("deep"));
|
||||
}
|
||||
|
||||
Void::Testing::Test hierarchy_lca_exit_entry_order()
|
||||
{
|
||||
Trace t;
|
||||
Builder b;
|
||||
auto top = b.state("top");
|
||||
auto a = b.state("a", top);
|
||||
auto a1 = b.state("a1", a);
|
||||
auto c = b.state("c", top);
|
||||
auto c1 = b.state("c1", c);
|
||||
b.initial(top);
|
||||
b.initial(a);
|
||||
b.initial(a1);
|
||||
b.initial(c1);
|
||||
const auto hop = b.event("hop");
|
||||
b.on_exit(a1, t.exit("a1"));
|
||||
b.on_exit(a, t.exit("a"));
|
||||
b.on_exit(top, t.exit("top"));
|
||||
b.on_entry(c, t.enter("c"));
|
||||
b.on_entry(c1, t.enter("c1"));
|
||||
b.transition(a1, hop, c1);
|
||||
|
||||
auto def = b.build();
|
||||
Void::Testing::expect(def.has_value());
|
||||
Machine m{*def, MachineOptions{.own_worker = false}};
|
||||
m.start();
|
||||
t.log.clear();
|
||||
|
||||
m.post(Event{hop, {}});
|
||||
m.run_pending();
|
||||
|
||||
// LCA(a1, c1) = top: exit a1, a (innermost first; top stays),
|
||||
// then enter c, c1 (outermost first).
|
||||
const std::vector<std::string> expected{"-a1", "-a", "+c", "+c1"};
|
||||
Void::Testing::expect(t.log == expected);
|
||||
Void::Testing::expect(m.is_in("top"));
|
||||
Void::Testing::expect(m.is_in("c1"));
|
||||
}
|
||||
|
||||
Void::Testing::Test hierarchy_inner_transition_wins_over_outer()
|
||||
{
|
||||
Builder b;
|
||||
auto outer = b.state("outer");
|
||||
auto in1 = b.state("in1", outer);
|
||||
auto in2 = b.state("in2", outer);
|
||||
auto away = b.state("away");
|
||||
b.initial(outer);
|
||||
b.initial(in1);
|
||||
const auto go = b.event("go");
|
||||
b.transition(outer, go, away); // outer handler
|
||||
b.transition(in1, go, in2); // inner handler must win
|
||||
|
||||
auto def = b.build();
|
||||
Void::Testing::expect(def.has_value());
|
||||
Machine m{*def, MachineOptions{.own_worker = false}};
|
||||
m.start();
|
||||
m.post(Event{go, {}});
|
||||
m.run_pending();
|
||||
|
||||
Void::Testing::expect(m.is_in("in2"));
|
||||
Void::Testing::expect(!m.is_in("away"));
|
||||
}
|
||||
|
||||
Void::Testing::Test hierarchy_outer_handles_when_inner_does_not()
|
||||
{
|
||||
Builder b;
|
||||
auto outer = b.state("outer");
|
||||
auto in1 = b.state("in1", outer);
|
||||
auto away = b.state("away");
|
||||
b.initial(outer);
|
||||
b.initial(in1);
|
||||
const auto leave = b.event("leave");
|
||||
b.transition(outer, leave, away);
|
||||
|
||||
auto def = b.build();
|
||||
Void::Testing::expect(def.has_value());
|
||||
Machine m{*def, MachineOptions{.own_worker = false}};
|
||||
m.start();
|
||||
m.post(Event{leave, {}});
|
||||
m.run_pending();
|
||||
|
||||
Void::Testing::expect(m.is_in("away"));
|
||||
Void::Testing::expect(!m.is_in("outer"));
|
||||
}
|
||||
|
||||
Void::Testing::Test hierarchy_shallow_history_restores_child()
|
||||
{
|
||||
Builder b;
|
||||
auto work = b.state("work");
|
||||
auto w1 = b.state("w1", work);
|
||||
auto w2 = b.state("w2", work);
|
||||
auto pause = b.state("pause");
|
||||
b.initial(work);
|
||||
b.initial(w1);
|
||||
b.history(work, History::Shallow);
|
||||
const auto next = b.event("next");
|
||||
const auto stop_ = b.event("stop");
|
||||
const auto resume = b.event("resume");
|
||||
b.transition(w1, next, w2);
|
||||
b.transition(work, stop_, pause);
|
||||
b.transition(pause, resume, work);
|
||||
|
||||
auto def = b.build();
|
||||
Void::Testing::expect(def.has_value());
|
||||
Machine m{*def, MachineOptions{.own_worker = false}};
|
||||
m.start();
|
||||
|
||||
m.post(Event{next, {}}); // w1 -> w2
|
||||
m.post(Event{stop_, {}}); // -> pause (records w2)
|
||||
m.run_pending();
|
||||
Void::Testing::expect(m.is_in("pause"));
|
||||
|
||||
m.post(Event{resume, {}}); // -> work, history -> w2
|
||||
m.run_pending();
|
||||
Void::Testing::expect(m.is_in("w2"));
|
||||
Void::Testing::expect(!m.is_in("w1"));
|
||||
}
|
||||
|
||||
Void::Testing::Test hierarchy_deep_history_restores_leaves()
|
||||
{
|
||||
Builder b;
|
||||
auto work = b.state("work");
|
||||
auto sub = b.state("sub", work);
|
||||
auto s1 = b.state("s1", sub);
|
||||
auto s2 = b.state("s2", sub);
|
||||
auto pause = b.state("pause");
|
||||
b.initial(work);
|
||||
b.initial(sub);
|
||||
b.initial(s1);
|
||||
b.history(work, History::Deep);
|
||||
const auto next = b.event("next");
|
||||
const auto stop_ = b.event("stop");
|
||||
const auto resume = b.event("resume");
|
||||
b.transition(s1, next, s2);
|
||||
b.transition(work, stop_, pause);
|
||||
b.transition(pause, resume, work);
|
||||
|
||||
auto def = b.build();
|
||||
Void::Testing::expect(def.has_value());
|
||||
Machine m{*def, MachineOptions{.own_worker = false}};
|
||||
m.start();
|
||||
|
||||
m.post(Event{next, {}});
|
||||
m.post(Event{stop_, {}});
|
||||
m.run_pending();
|
||||
Void::Testing::expect(m.is_in("pause"));
|
||||
|
||||
m.post(Event{resume, {}});
|
||||
m.run_pending();
|
||||
// Deep history re-activates the full chain down to s2 (shallow would
|
||||
// have restored sub and then default-descended back into s1).
|
||||
Void::Testing::expect(m.is_in("s2"));
|
||||
Void::Testing::expect(!m.is_in("s1"));
|
||||
}
|
||||
|
||||
Void::Testing::Test hierarchy_no_history_reenters_initial()
|
||||
{
|
||||
Builder b;
|
||||
auto work = b.state("work");
|
||||
auto w1 = b.state("w1", work);
|
||||
auto w2 = b.state("w2", work);
|
||||
auto pause = b.state("pause");
|
||||
b.initial(work);
|
||||
b.initial(w1);
|
||||
const auto next = b.event("next");
|
||||
const auto stop_ = b.event("stop");
|
||||
const auto resume = b.event("resume");
|
||||
b.transition(w1, next, w2);
|
||||
b.transition(work, stop_, pause);
|
||||
b.transition(pause, resume, work);
|
||||
|
||||
auto def = b.build();
|
||||
Void::Testing::expect(def.has_value());
|
||||
Machine m{*def, MachineOptions{.own_worker = false}};
|
||||
m.start();
|
||||
|
||||
m.post(Event{next, {}});
|
||||
m.post(Event{stop_, {}});
|
||||
m.post(Event{resume, {}});
|
||||
m.run_pending();
|
||||
Void::Testing::expect(m.is_in("w1")); // back to initial, not w2
|
||||
}
|
||||
@@ -1,186 +0,0 @@
|
||||
#include <Void/Fsm/Definition.hpp>
|
||||
#include <Void/Fsm/Machine.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
using namespace Void::Fsm;
|
||||
|
||||
namespace
|
||||
{
|
||||
// work{ sub{ s1, s2 } }, pause — with deep history on work.
|
||||
std::shared_ptr<const MachineDef> make_def()
|
||||
{
|
||||
Builder b;
|
||||
auto work = b.state("work");
|
||||
auto sub = b.state("sub", work);
|
||||
auto s1 = b.state("s1", sub);
|
||||
auto s2 = b.state("s2", sub);
|
||||
auto pause = b.state("pause");
|
||||
b.initial(work);
|
||||
b.initial(sub);
|
||||
b.initial(s1);
|
||||
b.history(work, History::Deep);
|
||||
b.transition(s1, b.event("next"), s2);
|
||||
b.transition(work, b.event("stop"), pause);
|
||||
b.transition(pause, b.event("resume"), work);
|
||||
auto def = b.build();
|
||||
Void::Testing::expect(def.has_value());
|
||||
return *def;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
Void::Testing::Test serialize_captures_leaves_by_name()
|
||||
{
|
||||
auto def = make_def();
|
||||
Machine m{def, MachineOptions{.own_worker = false}};
|
||||
m.start();
|
||||
m.post(Event{*def->event_id("next"), {}});
|
||||
m.run_pending();
|
||||
|
||||
const auto json = m.serialize_state();
|
||||
Void::Testing::expect(json.is_object());
|
||||
const auto& leaves = json["leaves"].as_array();
|
||||
Void::Testing::expect_eq(leaves.size(), std::size_t{1});
|
||||
Void::Testing::expect_eq(leaves[0].as_string(), std::string{"s2"});
|
||||
}
|
||||
|
||||
Void::Testing::Test serialize_restore_round_trip()
|
||||
{
|
||||
auto def = make_def();
|
||||
Void::Json::Value saved;
|
||||
{
|
||||
Machine m{def, MachineOptions{.own_worker = false}};
|
||||
m.start();
|
||||
m.post(Event{*def->event_id("next"), {}}); // s1 -> s2
|
||||
m.run_pending();
|
||||
saved = m.serialize_state();
|
||||
m.stop();
|
||||
}
|
||||
|
||||
Machine restored{def, MachineOptions{.own_worker = false}};
|
||||
Void::Testing::expect(restored.restore_state(saved).has_value());
|
||||
restored.start();
|
||||
|
||||
Void::Testing::expect(restored.is_in("s2"));
|
||||
Void::Testing::expect(restored.is_in("work"));
|
||||
Void::Testing::expect(!restored.is_in("s1"));
|
||||
|
||||
// The restored machine behaves identically: stop/resume goes back
|
||||
// to s2 via deep history captured in the serialized state.
|
||||
restored.post(Event{*def->event_id("stop"), {}});
|
||||
restored.post(Event{*def->event_id("resume"), {}});
|
||||
restored.run_pending();
|
||||
Void::Testing::expect(restored.is_in("s2"));
|
||||
}
|
||||
|
||||
Void::Testing::Test serialize_preserves_history_records()
|
||||
{
|
||||
auto def = make_def();
|
||||
Void::Json::Value saved;
|
||||
{
|
||||
Machine m{def, MachineOptions{.own_worker = false}};
|
||||
m.start();
|
||||
m.post(Event{*def->event_id("next"), {}}); // -> s2
|
||||
m.post(Event{*def->event_id("stop"), {}}); // -> pause, hist {s2}
|
||||
m.run_pending();
|
||||
saved = m.serialize_state();
|
||||
m.stop();
|
||||
}
|
||||
|
||||
Machine restored{def, MachineOptions{.own_worker = false}};
|
||||
Void::Testing::expect(restored.restore_state(saved).has_value());
|
||||
restored.start();
|
||||
Void::Testing::expect(restored.is_in("pause"));
|
||||
|
||||
restored.post(Event{*def->event_id("resume"), {}});
|
||||
restored.run_pending();
|
||||
Void::Testing::expect(restored.is_in("s2")); // history survived
|
||||
}
|
||||
|
||||
Void::Testing::Test restore_rejects_running_machine_and_garbage()
|
||||
{
|
||||
auto def = make_def();
|
||||
Machine m{def, MachineOptions{.own_worker = false}};
|
||||
Void::Testing::expect(
|
||||
!m.restore_state(Void::Json::Value{42}).has_value());
|
||||
m.start();
|
||||
const auto state = m.serialize_state();
|
||||
Void::Testing::expect(!m.restore_state(state).has_value());
|
||||
}
|
||||
|
||||
Void::Testing::Test restore_with_unknown_states_falls_back_to_initial()
|
||||
{
|
||||
auto def = make_def();
|
||||
auto bogus = Void::Json::parse(
|
||||
R"({"__fsm":1,"leaves":["no_such_state"],"history":{}})");
|
||||
Void::Testing::expect(bogus.has_value());
|
||||
|
||||
Machine m{def, MachineOptions{.own_worker = false}};
|
||||
Void::Testing::expect(m.restore_state(*bogus).has_value());
|
||||
m.start();
|
||||
Void::Testing::expect(m.is_in("s1")); // initial configuration
|
||||
}
|
||||
|
||||
// ── hot definition swap ───────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test swap_same_names_keeps_configuration()
|
||||
{
|
||||
auto def = make_def();
|
||||
Machine m{def, MachineOptions{.own_worker = false}};
|
||||
m.start();
|
||||
m.post(Event{*def->event_id("next"), {}}); // -> s2
|
||||
m.run_pending();
|
||||
|
||||
int entries = 0;
|
||||
// New definition: same state names, one extra transition + an entry
|
||||
// probe that must NOT run during a seamless swap.
|
||||
Builder b;
|
||||
auto work = b.state("work");
|
||||
auto sub = b.state("sub", work);
|
||||
auto s1 = b.state("s1", sub);
|
||||
auto s2 = b.state("s2", sub);
|
||||
auto pause = b.state("pause");
|
||||
b.initial(work);
|
||||
b.initial(sub);
|
||||
b.initial(s1);
|
||||
b.on_entry(s2, SyncAction{[&](Machine&, const Event&) {
|
||||
++entries;
|
||||
}});
|
||||
b.transition(s2, b.event("back"), s1); // new behavior
|
||||
b.transition(work, b.event("stop"), pause);
|
||||
auto next_def = b.build();
|
||||
Void::Testing::expect(next_def.has_value());
|
||||
|
||||
m.swap_definition(*next_def);
|
||||
m.run_pending();
|
||||
|
||||
Void::Testing::expect(m.is_in("s2")); // configuration survived
|
||||
Void::Testing::expect_eq(entries, 0); // no re-entry side effects
|
||||
|
||||
// New transition is live.
|
||||
m.post(Event{*(*next_def)->event_id("back"), {}});
|
||||
m.run_pending();
|
||||
Void::Testing::expect(m.is_in("s1"));
|
||||
}
|
||||
|
||||
Void::Testing::Test swap_with_missing_states_reenters_initial()
|
||||
{
|
||||
auto def = make_def();
|
||||
Machine m{def, MachineOptions{.own_worker = false}};
|
||||
m.start();
|
||||
m.post(Event{*def->event_id("next"), {}}); // -> s2
|
||||
m.run_pending();
|
||||
|
||||
Builder b;
|
||||
(void)b.state("fresh_a");
|
||||
(void)b.state("fresh_b");
|
||||
auto next_def = b.build();
|
||||
Void::Testing::expect(next_def.has_value());
|
||||
|
||||
m.swap_definition(*next_def);
|
||||
m.run_pending();
|
||||
Void::Testing::expect(m.is_in("fresh_a"));
|
||||
}
|
||||
@@ -1,114 +0,0 @@
|
||||
#include <Void/StateMachine/StateMachine.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <string>
|
||||
|
||||
// ── Simple traffic-light FSM ──────────────────────────────────────────────────
|
||||
|
||||
struct Red {};
|
||||
struct Green {};
|
||||
struct Yellow {};
|
||||
|
||||
struct GoEvent {};
|
||||
struct SlowEvent {};
|
||||
struct StopEvent {};
|
||||
|
||||
using TrafficLight = Void::StateMachine::StateMachine<
|
||||
std::tuple<Red, Green, Yellow>,
|
||||
std::tuple<
|
||||
Void::StateMachine::Transition<Red, GoEvent, Green>,
|
||||
Void::StateMachine::Transition<Green, SlowEvent, Yellow>,
|
||||
Void::StateMachine::Transition<Yellow, StopEvent, Red>
|
||||
>>;
|
||||
|
||||
Void::Testing::Test initial_state_is_first()
|
||||
{
|
||||
TrafficLight fsm;
|
||||
Void::Testing::expect(fsm.is<Red>());
|
||||
}
|
||||
|
||||
Void::Testing::Test valid_transition_taken()
|
||||
{
|
||||
TrafficLight fsm;
|
||||
const bool ok = fsm.send(GoEvent{});
|
||||
Void::Testing::expect(ok);
|
||||
Void::Testing::expect(fsm.is<Green>());
|
||||
}
|
||||
|
||||
Void::Testing::Test invalid_event_not_taken()
|
||||
{
|
||||
TrafficLight fsm;
|
||||
const bool ok = fsm.send(StopEvent{}); // Red has no StopEvent arc
|
||||
Void::Testing::expect(!ok);
|
||||
Void::Testing::expect(fsm.is<Red>());
|
||||
}
|
||||
|
||||
Void::Testing::Test full_cycle()
|
||||
{
|
||||
TrafficLight fsm;
|
||||
Void::Testing::expect(fsm.send(GoEvent{}));
|
||||
Void::Testing::expect(fsm.send(SlowEvent{}));
|
||||
Void::Testing::expect(fsm.send(StopEvent{}));
|
||||
Void::Testing::expect(fsm.is<Red>());
|
||||
}
|
||||
|
||||
Void::Testing::Test entry_callback_fired()
|
||||
{
|
||||
TrafficLight fsm;
|
||||
bool fired = false;
|
||||
fsm.on_enter<Green>([&](const Green&) { fired = true; });
|
||||
fsm.send(GoEvent{});
|
||||
Void::Testing::expect(fired);
|
||||
}
|
||||
|
||||
Void::Testing::Test exit_callback_fired()
|
||||
{
|
||||
TrafficLight fsm;
|
||||
bool fired = false;
|
||||
fsm.on_exit<Red>([&](const Red&) { fired = true; });
|
||||
fsm.send(GoEvent{});
|
||||
Void::Testing::expect(fired);
|
||||
}
|
||||
|
||||
Void::Testing::Test callbacks_not_fired_on_invalid_transition()
|
||||
{
|
||||
TrafficLight fsm;
|
||||
bool entry = false, exit_cb = false;
|
||||
fsm.on_enter<Green>([&](const Green&) { entry = true; });
|
||||
fsm.on_exit<Red>([&](const Red&) { exit_cb = true; });
|
||||
fsm.send(StopEvent{}); // invalid from Red
|
||||
Void::Testing::expect(!entry);
|
||||
Void::Testing::expect(!exit_cb);
|
||||
}
|
||||
|
||||
Void::Testing::Test state_index_matches_variant_order()
|
||||
{
|
||||
TrafficLight fsm;
|
||||
Void::Testing::expect_eq(fsm.state_index(), std::size_t{0}); // Red is first
|
||||
fsm.send(GoEvent{});
|
||||
Void::Testing::expect_eq(fsm.state_index(), std::size_t{1}); // Green is second
|
||||
}
|
||||
|
||||
// ── Two-state toggle ──────────────────────────────────────────────────────────
|
||||
|
||||
struct Off {};
|
||||
struct On {};
|
||||
struct Toggle {};
|
||||
|
||||
using Switch = Void::StateMachine::StateMachine<
|
||||
std::tuple<Off, On>,
|
||||
std::tuple<
|
||||
Void::StateMachine::Transition<Off, Toggle, On>,
|
||||
Void::StateMachine::Transition<On, Toggle, Off>
|
||||
>>;
|
||||
|
||||
Void::Testing::Test toggle_back_and_forth()
|
||||
{
|
||||
Switch sw;
|
||||
Void::Testing::expect(sw.is<Off>());
|
||||
sw.send(Toggle{});
|
||||
Void::Testing::expect(sw.is<On>());
|
||||
sw.send(Toggle{});
|
||||
Void::Testing::expect(sw.is<Off>());
|
||||
}
|
||||
Reference in new issue
Block a user