5.1 revisione, ciclo di vita del motore: un solo lucchetto per avvio, arresto e riavvii, nessun comando senza risposta, chiusura all'arresto sul thread di decisione

FERMA arrivato mentre AVVIA (o un riavvio automatico delle impostazioni) costruiva il motore dichiarava il bot fermo e lasciava un motore che operava senza che kill-switch, FERMA e comandi lo raggiungessero. Ora il supervisore ha un unico lucchetto del ciclo di vita che serializza avvio, arresto, riavvio automatico, rilascio di un motore in errore e ciclo di apprendimento a motore fermo; ogni avvio ha un numero di generazione e un arresto pulisce solo il motore che ha fermato; lo stato resta «stopping» finché il motore vecchio non ha lasciato instance.lock, così AVVIA subito dopo FERMA aspetta invece di fallire con «un'altra istanza». Un motore il cui ciclo finisce senza che nessuno l'abbia fermato è un errore, non un arresto silenzioso.

Il riavvio automatico passa dallo stesso lucchetto, rilegge lo stato e riavvia solo un motore ancora acceso: FERMA arrivato durante un salvataggio o durante la verifica delle chiavi non viene più annullato. Un kill-switch, una chiusura o la chiusura dei residui in corso non vengono mai tagliati a metà: FERMA e i salvataggi che riavvierebbero il motore rispondono 409 prima di scrivere; solo l'arresto del processo li interrompe, dopo 30 s, e un kill-switch interrotto registra il residuo (Halted-Residuo) invece di un blocco pulito.

