diff --git a/tests/unit/test_ini_only_settings.cpp b/tests/unit/test_ini_only_settings.cpp index f90e9b2f9..83303aad4 100644 --- a/tests/unit/test_ini_only_settings.cpp +++ b/tests/unit/test_ini_only_settings.cpp @@ -141,3 +141,14 @@ TEST_CASE("ini only settings: nothing changed, nothing to tell") { CHECK(ini.restore(*settings).empty()); CHECK(settings->exec_on_exit == "notify.exe"); } + +TEST_CASE("ini only settings: a scenery's config block doesn't change the period of the odometer states") { + auto const settings{std::make_unique()}; + settings->odometer_expiry = 730; + ini_only_settings const ini{*settings}; + // "config odometer.expiry 1 endconfig" in the .scn would drop the states of the vehicles not run yesterday + settings->odometer_expiry = 1; + auto const changed{ini.restore(*settings)}; + CHECK(settings->odometer_expiry == 730); + CHECK(changed == std::vector{"odometer.expiry"}); +} diff --git a/tests/unit/test_odometer.cpp b/tests/unit/test_odometer.cpp index 295d722cd..b3da8d792 100644 --- a/tests/unit/test_odometer.cpp +++ b/tests/unit/test_odometer.cpp @@ -4,9 +4,23 @@ #include "utilities/Globals.h" #include "vehicle/odometer.h" +#include +#include +#include #include #include +#include +#include +#include #include +#include +#include +#include +#ifdef _WIN32 +#include +#else +#include +#endif // the odometer of a vehicle, kept between the sessions (eu07/maszyna#72): one state the cab's counters and the // python screens show, saved in one store, taking over the states the python screens kept in their own files @@ -665,3 +679,467 @@ TEST_CASE("odometer: the files of both kinds of python screens are read, by the CHECK_FALSE(odometer::legacy_state(vehicles, "EU07-425", scripts).has_value()); CHECK_FALSE(odometer::legacy_state(vehicles, "", scripts).has_value()); } + +// the day a state was last updated, kept in the file so the vehicles not run for long are dropped from it (review of +// eu07/maszyna#283: the file grew with every vehicle ever run). the tests give the day, the clock of the machine +// doesn't matter + +namespace { + +constexpr odometer::day today{std::chrono::year{2026} / 11 / 21}; + +odometer::day days_ago(int const Days) { + return today - std::chrono::days{Days}; +} + +odometer::day days_on(int const Days) { + return today + std::chrono::days{Days}; +} + +odometer::store read_text(std::string const &Text, odometer::day const Today = today) { + std::stringstream file{Text}; + odometer::store store; + store.read(file, Today); + return store; +} + +std::string read_file(std::filesystem::path const &Path) { + std::ifstream input{Path, std::ios::binary}; + std::stringstream content; + content << input.rdbuf(); + return content.str(); +} + +std::string written(odometer::store const &Store) { + std::stringstream text; + Store.write(text); + return text.str(); +} + +// the reader of the builds before the stamps, as it was (2f127688, odometer::store::read): the states it gets +struct old_state { + double km; + bool guessed; +}; + +std::optional old_line(std::string const &Line, std::string &Name) { + auto const separator{Line.find_first_of(" \t")}; + if (separator == std::string::npos) + return std::nullopt; + auto number{Line.substr(0, separator)}; + auto const guessed{false == number.empty() && number.front() == '~'}; + if (guessed) + number.erase(0, 1); + std::size_t used{0}; + double km{0.0}; + try { + km = std::stod(number, &used); + } catch (std::exception const &) { + return std::nullopt; + } + Name = Line.substr(separator + 1); + if (used != number.size() || false == std::isfinite(km) || km < 0.0 || Name.empty()) + return std::nullopt; + return old_state{km, guessed}; +} + +std::map old_read(std::string const &Text) { + std::map states; + std::stringstream input{Text}; + std::string line; + while (std::getline(input, line)) { + if (false == line.empty() && line.back() == '\r') + line.pop_back(); + if (line.empty() || line.front() == '#') + continue; + std::string name; + if (auto const state{old_line(line, name)}; state.has_value()) + states[name] = *state; + } + return states; +} + +odometer::reading guessed_run(double const Km, double const Metres) { + odometer::reading reading; + reading.begin(Km, odometer::origin::guessed); + reading.run(Metres); + return reading; +} + +} // namespace + +TEST_CASE("odometer: a file of the builds before the stamps is read whole, its states updated the day it's read") { + std::string const unstamped{"# odometer states of the vehicles: , ~ for one counted from a made up state\n" + "1000.0000 EU07-424\n" + "~20000.0000 SM42-001\n" + "42.5000 loco with spaces\n"}; + auto const store{read_text(unstamped)}; + REQUIRE(store.size() == 3); + CHECK(store.find("EU07-424").value() == 1000.0); + CHECK(store.guessed("SM42-001")); + CHECK(store.find("loco with spaces").value() == 42.5); + for (auto const *name : {"EU07-424", "SM42-001", "loco with spaces"}) { + CAPTURE(name); + CHECK(store.updated(name) == today); + } + CHECK_FALSE(store.updated("EU07-425").has_value()); + + // saved, all of them are written with the day they were read, none dropped + scratch_directory directory{"odometer_unstamped"}; + auto const path{directory.path / "eu07_odometers.txt"}; + write_file(path, unstamped); + auto loaded{read_text(read_file(path))}; + loaded.record("EU07-424", run(1000.0, 1000.0), today); + REQUIRE(odometer::save(loaded, path, today)); + auto const text{read_file(path)}; + CHECK(text.find("# updated 2026-11-21\n") != std::string::npos); + auto const after{read_text(text, days_on(10))}; + CHECK(after.size() == 3); + CHECK(after.find("EU07-424").value() == doctest::Approx(1001.0)); + CHECK(after.find("SM42-001").value() == 20000.0); + CHECK(after.updated("SM42-001") == today); +} + +TEST_CASE("odometer: the day a state was last updated is written with it and read back") { + odometer::store store; + store.record("EU07-424", run(1000.0, 1000.0), days_ago(10)); + store.record("loco with spaces", run(42.0, 500.0), today); + store.record("SM42-001", guessed_run(20000.0, 1000.0), days_ago(10)); + store.record("ET22-001", run(5.0, 1000.0), days_ago(400)); + auto const text{written(store)}; + // grouped by the day, the oldest first, by the name in a group + CHECK(text.find("# updated 2025-10-17\n6.0000 ET22-001\n" + "# updated 2026-11-11\n1001.0000 EU07-424\n~20001.0000 SM42-001\n" + "# updated 2026-11-21\n42.5000 loco with spaces\n") + != std::string::npos); + + auto const read{read_text(text)}; + CHECK(read.size() == 4); + CHECK(read.updated("EU07-424") == days_ago(10)); + CHECK(read.updated("SM42-001") == days_ago(10)); + CHECK(read.guessed("SM42-001")); + CHECK(read.updated("loco with spaces") == today); + CHECK(read.updated("ET22-001") == days_ago(400)); + CHECK(read.find("loco with spaces").value() == doctest::Approx(42.5)); + // the store read writes the same file again + CHECK(written(read) == text); +} + +TEST_CASE("odometer: a build before the stamps reads the file with them as it read its own") { + odometer::store store; + store.record("EU07-424", run(1000.0, 1000.0), days_ago(10)); + store.record("loco with spaces", run(42.0, 500.0), today); + store.record("SM42-001", guessed_run(20000.0, 1000.0), days_ago(300)); + auto const old{old_read(written(store))}; + REQUIRE(old.size() == 3); + CHECK(old.at("EU07-424").km == doctest::Approx(1001.0)); + CHECK_FALSE(old.at("EU07-424").guessed); + CHECK(old.at("loco with spaces").km == doctest::Approx(42.5)); + CHECK(old.at("SM42-001").km == doctest::Approx(20001.0)); + CHECK(old.at("SM42-001").guessed); +} + +TEST_CASE("odometer: a stamp later than the day is kept as written, a malformed one doesn't make a state expire") { + auto const store{read_text("# updated 2099-01-01\n1 future\n" + "# updated 2025-01-01\n2 dated\n" + "# a comment between\n3 after a comment\n" + "# updated nonsense\n4 malformed\n" + "# updated 2026-02-30\n5 no such day\n" + "# updated 2025-1-01\n6 short\n" + "# updated 2025-01-01 \r\n7 trailing space\n" + "#updated 2024-01-01\n8 not a stamp\n")}; + odometer::day const newyear{std::chrono::year{2025} / 1 / 1}; + CHECK(store.size() == 8); + // a clock set back doesn't move it back (review of #435: the next session with the right clock dropped them all) + CHECK(store.updated("future") == odometer::day{std::chrono::year{2099} / 1 / 1}); + CHECK(store.updated("dated") == newyear); + CHECK(store.updated("after a comment") == newyear); + CHECK(store.updated("malformed") == today); + CHECK(store.updated("no such day") == today); + CHECK(store.updated("short") == today); + CHECK(store.updated("trailing space") == newyear); + CHECK(store.updated("not a stamp") == newyear); +} + +TEST_CASE("odometer: a state is updated the day it's recorded, one left as it was keeps its day") { + auto store{read_text("# updated 2026-08-13\n300 known\n")}; + REQUIRE(store.updated("known") == days_ago(100)); + store.record("known", started(300.0), today); + CHECK(store.updated("known") == days_ago(100)); + store.record("known", run(300.0, 1000.0), today); + CHECK(store.updated("known") == today); +} + +TEST_CASE("odometer: of two stores merged, the later day of a state is kept, whichever state is newer") { + auto const other{read_text("# updated 2026-11-01\n100 known\n# updated 2026-11-20\n200 other\n")}; + auto mine{read_text("# updated 2026-11-10\n150 known\n# updated 2026-11-15\n250 other\n")}; + mine.merge(other); + CHECK(mine.find("known").value() == 150.0); + CHECK(mine.updated("known") == days_ago(11)); + CHECK(mine.find("other").value() == 250.0); + CHECK(mine.updated("other") == days_ago(1)); + auto const newer{read_text("# updated 2026-11-01\n500 known\n")}; + mine.merge(newer); + CHECK(mine.find("known").value() == 500.0); + CHECK(mine.updated("known") == days_ago(11)); +} + +TEST_CASE("odometer: a save drops the states not updated for longer than a year, the other simulations' too") { + CHECK(odometer::expiry() == std::chrono::days{365}); + scratch_directory directory{"odometer_expiry"}; + auto const path{directory.path / "eu07_odometers.txt"}; + write_file(path, "# updated 2025-11-20\n100 over a year\n" + "# updated 2025-11-21\n200 a year\n" + "# updated 2026-11-21\n300 fresh\n"); + auto store{read_text(read_file(path))}; + // another simulation saved meanwhile, with a state as old as one of this one's + write_file(path, "# updated 2025-11-20\n100 over a year\n" + "# updated 2025-11-21\n200 a year\n" + "# updated 2025-06-01\n5 old of another\n" + "# updated 2026-11-21\n300 fresh\n6 fresh of another\n"); + store.record("run today", run(70.0, 1000.0), today); + REQUIRE(odometer::save(store, path, today)); + + auto const saved{read_text(read_file(path))}; + CHECK(saved.size() == 4); + CHECK_FALSE(saved.find("over a year").has_value()); + CHECK_FALSE(saved.find("old of another").has_value()); + CHECK(saved.find("a year").value() == 200.0); + CHECK(saved.updated("a year") == days_ago(365)); + CHECK(saved.find("fresh").value() == 300.0); + CHECK(saved.find("fresh of another").value() == 6.0); + CHECK(saved.find("run today").value() == doctest::Approx(71.0)); + // gone from the store of the simulation too + CHECK_FALSE(store.find("over a year").has_value()); + CHECK(store.size() == 4); + + SUBCASE("the one of a year drops too once the file was updated a day later, in the session that reads it") { + // the session goes on the next day: measured from the day the file had when the session read it + store.record("run today", run(71.0, 1000.0), days_on(1)); + REQUIRE(odometer::save(store, path, days_on(1))); + CHECK(read_text(read_file(path), days_on(1)).find("a year").has_value()); + // the next session + auto next{read_text(read_file(path), days_on(1))}; + next.record("run today", run(72.0, 1000.0), days_on(1)); + REQUIRE(odometer::save(next, path, days_on(1))); + auto const later{read_text(read_file(path), days_on(1))}; + CHECK(later.size() == 3); + CHECK_FALSE(later.find("a year").has_value()); + CHECK(later.updated("run today") == days_on(1)); + } + SUBCASE("a store with nothing recorded since doesn't write the file only to drop them") { + REQUIRE(odometer::save(store, path, today)); + mark(path); + REQUIRE(odometer::save(store, path, days_on(1))); + CHECK(marked(path)); + CHECK(read_text(read_file(path), days_on(1)).find("a year").has_value()); + } +} + +TEST_CASE("odometer: a save lost to another simulation's save is written again with its stamps") { + scratch_directory directory{"odometer_lost_save_stamps"}; + auto const path{directory.path / "eu07_odometers.txt"}; + write_file(path, "# updated 2026-06-01\n1000 shared\n"); + auto first{read_text(read_file(path))}; + auto second{read_text(read_file(path))}; + first.record("shared", run(1000.0, 5000.0), today); + first.record("first only", run(70.0, 1000.0), today); + second.record("second only", run(80.0, 1000.0), days_ago(1)); + + // the second one reads the file before the first one writes it, and puts its own in place after + auto const view{directory.path / "late_view" / path.filename()}; + std::filesystem::create_directories(view.parent_path()); + std::filesystem::copy_file(path, view); + REQUIRE(odometer::save(first, path, today)); + REQUIRE(odometer::save(second, view, today)); + std::filesystem::rename(view, path); + REQUIRE_FALSE(read_text(read_file(path)).find("first only").has_value()); + + REQUIRE(odometer::save(first, path, today)); + REQUIRE(odometer::save(second, path, today)); + auto const saved{read_text(read_file(path))}; + CHECK(saved.size() == 3); + CHECK(saved.find("shared").value() == doctest::Approx(1005.0)); + CHECK(saved.updated("shared") == today); + CHECK(saved.find("first only").value() == doctest::Approx(71.0)); + CHECK(saved.updated("first only") == today); + CHECK(saved.find("second only").value() == doctest::Approx(81.0)); + CHECK(saved.updated("second only") == days_ago(1)); +} + +// a wrong clock, the period of eu07.ini (odometer.expiry) and the log of what's dropped (review of eu07/maszyna#435) + +// the lines logged while the object lives, kept by the engine stubs (engine_stubs.cpp) +void unit_tests_log_capture(bool Enabled); +std::vector unit_tests_logged_lines(); + +namespace { + +odometer::day const backintime{std::chrono::year{2000} / 1 / 1}; + +int process_id() { +#ifdef _WIN32 + return _getpid(); +#else + return static_cast(getpid()); +#endif +} + +class log_capture { +public: + log_capture() { unit_tests_log_capture(true); } + ~log_capture() { unit_tests_log_capture(false); } + log_capture(log_capture const &) = delete; + log_capture &operator=(log_capture const &) = delete; + + std::size_t count(std::string_view const Text) const { + auto const lines{unit_tests_logged_lines()}; + return static_cast(std::ranges::count_if(lines, [Text](std::string const &Line) { return Line.find(Text) != std::string::npos; })); + } +}; + +std::string const stamped_file{"# updated 2025-12-01\n100 a year ago\n" + "# updated 2026-11-11\n200 driven\n" + "# updated 2026-11-21\n300 fresh\n"}; + +} // namespace + +TEST_CASE("odometer: a clock set back doesn't move the days of the states back, nor drops them then") { + scratch_directory directory{"odometer_clock_back"}; + auto const path{directory.path / "eu07_odometers.txt"}; + write_file(path, stamped_file); + // a dead battery of the clock: the session starts on 2000-01-01 + auto back{read_text(read_file(path), backintime)}; + CHECK(back.updated("a year ago") == days_ago(355)); + back.record("driven", run(200.0, 1000.0), backintime); + CHECK(back.updated("driven") == days_ago(10)); + REQUIRE(odometer::save(back, path, backintime)); + auto const written{read_file(path)}; + CHECK(written.find("# updated 2000-01-01") == std::string::npos); + CHECK(read_text(written).size() == 3); + + // the next session with the right clock drops none of them + auto right{read_text(written, days_on(1))}; + right.record("fresh", run(300.0, 1000.0), days_on(1)); + REQUIRE(odometer::save(right, path, days_on(1))); + auto const after{read_text(read_file(path), days_on(1))}; + CHECK(after.size() == 3); + CHECK(after.updated("a year ago") == days_ago(355)); + CHECK(after.updated("driven") == days_ago(10)); + CHECK(after.find("driven").value() == doctest::Approx(201.0)); +} + +TEST_CASE("odometer: a clock set forward doesn't drop the states not run in that session") { + scratch_directory directory{"odometer_clock_forward"}; + auto const path{directory.path / "eu07_odometers.txt"}; + write_file(path, stamped_file); + // two years ahead: measured from the day the file had when the session read it + auto ahead{read_text(read_file(path), days_on(730))}; + ahead.record("driven", run(200.0, 1000.0), days_on(730)); + REQUIRE(odometer::save(ahead, path, days_on(730))); + // the later saves of the session too, which find its own states of that day in the file + ahead.record("driven", run(201.0, 1000.0), days_on(730)); + REQUIRE(odometer::save(ahead, path, days_on(730))); + CHECK(read_text(read_file(path), days_on(730)).size() == 3); + + // the next session with the right clock: the day ahead is kept as written, nothing drops + auto right{read_text(read_file(path), days_on(1))}; + CHECK(right.updated("driven") == days_on(730)); + right.record("fresh", run(300.0, 1000.0), days_on(1)); + REQUIRE(odometer::save(right, path, days_on(1))); + auto const after{read_text(read_file(path), days_on(1))}; + CHECK(after.size() == 3); + CHECK(after.updated("a year ago") == days_ago(355)); + CHECK(after.updated("driven") == days_on(730)); +} + +TEST_CASE("odometer: a player back after a break keeps the states in the session he comes back in") { + scratch_directory directory{"odometer_break"}; + auto const path{directory.path / "eu07_odometers.txt"}; + // the last session was 500 days ago + write_file(path, "# updated 2024-05-19\n10 too old\n" + "# updated 2025-01-31\n20 older\n" + "# updated 2025-07-09\n30 last run\n40 not run since\n"); + REQUIRE(odometer::day{std::chrono::year{2025} / 7 / 9} == days_ago(500)); + auto back{read_text(read_file(path))}; + back.record("last run", run(30.0, 1000.0), today); + REQUIRE(odometer::save(back, path, today)); + auto const first{read_text(read_file(path))}; + // more than a year before the last session: gone, as that session would have dropped it the next day + CHECK_FALSE(first.find("too old").has_value()); + CHECK(first.find("older").has_value()); + CHECK(first.find("not run since").has_value()); + CHECK(first.updated("last run") == today); + + // the session after: not run for a year before the last one, they drop + auto next{read_text(read_file(path), days_on(1))}; + next.record("last run", run(31.0, 1000.0), days_on(1)); + REQUIRE(odometer::save(next, path, days_on(1))); + auto const second{read_text(read_file(path), days_on(1))}; + CHECK(second.size() == 1); + CHECK(second.find("last run").has_value()); +} + +TEST_CASE("odometer: the period is the one eu07.ini gives, 0 keeps every state") { + auto const text{"# updated 2000-01-01\n1 long ago\n# updated 2026-10-21\n2 a month ago\n# updated 2026-11-21\n3 fresh\n"}; + { + auto store{read_text(text)}; + CHECK(store.expire(today, std::chrono::days{0}) == 0); + CHECK(store.size() == 3); + } + { + auto store{read_text(text)}; + CHECK(store.expire(today, std::chrono::days{30}) == 2); + CHECK(store.find("fresh").has_value()); + } + { + // and a save with it + scratch_directory directory{"odometer_never"}; + auto const path{directory.path / "eu07_odometers.txt"}; + write_file(path, text); + auto store{read_text(read_file(path))}; + store.record("fresh", run(3.0, 1000.0), today); + REQUIRE(odometer::save(store, path, today, std::chrono::days{0})); + CHECK(read_text(read_file(path)).size() == 3); + } + + // odometer.expiry in eu07.ini, a year unless set (the parser of eu07.ini, Globals.cpp, isn't in the build of + // the unit tests) + CHECK(std::make_unique()->odometer_expiry == 365); + // the store of the simulation takes it from the settings, a negative one as 0 + auto const kept{Global.odometer_expiry}; + Global.odometer_expiry = 90; + CHECK(odometer::expiry() == std::chrono::days{90}); + Global.odometer_expiry = 0; + CHECK(odometer::expiry() == std::chrono::days{0}); + Global.odometer_expiry = -5; + CHECK(odometer::expiry() == std::chrono::days{0}); + Global.odometer_expiry = kept; +} + +TEST_CASE("odometer: the states dropped are logged once, by the save that writes the file without them") { + scratch_directory directory{"odometer_dropped_log"}; + auto const path{directory.path / "eu07_odometers.txt"}; + write_file(path, "# updated 2025-01-01\n1 long ago\n# updated 2026-11-21\n2 fresh\n"); + auto store{read_text(read_file(path))}; + store.record("fresh", run(2.0, 1000.0), today); + constexpr std::string_view dropped{"not updated for 365 days dropped"}; + log_capture const log; + + // the file aside can't be written: each save fails, none logs the states dropped + auto temporary{path}; + temporary += "." + std::to_string(process_id()) + ".tmp"; + std::filesystem::create_directories(temporary / "blocked"); + CHECK_FALSE(odometer::save(store, path, today, std::chrono::days{365})); + CHECK_FALSE(odometer::save(store, path, today, std::chrono::days{365})); + CHECK(log.count(dropped) == 0); + CHECK(read_text(read_file(path)).find("long ago").has_value()); + + std::filesystem::remove_all(temporary); + REQUIRE(odometer::save(store, path, today, std::chrono::days{365})); + CHECK(log.count(dropped) == 1); + CHECK_FALSE(read_text(read_file(path)).find("long ago").has_value()); + // the save after, which finds the file as written, doesn't log them again + REQUIRE(odometer::save(store, path, today, std::chrono::days{365})); + CHECK(log.count(dropped) == 1); +} diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp index e920849b2..5e64e40c4 100644 --- a/utilities/Globals.cpp +++ b/utilities/Globals.cpp @@ -614,6 +614,14 @@ bool global_settings::ConfigParseSimulation(cParser& Parser, const std::string& return true; } + // the saved odometer states of the vehicles not run for this many days are dropped, 0 = never (vehicle/odometer.h) + if (token == "odometer.expiry") + { + ParseOne(Parser, odometer_expiry); + odometer_expiry = std::max(0, odometer_expiry); + return true; + } + if (token == "blackbox") { bool blackbox{false}; @@ -1890,6 +1898,7 @@ global_settings::export_as_text( std::ostream &Output ) const { export_as_text( Output, "sound.efx.airabsorption", AudioAirAbsorption ); export_as_text( Output, "physicslog", WriteLogFlag ); export_as_text( Output, "physicslog.trains", WriteTrainLogFlag ); + export_as_text( Output, "odometer.expiry", odometer_expiry ); if( BlackBox ) { export_as_text( Output, "blackbox", *BlackBox ); } diff --git a/utilities/Globals.h b/utilities/Globals.h index 3b1441240..d37535778 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -131,6 +131,9 @@ struct global_settings { bool ParserLogIncludes{ true }; // simulation bool RealisticControlMode{ false }; // controls ability to steer the vehicle from outside views + // odometer.expiry: the saved odometer state of a vehicle not run for longer than this many days is dropped from the + // store (vehicle/odometer.h); 0 = never + int odometer_expiry{ 365 }; bool bEnableTraction{ true }; float fFriction{ 1.f }; // mnożnik tarcia - KURS90 float FrictionWeatherFactor{ 1.f }; diff --git a/utilities/inionlysettings.cpp b/utilities/inionlysettings.cpp index 9d6c587c2..fb8d8f58f 100644 --- a/utilities/inionlysettings.cpp +++ b/utilities/inionlysettings.cpp @@ -47,7 +47,8 @@ ini_only_settings::ini_only_settings(global_settings const &Settings) m_uart{Settings.uart_conf}, #endif m_feedback_mode{Settings.iFeedbackMode}, m_feedback_port{Settings.iFeedbackPort}, m_python_enabled{Settings.python_enabled}, - m_luascreens_enabled{Settings.luascreens_enabled}, m_lua_fulllibraries{Settings.lua_fulllibraries}, m_wasm_enabled{Settings.wasm_enabled} + m_luascreens_enabled{Settings.luascreens_enabled}, m_lua_fulllibraries{Settings.lua_fulllibraries}, m_wasm_enabled{Settings.wasm_enabled}, + m_odometer_expiry{Settings.odometer_expiry} { } @@ -90,5 +91,6 @@ std::vector ini_only_settings::restore(global_settings &Settin keep_off(Settings.luascreens_enabled, m_luascreens_enabled, "luascreens.enabled", changed); keep_off(Settings.lua_fulllibraries, m_lua_fulllibraries, "lua.fulllibraries", changed); keep_off(Settings.wasm_enabled, m_wasm_enabled, "wasm.enabled", changed); + keep(Settings.odometer_expiry, m_odometer_expiry, "odometer.expiry", changed); return changed; } diff --git a/utilities/inionlysettings.h b/utilities/inionlysettings.h index 667703b94..6dba86927 100644 --- a/utilities/inionlysettings.h +++ b/utilities/inionlysettings.h @@ -21,9 +21,10 @@ http://mozilla.org/MPL/2.0/. // (state_serializer::deserialize_config, global_settings::ConfigParse), and with these keys it would run a program // (execonexit, extcam.cmd, extcam.rec), write the screenshots elsewhere (screenshotsdir), open connections and ports // (network.server, network.client, zmq.address, motiontelemetry, uart, feedbackmode, feedbackport), switch back on a -// script runtime the player switched off (python.enabled, luascreens.enabled, wasm.enabled) or take its own scripts -// out of the sandbox (lua.fulllibraries). they keep what eu07.ini set; a scenery may still switch a runtime off, or -// keep its scripts in the sandbox when eu07.ini didn't, as it always could +// script runtime the player switched off (python.enabled, luascreens.enabled, wasm.enabled), take its own scripts +// out of the sandbox (lua.fulllibraries) or drop the odometer states the player keeps (odometer.expiry). they keep +// what eu07.ini set; a scenery may still switch a runtime off, or keep its scripts in the sandbox when eu07.ini didn't, +// as it always could class ini_only_settings { public: @@ -53,4 +54,5 @@ class ini_only_settings bool m_luascreens_enabled; bool m_lua_fulllibraries; bool m_wasm_enabled; + int m_odometer_expiry; }; diff --git a/vehicle/odometer.cpp b/vehicle/odometer.cpp index 484998e40..7495cbda2 100644 --- a/vehicle/odometer.cpp +++ b/vehicle/odometer.cpp @@ -15,13 +15,17 @@ http://mozilla.org/MPL/2.0/. #include "utilities/utilities.h" #include +#include #include #include #include +#include #include #include #include +#include #include +#include #ifdef _WIN32 #include #else @@ -62,8 +66,61 @@ std::optional parse_number(std::string const &Text) { } } +// the comment line which gives the day the states after it were last updated +constexpr std::string_view stamp_prefix{"# updated "}; + +// a whole number making up all of the text +std::optional parse_integer(std::string_view const Text) { + if (Text.empty() || Text.front() == '-') + return std::nullopt; + int value{0}; + auto const *const end{Text.data() + Text.size()}; + if (auto const [used, error] {std::from_chars(Text.data(), end, value)}; error != std::errc{} || used != end) + return std::nullopt; + return value; +} + +// day written as yyyy-mm-dd +std::optional parse_day(std::string_view const Text) { + if (Text.size() != 10 || Text[4] != '-' || Text[7] != '-') + return std::nullopt; + auto const year{parse_integer(Text.substr(0, 4))}; + auto const month{parse_integer(Text.substr(5, 2))}; + auto const dayofmonth{parse_integer(Text.substr(8, 2))}; + if (false == (year.has_value() && month.has_value() && dayofmonth.has_value())) + return std::nullopt; + std::chrono::year_month_day const date{std::chrono::year{*year}, std::chrono::month{static_cast(*month)}, + std::chrono::day{static_cast(*dayofmonth)}}; + if (false == date.ok()) + return std::nullopt; + return day{date}; +} + +std::string format_day(day const Day) { + std::chrono::year_month_day const date{Day}; + return std::format("{:04}-{:02}-{:02}", static_cast(date.year()), static_cast(date.month()), + static_cast(date.day())); +} + +// the day of a stamp line, as written, a day later than Today included. Today for a malformed one: the states after it +// are kept +day stamp_day(std::string_view const Line, day const Today) { + auto text{Line.substr(stamp_prefix.size())}; + while (false == text.empty() && (text.back() == ' ' || text.back() == '\t')) + text.remove_suffix(1); + return parse_day(text).value_or(Today); +} + } // namespace +day today() { + return std::chrono::floor(std::chrono::system_clock::now()); +} + +std::chrono::days expiry() { + return std::chrono::days{std::max(0, Global.odometer_expiry)}; +} + void reading::begin(double const Km, origin const Source) { km = Km; start = Km; @@ -89,12 +146,16 @@ bool reading::moved() const { return km != start; } -std::size_t store::read(std::istream &Input) { +std::size_t store::read(std::istream &Input, day const Today) { std::size_t count{0}; + // the states with no stamp before them, as the builds without the stamps wrote them, count as updated today + auto stamp{Today}; std::string line; while (std::getline(Input, line)) { if (false == line.empty() && line.back() == '\r') line.pop_back(); + if (line.starts_with(stamp_prefix)) + stamp = stamp_day(line, Today); if (line.empty() || line.front() == '#') continue; // the name goes last, it's the rest of the line after the separator @@ -109,7 +170,8 @@ std::size_t store::read(std::istream &Input) { auto const name{line.substr(separator + 1)}; if (false == km.has_value() || name.empty()) continue; - m_states[name] = state{*km, guessed}; + m_states[name] = state{*km, guessed, stamp}; + m_read_latest = std::max(m_read_latest.value_or(stamp), stamp); ++count; } return count; @@ -117,9 +179,23 @@ std::size_t store::read(std::istream &Input) { void store::write(std::ostream &Output) const { Output << "# odometer states of the vehicles: , ~ for one counted from a made up state\n"; + Output << "# the states after a line \"" << stamp_prefix << "\" were last updated on that day (UTC)\n"; Output << std::fixed << std::setprecision(4); - for (auto const &[name, state] : m_states) - Output << (state.guessed ? "~" : "") << state.km << ' ' << name << '\n'; + // by the day, then by the name as the map has them + std::vector::value_type const *> entries; + entries.reserve(m_states.size()); + for (auto const &entry : m_states) + entries.push_back(&entry); + std::ranges::stable_sort(entries, {}, [](auto const *Entry) { return Entry->second.updated; }); + std::optional group; + for (auto const *entry : entries) { + auto const &written{entry->second}; + if (group != written.updated) { + group = written.updated; + Output << stamp_prefix << format_day(written.updated) << '\n'; + } + Output << (written.guessed ? "~" : "") << written.km << ' ' << entry->first << '\n'; + } } std::optional store::find(std::string const &Vehicle) const { @@ -129,6 +205,13 @@ std::optional store::find(std::string const &Vehicle) const { return lookup->second.km; } +std::optional store::updated(std::string const &Vehicle) const { + auto const lookup{m_states.find(Vehicle)}; + if (lookup == m_states.end()) + return std::nullopt; + return lookup->second.updated; +} + bool store::guessed(std::string const &Vehicle) const { auto const lookup{m_states.find(Vehicle)}; return lookup != m_states.end() && lookup->second.guessed; @@ -140,10 +223,10 @@ bool store::newer(state const &Left, state const &Right) { return Left.km > Right.km; } -void store::record(std::string const &Vehicle, reading const &Odometer) { +void store::record(std::string const &Vehicle, reading const &Odometer, day const Today) { if (Vehicle.empty() || false == valid(Odometer.km)) return; - state const recorded{Odometer.km, Odometer.source == origin::guessed}; + state const recorded{Odometer.km, Odometer.source == origin::guessed, Today}; auto const lookup{m_states.find(Vehicle)}; if (lookup == m_states.end()) { if (false == Odometer.moved()) @@ -154,7 +237,10 @@ void store::record(std::string const &Vehicle, reading const &Odometer) { } if (false == newer(recorded, lookup->second)) return; + // a clock set back doesn't move the day back + auto const latest{std::max(lookup->second.updated, Today)}; lookup->second = recorded; + lookup->second.updated = latest; m_modified = true; } @@ -171,11 +257,25 @@ void record(store &States, std::string const &Vehicle, bool const Drivercab, rea void store::merge(store const &Other) { for (auto const &[name, other] : Other.m_states) { auto const [lookup, added] {m_states.try_emplace(name, other)}; - if (false == added && newer(other, lookup->second)) - lookup->second = other; + if (added) + continue; + auto &mine{lookup->second}; + auto const latest{std::max(mine.updated, other.updated)}; + if (newer(other, mine)) + mine = other; + mine.updated = latest; } } +std::size_t store::expire(day const Today, std::chrono::days const Period) { + if (Period <= std::chrono::days::zero()) + return 0; + // not from a later Today alone: a clock set forward, or the first save after a break, doesn't drop every state not + // run in this session + auto const since{std::min(Today, m_read_latest.value_or(Today))}; + return std::erase_if(m_states, [since, Period](auto const &Entry) { return since - Entry.second.updated > Period; }); +} + bool store::holds(store const &Other) const { return std::all_of(Other.m_states.begin(), Other.m_states.end(), [this](auto const &Entry) { auto const lookup{m_states.find(Entry.first)}; @@ -287,20 +387,21 @@ store &states() { namespace { // the states as the file holds them once written, the km rounded to the digits written -store as_written(store const &States) { +store as_written(store const &States, day const Today) { std::stringstream text; States.write(text); store result; - result.read(text); + result.read(text, Today); return result; } } // namespace -bool save(store &States, std::filesystem::path const &File) { +bool save(store &States, std::filesystem::path const &File, day const Today, std::chrono::days const Period) { if (false == States.modified() && false == States.unconfirmed()) return true; std::error_code error; + std::size_t expired{0}; if (File.has_parent_path()) std::filesystem::create_directories(File.parent_path(), error); // other simulations on the machine (multiplayer, parallel runs) keep their states in the same file: what they @@ -309,12 +410,16 @@ bool save(store &States, std::filesystem::path const &File) { store saved; std::ifstream input{File, std::ios::binary}; if (input.is_open()) - saved.read(input); + saved.read(input, Today); States.merge(saved); + // the vehicles not run for long, of this simulation and of the others alike, so the file doesn't keep every + // vehicle ever run. they're logged once the file is written without them: a save that doesn't write it leaves + // them in it (the next save that writes it drops them again), and a write that fails is tried again + expired = States.expire(Today, Period); // another simulation that read the file before the last save of this one and put its own in place after it // dropped the states this one wrote. when the file holds them all, the same or newer, there's nothing to write if (false == States.modified()) { - if (saved.holds(as_written(States))) { + if (saved.holds(as_written(States, Today))) { States.confirmed(); return true; } @@ -353,6 +458,8 @@ bool save(store &States, std::filesystem::path const &File) { return false; } States.saved(); + if (expired > 0) + WriteLog(std::format("Odometer states of {} vehicles not updated for {} days dropped", expired, Period.count())); return true; } diff --git a/vehicle/odometer.h b/vehicle/odometer.h index c7aa0950f..958a15f60 100644 --- a/vehicle/odometer.h +++ b/vehicle/odometer.h @@ -9,6 +9,7 @@ http://mozilla.org/MPL/2.0/. #pragma once +#include #include #include #include @@ -23,6 +24,16 @@ http://mozilla.org/MPL/2.0/. // their own files namespace odometer { +// a calendar day, in UTC +using day = std::chrono::sys_days; +day today(); + +// a state not updated for longer than this is dropped from the store when it's saved: the vehicle wasn't run for that +// long. it's odometer.expiry in eu07.ini (global_settings::odometer_expiry), a year unless set there, 0 for never. +// a year so the vehicles of the scenarios played once a season or once a year, and of the players who take a break of a +// few months, keep their states; the file of the vehicles run within a year stays small all the same +std::chrono::days expiry(); + // the saved odometer states of the vehicles, km by vehicle name. the name is the one the scenario gives the vehicle // (the name of its node, TDynamicObject::name(), e.g. EU07-424), the only identity a vehicle has between the sessions: // the vehicles of the same name in any scenarios share one state, whatever their type, and a vehicle the scenario @@ -31,21 +42,36 @@ namespace odometer { class store { public: // reads the states written by write(). lines " ", "~ " for a state counted - // from a made up one, '#' starts a comment line, a malformed line is skipped. returns the number of states read - std::size_t read(std::istream &Input); + // from a made up one, '#' starts a comment line, a malformed line is skipped. returns the number of states read. + // the day a state was last updated is in a comment line "# updated " before it, which the builds + // without the stamps skip as any comment. a state with no stamp before it (a file of such a build) or with a + // malformed one counts as updated Today. a stamp is kept as written, also one later than Today (a clock set back + // doesn't move the days of the states back, expire() doesn't measure from them) + std::size_t read(std::istream &Input, day Today = today()); + // the states grouped by the day they were last updated, the oldest first, each group after its stamp line void write(std::ostream &Output) const; std::optional find(std::string const &Vehicle) const; // the state of the vehicle is counted from a made up one, which the cab's counter can still replace bool guessed(std::string const &Vehicle) const; + // the day the state of the vehicle was last updated + std::optional updated(std::string const &Vehicle) const; // records the state of a vehicle. one not in the store yet gets in only once it has run, so the vehicles // standing in the sceneries don't fill the file. a recorded state is replaced only by a newer one: a larger - // one, or a known one in place of a guessed one - void record(std::string const &Vehicle, reading const &Odometer); + // one, or a known one in place of a guessed one. a state recorded is updated Today, or keeps its later day: the day + // of a state never goes back + void record(std::string const &Vehicle, reading const &Odometer, day Today = today()); // takes the states of the other store (the file, as other simulations have saved it since) newer than these. // the odometers only count up, so of two states of a vehicle the larger is the newer one. they aren't added - // up: two simulations on one machine (multiplayer) count the same runs of the same vehicles + // up: two simulations on one machine (multiplayer) count the same runs of the same vehicles. a state is updated + // on the later of the days the two stores have void merge(store const &Other); + // drops the states not updated for longer than Period, 0 for none. the period is measured back from Today, or from + // the latest day of the states read() took when that's earlier: the last day the file was updated before this + // simulation read it. so a clock set forward doesn't drop the states at once (nor one set back, the days of the + // states are then later than Today), and a player back after a break keeps them in the session he comes back in; + // the states this session records, updated Today, don't count. returns the number dropped + std::size_t expire(day Today, std::chrono::days Period); // this store holds every state of the other one, the same or a newer one bool holds(store const &Other) const; @@ -65,11 +91,14 @@ private: struct state { double km{0.0}; bool guessed{false}; + day updated{}; }; // the first state is newer than the second one static bool newer(state const &Left, state const &Right); std::map m_states; + // the latest day of the states read() took + std::optional m_read_latest; bool m_modified{false}; bool m_unconfirmed{false}; }; @@ -125,8 +154,10 @@ std::filesystem::path file(); // writes the store to the file when anything was recorded since, merged with what other simulations saved in the // file meanwhile. it's written to a file of this process aside first, then put in place. with nothing recorded since, // the file is read once more after a write, and written again when it lacks any of the states (another simulation's -// save put its file over this one's); otherwise left as it is. returns false when the write failed -bool save(store &States, std::filesystem::path const &File); +// save put its file over this one's); otherwise left as it is. the states, those of the other simulations included, +// not updated for longer than Period (store::expire()) are dropped first; the number dropped is logged by the save that +// writes the file without them. returns false when the write failed +bool save(store &States, std::filesystem::path const &File, day Today = today(), std::chrono::days Period = expiry()); // saves the store of the simulation to its file. a test run doesn't save it bool save();