Rebuild the state from the brokers after a restore and refuse an older copy
A restore, an import or an adopted database restarts protected: the engine stays stopped, reads from the broker what the archive does not know (orders, stops, executions, also from the OKX history up to 89 days), cancels orders left working, protects what it finds and waits for the user. Strategies with real money stay exit only until confirmed again. The database of before the restore, put back by mistake, is refused by its fingerprint. A failed migration leaves the engine off with one backup and a way to try again; an archive is checked whole before the database is touched; a changed secret key no longer crashes anything, and "anubis access reset" gives the access back to whoever holds the computer. The image runs the db and access commands without the guard. refs #69 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
3da9b00f44
commit
4897594b87
40 files changed
+1871
-90
No files matched your search
@@ -0,0 +1,56 @@
|
||||
using System.Collections;
|
||||
using Anubis.Access;
|
||||
using Anubis.Core;
|
||||
using Anubis.Db;
|
||||
using Anubis.Platform;
|
||||
|
||||
namespace Anubis.Server;
|
||||
|
||||
/// <summary>
|
||||
/// "anubis access reset": a temporary password printed once, the second factor off, every session closed. Only whoever
|
||||
/// can run a command on the computer or in the container gets here, and that person owns the data folder already. Used
|
||||
/// after a lost password, a lost phone or a changed secret key (RUNBOOK).
|
||||
/// </summary>
|
||||
internal static class AccessCommand
|
||||
{
|
||||
public static async Task<int> RunAsync(string[] args, TextWriter? output = null, IReadOnlyDictionary<string, string?>? environment = null, int? iterations = null)
|
||||
{
|
||||
output ??= Console.Out;
|
||||
if (args.Length < 1 || args[0] != "reset")
|
||||
{
|
||||
await output.WriteLineAsync("Uso: anubis access reset [--platform docker|desktop] [--data-dir <cartella>]").ConfigureAwait(false);
|
||||
return 2;
|
||||
}
|
||||
|
||||
environment ??= Environment.GetEnvironmentVariables().Cast<DictionaryEntry>().ToDictionary(e => (string)e.Key, e => e.Value as string, StringComparer.Ordinal);
|
||||
var config = ServerOptions.Parse(args[1..], environment).LoadConfig(environment);
|
||||
if (config.Db is not { } settings)
|
||||
{
|
||||
await output.WriteLineAsync("La configurazione d'avvio non indica il database.").ConfigureAwait(false);
|
||||
return 1;
|
||||
}
|
||||
|
||||
Redactor.Register(settings.Password);
|
||||
var clock = new SystemClock();
|
||||
try
|
||||
{
|
||||
await using var db = Database.Open(settings, allowCreate: false);
|
||||
var access = new AccessStore(db, clock, new SecretStore(db, clock, new byte[32]), iterations ?? Passwords.DefaultIterations);
|
||||
var temporary = Ids.NewToken()[..16];
|
||||
if (!await access.ResetAsync(temporary).ConfigureAwait(false))
|
||||
{
|
||||
await output.WriteLineAsync("Non c'è ancora nessun utente: apri Anubis e fai il primo accesso.").ConfigureAwait(false);
|
||||
return 1;
|
||||
}
|
||||
|
||||
await output.WriteLineAsync("Password provvisoria: " + temporary + Environment.NewLine +
|
||||
"Accedi subito: ti chiederà di sceglierne una nuova. Il secondo fattore è tolto e tutte le sessioni sono chiuse.").ConfigureAwait(false);
|
||||
return 0;
|
||||
}
|
||||
catch (Exception ex) when (Forms.IsArchiveProblem(ex))
|
||||
{
|
||||
await output.WriteLineAsync("Non riuscito: " + Redactor.Redact(ex.Message)).ConfigureAwait(false);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -96,6 +96,9 @@ internal sealed partial class AnubisHost(
|
||||
|
||||
public int PasswordIterations => overrides?.PasswordIterations ?? Passwords.DefaultIterations;
|
||||
|
||||
/// <summary>Why the last migration failed; the error page's "Riprova" clears it.</summary>
|
||||
internal string? MigrationFailed { get; set; }
|
||||
|
||||
/// <summary>Asks the loop to check again now (after the wizard or an error-page choice).</summary>
|
||||
public void Wake()
|
||||
{
|
||||
@@ -286,7 +289,7 @@ internal sealed partial class AnubisHost(
|
||||
}
|
||||
catch (SchemaException ex)
|
||||
{
|
||||
SetStatus(HostMode.SchemaProblem, ex.Message);
|
||||
SetStatus(HostMode.SchemaProblem, Redactor.Redact(ex.Message));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -396,9 +399,27 @@ internal sealed partial class AnubisHost(
|
||||
SetStatus(HostMode.Ready, null);
|
||||
}
|
||||
|
||||
private async Task MigrateAsync(Backups backups, CancellationToken cancellationToken)
|
||||
internal async Task MigrateAsync(Backups backups, CancellationToken cancellationToken)
|
||||
{
|
||||
var applied = await Migrations.MigrateAsync(_db!, clock, ct => backups.TakeAsync(_db!, "prima-della-migrazione", ct), cancellationToken).ConfigureAwait(false);
|
||||
// SPEC 9.4: after a migration that failed the engine stays off. It is not tried again by itself, because every
|
||||
// attempt would take one more backup; the user tries again from the error page or with a restart.
|
||||
if (MigrationFailed is { } failed)
|
||||
{
|
||||
throw new SchemaException(failed);
|
||||
}
|
||||
|
||||
int applied;
|
||||
try
|
||||
{
|
||||
applied = await Migrations.MigrateAsync(_db!, clock, ct => backups.TakeAsync(_db!, Backups.BeforeMigration, ct), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (SchemaException ex) when (ex.InnerException is not null)
|
||||
{
|
||||
LogMigrationFailed(logger, ex);
|
||||
MigrationFailed = ex.Message;
|
||||
throw;
|
||||
}
|
||||
|
||||
if (applied > 0)
|
||||
{
|
||||
LogMigrated(logger, applied, Migrations.Latest);
|
||||
@@ -739,6 +760,9 @@ internal sealed partial class AnubisHost(
|
||||
[LoggerMessage(Level = LogLevel.Warning, Message = "Demo mode: separate database in {Folder}")]
|
||||
private static partial void LogDemo(ILogger logger, string folder);
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Error, Message = "Migration failed: the engine stays off until the user tries again")]
|
||||
private static partial void LogMigrationFailed(ILogger logger, Exception exception);
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Information, Message = "Applied {Count} migrations, schema version {Version}")]
|
||||
private static partial void LogMigrated(ILogger logger, int count, int version);
|
||||
|
||||
|
||||
@@ -18,6 +18,9 @@
|
||||
case IdentityVerdict.DifferentInstallation:
|
||||
<p>Il database appartiene a un'altra installazione di Anubis. Il motore resta spento: due registri sugli stessi conti produrrebbero ordini doppi.</p>
|
||||
break;
|
||||
case IdentityVerdict.MissingFile:
|
||||
<p>Il database appartiene a un'installazione, ma la cartella dei dati non ha il suo file d'identità: non posso sapere se questo database è quello giusto o una copia vecchia. Il motore resta spento finché non lo dici tu.</p>
|
||||
break;
|
||||
case IdentityVerdict.StaleDatabase:
|
||||
<p>È il database di questa installazione, ma una copia più vecchia: dopo l'ultimo ripristino o spostamento ne è nata una più recente. Il motore resta spento per non lavorare su dati superati.</p>
|
||||
break;
|
||||
|
||||
@@ -40,6 +40,7 @@
|
||||
{
|
||||
"password" => "Password sbagliata. Riprova: dopo 5 tentativi sbagliati l'accesso si blocca per 15 minuti.",
|
||||
"codice" => "Il codice non è giusto o è scaduto. Usa quello che l'app mostra adesso.",
|
||||
"chiave" => "La password è giusta, ma la chiave dei segreti (ANUBIS_SECRET_KEY) non è più quella di prima e il codice non si può controllare. Rimetti la vecchia chiave, oppure azzera l'accesso dal computer che ospita Anubis: il manuale dice come.",
|
||||
"attesa" => $"Troppi tentativi sbagliati. Riprova tra {Minuti ?? "15"} minuti.",
|
||||
_ => null,
|
||||
};
|
||||
|
||||
@@ -812,6 +812,7 @@
|
||||
private string KeyState(SecretStatus status) => status switch
|
||||
{
|
||||
{ FromEnvironment: true } => "Dalle variabili d'ambiente",
|
||||
{ Unreadable: true } => "Non si legge più: la chiave dei segreti è cambiata, inseriscila di nuovo",
|
||||
{ IsSet: true, UpdatedAt: { } at } => "Impostata " + Inline(Format.ShortDate(at, Shell.Now, Shell.Zone)),
|
||||
{ IsSet: true } => "Impostata",
|
||||
_ => "Non impostata",
|
||||
|
||||
@@ -17,6 +17,10 @@
|
||||
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 (p.ProtectedRestart)
|
||||
{
|
||||
<div class="notice notice-attention" role="status"><Icon Name="alert" Size="16" /><span><strong>Ripartenza protetta.</strong> Dopo un ripristino o un'importazione sono fermo: non apro posizioni finché non hai controllato e non confermi dalla pagina <a href="/rischio">Rischio</a>.</span></div>
|
||||
}
|
||||
@if (_absence is { } away)
|
||||
{
|
||||
<div class="notice notice-attention absence" role="status">
|
||||
|
||||
@@ -22,6 +22,34 @@
|
||||
<h2 id="interruttore">Interruttore d'emergenza</h2>
|
||||
<span class="link-state @(v.BotState == "active" ? null : "down")"><span class="dot"></span>@BotText(v.BotState)</span>
|
||||
</div>
|
||||
@if (v.ProtectedRestart is { } restart)
|
||||
{
|
||||
<div class="notice notice-attention" role="status"><Icon Name="alert" Size="16" /><div>
|
||||
<p><strong>Ripartenza protetta.</strong> Il database è cambiato il @Moment(restart.Since) (ripristino, importazione o copia più vecchia del conto): prima di ripartire guarda cosa ho ricostruito.</p>
|
||||
<ul>
|
||||
@foreach (var line in restart.Rebuilt)
|
||||
{
|
||||
<li>@line</li>
|
||||
}
|
||||
@if (restart.Working)
|
||||
{
|
||||
<li>Sto ancora leggendo i conti.</li>
|
||||
}
|
||||
else if (restart.Waiting.Count > 0)
|
||||
{
|
||||
<li>Non ho ancora letto: @string.Join(", ", restart.Waiting). Riprovo ogni minuto; se una chiave è scaduta, cambiala nelle Impostazioni.</li>
|
||||
}
|
||||
else if (restart.Rebuilt.Count == 0)
|
||||
{
|
||||
<li>Sui conti non c'era niente che il database non conoscesse già.</li>
|
||||
}
|
||||
@if (restart.ToReconfirm.Count > 0)
|
||||
{
|
||||
<li>Da riconfermare nella pagina Strategie, altrimenti restano in sola uscita: @string.Join(", ", restart.ToReconfirm).</li>
|
||||
}
|
||||
</ul>
|
||||
</div></div>
|
||||
}
|
||||
@if (v.WaitsForRestart)
|
||||
{
|
||||
<p class="notice notice-attention" role="status"><Icon Name="alert" Size="16" /><span>
|
||||
@@ -51,7 +79,7 @@
|
||||
<form method="post" action="/azioni/bot/riattiva" class="form-inline">
|
||||
<AntiforgeryToken />
|
||||
<input type="hidden" name="ritorno" value="/rischio" />
|
||||
<button class="btn" type="submit" disabled="@v.StopFile" data-confirm="@RestartText(v)">Riparti</button>
|
||||
<button class="btn" type="submit" disabled="@(v.StopFile || v.ProtectedRestart is { CanRestart: false })" data-confirm="@RestartText(v)">Riparti</button>
|
||||
</form>
|
||||
}
|
||||
}
|
||||
@@ -293,7 +321,9 @@
|
||||
|
||||
private static string Where(string world) => world == Worlds.Real ? "sui conti veri" : "nel mondo simulato";
|
||||
|
||||
private static string RestartText(RiskView v) => v.Tripped.Count > 0
|
||||
private static string RestartText(RiskView v) => v.ProtectedRestart is not null
|
||||
? "Riparti dopo il ripristino: hai controllato posizioni e operazioni ricostruite? Il bot torna a operare; le strategie con soldi veri restano in sola uscita finché non le riconfermi. Confermi?"
|
||||
: v.Tripped.Count > 0
|
||||
? "Riparti: il massimo di riferimento riparte dal patrimonio di adesso e il bot torna a operare. Confermi?"
|
||||
: "Riparti: il bot torna a operare. Confermi?";
|
||||
|
||||
|
||||
@@ -65,6 +65,25 @@
|
||||
|
||||
case HostMode.SchemaProblem:
|
||||
<p>@_status.Detail</p>
|
||||
@if (Host.MigrationFailed is not null)
|
||||
{
|
||||
var copies = new Backups(Host.Config.Data, Clock).List();
|
||||
<p>Il motore resta spento.
|
||||
@if (copies.Count > 0)
|
||||
{
|
||||
<text>L'ultimo salvataggio è <code>@copies[0].Name</code>, in <code>@Host.Config.Data.Backups</code>: per tornarci, indica nella configurazione un database nuovo e vuoto e sceglilo in questa pagina.</text>
|
||||
}
|
||||
Se il problema è passeggero (spazio sul disco, permessi), risolvilo e riprova.</p>
|
||||
@if (Host.Config.Platform == PlatformKind.Docker || _local)
|
||||
{
|
||||
<form method="post" action="/azioni/servizio/riprova" class="form">
|
||||
<AntiforgeryToken />
|
||||
<AdminPassword Docker="Host.Config.Platform == PlatformKind.Docker" />
|
||||
<button class="btn btn-primary" type="submit">Riprova l'aggiornamento</button>
|
||||
</form>
|
||||
}
|
||||
break;
|
||||
}
|
||||
<p>Per non rovinare i dati il motore resta spento. Aggiorna Anubis alla versione che ha creato questo database, oppure ripristina un salvataggio in un database vuoto.</p>
|
||||
break;
|
||||
|
||||
@@ -82,7 +101,7 @@
|
||||
<p class="notice notice-loss" role="alert"><Icon Name="alert" Size="16" />@(errore switch
|
||||
{
|
||||
"password" => "Password della configurazione d'avvio sbagliata, oppure scelta fatta da un altro computer.",
|
||||
"importazione" => "Il ripristino non è riuscito e non ho cambiato nulla. Controlla l'archivio e riprova.",
|
||||
"importazione" => "Non ci sono riuscito e nessun dato a metà è in uso. Controlla l'archivio o guarda i log, poi riprova.",
|
||||
"attesa" => "Troppi tentativi sbagliati. Riprova tra 15 minuti.",
|
||||
_ => "Questa scelta non è disponibile adesso.",
|
||||
})</p>
|
||||
|
||||
@@ -51,7 +51,7 @@
|
||||
var up = s.ResultEur >= 0;
|
||||
<section class="panel strategy" aria-label="@s.Name">
|
||||
<div class="strategy-about">
|
||||
<h2><span class="swatch round" style="background: @s.Color"></span>@s.Name <span class="tag">@(s.Stage.ExitOnly ? "Sola uscita" : "In " + StrategyStages.Label(s.Stage.Stage).ToLower(CultureInfo.GetCultureInfo("it-IT")))</span></h2>
|
||||
<h2><span class="swatch round" style="background: @s.Color"></span>@s.Name <span class="tag">@(s.Stage.WaitsForReconfirmation ? "Da riconfermare" : s.Stage.ExitOnly ? "Sola uscita" : "In " + StrategyStages.Label(s.Stage.Stage).ToLower(CultureInfo.GetCultureInfo("it-IT")))</span></h2>
|
||||
<p>@s.Description</p>
|
||||
<ul>
|
||||
@foreach (var rule in s.Rules)
|
||||
@@ -92,7 +92,30 @@
|
||||
</li>
|
||||
}
|
||||
</ul>
|
||||
@if (s.Stage.ExitOnly)
|
||||
@if (s.Stage.WaitsForReconfirmation)
|
||||
{
|
||||
<p class="notice notice-attention"><Icon Name="alert" Size="16" />Dopo un ripristino non compra con soldi veri finché non la riconfermi: vende e tiene gli stop. I giorni e i conteggi restano quelli di prima.</p>
|
||||
@if (!Shell.IsDemo)
|
||||
{
|
||||
<details class="confirm-live">
|
||||
<summary class="btn">Riconferma</summary>
|
||||
<form method="post" action="/azioni/strategie/@s.Stage.Strategy/riconferma" class="form-grid">
|
||||
<AntiforgeryToken />
|
||||
<p>Ecco con che cosa riprende <strong>@s.Name</strong>:</p>
|
||||
<ul class="confirm-summary">
|
||||
@foreach (var line in s.Summary)
|
||||
{
|
||||
<li>@line</li>
|
||||
}
|
||||
</ul>
|
||||
<label>Password<input name="password" type="password" required autocomplete="current-password" /></label>
|
||||
<label>Codice a sei cifre (se attivo)<input name="codice" inputmode="numeric" autocomplete="one-time-code" /></label>
|
||||
<button class="btn btn-danger" type="submit">Riconferma soldi veri</button>
|
||||
</form>
|
||||
</details>
|
||||
}
|
||||
}
|
||||
else if (s.Stage.ExitOnly)
|
||||
{
|
||||
<p class="notice notice-attention"><Icon Name="alert" Size="16" />Tornata indietro con posizioni vere ancora aperte: le gestisce fino a zero, con i loro stop, senza nuovi acquisti.</p>
|
||||
}
|
||||
@@ -220,6 +243,7 @@
|
||||
("simulazione", _) => ("Fatto: la strategia è in simulazione, con ordini finti su prezzi veri.", true),
|
||||
("osservazione", _) => ("Fatto: la strategia è in osservazione.", true),
|
||||
("reale", _) => ("Fatto: la strategia usa soldi veri da adesso. Se peggiora torna indietro da sola.", true),
|
||||
("riconferma", _) => ("Fatto: la strategia è riconfermata e torna a operare con soldi veri.", true),
|
||||
(_, "backtest") => ("Solo una strategia che ha superato il backtest può andare in simulazione.", false),
|
||||
(_, "osservazione-giorni") => ($"Prima della simulazione servono almeno {StageBook.ObservationDays} giorni di segnali raccolti dal vivo in osservazione.", false),
|
||||
(_, "frase") => ("La frase non corrisponde: scrivila esattamente come è mostrata.", false),
|
||||
|
||||
@@ -40,7 +40,15 @@ internal static class DatabaseCommand
|
||||
var folder = Path.GetFullPath(args[1]);
|
||||
try
|
||||
{
|
||||
await using var db = Database.Open(config.Db!, allowCreate: args[0] == "import" && !File.Exists(config.Data.InstallationFile));
|
||||
if (args[0] == "import")
|
||||
{
|
||||
// Read before the database is opened: a wrong folder must not leave a new empty SQLite file behind.
|
||||
await Archive.ReadIndexAsync(folder).ConfigureAwait(false);
|
||||
config.Data.Ensure();
|
||||
}
|
||||
|
||||
// Moving to SQLite, the file does not exist yet: the user asked for it by name, unlike a start (trap 20).
|
||||
await using var db = Database.Open(config.Db!, allowCreate: args[0] == "import");
|
||||
if (args[0] == "export")
|
||||
{
|
||||
var index = await Archive.ExportAsync(db, folder, clock).ConfigureAwait(false);
|
||||
@@ -48,14 +56,13 @@ internal static class DatabaseCommand
|
||||
return 0;
|
||||
}
|
||||
|
||||
config.Data.Ensure();
|
||||
var imported = await Archive.ImportAsync(db, folder, clock).ConfigureAwait(false);
|
||||
await Installation.RenewAsync(db, config.Data, clock, adoptDatabaseIdentity: !File.Exists(config.Data.InstallationFile)).ConfigureAwait(false);
|
||||
await Installation.RenewAsync(db, config.Data, clock, "Archivio importato").ConfigureAwait(false);
|
||||
await output.WriteLineAsync($"Importate {imported.Tables.Sum(t => t.Count)} righe di {imported.Tables.Count} tabelle: conteggi e totali coincidono. " +
|
||||
"Al prossimo avvio il bot riparte protetto.").ConfigureAwait(false);
|
||||
return 0;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or InvalidOperationException or SchemaException or System.Text.Json.JsonException or System.Data.Common.DbException)
|
||||
catch (Exception ex) when (Forms.IsArchiveProblem(ex))
|
||||
{
|
||||
await output.WriteLineAsync("Non riuscito: " + Redactor.Redact(ex.Message)).ConfigureAwait(false);
|
||||
return 1;
|
||||
|
||||
@@ -330,6 +330,16 @@ internal static partial class Endpoints
|
||||
: "Comando non ammesso nello stato attuale del bot.");
|
||||
}
|
||||
|
||||
var restart = command is "restart" or "riattiva"
|
||||
&& await Platform.Installation.ReadRowAsync(host.Services.Db, ct).ConfigureAwait(false) is { ProtectedRestart: true };
|
||||
if (restart && (host.Services.Trading is not { Risk: not null, Started: true } engineOn || engineOn.AccountsToRebuild.Count > 0))
|
||||
{
|
||||
// SPEC 15.1: first the executions after the archive, then the user's confirmation.
|
||||
var waiting = host.Services.Trading?.AccountsToRebuild ?? [];
|
||||
return (false, "Dopo il ripristino devo prima ricostruire dal broker le esecuzioni successive al salvataggio" +
|
||||
(waiting.Count == 0 ? "." : $". Aspetto: {string.Join(", ", waiting)}."));
|
||||
}
|
||||
|
||||
if (host.Services.Trading is { Risk: { } risk } trading)
|
||||
{
|
||||
// The switch of SPEC 9.3 goes through the risk engine: it cancels the orders under way and keeps the stops.
|
||||
@@ -346,6 +356,11 @@ internal static partial class Endpoints
|
||||
try
|
||||
{
|
||||
await risk.RestartAsync(by, ct).ConfigureAwait(false);
|
||||
if (restart)
|
||||
{
|
||||
await Platform.Installation.ClearProtectedRestartAsync(host.Services.Db, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await NotifyBotAsync(host, "bot_restarted", $"Il bot è ripartito dopo «Ferma tutto» (da {by}).", ct).ConfigureAwait(false);
|
||||
return (true, target);
|
||||
}
|
||||
|
||||
@@ -173,6 +173,8 @@ internal static partial class Forms
|
||||
case LoginResult.SecondFactorNeeded:
|
||||
limiter.Forgive(address);
|
||||
return Results.Redirect(With(With("/accesso", "fattore", "1"), "ritorno", back));
|
||||
case LoginResult.UnreadableSecondFactor:
|
||||
return Results.Redirect(With("/accesso", "errore", "chiave"));
|
||||
case LoginResult.WrongSecondFactor:
|
||||
return Results.Redirect(With(With(With("/accesso", "fattore", "1"), "errore", "codice"), "ritorno", back));
|
||||
default:
|
||||
@@ -590,6 +592,10 @@ internal static partial class Forms
|
||||
await stages.ConfirmLiveAsync(new Anubis.Trading.LiveConfirmation(strategy, account, form["frase"].ToString(), form["password"].ToString(),
|
||||
string.IsNullOrWhiteSpace(code) ? null : code.Trim(), by), ct).ConfigureAwait(false);
|
||||
return Results.Redirect("/strategie?ok=reale");
|
||||
case "riconferma":
|
||||
var second = form["codice"].ToString();
|
||||
await stages.ReconfirmAsync(strategy, form["password"].ToString(), string.IsNullOrWhiteSpace(second) ? null : second.Trim(), by, ct).ConfigureAwait(false);
|
||||
return Results.Redirect("/strategie?ok=riconferma");
|
||||
default:
|
||||
return Results.Redirect("/strategie?errore=scelta");
|
||||
}
|
||||
@@ -1041,6 +1047,14 @@ internal static partial class Forms
|
||||
using var exclusive = await host.ExclusiveAsync(ct).ConfigureAwait(false);
|
||||
var status = host.Status;
|
||||
var db = host.Database;
|
||||
if (choice == "riprova" && status.Mode == HostMode.SchemaProblem)
|
||||
{
|
||||
host.MigrationFailed = null;
|
||||
exclusive.Dispose();
|
||||
host.Wake();
|
||||
return Results.Redirect("/");
|
||||
}
|
||||
|
||||
if (status.Mode != HostMode.IdentityProblem || status.Identity is null || db is null)
|
||||
{
|
||||
return Results.Redirect("/");
|
||||
@@ -1059,7 +1073,7 @@ internal static partial class Forms
|
||||
}
|
||||
|
||||
await Archive.ImportAsync(db, Path.Combine(backup.Folder, Backups.ArchiveFolder), clock, ct).ConfigureAwait(false);
|
||||
await Installation.RenewAsync(db, config.Data, clock, adoptDatabaseIdentity: false, ct).ConfigureAwait(false);
|
||||
await Installation.RenewAsync(db, config.Data, clock, "Salvataggio ripristinato", ct).ConfigureAwait(false);
|
||||
break;
|
||||
case "importa" when verdict == IdentityVerdict.EmptyDatabase:
|
||||
var folder = ServiceChoices.ImportFolders(config.Data).FirstOrDefault(f => Path.GetFileName(f) == form["archivio"].ToString());
|
||||
@@ -1069,13 +1083,15 @@ internal static partial class Forms
|
||||
}
|
||||
|
||||
await Archive.ImportAsync(db, folder, clock, ct).ConfigureAwait(false);
|
||||
await Installation.RenewAsync(db, config.Data, clock, adoptDatabaseIdentity: false, ct).ConfigureAwait(false);
|
||||
await Installation.RenewAsync(db, config.Data, clock, "Archivio importato", ct).ConfigureAwait(false);
|
||||
break;
|
||||
case "da-capo" when verdict == IdentityVerdict.EmptyDatabase:
|
||||
Installation.StartOver(config.Data, clock);
|
||||
break;
|
||||
case "usa-questo" when verdict is IdentityVerdict.DifferentInstallation or IdentityVerdict.StaleDatabase:
|
||||
await Installation.RenewAsync(db, config.Data, clock, adoptDatabaseIdentity: true, ct).ConfigureAwait(false);
|
||||
case "usa-questo" when verdict is IdentityVerdict.DifferentInstallation or IdentityVerdict.StaleDatabase or IdentityVerdict.MissingFile:
|
||||
// An old copy may have an old schema: it is brought up to date, after its own backup, before it is protected.
|
||||
await host.MigrateAsync(new Backups(config.Data, clock), ct).ConfigureAwait(false);
|
||||
await Installation.RenewAsync(db, config.Data, clock, "Database scelto dalla pagina d'errore", ct).ConfigureAwait(false);
|
||||
break;
|
||||
default:
|
||||
return Results.Redirect("/?errore=scelta");
|
||||
|
||||
@@ -40,6 +40,9 @@ internal sealed record PanoramaView(
|
||||
LearningSummary Learning,
|
||||
DateTimeOffset? FractionStops)
|
||||
{
|
||||
/// <summary>After a restore the bot waits for the user (SPEC 15.1).</summary>
|
||||
public bool ProtectedRestart { get; init; }
|
||||
|
||||
private static readonly CultureInfo _it = CultureInfo.InvariantCulture;
|
||||
|
||||
/// <summary>"Notizie che contano" (SPEC 13.6): first those with an effect in force, then the latest on the positions or their markets.</summary>
|
||||
@@ -97,7 +100,10 @@ internal sealed record PanoramaView(
|
||||
{
|
||||
var board = await new Anubis.News.NewsBoard(services.Db, clock, services.Settings).LoadAsync(cancellationToken).ConfigureAwait(false);
|
||||
return new PanoramaView(accounts, trends, limits, kept, cards, anyLive, system, null, null, Decision(overview.NextDecision, shell.Now, shell.Zone),
|
||||
services.MarketData is null && board.Rows.Count == 0 ? null : Matters(board, shell), learning, fractions);
|
||||
services.MarketData is null && board.Rows.Count == 0 ? null : Matters(board, shell), learning, fractions)
|
||||
{
|
||||
ProtectedRestart = risk.ProtectedRestart is not null,
|
||||
};
|
||||
}
|
||||
|
||||
var root = aggregates.RootElement;
|
||||
|
||||
@@ -6,6 +6,12 @@ if (args.Length >= 1 && args[0] == "db")
|
||||
return await DatabaseCommand.RunAsync(args[1..]).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// "anubis access reset": a new password for whoever holds the computer, the second factor off (RUNBOOK).
|
||||
if (args.Length >= 1 && args[0] == "access")
|
||||
{
|
||||
return await AccessCommand.RunAsync(args[1..]).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// "anubis data report|binance|csv": the data quality report and the research imports (Phase 2).
|
||||
if (args.Length >= 1 && args[0] == "data")
|
||||
{
|
||||
|
||||
@@ -9,6 +9,29 @@ namespace Anubis.Server;
|
||||
/// <summary>A row of the limits table: what is used now against the threshold, and what happens beyond it.</summary>
|
||||
internal sealed record LimitRow(string Label, string Now, string? Detail, decimal? Usage, string Threshold, string Beyond, string Key);
|
||||
|
||||
/// <summary>
|
||||
/// The protected restart of SPEC 15.1: since when, the accounts still to rebuild, what was rebuilt, the strategies
|
||||
/// that stay in exit only until they are confirmed again.
|
||||
/// </summary>
|
||||
internal sealed record ProtectedRestartView(DateTimeOffset Since, bool Working, IReadOnlyList<string> Waiting, IReadOnlyList<string> Rebuilt, IReadOnlyList<string> ToReconfirm)
|
||||
{
|
||||
public bool CanRestart => !Working && Waiting.Count == 0;
|
||||
|
||||
public static async Task<ProtectedRestartView?> LoadAsync(AppServices services, CancellationToken cancellationToken)
|
||||
{
|
||||
if (await Platform.Installation.ReadRowAsync(services.Db, cancellationToken).ConfigureAwait(false) is not { ProtectedRestart: true } row)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var rebuilt = await services.Db.ReadAsync(s => s.QueryAsync("SELECT message FROM journal WHERE code = 'ledger_rebuilt' AND occurred_at >= @f ORDER BY occurred_at, id",
|
||||
r => r.Text("message"), ("f", row.RenewedAt)), cancellationToken).ConfigureAwait(false);
|
||||
var stages = services.Trading is { } trading ? await trading.Stages.AllAsync(cancellationToken).ConfigureAwait(false) : [];
|
||||
return new ProtectedRestartView(row.RenewedAt, services.Trading is { Started: false }, services.Trading?.AccountsToRebuild ?? [], rebuilt,
|
||||
[.. stages.Where(s => s.WaitsForReconfirmation).Select(s => StrategyNames.Label(s.Strategy, withMarket: true))]);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A point of the fall from the high, as a fraction: 0 at the high, −0,03 three percent below.</summary>
|
||||
internal sealed record DrawdownPoint(DateTimeOffset At, decimal Drawdown);
|
||||
|
||||
@@ -33,6 +56,9 @@ internal sealed record RiskView(
|
||||
bool HasPositions,
|
||||
IReadOnlyList<WorldRisk> Tripped)
|
||||
{
|
||||
/// <summary>After a restore (SPEC 15.1): what the restart waits for, and what stays in exit only after it.</summary>
|
||||
public ProtectedRestartView? ProtectedRestart { get; init; }
|
||||
|
||||
public bool AnyBlock => Tripped.Count > 0 || Risk.EntriesBlocked || Risk.Multiplier < 1m || BotState != "active";
|
||||
|
||||
/// <summary>The switch tripped by itself in a world (SPEC 9.2): it waits for the user's restart, like "Ferma tutto".</summary>
|
||||
@@ -133,7 +159,10 @@ internal sealed record RiskView(
|
||||
|
||||
return new RiskView(bot, engine.StopRequested, (await engine.BotAsync(cancellationToken).ConfigureAwait(false)).CloseAll, world, risk, limits, rows, drawdown, scenarios,
|
||||
await engine.EventsAsync(8, cancellationToken).ConfigureAwait(false), next, last, await RiskSettings.PdtGuardAsync(services.Settings, cancellationToken).ConfigureAwait(false),
|
||||
positions.Count > 0, tripped);
|
||||
positions.Count > 0, tripped)
|
||||
{
|
||||
ProtectedRestart = await ProtectedRestartView.LoadAsync(services, cancellationToken).ConfigureAwait(false),
|
||||
};
|
||||
}
|
||||
|
||||
private static decimal? Worst(IReadOnlyList<IndexPoint> index, DateTimeOffset? from)
|
||||
|
||||
Reference in new issue
Block a user