#include #include #include #include #include using Void::Coro::Task; using Void::Fsm::MachineOptions; using Void::Fsm::Step; namespace { // A machine that parks at a named state and exposes its data for // serialize/restore. class Pipeline : public Void::Fsm::Machine { public: using Success = int; struct Data { int processed = 0; std::string stage = "init"; }; Data data; struct Ingest : State { Task run() { co_await await_event(); // park here co_return next(); } }; struct Process : State { Task run() { auto& m = self(); m.data.processed += 1; co_return succeed(m.data.processed); } }; Pipeline() : Void::Fsm::Machine( MachineOptions{.own_worker = false}) { initial(); add(); } protected: void on_serialize(Void::Json::Value& out) const override { out = Void::Json::to_json(data); } void on_restore(const Void::Json::Value& in) override { if (auto r = Void::Json::from_json(in); r.has_value()) { data = std::move(*r); } } }; } // namespace Void::Testing::Test fsm_serialize_captures_state_and_data() { Pipeline fsm; fsm.data.processed = 5; fsm.data.stage = "running"; fsm.start(); fsm.pump(); // enters Ingest, parks on await_event const auto json = fsm.serialize(); Void::Testing::expect_eq(json["state"].as_string(), std::string{"Ingest"}); Void::Testing::expect_eq(json["data"]["processed"].as_int(), std::int64_t{5}); Void::Testing::expect_eq(json["data"]["stage"].as_string(), std::string{"running"}); fsm.stop(); } Void::Testing::Test fsm_restore_resumes_at_named_state() { const auto saved = Void::Json::parse( R"({"state":"Process","data":{"processed":9,"stage":"mid"}})"); Void::Testing::expect(saved.has_value()); Pipeline fsm; const auto r = fsm.restore(*saved); Void::Testing::expect(r.has_value()); // Starts directly at Process (skipping Ingest's event wait), with the // restored data → succeeds with processed+1. const auto outcome = fsm.run_blocking(); Void::Testing::expect(outcome.has_value()); Void::Testing::expect_eq(*outcome, 10); } Void::Testing::Test fsm_restore_rejects_unknown_state_and_running() { const auto bogus = Void::Json::parse(R"({"state":"NoSuch","data":{}})"); Void::Testing::expect(bogus.has_value()); Pipeline fsm; Void::Testing::expect(!fsm.restore(*bogus).has_value()); fsm.start(); Void::Testing::expect(!fsm.restore(*bogus).has_value()); // running fsm.stop(); }