diff --git a/SerialPrograms/Source/CommonFramework/Panels/UI/PanelElements.cpp b/SerialPrograms/Source/CommonFramework/Panels/UI/PanelElements.cpp index 8b8d32b8e7..bbbc9675dd 100644 --- a/SerialPrograms/Source/CommonFramework/Panels/UI/PanelElements.cpp +++ b/SerialPrograms/Source/CommonFramework/Panels/UI/PanelElements.cpp @@ -269,10 +269,10 @@ void start_or_stop_program(ProgramSession& program_session){ std::string error; switch (program_session.current_state()){ case ProgramState::STOPPED: - error = program_session.start_program(); + error = program_session.start_program(ActionSource::UI, std::nullopt); break; case ProgramState::RUNNING: - error = program_session.stop_program(); + error = program_session.stop_program(ActionSource::UI, std::nullopt); break; default:; } diff --git a/SerialPrograms/Source/CommonFramework/ProgramSession.cpp b/SerialPrograms/Source/CommonFramework/ProgramSession.cpp index f4176b9199..344c6648ba 100644 --- a/SerialPrograms/Source/CommonFramework/ProgramSession.cpp +++ b/SerialPrograms/Source/CommonFramework/ProgramSession.cpp @@ -177,6 +177,15 @@ void ProgramSession::set_state(ProgramState state){ m_state.store(state, std::memory_order_relaxed); m_listeners.run_method(&Listener::state_change, state); } +void ProgramSession::mark_started(ActionSource source, std::optional request_id){ + const WallClock now = current_time(); + m_last_state_change.store(now, std::memory_order_relaxed); + m_transitions.started(source, std::move(request_id), now); +} +void ProgramSession::set_finished(){ + m_transitions.finished(current_time()); + set_state(ProgramState::STOPPED); +} void ProgramSession::push_stats(){ m_listeners.run_method( &Listener::stats_update, @@ -185,6 +194,7 @@ void ProgramSession::push_stats(){ ); } void ProgramSession::push_error(const std::string& message){ + m_transitions.error_reported(); m_listeners.run_method(&Listener::error, message); } @@ -227,7 +237,7 @@ void ProgramSession::update_historical_stats_with_current(){ } -std::string ProgramSession::start_program(){ +std::string ProgramSession::start_program(ActionSource source, std::optional request_id){ m_logger.log("Received Program Start Request"); std::lock_guard lg(m_lock); @@ -249,7 +259,7 @@ std::string ProgramSession::start_program(){ // Now start the program. m_logger.log("Starting program..."); - m_last_state_change.store(current_time(), std::memory_order_relaxed); + mark_started(source, std::move(request_id)); set_state(ProgramState::RUNNING); m_program_thread = GlobalThreadPools::unlimited_realtime().dispatch_now_blocking( [this]{ @@ -284,7 +294,7 @@ std::string ProgramSession::start_program(){ "Invalid State: " + std::to_string((int)state) ); } -std::string ProgramSession::stop_program(){ +std::string ProgramSession::stop_program(ActionSource source, std::optional request_id){ m_logger.log("Received Stop Request"); { std::lock_guard lg(m_lock); @@ -299,6 +309,7 @@ std::string ProgramSession::stop_program(){ return "Program is already stopped."; case ProgramState::RUNNING: m_logger.log("Stopping program..."); + m_transitions.stop_requested(source, std::move(request_id), current_time()); set_state(ProgramState::STOPPING); break; case ProgramState::STOPPING: @@ -449,7 +460,7 @@ void ProgramSession::run_program(){ std::lock_guard lg(m_lock); push_stats(); update_historical_stats_with_current(); - set_state(ProgramState::STOPPED); + set_finished(); } } diff --git a/SerialPrograms/Source/CommonFramework/ProgramSession.h b/SerialPrograms/Source/CommonFramework/ProgramSession.h index af12d8c820..85f4892054 100644 --- a/SerialPrograms/Source/CommonFramework/ProgramSession.h +++ b/SerialPrograms/Source/CommonFramework/ProgramSession.h @@ -17,6 +17,7 @@ #define PokemonAutomation_CommonFramework_ProgramSession_H #include +#include #include #include #include "Common/Cpp/Logging/TaggedLogger.h" @@ -29,6 +30,7 @@ #include "CommonFramework/Globals.h" //#include "CommonFramework/Logging/Logger.h" #include "CommonFramework/Panels/ProgramDescriptor.h" +#include "CommonFramework/ProgramTransition.h" #include "CommonFramework/Tools/ProgramEnvironment.h" // #include "CommonFramework/ResourceDownload/ProgramMissingResourceTracker.h" #include "Integrations/ProgramTrackerInterfaces.h" @@ -97,6 +99,9 @@ class ProgramSession : public TrackableProgram{ std::string historical_stats() const; virtual WallClock last_state_change() const final; + // The last start or stop and who asked for it, or nullopt before the first start. + std::optional last_transition() const{ return m_transitions.last(); } + // Temporary for migration. StatsTracker* current_stats_tracker(){ return m_current_stats.get(); } const StatsTracker* historical_stats_tracker() const{ return m_historical_stats.get(); } @@ -109,13 +114,17 @@ class ProgramSession : public TrackableProgram{ // Returns empty string on success. Otherwise returns error string. // Note that these are asynchronous and will return before they are finished. + // `source` is who asks; `request_id` the lab request's id when the lab asks. + // last_transition() reports them. - std::string start_program(); // Returns before the program is fully started up. - std::string stop_program(); // Returns before the program is completely stopped. + // Returns before the program is fully started up. + std::string start_program(ActionSource source, std::optional request_id); + // Returns before the program is completely stopped. + std::string stop_program(ActionSource source, std::optional request_id); // Temporary - virtual void async_start() override{ start_program(); } - virtual void async_stop() override{ stop_program(); } + virtual void async_start() override{ start_program(ActionSource::UI, std::nullopt); } + virtual void async_stop() override{ stop_program(ActionSource::UI, std::nullopt); } protected: @@ -145,6 +154,10 @@ class ProgramSession : public TrackableProgram{ // Everything here must be called under the lock. void set_state(ProgramState state); + // Records the start time and who asked, before the state goes RUNNING. + void mark_started(ActionSource source, std::optional request_id); + // The run ended: records who ended it, unless a stop was asked for, and goes STOPPED. + void set_finished(); void push_stats(); void push_error(const std::string& message); void push_download_error(const std::string& message); @@ -168,6 +181,7 @@ class ProgramSession : public TrackableProgram{ std::atomic m_last_state_change; std::atomic m_state; + ProgramTransitionLatch m_transitions; // ProgramMissingResourceTracker m_missing_resource_tracker; diff --git a/SerialPrograms/Source/CommonFramework/ProgramTransition.cpp b/SerialPrograms/Source/CommonFramework/ProgramTransition.cpp new file mode 100644 index 0000000000..840ab2a71f --- /dev/null +++ b/SerialPrograms/Source/CommonFramework/ProgramTransition.cpp @@ -0,0 +1,42 @@ +/* Program Transition + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "ProgramTransition.h" + +namespace PokemonAutomation{ + + +void ProgramTransitionLatch::started(ActionSource source, std::optional request_id, WallClock now){ + std::lock_guard lg(m_lock); + m_stop_requested = false; + m_error = false; + m_last = ProgramTransition{ProgramAction::START, source, std::move(request_id), now}; +} +void ProgramTransitionLatch::stop_requested(ActionSource source, std::optional request_id, WallClock now){ + std::lock_guard lg(m_lock); + m_stop_requested = true; + m_last = ProgramTransition{ProgramAction::STOP, source, std::move(request_id), now}; +} +void ProgramTransitionLatch::error_reported(){ + std::lock_guard lg(m_lock); + m_error = true; +} +void ProgramTransitionLatch::finished(WallClock now){ + std::lock_guard lg(m_lock); + if (m_stop_requested){ + return; + } + const ActionSource source = m_error ? ActionSource::PROGRAM_ERROR : ActionSource::PROGRAM; + m_last = ProgramTransition{ProgramAction::STOP, source, std::nullopt, now}; +} +std::optional ProgramTransitionLatch::last() const{ + std::lock_guard lg(m_lock); + return m_last; +} + + + +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/CommonFramework/ProgramTransition.h b/SerialPrograms/Source/CommonFramework/ProgramTransition.h new file mode 100644 index 0000000000..739918fd1c --- /dev/null +++ b/SerialPrograms/Source/CommonFramework/ProgramTransition.h @@ -0,0 +1,74 @@ +/* Program Transition + * + * From: https://github.com/PokemonAutomation/ + * + * Who started or stopped a program: the Start/Stop button, a lab request + * (with the lab server's id for it), or the program itself when it ends. + * ProgramSession passes the asker in with each start and stop and keeps + * the last transition here, so a reader such as the lab channel never has + * to guess it from the state changes. Free of Qt and of ProgramSession, so + * it is unit tested. + * + */ + +#ifndef PokemonAutomation_CommonFramework_ProgramTransition_H +#define PokemonAutomation_CommonFramework_ProgramTransition_H + +#include +#include +#include "Common/Cpp/Time.h" +#include "Common/Cpp/Concurrency/Mutex.h" + +namespace PokemonAutomation{ + + +// Whether a transition started or stopped the program. +enum class ProgramAction{ + START, + STOP, +}; + +// Who asked for a start or stop. +enum class ActionSource{ + UI, // The Start/Stop button, or an integration (e.g. Discord). + LAB, // A lab channel request. + PROGRAM, // The program finished by itself. + PROGRAM_ERROR, // The program ended with an error. +}; + +// One start or stop of a program. +struct ProgramTransition{ + ProgramAction action; + ActionSource source; + std::optional request_id; // The lab request's id, if a lab request asked. + WallClock at; +}; + + +// The last transition of one program. A stop keeps its asker from STOPPING +// through STOPPED: an error or the program's own end after a stop request +// does not overwrite who stopped it. Thread-safe. +class ProgramTransitionLatch{ +public: + // The program went RUNNING because `source` asked. + void started(ActionSource source, std::optional request_id, WallClock now); + // The program went STOPPING because `source` asked. + void stop_requested(ActionSource source, std::optional request_id, WallClock now); + // The running program reported an error. + void error_reported(); + // The program went STOPPED. + void finished(WallClock now); + + std::optional last() const; + +private: + mutable Mutex m_lock; + bool m_stop_requested = false; + bool m_error = false; + std::optional m_last; +}; + + + +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/CommonFramework/ProgramTransition_Tests.cpp b/SerialPrograms/Source/CommonFramework/ProgramTransition_Tests.cpp new file mode 100644 index 0000000000..0e644fcb54 --- /dev/null +++ b/SerialPrograms/Source/CommonFramework/ProgramTransition_Tests.cpp @@ -0,0 +1,172 @@ +/* Program Transition - Tests + * + * From: https://github.com/PokemonAutomation/ + * + * Who each start and stop of a program is said to come from, as + * ProgramSession reports its steps to ProgramTransitionLatch. + * + */ + +#include +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "ProgramTransition.h" +#include "ProgramTransition_Tests.h" + +namespace PokemonAutomation{ + +namespace{ + +using namespace std::chrono_literals; + + +constexpr std::string_view REQUEST_ID = "5f0c2a8e-3d41-4b7a-9c55-0e6a1f2b7c10"; + +// One step ProgramSession reports. +enum class Step{ + UI_START, + LAB_START, + UI_STOP, + LAB_STOP, + ERROR_REPORTED, + FINISHED, +}; +struct LatchInput{ + std::vector steps; +}; +struct LatchExpectation{ + std::optional action; // None: no transition yet. + ActionSource source = ActionSource::UI; + bool has_request_id = false; + size_t at_step = 0; // The step (from 1) whose time the transition has. +}; +struct LatchCase{ + std::string name; + LatchInput input; + LatchExpectation expectation; +}; + +WallClock step_time(size_t step){ + return WallClock{} + Seconds(1000 + step); +} +void apply(Step step, WallClock now, ProgramTransitionLatch& latch){ + switch (step){ + case Step::UI_START: + latch.started(ActionSource::UI, std::nullopt, now); + return; + case Step::LAB_START: + latch.started(ActionSource::LAB, std::string(REQUEST_ID), now); + return; + case Step::UI_STOP: + latch.stop_requested(ActionSource::UI, std::nullopt, now); + return; + case Step::LAB_STOP: + latch.stop_requested(ActionSource::LAB, std::string(REQUEST_ID), now); + return; + case Step::ERROR_REPORTED: + latch.error_reported(); + return; + case Step::FINISHED: + latch.finished(now); + return; + } +} +UnitTestResult check(const LatchCase& c){ + ProgramTransitionLatch latch; + for (size_t i = 0; i < c.input.steps.size(); i++){ + apply(c.input.steps[i], step_time(i + 1), latch); + } + const std::optional last = latch.last(); + const LatchExpectation& expected = c.expectation; + if (!expected.action){ + return last ? UnitTestResult("expected no transition") : UnitTestResult(true); + } + if (!last || last->action != *expected.action || last->source != expected.source){ + return "wrong action or source"; + } + if (last->request_id.has_value() != expected.has_request_id){ + return "a request id goes with a lab request only"; + } + if (last->at != step_time(expected.at_step)){ + return "the transition has the time of the wrong step"; + } + return true; +} +class Test_ProgramTransitionLatch : public UnitTest{ +public: + explicit Test_ProgramTransitionLatch(LatchCase test_case) + : UnitTest(std::format("CommonFramework::ProgramTransition - {}", test_case.name)) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + return check(m_case); + } + +private: + LatchCase m_case; +}; +const LatchCase LATCH_CASES[] = { + {.name = "nothing yet", .input = {.steps = {}}, .expectation = {.action = std::nullopt}}, + { + .name = "UI start", + .input = {.steps = {Step::UI_START}}, + .expectation = {.action = ProgramAction::START, .source = ActionSource::UI, .at_step = 1}, + }, + { + .name = "lab start", + .input = {.steps = {Step::LAB_START}}, + .expectation = {.action = ProgramAction::START, .source = ActionSource::LAB, .has_request_id = true, .at_step = 1}, + }, + { + .name = "UI stop after a lab start", + .input = {.steps = {Step::LAB_START, Step::UI_STOP, Step::FINISHED}}, + .expectation = {.action = ProgramAction::STOP, .source = ActionSource::UI, .at_step = 2}, + }, + { + .name = "lab stop is latched through the end of the run", + .input = {.steps = {Step::UI_START, Step::LAB_STOP, Step::FINISHED}}, + .expectation = {.action = ProgramAction::STOP, .source = ActionSource::LAB, .has_request_id = true, .at_step = 2}, + }, + { + .name = "error while stopping keeps who stopped", + .input = {.steps = {Step::UI_START, Step::LAB_STOP, Step::ERROR_REPORTED, Step::FINISHED}}, + .expectation = {.action = ProgramAction::STOP, .source = ActionSource::LAB, .has_request_id = true, .at_step = 2}, + }, + { + .name = "program finished by itself", + .input = {.steps = {Step::LAB_START, Step::FINISHED}}, + .expectation = {.action = ProgramAction::STOP, .source = ActionSource::PROGRAM, .at_step = 2}, + }, + { + .name = "program ended with an error", + .input = {.steps = {Step::UI_START, Step::ERROR_REPORTED, Step::FINISHED}}, + .expectation = {.action = ProgramAction::STOP, .source = ActionSource::PROGRAM_ERROR, .at_step = 3}, + }, + { + .name = "error of an earlier run is forgotten", + .input = {.steps = {Step::UI_START, Step::ERROR_REPORTED, Step::FINISHED, Step::UI_START, Step::FINISHED}}, + .expectation = {.action = ProgramAction::STOP, .source = ActionSource::PROGRAM, .at_step = 5}, + }, + { + .name = "stop of an earlier run is forgotten", + .input = {.steps = {Step::UI_START, Step::LAB_STOP, Step::FINISHED, Step::UI_START, Step::FINISHED}}, + .expectation = {.action = ProgramAction::STOP, .source = ActionSource::PROGRAM, .at_step = 5}, + }, +}; + + +} // namespace + + +void add_tests_ProgramTransition(UnitTestDatabase& database){ + for (const LatchCase& c : LATCH_CASES){ + database.add(c); + } +} + + + +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/CommonFramework/ProgramTransition_Tests.h b/SerialPrograms/Source/CommonFramework/ProgramTransition_Tests.h new file mode 100644 index 0000000000..8aa4419356 --- /dev/null +++ b/SerialPrograms/Source/CommonFramework/ProgramTransition_Tests.h @@ -0,0 +1,21 @@ +/* Program Transition - Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonFramework_ProgramTransition_Tests_H +#define PokemonAutomation_CommonFramework_ProgramTransition_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ + + +// Adds the tests of ProgramTransitionLatch. +void add_tests_ProgramTransition(UnitTestDatabase& database); + + + +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/CommonFramework/Windows/Lab.md b/SerialPrograms/Source/CommonFramework/Windows/Lab.md index d64089d611..6212f99a95 100644 --- a/SerialPrograms/Source/CommonFramework/Windows/Lab.md +++ b/SerialPrograms/Source/CommonFramework/Windows/Lab.md @@ -23,12 +23,12 @@ takes effect at the next launch. | Path | Direction | Meaning | |---|---|---| -| `Lab/inbox/.txt` | script writes | A request: one command per line, run in order. Requests run one at a time, in name order. | +| `Lab/inbox/.txt` | script writes | A request: one command per line, run in order. Requests run one at a time, in name order; a request of `snapshot` lines only runs beside them (see [Snapshot](#snapshot)). | | `Lab/done/.txt` | app moves | The request, moved here when it starts. | | `Lab/outbox/.out` | app writes | The request's journal (below). It appears only once the request has finished; `.tmp` shows the progress so far. | | `Lab/outbox/_