diff --git a/Encelado/docs/API.md b/Encelado/docs/API.md index 28bd190..bafdd62 100644 --- a/Encelado/docs/API.md +++ b/Encelado/docs/API.md @@ -51,6 +51,8 @@ type Tick = { startedAtUtc: string | null; uptimeSeconds: number; engineTickAgeSeconds: number | null; // da quanto il ciclo di decisione non gira (null a motore fermo) + heartbeatSeconds: number; // intervallo del battito del motore in esecuzione (recovery.heartbeatSeconds, 5-600, cambia senza riavvio); 0 se fermo. + // L'heartbeat è vecchio oltre 3 × heartbeatSeconds + 15 s (105 s con il default 30): è la soglia di /api/health alarms: { halted: boolean; // kill-switch o equity stop: entrate bloccate fino al reset haltKind: "" | "kill" | "equity"; @@ -238,7 +240,9 @@ Tutto ciò che non serve in dashboard: stato del motore, collegamento eToro, quo { asOfUtc: string; engine: { state: string; account: "demo" | "live"; runId: string; strategyHash: string; preset: string; startedUtc: string | null; uptimeSeconds: number; lastTickUtc: string | null; tickAgeSeconds: number | null; - heartbeatUtc: string | null; heartbeatAgeSeconds: number | null; recoveryPending: boolean; recoveryCause: string; + heartbeatUtc: string | null; heartbeatAgeSeconds: number | null; + heartbeatSeconds: number; heartbeatStaleSeconds: number; // intervallo del battito e soglia di /api/health (3 × intervallo + 15 s); 0 a motore fermo + recoveryPending: boolean; recoveryCause: string; entriesBlockedReason: string; entriesBlockedUntilUtc: string | null; paused: boolean; autostart: boolean; orphanPolicy: "Close" | "Report"; instanceLock: string }; api: { endpoint: string; account: "demo" | "live"; state: string; latencyMs: number | null; latencyAvg1mMs: number | null; @@ -340,19 +344,21 @@ type ModelEvaluation = { model: string; rows: number; burnIn: number; auc: numbe ## Comandi -`POST /api/commands/{nome}` con corpo JSON facoltativo. Risposta `{ ok, message, needsPhrase, code?, … }`: `needsPhrase` è `true` (HTTP **409**) quando serve la frase `CONFERMO LIVE`; `code` (se presente) è `needsPhrase`, `restart` o `refused`. Anche `refused` risponde **409**: lo stato rifiuta il comando adesso (un ciclo di apprendimento già in corso, AVVIA durante la manutenzione a motore fermo) e il messaggio dice perché. +`POST /api/commands/{nome}` con corpo JSON facoltativo. Risposta `{ ok, message, needsPhrase, code?, … }`: `needsPhrase` è `true` (HTTP **409**) quando serve la frase `CONFERMO LIVE`; `code` (se presente) è `needsPhrase`, `restart`, `refused` o `timeout`. Anche `refused` risponde **409**: lo stato rifiuta il comando adesso (un ciclo di apprendimento già in corso, AVVIA durante la manutenzione a motore fermo, il motore che si avvia o si ferma, FERMA durante un kill-switch) e il messaggio dice perché. Un comando che il motore non ha eseguito perché si è fermato prima di prenderlo, o a metà, risponde subito `refused` con «comando interrotto: il motore si è fermato» (mai un'attesa di 120 s). `timeout` risponde **504**: il motore, occupato, non ha risposto entro 120 s; il comando resta in coda e l'esito va nel log. Nessun comando risponde 500 per un'attesa scaduta. + +Il ciclo di vita del motore è serializzato: AVVIA, FERMA, i riavvii automatici delle impostazioni e il ciclo di apprendimento a motore fermo passano uno alla volta. FERMA durante un avvio aspetta il motore in costruzione e lo ferma; AVVIA subito dopo FERMA aspetta che il motore precedente abbia lasciato la cartella dati (lo stato resta `stopping` fino ad allora). Un kill-switch, una chiusura (`close`), la chiusura dei residui o una chiusura della bonifica in corso non vengono mai interrotti da FERMA o da un riavvio automatico (409 `refused`); solo l'arresto del processo (SIGTERM) li interrompe, dopo 30 s, e un kill-switch interrotto lascia il residuo registrato (Halted-Residuo). | Nome | Corpo | Effetto | |---|---|---| | `start` | `{ confirm?: string }` | Avvia il motore. In modalità Live serve `confirm = "CONFERMO LIVE"` (409 `needsPhrase` altrimenti). 409 `refused` mentre gira un ciclo di apprendimento a motore fermo. | -| `stop` | — | Ferma il motore; i basket restano sul conto salvo `run.closeOnShutdown`. | +| `stop` | — | Ferma il motore; i basket restano sul conto salvo `run.closeOnShutdown`, con cui il motore stesso, sul suo thread di decisione, blocca le nuove entrate e chiude basket, gambe in attesa e orfane (al più 30 s) prima di fermarsi. 409 `refused` mentre è in corso un kill-switch, una chiusura o la chiusura dei residui. | | `close` | `{ argument: "EURUSD/USDCHF" }` | Chiude il basket. | | `kill` | `{ foreign?: boolean }` | Kill-switch; `foreign` chiude anche le posizioni esterne. Risposta con `positions[]` residue. | | `reset` | `{ reason: string }` | Ripristino in cinque passi; risposta con `steps[]`. | | `residue` | `{ argument?: "all" \| "" }` | Richiude i residui del kill-switch. | | `pause`, `resume` | — | Pausa/ripresa delle entrate. | | `bonifica` | `{ argument: "list" \| "close:" }` | Elenco o chiusura delle orfane; `positions[]`. | -| `learn` | — | Ciclo di apprendimento in background. Motore acceso: lo avvia il motore e la risposta è immediata (avanzamento in `schedule.running` / `runningPhase` di `/api/learning` e in `learning.cycleRunning` del tick). Motore fermo o in errore: manutenzione che prende il lock di istanza della cartella dati; `start` risponde 409 `refused` finché dura. 409 `refused` con un ciclo già in corso, con il motore che si avvia o si ferma, o con il lock tenuto da un altro processo. | +| `learn` | — | Ciclo di apprendimento in background. Motore acceso: lo avvia il motore e la risposta è immediata (avanzamento in `schedule.running` / `runningPhase` di `/api/learning` e in `learning.cycleRunning` del tick). Motore fermo o in errore: manutenzione che prende il lock di istanza della cartella dati; `start` risponde 409 `refused` finché dura. 409 `refused` con un ciclo già in corso, con il motore che si avvia (finché il ciclo di decisione non è partito: verifica, riscaldamento, riconciliazione) o si ferma, o con il lock tenuto da un altro processo. | Le righe di `positions[]` (`kill`, `residue`, `bonifica`) hanno la forma della 5.0: `{ positionId: number; symbol: string; isBuy: boolean; units: number | null; openedUtc: string; unrealizedPnl: number | null; origin: "basket" | "orfana-bot" | "esterna"; basket: string; reason: string }`. @@ -401,7 +407,9 @@ Risposta: version: number } ``` -Con `restart = "needsPhrase"` (HTTP 409) niente è stato scritto: il client chiede la frase e ripete con `confirm`. Con `restart = "refused"` (HTTP 409) niente è stato scritto: il cambio di conto (o delle coppie dei basket) è rifiutato finché ci sono basket aperti, in attesa o ordini senza esito, oppure mancano le chiavi del conto scelto a motore acceso. Valori non validi: HTTP 400 con `errors`. +Con `restart = "needsPhrase"` (HTTP 409) niente è stato scritto: il client chiede la frase e ripete con `confirm`. Con `restart = "refused"` (HTTP 409) niente è stato scritto: il cambio di conto (o delle coppie dei basket) è rifiutato finché ci sono basket aperti, in attesa o ordini senza esito, oppure mancano le chiavi del conto scelto a motore acceso, oppure il cambio riavvierebbe il motore mentre è in corso un kill-switch, una chiusura o la chiusura dei residui. Valori non validi: HTTP 400 con `errors`. + +Il riavvio automatico riavvia solo un motore che è ancora acceso quando tocca a lui: se nel frattempo è arrivato FERMA, il motore resta fermo e i valori salvati valgono al prossimo avvio (`applied = "stored"`, `restart = "none"`). ### Segreti @@ -416,14 +424,14 @@ Con `restart = "needsPhrase"` (HTTP 409) niente è stato scritto: il client chie | `POST /api/settings/secrets/reset` | — | Ricomincia con un deposito vuoto (il vecchio file resta come `.bak`). | | `POST /api/settings/restore` | — | Valori di fabbrica di `encelado.json` (a motore fermo; backup con la data). | -Ogni rotta dei segreti risponde `{ ok, message, restart, needsPhrase, detail, version }`: `detail` è ciò che la verifica ha trovato (utente ed equity del conto, nome del bot Telegram) o il percorso del backup. Chiavi rifiutate da eToro o token rifiutato da Telegram: HTTP 400, niente salvato. Deposito bloccato o chiavi del conto in uso a motore acceso: HTTP 409. +Ogni rotta dei segreti risponde `{ ok, message, restart, needsPhrase, detail, version }`: `detail` è ciò che la verifica ha trovato (utente ed equity del conto, nome del bot Telegram) o il percorso del backup. Chiavi rifiutate da eToro o token rifiutato da Telegram: HTTP 400, niente salvato. Deposito bloccato o chiavi del conto in uso a motore acceso: HTTP 409. Nuove chiavi del conto in uso mentre è in corso un kill-switch, una chiusura o la chiusura dei residui: HTTP 409 `restart = "refused"`, niente salvato. Lo stato del motore si rilegge dopo la verifica: se nel frattempo è arrivato FERMA le chiavi vengono salvate senza riavviare niente. ## Salute `GET /api/health` (libera, per il `HEALTHCHECK` del container): ```ts -{ ok: boolean; state: string; apiState: string; heartbeatAgeSeconds: number | null; diskWritable: boolean; uptimeSeconds: number } +{ ok: boolean; state: string; apiState: string; heartbeatAgeSeconds: number | null; heartbeatSeconds: number; diskWritable: boolean; uptimeSeconds: number } ``` -`ok` è falso se il disco dei dati non è scrivibile o se, a motore acceso, l'heartbeat è più vecchio di 105 s. `apiState` usa le parole di `health.api` del tick (`ok`, `degraded`, `error`, `off`). La prova di scrittura del disco si ripete al più una volta al minuto; nessuno snapshot viene costruito. +`ok` è falso se il disco dei dati non è scrivibile o se, a motore acceso, l'heartbeat è più vecchio di 3 × `heartbeatSeconds` + 15 s (105 s con il default di 30 s; `heartbeatSeconds` è l'intervallo che il motore sta usando, 0 a motore fermo); prima del primo heartbeat, se l'avvio risale a più di dieci minuti. `apiState` usa le parole di `health.api` del tick (`ok`, `degraded`, `error`, `off`). La prova di scrittura del disco si ripete al più una volta al minuto; nessuno snapshot viene costruito. diff --git a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Commands.cs b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Commands.cs index a5a2563..a7e2298 100644 --- a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Commands.cs +++ b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Commands.cs @@ -13,40 +13,148 @@ namespace Encelado.Engine.Baskets; /// Commands from the window, the console or Telegram, executed on the engine's own thread and written to the ledger. public sealed partial class BasketEngine { + /// How long a caller waits for the answer before it hears (the command stays queued). + private static readonly TimeSpan CommandWait = TimeSpan.FromSeconds(120); + + /// How long the close at the stop may take (run.closeOnShutdown); the supervisor cancels the loop afterwards anyway. + private static readonly TimeSpan ShutdownCloseBudget = TimeSpan.FromSeconds(30); + + /// What blocks entries and adds once the stop began (). + private const string StopReason = "arresto del motore in corso"; + + /// Guards : a command is queued before the queue closes, or answered at once after. + private readonly Lock _commandGate = new(); + + /// Set when the run ended: nobody takes commands any more. + private bool _commandsClosed; + + /// Set by the loop when it begins (). + private bool _loopStarted; + + /// Set by : this engine opens nothing new until it is gone. + private bool _stopping; + + /// The answer of a command the engine will never finish: it stopped before taking it, or in the middle of it. + private static CommandResult Interrupted => new(false, "comando interrotto: il motore si è fermato") { Code = CommandResult.Refused }; + + /// True once the decision loop runs: before it (verification, warm-up, reconciliation) commands only wait in the queue. + public bool LoopStarted => Volatile.Read(ref _loopStarted); + public Task ExecuteAsync(EngineCommand command, CancellationToken ct) { ArgumentNullException.ThrowIfNull(command); TaskCompletionSource tcs = new(TaskCreationOptions.RunContinuationsAsynchronously); - _commands.Enqueue((command, tcs)); - return tcs.Task.WaitAsync(TimeSpan.FromSeconds(120), ct); + lock (_commandGate) + { + if (!_commandsClosed) + { + _commands.Enqueue((command, tcs)); + return tcs.Task.WaitAsync(CommandWait, ct); + } + } + + // The run is over (the ledger may be closed already): the log says it, the caller hears it now. + Log.Warn($"comando {command.Kind} non eseguito: il motore si è fermato"); + return Task.FromResult(Interrupted); } private async Task DrainCommandsAsync(CancellationToken ct) { while (_commands.TryDequeue(out (EngineCommand Command, TaskCompletionSource Done) item)) { - CommandResult result; + // Answered on every way out: the result, the failure, or the stop in the middle of it. + CommandResult result = Interrupted; try { result = await RunCommandAsync(item.Command, ct).ConfigureAwait(false); } - catch (Exception ex) when (ex is not OperationCanceledException) + catch (OperationCanceledException) when (ct.IsCancellationRequested) { - Log.Error($"comando {item.Command.Kind} fallito", ex); - result = new CommandResult(false, ex.Message); + Log.Warn($"comando {item.Command.Kind} interrotto: il motore si ferma"); + throw; } - - // Every command from the window, the console or Telegram is in the ledger. - _ledger.Note(_runId, "comando", string.Empty, $"{item.Command.Kind} {item.Command.Argument} ({item.Command.Reason}) → {(result.Ok ? "ok" : "NO")}: {FirstLine(result.Message)}", w => + catch (Exception ex) when (ex is not OutOfMemoryException) { - w.WriteString("comando", item.Command.Kind.ToString()); - w.WriteString("argomento", item.Command.Argument); - w.WriteBoolean("ok", result.Ok); - }); + // A timeout of the command's own (not the stop) is a failure of the command, never the end of the loop. + Log.Error($"comando {item.Command.Kind} fallito", ex); + result = new CommandResult(false, ex is OperationCanceledException ? "comando non concluso: tempo scaduto" : ex.Message); + } + finally + { + NoteCommand(item.Command, result); + item.Done.TrySetResult(result); + } + } + } + + /// + /// No more commands: every one still queued is answered and + /// written to the ledger, later ones are answered at once. Called when the run ends — the + /// loop stopped or the startup failed — and by the dispose, before the ledger closes. + /// + private void CloseCommands() + { + lock (_commandGate) + { + _commandsClosed = true; + } + + while (_commands.TryDequeue(out (EngineCommand Command, TaskCompletionSource Done) item)) + { + CommandResult result = Interrupted; + Log.Warn($"comando {item.Command.Kind} non eseguito: il motore si è fermato prima di prenderlo"); + NoteCommand(item.Command, result); item.Done.TrySetResult(result); } } + /// Every command from the window, the console or Telegram is in the ledger, with its outcome. + private void NoteCommand(EngineCommand command, CommandResult result) => + _ledger.Note(_runId, "comando", string.Empty, $"{command.Kind} {command.Argument} ({command.Reason}) → {(result.Ok ? "ok" : "NO")}: {FirstLine(result.Message)}", w => + { + w.WriteString("comando", command.Kind.ToString()); + w.WriteString("argomento", command.Argument); + w.WriteBoolean("ok", result.Ok); + }); + + /// + /// The stop, on the decision thread (5.1): no new entry and no add from now on — the loop + /// keeps watching the exits until the supervisor cancels it — then, with + /// , every basket, pending leg and orphan of ours closed + /// with the ordinary exit, within . + /// + private async Task PrepareStopAsync(EngineCommand c, CancellationToken ct) + { + _stopping = true; + if (!c.Argument.Equals(EngineCommand.CloseAll, StringComparison.OrdinalIgnoreCase)) + { + return new CommandResult(true, "arresto: nessuna nuova entrata"); + } + + Log.Warn("arresto con closeOnShutdown: chiudo basket, gambe in attesa e orfane prima di fermare il motore"); + using CancellationTokenSource budget = CancellationTokenSource.CreateLinkedTokenSource(ct); + budget.CancelAfter(ShutdownCloseBudget); + try + { + await CloseAllAsync(c.Reason.Length > 0 ? c.Reason : "arresto del motore", budget.Token).ConfigureAwait(false); + } + catch (OperationCanceledException) when (!ct.IsCancellationRequested) + { + string late = string.Create(CultureInfo.InvariantCulture, $"chiusura all'arresto non conclusa entro {ShutdownCloseBudget.TotalSeconds:0} s"); + Log.Warn($"{late}: ciò che resta aperto rimane sul conto con gli stop nativi"); + SaveState(); + return new CommandResult(false, late); + } + + int left = _slots.Count(static s => s.Position is not null || s.State.IsPending()); + string summary = left == 0 + ? "basket chiusi per l'arresto" + : string.Create(CultureInfo.InvariantCulture, $"{left} basket ancora aperti o in attesa dopo la chiusura all'arresto: restano sul conto con gli stop nativi"); + Log.Info(summary); + SaveState(); + return new CommandResult(left == 0, summary); + } + private async Task RunCommandAsync(EngineCommand c, CancellationToken ct) { switch (c.Kind) @@ -123,6 +231,9 @@ public sealed partial class BasketEngine case EngineCommandKind.Bonifica: return await BonificaAsync(c.Argument, ct).ConfigureAwait(false); + case EngineCommandKind.Shutdown: + return await PrepareStopAsync(c, ct).ConfigureAwait(false); + default: return new CommandResult(false, $"comando {c.Kind} non supportato"); } diff --git a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Kill.cs b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Kill.cs index f115faa..7576793 100644 --- a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Kill.cs +++ b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Kill.cs @@ -49,12 +49,64 @@ public sealed partial class BasketEngine { return await KillCoreAsync(reason, includeForeign, ct).ConfigureAwait(false); } + catch (OperationCanceledException) when (ct.IsCancellationRequested) + { + // FERMA and the restarts wait for a kill-switch sent as a command; the process's stop + // (or FERMA during one the engine started itself, from the STOP file) can still cut it: + // what it had not closed yet is the residue, never a clean halt. + RecordInterruptedKill(reason, includeForeign || _strategy.Risk.CloseForeignOnKill); + throw; + } finally { _collect = null; } } + /// + /// A kill-switch cut by a stop: every position of the bot still known — basket legs, + /// pending legs, orphans (and the foreign ones when they were to be closed) — becomes the + /// residue, so the next start shows Halted-Residuo and the reset asks for a flat account + /// instead of resuming a clean halt (the resumed baskets are closed anyway: the halt forces + /// their exit). + /// + private void RecordInterruptedKill(string reason, bool includeForeign) + { + HashSet ids = []; + foreach (BasketSlot slot in _slots) + { + ids.UnionWith(slot.LegPositionIds()); + } + + foreach (ClassifiedPosition c in _classified) + { + if (c.Origin == PositionOrigin.OrphanBot || (includeForeign && c.Origin == PositionOrigin.Foreign)) + { + ids.Add(c.Position.PositionId); + } + } + + ids.Remove(0); + _haltResidue = [.. ids.Select(ResidueRow)]; + _haltReason = string.Create(CultureInfo.InvariantCulture, $"kill-switch ({reason}) INTERROTTO dall'arresto del motore: {ids.Count} posizioni forse ancora sul conto"); + string what = ids.Count == 0 + ? "kill-switch interrotto dall'arresto del motore: nessuna posizione del bot nota ancora aperta" + : $"kill-switch interrotto dall'arresto del motore: residuo {string.Join(", ", ids)}; al prossimo avvio verificalo e chiudilo con «chiudi i residui» o con un nuovo kill-switch"; + Log.Error(what, null); + _ledger.Note(_runId, "kill_switch_interrotto", string.Empty, what, w => w.WriteNumber("residuo", ids.Count)); + SaveState(); + _notifier.Notify(NotificationKind.Alert, "Kill-switch interrotto", TelegramEscape(what)); + } + + /// A residue row as the kill-switch writes it: what the last reconciliation knew of the position. + private PositionInfo ResidueRow(long id) + { + ClassifiedPosition? c = _classified.FirstOrDefault(x => x.Position.PositionId == id); + BrokerPosition? p = c?.Position; + return new PositionInfo(id, p is null ? "?" : SymbolOf(p.InstrumentId), p?.IsBuy ?? false, p?.Units ?? 0, p?.OpenedUtc ?? default, p?.UnrealizedPnl ?? 0, + c?.Origin == PositionOrigin.Foreign ? "esterna" : c?.Origin == PositionOrigin.Basket ? "basket" : "orfana-bot", c?.Basket ?? string.Empty, c?.Reason ?? "non più classificabile"); + } + private async Task KillCoreAsync(string reason, bool includeForeign, CancellationToken ct) { _killSwitched = true; @@ -127,13 +179,7 @@ public sealed partial class BasketEngine } } - _haltResidue = [.. residue.Select(id => - { - ClassifiedPosition? c = _classified.FirstOrDefault(x => x.Position.PositionId == id); - BrokerPosition? p = c?.Position; - return new PositionInfo(id, p is null ? "?" : SymbolOf(p.InstrumentId), p?.IsBuy ?? false, p?.Units ?? 0, p?.OpenedUtc ?? default, p?.UnrealizedPnl ?? 0, - c?.Origin == PositionOrigin.Foreign ? "esterna" : c?.Origin == PositionOrigin.Basket ? "basket" : "orfana-bot", c?.Basket ?? string.Empty, c?.Reason ?? "non più classificabile"); - })]; + _haltResidue = [.. residue.Select(ResidueRow)]; bool flat = residue.Count == 0; List bot = _collect ?? []; @@ -175,8 +221,12 @@ public sealed partial class BasketEngine return report; } - /// Closes every basket, every pending leg and every orphan of ours; foreign positions are left alone. No flatness check: the kill-switch adds it. - public async Task CloseAllAsync(string reason, CancellationToken ct) + /// + /// Closes every basket, every pending leg and every orphan of ours; foreign positions are left + /// alone. No flatness check: the kill-switch adds it. Decision thread only (the kill-switch, + /// the close at the stop): never called from outside the engine. + /// + private async Task CloseAllAsync(string reason, CancellationToken ct) { string code = reason.Contains("equity", StringComparison.OrdinalIgnoreCase) ? "equity_stop" : "kill_switch"; foreach (BasketSlot slot in _slots) diff --git a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.State.cs b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.State.cs index 8027ab6..b05795b 100644 --- a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.State.cs +++ b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.State.cs @@ -10,7 +10,8 @@ namespace Encelado.Engine.Baskets; /// /// The state on disk (data/state/baskets_state.json): open baskets, entries in /// flight, the equity tracker, the session's counters and the halts. Written atomically -/// after every change that matters; read at startup before the reconciliation. +/// () after every change that matters; read at startup before the +/// reconciliation. /// public sealed partial class BasketEngine { @@ -128,8 +129,9 @@ public sealed partial class BasketEngine w.WriteEndObject(); } - File.WriteAllBytes(_statePath + ".tmp", ms.ToArray()); - File.Move(_statePath + ".tmp", _statePath, overwrite: true); + // A unique temporary name (5.1): two writers — the loop and a dispose that did not wait + // for it — never share one, so a torn file can never be moved into place. + AtomicFile.Write(_statePath, ms.ToArray()); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { diff --git a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.View.cs b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.View.cs index e6e4fc1..72e15e3 100644 --- a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.View.cs +++ b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.View.cs @@ -126,6 +126,7 @@ public sealed partial class BasketEngine OrphanPolicy = OrphanPolicy, InstanceLock = _instanceLock?.Path ?? string.Empty, HeartbeatUtc = _lastHeartbeatUtc, + HeartbeatSeconds = _strategy.Recovery.HeartbeatSeconds, RecoveryPending = _recoveryPending, RecoveryCause = _recoveryPending ? _recoveryCause : string.Empty, Api = new ApiView(_apiState, _feed.Endpoint, http.Requests > 0 ? _feed.ClockSkew.TotalSeconds : double.NaN, _strategy.ClockSkewMaxSeconds, diff --git a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.cs b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.cs index 85ff477..d940167 100644 --- a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.cs +++ b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.cs @@ -375,6 +375,19 @@ public sealed partial class BasketEngine : IEngine // ----------------------------------------------------------------------- public async Task RunAsync(CancellationToken ct) + { + try + { + await RunCoreAsync(ct).ConfigureAwait(false); + } + finally + { + // The loop stopped or the startup failed: whatever is still queued is answered now, not after 120 s. + CloseCommands(); + } + } + + private async Task RunCoreAsync(CancellationToken ct) { Log.Info($"motore basket: {_mode} su {_broker.Name}, preset {PresetLabel}, strategia {_configHash}, run {_runId}"); _startedUtc = DateTime.UtcNow; @@ -646,6 +659,8 @@ public sealed partial class BasketEngine : IEngine using PeriodicTimer timer = new(TimeSpan.FromSeconds(1)); TimeSpan reconcile = TimeSpan.FromSeconds(ReconcileSeconds); + // From here on commands are taken: «Esegui ciclo» is refused (409) before it. + Volatile.Write(ref _loopStarted, true); try { while (await timer.WaitForNextTickAsync(ct).ConfigureAwait(false)) @@ -718,7 +733,7 @@ public sealed partial class BasketEngine : IEngine PublishView(); } } - catch (OperationCanceledException) + catch (OperationCanceledException) when (ct.IsCancellationRequested) { Log.Info("arresto richiesto"); } @@ -1156,7 +1171,9 @@ public sealed partial class BasketEngine : IEngine LeverageB = BasketExecutor.ChooseLeverage(slot.B.Instrument, _strategy.OrderLeverage), EquityStopped = _equityStopped, KillSwitched = _killSwitched, - EntriesBlockedReason = _entriesBlocked ?? StaleQuoteReason(slot, now), + + // The stop began (FERMA, the container's stop): nothing new until the loop is cancelled. + EntriesBlockedReason = _stopping ? StopReason : _entriesBlocked ?? StaleQuoteReason(slot, now), IsBarClose = isBarClose, MinutesToNextHigh = f.MinutesToNextHigh, MinutesSinceLastHigh = f.MinutesSinceLastHigh, @@ -1242,7 +1259,7 @@ public sealed partial class BasketEngine : IEngine // live mode, the kill-switch and the reset after an equity stop. private async Task ExecuteEntryAsync(BasketSlot slot, BasketContext ctx, BasketDecision d, CancellationToken ct) { - if (slot.Position is not null || slot.State != BasketState.Idle) + if (_stopping || slot.Position is not null || slot.State != BasketState.Idle) { return; } @@ -1382,7 +1399,7 @@ public sealed partial class BasketEngine : IEngine private async Task ExecuteAddAsync(BasketSlot slot, BasketContext ctx, BasketDecision d, CancellationToken ct) { - if (slot.Position is null || slot.State != BasketState.Open) + if (_stopping || slot.Position is null || slot.State != BasketState.Open) { return; } @@ -1631,6 +1648,9 @@ public sealed partial class BasketEngine : IEngine public async ValueTask DisposeAsync() { + // Answered before the ledger closes (an engine disposed without having run, or whose run is still unwinding). + CloseCommands(); + // A cycle still training is cancelled: its result would have nobody to apply it. _cycles.Cancel(); await _cycles.WaitAsync(TimeSpan.FromSeconds(5)).ConfigureAwait(false); diff --git a/Encelado/src/Encelado.Engine/Baskets/LearningDiskReader.cs b/Encelado/src/Encelado.Engine/Baskets/LearningDiskReader.cs index b05d6b7..56f89a0 100644 --- a/Encelado/src/Encelado.Engine/Baskets/LearningDiskReader.cs +++ b/Encelado/src/Encelado.Engine/Baskets/LearningDiskReader.cs @@ -190,7 +190,7 @@ public static class LearningDiskReader string? text = ReadText(path); return text is null ? null : parse(text); } - catch (Exception ex) when (ex is JsonException or InvalidOperationException or KeyNotFoundException or FormatException or IOException or IndexOutOfRangeException) + catch (Exception ex) when (ex is JsonException or InvalidOperationException or KeyNotFoundException or FormatException or IOException or IndexOutOfRangeException or UnauthorizedAccessException) { if (attempt < 2) { diff --git a/Encelado/src/Encelado.Engine/Engine/BotSnapshot.cs b/Encelado/src/Encelado.Engine/Engine/BotSnapshot.cs index 0d8db47..93a80ae 100644 --- a/Encelado/src/Encelado.Engine/Engine/BotSnapshot.cs +++ b/Encelado/src/Encelado.Engine/Engine/BotSnapshot.cs @@ -305,12 +305,15 @@ public readonly record struct CommandResult(bool Ok, string Message) /// A settings change that only a fresh engine can take. public const string RestartRequired = "restart"; - /// Refused because of the state of the account (open baskets, pending orders). + /// Refused because of the state of the account (open baskets, pending orders) or of the engine (starting, stopping, a kill-switch in progress). public const string Refused = "refused"; + /// The engine did not answer in time (busy): the command stays queued and its outcome goes to the log. + public const string Timeout = "timeout"; + /// Structured data for the caller, when a message is not enough (the bonifica's list of positions). public object? Payload { get; init; } - /// A machine-readable reason next to the message (, , ), or empty. + /// A machine-readable reason next to the message (, , , ), or empty. public string Code { get; init; } = string.Empty; } diff --git a/Encelado/src/Encelado.Engine/Engine/BotSupervisor.cs b/Encelado/src/Encelado.Engine/Engine/BotSupervisor.cs index 4c7f147..e13a95c 100644 --- a/Encelado/src/Encelado.Engine/Engine/BotSupervisor.cs +++ b/Encelado/src/Encelado.Engine/Engine/BotSupervisor.cs @@ -14,6 +14,9 @@ public sealed record HostStatus(string SecretsState, IReadOnlyList Ignor public static readonly HostStatus Unknown = new("empty", []); } +/// What an automatic restart did: whether this call stopped a running engine; the new start's answer, or why nothing happened. +public sealed record RestartResult(bool Stopped, CommandResult Result); + /// /// Owns the engine's lifecycle so the interface can start and stop trading without /// restarting the process, and assembles the snapshot the UI renders. @@ -27,10 +30,24 @@ public sealed record HostStatus(string SecretsState, IReadOnlyList Ignor /// left behind by a previous one (5.1, decision C7): a start without the phrase typed by a /// person — the autostart, an automatic restart — can never reach the real account. /// +/// +/// One lifecycle lock (5.1 review) orders every start, stop, automatic restart, release of a +/// faulted engine and offline cycle, each from its first check to its last state change: a +/// FERMA that lands while an engine is being built waits for it and stops it; an AVVIA that +/// lands while the previous engine is being disposed waits until its instance lock is free +/// (the state reads Stopping until then). A stop clears only the engine it stopped (a +/// generation number per start). A kill-switch, a close or a residue close the engine has in +/// hand is never cut in half by FERMA or a restart (409); only the process's stop may cut it, +/// after . The close at the stop (run.closeOnShutdown) is a +/// command executed on the engine's decision thread, never a call from this one. +/// /// public sealed class BotSupervisor : IAsyncDisposable { private readonly Lock _gate = new(); + + /// The lifecycle lock: one start, stop, restart, release or offline cycle at a time. Never taken inside . + private readonly SemaphoreSlim _lifecycle = new(1, 1); private readonly BotConfig _config; private readonly Func _factory; @@ -44,15 +61,31 @@ public sealed class BotSupervisor : IAsyncDisposable private bool _startedLive; private EngineView? _lastView; + /// Counts the starts: the end of an engine's run and a stop change the fields only while they still belong to that engine. + private long _generation; + + /// The kill-switches, closes and residue closes the engine has now (queued or running): FERMA and the restarts wait for them. + private readonly List _critical = []; + /// The learning cycle of a stopped bot (5.1): trained in the background while this process holds the instance lock. private readonly CycleRunner _offline = new(); private readonly CancellationTokenSource _disposing = new(); private bool _maintenanceActive; private Task? _maintenance; - /// How long «Esegui ciclo» waits for a busy engine (starting, warming up) to take the command; past that it stays queued. + /// How long «Esegui ciclo» waits for a busy engine (a command in progress) to take the command; past that it stays queued. private static readonly TimeSpan LearnCommandWait = TimeSpan.FromSeconds(15); + /// How long a stop waits for the engine's loop to end once it is cancelled; past it the engine is disposed anyway. + private static readonly TimeSpan LoopStopWait = TimeSpan.FromSeconds(45); + + /// + /// How long a stop gives the engine, on its decision thread, to close everything + /// (run.closeOnShutdown) or — at the process's stop — to finish a kill-switch in + /// progress, before it cancels the loop anyway. Thirty seconds; the tests shorten it. + /// + internal TimeSpan ShutdownBudget { get; set; } = TimeSpan.FromSeconds(30); + /// The shared configuration. /// Builds an engine for a start (the tests pass a fake); the default is a without keys. /// The process's notifier, for the default factory. @@ -148,10 +181,122 @@ public sealed class BotSupervisor : IAsyncDisposable /// /// Builds and starts a fresh engine. is true only when /// a person typed the phrase for this very start; the engine refuses Live without it. + /// Waits for a stop in progress to end (the previous engine's instance lock free). /// public async Task StartAsync(bool liveConfirmed = false) { - await ReleaseFaultedEngineAsync().ConfigureAwait(false); + await _lifecycle.WaitAsync().ConfigureAwait(false); + try + { + return await StartCoreAsync(liveConfirmed).ConfigureAwait(false); + } + finally + { + _lifecycle.Release(); + } + } + + /// + /// FERMA: stops the engine. true (FERMA, the console) + /// honours run.closeOnShutdown — the engine closes on its decision thread before its + /// loop is cancelled; false never closes anything. Waits for a start in progress and stops + /// the engine it built. Refused () while a kill-switch, a + /// close or a residue close is in progress: it would be cut in half. + /// + public async Task StopAsync(bool closeBaskets = true) + { + await _lifecycle.WaitAsync().ConfigureAwait(false); + try + { + return await StopCoreAsync(closeBaskets, shutdown: false).ConfigureAwait(false); + } + finally + { + _lifecycle.Release(); + } + } + + /// + /// The process's stop (SIGTERM, Ctrl+C, the console's stop, the dispose): like FERMA, + /// run.closeOnShutdown included, but never refused — a kill-switch in progress gets + /// to finish before the loop is cancelled anyway. + /// + public async Task ShutdownAsync() + { + await _lifecycle.WaitAsync().ConfigureAwait(false); + try + { + return await StopCoreAsync(closeBaskets: true, shutdown: true).ConfigureAwait(false); + } + finally + { + _lifecycle.Release(); + } + } + + /// + /// The automatic restart after a settings change (5.1, decision C11): under the lifecycle + /// lock, only an engine that runs now is stopped — without closing a basket — and started + /// again; an engine a FERMA stopped first stays stopped. Refused (, + /// the engine untouched) while a kill-switch, a close or a residue close is in progress. + /// runs between the stop and the start and may refuse the + /// start (keys missing, secrets locked, Live without the phrase). + /// + public async Task RestartAsync(string reason, bool liveConfirmed, Func? beforeStart = null) + { + await _lifecycle.WaitAsync().ConfigureAwait(false); + try + { + string? busy; + lock (_gate) + { + if (_state != BotState.Running) + { + return new RestartResult(false, new CommandResult(false, "il motore non è in esecuzione: nessun riavvio, le impostazioni valgono al prossimo avvio")); + } + + busy = CriticalInProgress(); + } + + if (busy is not null) + { + Log.Warn($"riavvio automatico non eseguito ({reason}): {busy} in corso"); + return new RestartResult(false, Refused($"{busy} in corso: il motore non viene riavviato finché non è concluso")); + } + + Log.Info($"riavvio automatico del motore: {reason}"); + CommandResult stopped = await StopCoreAsync(closeBaskets: false, shutdown: false).ConfigureAwait(false); + if (!stopped.Ok) + { + Log.Warn($"riavvio automatico non eseguito: {stopped.Message}"); + return new RestartResult(false, stopped); + } + + if (beforeStart?.Invoke() is { } refusal) + { + Log.Warn($"il motore non è ripartito dopo il riavvio automatico: {refusal.Message}"); + return new RestartResult(true, refusal); + } + + CommandResult started = await StartCoreAsync(liveConfirmed).ConfigureAwait(false); + if (!started.Ok) + { + Log.Warn($"il motore non è ripartito dopo il riavvio automatico: {started.Message}"); + } + + return new RestartResult(true, started); + } + finally + { + _lifecycle.Release(); + } + } + + /// A start, the lifecycle lock held. + private async Task StartCoreAsync(bool liveConfirmed) + { + await ReleaseFinishedEngineCoreAsync().ConfigureAwait(false); + long generation; lock (_gate) { if (_state is BotState.Running or BotState.Starting) @@ -167,11 +312,12 @@ public sealed class BotSupervisor : IAsyncDisposable if (_maintenanceActive) { // The offline cycle holds the instance lock and writes the models: one writer at a time (5.1, decision L2). - return new CommandResult(false, "ciclo di apprendimento a motore fermo in corso: AVVIA è bloccato finché non finisce (di solito pochi secondi)") { Code = CommandResult.Refused }; + return Refused("ciclo di apprendimento a motore fermo in corso: AVVIA è bloccato finché non finisce (di solito pochi secondi)"); } _state = BotState.Starting; _error = null; + generation = ++_generation; } Log.Info("── avvio richiesto ──"); @@ -207,40 +353,13 @@ public sealed class BotSupervisor : IAsyncDisposable // RunAsync blocks for the whole session, so it owns a background task and the // caller gets control back immediately so the UI stays responsive. - Task task = Task.Run(async () => - { - try - { - await engine.RunAsync(cts.Token).ConfigureAwait(false); - lock (_gate) - { - _state = BotState.Stopped; - } - } - catch (OperationCanceledException) - { - lock (_gate) - { - _state = BotState.Stopped; - } - } - catch (Exception ex) - { - Log.Error("il motore si è fermato con un errore", ex); - lock (_gate) - { - _state = BotState.Faulted; - _error = ex.Message; - } - } - - Versions.BumpAll(); - }); + CancellationToken token = cts.Token; + Task task = Task.Run(() => RunEngineAsync(engine, generation, token)); lock (_gate) { _engineTask = task; - if (_state == BotState.Starting) + if (_state == BotState.Starting && _generation == generation) { _state = BotState.Running; } @@ -252,7 +371,7 @@ public sealed class BotSupervisor : IAsyncDisposable lock (_gate) { - if (_state == BotState.Faulted) + if (_state == BotState.Faulted && _generation == generation) { return new CommandResult(false, _error ?? "avvio fallito"); } @@ -262,15 +381,52 @@ public sealed class BotSupervisor : IAsyncDisposable } /// - /// Stops the engine. true (FERMA, the container's stop) - /// honours run.closeOnShutdown; false (the automatic restart after a settings - /// change) never closes anything: the next engine takes the baskets over from the state. + /// One engine's session, on its own task. When it ends the state says how — unless a stop + /// is in progress (it sets the final state once the engine is disposed) or a newer engine + /// owns the state. A run that ends without being asked to is a fault, never a quiet stop. /// - public async Task StopAsync(bool closeBaskets = true) + private async Task RunEngineAsync(IEngine engine, long generation, CancellationToken ct) { + Exception? failure = null; + try + { + await engine.RunAsync(ct).ConfigureAwait(false); + if (!ct.IsCancellationRequested) + { + failure = new InvalidOperationException("il ciclo del motore è finito senza che nessuno lo fermasse"); + Log.Error("il motore si è fermato da solo", failure); + } + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) + { + // The stop asked for it. + } + catch (Exception ex) + { + failure = ex; + Log.Error("il motore si è fermato con un errore", ex); + } + + lock (_gate) + { + if (_generation == generation && _state is BotState.Running or BotState.Starting) + { + _state = failure is null ? BotState.Stopped : BotState.Faulted; + _error = failure?.Message ?? _error; + } + } + + Versions.BumpAll(); + } + + /// A stop, the lifecycle lock held: refused while a critical command runs unless . + private async Task StopCoreAsync(bool closeBaskets, bool shutdown) + { + IEngine? engine; CancellationTokenSource? cts; Task? task; - + long generation; + string? busy; lock (_gate) { if (_state is BotState.Stopped or BotState.Stopping) @@ -278,32 +434,77 @@ public sealed class BotSupervisor : IAsyncDisposable return new CommandResult(false, "il bot non è in esecuzione"); } + busy = CriticalInProgress(); + if (busy is not null && !shutdown) + { + return Refused($"{busy} in corso: il motore non si ferma finché non è concluso, per non lasciarlo a metà; riprova fra poco"); + } + _state = BotState.Stopping; + engine = _engine; cts = _engineCts; task = _engineTask; + generation = _generation; } - Log.Info(closeBaskets ? "── arresto richiesto ──" : "── arresto per il riavvio (i basket restano aperti) ──"); - - IEngine? engine; - lock (_gate) + Versions.Bump(Section.System); + bool close = closeBaskets && _config.Run.CloseOnShutdown; + Log.Info(!closeBaskets ? "── arresto per il riavvio (i basket restano aperti) ──" : close ? "── arresto richiesto: chiudo i basket prima (closeOnShutdown) ──" : "── arresto richiesto ──"); + try { - engine = _engine; - } - - if (engine is not null && closeBaskets && _config.Run.CloseOnShutdown) - { - try + // On the engine's own thread, never from here (5.1): with closeOnShutdown it closes + // everything; at the process's stop it lets a kill-switch in progress finish first. + if (engine is not null && task is { IsCompleted: false } && (close || busy is not null)) { - using CancellationTokenSource closing = new(TimeSpan.FromSeconds(30)); - await engine.CloseAllAsync("arresto del motore", closing.Token).ConfigureAwait(false); - } - catch (Exception ex) when (ex is not OperationCanceledException) - { - Log.Error("chiusura dei basket all'arresto non riuscita", ex); + await ShutdownCommandAsync(engine, close, busy).ConfigureAwait(false); } } + finally + { + await FinishStopAsync(engine, cts, task, generation).ConfigureAwait(false); + } + Log.Info("bot fermo"); + return new CommandResult(true, "bot fermo"); + } + + /// + /// Asks the engine, on its decision thread, to take no new entry and — with + /// — to close everything, before its loop is cancelled. The + /// command queues behind the ones already there, so a kill-switch in progress finishes + /// first. At most : a stop never hangs on a slow venue. + /// + private async Task ShutdownCommandAsync(IEngine engine, bool close, string? busy) + { + EngineCommand command = new(EngineCommandKind.Shutdown, close ? EngineCommand.CloseAll : string.Empty, close ? "arresto del motore (closeOnShutdown)" : "arresto del motore"); + TimeSpan budget = ShutdownBudget; + using CancellationTokenSource limit = new(budget); + try + { + CommandResult r = await engine.ExecuteAsync(command, limit.Token).ConfigureAwait(false); + if (!r.Ok) + { + Log.Warn($"arresto: {r.Message}"); + } + } + catch (Exception ex) when (ex is OperationCanceledException or TimeoutException) + { + Log.Warn(close + ? string.Create(CultureInfo.InvariantCulture, $"chiusura dei basket all'arresto non conclusa entro {budget.TotalSeconds:0} s: il motore si ferma comunque, ciò che resta aperto ha solo gli stop nativi") + : string.Create(CultureInfo.InvariantCulture, $"{busy} non concluso entro {budget.TotalSeconds:0} s: il motore si ferma comunque")); + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + Log.Error("chiusura dei basket all'arresto non riuscita", ex); + } + } + + /// + /// The end of every stop: cancel the loop, wait for it, dispose the engine (its instance + /// lock is free after it) and only then read Stopped — for the engine this stop stopped. + /// + private async Task FinishStopAsync(IEngine? engine, CancellationTokenSource? cts, Task? task, long generation) + { if (cts is not null) { await cts.CancelAsync().ConfigureAwait(false); @@ -313,65 +514,143 @@ public sealed class BotSupervisor : IAsyncDisposable { try { - await task.WaitAsync(TimeSpan.FromSeconds(45)).ConfigureAwait(false); + await task.WaitAsync(LoopStopWait).ConfigureAwait(false); } catch (TimeoutException) { - Log.Warn("il motore non si è fermato entro 45 s"); + Log.Warn(string.Create(CultureInfo.InvariantCulture, $"il motore non si è fermato entro {LoopStopWait.TotalSeconds:0} s")); } } - lock (_gate) - { - _lastView = engine?.View ?? _lastView; - _engine = null; - _engineTask = null; - _engineCts = null; - _state = BotState.Stopped; - _startedLive = false; - } - + EngineView? last = engine?.View; if (engine is not null) { - await engine.DisposeAsync().ConfigureAwait(false); + try + { + await engine.DisposeAsync().ConfigureAwait(false); + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + Log.Warn($"motore non rilasciato del tutto: {ex.Message}"); + } } cts?.Dispose(); - Versions.BumpAll(); - Log.Info("bot fermo"); - return new CommandResult(true, "bot fermo"); - } - - /// Hands a saved change to the running engine (no-op when stopped: the next start reads the files). - public Task ApplySettingsAsync(IEnumerable paths, string reason, CancellationToken ct) - { - ArgumentNullException.ThrowIfNull(paths); - return IsRunning - ? ExecuteAsync(new EngineCommand(EngineCommandKind.ApplySettings, string.Join(',', paths), reason), ct) - : Task.FromResult(new CommandResult(true, "motore fermo: vale al prossimo avvio")); - } - - /// Forwards a command to the running engine. - public async Task ExecuteAsync(EngineCommand command, CancellationToken ct) - { - IEngine? engine; lock (_gate) { - engine = _state == BotState.Running ? _engine : null; + if (_generation == generation) + { + _lastView = last ?? _lastView; + _engine = null; + _engineTask = null; + _engineCts = null; + _state = BotState.Stopped; + _startedLive = false; + } + } + + Versions.BumpAll(); + } + + /// Hands a saved change to the running engine; Delivered false when no engine runs (the next start reads the files). + public async Task<(bool Delivered, CommandResult Result)> ApplySettingsAsync(IEnumerable paths, string reason, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(paths); + if (!IsRunning) + { + return (false, new CommandResult(true, "motore fermo: vale al prossimo avvio")); + } + + CommandResult r = await ExecuteAsync(new EngineCommand(EngineCommandKind.ApplySettings, string.Join(',', paths), reason), ct).ConfigureAwait(false); + return (IsRunning || r.Ok, r); + } + + /// + /// Forwards a command to the running engine. A kill-switch, a close or a residue close is + /// tracked while the engine has it: FERMA and the automatic restarts wait for it. A command + /// without an answer in 120 s is answered (it stays in the + /// engine's queue). + /// + public async Task ExecuteAsync(EngineCommand command, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(command); + bool critical = IsCritical(command); + IEngine? engine; + BotState state; + lock (_gate) + { + state = _state; + engine = state == BotState.Running ? _engine : null; + if (engine is not null && critical) + { + // Registered with the state check: a stop either sees it or has already begun (and this is refused). + _critical.Add(command); + } } if (engine is null) { - return new CommandResult(false, "il bot non è in esecuzione"); + return state switch + { + BotState.Starting => Refused("il motore si sta avviando: riprova fra qualche secondo"), + BotState.Stopping => Refused("il motore si sta fermando: comando non eseguito"), + _ => new CommandResult(false, "il bot non è in esecuzione"), + }; } - return await engine.ExecuteAsync(command, ct).ConfigureAwait(false); + try + { + return await engine.ExecuteAsync(command, ct).ConfigureAwait(false); + } + catch (TimeoutException) + { + Log.Warn($"comando {command.Kind} senza risposta entro 120 s: resta in coda, il motore lo esegue appena è libero"); + return new CommandResult(false, "il motore non ha risposto entro 120 s: il comando resta in coda e lo esegue appena è libero; l'esito sarà nel log") { Code = CommandResult.Timeout }; + } + finally + { + if (critical) + { + lock (_gate) + { + _critical.Remove(command); + } + } + } } /// Closes one basket on demand from the interface or the console. public Task CloseAsync(string basket, CancellationToken ct) => ExecuteAsync(new EngineCommand(EngineCommandKind.Close, basket, "chiusura manuale"), ct); + /// What the engine has in hand that a stop or a restart would cut in half, described for the operator; null when nothing. + public string? CommandInProgress + { + get + { + lock (_gate) + { + return CriticalInProgress(); + } + } + } + + /// The first critical command in hand, described; held. + private string? CriticalInProgress() => _critical.Count > 0 ? Describe(_critical[0]) : null; + + /// The commands that send closes to the venue: a stop or a restart must not cut them in half. + private static bool IsCritical(EngineCommand c) => + c.Kind is EngineCommandKind.KillSwitch or EngineCommandKind.Close or EngineCommandKind.CloseResidue || + (c.Kind == EngineCommandKind.Bonifica && c.Argument.StartsWith("close:", StringComparison.OrdinalIgnoreCase)); + + private static string Describe(EngineCommand c) => c.Kind switch + { + EngineCommandKind.KillSwitch => "kill-switch", + EngineCommandKind.Close => $"chiusura di {c.Argument}", + EngineCommandKind.CloseResidue => "chiusura dei residui", + _ => "chiusura di una gamba orfana (bonifica)", + }; + // ----------------------------------------------------------------------- // The learning cycle on demand (5.1, decision L2) // ----------------------------------------------------------------------- @@ -380,8 +659,9 @@ public sealed class BotSupervisor : IAsyncDisposable /// «Esegui ciclo»: with the engine running, a command it answers at once (the training runs /// in the background, the result is applied on its decision thread); with the engine /// stopped or faulted, an offline maintenance that takes the instance lock — START is - /// refused until it ends — and applies the result itself. Refused while a cycle already - /// runs, while the engine starts or stops, or when another process holds the lock. + /// refused until it ends — and applies the result itself. Refused (409) while a cycle + /// already runs, while the engine starts — until its decision loop runs, the only place + /// that takes commands — or stops, or when another process holds the lock. /// public async Task RunLearningCycleAsync(CancellationToken ct = default) { @@ -403,6 +683,10 @@ public sealed class BotSupervisor : IAsyncDisposable switch (state) { + case BotState.Running when engine is not null && !engine.LoopStarted: + // Verification, instruments, warm-up, reconciliation: tens of seconds in which a command only waits (docs/API.md). + return Refused("il motore si sta avviando (verifica, riscaldamento, riconciliazione): «Esegui ciclo» è disponibile appena il ciclo di decisione è partito"); + case BotState.Running when engine is not null: using (CancellationTokenSource wait = CancellationTokenSource.CreateLinkedTokenSource(ct)) { @@ -413,7 +697,7 @@ public sealed class BotSupervisor : IAsyncDisposable } catch (Exception ex) when (ex is OperationCanceledException or TimeoutException && !ct.IsCancellationRequested) { - return new CommandResult(true, "il motore è occupato (avvio o riscaldamento): il ciclo parte appena prende il comando"); + return new CommandResult(true, "il motore è occupato (un comando in corso): il ciclo parte appena prende il comando"); } } @@ -421,38 +705,55 @@ public sealed class BotSupervisor : IAsyncDisposable return Refused("il motore si sta avviando o fermando: riprova fra qualche secondo"); default: - await ReleaseFaultedEngineAsync().ConfigureAwait(false); - return StartOfflineCycle(); + await _lifecycle.WaitAsync(ct).ConfigureAwait(false); + try + { + await ReleaseFinishedEngineCoreAsync().ConfigureAwait(false); + return StartOfflineCycle(); + } + finally + { + _lifecycle.Release(); + } } } /// - /// A faulted engine may still hold the data folder's instance lock (its run threw after - /// taking it): it is disposed — lock released, state saved if it had been read — before - /// anything else takes the lock (a new start, the offline cycle). + /// An engine whose run ended by itself (faulted) may still hold the data folder's instance + /// lock (its run threw after taking it): it is disposed — lock released, state saved if it + /// had been read — before anything else takes the lock (a new start, the offline cycle). + /// The lifecycle lock is held. /// - private async Task ReleaseFaultedEngineAsync() + private async Task ReleaseFinishedEngineCoreAsync() { - IEngine? faulted; + IEngine? finished; CancellationTokenSource? cts; + Task? task; lock (_gate) { - if (_state != BotState.Faulted || _engine is null) + if (_state is not (BotState.Faulted or BotState.Stopped) || _engine is null) { return; } - faulted = _engine; + finished = _engine; cts = _engineCts; - _lastView = faulted.View ?? _lastView; + task = _engineTask; + _lastView = finished.View ?? _lastView; _engine = null; _engineTask = null; _engineCts = null; } + if (task is not null) + { + // Its state is set just before its task ends: never dispose under a run still unwinding. + await Task.WhenAny(task, Task.Delay(LoopStopWait)).ConfigureAwait(false); + } + try { - await faulted.DisposeAsync().ConfigureAwait(false); + await finished.DisposeAsync().ConfigureAwait(false); } catch (Exception ex) when (ex is not OutOfMemoryException) { @@ -466,6 +767,7 @@ public sealed class BotSupervisor : IAsyncDisposable private string InstanceLockPath => Path.Combine(_config.Run.DataPath, "state", "instance.lock"); + /// The offline maintenance's start, the lifecycle lock held: no engine can start or stop meanwhile. private CommandResult StartOfflineCycle() { DateTime now = DateTime.UtcNow; @@ -673,7 +975,8 @@ public sealed class BotSupervisor : IAsyncDisposable await Task.WhenAny(maintenance, Task.Delay(TimeSpan.FromSeconds(10))).ConfigureAwait(false); } - await StopAsync().ConfigureAwait(false); + // The process's stop: never refused (a kill-switch in progress gets its budget, then the loop is cancelled). + await ShutdownAsync().ConfigureAwait(false); _disposing.Dispose(); } } diff --git a/Encelado/src/Encelado.Engine/Engine/EngineView.cs b/Encelado/src/Encelado.Engine/Engine/EngineView.cs index 9ba9c9b..1327db7 100644 --- a/Encelado/src/Encelado.Engine/Engine/EngineView.cs +++ b/Encelado/src/Encelado.Engine/Engine/EngineView.cs @@ -45,6 +45,12 @@ public sealed record EngineView /// The last heartbeat written; before the first. public DateTime HeartbeatUtc { get; init; } + /// + /// The heartbeat interval in force (recovery.heartbeatSeconds, 5-600, changed without a + /// restart): the health check allows three of them and fifteen seconds (). + /// + public int HeartbeatSeconds { get; init; } + public bool RecoveryPending { get; init; } public string RecoveryCause { get; init; } = string.Empty; diff --git a/Encelado/src/Encelado.Engine/Engine/HealthRules.cs b/Encelado/src/Encelado.Engine/Engine/HealthRules.cs index 219cb81..c9889c4 100644 --- a/Encelado/src/Encelado.Engine/Engine/HealthRules.cs +++ b/Encelado/src/Encelado.Engine/Engine/HealthRules.cs @@ -58,4 +58,37 @@ public static class HealthRules /// The most used quota class, 0..1; null when the HTTP layer has none. public static double? QuotaPeak(EngineView? view) => view is { Api.Http.Quotas.Count: > 0 } v ? v.Api.Http.Quotas.Max(static q => q.UsedFraction) : null; + + /// The heartbeat interval of strategy.json when a picture carries none. + public const int DefaultHeartbeatSeconds = 30; + + /// + /// How old a running engine's heartbeat may be before it counts as stale: three intervals and + /// fifteen seconds — 105 s with the default 30, 915 s with 300. The interval is the one the + /// engine publishes (), changed in the settings without a restart. + /// + public static double HeartbeatStaleSeconds(int heartbeatSeconds) => (3.0 * (heartbeatSeconds > 0 ? heartbeatSeconds : DefaultHeartbeatSeconds)) + 15; + + /// The age of the published heartbeat in seconds; null before the first one. + public static double? HeartbeatAgeSeconds(EngineView? view, DateTime nowUtc) => + view is not null && view.HeartbeatUtc != DateTime.MinValue && view.HeartbeatUtc != default ? (nowUtc - view.HeartbeatUtc).TotalSeconds : null; + + /// + /// The container's health (/api/health): a running engine's heartbeat younger than + /// of its own interval — before the first heartbeat, a start + /// less than ten minutes ago (the warm-up). Anything but a running engine is not judged here. + /// + public static bool HeartbeatFresh(EngineStatus status, DateTime nowUtc) + { + ArgumentNullException.ThrowIfNull(status); + if (status.State != BotState.Running) + { + return true; + } + + EngineView? v = status.Live; + return HeartbeatAgeSeconds(v, nowUtc) is { } age + ? age < HeartbeatStaleSeconds(v?.HeartbeatSeconds ?? 0) + : status.StartedUtc is { } started && nowUtc - started < TimeSpan.FromMinutes(10); + } } diff --git a/Encelado/src/Encelado.Engine/Engine/IEngine.cs b/Encelado/src/Encelado.Engine/Engine/IEngine.cs index 38329b8..d60e010 100644 --- a/Encelado/src/Encelado.Engine/Engine/IEngine.cs +++ b/Encelado/src/Encelado.Engine/Engine/IEngine.cs @@ -51,25 +51,53 @@ public enum EngineCommandKind /// ready. Refused () while a cycle is already running. /// Learn, + + /// + /// The stop (FERMA, the container's stop), sent by the supervisor before it cancels the + /// loop: from here on this engine takes no new entry and no add. With Argument = + /// (run.closeOnShutdown) it then closes every + /// basket, pending leg and orphan of ours with the ordinary exit, within thirty seconds. + /// Executed on the decision thread like every command, after the ones queued before it: a + /// kill-switch in progress finishes first (5.1: nothing closes from another thread). + /// + Shutdown, } -public sealed record EngineCommand(EngineCommandKind Kind, string Argument = "", string Reason = ""); +public sealed record EngineCommand(EngineCommandKind Kind, string Argument = "", string Reason = "") +{ + /// The argument of that closes everything first (run.closeOnShutdown). + public const string CloseAll = "chiudi"; +} /// /// The seam between the supervisor and the engine. The engine runs for the whole session /// inside , answers commands on demand and hands the window an /// immutable snapshot on request. An interface rather than the class so the tests can /// drive the supervisor with a fake. +/// +/// Nothing outside the engine touches its state (5.1): every action — the close at the stop +/// included () — is a command executed on its decision +/// thread; the rest of the members read published pictures. +/// /// public interface IEngine : IAsyncDisposable { Task RunAsync(CancellationToken ct); - /// Closes every open basket, for the shutdown path. - Task CloseAllAsync(string reason, CancellationToken ct); - + /// + /// Queues a command for the decision thread and waits for its answer (at most 120 s, then + /// ). Every command gets an answer: one the engine never + /// executed because it stopped first — or stopped in the middle of it — is answered + /// "comando interrotto: il motore si è fermato" at once, never left waiting. + /// Task ExecuteAsync(EngineCommand command, CancellationToken ct); + /// + /// True once the decision loop runs, after the startup (verification, instruments, warm-up, + /// reconciliation): only from then on are commands taken. The fakes of the tests are ready at once. + /// + bool LoopStarted => true; + /// /// The 5.0 picture for the console and Telegram, adapted from : /// building it reads nothing the decision thread writes. is the diff --git a/Encelado/src/Encelado.Engine/Engine/SampleData.cs b/Encelado/src/Encelado.Engine/Engine/SampleData.cs index 9141803..9f128e0 100644 --- a/Encelado/src/Encelado.Engine/Engine/SampleData.cs +++ b/Encelado/src/Encelado.Engine/Engine/SampleData.cs @@ -164,6 +164,7 @@ public static partial class SampleData OrphanPolicy = OrphanPolicy.Report, InstanceLock = "/data/data/state/instance.lock", HeartbeatUtc = now.AddSeconds(-(t % 30)), + HeartbeatSeconds = 30, RecoveryPending = false, Api = Api(epoch, now, t), Funds = funds, diff --git a/Encelado/src/Encelado.Engine/Settings/SettingsCatalogue.cs b/Encelado/src/Encelado.Engine/Settings/SettingsCatalogue.cs index 13f1200..b299503 100644 --- a/Encelado/src/Encelado.Engine/Settings/SettingsCatalogue.cs +++ b/Encelado/src/Encelado.Engine/Settings/SettingsCatalogue.cs @@ -255,7 +255,8 @@ public static class SettingsCatalogue g.Fields.Add(Integer(S + "recovery.warmupMinutes", "Riscaldamento dopo recupero o reset", s.Recovery.WarmupMinutes, "minuti", 0, 1440, SettingScope.Engine, "Per quanto le entrate restano bloccate dopo un recupero o un reset, mentre le quotazioni si assestano.")); g.Fields.Add(Integer(S + "recovery.heartbeatSeconds", "Heartbeat ogni", s.Recovery.HeartbeatSeconds, "secondi", 5, 600, SettingScope.Engine, - "Ogni quanto il bot scrive data/state/heartbeat.json: è la prova, per il recupero e per il controllo di salute del container, che il ciclo gira.")); + "Ogni quanto il bot scrive data/state/heartbeat.json: è la prova, per il recupero e per il controllo di salute del container, che il ciclo gira. " + + "Il controllo di salute segnala un problema dopo tre intervalli senza battito più 15 secondi (105 s con 30).")); // Learning (ADR-0006). g.Fields.Add(Bool(S + "learning.enabled", "Apprendimento attivo", s.Learning.Enabled, SettingScope.Engine, diff --git a/Encelado/src/Encelado.Engine/Settings/SettingsRuntime.cs b/Encelado/src/Encelado.Engine/Settings/SettingsRuntime.cs index 9abab36..264f3c8 100644 --- a/Encelado/src/Encelado.Engine/Settings/SettingsRuntime.cs +++ b/Encelado/src/Encelado.Engine/Settings/SettingsRuntime.cs @@ -70,6 +70,12 @@ public sealed record SecretActionResult(bool Ok, string Message, string Restart /// are open (). /// /// +/// The restart itself runs under the supervisor's lifecycle lock +/// (), which FERMA takes too: it restarts only an +/// engine that still runs — a FERMA that came meanwhile is never undone — and never one with a +/// kill-switch, a close or a residue close in progress (answered 409 before anything is written). +/// +/// /// The secrets live in the ; keys are proved on their own /// account before they are saved, the Telegram token with getMe. /// @@ -240,6 +246,12 @@ public sealed class SettingsRuntime return Refused($"mancano le chiavi del conto {(after.IsLive() ? "reale" : "demo")}: inseriscile prima di cambiare conto a motore acceso"); } + // A kill-switch, a close or a residue close is never cut in half by a restart (5.1 review). + if (running && restartFields.Count > 0 && Supervisor.CommandInProgress is { } busy) + { + return Refused($"{busy} in corso: il cambio riavvia il motore e lo interromperebbe a metà. Salva quando è concluso (niente è stato salvato)."); + } + if (running && restartFields.Count > 0 && after.IsLive() && !confirmed) { return new SettingsResult(false, $"il cambio riavvia il motore sul conto reale: scrivi {LiveConfirmation.Phrase} per confermare (niente è stato salvato)", @@ -257,7 +269,9 @@ public sealed class SettingsRuntime await RefreshMemoryAsync(plan.Changed.Keys, accountChange).ConfigureAwait(false); - // The running engine. + // The running engine. "running" was read before the write: a FERMA may have come since, and + // then the files simply count at the next start (the restart reads the state again under the + // supervisor's lifecycle lock and never undoes a stop). string restart = SettingsResult.RestartNone; bool engineOk = true; string engineMessage = string.Empty; @@ -266,15 +280,16 @@ public sealed class SettingsRuntime string paths = string.Join(", ", plan.Changed.Keys); if (restartFields.Count > 0) { - CommandResult r = await RestartCoreAsync(confirmed, $"impostazioni salvate: {paths}").ConfigureAwait(false); - restart = SettingsResult.RestartDone; - engineOk = r.Ok; - engineMessage = r.Message; + (restart, engineOk, engineMessage, running) = Restarted(await RestartCoreAsync(confirmed, $"impostazioni salvate: {paths}").ConfigureAwait(false)); } else if (plan.Changed.Values.Any(static f => f.Scope == SettingScope.Engine)) { - CommandResult r = await ApplyToEngineAsync(plan.Changed.Keys, ct).ConfigureAwait(false); - if (!r.Ok && r.Code == CommandResult.RestartRequired) + (bool delivered, CommandResult r) = await ApplyToEngineAsync(plan.Changed.Keys, ct).ConfigureAwait(false); + if (!delivered) + { + running = false; + } + else if (!r.Ok && r.Code == CommandResult.RestartRequired) { // strategy.json changed what a running engine cannot take (edited by hand as well). if (Supervisor.RunningLive && !confirmed) @@ -284,10 +299,7 @@ public sealed class SettingsRuntime } else { - r = await RestartCoreAsync(confirmed, $"strategia cambiata: {paths}").ConfigureAwait(false); - restart = SettingsResult.RestartDone; - engineOk = r.Ok; - engineMessage = r.Message; + (restart, engineOk, engineMessage, running) = Restarted(await RestartCoreAsync(confirmed, $"strategia cambiata: {paths}").ConfigureAwait(false)); } } else @@ -324,8 +336,9 @@ public sealed class SettingsRuntime /// Hands the change to the engine's decision thread. An engine still warming up (the /// first minute after a start) drains its commands only when its loop begins: the /// command stays queued and is applied then, and the page is not kept waiting. + /// Delivered is false when no engine runs any more (a FERMA came first). /// - private async Task ApplyToEngineAsync(IEnumerable paths, CancellationToken ct) + private async Task<(bool Delivered, CommandResult Result)> ApplyToEngineAsync(IEnumerable paths, CancellationToken ct) { using CancellationTokenSource wait = CancellationTokenSource.CreateLinkedTokenSource(ct); wait.CancelAfter(EngineApplyWait); @@ -336,10 +349,23 @@ public sealed class SettingsRuntime catch (Exception ex) when (ex is OperationCanceledException or TimeoutException && !ct.IsCancellationRequested) { Log.Info("impostazioni in coda: il motore le applica appena finisce ciò che sta facendo (avvio o riscaldamento)"); - return new CommandResult(true, "in coda: il motore le applica appena libero"); + return (true, new CommandResult(true, "in coda: il motore le applica appena libero")); } } + /// + /// What an automatic restart means for the answer: done (or stopped and not started + /// again); refused because a kill-switch, a close or a residue close is in progress (the + /// engine untouched, the files saved); or nothing to restart because a FERMA came first + /// (the files count at the next start: Running false). + /// + private static (string Restart, bool EngineOk, string EngineMessage, bool Running) Restarted(RestartResult r) => + r.Stopped + ? (SettingsResult.RestartDone, r.Result.Ok, r.Result.Message, true) + : r.Result.Code == CommandResult.Refused + ? (SettingsResult.RestartNone, false, $"salvato, ma il motore non è stato riavviato: {r.Result.Message}; premi FERMA e poi AVVIA quando è concluso", true) + : (SettingsResult.RestartNone, true, string.Empty, false); + private static string Saved(int n) => n == 1 ? "1 valore salvato" : string.Create(CultureInfo.InvariantCulture, $"{n} valori salvati"); private static string Part(int n, string one, string many) => n switch @@ -447,6 +473,17 @@ public sealed class SettingsRuntime } private async Task StartCoreAsync(bool liveConfirmed) + { + if (StartRefusal(liveConfirmed) is { } refusal) + { + return refusal; + } + + return await Supervisor.StartAsync(liveConfirmed: Config.Run.Mode.IsLive() && liveConfirmed).ConfigureAwait(false); + } + + /// Why the engine cannot start now — secrets locked, no keys for the account of the mode, Live without the phrase — or null. + private CommandResult? StartRefusal(bool liveConfirmed) { if (Secrets.State == SecretStoreState.Locked) { @@ -459,27 +496,19 @@ public sealed class SettingsRuntime return new CommandResult(false, $"nessuna chiave eToro per il conto {(live ? "reale" : "demo")}: inseriscile da Impostazioni ▸ Conto"); } - if (live && !liveConfirmed) - { - return new CommandResult(false, $"la modalità Live parte solo con la frase {LiveConfirmation.Phrase}") { Code = CommandResult.NeedsPhrase }; - } - - return await Supervisor.StartAsync(liveConfirmed: live && liveConfirmed).ConfigureAwait(false); + return live && !liveConfirmed + ? new CommandResult(false, $"la modalità Live parte solo con la frase {LiveConfirmation.Phrase}") { Code = CommandResult.NeedsPhrase } + : null; } - /// Stops without closing a basket and starts again; the new engine takes the baskets over from the state. - private async Task RestartCoreAsync(bool liveConfirmed, string reason) - { - Log.Info($"riavvio automatico del motore: {reason}"); - await Supervisor.StopAsync(closeBaskets: false).ConfigureAwait(false); - CommandResult started = await StartCoreAsync(liveConfirmed).ConfigureAwait(false); - if (!started.Ok) - { - Log.Warn($"il motore non è ripartito dopo il riavvio automatico: {started.Message}"); - } - - return started; - } + /// + /// Stops without closing a basket and starts again, all under the supervisor's lifecycle + /// lock: only an engine that still runs is restarted (a FERMA that came first wins), never + /// one with a kill-switch, a close or a residue close in progress; the new engine takes + /// the baskets over from the state. + /// + private Task RestartCoreAsync(bool liveConfirmed, string reason) => + Supervisor.RestartAsync(reason, Config.Run.Mode.IsLive() && liveConfirmed, () => StartRefusal(liveConfirmed)); // ----------------------------------------------------------------------- // Secrets @@ -511,11 +540,19 @@ public sealed class SettingsRuntime string label = demo ? "demo" : "reale"; bool active = Config.Run.Mode.IsLive() != demo; - bool restart = active && Supervisor.IsRunning; bool confirmed = LiveConfirmation.IsConfirmed(confirm); - if (restart && !demo && !confirmed) + if (active && Supervisor.IsRunning) { - return new SecretActionResult(false, $"le chiavi del conto reale in uso riavviano il motore: scrivi {LiveConfirmation.Phrase} per confermare (niente è stato salvato)", SettingsResult.RestartNeedsPhrase, 409); + // Asked before the keys are even checked: nothing is saved until the answer is yes. + if (Supervisor.CommandInProgress is { } busy) + { + return new SecretActionResult(false, $"{busy} in corso: le chiavi del conto in uso riavviano il motore e lo interromperebbero a metà; salvale quando è concluso (niente è stato salvato)", SettingsResult.RestartRefused, 409); + } + + if (!demo && !confirmed) + { + return new SecretActionResult(false, $"le chiavi del conto reale in uso riavviano il motore: scrivi {LiveConfirmation.Phrase} per confermare (niente è stato salvato)", SettingsResult.RestartNeedsPhrase, 409); + } } EtoroOptions options = new() @@ -549,13 +586,29 @@ public sealed class SettingsRuntime Log.Info($"chiavi eToro del conto {label} verificate ({who}, {KeyStores.Mask(api)}) e salvate cifrate"); string message = $"chiavi del conto {label} verificate: {who}; salvate cifrate"; - if (!restart) + + // Read again now: a FERMA or an AVVIA may have come while eToro checked the keys. + if (!(active && Supervisor.IsRunning)) { return new SecretActionResult(true, message) { Detail = who }; } - CommandResult r = await RestartCoreAsync(confirmed, $"nuove chiavi del conto {label}").ConfigureAwait(false); - return new SecretActionResult(r.Ok, r.Ok ? $"{message}; motore riavviato" : $"{message}; il motore non è ripartito: {r.Message}", SettingsResult.RestartDone, r.Ok ? 200 : 500) { Detail = who }; + if (!demo && !confirmed) + { + // Started in Live meanwhile, without the phrase for this save: saved, not restarted. + return new SecretActionResult(true, $"{message}; il motore in Live non è stato riavviato: per usarle premi FERMA e poi AVVIA con {LiveConfirmation.Phrase}") { Detail = who }; + } + + RestartResult r = await RestartCoreAsync(confirmed, $"nuove chiavi del conto {label}").ConfigureAwait(false); + if (!r.Stopped) + { + // A FERMA came first (the keys count at the next start), or a kill-switch is in progress. + return new SecretActionResult(true, r.Result.Code == CommandResult.Refused + ? $"{message}; il motore NON è stato riavviato ({r.Result.Message}): per usarle premi FERMA e poi AVVIA quando è concluso" + : message) { Detail = who }; + } + + return new SecretActionResult(r.Result.Ok, r.Result.Ok ? $"{message}; motore riavviato" : $"{message}; il motore non è ripartito: {r.Result.Message}", SettingsResult.RestartDone, r.Result.Ok ? 200 : 500) { Detail = who }; } catch (InvalidOperationException ex) { diff --git a/Encelado/src/Encelado.Server/Program.cs b/Encelado/src/Encelado.Server/Program.cs index 807049a..eedf45c 100644 --- a/Encelado/src/Encelado.Server/Program.cs +++ b/Encelado/src/Encelado.Server/Program.cs @@ -287,7 +287,17 @@ public static class Program // Stop requested. } - await supervisor.StopAsync().ConfigureAwait(false); + // The process's stop is never refused (a kill-switch in progress gets its thirty seconds); + // whatever goes wrong in it, the web host still stops and the log is still flushed. + try + { + await supervisor.ShutdownAsync().ConfigureAwait(false); + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + Log.Error("arresto del motore non concluso", ex); + } + try { await web.StopAsync(TimeSpan.FromSeconds(5)).ConfigureAwait(false); diff --git a/Encelado/src/Encelado.Server/Web/SnapshotHub.cs b/Encelado/src/Encelado.Server/Web/SnapshotHub.cs index 920d782..6ea677d 100644 --- a/Encelado/src/Encelado.Server/Web/SnapshotHub.cs +++ b/Encelado/src/Encelado.Server/Web/SnapshotHub.cs @@ -144,7 +144,9 @@ public sealed class SnapshotHub : IAsyncDisposable /// /// A new client: a channel of one frame that keeps the newest, filled at once — with the - /// latest frame when it is fresh, with a new one otherwise. + /// latest frame when it is fresh, with a new one otherwise. When that new frame cannot be + /// built the client is not kept: the caller never got its subscription to dispose, and a + /// channel left behind would make the hub build a frame every second for nobody. /// public Subscription Subscribe() { @@ -165,7 +167,15 @@ public sealed class SnapshotHub : IAsyncDisposable _subscribers[id] = channel; if (!fresh) { - Publish(); + try + { + Publish(); + } + catch + { + Unsubscribe(id); + throw; + } } return new Subscription(this, id, channel.Reader); diff --git a/Encelado/src/Encelado.Server/Web/SystemJson.cs b/Encelado/src/Encelado.Server/Web/SystemJson.cs index bb3dd16..e31d339 100644 --- a/Encelado/src/Encelado.Server/Web/SystemJson.cs +++ b/Encelado/src/Encelado.Server/Web/SystemJson.cs @@ -137,6 +137,8 @@ internal static class SystemJson Json.AgeOrNull(w, "tickAgeSeconds", v?.TickUtc, now); Json.TimeOrNull(w, "heartbeatUtc", v?.HeartbeatUtc); Json.AgeOrNull(w, "heartbeatAgeSeconds", v?.HeartbeatUtc, now); + w.WriteNumber("heartbeatSeconds", v?.HeartbeatSeconds ?? 0); + w.WriteNumber("heartbeatStaleSeconds", v is null ? 0 : HealthRules.HeartbeatStaleSeconds(v.HeartbeatSeconds)); w.WriteBoolean("recoveryPending", v?.RecoveryPending ?? false); w.WriteString("recoveryCause", v?.RecoveryCause ?? string.Empty); w.WriteString("entriesBlockedReason", v?.Alarms.EntriesBlockedReason ?? string.Empty); diff --git a/Encelado/src/Encelado.Server/Web/TickWriter.cs b/Encelado/src/Encelado.Server/Web/TickWriter.cs index 2eb9ff2..5fada86 100644 --- a/Encelado/src/Encelado.Server/Web/TickWriter.cs +++ b/Encelado/src/Encelado.Server/Web/TickWriter.cs @@ -58,6 +58,9 @@ internal sealed class TickWriter(WebContext ctx, Func sseClients) Json.TimeOrNull(w, "startedAtUtc", status.StartedUtc); w.WriteNumber("uptimeSeconds", status.StartedUtc is { } st && status.Active ? Math.Round(Math.Max(0, (now - st).TotalSeconds)) : 0); Json.AgeOrNull(w, "engineTickAgeSeconds", v is null || v.TickUtc == DateTime.MinValue ? null : v.TickUtc, now); + + // The running engine's heartbeat interval (a setting applied hot): the health allows three of them and 15 s; 0 when stopped. + w.WriteNumber("heartbeatSeconds", v?.HeartbeatSeconds ?? 0); WriteAlarms(w, status, v, secrets); WriteMoney(w, v, thresholds); w.WriteString("displayCurrency", ctx.Config.Ui.DisplayCurrency); diff --git a/Encelado/src/Encelado.Server/Web/WebHost.cs b/Encelado/src/Encelado.Server/Web/WebHost.cs index c33a451..aebcf89 100644 --- a/Encelado/src/Encelado.Server/Web/WebHost.cs +++ b/Encelado/src/Encelado.Server/Web/WebHost.cs @@ -116,9 +116,6 @@ public static class WebHost /// The placeholder the login page may carry: a wrong password replaces it with the message. public const string LoginErrorPlaceholder = ""; - /// A running engine whose heartbeat is older than this is unhealthy (three heartbeats and a margin). - public static readonly TimeSpan HeartbeatStale = TimeSpan.FromSeconds((3 * 30) + 15); - public static int Port => int.TryParse(Environment.GetEnvironmentVariable(PortVariable), NumberStyles.Integer, CultureInfo.InvariantCulture, out int p) && p is > 0 and < 65536 ? p : DefaultPort; /// @@ -424,31 +421,32 @@ public static class WebHost string reason = body.GetValueOrDefault("reason") ?? string.Empty; CancellationToken ct = http.RequestAborted; CommandResult result; - if (ctx.Sample && name is not ("start" or "stop")) + try { - result = new CommandResult(false, "modalità dimostrativa (--sample): i comandi non vengono eseguiti"); + result = ctx.Sample && name is not ("start" or "stop") + ? new CommandResult(false, "modalità dimostrativa (--sample): i comandi non vengono eseguiti") + : await RunCommandAsync(ctx, name, body, arg, reason, ct).ConfigureAwait(false); } - else + catch (OperationCanceledException) when (ct.IsCancellationRequested) { - result = name switch - { - "start" => await ctx.Start(body.GetValueOrDefault("confirm")).ConfigureAwait(false), - "stop" => ctx.Sample ? new CommandResult(false, "modalità dimostrativa (--sample): il motore non si ferma") : await ctx.Supervisor.StopAsync().ConfigureAwait(false), - "close" => await ctx.Supervisor.ExecuteAsync(new EngineCommand(EngineCommandKind.Close, arg, reason.Length > 0 ? reason : "chiusura manuale dalla web UI"), ct).ConfigureAwait(false), - "kill" => await ctx.Supervisor.ExecuteAsync(new EngineCommand(EngineCommandKind.KillSwitch, body.GetValueOrDefault("foreign") is "true" or "1" ? "esterne" : string.Empty, "kill-switch dalla web UI"), ct).ConfigureAwait(false), - "preset" => new CommandResult(false, "il comando preset non esiste più: il preset si sceglie in Impostazioni ▸ Strategia"), - "reset" => await ctx.Supervisor.ExecuteAsync(new EngineCommand(EngineCommandKind.ResetEquityStop, string.Empty, reason), ct).ConfigureAwait(false), - "residue" => await ctx.Supervisor.ExecuteAsync(new EngineCommand(EngineCommandKind.CloseResidue, arg.Length > 0 ? arg : "all", "chiusura dei residui dalla web UI"), ct).ConfigureAwait(false), - "pause" => await ctx.Supervisor.ExecuteAsync(new EngineCommand(EngineCommandKind.Pause, string.Empty, "pausa dalla web UI"), ct).ConfigureAwait(false), - "resume" => await ctx.Supervisor.ExecuteAsync(new EngineCommand(EngineCommandKind.Resume, string.Empty, "ripresa dalla web UI"), ct).ConfigureAwait(false), - "bonifica" => await ctx.Supervisor.ExecuteAsync(new EngineCommand(EngineCommandKind.Bonifica, arg.Length > 0 ? arg : "list", "bonifica dalla web UI"), ct).ConfigureAwait(false), - "learn" => await (ctx.Learn?.Invoke() ?? ctx.Supervisor.RunLearningCycleAsync(ct)).ConfigureAwait(false), - _ => new CommandResult(false, $"comando {name} sconosciuto"), - }; + // The client went away: nobody to answer. + return; + } + catch (Exception ex) when (ex is TimeoutException or OperationCanceledException) + { + // Never a 500: a command without an answer may still be in the engine's queue. + EngineLog.Warn($"comando {name} senza risposta in tempo: {ex.Message}"); + result = new CommandResult(false, $"il comando {name} non ha avuto risposta in tempo: il motore è occupato; se è in coda lo esegue appena è libero e l'esito sarà nel log") { Code = CommandResult.Timeout }; } - // 409: the phrase is missing, or the state refuses it now (a cycle already running, the offline maintenance holding the lock). - http.Response.StatusCode = result.Ok ? 200 : result.Code is CommandResult.NeedsPhrase or CommandResult.Refused ? 409 : 400; + // 409: the phrase is missing, or the state refuses it now (a cycle already running, the offline maintenance holding + // the lock, the engine starting or stopping, a kill-switch in progress); 504: no answer in time (busy engine). + http.Response.StatusCode = result.Ok ? 200 : result.Code switch + { + CommandResult.NeedsPhrase or CommandResult.Refused => 409, + CommandResult.Timeout => 504, + _ => 400, + }; await Text(http, Json.Result(result.Ok, result.Message, w => { w.WriteBoolean("needsPhrase", result.Code == CommandResult.NeedsPhrase); @@ -480,6 +478,23 @@ public static class WebHost }), "application/json").ConfigureAwait(false); } + /// One command of POST /api/commands/{name}: FERMA to the supervisor (refused while a kill-switch runs), the rest to the engine. + private static async Task RunCommandAsync(WebContext ctx, string name, Dictionary body, string arg, string reason, CancellationToken ct) => name switch + { + "start" => await ctx.Start(body.GetValueOrDefault("confirm")).ConfigureAwait(false), + "stop" => ctx.Sample ? new CommandResult(false, "modalità dimostrativa (--sample): il motore non si ferma") : await ctx.Supervisor.StopAsync().ConfigureAwait(false), + "close" => await ctx.Supervisor.ExecuteAsync(new EngineCommand(EngineCommandKind.Close, arg, reason.Length > 0 ? reason : "chiusura manuale dalla web UI"), ct).ConfigureAwait(false), + "kill" => await ctx.Supervisor.ExecuteAsync(new EngineCommand(EngineCommandKind.KillSwitch, body.GetValueOrDefault("foreign") is "true" or "1" ? "esterne" : string.Empty, "kill-switch dalla web UI"), ct).ConfigureAwait(false), + "preset" => new CommandResult(false, "il comando preset non esiste più: il preset si sceglie in Impostazioni ▸ Strategia"), + "reset" => await ctx.Supervisor.ExecuteAsync(new EngineCommand(EngineCommandKind.ResetEquityStop, string.Empty, reason), ct).ConfigureAwait(false), + "residue" => await ctx.Supervisor.ExecuteAsync(new EngineCommand(EngineCommandKind.CloseResidue, arg.Length > 0 ? arg : "all", "chiusura dei residui dalla web UI"), ct).ConfigureAwait(false), + "pause" => await ctx.Supervisor.ExecuteAsync(new EngineCommand(EngineCommandKind.Pause, string.Empty, "pausa dalla web UI"), ct).ConfigureAwait(false), + "resume" => await ctx.Supervisor.ExecuteAsync(new EngineCommand(EngineCommandKind.Resume, string.Empty, "ripresa dalla web UI"), ct).ConfigureAwait(false), + "bonifica" => await ctx.Supervisor.ExecuteAsync(new EngineCommand(EngineCommandKind.Bonifica, arg.Length > 0 ? arg : "list", "bonifica dalla web UI"), ct).ConfigureAwait(false), + "learn" => await (ctx.Learn?.Invoke() ?? ctx.Supervisor.RunLearningCycleAsync(ct)).ConfigureAwait(false), + _ => new CommandResult(false, $"comando {name} sconosciuto"), + }; + // ----------------------------------------------------------------------- // Sections on demand (decision E3) // ----------------------------------------------------------------------- @@ -755,23 +770,23 @@ public static class WebHost /// /api/health for the container's HEALTHCHECK, every thirty seconds: the /// supervisor's state and the engine's published heartbeat (no snapshot, no file read), the /// disk probe of the last minute. Unhealthy when the data folder cannot be written or a - /// running engine's heartbeat is older than . + /// running engine's heartbeat is older than three of its own intervals and fifteen seconds + /// (: the interval is a setting applied hot, 5-600 s). /// internal static string Health(WebContext ctx, DiskProbe disk) { DateTime now = DateTime.UtcNow; EngineStatus status = ctx.Read.Engine(); EngineView? v = status.Live; - double? age = v is not null && v.HeartbeatUtc != DateTime.MinValue && v.HeartbeatUtc != default ? (now - v.HeartbeatUtc).TotalSeconds : null; - bool running = !ctx.Read.IsSample && status.State == BotState.Running; - bool heartbeatFresh = !running || (age is { } a ? a < HeartbeatStale.TotalSeconds : status.StartedUtc is { } started && now - started < TimeSpan.FromMinutes(10)); + bool heartbeatFresh = ctx.Read.IsSample || HealthRules.HeartbeatFresh(status, now); bool writable = disk.Check().Writable; return Json.Object(w => { w.WriteBoolean("ok", writable && heartbeatFresh); w.WriteString("state", status.State.ToString().ToLowerInvariant()); w.WriteString("apiState", HealthRules.Api(v, now, ctx.Config.Run.PollSeconds)); - Json.Num(w, "heartbeatAgeSeconds", age, 0); + Json.Num(w, "heartbeatAgeSeconds", HealthRules.HeartbeatAgeSeconds(v, now), 0); + w.WriteNumber("heartbeatSeconds", v?.HeartbeatSeconds ?? 0); w.WriteBoolean("diskWritable", writable); w.WriteNumber("uptimeSeconds", Math.Round((now - ctx.StartedUtc).TotalSeconds)); }); diff --git a/Encelado/tests/Encelado.Tests/ApiV2Tests.cs b/Encelado/tests/Encelado.Tests/ApiV2Tests.cs index ee30ead..3babf36 100644 --- a/Encelado/tests/Encelado.Tests/ApiV2Tests.cs +++ b/Encelado/tests/Encelado.Tests/ApiV2Tests.cs @@ -31,6 +31,12 @@ public abstract class ApiHostFixture : IAsyncLifetime /// True: POST /api/commands/learn reaches the supervisor (the learning tests); false: a stub that refuses. protected virtual bool SupervisorLearns => false; + /// The engine the supervisor builds at a start (a fake for the command tests); null: a without keys. + protected virtual Func? EngineFactory => null; + + /// What POST /api/commands/start calls; the default refuses. + protected virtual Func> StartCommand => static _ => Task.FromResult(new CommandResult(false, "non in questo test")); + /// The fixture's folder: encelado.json, strategy.json, data/, knowledge/. protected string Folder => _dir; @@ -51,7 +57,7 @@ public abstract class ApiHostFixture : IAsyncLifetime File.WriteAllText(Path.Combine(_dir, "strategy.json"), Encelado.Core.Baskets.BasketStrategyConfig.DefaultJson); Seed(_dir); BotConfig config = ConfigLoader.Load(configPath, out _); - _supervisor = new BotSupervisor(config); + _supervisor = new BotSupervisor(config, EngineFactory); _history = new HistoryService(config); Context = new WebContext { @@ -62,7 +68,7 @@ public abstract class ApiHostFixture : IAsyncLifetime ConfigPath = configPath, Settings = new Engine.Settings.SettingsRuntime(config, configPath, new SecretStore(_dir, HostPassword, 1_000), _supervisor), Sample = Sample, - Start = static _ => Task.FromResult(new CommandResult(false, "non in questo test")), + Start = StartCommand, Learn = SupervisorLearns ? null : static () => Task.FromResult(new CommandResult(false, "non in questo test")), }; @@ -124,7 +130,7 @@ public abstract class ApiHostFixture : IAsyncLifetime protected static readonly string[] TickKeys = [ - "nowUtc", "v", "frame", "state", "error", "account", "preset", "startedAtUtc", "uptimeSeconds", "engineTickAgeSeconds", "alarms", + "nowUtc", "v", "frame", "state", "error", "account", "preset", "startedAtUtc", "uptimeSeconds", "engineTickAgeSeconds", "heartbeatSeconds", "alarms", "equity", "balance", "availableBalance", "usedMargin", "marginRatio", "peakEquity", "drawdownPct", "equityStopPct", "dailyLossPct", "dailyLossUsedPct", "cumulativeCashFlow", "todayPnl", "todayPnlPct", "todayPnlProvisional", "todayEquityChange", "dayStartEquity", "todayClosed", "openPnl", "accountOpenPnl", "openBaskets", "maxBaskets", "pendingBaskets", "pendingOrders", "orphanLegs", "foreignPositions", "displayCurrency", "theme", "navExpanded", "fxRates", @@ -186,6 +192,7 @@ public sealed class SampleApiTests : ApiHostFixture JsonElement tick = doc.RootElement; IsTick(tick); Assert.Equal("running", tick.GetProperty("state").GetString()); + Assert.Equal(30, tick.GetProperty("heartbeatSeconds").GetInt32()); Assert.Equal(5, tick.GetProperty("baskets").GetArrayLength()); Assert.Equal(1, tick.GetProperty("openBaskets").GetInt32()); Assert.Equal(2, tick.GetProperty("foreignPositions").GetInt32()); @@ -390,7 +397,10 @@ public sealed class SampleApiTests : ApiHostFixture JsonElement s = doc.RootElement; HasKeys(s, "asOfUtc", "engine", "api", "feeds", "telegram", "secrets", "process", "disk", "log", "web", "about"); HasKeys(s.GetProperty("engine"), "state", "account", "runId", "strategyHash", "preset", "startedUtc", "uptimeSeconds", "lastTickUtc", "tickAgeSeconds", "heartbeatUtc", - "heartbeatAgeSeconds", "recoveryPending", "recoveryCause", "entriesBlockedReason", "entriesBlockedUntilUtc", "paused", "autostart", "orphanPolicy", "instanceLock"); + "heartbeatAgeSeconds", "heartbeatSeconds", "heartbeatStaleSeconds", "recoveryPending", "recoveryCause", "entriesBlockedReason", "entriesBlockedUntilUtc", "paused", "autostart", + "orphanPolicy", "instanceLock"); + Assert.Equal(30, s.GetProperty("engine").GetProperty("heartbeatSeconds").GetInt32()); + Assert.Equal(105, s.GetProperty("engine").GetProperty("heartbeatStaleSeconds").GetDouble()); JsonElement api = s.GetProperty("api"); HasKeys(api, "endpoint", "account", "state", "latencyMs", "latencyAvg1mMs", "clockSkewSeconds", "clockSkewMaxSeconds", "consecutiveErrors", "lastError", "quotas"); Assert.Equal(7, api.GetProperty("quotas").GetArrayLength()); @@ -516,11 +526,12 @@ public sealed class StoppedApiTests : ApiHostFixture { using JsonDocument doc = await GetJsonAsync("/api/health"); JsonElement h = doc.RootElement; - HasKeys(h, "ok", "state", "apiState", "heartbeatAgeSeconds", "diskWritable", "uptimeSeconds"); + HasKeys(h, "ok", "state", "apiState", "heartbeatAgeSeconds", "heartbeatSeconds", "diskWritable", "uptimeSeconds"); Assert.True(h.GetProperty("ok").GetBoolean()); Assert.Equal("stopped", h.GetProperty("state").GetString()); Assert.Equal("off", h.GetProperty("apiState").GetString()); Assert.Equal(JsonValueKind.Null, h.GetProperty("heartbeatAgeSeconds").ValueKind); + Assert.Equal(0, h.GetProperty("heartbeatSeconds").GetInt32()); Assert.True(h.GetProperty("diskWritable").GetBoolean()); } @@ -537,6 +548,7 @@ public sealed class StoppedApiTests : ApiHostFixture Assert.Equal(JsonValueKind.Null, tick.GetProperty("todayPnl").ValueKind); Assert.Equal(JsonValueKind.Null, tick.GetProperty("startedAtUtc").ValueKind); Assert.Equal(JsonValueKind.Null, tick.GetProperty("engineTickAgeSeconds").ValueKind); + Assert.Equal(0, tick.GetProperty("heartbeatSeconds").GetInt32()); Assert.Equal(3, tick.GetProperty("maxBaskets").GetInt32()); Assert.Equal(5, tick.GetProperty("baskets").GetArrayLength()); Assert.All(tick.GetProperty("baskets").EnumerateArray(), static b => Assert.Equal("Idle", b.GetProperty("state").GetString())); diff --git a/Encelado/tests/Encelado.Tests/EngineViewTests.cs b/Encelado/tests/Encelado.Tests/EngineViewTests.cs index 84be4ea..1432025 100644 --- a/Encelado/tests/Encelado.Tests/EngineViewTests.cs +++ b/Encelado/tests/Encelado.Tests/EngineViewTests.cs @@ -467,8 +467,6 @@ public sealed class EngineViewTests public Task RunAsync(CancellationToken ct) => Task.Delay(Timeout.Infinite, ct); - public Task CloseAllAsync(string reason, CancellationToken ct) => Task.CompletedTask; - public Task ExecuteAsync(EngineCommand command, CancellationToken ct) => Task.FromResult(new CommandResult(true, "ok")); public BotSnapshot Snapshot(BotState state, string? error, DateTime? startedUtc, EventRow[] events) => SampleSnapshot.Minimal(state); diff --git a/Encelado/tests/Encelado.Tests/LearningReportTests.cs b/Encelado/tests/Encelado.Tests/LearningReportTests.cs index 51895e1..aa297b3 100644 --- a/Encelado/tests/Encelado.Tests/LearningReportTests.cs +++ b/Encelado/tests/Encelado.Tests/LearningReportTests.cs @@ -789,8 +789,6 @@ public sealed class LearnCommandTests : TempFolderTests public Task RunAsync(CancellationToken ct) => Task.Delay(Timeout.Infinite, ct); - public Task CloseAllAsync(string reason, CancellationToken ct) => Task.CompletedTask; - public Task ExecuteAsync(EngineCommand command, CancellationToken ct) { lock (Commands) diff --git a/Encelado/tests/Encelado.Tests/LifecycleTests.cs b/Encelado/tests/Encelado.Tests/LifecycleTests.cs new file mode 100644 index 0000000..6311ba1 --- /dev/null +++ b/Encelado/tests/Encelado.Tests/LifecycleTests.cs @@ -0,0 +1,419 @@ +using System.Net; +using System.Text; +using System.Text.Json; +using Encelado.Core.Baskets; +using Encelado.Engine; +using Encelado.Engine.Baskets; +using Encelado.Engine.Configuration; + +namespace Encelado.Tests; + +/// +/// An engine the lifecycle tests drive step by step: its run, its commands and its dispose +/// wait on gates the test opens, so every interleaving is reproduced on purpose, never by +/// timing. It can hold the data folder's real instance lock, as a does. +/// +internal sealed class GatedEngine(int id, string? lockPath = null) : IEngine +{ + private readonly List<(EngineCommand Command, bool LoopCancelled)> _commands = []; + private InstanceLock? _lock; + private CancellationToken _run; + + public int Id { get; } = id; + + /// Set when the run began (the instance lock is held from then on). + public TaskCompletionSource Started { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + + /// Set when the run ended because its token was cancelled. + public TaskCompletionSource Cancelled { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + + /// Set when the dispose began. + public TaskCompletionSource Disposing { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + + /// When set, the dispose waits for it (a real one saves the state and the models before it lets go of the lock). + public TaskCompletionSource? DisposeGate { get; init; } + + /// When set, the run ends by itself (without being cancelled) as soon as it completes. + public TaskCompletionSource? EndOfRun { get; init; } + + public bool Disposed { get; private set; } + + /// Answers a command; null answers at once. + public Func>? Answer { get; set; } + + /// The commands received, each with whether the loop had already been cancelled then. + public IReadOnlyList<(EngineCommand Command, bool LoopCancelled)> Commands + { + get + { + lock (_commands) + { + return [.. _commands]; + } + } + } + + public async Task RunAsync(CancellationToken ct) + { + _run = ct; + if (lockPath is not null) + { + _lock = InstanceLock.Acquire(lockPath, $"prova-{Id}"); + } + + Started.TrySetResult(); + try + { + if (EndOfRun is not null) + { + await EndOfRun.Task.WaitAsync(ct); + return; + } + + await Task.Delay(Timeout.Infinite, ct); + } + catch (OperationCanceledException) + { + Cancelled.TrySetResult(); + throw; + } + } + + /// The engine's own flag (): false while it would still be warming up. + public bool LoopStarted { get; set; } = true; + + public Task ExecuteAsync(EngineCommand command, CancellationToken ct) + { + lock (_commands) + { + _commands.Add((command, _run.IsCancellationRequested)); + } + + return Answer?.Invoke(command, ct) ?? Task.FromResult(new CommandResult(true, $"motore {Id}: {command.Kind} eseguito")); + } + + public BotSnapshot Snapshot(BotState state, string? error, DateTime? startedUtc, EventRow[] events) => SampleSnapshot.Minimal(state); + + public async ValueTask DisposeAsync() + { + Disposing.TrySetResult(); + if (DisposeGate is not null) + { + await DisposeGate.Task; + } + + _lock?.Dispose(); + Disposed = true; + } +} + +/// +/// The engine's lifecycle (5.1 review, group «ciclo di vita»): one lock orders starts, stops, +/// restarts and the offline cycle; a stop clears only the engine it stopped and reads Stopping +/// until that engine is disposed; a command is always answered, even by an engine that stops. +/// +public sealed class LifecycleTests : TempFolderTests +{ + private static readonly TimeSpan Wait = TimeSpan.FromSeconds(15); + + private BotConfig Config() + { + string configPath = Path.Combine(Root, "encelado.json"); + File.WriteAllText(configPath, ConfigDefaults.Json); + File.WriteAllText(Path.Combine(Root, "strategy.json"), BasketStrategyConfig.DefaultJson); + return ConfigLoader.Load(configPath, out _); + } + + private static string LockPath(BotConfig config) => Path.Combine(config.Run.DataPath, "state", "instance.lock"); + + [Fact] + public async Task FermaDuringAStartWaitsForTheEngineAndStopsIt() + { + BotConfig config = Config(); + using ManualResetEventSlim build = new(false); + TaskCompletionSource building = new(TaskCreationOptions.RunContinuationsAsynchronously); + List engines = []; + await using BotSupervisor supervisor = new(config, (_, _) => + { + // The constructor of a BasketEngine reads the ledger and the order register: FERMA can land meanwhile. + building.TrySetResult(); + build.Wait(Wait); + GatedEngine e = new(engines.Count + 1); + lock (engines) + { + engines.Add(e); + } + + return e; + }); + + Task start = Task.Run(() => supervisor.StartAsync()); + await building.Task.WaitAsync(Wait); + Assert.Equal(BotState.Starting, supervisor.State); + + Task stop = supervisor.StopAsync(); + Assert.False(stop.IsCompleted, "FERMA aspetta il motore in costruzione invece di dichiararlo fermo"); + Assert.Equal(BotState.Starting, supervisor.State); + + build.Set(); + CommandResult started = await start.WaitAsync(Wait); + CommandResult stopped = await stop.WaitAsync(Wait); + + Assert.True(started.Ok, started.Message); + Assert.True(stopped.Ok, stopped.Message); + GatedEngine engine = Assert.Single(engines); + await engine.Cancelled.Task.WaitAsync(Wait); + Assert.True(engine.Disposed); + Assert.Equal(BotState.Stopped, supervisor.State); + Assert.Null(supervisor.Status().Live); + Assert.False((await supervisor.StopAsync()).Ok); + } + + [Fact] + public async Task AvviaRightAfterFermaWaitsForThePreviousEngineToLetGoOfTheFolder() + { + BotConfig config = Config(); + List engines = []; + TaskCompletionSource slowDispose = new(TaskCreationOptions.RunContinuationsAsynchronously); + await using BotSupervisor supervisor = new(config, (_, _) => + { + lock (engines) + { + GatedEngine e = new(engines.Count + 1, LockPath(config)) { DisposeGate = engines.Count == 0 ? slowDispose : null }; + engines.Add(e); + return e; + } + }); + Assert.True((await supervisor.StartAsync()).Ok); + await engines[0].Started.Task.WaitAsync(Wait); + + Task stop = supervisor.StopAsync(); + await engines[0].Disposing.Task.WaitAsync(Wait); + Assert.Equal(BotState.Stopping, supervisor.State); + + // AVVIA while the old engine still holds instance.lock: it waits, instead of failing on "another instance". + Task start = supervisor.StartAsync(); + Assert.False(start.IsCompleted); + slowDispose.SetResult(); + + Assert.True((await stop.WaitAsync(Wait)).Ok); + CommandResult restarted = await start.WaitAsync(Wait); + Assert.True(restarted.Ok, restarted.Message); + Assert.Equal(2, engines.Count); + await engines[1].Started.Task.WaitAsync(Wait); + Assert.Equal(BotState.Running, supervisor.State); + Assert.True((await supervisor.StopAsync()).Ok); + Assert.True(engines[1].Disposed); + } + + [Fact] + public async Task ACommandQueuedToAnEngineThatStopsIsAnsweredAtOnce() + { + BotConfig config = Config(); + BasketEngine engine = new(config, null, false); + Task kill = engine.ExecuteAsync(new EngineCommand(EngineCommandKind.KillSwitch, string.Empty, "prova"), CancellationToken.None); + + // Without keys the start fails before the loop, the only place that took commands. + await Assert.ThrowsAsync(() => engine.RunAsync(CancellationToken.None)); + + CommandResult r = await kill.WaitAsync(TimeSpan.FromSeconds(5)); + Assert.False(r.Ok); + Assert.Contains("interrotto", r.Message, StringComparison.Ordinal); + + // A command that arrives afterwards is answered at once as well. + CommandResult late = await engine.ExecuteAsync(new EngineCommand(EngineCommandKind.Pause, string.Empty, "prova"), CancellationToken.None).WaitAsync(TimeSpan.FromSeconds(5)); + Assert.False(late.Ok); + Assert.False(engine.LoopStarted); + Assert.Equal(30, engine.View!.HeartbeatSeconds); + await engine.DisposeAsync(); + string ledger = File.ReadAllText(Path.Combine(config.Run.DataPath, "ledger", "decisions.jsonl")); + Assert.Contains("\"comando\":\"KillSwitch\"", ledger, StringComparison.Ordinal); + } + + [Fact] + public async Task FermaWithCloseOnShutdownClosesOnTheDecisionThreadBeforeTheLoopIsCancelled() + { + BotConfig config = Config(); + config.Run.CloseOnShutdown = true; + GatedEngine engine = new(1); + await using BotSupervisor supervisor = new(config, (_, _) => engine); + Assert.True((await supervisor.StartAsync()).Ok); + await engine.Started.Task.WaitAsync(Wait); + + CommandResult stopped = await supervisor.StopAsync(); + + Assert.True(stopped.Ok, stopped.Message); + (EngineCommand command, bool loopCancelled) = Assert.Single(engine.Commands); + Assert.Equal(EngineCommandKind.Shutdown, command.Kind); + Assert.Equal(EngineCommand.CloseAll, command.Argument); + Assert.False(loopCancelled, "la chiusura avviene mentre il ciclo gira ancora, sul suo thread"); + await engine.Cancelled.Task.WaitAsync(Wait); + Assert.True(engine.Disposed); + Assert.Equal(BotState.Stopped, supervisor.State); + } + + [Fact] + public async Task ACloseAtTheStopThatOverrunsItsBudgetStillStopsTheEngine() + { + BotConfig config = Config(); + config.Run.CloseOnShutdown = true; + GatedEngine engine = new(1) + { + // A venue that never confirms the closes: the command waits until it is given up. + Answer = static async (_, ct) => + { + await Task.Delay(Timeout.Infinite, ct); + return new CommandResult(true, "mai"); + }, + }; + await using BotSupervisor supervisor = new(config, (_, _) => engine) { ShutdownBudget = TimeSpan.FromMilliseconds(200) }; + Assert.True((await supervisor.StartAsync()).Ok); + + CommandResult stopped = await supervisor.StopAsync().WaitAsync(Wait); + + Assert.True(stopped.Ok, stopped.Message); + await engine.Cancelled.Task.WaitAsync(Wait); + Assert.True(engine.Disposed); + Assert.Equal(BotState.Stopped, supervisor.State); + Assert.False((await supervisor.ExecuteAsync(new EngineCommand(EngineCommandKind.KillSwitch), CancellationToken.None)).Ok); + Assert.True((await supervisor.StartAsync()).Ok); + } + + [Fact] + public async Task TheProcessStopIsNeverRefusedAndGivesAKillSwitchItsBudgetFirst() + { + BotConfig config = Config(); + TaskCompletionSource killing = new(TaskCreationOptions.RunContinuationsAsynchronously); + GatedEngine engine = new(1) { Answer = (c, ct) => c.Kind == EngineCommandKind.KillSwitch ? killing.Task.WaitAsync(ct) : Task.FromResult(new CommandResult(true, "ok")) }; + await using BotSupervisor supervisor = new(config, (_, _) => engine); + Assert.True((await supervisor.StartAsync()).Ok); + Task kill = supervisor.ExecuteAsync(new EngineCommand(EngineCommandKind.KillSwitch, string.Empty, "prova"), CancellationToken.None); + Assert.Equal("kill-switch", supervisor.CommandInProgress); + + CommandResult ferma = await supervisor.StopAsync(); + Assert.False(ferma.Ok); + Assert.Equal(CommandResult.Refused, ferma.Code); + + CommandResult shutdown = await supervisor.ShutdownAsync().WaitAsync(Wait); + Assert.True(shutdown.Ok, shutdown.Message); + Assert.Contains(engine.Commands, static c => c.Command.Kind == EngineCommandKind.Shutdown && c.Command.Argument.Length == 0 && !c.LoopCancelled); + Assert.Equal(BotState.Stopped, supervisor.State); + killing.SetResult(new CommandResult(false, "comando interrotto: il motore si è fermato")); + Assert.False((await kill).Ok); + Assert.Null(supervisor.CommandInProgress); + } + + [Fact] + public async Task EseguiCicloIsRefusedUntilTheDecisionLoopRuns() + { + BotConfig config = Config(); + GatedEngine engine = new(1) { LoopStarted = false }; + await using BotSupervisor supervisor = new(config, (_, _) => engine); + Assert.True((await supervisor.StartAsync()).Ok); + + CommandResult early = await supervisor.RunLearningCycleAsync(); + + Assert.False(early.Ok); + Assert.Equal(CommandResult.Refused, early.Code); + Assert.Empty(engine.Commands); + + engine.LoopStarted = true; + CommandResult ready = await supervisor.RunLearningCycleAsync(); + Assert.True(ready.Ok, ready.Message); + Assert.Equal(EngineCommandKind.Learn, Assert.Single(engine.Commands).Command.Kind); + } + + [Fact] + public async Task AnEngineWhoseRunEndsByItselfIsAFaultAndIsReleasedBeforeTheNextStart() + { + BotConfig config = Config(); + List engines = []; + TaskCompletionSource end = new(TaskCreationOptions.RunContinuationsAsynchronously); + await using BotSupervisor supervisor = new(config, (_, _) => + { + lock (engines) + { + GatedEngine e = new(engines.Count + 1, LockPath(config)) { EndOfRun = engines.Count == 0 ? end : null }; + engines.Add(e); + return e; + } + }); + Assert.True((await supervisor.StartAsync()).Ok); + await engines[0].Started.Task.WaitAsync(Wait); + + end.SetResult(); + using CancellationTokenSource wait = new(Wait); + while (supervisor.State != BotState.Faulted) + { + await Task.Delay(10, wait.Token); + } + + Assert.NotNull(supervisor.Status().Error); + CommandResult again = await supervisor.StartAsync(); + Assert.True(again.Ok, again.Message); + Assert.True(engines[0].Disposed, "il motore precedente lascia il lock prima che il nuovo lo prenda"); + await engines[1].Started.Task.WaitAsync(Wait); + Assert.True((await supervisor.StopAsync()).Ok); + } + + [Fact] + public void TheHeartbeatIsStaleAfterThreeOfItsOwnIntervals() + { + DateTime now = new(2026, 9, 30, 12, 0, 0, DateTimeKind.Utc); + Assert.Equal(105, HealthRules.HeartbeatStaleSeconds(30)); + Assert.Equal(915, HealthRules.HeartbeatStaleSeconds(300)); + Assert.Equal(105, HealthRules.HeartbeatStaleSeconds(0)); + + EngineView view = SampleData.View(now.AddHours(-1), now, BasketStrategyConfig.ParseText(BasketStrategyConfig.DefaultJson, out _)) with { HeartbeatUtc = now.AddSeconds(-200), HeartbeatSeconds = 300 }; + EngineStatus running = new(BotState.Running, null, now.AddHours(-1), view, view); + Assert.True(HealthRules.HeartbeatFresh(running, now), "200 s con un battito ogni 300 s non è un motore fermo"); + Assert.False(HealthRules.HeartbeatFresh(running, now.AddSeconds(800))); + Assert.False(HealthRules.HeartbeatFresh(running with { View = view with { HeartbeatSeconds = 30 } }, now)); + Assert.True(HealthRules.HeartbeatFresh(running with { State = BotState.Stopped }, now.AddDays(1))); + Assert.Equal(200, HealthRules.HeartbeatAgeSeconds(view, now)); + } +} + +/// A command the engine does not answer in time gets an explicit answer, never an HTTP 500 (5.1 review). +public sealed class CommandTimeoutApiTests : ApiHostFixture +{ + protected override bool Sample => false; + + protected override string HostPassword => string.Empty; + + protected override Func? EngineFactory => + static (_, _) => new GatedEngine(1) { Answer = static (_, _) => Task.FromException(new TimeoutException()) }; + + protected override Func> StartCommand => static _ => Task.FromException(new TimeoutException()); + + private async Task<(HttpStatusCode Status, JsonDocument Body)> PostAsync(string command) + { + HttpResponseMessage r = await Client.PostAsync("/api/commands/" + command, new StringContent("{}", Encoding.UTF8, "application/json")); + return (r.StatusCode, JsonDocument.Parse(await r.Content.ReadAsStringAsync())); + } + + [Fact] + public async Task ACommandWithoutAnAnswerInTimeIsNotAServerError() + { + Assert.True((await Context.Supervisor.StartAsync()).Ok); + + (HttpStatusCode status, JsonDocument body) = await PostAsync("kill"); + using (body) + { + Assert.Equal(HttpStatusCode.GatewayTimeout, status); + Assert.False(body.RootElement.GetProperty("ok").GetBoolean()); + Assert.Equal("timeout", body.RootElement.GetProperty("code").GetString()); + Assert.Contains("120 s", body.RootElement.GetProperty("message").GetString(), StringComparison.Ordinal); + } + + (HttpStatusCode startStatus, JsonDocument startBody) = await PostAsync("start"); + using (startBody) + { + Assert.Equal(HttpStatusCode.GatewayTimeout, startStatus); + Assert.False(startBody.RootElement.GetProperty("ok").GetBoolean()); + Assert.NotEqual(string.Empty, startBody.RootElement.GetProperty("message").GetString()); + } + + Assert.True((await Context.Supervisor.StopAsync()).Ok); + } +} diff --git a/Encelado/tests/Encelado.Tests/SettingsRuntimeTests.cs b/Encelado/tests/Encelado.Tests/SettingsRuntimeTests.cs index adfd2e9..a44ca69 100644 --- a/Encelado/tests/Encelado.Tests/SettingsRuntimeTests.cs +++ b/Encelado/tests/Encelado.Tests/SettingsRuntimeTests.cs @@ -26,6 +26,12 @@ public sealed class SettingsRuntimeTests : IAsyncLifetime private int _notifierReconfigured; private int _historyInvalidated; + /// Runs inside a save, after the files are written and before the engine is touched (where a FERMA from another tab can land). + private Action? _duringRefresh; + + /// Runs while eToro "verifies" a pair of keys (up to 25 s in real life). + private Func? _duringKeyCheck; + private sealed class FakeEngine(bool liveConfirmed, ExecutionMode mode) : IEngine { public bool LiveConfirmed { get; } = liveConfirmed; @@ -34,19 +40,14 @@ public sealed class SettingsRuntimeTests : IAsyncLifetime public List Commands { get; } = []; - public bool ClosedAll { get; private set; } - public int OpenBaskets { get; set; } public Func? Answer { get; set; } - public Task RunAsync(CancellationToken ct) => Task.Delay(Timeout.Infinite, ct); + /// A command that takes its time (a kill-switch closing baskets): the task the test completes, or null to answer at once. + public Func?>? Hold { get; set; } - public Task CloseAllAsync(string reason, CancellationToken ct) - { - ClosedAll = true; - return Task.CompletedTask; - } + public Task RunAsync(CancellationToken ct) => Task.Delay(Timeout.Infinite, ct); public Task ExecuteAsync(EngineCommand command, CancellationToken ct) { @@ -55,6 +56,11 @@ public sealed class SettingsRuntimeTests : IAsyncLifetime Commands.Add(command); } + if (Hold?.Invoke(command) is { } held) + { + return held.WaitAsync(ct); + } + return Task.FromResult(Answer?.Invoke(command) ?? new CommandResult(true, "applicato")); } @@ -100,14 +106,26 @@ public sealed class SettingsRuntimeTests : IAsyncLifetime }); _runtime = new SettingsRuntime(config, ConfigPath, secrets, _supervisor, new SettingsHooks { - ReconfigureProcess = _ => Interlocked.Increment(ref _processReconfigured), + ReconfigureProcess = _ => + { + Interlocked.Increment(ref _processReconfigured); + _duringRefresh?.Invoke(); + }, ReconfigureNotifier = () => { Interlocked.Increment(ref _notifierReconfigured); return Task.CompletedTask; }, InvalidateHistory = () => Interlocked.Increment(ref _historyInvalidated), - VerifyEtoroKeys = static (o, _) => o.ApiKey == "rifiutata" ? throw new InvalidOperationException("401 Unauthorized") : Task.FromResult($"utente prova ({o.Environment})"), + VerifyEtoroKeys = async (o, _) => + { + if (_duringKeyCheck is { } during) + { + await during(); + } + + return o.ApiKey == "rifiutata" ? throw new InvalidOperationException("401 Unauthorized") : $"utente prova ({o.Environment})"; + }, VerifyTelegramToken = static (t, _) => Task.FromResult("encelado_bot"), }); } @@ -202,12 +220,85 @@ public sealed class SettingsRuntimeTests : IAsyncLifetime Assert.Equal(SettingsResult.RestartDone, r.Restart); Assert.Equal("restart", Assert.Single(r.Results).Applied); Assert.Equal(2, _engines.Count); - Assert.False(_engines[0].ClosedAll, "un riavvio automatico non chiude mai i basket, anche con closeOnShutdown"); + Assert.DoesNotContain(_engines[0].Commands, static c => c.Kind == EngineCommandKind.Shutdown); Assert.False(_engines[1].LiveConfirmed); Assert.Equal(ExecutionMode.Demo, _engines[1].Mode); Assert.Equal(BotState.Running, Supervisor.State); } + [Fact] + public async Task AFermaDuringASaveIsNotUndoneByTheRestart() + { + Build(); + Assert.True((await Runtime.StartEngineAsync(null)).Ok); + CommandResult? ferma = null; + _duringRefresh = () => ferma = Supervisor.StopAsync().GetAwaiter().GetResult(); + + SettingsResult r = await Runtime.ApplyAsync(new Dictionary { ["strategy:preferDirectCross"] = "true" }, null, CancellationToken.None); + + Assert.NotNull(ferma); + Assert.True(ferma.Value.Ok, ferma.Value.Message); + Assert.True(r.Ok, r.Message); + Assert.Equal(SettingsResult.RestartNone, r.Restart); + Assert.Equal("stored", Assert.Single(r.Results).Applied); + Assert.Single(_engines); + Assert.Equal(BotState.Stopped, Supervisor.State); + Assert.True(BasketStrategyConfig.Load(StrategyPath, out _).PreferDirectCross); + } + + [Fact] + public async Task AFermaWhileTheKeysAreCheckedIsNotUndoneByTheRestart() + { + Build(); + Assert.True((await Runtime.StartEngineAsync(null)).Ok); + _duringKeyCheck = async () => Assert.True((await Supervisor.StopAsync()).Ok); + + SecretActionResult r = await Runtime.SaveKeysAsync("demo", "api-demo-2", "user-demo-2", null, CancellationToken.None); + + Assert.True(r.Ok, r.Message); + Assert.Equal(SettingsResult.RestartNone, r.Restart); + Assert.Equal("api-demo-2", Runtime.Secrets.Etoro(demo: true)!.ApiKey); + Assert.Single(_engines); + Assert.Equal(BotState.Stopped, Supervisor.State); + } + + [Fact] + public async Task AKillSwitchInProgressIsNeverCutByASaveOrByFerma() + { + Build(); + Assert.True((await Runtime.StartEngineAsync(null)).Ok); + TaskCompletionSource killing = new(TaskCreationOptions.RunContinuationsAsynchronously); + _engines[0].Hold = c => c.Kind == EngineCommandKind.KillSwitch ? killing.Task : null; + Task kill = Supervisor.ExecuteAsync(new EngineCommand(EngineCommandKind.KillSwitch, string.Empty, "prova"), CancellationToken.None); + string strategy = File.ReadAllText(StrategyPath); + + SettingsResult save = await Runtime.ApplyAsync(new Dictionary { ["strategy:preferDirectCross"] = "true" }, null, CancellationToken.None); + Assert.False(save.Ok); + Assert.Equal(SettingsResult.RestartRefused, save.Restart); + Assert.Equal(409, save.HttpStatus); + Assert.Contains("kill-switch", save.Message, StringComparison.Ordinal); + Assert.Equal(strategy, File.ReadAllText(StrategyPath)); + + SecretActionResult keys = await Runtime.SaveKeysAsync("demo", "api-demo-2", "user-demo-2", null, CancellationToken.None); + Assert.False(keys.Ok); + Assert.Equal(409, keys.HttpStatus); + Assert.Equal("api-demo", Runtime.Secrets.Etoro(demo: true)!.ApiKey); + + CommandResult ferma = await Supervisor.StopAsync(); + Assert.False(ferma.Ok); + Assert.Equal(CommandResult.Refused, ferma.Code); + Assert.Contains("kill-switch", ferma.Message, StringComparison.Ordinal); + Assert.Equal(BotState.Running, Supervisor.State); + Assert.Single(_engines); + + killing.SetResult(new CommandResult(true, "kill-switch eseguito")); + Assert.True((await kill).Ok); + SettingsResult again = await Runtime.ApplyAsync(new Dictionary { ["strategy:preferDirectCross"] = "true" }, null, CancellationToken.None); + Assert.True(again.Ok, again.Message); + Assert.Equal(SettingsResult.RestartDone, again.Restart); + Assert.Equal(2, _engines.Count); + } + [Fact] public async Task LiveNeverStartsWithoutThePhrase() { diff --git a/Encelado/tests/Encelado.Tests/SnapshotHubTests.cs b/Encelado/tests/Encelado.Tests/SnapshotHubTests.cs index e0ef75d..8f4b073 100644 --- a/Encelado/tests/Encelado.Tests/SnapshotHubTests.cs +++ b/Encelado/tests/Encelado.Tests/SnapshotHubTests.cs @@ -30,6 +30,27 @@ public sealed class SnapshotHubTests Assert.Null(hub.Latest); } + /// A first frame that fails (a model file the process cannot read) leaves no client behind: nothing is built for nobody afterwards. + [Fact] + public async Task AFirstFrameThatFailsLeavesNoSubscriberBehind() + { + int calls = 0; + await using SnapshotHub hub = new((frame, now) => Interlocked.Increment(ref calls) <= 3 + ? throw new UnauthorizedAccessException("learning_state.json: accesso negato") + : Build(frame, now), TimeSpan.FromHours(1)); + hub.Start(); + + for (int i = 0; i < 3; i++) + { + Assert.Throws(() => hub.Subscribe()); + Assert.Equal(0, hub.Subscribers); + } + + using SnapshotHub.Subscription client = hub.Subscribe(); + Assert.Equal(1, hub.Subscribers); + Assert.True(client.Reader.TryRead(out _)); + } + [Fact] public async Task ThreeClientsShareOneFrame() {