FSM (2): declarative sub-machine continuations (startMachine + Continue<R>)
A state can now launch a full sub-FSM and have the engine resume into a
named state that handles the result, instead of awaiting+branching by hand:
co_return startMachine<Login, AfterLogin>(user, tries);
struct AfterLogin : Continue<bool> { // Login = Machine<Login,bool>
Task<Step> on_success(bool ok) override {
co_return ok ? next<Home>() : next<Locked>(); }
Task<Step> on_failure(FsmError e) override { co_return fail(e.message); }
};
- Sub runs on the parent's shared executor/event-mailbox/services (reuses
run_child); seed data is forwarded to Sub's constructor.
- The engine dispatches on its own: on entry with a pending result it calls
the state's resume(), which Continue<R> overrides to pick
on_success(R)/on_failure(FsmError) by the outcome. Continue<void> takes a
nullary on_success(). A Continue handler may itself return another
startMachine (chaining) or any Step.
- Type-safe: startMachine<Sub, Next> static_asserts Next derives
Continue<Sub::result_type> and is in States<>.
Mechanics: Step gains Kind::Launch carrying the target + a type-erased
launcher (a coroutine that runs the sub and maps its Outcome to a
LaunchResult); drive() awaits it, stashes the result, and the entered
state's resume() consumes it. StateBase::resume defaults to run().
5 new tests (SubMachine): success/failure dispatch, void-result nullary
on_success, chained startMachine through Continue states, and that the sub
shares the parent's event mailbox. 987 green, ASan+UBSan clean, stable
across 10 runs, -Werror clean.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
fedc14b0e3
commit
b34226369a
7 files changed
+447
-3
No files matched your search
@@ -0,0 +1,87 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Async/Task.hpp>
|
||||
#include <Void/Fsm/Detail/Engine.hpp>
|
||||
#include <Void/Fsm/Step.hpp>
|
||||
|
||||
#include <any>
|
||||
#include <utility>
|
||||
|
||||
namespace Void::Fsm::Detail
|
||||
{
|
||||
namespace Coro = Void::Coro;
|
||||
|
||||
// Base for a state that resumes from a sub-machine launched via
|
||||
// startMachine<Sub, This>(). `StateT` is the owning machine's nested State
|
||||
// (so the continuation inherits self()/next/fail/...); `SubResult` is the
|
||||
// sub-machine's result_type. The engine enters this state carrying the
|
||||
// sub's LaunchResult and calls resume(), which dispatches to on_success /
|
||||
// on_failure — the FSM "finds on its own which method to call".
|
||||
//
|
||||
// Machine exposes it as `Continue<R>`; users derive it and implement
|
||||
// on_success(R) (and optionally on_failure).
|
||||
template <typename StateT, typename SubResult>
|
||||
class Continuation : public StateT
|
||||
{
|
||||
public:
|
||||
|
||||
Coro::Task<Step> resume(LaunchResult lr) final
|
||||
{
|
||||
if (lr.ok) {
|
||||
co_return co_await on_success(
|
||||
std::any_cast<SubResult>(std::move(lr.value)));
|
||||
}
|
||||
co_return co_await on_failure(std::move(lr.error));
|
||||
}
|
||||
|
||||
Coro::Task<Step> run() override
|
||||
{
|
||||
co_return this->fail(
|
||||
"Continue<R> state entered without a sub-machine result "
|
||||
"(reach it via startMachine<Sub, This>())");
|
||||
}
|
||||
|
||||
protected:
|
||||
|
||||
/// The sub-machine succeeded with `result`.
|
||||
virtual Coro::Task<Step> on_success(SubResult result) = 0;
|
||||
|
||||
/// The sub-machine failed. Default: fail the parent with the same
|
||||
/// message; override to recover.
|
||||
virtual Coro::Task<Step> on_failure(FsmError error)
|
||||
{
|
||||
co_return this->fail(std::move(error.message));
|
||||
}
|
||||
};
|
||||
|
||||
// Specialisation for a void-result sub-machine: on_success() takes no
|
||||
// argument.
|
||||
template <typename StateT> class Continuation<StateT, void> : public StateT
|
||||
{
|
||||
public:
|
||||
|
||||
Coro::Task<Step> resume(LaunchResult lr) final
|
||||
{
|
||||
if (lr.ok) {
|
||||
co_return co_await on_success();
|
||||
}
|
||||
co_return co_await on_failure(std::move(lr.error));
|
||||
}
|
||||
|
||||
Coro::Task<Step> run() override
|
||||
{
|
||||
co_return this->fail(
|
||||
"Continue<void> state entered without a sub-machine result "
|
||||
"(reach it via startMachine<Sub, This>())");
|
||||
}
|
||||
|
||||
protected:
|
||||
|
||||
virtual Coro::Task<Step> on_success() = 0;
|
||||
|
||||
virtual Coro::Task<Step> on_failure(FsmError error)
|
||||
{
|
||||
co_return this->fail(std::move(error.message));
|
||||
}
|
||||
};
|
||||
} // namespace Void::Fsm::Detail
|
||||
@@ -54,6 +54,11 @@ namespace Void::Fsm::Detail
|
||||
/// Main body. Default fails (a state must define run() unless it
|
||||
/// is reactive, in which case the engine uses its table).
|
||||
virtual Coro::Task<Step> run();
|
||||
|
||||
/// Entered carrying a sub-machine result (from
|
||||
/// startMachine<Sub, This>()). Default ignores it and runs run();
|
||||
/// Continue<R> states override to dispatch on_success / on_failure.
|
||||
virtual Coro::Task<Step> resume(LaunchResult result);
|
||||
};
|
||||
|
||||
struct EventEnvelope {
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
#include <Void/Async/Task.hpp>
|
||||
#include <Void/Data/Json.hpp>
|
||||
#include <Void/Fsm/Detail/Awaiter.hpp>
|
||||
#include <Void/Fsm/Detail/Continuation.hpp>
|
||||
#include <Void/Fsm/Detail/Engine.hpp>
|
||||
#include <Void/Fsm/Detail/Introspect.hpp>
|
||||
#include <Void/Fsm/Detail/Reactive.hpp>
|
||||
@@ -244,6 +245,24 @@ namespace Void::Fsm
|
||||
return m_machine->template await_any<Es...>();
|
||||
}
|
||||
|
||||
/// Launch a sub-machine `Sub` (constructed from `args`,
|
||||
/// sharing this machine's executor/events/services), then
|
||||
/// transition to `Next` — which must derive
|
||||
/// Continue<Sub::result_type>. When Sub finishes the engine
|
||||
/// calls Next's on_success(result) or on_failure(error):
|
||||
/// co_return startMachine<Login, AfterLogin>(user, 3);
|
||||
template <typename Sub, typename Next, typename... Args>
|
||||
[[nodiscard]] Step startMachine(Args&&... args) const
|
||||
{
|
||||
static_assert(
|
||||
std::is_base_of_v<
|
||||
Continue<typename Sub::result_type>, Next>,
|
||||
"startMachine<Sub, Next>: Next must derive "
|
||||
"Continue<Sub::result_type>");
|
||||
return m_machine->template start_machine<Sub, Next>(
|
||||
std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
template <typename S> [[nodiscard]] bool has_state() const
|
||||
{
|
||||
return m_machine->template has_state<S>();
|
||||
@@ -255,6 +274,23 @@ namespace Void::Fsm
|
||||
Machine* m_machine{nullptr};
|
||||
};
|
||||
|
||||
// ── continuation states ───────────────────────────────────────
|
||||
//
|
||||
// A state that resumes from a launched sub-machine. Reach it with
|
||||
// `co_return startMachine<Sub, Next>(args...)`; the engine runs Sub
|
||||
// then enters Next, dispatching to on_success / on_failure by the
|
||||
// outcome:
|
||||
//
|
||||
// struct AfterLogin : Continue<bool> { // Sub =
|
||||
// Machine<..,bool>
|
||||
// Coro::Task<Step> on_success(bool ok) override {
|
||||
// co_return ok ? next<Home>() : next<Locked>(); }
|
||||
// Coro::Task<Step> on_failure(FsmError e) override {
|
||||
// co_return fail(e.message); }
|
||||
// };
|
||||
template <typename SubResult>
|
||||
using Continue = Detail::Continuation<State, SubResult>;
|
||||
|
||||
// ── reactive (declarative) states ─────────────────────────────
|
||||
//
|
||||
// A reactive state declares a transition table instead of an
|
||||
@@ -617,6 +653,43 @@ namespace Void::Fsm
|
||||
co_return std::move(outcome);
|
||||
}
|
||||
|
||||
/// Build a Launch step: run `Sub` (constructed from `args`) on this
|
||||
/// machine's shared executor, then enter `Next` carrying Sub's
|
||||
/// outcome as a LaunchResult. Reached via State::startMachine.
|
||||
template <typename Sub, typename Next, typename... Args>
|
||||
[[nodiscard]] Step start_machine(Args&&... args)
|
||||
{
|
||||
if constexpr (requires { typename Derived::States; }) {
|
||||
static_assert(
|
||||
Derived::States::template contains<Next>(),
|
||||
"startMachine<Sub, Next>: Next is not in States<...>");
|
||||
}
|
||||
auto launcher =
|
||||
[this,
|
||||
tup = std::make_tuple(std::forward<Args>(
|
||||
args)...)]() mutable -> Coro::Task<LaunchResult> {
|
||||
auto outcome = co_await std::apply(
|
||||
[this](auto&&... a) {
|
||||
return this->template run_child<Sub>(
|
||||
std::forward<decltype(a)>(a)...);
|
||||
},
|
||||
std::move(tup));
|
||||
LaunchResult lr;
|
||||
if (outcome.has_value()) {
|
||||
lr.ok = true;
|
||||
if constexpr (!std::is_void_v<
|
||||
typename Sub::result_type>) {
|
||||
lr.value = std::any{std::move(*outcome)};
|
||||
}
|
||||
} else {
|
||||
lr.ok = false;
|
||||
lr.error = std::move(outcome.error());
|
||||
}
|
||||
co_return lr;
|
||||
};
|
||||
return Step::launch(typeid(Next), std::move(launcher));
|
||||
}
|
||||
|
||||
// ── observation ───────────────────────────────────────────────
|
||||
[[nodiscard]] std::string current_state() const
|
||||
{
|
||||
@@ -847,13 +920,29 @@ namespace Void::Fsm
|
||||
set_current(cur);
|
||||
auto state = it->second();
|
||||
co_await state->on_enter();
|
||||
Step step = co_await state->run();
|
||||
// A state entered via startMachine resumes from the sub's
|
||||
// result (Continue<R> dispatches); otherwise it runs.
|
||||
Step step;
|
||||
if (m_pending_result.has_value()) {
|
||||
LaunchResult pending = std::move(*m_pending_result);
|
||||
m_pending_result.reset();
|
||||
step = co_await state->resume(std::move(pending));
|
||||
} else {
|
||||
step = co_await state->run();
|
||||
}
|
||||
co_await state->on_exit();
|
||||
fire_after(current_state());
|
||||
switch (step.kind()) {
|
||||
case Step::Kind::Transition:
|
||||
cur = step.target();
|
||||
continue;
|
||||
case Step::Kind::Launch:
|
||||
// Run the sub-machine, stash its result, then enter
|
||||
// the Next (Continue<R>) state.
|
||||
m_pending_result.emplace(
|
||||
co_await step.run_launch());
|
||||
cur = step.target();
|
||||
continue;
|
||||
case Step::Kind::Success:
|
||||
if constexpr (std::is_void_v<ResultT>) {
|
||||
co_return Outcome{};
|
||||
@@ -912,6 +1001,10 @@ namespace Void::Fsm
|
||||
// Active child region's path provider (run_region); consulted by
|
||||
// state_path(). Set/cleared on the consumer thread.
|
||||
std::function<std::vector<std::string>()> m_region_probe;
|
||||
|
||||
// Set by a Launch step's sub-machine result; consumed by the next
|
||||
// state's resume() (a Continue<R> dispatch).
|
||||
std::optional<LaunchResult> m_pending_result;
|
||||
};
|
||||
|
||||
} // namespace Void::Fsm
|
||||
@@ -1,16 +1,31 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Async/Task.hpp>
|
||||
|
||||
#include <any>
|
||||
#include <functional>
|
||||
#include <string>
|
||||
#include <typeinfo>
|
||||
#include <utility>
|
||||
|
||||
namespace Void::Fsm
|
||||
{
|
||||
namespace Coro = Void::Coro;
|
||||
|
||||
struct FsmError {
|
||||
std::string message;
|
||||
};
|
||||
|
||||
/// The outcome of a sub-machine launched via startMachine<Sub, Next>():
|
||||
/// `ok` with the result in `value` (a `Sub::result_type`, empty for void),
|
||||
/// or `!ok` with `error`. Delivered to the Next state's Continue<R>
|
||||
/// handlers (on_success / on_failure).
|
||||
struct LaunchResult {
|
||||
bool ok{false};
|
||||
std::any value;
|
||||
FsmError error;
|
||||
};
|
||||
|
||||
enum class Status {
|
||||
Idle, // constructed, not started
|
||||
Running, // worker active
|
||||
@@ -25,7 +40,7 @@ namespace Void::Fsm
|
||||
{
|
||||
public:
|
||||
|
||||
enum class Kind { Transition, Success, Fail };
|
||||
enum class Kind { Transition, Success, Fail, Launch };
|
||||
|
||||
[[nodiscard]] static Step transition(const std::type_info& target)
|
||||
{
|
||||
@@ -35,6 +50,20 @@ namespace Void::Fsm
|
||||
return s;
|
||||
}
|
||||
|
||||
/// Launch a sub-machine, then enter `target` (a Continue<R> state)
|
||||
/// with the sub's LaunchResult. `launcher` runs the sub and yields
|
||||
/// its result; the engine awaits it in drive().
|
||||
[[nodiscard]] static Step
|
||||
launch(const std::type_info& target,
|
||||
std::function<Coro::Task<LaunchResult>()> launcher)
|
||||
{
|
||||
Step s;
|
||||
s.m_kind = Kind::Launch;
|
||||
s.m_target = ⌖
|
||||
s.m_launcher = std::move(launcher);
|
||||
return s;
|
||||
}
|
||||
|
||||
[[nodiscard]] static Step success(std::any result)
|
||||
{
|
||||
Step s;
|
||||
@@ -65,12 +94,19 @@ namespace Void::Fsm
|
||||
return m_error;
|
||||
}
|
||||
|
||||
/// Run the sub-machine for a Launch step (yields its LaunchResult).
|
||||
[[nodiscard]] Coro::Task<LaunchResult> run_launch()
|
||||
{
|
||||
return m_launcher();
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
Kind m_kind{Kind::Fail};
|
||||
const std::type_info* m_target{nullptr};
|
||||
std::any m_result;
|
||||
FsmError m_error;
|
||||
std::function<Coro::Task<LaunchResult>()> m_launcher;
|
||||
};
|
||||
|
||||
} // namespace Void::Fsm
|
||||
Reference in new issue
Block a user