Fase 6 — Motore dal vivo in simulazione #92

Merged
Alby96 merged 12 commits from fase-6 into main 2026-11-11 22:30:56 +01:00
4 changed files with 71 additions and 4 deletions
Showing only changes of commit 9ae107000b - Show all commits

No files matched your search

+2 -2
View File
@@ -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)
+31
View File
@@ -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<string> say)
{
say((ok ? "OK " : "NO ") + (ok ? yes : no));
+27 -2
View File
@@ -68,6 +68,9 @@ public sealed partial class Guardian(GuardPaths paths, IClock clock, GuardOption
private DateTimeOffset _lastBeat;
private DateTimeOffset _stepSince;
private bool _announced;
/// <summary>Which engine is the current one: a late message from an engine already replaced is ignored.</summary>
private int _generation;
private IReadOnlyList<GuardKeys> _keys = [];
private DateTimeOffset _lastRound;
private DateTimeOffset? _downSince;
@@ -100,13 +103,33 @@ public sealed partial class Guardian(GuardPaths paths, IClock clock, GuardOption
/// <summary>Starts the engine; <paramref name="fault"/> only for the drill.</summary>
public void Start(bool fault = false) => StartEngine(fault);
/// <summary>A message from the engine.</summary>
/// <summary>A message from the current engine.</summary>
public void Receive(GuardMessage message)
{
int current;
lock (_gate)
{
current = _generation;
}
Receive(current, message);
}
/// <summary>
/// A message from engine number <paramref name="generation"/>. 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.
/// </summary>
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);
}
+11
View File
@@ -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]