diff --git a/src/Anubis.Server/TelegramDesk.cs b/src/Anubis.Server/TelegramDesk.cs index e223d08..36bfbfd 100644 --- a/src/Anubis.Server/TelegramDesk.cs +++ b/src/Anubis.Server/TelegramDesk.cs @@ -140,8 +140,8 @@ internal sealed class TelegramDesk(AnubisHost host) : ITelegramDesk text.AppendLine(Positions(overview.Positions, overview.PositionsWithoutStop)); var local = TimeZoneInfo.ConvertTime(now, Zone).Date; - var today = overview.Next.Count == 0 ? [] : services.Scheduler.Upcoming(20) - .Where(u => TimeZoneInfo.ConvertTime(u.DueUtc, Zone).Date == local) + var today = overview.Next.Count == 0 ? [] : services.Scheduler.Upcoming(200) + .Where(u => u.IsMove && TimeZoneInfo.ConvertTime(u.DueUtc, Zone).Date == local) .Select(u => TimeZoneInfo.ConvertTime(u.DueUtc, Zone).ToString("HH:mm", System.Globalization.CultureInfo.InvariantCulture) + " " + u.Description) .ToList(); if (today.Count > 0) diff --git a/src/Anubis/Supervision/GuardDrill.cs b/src/Anubis/Supervision/GuardDrill.cs index 433ccbe..33fd486 100644 --- a/src/Anubis/Supervision/GuardDrill.cs +++ b/src/Anubis/Supervision/GuardDrill.cs @@ -93,6 +93,15 @@ public static class GuardDrill var intervened = await WaitAsync(() => guardian.Interventions > 0, options.Silence + TimeSpan.FromMinutes(3), cancellationToken).ConfigureAwait(false); var restarted = intervened && await WaitAsync(() => guardian.EngineAlive && guardian.Stage == GuardStages.Running, TimeSpan.FromMinutes(3), cancellationToken) .ConfigureAwait(false); + + // "Running" comes as soon as the scheduler starts: the restart's own work (adopting the stop, cancelling the sale + // left halfway, planning it again) may take a few more seconds on a busy machine. + if (restarted) + { + var noted = guardian.Notes; + await WaitForRepairAsync(data, noted.Count > 0 ? noted[0].At : DateTimeOffset.MinValue, TimeSpan.FromMinutes(2), cancellationToken).ConfigureAwait(false); + } + await stop.CancelAsync().ConfigureAwait(false); var code = await guarding.ConfigureAwait(false); Say($"Motore fermato in ordine alla fine dell'esercitazione (codice {code})."); @@ -122,6 +131,28 @@ public static class GuardDrill return new DrillResult(passed, lines); } + private static async Task WaitForRepairAsync(DataDirectory data, DateTimeOffset intervention, TimeSpan timeout, CancellationToken cancellationToken) + { + var until = SystemClock.Instance.UtcNow + timeout; + await using var db = Database.Open(new DbSettings { Engine = DbEngine.Sqlite, SqlitePath = data.SqliteFile }, allowCreate: false); + while (SystemClock.Instance.UtcNow < until) + { + var done = await db.ReadAsync(async s => + await s.CountAsync("SELECT COUNT(*) FROM executions WHERE side = 'sell' AND purpose = 'exit' AND status = 'canceled' AND reason = @r", + ("r", LiveReasons.Restart)).ConfigureAwait(false) > 0 + && await s.CountAsync("SELECT COUNT(*) FROM planned_orders WHERE side = 'sell'").ConfigureAwait(false) > 1 + && await s.CountAsync("SELECT COUNT(*) FROM journal WHERE code = 'guard_intervention'").ConfigureAwait(false) > 0 + && await s.CountAsync("SELECT COUNT(*) FROM orders WHERE purpose = 'stop' AND created_at > @t", ("t", intervention)).ConfigureAwait(false) > 0, + cancellationToken).ConfigureAwait(false); + if (done) + { + return; + } + + await Task.Delay(TimeSpan.FromMilliseconds(500), cancellationToken).ConfigureAwait(false); + } + } + private static bool Check(bool ok, string yes, string no, Action say) { say((ok ? "OK " : "NO ") + (ok ? yes : no)); diff --git a/src/Anubis/Supervision/Guardian.cs b/src/Anubis/Supervision/Guardian.cs index 43fea09..47b4710 100644 --- a/src/Anubis/Supervision/Guardian.cs +++ b/src/Anubis/Supervision/Guardian.cs @@ -68,6 +68,9 @@ public sealed partial class Guardian(GuardPaths paths, IClock clock, GuardOption private DateTimeOffset _lastBeat; private DateTimeOffset _stepSince; private bool _announced; + + /// Which engine is the current one: a late message from an engine already replaced is ignored. + private int _generation; private IReadOnlyList _keys = []; private DateTimeOffset _lastRound; private DateTimeOffset? _downSince; @@ -100,13 +103,33 @@ public sealed partial class Guardian(GuardPaths paths, IClock clock, GuardOption /// Starts the engine; only for the drill. public void Start(bool fault = false) => StartEngine(fault); - /// A message from the engine. + /// A message from the current engine. public void Receive(GuardMessage message) + { + int current; + lock (_gate) + { + current = _generation; + } + + Receive(current, message); + } + + /// + /// A message from engine number . The pipe of a stopped engine can still deliver what it + /// had sent: a "running" beat would make the new engine look ready, a "stopping" would make its crash look planned. + /// + private void Receive(int generation, GuardMessage message) { ArgumentNullException.ThrowIfNull(message); var now = clock.UtcNow; lock (_gate) { + if (generation != _generation) + { + return; + } + switch (message.Type) { case GuardMessageTypes.Beat: @@ -283,8 +306,10 @@ public sealed partial class Guardian(GuardPaths paths, IClock clock, GuardOption { _engine?.Dispose(); var now = clock.UtcNow; + int generation; lock (_gate) { + generation = ++_generation; _stage = GuardStages.Starting; _step = null; _lastBeat = now; @@ -293,7 +318,7 @@ public sealed partial class Guardian(GuardPaths paths, IClock clock, GuardOption } _lastRound = now; - _engine = start(new EngineStart(fault, Receive)); + _engine = start(new EngineStart(fault, message => Receive(generation, message))); LogStarted(logger, fault); } diff --git a/tests/Anubis.Tests/GuardTests.cs b/tests/Anubis.Tests/GuardTests.cs index 036cb29..f7ecb2c 100644 --- a/tests/Anubis.Tests/GuardTests.cs +++ b/tests/Anubis.Tests/GuardTests.cs @@ -36,6 +36,17 @@ public sealed class GuardTests Assert.AreEqual(GuardNote.Silence, note.Reason); Assert.Contains("Non ho trovato il file di stato", string.Join(" ", note.Lines)); Assert.IsFalse(File.Exists(g.Paths.StopFile)); + + // What the stopped engine's pipe still delivers is not about the new one: it is not "running", and its crash + // is not a planned stop. + g.Engines[0].Beat(GuardStages.Running); + g.Engines[0].Start.OnMessage(new GuardMessage(GuardMessageTypes.Stopping) { Reason = "uscita" }); + Assert.AreEqual(GuardStages.Starting, g.Guardian.Stage); + g.Engine.Beat(GuardStages.Running); + Assert.AreEqual(GuardStages.Running, g.Guardian.Stage); + g.Engine.Exit(1); + await g.PassAsync(TimeSpan.FromSeconds(30)).ConfigureAwait(false); + Assert.HasCount(3, g.Engines, "An exit without notice is restarted, whatever the old engine said."); } [TestMethod]