Ogni comando riceve risposta: quelli in coda o interrotti quando il motore si ferma (anche quando l'avvio fallisce) rispondono subito «comando interrotto: il motore si è fermato» e finiscono nel ledger; un'attesa scaduta risponde 504 con un messaggio esplicito, mai 500. Con closeOnShutdown la chiusura all'arresto è un comando eseguito dal motore sul suo thread di decisione (blocca nuove entrate e aggiunte, chiude entro 30 s, poi il ciclo viene annullato): nessun metodo del motore è più chiamato da un altro thread e una chiusura oltre il tempo non lascia più il supervisore bloccato in «stopping» con il motore che continua a operare. Lo stato si scrive con un file temporaneo unico.

«Esegui ciclo» risponde 409 finché il ciclo di decisione non è partito. SnapshotHub non tiene più un iscritto quando il primo tick fallisce (e un file del modello non leggibile per permessi non fa più fallire ogni tick). Il motore pubblica l'intervallo dell'heartbeat, che si cambia a caldo fino a 600 s: campo heartbeatSeconds nel tick, in /api/system e in /api/health, e il controllo di salute usa 3 × intervallo + 15 s invece dei 105 s fissi. docs/API.md aggiornato.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-09-30 23:11:29 +02:00
1 parent fef00c5cd7
commit 07a00cd91c
26 files changed
+1437 -238

No files matched your search

+16 -8
View File
@@ -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" \| "<positionId>" }` | Richiude i residui del kill-switch. |
| `pause`, `resume` | — | Pausa/ripresa delle entrate. |
| `bonifica` | `{ argument: "list" \| "close:<positionId>" }` | 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.
@@ -13,40 +13,148 @@ namespace Encelado.Engine.Baskets;
/// <summary>Commands from the window, the console or Telegram, executed on the engine's own thread and written to the ledger.</summary>
public sealed partial class BasketEngine
{
/// <summary>How long a caller waits for the answer before it hears <see cref="TimeoutException"/> (the command stays queued).</summary>
private static readonly TimeSpan CommandWait = TimeSpan.FromSeconds(120);
/// <summary>How long the close at the stop may take (<c>run.closeOnShutdown</c>); the supervisor cancels the loop afterwards anyway.</summary>
private static readonly TimeSpan ShutdownCloseBudget = TimeSpan.FromSeconds(30);
/// <summary>What blocks entries and adds once the stop began (<see cref="EngineCommandKind.Shutdown"/>).</summary>
private const string StopReason = "arresto del motore in corso";
/// <summary>Guards <see cref="_commandsClosed"/>: a command is queued before the queue closes, or answered at once after.</summary>
private readonly Lock _commandGate = new();
/// <summary>Set when the run ended: nobody takes commands any more.</summary>
private bool _commandsClosed;
/// <summary>Set by the loop when it begins (<see cref="LoopStarted"/>).</summary>
private bool _loopStarted;
/// <summary>Set by <see cref="EngineCommandKind.Shutdown"/>: this engine opens nothing new until it is gone.</summary>
private bool _stopping;
/// <summary>The answer of a command the engine will never finish: it stopped before taking it, or in the middle of it.</summary>
private static CommandResult Interrupted => new(false, "comando interrotto: il motore si è fermato") { Code = CommandResult.Refused };
/// <summary>True once the decision loop runs: before it (verification, warm-up, reconciliation) commands only wait in the queue.</summary>
public bool LoopStarted => Volatile.Read(ref _loopStarted);
public Task<CommandResult> ExecuteAsync(EngineCommand command, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(command);
TaskCompletionSource<CommandResult> 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<CommandResult> 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);
}
}
}
/// <summary>
/// No more commands: every one still queued is answered <see cref="Interrupted"/> 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.
/// </summary>
private void CloseCommands()
{
lock (_commandGate)
{
_commandsClosed = true;
}
while (_commands.TryDequeue(out (EngineCommand Command, TaskCompletionSource<CommandResult> 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);
}
}
/// <summary>Every command from the window, the console or Telegram is in the ledger, with its outcome.</summary>
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);
});
/// <summary>
/// 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
/// <see cref="EngineCommand.CloseAll"/>, every basket, pending leg and orphan of ours closed
/// with the ordinary exit, within <see cref="ShutdownCloseBudget"/>.
/// </summary>
private async Task<CommandResult> 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<CommandResult> 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");
}
@@ -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;
}
}
/// <summary>
/// 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).
/// </summary>
private void RecordInterruptedKill(string reason, bool includeForeign)
{
HashSet<long> 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));
}
/// <summary>A residue row as the kill-switch writes it: what the last reconciliation knew of the position.</summary>
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<FlattenReport> 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<PendingSettlement> bot = _collect ?? [];
@@ -175,8 +221,12 @@ public sealed partial class BasketEngine
return report;
}
/// <summary>Closes every basket, every pending leg and every orphan of ours; foreign positions are left alone. No flatness check: the kill-switch adds it.</summary>
public async Task CloseAllAsync(string reason, CancellationToken ct)
/// <summary>
/// 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.
/// </summary>
private async Task CloseAllAsync(string reason, CancellationToken ct)
{
string code = reason.Contains("equity", StringComparison.OrdinalIgnoreCase) ? "equity_stop" : "kill_switch";
foreach (BasketSlot slot in _slots)
@@ -10,7 +10,8 @@ namespace Encelado.Engine.Baskets;
/// <summary>
/// The state on disk (<c>data/state/baskets_state.json</c>): 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.
/// (<see cref="AtomicFile"/>) after every change that matters; read at startup before the
/// reconciliation.
/// </summary>
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)
{
@@ -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,
@@ -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);
@@ -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)
{
@@ -305,12 +305,15 @@ public readonly record struct CommandResult(bool Ok, string Message)
/// <summary>A settings change that only a fresh engine can take.</summary>
public const string RestartRequired = "restart";
/// <summary>Refused because of the state of the account (open baskets, pending orders).</summary>
/// <summary>Refused because of the state of the account (open baskets, pending orders) or of the engine (starting, stopping, a kill-switch in progress).</summary>
public const string Refused = "refused";
/// <summary>The engine did not answer in time (busy): the command stays queued and its outcome goes to the log.</summary>
public const string Timeout = "timeout";
/// <summary>Structured data for the caller, when a message is not enough (the bonifica's list of positions).</summary>
public object? Payload { get; init; }
/// <summary>A machine-readable reason next to the message (<see cref="NeedsPhrase"/>, <see cref="RestartRequired"/>, <see cref="Refused"/>), or empty.</summary>
/// <summary>A machine-readable reason next to the message (<see cref="NeedsPhrase"/>, <see cref="RestartRequired"/>, <see cref="Refused"/>, <see cref="Timeout"/>), or empty.</summary>
public string Code { get; init; } = string.Empty;
}
@@ -14,6 +14,9 @@ public sealed record HostStatus(string SecretsState, IReadOnlyList<string> Ignor
public static readonly HostStatus Unknown = new("empty", []);
}
/// <summary>What an automatic restart did: <paramref name="Stopped"/> whether this call stopped a running engine; <paramref name="Result"/> the new start's answer, or why nothing happened.</summary>
public sealed record RestartResult(bool Stopped, CommandResult Result);
/// <summary>
/// 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<string> 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.
/// </para>
/// <para>
/// 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 <see cref="ShutdownBudget"/>. The close at the stop (<c>run.closeOnShutdown</c>) is a
/// command executed on the engine's decision thread, never a call from this one.
/// </para>
/// </summary>
public sealed class BotSupervisor : IAsyncDisposable
{
private readonly Lock _gate = new();
/// <summary>The lifecycle lock: one start, stop, restart, release or offline cycle at a time. Never taken inside <see cref="_gate"/>.</summary>
private readonly SemaphoreSlim _lifecycle = new(1, 1);
private readonly BotConfig _config;
private readonly Func<BotConfig, bool, IEngine> _factory;
@@ -44,15 +61,31 @@ public sealed class BotSupervisor : IAsyncDisposable
private bool _startedLive;
private EngineView? _lastView;
/// <summary>Counts the starts: the end of an engine's run and a stop change the fields only while they still belong to that engine.</summary>
private long _generation;
/// <summary>The kill-switches, closes and residue closes the engine has now (queued or running): FERMA and the restarts wait for them.</summary>
private readonly List<EngineCommand> _critical = [];
/// <summary>The learning cycle of a stopped bot (5.1): trained in the background while this process holds the instance lock.</summary>
private readonly CycleRunner _offline = new();
private readonly CancellationTokenSource _disposing = new();
private bool _maintenanceActive;
private Task? _maintenance;
/// <summary>How long «Esegui ciclo» waits for a busy engine (starting, warming up) to take the command; past that it stays queued.</summary>
/// <summary>How long «Esegui ciclo» waits for a busy engine (a command in progress) to take the command; past that it stays queued.</summary>
private static readonly TimeSpan LearnCommandWait = TimeSpan.FromSeconds(15);
/// <summary>How long a stop waits for the engine's loop to end once it is cancelled; past it the engine is disposed anyway.</summary>
private static readonly TimeSpan LoopStopWait = TimeSpan.FromSeconds(45);
/// <summary>
/// How long a stop gives the engine, on its decision thread, to close everything
/// (<c>run.closeOnShutdown</c>) 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.
/// </summary>
internal TimeSpan ShutdownBudget { get; set; } = TimeSpan.FromSeconds(30);
/// <param name="config">The shared configuration.</param>
/// <param name="factory">Builds an engine for a start (the tests pass a fake); the default is a <see cref="BasketEngine"/> without keys.</param>
/// <param name="notifier">The process's notifier, for the default factory.</param>
@@ -148,10 +181,122 @@ public sealed class BotSupervisor : IAsyncDisposable
/// <summary>
/// Builds and starts a fresh engine. <paramref name="liveConfirmed"/> 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).
/// </summary>
public async Task<CommandResult> StartAsync(bool liveConfirmed = false)
{
await ReleaseFaultedEngineAsync().ConfigureAwait(false);
await _lifecycle.WaitAsync().ConfigureAwait(false);
try
{
return await StartCoreAsync(liveConfirmed).ConfigureAwait(false);
}
finally
{
_lifecycle.Release();
}
}
/// <summary>
/// FERMA: stops the engine. <paramref name="closeBaskets"/> true (FERMA, the console)
/// honours <c>run.closeOnShutdown</c> — 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 (<see cref="CommandResult.Refused"/>) while a kill-switch, a
/// close or a residue close is in progress: it would be cut in half.
/// </summary>
public async Task<CommandResult> StopAsync(bool closeBaskets = true)
{
await _lifecycle.WaitAsync().ConfigureAwait(false);
try
{
return await StopCoreAsync(closeBaskets, shutdown: false).ConfigureAwait(false);
}
finally
{
_lifecycle.Release();
}
}
/// <summary>
/// The process's stop (SIGTERM, Ctrl+C, the console's <c>stop</c>, the dispose): like FERMA,
/// <c>run.closeOnShutdown</c> included, but never refused — a kill-switch in progress gets
/// <see cref="ShutdownBudget"/> to finish before the loop is cancelled anyway.
/// </summary>
public async Task<CommandResult> ShutdownAsync()
{
await _lifecycle.WaitAsync().ConfigureAwait(false);
try
{
return await StopCoreAsync(closeBaskets: true, shutdown: true).ConfigureAwait(false);
}
finally
{
_lifecycle.Release();
}
}
/// <summary>
/// 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 (<see cref="CommandResult.Refused"/>,
/// the engine untouched) while a kill-switch, a close or a residue close is in progress.
/// <paramref name="beforeStart"/> runs between the stop and the start and may refuse the
/// start (keys missing, secrets locked, Live without the phrase).
/// </summary>
public async Task<RestartResult> RestartAsync(string reason, bool liveConfirmed, Func<CommandResult?>? 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();
}
}
/// <summary>A start, the lifecycle lock held.</summary>
private async Task<CommandResult> 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
}
/// <summary>
/// Stops the engine. <paramref name="closeBaskets"/> true (FERMA, the container's stop)
/// honours <c>run.closeOnShutdown</c>; 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.
/// </summary>
public async Task<CommandResult> 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();
}
/// <summary>A stop, the lifecycle lock held: refused while a critical command runs unless <paramref name="shutdown"/>.</summary>
private async Task<CommandResult> 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");
}
/// <summary>
/// Asks the engine, on its decision thread, to take no new entry and — with
/// <paramref name="close"/> — 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 <see cref="ShutdownBudget"/>: a stop never hangs on a slow venue.
/// </summary>
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);
}
}
/// <summary>
/// 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.
/// </summary>
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");
}
/// <summary>Hands a saved change to the running engine (no-op when stopped: the next start reads the files).</summary>
public Task<CommandResult> ApplySettingsAsync(IEnumerable<string> 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"));
}
/// <summary>Forwards a command to the running engine.</summary>
public async Task<CommandResult> 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();
}
/// <summary>Hands a saved change to the running engine; <c>Delivered</c> false when no engine runs (the next start reads the files).</summary>
public async Task<(bool Delivered, CommandResult Result)> ApplySettingsAsync(IEnumerable<string> 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);
}
/// <summary>
/// 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 <see cref="CommandResult.Timeout"/> (it stays in the
/// engine's queue).
/// </summary>
public async Task<CommandResult> 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);
}
}
}
}
/// <summary>Closes one basket on demand from the interface or the console.</summary>
public Task<CommandResult> CloseAsync(string basket, CancellationToken ct) =>
ExecuteAsync(new EngineCommand(EngineCommandKind.Close, basket, "chiusura manuale"), ct);
/// <summary>What the engine has in hand that a stop or a restart would cut in half, described for the operator; null when nothing.</summary>
public string? CommandInProgress
{
get
{
lock (_gate)
{
return CriticalInProgress();
}
}
}
/// <summary>The first critical command in hand, described; <see cref="_gate"/> held.</summary>
private string? CriticalInProgress() => _critical.Count > 0 ? Describe(_critical[0]) : null;
/// <summary>The commands that send closes to the venue: a stop or a restart must not cut them in half.</summary>
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.
/// </summary>
public async Task<CommandResult> 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();
}
}
}
/// <summary>
/// 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.
/// </summary>
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");
/// <summary>The offline maintenance's start, the lifecycle lock held: no engine can start or stop meanwhile.</summary>
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();
}
}
@@ -45,6 +45,12 @@ public sealed record EngineView
/// <summary>The last heartbeat written; <see cref="DateTime.MinValue"/> before the first.</summary>
public DateTime HeartbeatUtc { get; init; }
/// <summary>
/// The heartbeat interval in force (<c>recovery.heartbeatSeconds</c>, 5-600, changed without a
/// restart): the health check allows three of them and fifteen seconds (<see cref="HealthRules.HeartbeatStaleSeconds"/>).
/// </summary>
public int HeartbeatSeconds { get; init; }
public bool RecoveryPending { get; init; }
public string RecoveryCause { get; init; } = string.Empty;
@@ -58,4 +58,37 @@ public static class HealthRules
/// <summary>The most used quota class, 0..1; null when the HTTP layer has none.</summary>
public static double? QuotaPeak(EngineView? view) =>
view is { Api.Http.Quotas.Count: > 0 } v ? v.Api.Http.Quotas.Max(static q => q.UsedFraction) : null;
/// <summary>The heartbeat interval of <c>strategy.json</c> when a picture carries none.</summary>
public const int DefaultHeartbeatSeconds = 30;
/// <summary>
/// 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 (<see cref="EngineView.HeartbeatSeconds"/>), changed in the settings without a restart.
/// </summary>
public static double HeartbeatStaleSeconds(int heartbeatSeconds) => (3.0 * (heartbeatSeconds > 0 ? heartbeatSeconds : DefaultHeartbeatSeconds)) + 15;
/// <summary>The age of the published heartbeat in seconds; null before the first one.</summary>
public static double? HeartbeatAgeSeconds(EngineView? view, DateTime nowUtc) =>
view is not null && view.HeartbeatUtc != DateTime.MinValue && view.HeartbeatUtc != default ? (nowUtc - view.HeartbeatUtc).TotalSeconds : null;
/// <summary>
/// The container's health (<c>/api/health</c>): a running engine's heartbeat younger than
/// <see cref="HeartbeatStaleSeconds"/> 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.
/// </summary>
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);
}
}
+32 -4
View File
@@ -51,25 +51,53 @@ public enum EngineCommandKind
/// ready. Refused (<see cref="CommandResult.Refused"/>) while a cycle is already running.
/// </summary>
Learn,
/// <summary>
/// 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 <c>Argument</c> =
/// <see cref="EngineCommand.CloseAll"/> (<c>run.closeOnShutdown</c>) 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).
/// </summary>
Shutdown,
}
public sealed record EngineCommand(EngineCommandKind Kind, string Argument = "", string Reason = "");
public sealed record EngineCommand(EngineCommandKind Kind, string Argument = "", string Reason = "")
{
/// <summary>The argument of <see cref="EngineCommandKind.Shutdown"/> that closes everything first (<c>run.closeOnShutdown</c>).</summary>
public const string CloseAll = "chiudi";
}
/// <summary>
/// The seam between the supervisor and the engine. The engine runs for the whole session
/// inside <see cref="RunAsync"/>, 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.
/// <para>
/// Nothing outside the engine touches its state (5.1): every action — the close at the stop
/// included (<see cref="EngineCommandKind.Shutdown"/>) — is a command executed on its decision
/// thread; the rest of the members read published pictures.
/// </para>
/// </summary>
public interface IEngine : IAsyncDisposable
{
Task RunAsync(CancellationToken ct);
/// <summary>Closes every open basket, for the shutdown path.</summary>
Task CloseAllAsync(string reason, CancellationToken ct);
/// <summary>
/// Queues a command for the decision thread and waits for its answer (at most 120 s, then
/// <see cref="TimeoutException"/>). 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.
/// </summary>
Task<CommandResult> ExecuteAsync(EngineCommand command, CancellationToken ct);
/// <summary>
/// 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.
/// </summary>
bool LoopStarted => true;
/// <summary>
/// The 5.0 picture for the console and Telegram, adapted from <see cref="View"/>:
/// building it reads nothing the decision thread writes. <paramref name="events"/> is the
@@ -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,
@@ -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,
@@ -70,6 +70,12 @@ public sealed record SecretActionResult(bool Ok, string Message, string Restart
/// are open (<see cref="AccountActivity"/>).
/// </para>
/// <para>
/// The restart itself runs under the supervisor's lifecycle lock
/// (<see cref="BotSupervisor.RestartAsync"/>), 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).
/// </para>
/// <para>
/// The secrets live in the <see cref="SecretStore"/>; keys are proved on their own
/// account before they are saved, the Telegram token with <c>getMe</c>.
/// </para>
@@ -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.
/// <c>Delivered</c> is false when no engine runs any more (a FERMA came first).
/// </summary>
private async Task<CommandResult> ApplyToEngineAsync(IEnumerable<string> paths, CancellationToken ct)
private async Task<(bool Delivered, CommandResult Result)> ApplyToEngineAsync(IEnumerable<string> 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"));
}
}
/// <summary>
/// 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: <c>Running</c> false).
/// </summary>
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<CommandResult> StartCoreAsync(bool liveConfirmed)
{
if (StartRefusal(liveConfirmed) is { } refusal)
{
return refusal;
}
return await Supervisor.StartAsync(liveConfirmed: Config.Run.Mode.IsLive() && liveConfirmed).ConfigureAwait(false);
}
/// <summary>Why the engine cannot start now — secrets locked, no keys for the account of the mode, Live without the phrase — or null.</summary>
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;
}
/// <summary>Stops without closing a basket and starts again; the new engine takes the baskets over from the state.</summary>
private async Task<CommandResult> 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;
}
/// <summary>
/// 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.
/// </summary>
private Task<RestartResult> 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)
{
+11 -1
View File
@@ -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);
@@ -144,7 +144,9 @@ public sealed class SnapshotHub : IAsyncDisposable
/// <summary>
/// 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.
/// </summary>
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);
@@ -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);
@@ -58,6 +58,9 @@ internal sealed class TickWriter(WebContext ctx, Func<int> 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);
+43 -28
View File
@@ -116,9 +116,6 @@ public static class WebHost
/// <summary>The placeholder the login page may carry: a wrong password replaces it with the message.</summary>
public const string LoginErrorPlaceholder = "<!--login-error-->";
/// <summary>A running engine whose heartbeat is older than this is unhealthy (three heartbeats and a margin).</summary>
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;
/// <summary>
@@ -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);
}
/// <summary>One command of <c>POST /api/commands/{name}</c>: FERMA to the supervisor (refused while a kill-switch runs), the rest to the engine.</summary>
private static async Task<CommandResult> RunCommandAsync(WebContext ctx, string name, Dictionary<string, string> 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
/// <c>/api/health</c> for the container's <c>HEALTHCHECK</c>, 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 <see cref="HeartbeatStale"/>.
/// running engine's heartbeat is older than three of its own intervals and fifteen seconds
/// (<see cref="HealthRules.HeartbeatFresh"/>: the interval is a setting applied hot, 5-600 s).
/// </summary>
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));
});
+17 -5
View File
@@ -31,6 +31,12 @@ public abstract class ApiHostFixture : IAsyncLifetime
/// <summary>True: <c>POST /api/commands/learn</c> reaches the supervisor (the learning tests); false: a stub that refuses.</summary>
protected virtual bool SupervisorLearns => false;
/// <summary>The engine the supervisor builds at a start (a fake for the command tests); null: a <see cref="BasketEngine"/> without keys.</summary>
protected virtual Func<BotConfig, bool, IEngine>? EngineFactory => null;
/// <summary>What <c>POST /api/commands/start</c> calls; the default refuses.</summary>
protected virtual Func<string?, Task<CommandResult>> StartCommand => static _ => Task.FromResult(new CommandResult(false, "non in questo test"));
/// <summary>The fixture's folder: <c>encelado.json</c>, <c>strategy.json</c>, <c>data/</c>, <c>knowledge/</c>.</summary>
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()));
@@ -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<CommandResult> 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);
@@ -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<CommandResult> ExecuteAsync(EngineCommand command, CancellationToken ct)
{
lock (Commands)
@@ -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;
/// <summary>
/// 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 <see cref="BasketEngine"/> does.
/// </summary>
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;
/// <summary>Set when the run began (the instance lock is held from then on).</summary>
public TaskCompletionSource Started { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
/// <summary>Set when the run ended because its token was cancelled.</summary>
public TaskCompletionSource Cancelled { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
/// <summary>Set when the dispose began.</summary>
public TaskCompletionSource Disposing { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
/// <summary>When set, the dispose waits for it (a real one saves the state and the models before it lets go of the lock).</summary>
public TaskCompletionSource? DisposeGate { get; init; }
/// <summary>When set, the run ends by itself (without being cancelled) as soon as it completes.</summary>
public TaskCompletionSource? EndOfRun { get; init; }
public bool Disposed { get; private set; }
/// <summary>Answers a command; null answers at once.</summary>
public Func<EngineCommand, CancellationToken, Task<CommandResult>>? Answer { get; set; }
/// <summary>The commands received, each with whether the loop had already been cancelled then.</summary>
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;
}
}
/// <summary>The engine's own flag (<see cref="IEngine.LoopStarted"/>): false while it would still be warming up.</summary>
public bool LoopStarted { get; set; } = true;
public Task<CommandResult> 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;
}
}
/// <summary>
/// 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.
/// </summary>
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<GatedEngine> 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<CommandResult> start = Task.Run(() => supervisor.StartAsync());
await building.Task.WaitAsync(Wait);
Assert.Equal(BotState.Starting, supervisor.State);
Task<CommandResult> 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<GatedEngine> 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<CommandResult> 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<CommandResult> 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<CommandResult> 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<InvalidOperationException>(() => 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<CommandResult> 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<CommandResult> 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<GatedEngine> 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));
}
}
/// <summary>A command the engine does not answer in time gets an explicit answer, never an HTTP 500 (5.1 review).</summary>
public sealed class CommandTimeoutApiTests : ApiHostFixture
{
protected override bool Sample => false;
protected override string HostPassword => string.Empty;
protected override Func<BotConfig, bool, IEngine>? EngineFactory =>
static (_, _) => new GatedEngine(1) { Answer = static (_, _) => Task.FromException<CommandResult>(new TimeoutException()) };
protected override Func<string?, Task<CommandResult>> StartCommand => static _ => Task.FromException<CommandResult>(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);
}
}
@@ -26,6 +26,12 @@ public sealed class SettingsRuntimeTests : IAsyncLifetime
private int _notifierReconfigured;
private int _historyInvalidated;
/// <summary>Runs inside a save, after the files are written and before the engine is touched (where a FERMA from another tab can land).</summary>
private Action? _duringRefresh;
/// <summary>Runs while eToro "verifies" a pair of keys (up to 25 s in real life).</summary>
private Func<Task>? _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<EngineCommand> Commands { get; } = [];
public bool ClosedAll { get; private set; }
public int OpenBaskets { get; set; }
public Func<EngineCommand, CommandResult>? Answer { get; set; }
public Task RunAsync(CancellationToken ct) => Task.Delay(Timeout.Infinite, ct);
/// <summary>A command that takes its time (a kill-switch closing baskets): the task the test completes, or null to answer at once.</summary>
public Func<EngineCommand, Task<CommandResult>?>? 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<CommandResult> 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<string, string> { ["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<CommandResult> killing = new(TaskCreationOptions.RunContinuationsAsynchronously);
_engines[0].Hold = c => c.Kind == EngineCommandKind.KillSwitch ? killing.Task : null;
Task<CommandResult> kill = Supervisor.ExecuteAsync(new EngineCommand(EngineCommandKind.KillSwitch, string.Empty, "prova"), CancellationToken.None);
string strategy = File.ReadAllText(StrategyPath);
SettingsResult save = await Runtime.ApplyAsync(new Dictionary<string, string> { ["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<string, string> { ["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()
{
@@ -30,6 +30,27 @@ public sealed class SnapshotHubTests
Assert.Null(hub.Latest);
}
/// <summary>A first frame that fails (a model file the process cannot read) leaves no client behind: nothing is built for nobody afterwards.</summary>
[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<UnauthorizedAccessException>(() => 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()
{