diff --git a/include/Void/Fsm/Detail/Engine.hpp b/include/Void/Fsm/Detail/Engine.hpp index d8dacde..45889d8 100644 --- a/include/Void/Fsm/Detail/Engine.hpp +++ b/include/Void/Fsm/Detail/Engine.hpp @@ -7,15 +7,22 @@ #include #include +#include #include #include +#include #include +#include +#include #include +#include #include +#include #include #include #include #include +#include namespace Void::Fsm::Detail { @@ -79,10 +86,29 @@ namespace Void::Fsm::Detail // Mailbox ops — consumer thread only (called from awaiters that // run on the executor, and from the worker drain). - [[nodiscard]] bool try_take(const std::type_info& type, - std::any& out); - void set_waiter(const std::type_info& type, - std::coroutine_handle<> cont, std::any* slot); + + using TimerId = std::uint64_t; + + /// Pop the oldest buffered event whose type is in `types`. + [[nodiscard]] bool + try_take_any(std::span types, + EventEnvelope& out); + + /// Suspend until an event of one of `types` arrives, or (if + /// `deadline` is set) the deadline passes. `slot` receives the + /// matched event; `*timed_out` is set true on timeout. + void set_waiter( + std::span types, + std::coroutine_handle<> cont, EventEnvelope* slot, + bool* timed_out, + std::optional deadline); + + /// Schedule `on_fire` at `deadline`. Returns an id for + /// cancel_timer. + TimerId add_timer(std::chrono::steady_clock::time_point deadline, + std::function + on_fire); + void cancel_timer(TimerId id); // ── worker lifecycle ───────────────────────────────────────── /// Spawn the worker thread (idempotent). @@ -108,18 +134,44 @@ namespace Void::Fsm::Detail void deliver(EventEnvelope& env); void run_loop(); void wake() noexcept; + void fire_due_timers(); + [[nodiscard]] std::optional + next_deadline() const; Async::ManualExecutor m_executor; Async::MpscQueue m_queue; std::unordered_map> m_buffers; struct Waiter { - const std::type_info* type{nullptr}; + std::vector types; std::coroutine_handle<> cont{}; - std::any* slot{nullptr}; + EventEnvelope* slot{nullptr}; + bool* timed_out{nullptr}; + TimerId timer{0}; + + [[nodiscard]] bool active() const noexcept + { + return static_cast(cont); + } + [[nodiscard]] bool wants(const std::type_info& t) const + { + for (const auto* ty : types) { + if (*ty == t) { + return true; + } + } + return false; + } }; Waiter m_waiter; + struct Timer { + std::chrono::steady_clock::time_point deadline; + std::function on_fire; + }; + std::map m_timers; + TimerId m_next_timer{1}; + std::counting_semaphore<> m_wakeup{0}; std::atomic m_sleeping{false}; std::atomic m_done{false}; diff --git a/include/Void/Fsm/Fsm.hpp b/include/Void/Fsm/Fsm.hpp index abf58d1..b810a4c 100644 --- a/include/Void/Fsm/Fsm.hpp +++ b/include/Void/Fsm/Fsm.hpp @@ -9,7 +9,9 @@ #include #include +#include #include +#include #include #include #include @@ -155,6 +157,14 @@ namespace Void::Fsm return m_machine->template await_event(); } + /// Await E or time out (nullopt on timeout). + template + [[nodiscard]] auto await_event_for( + std::chrono::duration d) const + { + return m_machine->template await_event_for(d); + } + template [[nodiscard]] auto run_child(Args&&... args) const { @@ -173,6 +183,258 @@ namespace Void::Fsm Machine* m_machine{nullptr}; }; + // ── reactive (declarative) states ───────────────────────────── + // + // A reactive state declares a transition table instead of an + // imperative run(): it waits for the declared events (or a + // timeout), checks guards in order, runs actions, and + // transitions. Mix freely with imperative State subclasses. + // + // struct Idle : Reactive { + // void transitions(TransitionBuilder& on) override { + // on.event().guard([](Idle& s, const Go& g){...}) + // .action([](Idle& s, const Go&){...}) + // .to(); + // on.event().to(); + // on.after(5s).to(); + // } + // }; + + struct EventEntry { + const std::type_info* type{nullptr}; + std::function guard; + std::function(Derived&, const std::any&)> + action; + Step step; + std::string target_name; // for introspection + }; + + struct TransitionTable { + std::vector events; + bool has_timeout{false}; + std::chrono::steady_clock::duration timeout_after{}; + Step timeout_step; + }; + + template class EventClause + { + public: + + explicit EventClause(TransitionTable& table) + : m_table(&table) + { + } + + EventClause& + guard(std::function g) + { + m_guard = std::move(g); + return *this; + } + + EventClause& action( + std::function(Derived&, const E&)> a) + { + m_action = std::move(a); + return *this; + } + + EventClause& + action(std::function a) + { + m_action = + [a = std::move(a)](Derived& d, + const E& e) -> Coro::Task { + a(d, e); + co_return; + }; + return *this; + } + + template void to() + { + if constexpr (requires { typename Derived::States; }) { + static_assert( + Derived::States::template contains(), + "to: S is not in this machine's " + "States<...> list"); + } + commit(Step::transition(typeid(S)), + Machine::template state_type_name()); + } + + void finish() + requires std::is_void_v + { + commit(Step::success(std::any{}), "(success)"); + } + template + void finish(V&& value) + requires(!std::is_void_v) + { + commit(Step::success( + std::any{ResultT(std::forward(value))}), + "(success)"); + } + + void fail(std::string message) + { + commit(Step::failure(FsmError{std::move(message)}), + "(fail)"); + } + + private: + + void commit(Step step, std::string target) + { + EventEntry entry; + entry.type = &typeid(E); + if (m_guard) { + entry.guard = [g = std::move(m_guard)]( + Derived& d, const std::any& a) { + return g(d, std::any_cast(a)); + }; + } + if (m_action) { + entry.action = + [a = std::move(m_action)]( + Derived& d, + const std::any& any) -> Coro::Task { + co_await a(d, std::any_cast(any)); + }; + } + entry.step = std::move(step); + entry.target_name = std::move(target); + m_table->events.push_back(std::move(entry)); + } + + TransitionTable* m_table; + std::function m_guard; + std::function(Derived&, const E&)> + m_action; + }; + + class AfterClause + { + public: + + AfterClause(TransitionTable& table, + std::chrono::steady_clock::duration after) + : m_table(&table), m_after(after) + { + } + + template void to() + { + if constexpr (requires { typename Derived::States; }) { + static_assert( + Derived::States::template contains(), + "after().to: S not in States<...>"); + } + m_table->has_timeout = true; + m_table->timeout_after = m_after; + m_table->timeout_step = Step::transition(typeid(S)); + } + + void fail(std::string message) + { + m_table->has_timeout = true; + m_table->timeout_after = m_after; + m_table->timeout_step = + Step::failure(FsmError{std::move(message)}); + } + + private: + + TransitionTable* m_table; + std::chrono::steady_clock::duration m_after; + }; + + class TransitionBuilder + { + public: + + explicit TransitionBuilder(TransitionTable& table) + : m_table(&table) + { + } + + template [[nodiscard]] EventClause event() + { + return EventClause{*m_table}; + } + + template + [[nodiscard]] AfterClause + after(std::chrono::duration d) + { + return AfterClause{ + *m_table, + std::chrono::duration_cast< + std::chrono::steady_clock::duration>(d)}; + } + + private: + + TransitionTable* m_table; + }; + + class Reactive : public State + { + public: + + [[nodiscard]] Detail::StateKind + kind() const noexcept override + { + return Detail::StateKind::Reactive; + } + + /// Declare this state's event/timeout transitions. + virtual void transitions(TransitionBuilder& on) = 0; + + Coro::Task run() final + { + TransitionTable table; + { + TransitionBuilder builder{table}; + transitions(builder); + } + std::vector types; + types.reserve(table.events.size()); + for (const auto& e : table.events) { + types.push_back(e.type); + } + for (;;) { + std::optional + deadline; + if (table.has_timeout) { + deadline = std::chrono::steady_clock::now() + + table.timeout_after; + } + auto ev = co_await this->machine().await_any_event( + types, deadline); + if (!ev) { + co_return std::move(table.timeout_step); + } + Derived& d = this->self(); + bool matched = false; + for (auto& e : table.events) { + if (*e.type != *ev->type) { + continue; + } + if (e.guard && !e.guard(d, ev->value)) { + continue; + } + if (e.action) { + co_await e.action(d, ev->value); + } + co_return std::move(e.step); + } + (void)matched; // unmatched event is dropped + } + } + }; + // ── construction ────────────────────────────────────────────── explicit Machine(Options options = {}) : m_options(options) { @@ -323,22 +585,98 @@ namespace Void::Fsm { struct Awaiter { Detail::ExecutionContext* ctx; - std::any slot; + std::array types; + Detail::EventEnvelope env; [[nodiscard]] bool await_ready() { - return ctx->try_take(typeid(E), slot); + return ctx->try_take_any(types, env); } void await_suspend(std::coroutine_handle<> h) { - ctx->set_waiter(typeid(E), h, &slot); + ctx->set_waiter(types, h, &env, nullptr, + std::nullopt); } [[nodiscard]] E await_resume() { - return std::any_cast(std::move(slot)); + return std::any_cast(std::move(env.value)); } }; - return Awaiter{m_ctx.get(), {}}; + return Awaiter{m_ctx.get(), {&typeid(E)}, {}}; + } + + /// Await an event of type E or time out after `duration`; + /// returns std::nullopt on timeout. + template + [[nodiscard]] auto + await_event_for(std::chrono::duration duration) + { + struct Awaiter { + Detail::ExecutionContext* ctx; + std::array types; + Detail::EventEnvelope env; + bool timed_out{false}; + std::chrono::steady_clock::time_point deadline; + + [[nodiscard]] bool await_ready() + { + return ctx->try_take_any(types, env); + } + void await_suspend(std::coroutine_handle<> h) + { + ctx->set_waiter(types, h, &env, &timed_out, + deadline); + } + [[nodiscard]] std::optional await_resume() + { + if (timed_out) { + return std::nullopt; + } + return std::any_cast(std::move(env.value)); + } + }; + return Awaiter{m_ctx.get(), + {&typeid(E)}, + {}, + false, + std::chrono::steady_clock::now() + duration}; + } + + /// Await any of several event types (optional deadline); used + /// by reactive states. Returns the matched envelope or nullopt + /// on timeout. + [[nodiscard]] auto await_any_event( + std::vector types, + std::optional deadline) + { + struct Awaiter { + Detail::ExecutionContext* ctx; + std::vector types; + Detail::EventEnvelope env; + bool timed_out{false}; + std::optional + deadline; + + [[nodiscard]] bool await_ready() + { + return ctx->try_take_any(types, env); + } + void await_suspend(std::coroutine_handle<> h) + { + ctx->set_waiter(types, h, &env, &timed_out, + deadline); + } + [[nodiscard]] std::optional + await_resume() + { + if (timed_out) { + return std::nullopt; + } + return std::move(env); + } + }; + return Awaiter{ + m_ctx.get(), std::move(types), {}, false, deadline}; } // ── nesting ─────────────────────────────────────────────────── @@ -459,6 +797,16 @@ namespace Void::Fsm return nullptr; } + template + [[nodiscard]] static std::string state_type_name() + { +#ifdef VOID_HAS_FSM_REFLECTION + return std::string{std::meta::identifier_of(^^S)}; +#else + return typeid(S).name(); +#endif + } + template [[nodiscard]] std::string state_name() { #ifdef VOID_HAS_FSM_REFLECTION diff --git a/src/Fsm/Engine.cpp b/src/Fsm/Engine.cpp index 5a327a4..df01bed 100644 --- a/src/Fsm/Engine.cpp +++ b/src/Fsm/Engine.cpp @@ -21,51 +21,124 @@ namespace Void::Fsm::Detail wake(); } - bool ExecutionContext::try_take(const std::type_info& type, std::any& out) + bool ExecutionContext::try_take_any( + std::span types, EventEnvelope& out) { - const auto it = m_buffers.find(std::type_index{type}); - if (it == m_buffers.end() || it->second.empty()) { - return false; + for (const auto* ty : types) { + const auto it = m_buffers.find(std::type_index{*ty}); + if (it != m_buffers.end() && !it->second.empty()) { + out.type = ty; + out.value = std::move(it->second.front()); + it->second.pop_front(); + return true; + } } - out = std::move(it->second.front()); - it->second.pop_front(); - return true; + return false; } - void ExecutionContext::set_waiter(const std::type_info& type, - std::coroutine_handle<> - cont, - std::any* slot) + void ExecutionContext::set_waiter( + std::span types, + std::coroutine_handle<> cont, EventEnvelope* slot, bool* timed_out, + std::optional deadline) { - m_waiter.type = &type; + m_waiter.types.assign(types.begin(), types.end()); m_waiter.cont = cont; m_waiter.slot = slot; + m_waiter.timed_out = timed_out; + m_waiter.timer = 0; + if (deadline.has_value()) { + m_waiter.timer = add_timer(*deadline, [this] { + // Timeout: resume the waiter with timed_out set. + if (!m_waiter.active()) { + return; + } + if (m_waiter.timed_out != nullptr) { + *m_waiter.timed_out = true; + } + auto cont2 = m_waiter.cont; + m_waiter = Waiter{}; + m_executor.post(cont2); + }); + } + } + + ExecutionContext::TimerId ExecutionContext::add_timer( + std::chrono::steady_clock::time_point deadline, + std::function + on_fire) + { + const TimerId id = m_next_timer++; + m_timers.emplace(id, Timer{deadline, std::move(on_fire)}); + return id; + } + + void ExecutionContext::cancel_timer(TimerId id) + { + if (id != 0) { + m_timers.erase(id); + } + } + + std::optional + ExecutionContext::next_deadline() const + { + std::optional next; + for (const auto& [id, timer] : m_timers) { + if (!next.has_value() || timer.deadline < *next) { + next = timer.deadline; + } + } + return next; + } + + void ExecutionContext::fire_due_timers() + { + if (m_timers.empty()) { + return; + } + const auto now = std::chrono::steady_clock::now(); + std::vector> due; + for (auto it = m_timers.begin(); it != m_timers.end();) { + if (it->second.deadline <= now) { + due.push_back(std::move(it->second.on_fire)); + it = m_timers.erase(it); + } else { + ++it; + } + } + for (auto& fn : due) { + if (fn) { + fn(); + } + } } void ExecutionContext::deliver(EventEnvelope& env) { - auto& buffer = m_buffers[std::type_index{*env.type}]; - buffer.push_back(std::move(env.value)); - - // Resume a matching waiter, if any. - if (m_waiter.type != nullptr && *m_waiter.type == *env.type && - !buffer.empty()) { - *m_waiter.slot = std::move(buffer.front()); - buffer.pop_front(); + // Match a waiting state first (lets a multi-type waiter receive an + // event without it ever sitting in a buffer). + if (m_waiter.active() && m_waiter.wants(*env.type)) { + *m_waiter.slot = std::move(env); + cancel_timer(m_waiter.timer); auto cont = m_waiter.cont; m_waiter = Waiter{}; m_executor.post(cont); + return; } + // Otherwise buffer for a later await. + m_buffers[std::type_index{*env.type}].push_back(std::move(env.value)); } std::size_t ExecutionContext::pump() { std::size_t work = 0; + fire_due_timers(); while (auto env = m_queue.try_pop()) { deliver(*env); ++work; } work += m_executor.drain(); + fire_due_timers(); return work; } @@ -121,7 +194,12 @@ namespace Void::Fsm::Detail m_sleeping.store(false, std::memory_order_release); continue; } - m_wakeup.acquire(); + // Park until woken, or until the earliest timer is due. + 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); } } diff --git a/tests/standalone/Fsm/Reactive.cpp b/tests/standalone/Fsm/Reactive.cpp new file mode 100644 index 0000000..76f91aa --- /dev/null +++ b/tests/standalone/Fsm/Reactive.cpp @@ -0,0 +1,172 @@ +#include +#include +#include + +#include +#include +#include +#include + +using Void::Coro::Task; +using Void::Fsm::MachineOptions; +using Void::Fsm::Step; +using namespace std::chrono_literals; + +namespace +{ + struct Go { + int amount; + }; + struct Stop { + }; + + // A declarative machine: Idle reacts to events with guards/actions; on + // timeout it bails out. + class Gate : public Void::Fsm::Machine + { + public: + + int total = 0; + std::vector trace; + + struct Idle : Reactive { + void transitions(TransitionBuilder& on) override + { + // Guarded: only positive amounts advance. + on.event() + .guard( + [](Gate&, const Go& g) { return g.amount > 0; }) + .action([](Gate& m, const Go& g) { + m.total += g.amount; + m.trace.push_back("go" + + std::to_string(g.amount)); + }) + .template to(); + on.event().template to(); + on.after(10s).fail("idle timeout"); + } + }; + + // Imperative terminal state: reports the accumulated total. + struct Done : State { + Task run() override + { + co_return succeed(self().total); + } + }; + + using States = Void::Fsm::States; + + Gate() {} // own worker + }; +} // namespace + +// Mixes a reactive (declarative, guarded) state with an imperative one. +Void::Testing::Test reactive_guard_and_action() +{ + Gate fsm; + fsm.start(); + fsm.post(Go{5}); + fsm.post(Go{-1}); // blocked by guard, dropped + fsm.post(Go{3}); + fsm.post(Stop{}); // -> Done -> succeed(total) + + const auto outcome = fsm.wait(); + Void::Testing::expect(outcome.has_value()); + Void::Testing::expect_eq(*outcome, 8); // 5 + 3, the -1 guarded out + const std::vector expected{"go5", "go3"}; + Void::Testing::expect(fsm.trace == expected); +} + +// ── timeouts +// ────────────────────────────────────────────────────────────────── + +namespace +{ + struct Wake { + }; + + // Imperative state using await_event_for: times out → expired. + class Sleeper : public Void::Fsm::Machine + { + public: + + struct Waiting : State { + Task run() override + { + auto w = co_await await_event_for(15ms); + if (w.has_value()) { + co_return succeed(std::string{"woken"}); + } + co_return succeed(std::string{"timed_out"}); + } + }; + using States = Void::Fsm::States; + Sleeper() {} // own worker + }; +} // namespace + +// @tag integration +Void::Testing::Test await_event_for_times_out() +{ + Sleeper fsm; + const auto outcome = fsm.run_blocking(); // no Wake posted + Void::Testing::expect(outcome.has_value()); + Void::Testing::expect_eq(*outcome, std::string{"timed_out"}); +} + +// @tag integration +Void::Testing::Test await_event_for_receives_event() +{ + Sleeper fsm; + fsm.start(); + fsm.post(Wake{}); + const auto outcome = fsm.wait(); + Void::Testing::expect(outcome.has_value()); + Void::Testing::expect_eq(*outcome, std::string{"woken"}); +} + +namespace +{ + // Reactive timeout transition (on.after().to<>). + class Deadline : public Void::Fsm::Machine + { + public: + + struct Pending : Reactive { + void transitions(TransitionBuilder& on) override + { + on.event().template to(); + on.after(15ms).template to(); + } + }; + struct Resolved : State { + Task run() override { co_return succeed(1); } + }; + struct Expired : State { + Task run() override { co_return succeed(2); } + }; + using States = Void::Fsm::States; + Deadline() {} + }; +} // namespace + +// @tag integration +Void::Testing::Test reactive_after_transition_fires() +{ + Deadline fsm; + const auto outcome = fsm.run_blocking(); // no Wake → Expired + Void::Testing::expect(outcome.has_value()); + Void::Testing::expect_eq(*outcome, 2); +} + +// @tag integration +Void::Testing::Test reactive_event_beats_timeout() +{ + Deadline fsm; + fsm.start(); + fsm.post(Wake{}); // arrives before the 15ms deadline + const auto outcome = fsm.wait(); + Void::Testing::expect(outcome.has_value()); + Void::Testing::expect_eq(*outcome, 1); +}