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
@@ -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
|
||||
)
|
||||
Reference in new issue
Block a user