Phase 10: new course and Docker only
Record the course the user chose on 2 December 2026 and make the container the only form of Anubis. - ADR 0021-0026: new roadmap (phases 10-24, readings per phase, the spec-to-ADR table, merge and tag only after the user's yes), Docker only, maths-only decisions, bans turned into limits on margin accounts, eToro Demo as currency venue and forward tests, strategy championship. ROADMAP rewritten from phase 10; STATE, CLAUDE.md, SVILUPPO, README, API-NOTES and the manuals without the desktop. - Remove the desktop: Anubis.Desktop, Anubis.Setup, deploy/windows, release-win and desktop-win, config.toml, PlatformKind, ANUBIS_PLATFORM, DPAPI with the ProtectedData package and the first-run wizard. Outside a container the server needs --data-dir, listens on 127.0.0.1 only and refuses foreign hosts; server and guard refuse --platform desktop with an Italian message and exit code 2. The demo keeps its key in a file and its error-page choices need no startup password. The diagnostics report says where the server runs from its own environment. - Lighter image: restore and publish for linux-x64 only, and leave out the Windows libraries ONNX Runtime copies anyway (829 MB to 410 MB on disk, /app from 282 MB to 42 MB). Rotating Docker logs in the Unraid template, the manual and the compose; backtest and learning run as one-shot commands. tasks dev uses artifacts/dev-data. refs #113 #114 #115 #78 #80 #81 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
3c57b3e84c
commit
e9ac6dccc9
95 files changed
+1426
-1604
No files matched your search
@@ -18,7 +18,7 @@ internal static class AccessCommand
|
||||
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);
|
||||
await output.WriteLineAsync("Uso: anubis access reset [--data-dir <cartella>, obbligatoria fuori dal container]").ConfigureAwait(false);
|
||||
return 2;
|
||||
}
|
||||
|
||||
|
||||
@@ -4,9 +4,9 @@
|
||||
<InvariantGlobalization>false</InvariantGlobalization>
|
||||
<!-- Static rendering only: no blazor.web.js, so no Microsoft.AspNetCore.App.Internal.Assets package (ADR 0007). -->
|
||||
<RequiresAspNetWebAssets>false</RequiresAspNetWebAssets>
|
||||
<!-- The Windows trial zip is published for win-x64 (tasks release-win). Declared here, the lock file also holds the
|
||||
native packages of that runtime (ONNX Runtime), so publishing never changes it. -->
|
||||
<RuntimeIdentifiers>win-x64</RuntimeIdentifiers>
|
||||
<!-- The image restores and publishes for linux-x64 only (ADR 0022): declared here, the lock file holds that runtime's
|
||||
native packages (ONNX Runtime, SQLite), so the locked restore for linux-x64 never changes it. -->
|
||||
<RuntimeIdentifiers>linux-x64</RuntimeIdentifiers>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Anubis\Anubis.csproj" />
|
||||
|
||||
@@ -18,9 +18,6 @@ public enum HostMode
|
||||
/// <summary>The startup configuration is missing or wrong: the error page lists what to fix.</summary>
|
||||
ConfigProblem,
|
||||
|
||||
/// <summary>Desktop without config.toml, or without a user yet: the first-run wizard.</summary>
|
||||
FirstRun,
|
||||
|
||||
/// <summary>The configured database does not answer: error page, retry, never another database (trap 20).</summary>
|
||||
DatabaseUnavailable,
|
||||
|
||||
@@ -79,13 +76,16 @@ internal sealed partial class AnubisHost(
|
||||
private volatile HostStatus _status = new(HostMode.Starting, null, null, clock.UtcNow, 0);
|
||||
private volatile AppServices? _services;
|
||||
|
||||
public StartupConfig Config { get; private set; } = initialConfig;
|
||||
public StartupConfig Config { get; } = initialConfig;
|
||||
|
||||
/// <summary>The channel to the guard that started this engine (SPEC 9.3); null without one.</summary>
|
||||
public GuardLink? Guard { get; init; }
|
||||
|
||||
public bool IsDemo => options.Demo;
|
||||
|
||||
/// <summary>Where this server answers from, in plain Italian: the container, the demo or a development run (ADR 0022).</summary>
|
||||
public string Where => options.Where;
|
||||
|
||||
public HostStatus Status => _status;
|
||||
|
||||
public IClock Clock => clock;
|
||||
@@ -93,15 +93,12 @@ internal sealed partial class AnubisHost(
|
||||
/// <summary>The running services; null until the first successful start.</summary>
|
||||
public AppServices? Services => _status.Mode == HostMode.Ready ? _services : null;
|
||||
|
||||
/// <summary>Desktop first run: the password chosen in the wizard, used once the database is ready.</summary>
|
||||
public string? PendingPassword { get; set; }
|
||||
|
||||
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>
|
||||
/// <summary>Asks the loop to check again now (after an error-page choice).</summary>
|
||||
public void Wake()
|
||||
{
|
||||
lock (_gate)
|
||||
@@ -302,18 +299,6 @@ internal sealed partial class AnubisHost(
|
||||
|
||||
private async Task StepAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
// Desktop: the wizard may have written config.toml, or the user fixed it by hand.
|
||||
if (Config.Platform == PlatformKind.Desktop && !options.Demo && !Config.IsComplete)
|
||||
{
|
||||
Config = options.LoadConfig(environment);
|
||||
}
|
||||
|
||||
if (Config.NeedsFirstRun)
|
||||
{
|
||||
SetStatus(HostMode.FirstRun, null);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!Config.IsComplete)
|
||||
{
|
||||
SetStatus(HostMode.ConfigProblem, null);
|
||||
@@ -406,11 +391,7 @@ internal sealed partial class AnubisHost(
|
||||
await DemoMode.SeedAsync(_db, Config.Data, clock, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (!await EnsureUserAsync(access, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
SetStatus(HostMode.FirstRun, null);
|
||||
return;
|
||||
}
|
||||
await EnsureUserAsync(access, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
var scheduler = new Scheduler(clock, bus);
|
||||
|
||||
@@ -530,34 +511,24 @@ internal sealed partial class AnubisHost(
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<bool> EnsureUserAsync(AccessStore access, CancellationToken cancellationToken)
|
||||
// The user is born from ANUBIS_ADMIN_PASSWORD, to be changed at the first access (ADR 0007, 0022). The loader
|
||||
// already made a missing or short password a problem of the configuration, so here it is always there.
|
||||
private async Task EnsureUserAsync(AccessStore access, CancellationToken cancellationToken)
|
||||
{
|
||||
if (await access.HasUserAsync(cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
return true;
|
||||
return;
|
||||
}
|
||||
|
||||
if (options.Demo)
|
||||
{
|
||||
// The demo signs in by itself (see SessionAuthentication); the password exists only to fill the table.
|
||||
await access.EnsureUserAsync(Ids.NewToken(), mustChange: false, cancellationToken).ConfigureAwait(false);
|
||||
return true;
|
||||
return;
|
||||
}
|
||||
|
||||
if (Config.Platform == PlatformKind.Docker && Config.AdminPassword is { } initial)
|
||||
{
|
||||
await access.EnsureUserAsync(initial, mustChange: true, cancellationToken).ConfigureAwait(false);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (PendingPassword is { } chosen)
|
||||
{
|
||||
await access.EnsureUserAsync(chosen, mustChange: false, cancellationToken).ConfigureAwait(false);
|
||||
PendingPassword = null;
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
var initial = Config.AdminPassword ?? throw new InvalidOperationException("ANUBIS_ADMIN_PASSWORD is checked by the loader.");
|
||||
await access.EnsureUserAsync(initial, mustChange: true, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// While running: the database is checked every few seconds. If it stops answering, the error page shows and the
|
||||
|
||||
@@ -262,14 +262,9 @@ h2 .note, h3 .note { font-weight: 400; letter-spacing: 0; }
|
||||
.form-inline label { min-width: 80px; font-weight: 550; }
|
||||
.row { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
|
||||
.row > div { display: flex; flex-direction: column; gap: 8px; }
|
||||
.choice { display: flex; gap: 10px; align-items: flex-start; font-weight: 400 !important; padding: 10px 12px; border: 1px solid var(--rule); border-radius: 10px; }
|
||||
.choice input { margin-top: 4px; }
|
||||
fieldset { border: 0; padding: 0; margin: 0; min-width: 0; }
|
||||
legend { display: flex; align-items: center; gap: 10px; font-size: 17px; font-weight: 650; margin-bottom: 8px; padding: 0; }
|
||||
.step { display: inline-flex; width: 26px; height: 26px; border-radius: 50%; background: var(--surface-2); align-items: center; justify-content: center; font-size: 14px; }
|
||||
.postgres-fields { display: flex; flex-direction: column; gap: 8px; margin-top: 4px; }
|
||||
.postgres-fields[hidden] { display: none; }
|
||||
.test-result:empty { display: none; }
|
||||
.steps { margin: 8px 0; padding-left: 20px; display: flex; flex-direction: column; gap: 6px; }
|
||||
.secret { background: var(--surface-2); padding: 2px 6px; border-radius: 6px; }
|
||||
.tabs { display: flex; gap: 16px; flex-wrap: wrap; }
|
||||
|
||||
@@ -37,32 +37,6 @@
|
||||
});
|
||||
});
|
||||
|
||||
// First run: PostgreSQL fields only when chosen; "Prova la connessione" without leaving the page.
|
||||
var wizard = document.querySelector("[data-wizard]");
|
||||
if (wizard) {
|
||||
var fields = wizard.querySelector("[data-postgres]");
|
||||
var engines = wizard.querySelectorAll("[data-engine]");
|
||||
var showFields = function () {
|
||||
if (!fields) { return; }
|
||||
var pg = wizard.querySelector("[data-engine]:checked");
|
||||
fields.hidden = !(pg && pg.value === "postgres");
|
||||
};
|
||||
engines.forEach(function (radio) { radio.addEventListener("change", showFields); });
|
||||
showFields();
|
||||
var test = wizard.querySelector("[data-test-connection]");
|
||||
var result = wizard.querySelector("[data-test-result]");
|
||||
if (test && result) {
|
||||
test.addEventListener("click", function (event) {
|
||||
event.preventDefault();
|
||||
result.textContent = "Provo…";
|
||||
fetch("/azioni/primo-avvio/prova", { method: "POST", body: new FormData(wizard), credentials: "same-origin" })
|
||||
.then(function (response) { return response.json(); })
|
||||
.then(function (answer) { result.textContent = answer.message; result.className = "test-result " + (answer.ok ? "gain" : "loss"); })
|
||||
.catch(function () { result.textContent = "Non riesco a fare la prova adesso. Riprova tra poco."; result.className = "test-result loss"; });
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Live status over the WebSocket: bot state, freshness of the data, and a discreet notice when the link drops.
|
||||
var age = document.querySelector("[data-live='age']");
|
||||
if (!age || !("WebSocket" in window)) { return; }
|
||||
|
||||
@@ -20,7 +20,7 @@ internal static class BacktestCommand
|
||||
{
|
||||
private const string Usage =
|
||||
"Uso: anubis backtest base|candidates [--to AAAA-MM-GG] [--out docs/backtests] [--offline]\n" +
|
||||
" --offline usa solo gli archivi già scaricati (i cambi BCE li scarica solo se mancano). Opzioni comuni: [--platform docker|desktop] [--data-dir <cartella>]";
|
||||
" --offline usa solo gli archivi già scaricati (i cambi BCE li scarica solo se mancano). Opzioni comuni: [--data-dir <cartella>, obbligatoria fuori dal container]";
|
||||
|
||||
public static async Task<int> RunAsync(string[] args, TextWriter? output = null, IReadOnlyDictionary<string, string?>? environment = null,
|
||||
HttpMessageHandler? handler = null)
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
@if (Docker)
|
||||
@inject AnubisHost Host
|
||||
@* The startup password is asked by the error-page choices, which anyone on the network can open (ADR 0022). The demo
|
||||
has no startup password and answers only this computer: there the choices go through without it. *@
|
||||
@if (!Host.IsDemo)
|
||||
{
|
||||
<label for="@_id">Password della configurazione d'avvio (<code>ANUBIS_ADMIN_PASSWORD</code>)</label>
|
||||
<input id="@_id" name="password" type="password" autocomplete="off" required />
|
||||
@@ -6,7 +9,4 @@
|
||||
|
||||
@code {
|
||||
private readonly string _id = "admin-" + Guid.NewGuid().ToString("N")[..6];
|
||||
|
||||
[Parameter]
|
||||
public bool Docker { get; set; }
|
||||
}
|
||||
@@ -1,13 +1,11 @@
|
||||
@inject AnubisHost Host
|
||||
@inject IClock Clock
|
||||
|
||||
@* SPEC 15.1: database and data folder disagree. The user chooses; Docker asks the startup password because users
|
||||
and sessions live in the database that is missing, desktop accepts choices only from the computer itself. *@
|
||||
@* SPEC 15.1: database and data folder disagree. The user chooses with the startup password (ANUBIS_ADMIN_PASSWORD),
|
||||
because users and sessions live in the database that is missing. *@
|
||||
@{
|
||||
var verdict = Status.Identity!.Verdict;
|
||||
var data = Host.Config.Data;
|
||||
var docker = Host.Config.Platform == PlatformKind.Docker;
|
||||
var canChoose = docker || Local;
|
||||
}
|
||||
|
||||
@switch (verdict)
|
||||
@@ -44,88 +42,78 @@
|
||||
|
||||
<p class="hint">La soluzione più sicura spesso è correggere la configurazione perché punti al database giusto. Altrimenti scegli qui sotto. Dopo un ripristino o un'importazione il bot riparte protetto: "Ferma tutto" acceso finché non confermi.</p>
|
||||
|
||||
@if (!canChoose)
|
||||
@if (verdict == IdentityVerdict.EmptyDatabase)
|
||||
{
|
||||
<p class="notice notice-attention" role="status"><Icon Name="lock" Size="16" />Queste scelte si fanno solo dal computer su cui gira Anubis.</p>
|
||||
var backups = new Backups(data, Clock).List();
|
||||
var imports = ServiceChoices.ImportFolders(data);
|
||||
<section class="service-section">
|
||||
<h2>Ripristina un salvataggio</h2>
|
||||
@if (backups.Count == 0)
|
||||
{
|
||||
<p class="hint">Nessun salvataggio nella cartella <code>@data.Backups</code>.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<form method="post" action="/azioni/servizio/ripristina" class="form">
|
||||
<AntiforgeryToken />
|
||||
<label for="salvataggio">Salvataggio</label>
|
||||
<select id="salvataggio" name="salvataggio">
|
||||
@foreach (var backup in backups)
|
||||
{
|
||||
<option value="@backup.Name">@Format.ShortDate(backup.TakenAt, Clock.UtcNow, Host.Config.TimeZone) · @backup.Reason</option>
|
||||
}
|
||||
</select>
|
||||
<AdminPassword />
|
||||
<button class="btn btn-primary" type="submit">Ripristina</button>
|
||||
</form>
|
||||
}
|
||||
</section>
|
||||
<section class="service-section">
|
||||
<h2>Importa un archivio</h2>
|
||||
@if (imports.Count == 0)
|
||||
{
|
||||
<p class="hint">Metti la cartella di un archivio esportato (con il suo <code>index.json</code>) dentro <code>@data.Import</code> e ricarica la pagina.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<form method="post" action="/azioni/servizio/importa" class="form">
|
||||
<AntiforgeryToken />
|
||||
<label for="archivio">Archivio</label>
|
||||
<select id="archivio" name="archivio">
|
||||
@foreach (var folder in imports)
|
||||
{
|
||||
<option value="@Path.GetFileName(folder)">@Path.GetFileName(folder)</option>
|
||||
}
|
||||
</select>
|
||||
<AdminPassword />
|
||||
<button class="btn btn-primary" type="submit">Importa</button>
|
||||
</form>
|
||||
}
|
||||
</section>
|
||||
<section class="service-section">
|
||||
<h2>Comincia da capo</h2>
|
||||
<p class="hint">Una nuova installazione in questo database vuoto. Il file d'identità della cartella viene messo da parte, non cancellato.</p>
|
||||
<form method="post" action="/azioni/servizio/da-capo" class="form">
|
||||
<AntiforgeryToken />
|
||||
<AdminPassword />
|
||||
<button class="btn btn-danger" type="submit" data-confirm="Cominciare da capo con un database vuoto? Lo storico precedente resta nei salvataggi.">Comincia da capo</button>
|
||||
</form>
|
||||
</section>
|
||||
}
|
||||
else
|
||||
{
|
||||
@if (verdict == IdentityVerdict.EmptyDatabase)
|
||||
{
|
||||
var backups = new Backups(data, Clock).List();
|
||||
var imports = ServiceChoices.ImportFolders(data);
|
||||
<section class="service-section">
|
||||
<h2>Ripristina un salvataggio</h2>
|
||||
@if (backups.Count == 0)
|
||||
{
|
||||
<p class="hint">Nessun salvataggio nella cartella <code>@data.Backups</code>.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<form method="post" action="/azioni/servizio/ripristina" class="form">
|
||||
<AntiforgeryToken />
|
||||
<label for="salvataggio">Salvataggio</label>
|
||||
<select id="salvataggio" name="salvataggio">
|
||||
@foreach (var backup in backups)
|
||||
{
|
||||
<option value="@backup.Name">@Format.ShortDate(backup.TakenAt, Clock.UtcNow, Host.Config.TimeZone) · @backup.Reason</option>
|
||||
}
|
||||
</select>
|
||||
<AdminPassword Docker="docker" />
|
||||
<button class="btn btn-primary" type="submit">Ripristina</button>
|
||||
</form>
|
||||
}
|
||||
</section>
|
||||
<section class="service-section">
|
||||
<h2>Importa un archivio</h2>
|
||||
@if (imports.Count == 0)
|
||||
{
|
||||
<p class="hint">Metti la cartella di un archivio esportato (con il suo <code>index.json</code>) dentro <code>@data.Import</code> e ricarica la pagina.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<form method="post" action="/azioni/servizio/importa" class="form">
|
||||
<AntiforgeryToken />
|
||||
<label for="archivio">Archivio</label>
|
||||
<select id="archivio" name="archivio">
|
||||
@foreach (var folder in imports)
|
||||
{
|
||||
<option value="@Path.GetFileName(folder)">@Path.GetFileName(folder)</option>
|
||||
}
|
||||
</select>
|
||||
<AdminPassword Docker="docker" />
|
||||
<button class="btn btn-primary" type="submit">Importa</button>
|
||||
</form>
|
||||
}
|
||||
</section>
|
||||
<section class="service-section">
|
||||
<h2>Comincia da capo</h2>
|
||||
<p class="hint">Una nuova installazione in questo database vuoto. Il file d'identità della cartella viene messo da parte, non cancellato.</p>
|
||||
<form method="post" action="/azioni/servizio/da-capo" class="form">
|
||||
<AntiforgeryToken />
|
||||
<AdminPassword Docker="docker" />
|
||||
<button class="btn btn-danger" type="submit" data-confirm="Cominciare da capo con un database vuoto? Lo storico precedente resta nei salvataggi.">Comincia da capo</button>
|
||||
</form>
|
||||
</section>
|
||||
}
|
||||
else
|
||||
{
|
||||
<section class="service-section">
|
||||
<h2>Usa comunque questo database</h2>
|
||||
<p class="hint">Diventa il database di questa installazione con una nuova impronta. Ogni altra copia non verrà più accettata. Il bot riparte protetto.</p>
|
||||
<form method="post" action="/azioni/servizio/usa-questo" class="form">
|
||||
<AntiforgeryToken />
|
||||
<AdminPassword Docker="docker" />
|
||||
<button class="btn btn-danger" type="submit" data-confirm="Usare questo database da ora in poi? Le altre copie non saranno più accettate.">Usa questo database</button>
|
||||
</form>
|
||||
</section>
|
||||
}
|
||||
<section class="service-section">
|
||||
<h2>Usa comunque questo database</h2>
|
||||
<p class="hint">Diventa il database di questa installazione con una nuova impronta. Ogni altra copia non verrà più accettata. Il bot riparte protetto.</p>
|
||||
<form method="post" action="/azioni/servizio/usa-questo" class="form">
|
||||
<AntiforgeryToken />
|
||||
<AdminPassword />
|
||||
<button class="btn btn-danger" type="submit" data-confirm="Usare questo database da ora in poi? Le altre copie non saranno più accettate.">Usa questo database</button>
|
||||
</form>
|
||||
</section>
|
||||
}
|
||||
|
||||
@code {
|
||||
[Parameter, EditorRequired]
|
||||
public HostStatus Status { get; set; } = null!;
|
||||
|
||||
[Parameter]
|
||||
public bool Local { get; set; }
|
||||
}
|
||||
@@ -597,23 +597,14 @@
|
||||
<section class="panel" id="sistema">
|
||||
<h2>Sistema</h2>
|
||||
<dl class="facts">
|
||||
<dt>Piattaforma</dt><dd>@(Host.Config.Platform == PlatformKind.Docker ? "Docker" : "Desktop (Windows)")</dd>
|
||||
<dt>Dove gira</dt><dd>@(Host.Where[..1].ToUpperInvariant() + Host.Where[1..])</dd>
|
||||
<dt>Database</dt><dd>@Host.Config.Db?.Describe()</dd>
|
||||
<dt>Cartella dei dati</dt><dd>@Host.Config.Data.Root</dd>
|
||||
<dt>Chiave dei segreti</dt><dd>@Host.Config.SecretKey.Description</dd>
|
||||
<dt>Fuso orario</dt><dd>@Host.Config.TimeZone.Id</dd>
|
||||
<dt>Versione</dt><dd>@AnubisInfo.Version</dd>
|
||||
</dl>
|
||||
<p class="hint">
|
||||
@if (Host.Config.Platform == PlatformKind.Docker)
|
||||
{
|
||||
@:Motore e connessione del database si cambiano solo nella configurazione del container.
|
||||
}
|
||||
else
|
||||
{
|
||||
@:Motore e connessione del database stanno in config.toml, nella cartella dei dati. Lo spostamento su un altro database arriva con l'applicazione desktop.
|
||||
}
|
||||
</p>
|
||||
<p class="hint">Motore e connessione del database si cambiano solo nella configurazione del container. Per passare a un altro database c'è l'esportazione e l'importazione: il manuale dice come.</p>
|
||||
|
||||
<h3>Salvataggi</h3>
|
||||
<p class="hint">Ogni notte alle 03:30 e prima di ogni aggiornamento dello schema. Tengo gli ultimi @Backups.Keep.</p>
|
||||
|
||||
@@ -1,83 +0,0 @@
|
||||
@page "/primo-avvio"
|
||||
@layout ServiceLayout
|
||||
@attribute [AllowAnonymous]
|
||||
@inject AnubisHost Host
|
||||
|
||||
<PageTitle>Primo avvio · Anubis</PageTitle>
|
||||
|
||||
<h1>Primo avvio</h1>
|
||||
@if (!_local)
|
||||
{
|
||||
<p class="notice notice-attention" role="alert"><Icon Name="lock" Size="16" />La prima configurazione si fa solo dal computer su cui gira Anubis.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<p>Due passi: dove tenere i dati e la password per entrare. Conti, capitale, Telegram e segnale di vita si aggiungono dopo, dalle Impostazioni: Telegram ha un pulsante che manda un messaggio di prova.</p>
|
||||
@if (Host.Config.Platform == Anubis.Platform.PlatformKind.Desktop)
|
||||
{
|
||||
<p class="hint">Su un computer di casa ti consiglio il segnale di vita (Impostazioni, sezione Telegram): un servizio esterno che ti avvisa quando il bot smette di chiamarlo. È l'unico modo per sapere che il bot è spento quando il computer è spento.</p>
|
||||
}
|
||||
@if (Message is { } message)
|
||||
{
|
||||
<p class="notice notice-loss" role="alert"><Icon Name="alert" Size="16" />@message</p>
|
||||
}
|
||||
|
||||
<form method="post" action="/azioni/primo-avvio" class="form" data-wizard>
|
||||
<AntiforgeryToken />
|
||||
@if (!Host.Config.IsComplete)
|
||||
{
|
||||
<fieldset class="service-section">
|
||||
<legend><span class="step">1</span>Database</legend>
|
||||
<label class="choice">
|
||||
<input type="radio" name="motore" value="sqlite" checked data-engine />
|
||||
<span><strong>SQLite</strong> (consigliato): un file nella cartella dei dati, niente da installare.</span>
|
||||
</label>
|
||||
<label class="choice">
|
||||
<input type="radio" name="motore" value="postgres" data-engine />
|
||||
<span><strong>PostgreSQL</strong>: un server che hai già, con un database dedicato e vuoto.</span>
|
||||
</label>
|
||||
<div class="postgres-fields" data-postgres>
|
||||
<label for="host">Indirizzo del server</label>
|
||||
<input id="host" name="host" autocomplete="off" placeholder="192.168.1.10" />
|
||||
<div class="row">
|
||||
<div><label for="porta">Porta</label><input id="porta" name="porta" inputmode="numeric" value="5432" /></div>
|
||||
<div><label for="nome">Nome del database</label><input id="nome" name="nome" value="anubis" /></div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div><label for="utente">Utente</label><input id="utente" name="utente" value="anubis" autocomplete="off" /></div>
|
||||
<div><label for="dbpassword">Password del database</label><input id="dbpassword" name="dbpassword" type="password" autocomplete="off" /></div>
|
||||
</div>
|
||||
<p class="hint">La password del database non va in <code>config.toml</code>: la custodisce Windows per il tuo utente.</p>
|
||||
<button class="btn" type="submit" formaction="/azioni/primo-avvio/prova" data-test-connection>Prova la connessione</button>
|
||||
<p class="test-result" data-test-result role="status"></p>
|
||||
</div>
|
||||
</fieldset>
|
||||
}
|
||||
<fieldset class="service-section">
|
||||
<legend><span class="step">@(Host.Config.IsComplete ? "1" : "2")</span>Password</legend>
|
||||
<p class="hint">Serve per entrare nell'interfaccia, anche da questo computer. Almeno @Passwords.MinimumLength caratteri.</p>
|
||||
<label for="password">Password</label>
|
||||
<input id="password" name="password" type="password" autocomplete="new-password" minlength="@Passwords.MinimumLength" required />
|
||||
<label for="conferma">Scrivila di nuovo</label>
|
||||
<input id="conferma" name="conferma" type="password" autocomplete="new-password" minlength="@Passwords.MinimumLength" required />
|
||||
</fieldset>
|
||||
<p class="hint">Anubis lavora solo quando il computer è acceso. Dopo un'assenza ricostruisce cosa è successo prima di riprendere.</p>
|
||||
<button class="btn btn-primary" type="submit">Crea l'installazione</button>
|
||||
</form>
|
||||
}
|
||||
|
||||
@code {
|
||||
private bool _local;
|
||||
|
||||
[CascadingParameter]
|
||||
public HttpContext? HttpContext { get; set; }
|
||||
|
||||
[SupplyParameterFromQuery(Name = "errore")]
|
||||
public string? Errore { get; set; }
|
||||
|
||||
protected override void OnInitialized() => _local = HttpContext is not null && CurrentUser.IsLocal(HttpContext);
|
||||
|
||||
private string? Message => Errore == "database"
|
||||
? "Non riesco a collegarmi al database con questi dati. Controlla indirizzo, porta, nome, utente e password, poi riprova."
|
||||
: PasswordMessages.For(Errore);
|
||||
}
|
||||
@@ -30,14 +30,7 @@
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
@if (Host.Config.Platform == PlatformKind.Docker)
|
||||
{
|
||||
<p class="hint">Le variabili si cambiano nella configurazione del container (su Unraid, nei campi del modello), poi si riavvia il container.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<p class="hint">Il file è <code>@Host.Config.Data.ConfigFile</code>. Appena lo correggi riprovo da solo.</p>
|
||||
}
|
||||
<p class="hint">Le variabili si cambiano nella configurazione del container (su Unraid, nei campi del modello), poi si riavvia il container.</p>
|
||||
break;
|
||||
|
||||
case HostMode.DatabaseUnavailable:
|
||||
@@ -74,25 +67,18 @@
|
||||
<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>
|
||||
}
|
||||
<form method="post" action="/azioni/servizio/riprova" class="form">
|
||||
<AntiforgeryToken />
|
||||
<AdminPassword />
|
||||
<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;
|
||||
|
||||
case HostMode.IdentityProblem:
|
||||
<IdentityChoices Status="_status" Local="_local" />
|
||||
break;
|
||||
|
||||
case HostMode.FirstRun:
|
||||
<p><a href="/primo-avvio">Apri la procedura di primo avvio</a>.</p>
|
||||
<IdentityChoices Status="_status" />
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -100,7 +86,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.",
|
||||
"password" => "Password della configurazione d'avvio (ANUBIS_ADMIN_PASSWORD) sbagliata.",
|
||||
"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.",
|
||||
@@ -110,7 +96,6 @@
|
||||
@code {
|
||||
private HostStatus _status = null!;
|
||||
private bool _refresh;
|
||||
private bool _local;
|
||||
|
||||
[CascadingParameter]
|
||||
public HttpContext? HttpContext { get; set; }
|
||||
@@ -124,7 +109,6 @@
|
||||
_refresh = _status.Mode is HostMode.Starting or HostMode.DatabaseUnavailable or HostMode.ConfigProblem;
|
||||
if (HttpContext is not null)
|
||||
{
|
||||
_local = CurrentUser.IsLocal(HttpContext);
|
||||
if (!HttpContext.Response.HasStarted)
|
||||
{
|
||||
HttpContext.Response.StatusCode = StatusCodes.Status503ServiceUnavailable;
|
||||
|
||||
@@ -7,7 +7,6 @@ internal static class ServiceText
|
||||
{
|
||||
HostMode.Starting => "Anubis si sta avviando",
|
||||
HostMode.ConfigProblem => "Manca qualcosa nella configurazione d'avvio",
|
||||
HostMode.FirstRun => "Anubis va configurato",
|
||||
HostMode.DatabaseUnavailable => "Il database non risponde",
|
||||
HostMode.SchemaProblem => "Il database non è compatibile con questa versione",
|
||||
HostMode.IdentityProblem => "Il database non è quello di questa installazione",
|
||||
|
||||
@@ -17,7 +17,7 @@ internal static class DataCommand
|
||||
"Uso: anubis data report [--days N] [--out file.md]\n" +
|
||||
" anubis data binance <SIMBOLO> <1d|1m> <AAAA-MM> (per esempio BTCUSDT 1d 2017-08)\n" +
|
||||
" anubis data csv <file.csv> (colonne descritte in file.mapping.json o mapping.json)\n" +
|
||||
"Opzioni comuni: [--platform docker|desktop] [--data-dir <cartella>]";
|
||||
"Opzioni comuni: [--data-dir <cartella>, obbligatoria fuori dal container]";
|
||||
|
||||
public static async Task<int> RunAsync(string[] args, TextWriter? output = null, IReadOnlyDictionary<string, string?>? environment = null,
|
||||
HttpMessageHandler? handler = null)
|
||||
|
||||
@@ -17,7 +17,7 @@ internal static class DatabaseCommand
|
||||
output ??= Console.Out;
|
||||
if (args.Length < 2 || args[0] is not ("export" or "import"))
|
||||
{
|
||||
await output.WriteLineAsync("Uso: anubis db export <cartella> | anubis db import <cartella> [--platform docker|desktop] [--data-dir <cartella>]").ConfigureAwait(false);
|
||||
await output.WriteLineAsync("Uso: anubis db export <cartella> | anubis db import <cartella> [--data-dir <cartella>, obbligatoria fuori dal container]").ConfigureAwait(false);
|
||||
return 2;
|
||||
}
|
||||
|
||||
|
||||
@@ -46,10 +46,10 @@ internal static class DiagnosticsExport
|
||||
{
|
||||
var lines = new List<KeyValuePair<string, string>>
|
||||
{
|
||||
new("Piattaforma", config.Platform.ToString().ToLowerInvariant()),
|
||||
new("Dove gira", DataDirectory.InContainer(environment) ? "container" : "fuori dal container, per sviluppo e prove"),
|
||||
new("Database", config.Db?.Describe() ?? "non configurato"),
|
||||
new("Cartella dei dati", config.Data.Root),
|
||||
new("Raggiungibile da altri computer", config.AllowNetwork ? "sì" : "no"),
|
||||
new("In ascolto su", DataDirectory.InContainer(environment) ? "tutte le interfacce del container" : "solo questo computer (127.0.0.1)"),
|
||||
new("Ordini reali consentiti", config.AllowLive ? "sì" : "no"),
|
||||
};
|
||||
var variables = environment
|
||||
@@ -71,14 +71,14 @@ internal static class DiagnosticsExport
|
||||
|
||||
/// <summary>
|
||||
/// "anubis diagnostics": the report to paste back after a long run of a release (issue #95, ADR 0013). It only reads,
|
||||
/// so it runs while the bot works: in Docker with <c>docker exec</c>, on desktop from a second terminal.
|
||||
/// so it runs while the bot works: in the container with <c>docker exec</c>.
|
||||
/// </summary>
|
||||
internal static class DiagnosticsCommand
|
||||
{
|
||||
private const string Usage =
|
||||
"Uso: anubis diagnostics [--hours 72] [--from AAAA-MM-GGTHH:MMZ] [--to AAAA-MM-GGTHH:MMZ] [--out file.md]\n" +
|
||||
" senza --hours né --from copre tutto ciò che è stato raccolto (al massimo 30 giorni).\n" +
|
||||
"Opzioni comuni: [--platform docker|desktop] [--data-dir <cartella>]";
|
||||
"Opzioni comuni: [--data-dir <cartella>, obbligatoria fuori dal container]";
|
||||
|
||||
/// <summary>0 when the report was made, 1 when it could not be, 2 for the usage.</summary>
|
||||
public static async Task<int> RunAsync(string[] args, TextWriter? output = null, IReadOnlyDictionary<string, string?>? environment = null, IClock? clock = null)
|
||||
|
||||
@@ -9,6 +9,7 @@ using Anubis.Data;
|
||||
using Anubis.Db;
|
||||
using Anubis.Platform;
|
||||
using Microsoft.AspNetCore.Antiforgery;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Anubis.Server;
|
||||
|
||||
@@ -229,10 +230,12 @@ internal static partial class Endpoints
|
||||
});
|
||||
|
||||
// The data collected for the analysis of a long run, as one Markdown report to paste (issue #95, ADR 0013).
|
||||
api.MapGet("/diagnostica.md", async (AnubisHost host, ShellData shell, IClock clock, double? ore, CancellationToken ct) =>
|
||||
// The environment the server started with (the tests' own, when they give one): "where it runs" is the server's.
|
||||
api.MapGet("/diagnostica.md", async (AnubisHost host, ShellData shell, IClock clock, [FromServices] IReadOnlyDictionary<string, string?> environment,
|
||||
double? ore, CancellationToken ct) =>
|
||||
{
|
||||
var now = clock.UtcNow;
|
||||
var text = await DiagnosticsExport.BuildAsync(host.Services!.Db, host.Config, DiagnosticsExport.ProcessEnvironment(), now, ore, null, null, ct).ConfigureAwait(false);
|
||||
var text = await DiagnosticsExport.BuildAsync(host.Services!.Db, host.Config, environment, now, ore, null, null, ct).ConfigureAwait(false);
|
||||
var day = TimeZoneInfo.ConvertTime(now, shell.Zone).ToString("yyyy-MM-dd-HHmm", System.Globalization.CultureInfo.InvariantCulture);
|
||||
return Results.File(System.Text.Encoding.UTF8.GetBytes(text), "text/markdown; charset=utf-8", $"anubis-diagnostica-{day}.md");
|
||||
});
|
||||
|
||||
+12
-132
@@ -15,8 +15,6 @@ internal static partial class Forms
|
||||
{
|
||||
var open = app.MapGroup("/azioni").AllowAnonymous();
|
||||
open.MapPost("/accesso", SignInAsync);
|
||||
open.MapPost("/primo-avvio/prova", TestDatabaseAsync);
|
||||
open.MapPost("/primo-avvio", FirstRunAsync);
|
||||
open.MapPost("/servizio/{choice}", ServiceChoiceAsync);
|
||||
|
||||
var signed = app.MapGroup("/azioni").RequireAuthorization();
|
||||
@@ -1011,144 +1009,29 @@ internal static partial class Forms
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Desktop first run (SPEC 15.6): only from the computer itself, only while the wizard is due. ----
|
||||
|
||||
private static DbSettings ReadDatabase(IFormCollection form, StartupConfig config)
|
||||
{
|
||||
if (form["motore"].ToString() != "postgres")
|
||||
{
|
||||
return new DbSettings { Engine = DbEngine.Sqlite, SqlitePath = config.Data.SqliteFile };
|
||||
}
|
||||
|
||||
return new DbSettings
|
||||
{
|
||||
Engine = DbEngine.Postgres,
|
||||
Host = form["host"].ToString().Trim(),
|
||||
Port = int.TryParse(form["porta"].ToString(), out var port) && port is > 0 and < 65536 ? port : 5432,
|
||||
Database = string.IsNullOrWhiteSpace(form["nome"]) ? "anubis" : form["nome"].ToString().Trim(),
|
||||
User = string.IsNullOrWhiteSpace(form["utente"]) ? "anubis" : form["utente"].ToString().Trim(),
|
||||
Password = form["dbpassword"].ToString(),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Opens the database without creating anything and asks it one question.</summary>
|
||||
private static async Task<string?> TryConnectAsync(DbSettings settings, CancellationToken ct)
|
||||
{
|
||||
if (settings.Engine == DbEngine.Postgres && string.IsNullOrWhiteSpace(settings.Host))
|
||||
{
|
||||
return "Manca l'indirizzo del server PostgreSQL.";
|
||||
}
|
||||
|
||||
Redactor.Register(settings.Password);
|
||||
try
|
||||
{
|
||||
await using var db = Database.Open(settings, allowCreate: settings.Engine == DbEngine.Sqlite);
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(8));
|
||||
await db.PingAsync(timeout.Token).ConfigureAwait(false);
|
||||
return null;
|
||||
}
|
||||
catch (Exception ex) when (!ct.IsCancellationRequested)
|
||||
{
|
||||
return Redactor.Redact(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
private static bool WizardAllowed(AnubisHost host, HttpContext context) =>
|
||||
host.Status.Mode == HostMode.FirstRun && host.Config.Platform == PlatformKind.Desktop && CurrentUser.IsLocal(context);
|
||||
|
||||
private static async Task<IResult> TestDatabaseAsync(IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
|
||||
{
|
||||
if (!WizardAllowed(host, context))
|
||||
{
|
||||
return Endpoints.Error(StatusCodes.Status403Forbidden, "non_ammesso", "La procedura guidata si usa solo dal computer su cui gira Anubis, al primo avvio.");
|
||||
}
|
||||
|
||||
var problem = await TryConnectAsync(ReadDatabase(form, host.Config), ct).ConfigureAwait(false);
|
||||
return Results.Json(new { ok = problem is null, message = problem ?? "Connessione riuscita." });
|
||||
}
|
||||
|
||||
private static async Task<IResult> FirstRunAsync(IFormCollection form, AnubisHost host, HttpContext context, ILogger<AnubisHost> logger, CancellationToken ct)
|
||||
{
|
||||
if (!WizardAllowed(host, context))
|
||||
{
|
||||
return Results.Redirect("/");
|
||||
}
|
||||
|
||||
var password = form["password"].ToString();
|
||||
if (password != form["conferma"].ToString())
|
||||
{
|
||||
return Results.Redirect("/primo-avvio?errore=diverse");
|
||||
}
|
||||
|
||||
if (Passwords.Problem(password) is not null)
|
||||
{
|
||||
return Results.Redirect("/primo-avvio?errore=corta");
|
||||
}
|
||||
|
||||
var config = host.Config;
|
||||
if (!config.IsComplete)
|
||||
{
|
||||
var settings = ReadDatabase(form, config);
|
||||
if (await TryConnectAsync(settings, ct).ConfigureAwait(false) is not null)
|
||||
{
|
||||
return Results.Redirect("/primo-avvio?errore=database");
|
||||
}
|
||||
|
||||
// config.toml without the database password: that goes to the protected store (SPEC 15.6).
|
||||
DesktopPlatform.WriteConfig(config.Data, ProtectedSecretKey.DefaultStore(config.Data), settings, config.Port, allowNetwork: false);
|
||||
}
|
||||
|
||||
host.PendingPassword = password;
|
||||
host.Wake();
|
||||
try
|
||||
{
|
||||
await host.WaitForAsync(HostMode.Ready, TimeSpan.FromSeconds(60)).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
LogFirstRunSlow(logger);
|
||||
return Results.Redirect("/");
|
||||
}
|
||||
|
||||
var (result, token) = await host.Services!.Access.SignInAsync(password, null, context.Request.Headers.UserAgent.ToString(),
|
||||
context.Connection.RemoteIpAddress?.ToString(), ct).ConfigureAwait(false);
|
||||
if (result == LoginResult.Ok)
|
||||
{
|
||||
SessionAuthentication.WriteCookie(context, token!);
|
||||
}
|
||||
|
||||
return Results.Redirect("/");
|
||||
}
|
||||
|
||||
// ---- Choices of the error page (SPEC 15.1): Docker asks the startup password, desktop only the computer itself. ----
|
||||
// ---- Choices of the error page (SPEC 15.1): the startup password, with the sign-in attempt limit (ADR 0022). ----
|
||||
|
||||
private static async Task<IResult> ServiceChoiceAsync(string choice, IFormCollection form, AnubisHost host, IClock clock, LoginLimiter limiter,
|
||||
HttpContext context, ILogger<AnubisHost> logger, CancellationToken ct)
|
||||
{
|
||||
var config = host.Config;
|
||||
if (config.Platform == PlatformKind.Docker)
|
||||
|
||||
// The startup password, asked by a page anyone on the network can open: same attempt limit as the sign-in. The
|
||||
// demo has none and answers only this computer (ServerApp.LocalOnly): its choices need no password.
|
||||
var address = context.Connection.RemoteIpAddress?.ToString() ?? "sconosciuto";
|
||||
if (limiter.Begin(address) > TimeSpan.Zero)
|
||||
{
|
||||
// The startup password, asked by a page anyone on the network can open: same attempt limit as the sign-in.
|
||||
var address = context.Connection.RemoteIpAddress?.ToString() ?? "sconosciuto";
|
||||
if (limiter.Begin(address) > TimeSpan.Zero)
|
||||
{
|
||||
return Results.Redirect("/?errore=attesa");
|
||||
}
|
||||
|
||||
if (!Endpoints.SameSecret(form["password"].ToString(), config.AdminPassword))
|
||||
{
|
||||
LogChoiceRefused(logger, choice);
|
||||
return Results.Redirect("/?errore=password");
|
||||
}
|
||||
|
||||
limiter.Succeeded(address);
|
||||
return Results.Redirect("/?errore=attesa");
|
||||
}
|
||||
else if (!CurrentUser.IsLocal(context))
|
||||
|
||||
if (!host.IsDemo && !Endpoints.SameSecret(form["password"].ToString(), config.AdminPassword))
|
||||
{
|
||||
LogChoiceRefused(logger, choice);
|
||||
return Results.Redirect("/?errore=password");
|
||||
}
|
||||
|
||||
limiter.Succeeded(address);
|
||||
|
||||
// The startup loop stays still until the choice is done and the installation renewed.
|
||||
using var exclusive = await host.ExclusiveAsync(ct).ConfigureAwait(false);
|
||||
var status = host.Status;
|
||||
@@ -1252,9 +1135,6 @@ internal static partial class Forms
|
||||
[LoggerMessage(Level = LogLevel.Error, Message = "Backup on request failed")]
|
||||
private static partial void LogBackupFailed(ILogger logger, Exception exception);
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Warning, Message = "First run: the application is not ready after 60 seconds")]
|
||||
private static partial void LogFirstRunSlow(ILogger logger);
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Warning, Message = "Error page choice {Choice} confirmed")]
|
||||
private static partial void LogChoice(ILogger logger, string choice);
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ internal static class LearningCommand
|
||||
{
|
||||
private const string Usage =
|
||||
"Uso: anubis learning base [--to AAAA-MM-GG] [--out docs/learning]\n" +
|
||||
" Usa gli storici già scaricati da 'anubis backtest base', senza rete. Opzioni comuni: [--platform docker|desktop] [--data-dir <cartella>]";
|
||||
" Usa gli storici già scaricati da 'anubis backtest base', senza rete. Opzioni comuni: [--data-dir <cartella>, obbligatoria fuori dal container]";
|
||||
|
||||
public static async Task<int> RunAsync(string[] args, TextWriter? output = null, IReadOnlyDictionary<string, string?>? environment = null)
|
||||
{
|
||||
|
||||
@@ -1,47 +1,62 @@
|
||||
using Anubis.Platform;
|
||||
using Anubis.Server;
|
||||
|
||||
// "anubis db export <folder>" and "anubis db import <folder>" (SPEC 5.4) run with the engine stopped; anything else starts the server.
|
||||
if (args.Length >= 1 && args[0] == "db")
|
||||
try
|
||||
{
|
||||
return await DatabaseCommand.RunAsync(args[1..]).ConfigureAwait(false);
|
||||
return await RunAsync(args).ConfigureAwait(false);
|
||||
}
|
||||
catch (StartupRefusedException refused)
|
||||
{
|
||||
// --platform desktop, or no data folder outside a container (ADR 0022): said in Italian, without a stack trace.
|
||||
await Console.Error.WriteLineAsync(refused.Message).ConfigureAwait(false);
|
||||
return 2;
|
||||
}
|
||||
|
||||
// "anubis access reset": a new password for whoever holds the computer, the second factor off (RUNBOOK).
|
||||
if (args.Length >= 1 && args[0] == "access")
|
||||
static async Task<int> RunAsync(string[] args)
|
||||
{
|
||||
return await AccessCommand.RunAsync(args[1..]).ConfigureAwait(false);
|
||||
}
|
||||
// "anubis db export <folder>" and "anubis db import <folder>" (SPEC 5.4) run with the engine stopped; anything else starts the server.
|
||||
if (args.Length >= 1 && args[0] == "db")
|
||||
{
|
||||
return await DatabaseCommand.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")
|
||||
{
|
||||
return await DataCommand.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 backtest base": the honest backtests of the base strategies, written to docs/backtests (Phase 5).
|
||||
if (args.Length >= 1 && args[0] == "backtest")
|
||||
{
|
||||
return await BacktestCommand.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")
|
||||
{
|
||||
return await DataCommand.RunAsync(args[1..]).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// "anubis learning base": the first model and its validation report, written to docs/learning (Phase 8).
|
||||
if (args.Length >= 1 && args[0] == "learning")
|
||||
{
|
||||
return await LearningCommand.RunAsync(args[1..]).ConfigureAwait(false);
|
||||
}
|
||||
// "anubis backtest base": the honest backtests of the base strategies, written to docs/backtests (Phase 5).
|
||||
if (args.Length >= 1 && args[0] == "backtest")
|
||||
{
|
||||
return await BacktestCommand.RunAsync(args[1..]).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// "anubis soak": the report of the endurance run in real time, read from the bot's records while it works (Phase 6).
|
||||
if (args.Length >= 1 && args[0] == "soak")
|
||||
{
|
||||
return await SoakCommand.RunAsync(args[1..]).ConfigureAwait(false);
|
||||
}
|
||||
// "anubis learning base": the first model and its validation report, written to docs/learning (Phase 8).
|
||||
if (args.Length >= 1 && args[0] == "learning")
|
||||
{
|
||||
return await LearningCommand.RunAsync(args[1..]).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// "anubis diagnostics": the data collected for the analysis of a long run, as one report to paste (issue #95).
|
||||
if (args.Length >= 1 && args[0] == "diagnostics")
|
||||
{
|
||||
return await DiagnosticsCommand.RunAsync(args[1..]).ConfigureAwait(false);
|
||||
}
|
||||
// "anubis soak": the report of the endurance run in real time, read from the bot's records while it works (Phase 6).
|
||||
if (args.Length >= 1 && args[0] == "soak")
|
||||
{
|
||||
return await SoakCommand.RunAsync(args[1..]).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var app = ServerApp.Build(args);
|
||||
await app.RunAsync().ConfigureAwait(false);
|
||||
return 0;
|
||||
// "anubis diagnostics": the data collected for the analysis of a long run, as one report to paste (issue #95).
|
||||
if (args.Length >= 1 && args[0] == "diagnostics")
|
||||
{
|
||||
return await DiagnosticsCommand.RunAsync(args[1..]).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var app = ServerApp.Build(args);
|
||||
await app.RunAsync().ConfigureAwait(false);
|
||||
return 0;
|
||||
}
|
||||
@@ -32,9 +32,8 @@ internal static class ServerApp
|
||||
|
||||
if (!options.AspNetArgs.Any(a => a.StartsWith("--urls", StringComparison.Ordinal)))
|
||||
{
|
||||
// Desktop and demo listen only on the computer itself unless the user allowed the home network (SPEC 15.6).
|
||||
var local = options.Demo || (config.Platform == PlatformKind.Desktop && !config.AllowNetwork);
|
||||
builder.WebHost.UseUrls((local ? "http://127.0.0.1:" : "http://0.0.0.0:") + config.Port.ToString(System.Globalization.CultureInfo.InvariantCulture));
|
||||
// Outside a container (development, tests, demo) only the computer itself; the container on every interface (ADR 0022).
|
||||
builder.WebHost.UseUrls((options.LocalOnly ? "http://127.0.0.1:" : "http://0.0.0.0:") + config.Port.ToString(System.Globalization.CultureInfo.InvariantCulture));
|
||||
}
|
||||
|
||||
builder.WebHost.ConfigureKestrel(k =>
|
||||
@@ -104,7 +103,7 @@ internal static class ServerApp
|
||||
}
|
||||
|
||||
app.Use(SecurityHeaders);
|
||||
app.Use((context, next) => LocalOnly(context, next, options, config));
|
||||
app.Use((context, next) => LocalOnly(context, next, options));
|
||||
app.Use((context, next) => Gate.InvokeAsync(context, next, host));
|
||||
app.UseWebSockets(new WebSocketOptions { KeepAliveInterval = TimeSpan.FromSeconds(20) });
|
||||
app.UseRouting();
|
||||
@@ -162,14 +161,13 @@ internal static class ServerApp
|
||||
return next();
|
||||
}
|
||||
|
||||
// Defence in depth: even if someone binds the server to every address, desktop and demo answer only the computer itself.
|
||||
private static Task LocalOnly(HttpContext context, Func<Task> next, ServerOptions options, StartupConfig config)
|
||||
// Defence in depth: even if someone binds the server to every address, outside a container it answers only the computer itself.
|
||||
private static Task LocalOnly(HttpContext context, Func<Task> next, ServerOptions options)
|
||||
{
|
||||
var localOnly = options.Demo || (config.Platform == PlatformKind.Desktop && !config.AllowNetwork);
|
||||
if (localOnly && !CurrentUser.IsLocal(context))
|
||||
if (options.LocalOnly && !CurrentUser.IsLocal(context))
|
||||
{
|
||||
context.Response.StatusCode = StatusCodes.Status403Forbidden;
|
||||
return context.Response.WriteAsync("Anubis risponde solo dal computer su cui gira.");
|
||||
return context.Response.WriteAsync("Fuori dal container Anubis risponde solo da questo computer (sviluppo, prove, modalità dimostrativa).");
|
||||
}
|
||||
|
||||
return next();
|
||||
@@ -202,7 +200,7 @@ internal static class ServerApp
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// While the application is not ready, every page is the service page (error, first run): the engine does not start
|
||||
/// While the application is not ready, every page is the service page (the error page): the engine does not start
|
||||
/// and no other database is ever opened (SPEC 15.1). Health, logo and style always answer.
|
||||
/// </summary>
|
||||
internal static class Gate
|
||||
@@ -223,7 +221,7 @@ internal static class Gate
|
||||
|
||||
if (mode == HostMode.Ready)
|
||||
{
|
||||
if (path.StartsWithSegments("/servizio", StringComparison.Ordinal) || path.StartsWithSegments("/primo-avvio", StringComparison.Ordinal))
|
||||
if (path.StartsWithSegments("/servizio", StringComparison.Ordinal))
|
||||
{
|
||||
context.Response.Redirect("/");
|
||||
return;
|
||||
@@ -234,21 +232,7 @@ internal static class Gate
|
||||
}
|
||||
|
||||
var api = SessionAuthentication.IsApi(context.Request);
|
||||
if (mode == HostMode.FirstRun)
|
||||
{
|
||||
if (path.StartsWithSegments("/primo-avvio", StringComparison.Ordinal) || path.StartsWithSegments("/azioni/primo-avvio", StringComparison.Ordinal))
|
||||
{
|
||||
await next().ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!api && HttpMethods.IsGet(context.Request.Method))
|
||||
{
|
||||
context.Response.Redirect("/primo-avvio");
|
||||
return;
|
||||
}
|
||||
}
|
||||
else if (path.StartsWithSegments("/azioni/servizio", StringComparison.Ordinal))
|
||||
if (path.StartsWithSegments("/azioni/servizio", StringComparison.Ordinal))
|
||||
{
|
||||
await next().ConfigureAwait(false);
|
||||
return;
|
||||
|
||||
@@ -4,23 +4,26 @@ using Anubis.Platform;
|
||||
namespace Anubis.Server;
|
||||
|
||||
/// <summary>
|
||||
/// What the server process was asked to be, from its arguments and environment: Docker or desktop, which data
|
||||
/// folder, demo mode. Tests pass a fake environment and clock through <see cref="ServerOverrides"/>.
|
||||
/// What the server process was asked to be, from its arguments and environment: which data folder, demo mode, and
|
||||
/// whether it runs inside a container. Outside a container Anubis runs only for development, tests and the demo,
|
||||
/// with the data folder given by hand and answering only the computer itself (ADR 0022). Tests pass a fake
|
||||
/// environment and clock through <see cref="ServerOverrides"/>.
|
||||
/// </summary>
|
||||
internal sealed record ServerOptions(PlatformKind Platform, string? DataDir, bool Demo, string[] AspNetArgs)
|
||||
internal sealed record ServerOptions(string? DataDir, bool Demo, bool InContainer, string[] AspNetArgs)
|
||||
{
|
||||
public static ServerOptions Parse(string[] args, IReadOnlyDictionary<string, string?> environment)
|
||||
{
|
||||
DataDirectory.RefuseOtherPlatforms(args);
|
||||
var rest = new List<string>();
|
||||
PlatformKind? platform = null;
|
||||
string? dataDir = null;
|
||||
var demo = false;
|
||||
for (var i = 0; i < args.Length; i++)
|
||||
{
|
||||
switch (args[i])
|
||||
{
|
||||
// Only "docker" gets here (RefuseOtherPlatforms): accepted and ignored.
|
||||
case "--platform" when i + 1 < args.Length:
|
||||
platform = args[++i].Equals("docker", StringComparison.OrdinalIgnoreCase) ? PlatformKind.Docker : PlatformKind.Desktop;
|
||||
i++;
|
||||
break;
|
||||
case "--data-dir" when i + 1 < args.Length:
|
||||
dataDir = Path.GetFullPath(args[++i]);
|
||||
@@ -34,26 +37,21 @@ internal sealed record ServerOptions(PlatformKind Platform, string? DataDir, boo
|
||||
}
|
||||
}
|
||||
|
||||
platform ??= (environment.GetValueOrDefault("ANUBIS_PLATFORM") ?? "").ToLowerInvariant() switch
|
||||
{
|
||||
"docker" => PlatformKind.Docker,
|
||||
"desktop" => PlatformKind.Desktop,
|
||||
_ => environment.GetValueOrDefault("DOTNET_RUNNING_IN_CONTAINER") == "true" ? PlatformKind.Docker : PlatformKind.Desktop,
|
||||
};
|
||||
return new ServerOptions(platform.Value, dataDir, demo, [.. rest]);
|
||||
return new ServerOptions(dataDir, demo, DataDirectory.InContainer(environment), [.. rest]);
|
||||
}
|
||||
|
||||
/// <summary>Reads the startup configuration of the chosen platform.</summary>
|
||||
public StartupConfig LoadConfig(IReadOnlyDictionary<string, string?> environment)
|
||||
{
|
||||
if (Platform == PlatformKind.Docker)
|
||||
{
|
||||
return DockerPlatform.Load(environment, DataDir ?? "/data");
|
||||
}
|
||||
/// <summary>
|
||||
/// Where this server answers from, in plain Italian, for Settings and the diary: the container, the demo or a
|
||||
/// development run on the computer itself.
|
||||
/// </summary>
|
||||
public string Where => Demo ? "modalità dimostrativa" : InContainer ? "container Docker" : "fuori dal container, per sviluppo e prove";
|
||||
|
||||
var data = DataDir is null ? DataDirectory.ForCurrentUser() : new DataDirectory(DataDir);
|
||||
return DesktopPlatform.Load(data, ProtectedSecretKey.DefaultStore(data));
|
||||
}
|
||||
/// <summary>Outside a container (development, tests, demo) the server listens and answers only on the computer itself.</summary>
|
||||
public bool LocalOnly => Demo || !InContainer;
|
||||
|
||||
/// <summary>Reads the startup configuration from the environment; outside a container only with <c>--data-dir</c>.</summary>
|
||||
public StartupConfig LoadConfig(IReadOnlyDictionary<string, string?> environment) =>
|
||||
DockerPlatform.Load(environment, DataDirectory.Locate(DataDir, environment));
|
||||
}
|
||||
|
||||
/// <summary>Test hooks: a fake environment, a manual clock, a cheaper password hash.</summary>
|
||||
|
||||
@@ -100,6 +100,4 @@ internal sealed class ShellData(AnubisHost host, IClock clock)
|
||||
|
||||
/// <summary>The aggregates of appendix F; only in demo mode (SPEC 13.1).</summary>
|
||||
public JsonDocument? Aggregates() => host.IsDemo ? DemoMode.ReadAggregates(host.Config.Data) : null;
|
||||
|
||||
public PlatformKind Platform => host.Config.Platform;
|
||||
}
|
||||
@@ -8,14 +8,14 @@ namespace Anubis.Server;
|
||||
|
||||
/// <summary>
|
||||
/// "anubis soak": the report of an endurance run in real time (SPEC 17, phase 6) from the bot's own records. It only
|
||||
/// reads, so it can run while the bot works: in Docker with <c>docker exec</c>, on desktop from a second terminal.
|
||||
/// reads, so it can run while the bot works: in the container with <c>docker exec</c>.
|
||||
/// </summary>
|
||||
internal static class SoakCommand
|
||||
{
|
||||
private const string Usage =
|
||||
"Uso: anubis soak [--from AAAA-MM-GGTHH:MMZ] [--to AAAA-MM-GGTHH:MMZ] [--hours 48] [--out file.md]\n" +
|
||||
" senza --from la prova è delle ultime --hours ore fino a --to (o adesso).\n" +
|
||||
"Opzioni comuni: [--platform docker|desktop] [--data-dir <cartella>]";
|
||||
"Opzioni comuni: [--data-dir <cartella>, obbligatoria fuori dal container]";
|
||||
|
||||
/// <summary>0 when the run is in order, 4 when something must be looked at, 1 when the report could not be made.</summary>
|
||||
public static async Task<int> RunAsync(string[] args, TextWriter? output = null, IReadOnlyDictionary<string, string?>? environment = null, IClock? clock = null)
|
||||
|
||||
@@ -192,7 +192,7 @@ internal sealed record SystemView(
|
||||
.Select(u => new PlannedJob(JobTime(u.DueUtc, now, zone), u.Description)).ToList();
|
||||
|
||||
var since = host.Status.Since;
|
||||
var platform = host.Config.Platform == PlatformKind.Docker ? "in Docker" : "come applicazione desktop";
|
||||
var platform = host.IsDemo ? "in modalità dimostrativa" : "in Docker";
|
||||
var localSince = TimeZoneInfo.ConvertTime(since, zone);
|
||||
var days = (int)Math.Floor((now - since).TotalDays);
|
||||
var running = days >= 1
|
||||
|
||||
@@ -61,8 +61,7 @@
|
||||
"Microsoft.Data.Sqlite": "[10.0.14, )",
|
||||
"Microsoft.ML.OnnxRuntime": "[1.31.1, )",
|
||||
"Microsoft.ML.Tokenizers": "[2.0.1, )",
|
||||
"Npgsql": "[10.0.3, )",
|
||||
"System.Security.Cryptography.ProtectedData": "[10.0.14, )"
|
||||
"Npgsql": "[10.0.3, )"
|
||||
}
|
||||
},
|
||||
"Microsoft.Data.Sqlite": {
|
||||
@@ -99,15 +98,9 @@
|
||||
"requested": "[10.0.3, )",
|
||||
"resolved": "10.0.3",
|
||||
"contentHash": "7nb5YzXuvWWJxB0J8DiyL3we+X4FOctZrt0fIBnucOIaIevFEEwGQVZKtiu9olXdlNAK1eNgqSral6r/jlhI4w=="
|
||||
},
|
||||
"System.Security.Cryptography.ProtectedData": {
|
||||
"type": "CentralTransitive",
|
||||
"requested": "[10.0.14, )",
|
||||
"resolved": "10.0.14",
|
||||
"contentHash": "UuaBUHgmtc9h6CMxaQqFDDJxkS5JVy7XEB+DbtCvD68GFcVM9/AccuNwFpARx8nwCnvjaxzoOBjG3gPz32P1Eg=="
|
||||
}
|
||||
},
|
||||
"net10.0/win-x64": {
|
||||
"net10.0/linux-x64": {
|
||||
"SQLitePCLRaw.lib.e_sqlite3": {
|
||||
"type": "Transitive",
|
||||
"resolved": "2.1.13",
|
||||
|
||||
Reference in new issue
Block a user