diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index a05974e..c69b63b 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -188,7 +188,7 @@ Il bot che lavora da solo, in simulazione, giorno e notte, e lo racconta. - [x] [#48](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/48) Processo di guardia, avvio e ripartenza sicuri - [x] [#49](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/49) Recupero dopo un'assenza (5.6) - [x] [#50](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/50) Diario con frasi in italiano dai codici motivo e confronto "senza bot" -- [ ] [#51](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/51) Schermate Panoramica e Diario e sistema +- [x] [#51](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/51) Schermate Panoramica e Diario e sistema - [x] [#52](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/52) Telegram e segnale di vita - [ ] [#53](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/53) Prova di durata di 48 ore in tempo reale - [ ] [#54](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/54) Chiusura della fase, revisione indipendente e tag `fase-6` @@ -200,8 +200,8 @@ Il bot che lavora da solo, in simulazione, giorno e notte, e lo racconta. - [x] Un test blocca il ciclo principale con una vendita a metà e verifica che dopo la guardia la posizione abbia di nuovo i suoi stop e il motore sia ripartito; la stessa prova passa dentro l'immagine Docker (`ALoopBlockedWithASaleHalfwayGetsItsStopBackAndTheEngineRestarts`, `TheGuardDrillPassesWithTheRealEngineAsChildProcess`; `docker run --rm drill` in `tasks ci` e nella CI: 7 controlli su 7) - [x] Un test con orologio simulato spegne il bot per 3 ore, 20 ore e 3 giorni e verifica le righe di 5.6 i cui lavori esistono (`ThreeHoursOffRecoverTheCryptoDecisionAndDropAnEntryThatMovedTooFar`, `TwentyHoursOffLetTheLateDecisionsUpdateOnlyExitsAndDropExpiredEntries`, `ThreeDaysOffAreDeclaredUntilSeenAndMissedRunsAreMadeOnce`) - [ ] A fine fase parte una prova di durata in tempo reale di almeno 48 ore a cavallo di due sedute USA (solo crypto senza chiavi Alpaca) -- [ ] In modalità dimostrativa la Panoramica corrisponde agli screen 01 (1440 px) e 09 (390 px) -- [ ] Il Diario corrisponde allo screen 08 a 1440 px e a 390 px non scorre in orizzontale +- [x] In modalità dimostrativa la Panoramica corrisponde agli screen 01 (1440 px) e 09 (390 px) (`TheDemoPanoramicaShowsAccountsPositionsAndLimits`; fotografie di `tasks screenshots`, confronto nella prova di #51) +- [x] Il Diario corrisponde allo screen 08 a 1440 px e a 390 px non scorre in orizzontale (`TheDiaryFiltersAndSearches`; a 390 px `scrollWidth` uguale alla larghezza su `/`, `/diario` e `/diario?cerca=…`) - [x] I comandi Telegram funzionano (o, senza token, superano i test con un finto server) — senza token, con un finto server: `TheCommandsWorkFromThePhoneThroughTheRealServer`, `FermaWantsAConfirmationWithinTwoMinutes`, `OnlyTheChatOfTheSettingsIsObeyedAndOldMessagesAreNot` e gli altri di `TelegramTests` ## Fase 7 — Notizie diff --git a/docs/adr/0012-scelte-fase-6.md b/docs/adr/0012-scelte-fase-6.md index e61b176..73e2859 100644 --- a/docs/adr/0012-scelte-fase-6.md +++ b/docs/adr/0012-scelte-fase-6.md @@ -123,6 +123,18 @@ La Fase 6 porta il bot che lavora da solo in simulazione: la giornata di 5.5, il - La prova gira sull'immagine Docker di questo PC, con un volume suo, senza chiavi: conto crypto sul simulatore interno con prezzi veri di OKX, nessuna parte azionaria. - `crypto_trend` non ha superato il backtest (ADR 0011, punto 13), quindi resta in osservazione: decide ogni notte, ma non manda ordini. Non la porto in simulazione per far vedere ordini: sarebbe aggirare il suo esito. Gli ordini, le ripartenze e i guasti sono coperti dalla prova accelerata (punto 2) e dalla prova della guardia (punto 5). +**12. Correzioni dopo la revisione indipendente.** Una revisione del codice della fase ha trovato nove difetti; le correzioni scelte sono queste. +- **Un conto parte solo quando è in ordine.** All'avvio ogni conto prima adotta gli stop messi dalla guardia, poi controlla la chiave, si riconcilia, riprende o annulla ciò che era rimasto a metà e allinea gli stop. Solo se tutto riesce il conto è "pronto". Finché non lo è, il motore non decide su di lui e non gli manda ordini pianificati; il ciclo riprova l'avvio ogni minuto. Prima, un broker che non rispondeva all'avvio lasciava il conto lavorare su un registro non riconciliato. +- **Gli stop della guardia si adottano prima di tutto il resto.** La nota della guardia si cancella solo quando ogni stop che ha messo risulta nel registro degli ordini; se l'adozione si interrompe, la nota resta e si riprova. +- **Un turno di conto ha un tempo massimo**: 45 secondi per il giro degli ordini, 60 per un nuovo avvio. Un broker lento non tiene più fermo il segnale di vita per i due minuti dopo i quali la guardia interviene: il turno si interrompe, si scrive nel registro e si riprova al giro dopo. Un motore davvero bloccato resta in silenzio e la guardia lo sente. +- **Il segnale di vita guarda anche il pianificatore.** Se il pianificatore, dove girano le decisioni, tace da 30 minuti (i suoi lavori più lunghi durano pochi minuti), il ciclo degli ordini smette di battere e la guardia interviene. +- **Le uscite alla chiusura di `equity_meanrev` sono ordini pianificati**, scritti nella stessa transazione che prende la chiave della decisione, con scadenza alla chiusura della sessione. Il rilascio li manda subito; una vendita con scadenza parte già aggressiva (limite vicino al prezzo opposto). Prima venivano mandate direttamente: un riavvio a metà poteva perderle o mandarle due volte. +- **La ripresa trova anche l'ordine pianificato non ancora collegato** alla sua esecuzione (riavvio tra l'invio e la scrittura del collegamento), dalla chiave dell'ordine, e lo chiude prima di ripianificare il resto. +- **Una decisione azionaria fatta dopo l'apertura** (per esempio dopo un'assenza) è segnata in ritardo e segue le regole del recupero. +- **I cicli di Telegram non si fermano per un errore inatteso** (database occupato, rete): scrivono nel registro e riprovano. +- **Lo spegnimento lungo si vede in Panoramica** (SPEC 5.6): un avviso in cima dice per quanto il bot è rimasto spento e rimanda al diario, finché l'utente non preme "Ho visto". +- Il segnale di vita in `http://` è accettato solo verso indirizzi della rete di casa (10.x, 172.16-31.x, 192.168.x, locali e i loro equivalenti IPv6); il rapporto della prova di durata non conta una chiusura giornaliera avvenuta meno di 30 minuti prima della fine della finestra. + ## Conseguenze - Un riavvio, un crash o un'assenza non producono decisioni né ordini doppi: le chiavi e le transazioni lo garantiscono, e i test lo provano su entrambi i motori. diff --git a/src/Anubis.Server/AnubisHost.cs b/src/Anubis.Server/AnubisHost.cs index 703aaaa..9a9df48 100644 --- a/src/Anubis.Server/AnubisHost.cs +++ b/src/Anubis.Server/AnubisHost.cs @@ -56,6 +56,9 @@ internal sealed partial class AnubisHost( ILogger logger, ServerOverrides? overrides = null) : BackgroundService { + /// A scheduler silent this long is stuck: the engine stops beating, so the guard steps in. + public static readonly TimeSpan SchedulerSilence = TimeSpan.FromMinutes(30); + private readonly TimeSpan _interval = overrides?.DatabaseCheckInterval ?? TimeSpan.FromSeconds(5); private readonly Lock _gate = new(); @@ -318,6 +321,10 @@ internal sealed partial class AnubisHost( // The drill's fault is honored only under a guard, which never passes it to an engine it restarts. Fault = Guard is null ? null : environment.GetValueOrDefault(GuardChannel.FaultVariable), + + // The decisions run in the scheduler: a scheduler silent for half an hour is stuck (its longest jobs take + // minutes), and the guard must hear it (SPEC 9.3). + OthersAlive = () => scheduler.LastBeatUtc is not { } beat || clock.UtcNow - beat < SchedulerSilence, } : null; if (_trading is not null) diff --git a/src/Anubis.Server/Components/Pages/Panoramica.razor b/src/Anubis.Server/Components/Pages/Panoramica.razor index 643c148..120500f 100644 --- a/src/Anubis.Server/Components/Pages/Panoramica.razor +++ b/src/Anubis.Server/Components/Pages/Panoramica.razor @@ -17,6 +17,14 @@ var phoneMoves = moves.Select((m, i) => (m, i)).Where(x => !x.m.Calendar).Take(2).Select(x => x.i).ToHashSet(); var v = p.Accounts; } +@if (_absence is { } away) +{ +
+ + Sono stato spento per @Anubis.Trading.DiaryText.Duration(away.Length), fino a @Format.ShortDate(away.EndedAt, Shell.Now, Shell.Zone, withTime: false).ToLowerInvariant() alle @TimeZoneInfo.ConvertTime(away.EndedAt, Shell.Zone).ToString("HH:mm", System.Globalization.CultureInfo.InvariantCulture). Ho ripreso i lavori saltati con le regole del recupero: cosa ho fatto e cosa ho lasciato perdere è nel diario. +
+
+} @if (!o.CapitalSet && !Shell.IsDemo) {

Primo passo: decidi quanto capitale affidare al bot in Impostazioni, Conti e chiavi. Lì puoi anche inserire le chiavi dei conti di prova. Finché non c'è capitale, le strategie osservano soltanto.

@@ -388,6 +396,7 @@ private string _period = "avvio"; private int? _runningDays; private decimal? _worst; + private Anubis.Trading.Absence? _absence; [CascadingParameter] public HttpContext? HttpContext { get; set; } @@ -406,6 +415,9 @@ _worst = _panorama.Limits[1].Worst is { } share ? -share * (await Anubis.Risk.RiskSettings.LoadAsync(services.Settings, ct)).DrawdownStop : null; using var aggregates = Shell.Aggregates(); _runningDays = aggregates?.RootElement.GetProperty("giorno").GetInt32(); + + // SPEC 5.6: an absence longer than a day stays at the top until the user says they have seen it. + _absence = Shell.IsDemo ? null : await new Anubis.Trading.AbsenceBook(services.Db, Host.Clock).DeclaredAsync(ct); } private static string Statement(Overview o) diff --git a/src/Anubis.Server/Forms.cs b/src/Anubis.Server/Forms.cs index 1da97e2..107a395 100644 --- a/src/Anubis.Server/Forms.cs +++ b/src/Anubis.Server/Forms.cs @@ -39,12 +39,24 @@ internal static partial class Forms signed.MapPost("/telegram/togli", RemoveTelegramAsync); signed.MapPost("/segnale-di-vita", SaveHeartbeatAsync); signed.MapPost("/segnale-di-vita/togli", RemoveHeartbeatAsync); + signed.MapPost("/assenza/{id:guid}/vista", AbsenceSeenAsync); signed.MapPost("/laboratorio", PlanTrialAsync); signed.MapPost("/strategie/{strategy}/{choice}", StrategyStageAsync); signed.MapPost("/rischio/limiti", SetLimitsAsync); signed.MapPost("/rischio/{key}", SetRiskSettingAsync); } + /// The notice of a long absence (SPEC 5.6) goes away once the user has seen it. + private static async Task AbsenceSeenAsync(Guid id, AnubisHost host, CancellationToken ct) + { + if (!host.IsDemo && host.Services is { } services) + { + await new Anubis.Trading.AbsenceBook(services.Db, host.Clock).AcknowledgeAsync(id, ct).ConfigureAwait(false); + } + + return Results.Redirect("/"); + } + private static string Back(IFormCollection form, string fallback) { var back = form["ritorno"].ToString(); diff --git a/src/Anubis.Server/TelegramServices.cs b/src/Anubis.Server/TelegramServices.cs index 51b11f1..aa8005e 100644 --- a/src/Anubis.Server/TelegramServices.cs +++ b/src/Anubis.Server/TelegramServices.cs @@ -8,7 +8,7 @@ namespace Anubis.Server; /// Telegram and the sign of life (SPEC 14): the queue sent every few seconds, the commands read as they arrive, the /// call to the checking service every minute, the morning summary and the optional periodic status. /// -internal sealed class TelegramServices : IDisposable +internal sealed partial class TelegramServices : IDisposable { /// The secret that keeps the address of the checking service when the configuration does not give one. public const string HeartbeatSecret = "HEARTBEAT_URL"; @@ -22,6 +22,7 @@ internal sealed class TelegramServices : IDisposable private readonly SettingsStore _settings; private readonly SecretStore _secrets; private readonly TimeZoneInfo _zone; + private readonly Microsoft.Extensions.Logging.ILogger _logger; public TelegramServices(AnubisHost host, Database db, IClock clock, SettingsStore settings, SecretStore secrets, string? configuredHeartbeat, HttpMessageHandler? handler, Microsoft.Extensions.Logging.ILogger logger) @@ -32,6 +33,7 @@ internal sealed class TelegramServices : IDisposable _settings = settings; _secrets = secrets; _zone = host.Config.TimeZone; + _logger = logger; _http = handler is null ? new HttpClient() : new HttpClient(handler, disposeHandler: false); // Longer than the wait of the commands' long polling. @@ -95,7 +97,16 @@ internal sealed class TelegramServices : IDisposable { while (!cancellationToken.IsCancellationRequested) { - await Sender.SendDueAsync(cancellationToken).ConfigureAwait(false); + try + { + await Sender.SendDueAsync(cancellationToken).ConfigureAwait(false); + } + catch (Exception ex) when (!cancellationToken.IsCancellationRequested) + { + // A busy or unreachable database, or anything else: the queue keeps its messages for the next pass. + LogSendFailed(_logger, ex); + } + await Task.Delay(SendEvery, cancellationToken).ConfigureAwait(false); } } @@ -156,4 +167,7 @@ internal sealed class TelegramServices : IDisposable var text = await Desk.StatusAsync(cancellationToken).ConfigureAwait(false); await _db.WriteAsync(s => NotificationSender.EnqueueAsync(s, _clock, "periodic_status", text, cancellationToken), cancellationToken).ConfigureAwait(false); } + + [Microsoft.Extensions.Logging.LoggerMessage(Level = Microsoft.Extensions.Logging.LogLevel.Error, Message = "Sending the Telegram queue failed")] + private static partial void LogSendFailed(Microsoft.Extensions.Logging.ILogger logger, Exception exception); } diff --git a/src/Anubis/Notifications/TelegramBot.cs b/src/Anubis/Notifications/TelegramBot.cs index 8533aef..d272857 100644 --- a/src/Anubis/Notifications/TelegramBot.cs +++ b/src/Anubis/Notifications/TelegramBot.cs @@ -174,6 +174,12 @@ public sealed partial class TelegramBot(IClock clock, Func Retry ? after : Retry; } + catch (Exception ex) when (!cancellationToken.IsCancellationRequested) + { + // The database or the network failed in a way Telegram did not report: the loop goes on after a pause. + LogLoopFailed(logger, ex); + pause = Retry; + } if (pause is { } wait) { @@ -188,6 +194,9 @@ public sealed partial class TelegramBot(IClock clock, FuncAn address of a home network: 10.x, 172.16-31.x, 192.168.x, link-local, or their IPv6 equivalents. + private static bool IsPrivate(string host) + { + if (!System.Net.IPAddress.TryParse(host.Trim('[', ']'), out var ip)) + { + return false; + } + + if (ip.IsIPv4MappedToIPv6) + { + ip = ip.MapToIPv4(); + } + + if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6) + { + return System.Net.IPAddress.IsLoopback(ip) || ip.IsIPv6LinkLocal || ip.IsIPv6SiteLocal || ip.IsIPv6UniqueLocal; + } + + var b = ip.GetAddressBytes(); + return b[0] == 10 || b[0] == 127 || (b[0] == 172 && b[1] is >= 16 and <= 31) || (b[0] == 192 && b[1] == 168) || (b[0] == 169 && b[1] == 254); + } + [LoggerMessage(Level = LogLevel.Warning, Message = "Heartbeat failed: {Error}")] private static partial void LogFailed(ILogger logger, string error); } diff --git a/src/Anubis/Supervision/SoakReport.cs b/src/Anubis/Supervision/SoakReport.cs index d0c0957..aedbc97 100644 --- a/src/Anubis/Supervision/SoakReport.cs +++ b/src/Anubis/Supervision/SoakReport.cs @@ -162,9 +162,16 @@ public static class SoakReporter }, cancellationToken).ConfigureAwait(false); } - /// How many crypto daily decisions (00:05 UTC) fall in the window. + /// The time a daily decision is given to run and be written before the report expects it. + public static readonly TimeSpan DecisionTime = TimeSpan.FromMinutes(30); + + /// + /// How many crypto daily decisions (00:05 UTC) fall in the window. A close too near the end of the window is not + /// counted: its decision may still be running when the report is made. + /// public static int DailyCloses(DateTimeOffset from, DateTimeOffset to) { + to -= DecisionTime; var count = 0; for (var day = DateOnly.FromDateTime(from.UtcDateTime); ; day = day.AddDays(1)) { diff --git a/src/Anubis/Trading/LiveEngine.cs b/src/Anubis/Trading/LiveEngine.cs index 9f58aaf..841944e 100644 --- a/src/Anubis/Trading/LiveEngine.cs +++ b/src/Anubis/Trading/LiveEngine.cs @@ -138,6 +138,12 @@ public sealed partial class LiveEngine : IDisposable /// public Func Ready { get; init; } = () => true; + /// + /// Whether an account finished its startup (SPEC 9.4): reconciled, its leftovers canceled or resumed, its stops + /// aligned. Until then nothing is decided on it and no planned order is sent to it. + /// + public Func AccountReady { get; init; } = _ => true; + /// /// The jobs of SPEC 5.5. The pulse every minute does the work; the others are the same pulse at the times the /// user reads in "Prossime mosse", so the work starts on time. @@ -245,11 +251,14 @@ public sealed partial class LiveEngine : IDisposable return; } + // SPEC 5.6: the signals are redone after an absence only before the next open; made after it, only the exits + // and the stops of the decision are kept. + var late = now >= next.OpenUtc; foreach (var strategy in new[] { StrategyNames.EquityMomentum, StrategyNames.EquityMeanrev }) { var ordersDue = next.OpenUtc + Options.OrdersAfterOpen; var entriesUntil = strategy == StrategyNames.EquityMeanrev ? next.OpenUtc + Options.MeanrevEntryWindow : SecondSessionOfWeek(next).CloseUtc; - await DecideAsync(new Moment(strategy, last.Date, Key(strategy, last.Date), last.CloseUtc + Options.SignalsAfterClose, false, next.OpenUtc, now, ordersDue, + await DecideAsync(new Moment(strategy, last.Date, Key(strategy, last.Date), last.CloseUtc + Options.SignalsAfterClose, late, next.OpenUtc, now, ordersDue, entriesUntil), cancellationToken).ConfigureAwait(false); } } @@ -323,7 +332,7 @@ public sealed partial class LiveEngine : IDisposable { var accounts = await _db.ReadAsync(s => s.QueryAsync("SELECT id FROM accounts WHERE broker = @b", r => r.Id("id"), ("b", Venues.Alpaca)), cancellationToken) .ConfigureAwait(false); - return [.. accounts.Select(_managers).OfType()]; + return [.. accounts.Where(AccountReady).Select(_managers).OfType()]; } /// @@ -340,12 +349,17 @@ public sealed partial class LiveEngine : IDisposable } var stage = await _stages.GetAsync(StrategyNames.EquityMeanrev, cancellationToken).ConfigureAwait(false); - if (stage?.OrdersAccount is not { } accountId || _managers(accountId) is not { } manager) + if (stage?.OrdersAccount is not { } accountId || _managers(accountId) is null) { await ClaimOnlyAsync(StrategyNames.EquityMeanrev, key, session.Date, cancellationToken).ConfigureAwait(false); return; } + if (!AccountReady(accountId)) + { + return; + } + var book = await BookAsync(accountId, StrategyNames.EquityMeanrev, cancellationToken).ConfigureAwait(false); if (book.Holdings.Count == 0) { @@ -364,16 +378,10 @@ public sealed partial class LiveEngine : IDisposable var record = BacktestEngine.DecideOnce(strategy, data.Data, book.State, session.Date, options); var decisionId = Ids.NewId(_clock); var exits = record.Final.Where(i => i.AtClose && i.TargetWeight == 0m && book.Holdings.ContainsKey(i.Symbol)).ToList(); - var submitted = new List<(Intent Intent, Guid? Execution, string? Refusal)>(); - foreach (var exit in exits) - { - var held = book.Holdings[exit.Symbol]; - var (execution, refusal) = await manager.SubmitAsync(new TradeIntent(held.InstrumentId, StrategyNames.EquityMeanrev, OrderSide.Sell, held.Holding.Quantity, OrderPurpose.Exit, - decisionId) - { StartAggressive = true }, cancellationToken).ConfigureAwait(false); - submitted.Add((exit, execution, refusal)); - } + // The exits are planned in the same transaction as the run key, like every other decision, and leave at once + // from the release below: a restart finds them planned and proposes them again (SPEC 9.4), and a failed + // attempt never sends the same exit twice with two keys. The deadline at the close makes them start aggressive. await _db.WriteAsync(async s => { if (!await ClaimAsync(s, StrategyNames.EquityMeanrev, key, session.Date, decisionId, DecisionModes.Full, null, null, cancellationToken).ConfigureAwait(false)) @@ -381,13 +389,23 @@ public sealed partial class LiveEngine : IDisposable return; } - foreach (var (intent, execution, refusal) in submitted) + foreach (var exit in exits) { - await DecisionLog.WriteAsync(s, _clock, new DecisionRow(decisionId, StrategyNames.EquityMeanrev, accountId, intent.Symbol, DecisionStages.Strategy, DecisionOutcomes.Proposed, - [intent.Reason], new Dictionary { ["weight"] = 0m, ["at_close"] = true }, now), cancellationToken).ConfigureAwait(false); - await DecisionLog.WriteAsync(s, _clock, new DecisionRow(decisionId, StrategyNames.EquityMeanrev, accountId, intent.Symbol, DecisionStages.Order, - refusal is null ? DecisionOutcomes.Passed : DecisionOutcomes.Refused, refusal is null ? [] : [refusal], - new Dictionary { ["execution"] = execution }, now), cancellationToken).ConfigureAwait(false); + var held = book.Holdings[exit.Symbol]; + var instrument = data.Data.Instruments.FirstOrDefault(i => i.Symbol == exit.Symbol); + var reference = instrument is null ? 0m : Close(instrument, session.Date) ?? 0m; + var id = Ids.NewId(_clock); + await DecisionLog.WriteAsync(s, _clock, new DecisionRow(decisionId, StrategyNames.EquityMeanrev, accountId, exit.Symbol, DecisionStages.Strategy, DecisionOutcomes.Proposed, + [exit.Reason], new Dictionary { ["weight"] = 0m, ["at_close"] = true }, now), cancellationToken).ConfigureAwait(false); + await s.ExecuteAsync( + "INSERT INTO planned_orders (id, decision_id, strategy, account_id, instrument_id, side, purpose, quantity, exit_all, stop_level, stop_offset, reference_price, reason, due_at, valid_until, status, created_at, updated_at) " + + "VALUES (@id, @d, @s, @a, @i, @side, @p, @q, @all, NULL, NULL, @ref, @r, @due, @until, @st, @now, @now)", cancellationToken, + ("id", id), ("d", decisionId), ("s", StrategyNames.EquityMeanrev), ("a", accountId), ("i", held.InstrumentId), ("side", Wire.Text(OrderSide.Sell)), + ("p", Wire.Text(OrderPurpose.Exit)), ("q", DbValues.Money(held.Holding.Quantity)), ("all", true), ("ref", reference), ("r", exit.Reason), ("due", now), + ("until", session.CloseUtc), ("st", PlannedStates.Pending), ("now", now)).ConfigureAwait(false); + await DecisionLog.WriteAsync(s, _clock, new DecisionRow(decisionId, StrategyNames.EquityMeanrev, accountId, exit.Symbol, DecisionStages.Sizing, DecisionOutcomes.Passed, [], + new Dictionary { ["side"] = Wire.Text(OrderSide.Sell), ["quantity"] = held.Holding.Quantity, ["close"] = reference, ["planned"] = id }, now), + cancellationToken).ConfigureAwait(false); } }, cancellationToken).ConfigureAwait(false); } @@ -422,6 +440,12 @@ public sealed partial class LiveEngine : IDisposable return; } + if (!observation && !AccountReady(account)) + { + // Its ledger is not reconciled yet: the decision waits for the next pulse, late if it must (SPEC 5.6). + return; + } + var book = observation ? Book.Empty : await BookAsync(account, m.Strategy, cancellationToken).ConfigureAwait(false); var loaded = await LoadAsync(m.Strategy, m.Day, book, provisional: false, cancellationToken).ConfigureAwait(false); if (loaded.Data is null || loaded.Missing.Count > 0) @@ -858,7 +882,7 @@ public sealed partial class LiveEngine : IDisposable return; } - if (_managers(order.AccountId) is not { } manager) + if (!AccountReady(order.AccountId) || _managers(order.AccountId) is not { } manager) { return; } @@ -908,8 +932,13 @@ public sealed partial class LiveEngine : IDisposable } } - var (execution, refusal) = await manager.SubmitAsync(new TradeIntent(order.InstrumentId, order.Strategy, order.Side, quantity, order.Purpose, order.Id) { StopLevel = stopLevel }, - cancellationToken).ConfigureAwait(false); + // A sale never expires; one with a deadline (the exits at the close) starts aggressive: there are minutes left. + var aggressive = order.Side == OrderSide.Sell && order.ValidUntil is not null; + var (execution, refusal) = await manager.SubmitAsync(new TradeIntent(order.InstrumentId, order.Strategy, order.Side, quantity, order.Purpose, order.Id) + { + StopLevel = stopLevel, + StartAggressive = aggressive, + }, cancellationToken).ConfigureAwait(false); var recovered = late ? DiaryText.Recovered(OrderWords(order, instrument.Symbol), order.Due, Zone) : null; await CloseAsync(order, refusal is null ? PlannedStates.Submitted : PlannedStates.Refused, refusal, execution, recovered, cancellationToken).ConfigureAwait(false); } @@ -927,23 +956,25 @@ public sealed partial class LiveEngine : IDisposable var again = 0; foreach (var execution in canceled) { - var row = await _db.ReadAsync(s => s.FirstOrDefaultAsync( - "SELECT p.id, p.decision_id, p.strategy, p.account_id, p.instrument_id, p.side, p.purpose, p.quantity, p.exit_all, p.stop_level, p.stop_offset, " + - "p.reference_price, p.reason, p.due_at, p.valid_until, e.filled FROM planned_orders p JOIN executions e ON e.id = p.execution_id WHERE p.execution_id = @e", - r => new Interrupted(new Planned(r.Id("id"), r.Id("decision_id"), r.Text("strategy"), r.Id("account_id"), r.Id("instrument_id"), Wire.Side(r.Text("side")), - Wire.Purpose(r.Text("purpose")), r.Money("quantity"), r.Bool("exit_all"), r.MoneyOrNull("stop_level"), r.MoneyOrNull("stop_offset"), r.Money("reference_price"), - r.Text("reason"), r.Moment("due_at"), r.MomentOrNull("valid_until")), r.Money("filled")), ("e", execution)), cancellationToken).ConfigureAwait(false); + var row = await InterruptedAsync(execution, cancellationToken).ConfigureAwait(false); if (row is not { } found || (found.Order.Quantity - found.Filled <= 0m && !found.Order.ExitAll)) { continue; } - var (order, filled) = found; + var (order, filled, unlinked) = found; var symbol = (await _catalog.GetAsync(order.InstrumentId, cancellationToken).ConfigureAwait(false))?.Symbol ?? "?"; var now = _clock.UtcNow; var sale = order.Side == OrderSide.Sell; await _db.WriteAsync(async s => { + if (unlinked) + { + // The process stopped between sending it and marking it sent: it is marked now, so it never goes again. + await s.ExecuteAsync("UPDATE planned_orders SET status = @st, execution_id = @e, updated_at = @now WHERE id = @id AND status = @p", cancellationToken, + ("st", PlannedStates.Submitted), ("e", execution), ("now", now), ("id", order.Id), ("p", PlannedStates.Pending)).ConfigureAwait(false); + } + await s.ExecuteAsync( "INSERT INTO planned_orders (id, decision_id, strategy, account_id, instrument_id, side, purpose, quantity, exit_all, stop_level, stop_offset, reference_price, " + "reason, due_at, valid_until, status, outcome, execution_id, created_at, updated_at) VALUES (@id, @d, @s, @a, @i, @side, @p, @q, @x, @sl, @so, @r, @reason, " + @@ -961,7 +992,42 @@ public sealed partial class LiveEngine : IDisposable return again; } - private sealed record Interrupted(Planned Order, decimal Filled); + private sealed record Interrupted(Planned Order, decimal Filled, bool Unlinked); + + private const string PlannedColumns = + "p.id, p.decision_id, p.strategy, p.account_id, p.instrument_id, p.side, p.purpose, p.quantity, p.exit_all, p.stop_level, p.stop_offset, p.reference_price, p.reason, p.due_at, p.valid_until"; + + private static Planned ReadPlanned(DbRow r) => + new(r.Id("id"), r.Id("decision_id"), r.Text("strategy"), r.Id("account_id"), r.Id("instrument_id"), Wire.Side(r.Text("side")), Wire.Purpose(r.Text("purpose")), + r.Money("quantity"), r.Bool("exit_all"), r.MoneyOrNull("stop_level"), r.MoneyOrNull("stop_offset"), r.Money("reference_price"), r.Text("reason"), r.Moment("due_at"), + r.MomentOrNull("valid_until")); + + /// + /// The planned order behind a canceled execution: the one that points to it, or, when the process stopped between + /// sending it and marking it sent, the pending one whose key the execution carries. + /// + private Task InterruptedAsync(Guid execution, CancellationToken cancellationToken) => + _db.ReadAsync(async s => + { + var info = await s.FirstOrDefaultAsync("SELECT account_id, instrument_id, order_key, filled FROM executions WHERE id = @e", + r => (Account: r.Id("account_id"), Instrument: r.Id("instrument_id"), Key: r.Text("order_key"), Filled: r.Money("filled")), ("e", execution)).ConfigureAwait(false); + if (info.Key is null) + { + return null; + } + + var linked = await s.FirstOrDefaultAsync("SELECT " + PlannedColumns + " FROM planned_orders p WHERE p.execution_id = @e", ReadPlanned, ("e", execution)) + .ConfigureAwait(false); + if (linked is not null) + { + return new Interrupted(linked, info.Filled, false); + } + + var pending = await s.QueryAsync("SELECT " + PlannedColumns + " FROM planned_orders p WHERE p.account_id = @a AND p.instrument_id = @i AND p.status = @p AND p.execution_id IS NULL", + ReadPlanned, ("a", info.Account), ("i", info.Instrument), ("p", PlannedStates.Pending)).ConfigureAwait(false); + var unlinked = pending.FirstOrDefault(p => ClientOrderIds.Key(p.Id) == info.Key); + return unlinked is null ? (Interrupted?)null : new Interrupted(unlinked, info.Filled, true); + }, cancellationToken); private static string OrderWords(Planned order, string symbol) => (order.Side == OrderSide.Buy ? "l'acquisto di " : "la vendita di ") + DiaryText.Shown(symbol); diff --git a/src/Anubis/Trading/TradingService.cs b/src/Anubis/Trading/TradingService.cs index bd44a26..f17a3ee 100644 --- a/src/Anubis/Trading/TradingService.cs +++ b/src/Anubis/Trading/TradingService.cs @@ -188,6 +188,7 @@ public sealed partial class TradingService : IDisposable { WantData = market is null ? null : _ => market.WakeWorker(), Ready = () => _started, + AccountReady = AccountReady, }; } @@ -305,36 +306,12 @@ public sealed partial class TradingService : IDisposable } await GuardAsync("azioni societarie nei registri", () => CorporateActionsAsync(cancellationToken), cancellationToken).ConfigureAwait(false); - var notes = GuardFiles is null ? [] : Supervision.GuardFiles.ReadNotes(GuardFiles); foreach (var manager in _managers.Values) { - await GuardAsync("avvio " + manager.Account.Name, async () => - { - if (manager.Broker is PaperBroker paper) - { - await paper.CatchUpAsync(MinuteBarsAsync, cancellationToken).ConfigureAwait(false); - } - else - { - await Reconciler.CheckKeyAsync(manager, cancellationToken).ConfigureAwait(false); - } - - // The stops the guard put back while the engine was stopped become the engine's own, before anything compares. - foreach (var placed in notes.SelectMany(n => n.Note.Placed).Where(p => p.AccountId == manager.Account.AccountId)) - { - await manager.AdoptStopAsync(placed, cancellationToken).ConfigureAwait(false); - } - - Guard?.Step("riconciliazione " + manager.Account.Name); - await Reconciler.ReconcileAsync(manager, cancellationToken).ConfigureAwait(false); - Guard?.Step("ordini rimasti aperti " + manager.Account.Name); - await Engine.ResumeAsync(manager, cancellationToken).ConfigureAwait(false); - Guard?.Step("stop " + manager.Account.Name); - await manager.AlignStopsAsync(cancellationToken).ConfigureAwait(false); - }, cancellationToken).ConfigureAwait(false); + await StartAccountAsync(manager, cancellationToken).ConfigureAwait(false); } - await GuardAsync("note della guardia", () => TakeGuardNotesAsync(notes, cancellationToken), cancellationToken).ConfigureAwait(false); + _accountsRetryAt = _clock.UtcNow + AccountRetry; await GuardAsync("patrimonio", () => PhotographAsync(cancellationToken), cancellationToken).ConfigureAwait(false); await GuardAsync("stato per la guardia", () => WriteGuardStateAsync(cancellationToken), cancellationToken).ConfigureAwait(false); await GuardAsync("chiavi per la guardia", () => SendGuardKeysAsync(alpaca, okx, cancellationToken), cancellationToken).ConfigureAwait(false); @@ -363,14 +340,97 @@ public sealed partial class TradingService : IDisposable _guardStateAt = _clock.UtcNow; } - // The guard's notes go in the diary once their stops are adopted; then they are gone. - private async Task TakeGuardNotesAsync(IReadOnlyList<(string Path, GuardNote Note)> notes, CancellationToken cancellationToken) + /// The accounts whose startup of SPEC 9.4 is done: only these are ticked, decided on and sent orders. + public bool AccountReady(Guid accountId) => _ready.ContainsKey(accountId); + + private readonly ConcurrentDictionary _ready = new(); + + /// An account whose startup failed (broker unreachable) is tried again this often. + public TimeSpan AccountRetry { get; init; } = TimeSpan.FromMinutes(1); + + private DateTimeOffset _accountsRetryAt; + + /// + /// The startup of one account (SPEC 9.4): the guard's stops adopted first, whatever else fails; then the key, the + /// complete reconciliation, the purchases and sales left open canceled (exits restart, entries are proposed again) + /// and every position checked for its stop. Until all of it is done the account is not ready. + /// + private async Task StartAccountAsync(OrderManager manager, CancellationToken cancellationToken) { - foreach (var (path, note) in notes) + var name = manager.Account.Name; + await GuardAsync("stop della guardia " + name, () => AdoptGuardStopsAsync(manager, cancellationToken), cancellationToken).ConfigureAwait(false); + var started = await TryAsync("avvio " + name, async () => { - await _db.WriteAsync(s => Diary.WriteAsync(s, _clock, DiaryKinds.System, "guard_intervention", string.Join(" ", note.Lines), - new { at = note.At, reason = note.Reason, stops = note.Placed.Count, stopFile = note.StopFileCreated }, cancellationToken), cancellationToken).ConfigureAwait(false); - File.Delete(path); + if (manager.Broker is PaperBroker paper) + { + await paper.CatchUpAsync(MinuteBarsAsync, cancellationToken).ConfigureAwait(false); + } + else + { + await Reconciler.CheckKeyAsync(manager, cancellationToken).ConfigureAwait(false); + } + + Guard?.Step("riconciliazione " + name); + await Reconciler.ReconcileAsync(manager, cancellationToken).ConfigureAwait(false); + Guard?.Step("ordini rimasti aperti " + name); + await Engine.ResumeAsync(manager, cancellationToken).ConfigureAwait(false); + Guard?.Step("stop " + name); + await manager.AlignStopsAsync(cancellationToken).ConfigureAwait(false); + }, cancellationToken).ConfigureAwait(false); + if (started) + { + _ready[manager.Account.AccountId] = true; + } + } + + /// + /// The stops the guard put back while the engine was stopped become the engine's own, before anything compares + /// them. A note goes in the diary and is deleted only when every stop it placed is adopted, for every account: a + /// stop left unknown would be put back a second time. + /// + private async Task AdoptGuardStopsAsync(OrderManager manager, CancellationToken cancellationToken) + { + if (GuardFiles is null) + { + return; + } + + foreach (var (path, note) in Supervision.GuardFiles.ReadNotes(GuardFiles)) + { + foreach (var placed in note.Placed.Where(p => p.AccountId == manager.Account.AccountId)) + { + await manager.AdoptStopAsync(placed, cancellationToken).ConfigureAwait(false); + } + + var adopted = true; + foreach (var placed in note.Placed) + { + adopted &= await _db.ReadAsync(async s => await s.CountAsync("SELECT COUNT(*) FROM orders WHERE client_order_id = @c", ("c", placed.ClientOrderId)) + .ConfigureAwait(false) > 0, cancellationToken).ConfigureAwait(false); + } + + if (adopted) + { + await _db.WriteAsync(s => Diary.WriteAsync(s, _clock, DiaryKinds.System, "guard_intervention", string.Join(" ", note.Lines), + new { at = note.At, reason = note.Reason, stops = note.Placed.Count, stopFile = note.StopFileCreated }, cancellationToken), cancellationToken).ConfigureAwait(false); + File.Delete(path); + } + } + } + + /// The accounts whose startup failed are tried again, once a minute. + private async Task RetryAccountsAsync(CancellationToken cancellationToken) + { + if (_clock.UtcNow < _accountsRetryAt) + { + return; + } + + _accountsRetryAt = _clock.UtcNow + AccountRetry; + foreach (var manager in _managers.Values.Where(m => !AccountReady(m.Account.AccountId))) + { + await LimitedAsync("nuovo avvio " + manager.Account.Name, RetryLimit, ct => StartAccountAsync(manager, ct), cancellationToken).ConfigureAwait(false); + BeatIfAlive(); } } @@ -504,7 +564,7 @@ public sealed partial class TradingService : IDisposable } await TickAllAsync(cancellationToken).ConfigureAwait(false); - Guard?.Beat(); + BeatIfAlive(); if (GuardFiles is not null && _clock.UtcNow - _guardStateAt >= GuardStateEvery) { await GuardAsync("stato per la guardia", () => WriteGuardStateAsync(cancellationToken), cancellationToken).ConfigureAwait(false); @@ -550,20 +610,52 @@ public sealed partial class TradingService : IDisposable public async Task TickAllAsync(CancellationToken cancellationToken) { - foreach (var manager in _managers.Values) + await RetryAccountsAsync(cancellationToken).ConfigureAwait(false); + + // An account not started yet keeps what it left open untouched: its startup cancels or resumes it first. + foreach (var manager in _managers.Values.Where(m => AccountReady(m.Account.AccountId))) { - await GuardAsync("ordini " + manager.Account.Name, async () => + await LimitedAsync("ordini " + manager.Account.Name, TickLimit, async ct => { if (manager.Broker is PaperBroker paper) { - await paper.PumpAsync(cancellationToken).ConfigureAwait(false); + await paper.PumpAsync(ct).ConfigureAwait(false); } - await manager.TickAsync(cancellationToken).ConfigureAwait(false); + await manager.TickAsync(ct).ConfigureAwait(false); }, cancellationToken).ConfigureAwait(false); + BeatIfAlive(); } } + /// + /// The longest one account's turn of the loop may take. A broker that stops answering (timeouts, retries) must + /// not keep the loop from beating for the two minutes after which the guard steps in: the turn is cut, written in + /// the log, and tried again at the next round. A loop that is truly stuck still falls silent. + /// + public TimeSpan TickLimit { get; init; } = TimeSpan.FromSeconds(45); + + /// The longest an account's startup may take when it is tried again from the loop. + public TimeSpan RetryLimit { get; init; } = TimeSpan.FromSeconds(60); + + /// Whether the other loops of the engine are alive (the scheduler): without them the beat is withheld. + public Func? OthersAlive { get; init; } + + private void BeatIfAlive() + { + if (OthersAlive is null || OthersAlive()) + { + Guard?.Beat(); + } + } + + private async Task LimitedAsync(string what, TimeSpan limit, Func work, CancellationToken cancellationToken) + { + using var limited = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + limited.CancelAfter(limit); + await GuardAsync(what, () => work(limited.Token), cancellationToken).ConfigureAwait(false); + } + public async Task ReconcileAllAsync(CancellationToken cancellationToken) { await RefreshSpecsAsync(cancellationToken).ConfigureAwait(false); @@ -816,11 +908,15 @@ public sealed partial class TradingService : IDisposable } } - private async Task GuardAsync(string what, Func work, CancellationToken cancellationToken) + private Task GuardAsync(string what, Func work, CancellationToken cancellationToken) => TryAsync(what, work, cancellationToken); + + /// Runs a step; a failure is logged and the answer is false. Only the stop of the service passes through. + private async Task TryAsync(string what, Func work, CancellationToken cancellationToken) { try { await work().ConfigureAwait(false); + return true; } catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { @@ -829,6 +925,7 @@ public sealed partial class TradingService : IDisposable catch (Exception ex) { LogWorkFailed(_logger, ex, what); + return false; } } diff --git a/tests/Anubis.Tests/LiveEngineTests.cs b/tests/Anubis.Tests/LiveEngineTests.cs index a8ad544..5c02e28 100644 --- a/tests/Anubis.Tests/LiveEngineTests.cs +++ b/tests/Anubis.Tests/LiveEngineTests.cs @@ -71,6 +71,8 @@ public sealed class LiveEngineTests var last = LiveFrom.AddDays(13); await using var live = await LiveRig.CreateAsync(LiveFrom, last).ConfigureAwait(false); var restarted = false; + var waited = false; + (int Runs, int Sent) before = default; for (var day = LiveFrom; day <= last; day = day.AddDays(1)) { var index = day.DayNumber - LiveFrom.DayNumber; @@ -90,6 +92,25 @@ public sealed class LiveEngineTests } , + // The account has not finished its startup (the broker did not answer it): for three minutes nothing is + // decided or sent on it, then the decision is made late. + 5 => async minute => + { + var runs = (await live.Rig.QueryAsync("SELECT run_key FROM engine_runs", r => r.Text("run_key")).ConfigureAwait(false)).Count; + if (minute == 0) + { + before = (runs, live.Sent.Count); + } + else if (minute == 3) + { + Assert.AreEqual(before, (runs, live.Sent.Count), "Nothing is decided or sent on an account not started."); + waited = true; + } + + live.AccountStarted = minute >= 3; + } + , + // The process dies with a purchase working at the broker and starts again. 11 => async minute => { @@ -118,6 +139,7 @@ public sealed class LiveEngineTests } Assert.IsTrue(restarted, "The run must restart halfway through an order."); + Assert.IsTrue(waited, "The run must hold an account not started."); Assert.AreEqual(1, live.Restarts); Assert.IsGreaterThan(0, live.Failures, "The faults must have hit the work."); diff --git a/tests/Anubis.Tests/LiveSupport.cs b/tests/Anubis.Tests/LiveSupport.cs index cb7fcd9..d42b353 100644 --- a/tests/Anubis.Tests/LiveSupport.cs +++ b/tests/Anubis.Tests/LiveSupport.cs @@ -36,6 +36,9 @@ internal sealed class LiveRig : IAsyncDisposable public LiveEngine Engine { get; private set; } = null!; + /// Whether the account finished its startup (SPEC 9.4); while false the engine leaves it alone. + public bool AccountStarted { get; set; } = true; + public EquityBook Equity { get; private set; } = null!; public Reconciler Reconciler { get; private set; } = null!; @@ -103,7 +106,10 @@ internal sealed class LiveRig : IAsyncDisposable { Broker = new FaultyBroker(Paper); Manager = Rig.Manager(Broker, Okx); - Engine = new LiveEngine(Rig.Db, Rig.Clock, Rig.Ledger, Stages, id => id == Okx.AccountId ? Manager : null, Rig.QuoteAsync); + Engine = new LiveEngine(Rig.Db, Rig.Clock, Rig.Ledger, Stages, id => id == Okx.AccountId ? Manager : null, Rig.QuoteAsync) + { + AccountReady = _ => AccountStarted, + }; } /// diff --git a/tests/Anubis.Tests/OverviewScreenTests.cs b/tests/Anubis.Tests/OverviewScreenTests.cs index 035fb36..f875548 100644 --- a/tests/Anubis.Tests/OverviewScreenTests.cs +++ b/tests/Anubis.Tests/OverviewScreenTests.cs @@ -130,6 +130,19 @@ public sealed class OverviewScreenTests StringAssert.Contains(diary, "Come sta il sistema"); StringAssert.Contains(diary, "non configurato"); StringAssert.Contains(diary, "Il computer che lo ospita"); + + // SPEC 5.6: an absence longer than a day stays at the top of the Panoramica until "Ho visto". + var now = server.Host.Clock.UtcNow; + var id = Guid.NewGuid(); + await server.Host.Services!.Db.WriteAsync(s => s.ExecuteAsync("INSERT INTO absences (id, started_at, ended_at, acknowledged_at, created_at) VALUES (@id, @s, @e, NULL, @e)", + CancellationToken.None, ("id", id), ("s", now.AddDays(-3).AddHours(-2)), ("e", now))); + StringAssert.Contains(await server.TextAsync("/"), "Sono stato spento per 3 giorni e 2 ore, fino a oggi alle"); + using (var seen = await server.PostFormAsync("/", $"/azioni/assenza/{id}/vista")) + { + Assert.AreEqual("/", ServerHarness.Location(seen)); + } + + Assert.DoesNotContain("Sono stato spento", await server.TextAsync("/")); } [TestMethod] diff --git a/tests/Anubis.Tests/ServerTests.cs b/tests/Anubis.Tests/ServerTests.cs index a770a45..630e7c1 100644 --- a/tests/Anubis.Tests/ServerTests.cs +++ b/tests/Anubis.Tests/ServerTests.cs @@ -200,23 +200,27 @@ public sealed class ServerTests ServerHarness.UsePostgres(env, empty); } - await using var server = await ServerHarness.StartAsync("docker", env, dataDir: data, waitReady: false); - await server.WaitForAsync(HostMode.IdentityProblem); - Assert.AreEqual(IdentityVerdict.EmptyDatabase, server.Host.Status.Identity!.Verdict); - using (var restore = await server.PostFormAsync("/", "/azioni/servizio/ripristina", ("password", ServerHarness.AdminPassword), ("salvataggio", backup.Name))) + // The server stops before its data folder is removed: a running one may still hold the database file. + await using (var server = await ServerHarness.StartAsync("docker", env, dataDir: data, waitReady: false)) { - Assert.AreEqual("/", ServerHarness.Location(restore)); + await server.WaitForAsync(HostMode.IdentityProblem); + Assert.AreEqual(IdentityVerdict.EmptyDatabase, server.Host.Status.Identity!.Verdict); + using (var restore = await server.PostFormAsync("/", "/azioni/servizio/ripristina", ("password", ServerHarness.AdminPassword), ("salvataggio", backup.Name))) + { + Assert.AreEqual("/", ServerHarness.Location(restore)); + } + + await server.WaitForAsync(HostMode.Ready); + + // SPEC 15.1: back with "Ferma tutto" on, a new fingerprint, and nobody signed in. + var state = await server.Host.Services!.Settings.GetAsync(SettingsStore.BotState.Key); + Assert.AreEqual("stopped", state.Value); + var row = await Installation.ReadRowAsync(server.Host.Services.Db); + Assert.IsTrue(row!.ProtectedRestart); + Assert.AreEqual(row.Fingerprint, Installation.ReadFile(new DataDirectory(data))!.Fingerprint); + Assert.AreEqual(0, await server.Host.Services.Db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM sessions"))); } - await server.WaitForAsync(HostMode.Ready); - - // SPEC 15.1: back with "Ferma tutto" on, a new fingerprint, and nobody signed in. - var state = await server.Host.Services!.Settings.GetAsync(SettingsStore.BotState.Key); - Assert.AreEqual("stopped", state.Value); - var row = await Installation.ReadRowAsync(server.Host.Services.Db); - Assert.IsTrue(row!.ProtectedRestart); - Assert.AreEqual(row.Fingerprint, Installation.ReadFile(new DataDirectory(data))!.Fingerprint); - Assert.AreEqual(0, await server.Host.Services.Db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM sessions"))); TempFolder.Delete(data); } diff --git a/tests/Anubis.Tests/SoakReportTests.cs b/tests/Anubis.Tests/SoakReportTests.cs index b8c0e75..3291b0b 100644 --- a/tests/Anubis.Tests/SoakReportTests.cs +++ b/tests/Anubis.Tests/SoakReportTests.cs @@ -17,7 +17,8 @@ public sealed class SoakReportTests { Assert.AreEqual(2, SoakReporter.DailyCloses(From, To)); // 12 and 13 November at 00:05 UTC var close = new DateTimeOffset(2026, 11, 11, 0, 5, 0, TimeSpan.Zero); - Assert.AreEqual(1, SoakReporter.DailyCloses(close, close)); + Assert.AreEqual(1, SoakReporter.DailyCloses(close, close + SoakReporter.DecisionTime)); + Assert.AreEqual(0, SoakReporter.DailyCloses(close, close.AddMinutes(10)), "A decision just started is not expected yet."); Assert.AreEqual(3, SoakReporter.DailyCloses(close, To)); Assert.AreEqual(0, SoakReporter.DailyCloses(From, From.AddHours(5))); } diff --git a/tests/Anubis.Tests/TelegramTests.cs b/tests/Anubis.Tests/TelegramTests.cs index cb55257..8e3bac0 100644 --- a/tests/Anubis.Tests/TelegramTests.cs +++ b/tests/Anubis.Tests/TelegramTests.cs @@ -168,6 +168,9 @@ public sealed class TelegramTests Assert.IsNull(Heartbeat.Check("https://hc-ping.com/uuid")); Assert.IsNull(Heartbeat.Check("http://192.168.30.23:8000/ping/x")); Assert.IsNotNull(Heartbeat.Check("http://hc-ping.com/uuid")); + Assert.IsNotNull(Heartbeat.Check("http://8.8.8.8/ping/x"), "A public address in plain http travels in clear."); + Assert.IsNull(Heartbeat.Check("http://10.0.0.5/ping/x")); + Assert.IsNull(Heartbeat.Check("http://[fd00::5]/ping/x")); Assert.IsNotNull(Heartbeat.Check("ftp://example.com")); Assert.IsNotNull(Heartbeat.Check("non è un indirizzo")); }