Fase 10 — Nuova rotta: solo Docker (#184)
ADR 0021-0026 for the new course of 2 December 2026, roadmap of phases 10-24. The desktop application is gone: Docker is the only form, and outside a container the server runs only for development and tests with --data-dir, on this computer only. Lighter image (829 MB to 410 MB), rotating logs, backtest and learning as one-shot commands. refs #113 #114 #115 #78 #80 #81 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #184.
This commit is contained in:
1 parent
3c57b3e84c
commit
1bc7e067fd
96 files changed
+1433
-1606
No files matched your search
@@ -1,11 +0,0 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0-windows</TargetFramework>
|
||||
<EnableWindowsTargeting>true</EnableWindowsTargeting>
|
||||
<RootNamespace>Anubis.Desktop</RootNamespace>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Anubis\Anubis.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -1,3 +0,0 @@
|
||||
// Placeholder: the desktop window and tray icon arrives in phase 10 (ADR 0003).
|
||||
await Console.Error.WriteLineAsync("Anubis.Desktop non è ancora disponibile: arriva nella Fase 10.").ConfigureAwait(false);
|
||||
return 2;
|
||||
@@ -1,127 +0,0 @@
|
||||
{
|
||||
"version": 2,
|
||||
"dependencies": {
|
||||
"net10.0-windows7.0": {
|
||||
"Google.Protobuf": {
|
||||
"type": "Transitive",
|
||||
"resolved": "3.30.2",
|
||||
"contentHash": "Y2aOVLIt75yeeEWigg9V9YnjsEm53sADtLGq0gLhwaXpk3iu8tYSoauolyhenagA2sWno2TQ2WujI0HQd6s1Vw=="
|
||||
},
|
||||
"Microsoft.Data.Sqlite.Core": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.14",
|
||||
"contentHash": "1p9rO3Q2X/L/9YrYog3vaDzi8u+WZfJCOkDYoHqmofqYP0DLPLPyZcS2Rnh/79JXAodgbs1AgsaNwLpIvC3Xew==",
|
||||
"dependencies": {
|
||||
"SQLitePCLRaw.core": "2.1.13"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.0",
|
||||
"contentHash": "L3AdmZ1WOK4XXT5YFPEwyt0ep6l8lGIPs7F5OOBZc77Zqeo01Of7XXICy47628sdVl0v/owxYJTe86DTgFwKCA=="
|
||||
},
|
||||
"Microsoft.Extensions.Logging.Abstractions": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.0",
|
||||
"contentHash": "FU/IfjDfwaMuKr414SSQNTIti/69bHEMb+QKrskRb26oVqpx3lNFXMjs/RC9ZUuhBhcwDM2BwOgoMw+PZ+beqQ==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.0"
|
||||
}
|
||||
},
|
||||
"Microsoft.ML.OnnxRuntime.Managed": {
|
||||
"type": "Transitive",
|
||||
"resolved": "1.31.1",
|
||||
"contentHash": "158JCbNXN9/90LtjF4vHFiJYCF0bqF7CxLjm031jq7dJLEn/CtlHpMJm3UItQSIhQenlx+9Zuqi3zulwnsRVtA==",
|
||||
"dependencies": {
|
||||
"System.Numerics.Tensors": "9.0.0"
|
||||
}
|
||||
},
|
||||
"SQLitePCLRaw.bundle_e_sqlite3": {
|
||||
"type": "Transitive",
|
||||
"resolved": "2.1.13",
|
||||
"contentHash": "NlDixlC7uHmo+ojXRgkNvN0tQtVGpLDZ3x2OpgNj+G07VHh5cXSszFDrAiC4BpUiPwkcaeuQkMV9WQ123xVtmQ==",
|
||||
"dependencies": {
|
||||
"SQLitePCLRaw.lib.e_sqlite3": "2.1.13",
|
||||
"SQLitePCLRaw.provider.e_sqlite3": "2.1.13"
|
||||
}
|
||||
},
|
||||
"SQLitePCLRaw.core": {
|
||||
"type": "Transitive",
|
||||
"resolved": "2.1.13",
|
||||
"contentHash": "2joofoinuHBFs0nMX3nKuXgxpXryRkCOdM2Ua6HBqQLLy6IW+5f28ZI+HAvMyF8vG7XfNz/lwfBfE6V4juru8Q=="
|
||||
},
|
||||
"SQLitePCLRaw.lib.e_sqlite3": {
|
||||
"type": "Transitive",
|
||||
"resolved": "2.1.13",
|
||||
"contentHash": "D2UAuiGxFYBqeRXjjjGgvJ5UQifzn6wefmSqeKU7XcNGKLbJRP6X7kcPZ6opOBJGdCIlgbSxTvDpBbLvsN594A=="
|
||||
},
|
||||
"SQLitePCLRaw.provider.e_sqlite3": {
|
||||
"type": "Transitive",
|
||||
"resolved": "2.1.13",
|
||||
"contentHash": "ZU60dSqoSNRe49KcQDUmOVgdRtjITOssVXFtiISs+zJXDI4D2Sndwpn2NOtzDQNPu0ZAvpoLPQ+GLKv6iEZn8Q==",
|
||||
"dependencies": {
|
||||
"SQLitePCLRaw.core": "2.1.13"
|
||||
}
|
||||
},
|
||||
"System.Numerics.Tensors": {
|
||||
"type": "Transitive",
|
||||
"resolved": "9.0.0",
|
||||
"contentHash": "hyJB4UlpAi19Xr9AXzu2NuagKC4lPfHObNMEAA0HmqFz2rX7wKgzeYzO/jM/eBHDhnUGFFEjk5cOoJaxqg5J4A=="
|
||||
},
|
||||
"anubis": {
|
||||
"type": "Project",
|
||||
"dependencies": {
|
||||
"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, )"
|
||||
}
|
||||
},
|
||||
"Microsoft.Data.Sqlite": {
|
||||
"type": "CentralTransitive",
|
||||
"requested": "[10.0.14, )",
|
||||
"resolved": "10.0.14",
|
||||
"contentHash": "muyroan6rKrf0omZL8UF7Kw5uOGp/yBg1L/XWvkFN3WhKaNtK2IWqRZw93nIwVqjhTVDO0l4CEGhHIh+mb+sKg==",
|
||||
"dependencies": {
|
||||
"Microsoft.Data.Sqlite.Core": "10.0.14",
|
||||
"SQLitePCLRaw.bundle_e_sqlite3": "2.1.13",
|
||||
"SQLitePCLRaw.core": "2.1.13"
|
||||
}
|
||||
},
|
||||
"Microsoft.ML.OnnxRuntime": {
|
||||
"type": "CentralTransitive",
|
||||
"requested": "[1.31.1, )",
|
||||
"resolved": "1.31.1",
|
||||
"contentHash": "XtsO/1JoKepkWbGk9/DcYtRUTduwJD68kw0eeaH5yy77YBivUZWhC1NBNlVecsBt9EitlQIjCd1hHDNXJ2jbQA==",
|
||||
"dependencies": {
|
||||
"Microsoft.ML.OnnxRuntime.Managed": "1.31.1"
|
||||
}
|
||||
},
|
||||
"Microsoft.ML.Tokenizers": {
|
||||
"type": "CentralTransitive",
|
||||
"requested": "[2.0.1, )",
|
||||
"resolved": "2.0.1",
|
||||
"contentHash": "RZN3zslVWinBCMDAnbZWEY8lQbMkP54Yxm1s5NigPcrvYFzXMrDjNcVM9afq4SZHf1BV1rEmO0p7ZdfBLDbu4g==",
|
||||
"dependencies": {
|
||||
"Google.Protobuf": "3.30.2"
|
||||
}
|
||||
},
|
||||
"Npgsql": {
|
||||
"type": "CentralTransitive",
|
||||
"requested": "[10.0.3, )",
|
||||
"resolved": "10.0.3",
|
||||
"contentHash": "7nb5YzXuvWWJxB0J8DiyL3we+X4FOctZrt0fIBnucOIaIevFEEwGQVZKtiu9olXdlNAK1eNgqSral6r/jlhI4w==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Logging.Abstractions": "10.0.0"
|
||||
}
|
||||
},
|
||||
"System.Security.Cryptography.ProtectedData": {
|
||||
"type": "CentralTransitive",
|
||||
"requested": "[10.0.14, )",
|
||||
"resolved": "10.0.14",
|
||||
"contentHash": "UuaBUHgmtc9h6CMxaQqFDDJxkS5JVy7XEB+DbtCvD68GFcVM9/AccuNwFpARx8nwCnvjaxzoOBjG3gPz32P1Eg=="
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,9 @@
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<RootNamespace>Anubis.Guard</RootNamespace>
|
||||
<!-- 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>
|
||||
<!-- The same shared runtime as the engine: in the image both live in /app (ADR 0012). -->
|
||||
|
||||
@@ -13,7 +13,18 @@ if (args is ["drill", ..])
|
||||
|
||||
var environment = Environment.GetEnvironmentVariables().Cast<DictionaryEntry>()
|
||||
.ToDictionary(e => (string)e.Key, e => e.Value as string, StringComparer.Ordinal);
|
||||
var paths = new GuardPaths(DataRoot(args, environment));
|
||||
string root;
|
||||
try
|
||||
{
|
||||
root = DataRoot(args, environment);
|
||||
}
|
||||
catch (StartupRefusedException refused)
|
||||
{
|
||||
await Console.Error.WriteLineAsync(refused.Message).ConfigureAwait(false);
|
||||
return 2;
|
||||
}
|
||||
|
||||
var paths = new GuardPaths(root);
|
||||
var logger = new LineLogger(Console.Out.WriteLine);
|
||||
using var http = Anubis.Brokers.Outgoing.KeyedClient();
|
||||
http.Timeout = TimeSpan.FromSeconds(20);
|
||||
@@ -36,15 +47,11 @@ void Stop(PosixSignalContext context)
|
||||
shutdown.Cancel();
|
||||
}
|
||||
|
||||
// The engine's data folder: --data-dir when given, /data in Docker, the user's folder on desktop (SPEC 15.2, 15.6).
|
||||
// The engine's data folder, with the rule of the server (ADR 0022): --data-dir when given, /data inside a container.
|
||||
// A refused --platform ends here, with the server's message, instead of an engine restarted again and again.
|
||||
static string DataRoot(string[] args, Dictionary<string, string?> environment)
|
||||
{
|
||||
DataDirectory.RefuseOtherPlatforms(args);
|
||||
var index = Array.IndexOf(args, "--data-dir");
|
||||
if (index >= 0 && index + 1 < args.Length)
|
||||
{
|
||||
return Path.GetFullPath(args[index + 1]);
|
||||
}
|
||||
|
||||
var platform = Array.IndexOf(args, "--platform") is var p and >= 0 && p + 1 < args.Length ? args[p + 1] : environment.GetValueOrDefault("ANUBIS_PLATFORM");
|
||||
return platform == "docker" ? "/data" : DataDirectory.ForCurrentUser().Root;
|
||||
return DataDirectory.Locate(index >= 0 && index + 1 < args.Length ? args[index + 1] : null, environment);
|
||||
}
|
||||
@@ -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,12 +98,22 @@
|
||||
"requested": "[10.0.3, )",
|
||||
"resolved": "10.0.3",
|
||||
"contentHash": "7nb5YzXuvWWJxB0J8DiyL3we+X4FOctZrt0fIBnucOIaIevFEEwGQVZKtiu9olXdlNAK1eNgqSral6r/jlhI4w=="
|
||||
}
|
||||
},
|
||||
"net10.0/linux-x64": {
|
||||
"SQLitePCLRaw.lib.e_sqlite3": {
|
||||
"type": "Transitive",
|
||||
"resolved": "2.1.13",
|
||||
"contentHash": "D2UAuiGxFYBqeRXjjjGgvJ5UQifzn6wefmSqeKU7XcNGKLbJRP6X7kcPZ6opOBJGdCIlgbSxTvDpBbLvsN594A=="
|
||||
},
|
||||
"System.Security.Cryptography.ProtectedData": {
|
||||
"Microsoft.ML.OnnxRuntime": {
|
||||
"type": "CentralTransitive",
|
||||
"requested": "[10.0.14, )",
|
||||
"resolved": "10.0.14",
|
||||
"contentHash": "UuaBUHgmtc9h6CMxaQqFDDJxkS5JVy7XEB+DbtCvD68GFcVM9/AccuNwFpARx8nwCnvjaxzoOBjG3gPz32P1Eg=="
|
||||
"requested": "[1.31.1, )",
|
||||
"resolved": "1.31.1",
|
||||
"contentHash": "XtsO/1JoKepkWbGk9/DcYtRUTduwJD68kw0eeaH5yy77YBivUZWhC1NBNlVecsBt9EitlQIjCd1hHDNXJ2jbQA==",
|
||||
"dependencies": {
|
||||
"Microsoft.ML.OnnxRuntime.Managed": "1.31.1"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,19 @@ 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;
|
||||
|
||||
/// <summary>True inside the container; outside it the server runs only for development and tests (ADR 0022).</summary>
|
||||
public bool InContainer => options.InContainer;
|
||||
|
||||
public HostStatus Status => _status;
|
||||
|
||||
public IClock Clock => clock;
|
||||
@@ -93,15 +96,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 +302,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 +394,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 +514,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" : host.InContainer ? "in Docker" : "fuori dal container (sviluppo)";
|
||||
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",
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0-windows</TargetFramework>
|
||||
<EnableWindowsTargeting>true</EnableWindowsTargeting>
|
||||
<RootNamespace>Anubis.Setup</RootNamespace>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Anubis\Anubis.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -1,3 +0,0 @@
|
||||
// Placeholder: the Windows installer arrives in phase 10 (ADR 0003).
|
||||
await Console.Error.WriteLineAsync("Anubis.Setup non è ancora disponibile: arriva nella Fase 10.").ConfigureAwait(false);
|
||||
return 2;
|
||||
@@ -1,127 +0,0 @@
|
||||
{
|
||||
"version": 2,
|
||||
"dependencies": {
|
||||
"net10.0-windows7.0": {
|
||||
"Google.Protobuf": {
|
||||
"type": "Transitive",
|
||||
"resolved": "3.30.2",
|
||||
"contentHash": "Y2aOVLIt75yeeEWigg9V9YnjsEm53sADtLGq0gLhwaXpk3iu8tYSoauolyhenagA2sWno2TQ2WujI0HQd6s1Vw=="
|
||||
},
|
||||
"Microsoft.Data.Sqlite.Core": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.14",
|
||||
"contentHash": "1p9rO3Q2X/L/9YrYog3vaDzi8u+WZfJCOkDYoHqmofqYP0DLPLPyZcS2Rnh/79JXAodgbs1AgsaNwLpIvC3Xew==",
|
||||
"dependencies": {
|
||||
"SQLitePCLRaw.core": "2.1.13"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.0",
|
||||
"contentHash": "L3AdmZ1WOK4XXT5YFPEwyt0ep6l8lGIPs7F5OOBZc77Zqeo01Of7XXICy47628sdVl0v/owxYJTe86DTgFwKCA=="
|
||||
},
|
||||
"Microsoft.Extensions.Logging.Abstractions": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.0",
|
||||
"contentHash": "FU/IfjDfwaMuKr414SSQNTIti/69bHEMb+QKrskRb26oVqpx3lNFXMjs/RC9ZUuhBhcwDM2BwOgoMw+PZ+beqQ==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.0"
|
||||
}
|
||||
},
|
||||
"Microsoft.ML.OnnxRuntime.Managed": {
|
||||
"type": "Transitive",
|
||||
"resolved": "1.31.1",
|
||||
"contentHash": "158JCbNXN9/90LtjF4vHFiJYCF0bqF7CxLjm031jq7dJLEn/CtlHpMJm3UItQSIhQenlx+9Zuqi3zulwnsRVtA==",
|
||||
"dependencies": {
|
||||
"System.Numerics.Tensors": "9.0.0"
|
||||
}
|
||||
},
|
||||
"SQLitePCLRaw.bundle_e_sqlite3": {
|
||||
"type": "Transitive",
|
||||
"resolved": "2.1.13",
|
||||
"contentHash": "NlDixlC7uHmo+ojXRgkNvN0tQtVGpLDZ3x2OpgNj+G07VHh5cXSszFDrAiC4BpUiPwkcaeuQkMV9WQ123xVtmQ==",
|
||||
"dependencies": {
|
||||
"SQLitePCLRaw.lib.e_sqlite3": "2.1.13",
|
||||
"SQLitePCLRaw.provider.e_sqlite3": "2.1.13"
|
||||
}
|
||||
},
|
||||
"SQLitePCLRaw.core": {
|
||||
"type": "Transitive",
|
||||
"resolved": "2.1.13",
|
||||
"contentHash": "2joofoinuHBFs0nMX3nKuXgxpXryRkCOdM2Ua6HBqQLLy6IW+5f28ZI+HAvMyF8vG7XfNz/lwfBfE6V4juru8Q=="
|
||||
},
|
||||
"SQLitePCLRaw.lib.e_sqlite3": {
|
||||
"type": "Transitive",
|
||||
"resolved": "2.1.13",
|
||||
"contentHash": "D2UAuiGxFYBqeRXjjjGgvJ5UQifzn6wefmSqeKU7XcNGKLbJRP6X7kcPZ6opOBJGdCIlgbSxTvDpBbLvsN594A=="
|
||||
},
|
||||
"SQLitePCLRaw.provider.e_sqlite3": {
|
||||
"type": "Transitive",
|
||||
"resolved": "2.1.13",
|
||||
"contentHash": "ZU60dSqoSNRe49KcQDUmOVgdRtjITOssVXFtiISs+zJXDI4D2Sndwpn2NOtzDQNPu0ZAvpoLPQ+GLKv6iEZn8Q==",
|
||||
"dependencies": {
|
||||
"SQLitePCLRaw.core": "2.1.13"
|
||||
}
|
||||
},
|
||||
"System.Numerics.Tensors": {
|
||||
"type": "Transitive",
|
||||
"resolved": "9.0.0",
|
||||
"contentHash": "hyJB4UlpAi19Xr9AXzu2NuagKC4lPfHObNMEAA0HmqFz2rX7wKgzeYzO/jM/eBHDhnUGFFEjk5cOoJaxqg5J4A=="
|
||||
},
|
||||
"anubis": {
|
||||
"type": "Project",
|
||||
"dependencies": {
|
||||
"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, )"
|
||||
}
|
||||
},
|
||||
"Microsoft.Data.Sqlite": {
|
||||
"type": "CentralTransitive",
|
||||
"requested": "[10.0.14, )",
|
||||
"resolved": "10.0.14",
|
||||
"contentHash": "muyroan6rKrf0omZL8UF7Kw5uOGp/yBg1L/XWvkFN3WhKaNtK2IWqRZw93nIwVqjhTVDO0l4CEGhHIh+mb+sKg==",
|
||||
"dependencies": {
|
||||
"Microsoft.Data.Sqlite.Core": "10.0.14",
|
||||
"SQLitePCLRaw.bundle_e_sqlite3": "2.1.13",
|
||||
"SQLitePCLRaw.core": "2.1.13"
|
||||
}
|
||||
},
|
||||
"Microsoft.ML.OnnxRuntime": {
|
||||
"type": "CentralTransitive",
|
||||
"requested": "[1.31.1, )",
|
||||
"resolved": "1.31.1",
|
||||
"contentHash": "XtsO/1JoKepkWbGk9/DcYtRUTduwJD68kw0eeaH5yy77YBivUZWhC1NBNlVecsBt9EitlQIjCd1hHDNXJ2jbQA==",
|
||||
"dependencies": {
|
||||
"Microsoft.ML.OnnxRuntime.Managed": "1.31.1"
|
||||
}
|
||||
},
|
||||
"Microsoft.ML.Tokenizers": {
|
||||
"type": "CentralTransitive",
|
||||
"requested": "[2.0.1, )",
|
||||
"resolved": "2.0.1",
|
||||
"contentHash": "RZN3zslVWinBCMDAnbZWEY8lQbMkP54Yxm1s5NigPcrvYFzXMrDjNcVM9afq4SZHf1BV1rEmO0p7ZdfBLDbu4g==",
|
||||
"dependencies": {
|
||||
"Google.Protobuf": "3.30.2"
|
||||
}
|
||||
},
|
||||
"Npgsql": {
|
||||
"type": "CentralTransitive",
|
||||
"requested": "[10.0.3, )",
|
||||
"resolved": "10.0.3",
|
||||
"contentHash": "7nb5YzXuvWWJxB0J8DiyL3we+X4FOctZrt0fIBnucOIaIevFEEwGQVZKtiu9olXdlNAK1eNgqSral6r/jlhI4w==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Logging.Abstractions": "10.0.0"
|
||||
}
|
||||
},
|
||||
"System.Security.Cryptography.ProtectedData": {
|
||||
"type": "CentralTransitive",
|
||||
"requested": "[10.0.14, )",
|
||||
"resolved": "10.0.14",
|
||||
"contentHash": "UuaBUHgmtc9h6CMxaQqFDDJxkS5JVy7XEB+DbtCvD68GFcVM9/AccuNwFpARx8nwCnvjaxzoOBjG3gPz32P1Eg=="
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -232,7 +232,7 @@ public sealed class AccessStore(Database db, IClock clock, SecretStore secrets,
|
||||
public Task<bool> HasUserAsync(CancellationToken cancellationToken = default) =>
|
||||
db.ReadAsync(async s => await s.CountAsync("SELECT COUNT(*) FROM users").ConfigureAwait(false) > 0, cancellationToken);
|
||||
|
||||
/// <summary>The single user, or null before the first run created it.</summary>
|
||||
/// <summary>The single user, or null before the first start created it.</summary>
|
||||
public Task<User?> GetUserAsync(CancellationToken cancellationToken = default) =>
|
||||
db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT id, username, must_change_password, totp_secret FROM users WHERE username = @u",
|
||||
r => new User(r.Id("id"), r.Text("username"), r.Bool("must_change_password"), !r.IsNull("totp_secret")), ("u", AdminName)), cancellationToken);
|
||||
|
||||
@@ -1,14 +1,13 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<RootNamespace>Anubis</RootNamespace>
|
||||
<!-- 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>
|
||||
<PackageReference Include="Npgsql" />
|
||||
<PackageReference Include="Microsoft.Data.Sqlite" />
|
||||
<PackageReference Include="System.Security.Cryptography.ProtectedData" />
|
||||
<PackageReference Include="Microsoft.ML.OnnxRuntime" />
|
||||
<PackageReference Include="Microsoft.ML.Tokenizers" />
|
||||
</ItemGroup>
|
||||
|
||||
@@ -81,11 +81,10 @@ public static class DemoMode
|
||||
|
||||
public static StartupConfig Config(DataDirectory data) => new()
|
||||
{
|
||||
Platform = PlatformKind.Desktop,
|
||||
Data = data,
|
||||
Db = new DbSettings { Engine = DbEngine.Sqlite, SqlitePath = data.SqliteFile },
|
||||
TimeZone = TimeZoneInfo.FindSystemTimeZoneById("Europe/Rome"),
|
||||
SecretKey = new ProtectedSecretKey(new RestrictedFileStore(Path.Combine(data.Root, "keys"))),
|
||||
SecretKey = new FileSecretKey(Path.Combine(data.Root, "keys")),
|
||||
AllowLive = false,
|
||||
};
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
namespace Anubis.Platform;
|
||||
|
||||
/// <summary>
|
||||
/// The data folder (SPEC 15.2, 15.6): <c>/data</c> in Docker, the user's application folder on desktop.
|
||||
/// Same layout on both: db/, models/, research/, import/, backups/, logs/, installation.json.
|
||||
/// The data folder (SPEC 15.2): <c>/data</c> in the container, a folder given with <c>--data-dir</c> for development
|
||||
/// and tests (ADR 0022). Layout: db/, models/, research/, import/, backups/, logs/, installation.json.
|
||||
/// </summary>
|
||||
public sealed record DataDirectory(string Root)
|
||||
{
|
||||
@@ -22,8 +22,6 @@ public sealed record DataDirectory(string Root)
|
||||
|
||||
public string InstallationFile => Path.Combine(Root, "installation.json");
|
||||
|
||||
public string ConfigFile => Path.Combine(Root, "config.toml");
|
||||
|
||||
public string SqliteFile => Path.Combine(Db, "anubis.sqlite3");
|
||||
|
||||
/// <summary>Creates the folder and its sub-folders when missing. Never deletes anything.</summary>
|
||||
@@ -36,21 +34,66 @@ public sealed record DataDirectory(string Root)
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The standard per-user folder (SPEC 15.6): %APPDATA%\Anubis, ~/Library/Application Support/Anubis, ~/.local/share/anubis.</summary>
|
||||
public static DataDirectory ForCurrentUser()
|
||||
/// <summary>True inside a container: the .NET images of Microsoft set DOTNET_RUNNING_IN_CONTAINER (ADR 0022).</summary>
|
||||
public static bool InContainer(IReadOnlyDictionary<string, string?> environment)
|
||||
{
|
||||
if (OperatingSystem.IsWindows())
|
||||
ArgumentNullException.ThrowIfNull(environment);
|
||||
return environment.GetValueOrDefault("DOTNET_RUNNING_IN_CONTAINER") == "true";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Where the data folder is, for the server and the guard alike (ADR 0022): <c>--data-dir</c> when given,
|
||||
/// <c>/data</c> inside a container, otherwise nowhere: outside a container Anubis runs only for development
|
||||
/// and tests, with the folder given by hand.
|
||||
/// </summary>
|
||||
public static string Locate(string? dataDir, IReadOnlyDictionary<string, string?> environment)
|
||||
{
|
||||
if (dataDir is not null)
|
||||
{
|
||||
return new(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Anubis"));
|
||||
return Path.GetFullPath(dataDir);
|
||||
}
|
||||
|
||||
var home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
|
||||
if (OperatingSystem.IsMacOS())
|
||||
{
|
||||
return new(Path.Combine(home, "Library", "Application Support", "Anubis"));
|
||||
}
|
||||
return InContainer(environment) ? "/data" : throw new StartupRefusedException(OutsideContainer);
|
||||
}
|
||||
|
||||
var xdg = Environment.GetEnvironmentVariable("XDG_DATA_HOME");
|
||||
return new(Path.Combine(string.IsNullOrEmpty(xdg) ? Path.Combine(home, ".local", "share") : xdg, "anubis"));
|
||||
public const string OutsideContainer =
|
||||
"Fuori da un container Anubis gira solo per sviluppo e prove: indica la cartella dei dati con --data-dir <cartella>.";
|
||||
|
||||
public const string NoDesktop =
|
||||
"L'applicazione desktop non esiste più: Anubis gira solo in un container Docker (ADR 0022). " +
|
||||
"Per sviluppo e prove avvia il server con --data-dir <cartella>, senza --platform.";
|
||||
|
||||
/// <summary>
|
||||
/// <c>--platform</c> is still accepted with "docker", the only form there is, for the commands already in the
|
||||
/// manuals; any other value (the desktop) is refused with <see cref="NoDesktop"/>. Server and guard both apply it.
|
||||
/// </summary>
|
||||
public static void RefuseOtherPlatforms(IReadOnlyList<string> args)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(args);
|
||||
for (var i = 0; i + 1 < args.Count; i++)
|
||||
{
|
||||
if (args[i] == "--platform" && !args[i + 1].Equals("docker", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
throw new StartupRefusedException(NoDesktop);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The process cannot start as asked; the message, in Italian, says why and what to do.</summary>
|
||||
public sealed class StartupRefusedException : Exception
|
||||
{
|
||||
public StartupRefusedException()
|
||||
{
|
||||
}
|
||||
|
||||
public StartupRefusedException(string message)
|
||||
: base(message)
|
||||
{
|
||||
}
|
||||
|
||||
public StartupRefusedException(string message, Exception innerException)
|
||||
: base(message, innerException)
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,10 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using Anubis.Core;
|
||||
|
||||
namespace Anubis.Platform;
|
||||
|
||||
/// <summary>
|
||||
/// Docker (SPEC 15.1): everything from environment variables. Missing or wrong values become
|
||||
/// The container (SPEC 15.1, ADR 0022): everything from environment variables, also for the development runs outside it. Missing or wrong values become
|
||||
/// <see cref="ConfigProblem"/>s for the error page; nothing falls back to another database (trap 20).
|
||||
/// </summary>
|
||||
public static class DockerPlatform
|
||||
@@ -82,12 +81,10 @@ public static class DockerPlatform
|
||||
|
||||
return new StartupConfig
|
||||
{
|
||||
Platform = PlatformKind.Docker,
|
||||
Data = data,
|
||||
Db = db,
|
||||
TimeZone = zone,
|
||||
Port = port,
|
||||
AllowNetwork = true,
|
||||
AllowLive = allowLive,
|
||||
AdminPassword = admin,
|
||||
SecretKey = new EnvironmentSecretKey(secret),
|
||||
@@ -210,153 +207,3 @@ public static class DockerPlatform
|
||||
return port;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Desktop (SPEC 15.6): <c>config.toml</c> in the user's data folder, written by the first-run wizard.
|
||||
/// The secret key and the PostgreSQL password never go in the file: they live in the <see cref="IProtectedStore"/>.
|
||||
/// </summary>
|
||||
public static class DesktopPlatform
|
||||
{
|
||||
public const string DbPasswordName = "db-password";
|
||||
|
||||
public static StartupConfig Load(DataDirectory data, IProtectedStore store)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(data);
|
||||
ArgumentNullException.ThrowIfNull(store);
|
||||
var problems = new List<ConfigProblem>();
|
||||
var secretKey = new ProtectedSecretKey(store);
|
||||
if (!File.Exists(data.ConfigFile))
|
||||
{
|
||||
return new StartupConfig
|
||||
{
|
||||
Platform = PlatformKind.Desktop,
|
||||
Data = data,
|
||||
TimeZone = TimeZoneInfo.Local,
|
||||
SecretKey = secretKey,
|
||||
NeedsFirstRun = true,
|
||||
};
|
||||
}
|
||||
|
||||
IReadOnlyDictionary<string, object> toml;
|
||||
try
|
||||
{
|
||||
toml = Toml.Parse(File.ReadAllText(data.ConfigFile));
|
||||
}
|
||||
catch (FormatException ex)
|
||||
{
|
||||
problems.Add(new("config.toml", "Il file di configurazione non si legge: " + ex.Message,
|
||||
$"Correggi il file {data.ConfigFile} oppure rinominalo per ripetere la procedura di primo avvio."));
|
||||
return new StartupConfig { Platform = PlatformKind.Desktop, Data = data, TimeZone = TimeZoneInfo.Local, SecretKey = secretKey, Problems = problems };
|
||||
}
|
||||
|
||||
string? Text(string key) => toml.TryGetValue(key, out var v) ? v as string ?? Fail<string>(key, "testo tra virgolette") : null;
|
||||
long? Integer(string key) => toml.TryGetValue(key, out var v) ? v is long n ? n : Fail<long?>(key, "un numero intero") : null;
|
||||
bool? Flag(string key) => toml.TryGetValue(key, out var v) ? v is bool b ? b : Fail<bool?>(key, "true o false") : null;
|
||||
T? Fail<T>(string key, string expected)
|
||||
{
|
||||
problems.Add(new("config.toml", $"La voce '{key}' deve essere {expected}.", $"Correggi {data.ConfigFile} e riavvia."));
|
||||
return default;
|
||||
}
|
||||
|
||||
var zone = Text("timezone") is { } tz ? DockerPlatform.ResolveTimeZone(tz, problems, "config.toml: timezone") : TimeZoneInfo.Local;
|
||||
DbSettings? db = null;
|
||||
switch (Text("database.engine"))
|
||||
{
|
||||
case "sqlite":
|
||||
db = new DbSettings { Engine = DbEngine.Sqlite, SqlitePath = data.SqliteFile };
|
||||
break;
|
||||
case "postgres":
|
||||
var password = store.Read(DbPasswordName) is { } bytes ? Encoding.UTF8.GetString(bytes) : null;
|
||||
Redactor.Register(password);
|
||||
if (Text("database.host") is not { } host)
|
||||
{
|
||||
problems.Add(new("config.toml", "Manca l'indirizzo del server PostgreSQL (database.host).", $"Correggi {data.ConfigFile} e riavvia."));
|
||||
}
|
||||
else
|
||||
{
|
||||
if (password is null)
|
||||
{
|
||||
problems.Add(new("Password del database", "La password di PostgreSQL non è nel portachiavi.",
|
||||
"Ripeti la procedura di primo avvio rinominando config.toml, oppure torna a SQLite."));
|
||||
}
|
||||
|
||||
db = new DbSettings
|
||||
{
|
||||
Engine = DbEngine.Postgres,
|
||||
Host = host,
|
||||
Port = (int)(Integer("database.port") ?? 5432),
|
||||
Database = Text("database.name") ?? "anubis",
|
||||
User = Text("database.user") ?? "anubis",
|
||||
Password = password,
|
||||
};
|
||||
}
|
||||
|
||||
break;
|
||||
case null:
|
||||
problems.Add(new("config.toml", "Non è indicato quale database usare (database.engine).", $"Scrivi engine = \"sqlite\" oppure \"postgres\" nella sezione [database] di {data.ConfigFile}."));
|
||||
break;
|
||||
case var other:
|
||||
problems.Add(new("config.toml", $"Il database '{other}' non è conosciuto.", "Usa \"sqlite\" oppure \"postgres\"."));
|
||||
break;
|
||||
}
|
||||
|
||||
var port = Integer("port") ?? 8787;
|
||||
if (port is < 1 or > 65535)
|
||||
{
|
||||
problems.Add(new("config.toml", "La porta non è valida.", "Usa un numero tra 1 e 65535."));
|
||||
port = 8787;
|
||||
}
|
||||
|
||||
return new StartupConfig
|
||||
{
|
||||
Platform = PlatformKind.Desktop,
|
||||
Data = data,
|
||||
Db = db,
|
||||
TimeZone = zone,
|
||||
Port = (int)port,
|
||||
AllowNetwork = Flag("allow_network") ?? false,
|
||||
AllowLive = Flag("allow_live") ?? false,
|
||||
SecretKey = secretKey,
|
||||
Problems = problems,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes config.toml at the end of the first-run wizard. <c>allow_live</c> is born false and only a hand edit
|
||||
/// turns it on (SPEC 15.6). The PostgreSQL password goes to the protected store, never into the file.
|
||||
/// </summary>
|
||||
public static void WriteConfig(DataDirectory data, IProtectedStore store, DbSettings db, int port = 8787, bool allowNetwork = false)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(data);
|
||||
ArgumentNullException.ThrowIfNull(store);
|
||||
ArgumentNullException.ThrowIfNull(db);
|
||||
var text = new StringBuilder();
|
||||
text.AppendLine("# Anubis: configurazione d'avvio (SPEC 15.6). Scritta dalla procedura di primo avvio.");
|
||||
text.AppendLine("# La chiave dei segreti e la password del database non stanno qui: sono nel portachiavi.");
|
||||
text.AppendLine();
|
||||
text.AppendLine("# Soldi veri: false. Si cambia solo a mano, mai dall'interfaccia.");
|
||||
text.AppendLine(CultureInfo.InvariantCulture, $"allow_live = false");
|
||||
text.AppendLine(CultureInfo.InvariantCulture, $"port = {port}");
|
||||
text.AppendLine(CultureInfo.InvariantCulture, $"allow_network = {(allowNetwork ? "true" : "false")}");
|
||||
text.AppendLine();
|
||||
text.AppendLine("[database]");
|
||||
if (db.Engine == DbEngine.Sqlite)
|
||||
{
|
||||
text.AppendLine("engine = \"sqlite\"");
|
||||
}
|
||||
else
|
||||
{
|
||||
text.AppendLine("engine = \"postgres\"");
|
||||
text.AppendLine(CultureInfo.InvariantCulture, $"host = {Toml.Quote(db.Host ?? "")}");
|
||||
text.AppendLine(CultureInfo.InvariantCulture, $"port = {db.Port}");
|
||||
text.AppendLine(CultureInfo.InvariantCulture, $"name = {Toml.Quote(db.Database)}");
|
||||
text.AppendLine(CultureInfo.InvariantCulture, $"user = {Toml.Quote(db.User)}");
|
||||
store.Write(DbPasswordName, Encoding.UTF8.GetBytes(db.Password ?? ""));
|
||||
}
|
||||
|
||||
data.Ensure();
|
||||
var temp = data.ConfigFile + ".tmp";
|
||||
File.WriteAllText(temp, text.ToString().ReplaceLineEndings("\n"));
|
||||
File.Move(temp, data.ConfigFile, overwrite: true);
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,10 @@
|
||||
using System.Runtime.Versioning;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace Anubis.Platform;
|
||||
|
||||
/// <summary>
|
||||
/// Custody of the key that encrypts the secrets in the database (SPEC 15.4, 15.6). The interface says
|
||||
/// Custody of the key that encrypts the secrets in the database (SPEC 15.4, ADR 0022). The interface says
|
||||
/// where the key lives, so Settings can declare it.
|
||||
/// </summary>
|
||||
public interface ISecretKeyStore
|
||||
@@ -13,14 +12,14 @@ public interface ISecretKeyStore
|
||||
/// <summary>Where the key lives, in plain Italian, for Settings → Sistema.</summary>
|
||||
string Description { get; }
|
||||
|
||||
/// <summary>True when the key exists (or, in Docker, the variable is set).</summary>
|
||||
/// <summary>True when the key exists (in the container: when the variable is set).</summary>
|
||||
bool HasKey { get; }
|
||||
|
||||
/// <summary>The 32-byte key. Desktop stores create it on first use.</summary>
|
||||
/// <summary>The 32-byte key. The demo creates it on first use.</summary>
|
||||
byte[] GetOrCreateKey();
|
||||
}
|
||||
|
||||
/// <summary>Docker: the key derives from <c>ANUBIS_SECRET_KEY</c> (at least 32 characters, SPEC 15.1).</summary>
|
||||
/// <summary>The container: the key derives from <c>ANUBIS_SECRET_KEY</c> (at least 32 characters, SPEC 15.1).</summary>
|
||||
public sealed class EnvironmentSecretKey(string? value) : ISecretKeyStore
|
||||
{
|
||||
public const int MinimumLength = 32;
|
||||
@@ -40,65 +39,43 @@ public sealed class EnvironmentSecretKey(string? value) : ISecretKeyStore
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Small values kept outside config.toml: the desktop secret key and the PostgreSQL password (SPEC 15.6).</summary>
|
||||
public interface IProtectedStore
|
||||
{
|
||||
string Description { get; }
|
||||
|
||||
byte[]? Read(string name);
|
||||
|
||||
void Write(string name, byte[] value);
|
||||
}
|
||||
|
||||
/// <summary>Windows: files in the data folder encrypted with DPAPI for the current user (ADR 0003 in place of keyring).</summary>
|
||||
[SupportedOSPlatform("windows")]
|
||||
public sealed class DpapiStore(string folder) : IProtectedStore
|
||||
{
|
||||
private static readonly byte[] _entropy = "Anubis protected store v1"u8.ToArray();
|
||||
|
||||
public string Description => "Protetta da Windows per il tuo utente (DPAPI), nella cartella dei dati";
|
||||
|
||||
public byte[]? Read(string name)
|
||||
{
|
||||
var path = PathOf(name);
|
||||
return File.Exists(path) ? ProtectedData.Unprotect(File.ReadAllBytes(path), _entropy, DataProtectionScope.CurrentUser) : null;
|
||||
}
|
||||
|
||||
public void Write(string name, byte[] value)
|
||||
{
|
||||
Directory.CreateDirectory(folder);
|
||||
File.WriteAllBytes(PathOf(name), ProtectedData.Protect(value, _entropy, DataProtectionScope.CurrentUser));
|
||||
}
|
||||
|
||||
private string PathOf(string name) => Path.Combine(folder, name + ".dpapi");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Where no system keychain exists (Linux without a session, macOS for now, the tests): a file readable
|
||||
/// only by its owner. The interface declares it (SPEC 15.6).
|
||||
/// The demo mode (ADR 0022): a random 32-byte key born on first start, in a file of the demo folder that only its
|
||||
/// owner can read. The container always uses <see cref="EnvironmentSecretKey"/>.
|
||||
/// </summary>
|
||||
public sealed class RestrictedFileStore(string folder) : IProtectedStore
|
||||
public sealed class FileSecretKey(string folder) : ISecretKeyStore
|
||||
{
|
||||
public string Description => "File con permessi ristretti nella cartella dei dati (nessun portachiavi disponibile)";
|
||||
public string Description => "Un file con permessi ristretti nella cartella della modalità dimostrativa";
|
||||
|
||||
public byte[]? Read(string name)
|
||||
public bool HasKey => Read() is { Length: 32 };
|
||||
|
||||
private string KeyFile => Path.Combine(folder, "secret-key.key");
|
||||
|
||||
public byte[] GetOrCreateKey()
|
||||
{
|
||||
var path = PathOf(name);
|
||||
return File.Exists(path) ? Convert.FromBase64String(File.ReadAllText(path).Trim()) : null;
|
||||
if (Read() is { Length: 32 } existing)
|
||||
{
|
||||
return existing;
|
||||
}
|
||||
|
||||
var key = RandomNumberGenerator.GetBytes(32);
|
||||
Write(key);
|
||||
return key;
|
||||
}
|
||||
|
||||
public void Write(string name, byte[] value)
|
||||
private byte[]? Read() => File.Exists(KeyFile) ? Convert.FromBase64String(File.ReadAllText(KeyFile).Trim()) : null;
|
||||
|
||||
private void Write(byte[] value)
|
||||
{
|
||||
Directory.CreateDirectory(folder);
|
||||
var path = PathOf(name);
|
||||
if (OperatingSystem.IsWindows())
|
||||
{
|
||||
File.WriteAllText(path, Convert.ToBase64String(value));
|
||||
File.WriteAllText(KeyFile, Convert.ToBase64String(value));
|
||||
return;
|
||||
}
|
||||
|
||||
// Create with 0600 from the start, so the value is never readable by others even for an instant.
|
||||
using var stream = new FileStream(path, new FileStreamOptions
|
||||
// Created with 0600 from the start, so the key is never readable by others even for an instant.
|
||||
using var stream = new FileStream(KeyFile, new FileStreamOptions
|
||||
{
|
||||
Mode = FileMode.Create,
|
||||
Access = FileAccess.Write,
|
||||
@@ -106,36 +83,4 @@ public sealed class RestrictedFileStore(string folder) : IProtectedStore
|
||||
});
|
||||
stream.Write(Encoding.ASCII.GetBytes(Convert.ToBase64String(value)));
|
||||
}
|
||||
|
||||
private string PathOf(string name) => Path.Combine(folder, name + ".key");
|
||||
}
|
||||
|
||||
/// <summary>Desktop: a random 32-byte key born on first start and kept in an <see cref="IProtectedStore"/>.</summary>
|
||||
public sealed class ProtectedSecretKey(IProtectedStore store) : ISecretKeyStore
|
||||
{
|
||||
private const string Name = "secret-key";
|
||||
|
||||
public string Description => store.Description;
|
||||
|
||||
public bool HasKey => store.Read(Name) is { Length: 32 };
|
||||
|
||||
public byte[] GetOrCreateKey()
|
||||
{
|
||||
if (store.Read(Name) is { Length: 32 } existing)
|
||||
{
|
||||
return existing;
|
||||
}
|
||||
|
||||
var key = RandomNumberGenerator.GetBytes(32);
|
||||
store.Write(Name, key);
|
||||
return key;
|
||||
}
|
||||
|
||||
/// <summary>The store for this machine: DPAPI on Windows, a restricted file elsewhere.</summary>
|
||||
public static IProtectedStore DefaultStore(DataDirectory data)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(data);
|
||||
var folder = Path.Combine(data.Root, "keys");
|
||||
return OperatingSystem.IsWindows() ? new DpapiStore(folder) : new RestrictedFileStore(folder);
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,5 @@
|
||||
namespace Anubis.Platform;
|
||||
|
||||
public enum PlatformKind
|
||||
{
|
||||
Docker,
|
||||
Desktop,
|
||||
}
|
||||
|
||||
public enum DbEngine
|
||||
{
|
||||
Sqlite,
|
||||
@@ -62,14 +56,12 @@ public sealed record DbSettings
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The startup configuration (SPEC 15.1, 15.6): everything needed before the database is reachable.
|
||||
/// It comes from environment variables in Docker and from <c>config.toml</c> on desktop. Values here win
|
||||
/// over the ones saved from the interface, which shows them read-only.
|
||||
/// The startup configuration (SPEC 15.1): everything needed before the database is reachable. It comes from the
|
||||
/// environment variables of the container (ADR 0022). Values here win over the ones saved from the interface,
|
||||
/// which shows them read-only.
|
||||
/// </summary>
|
||||
public sealed record StartupConfig
|
||||
{
|
||||
public required PlatformKind Platform { get; init; }
|
||||
|
||||
public required DataDirectory Data { get; init; }
|
||||
|
||||
/// <summary>Null when the configuration does not say which database to use (the error page explains what is missing).</summary>
|
||||
@@ -79,13 +71,10 @@ public sealed record StartupConfig
|
||||
|
||||
public int Port { get; init; } = 8787;
|
||||
|
||||
/// <summary>Desktop: listen on the home network too (SPEC 15.6). Docker always listens on every interface of the container.</summary>
|
||||
public bool AllowNetwork { get; init; }
|
||||
|
||||
/// <summary><c>ANUBIS_ALLOW_LIVE=1</c> or <c>allow_live = true</c>: only then adapters accept a real account (SPEC 2.2).</summary>
|
||||
/// <summary><c>ANUBIS_ALLOW_LIVE=1</c>: only then adapters accept a real account (SPEC 2.2).</summary>
|
||||
public bool AllowLive { get; init; }
|
||||
|
||||
/// <summary>Docker: the initial password (<c>ANUBIS_ADMIN_PASSWORD</c>), also the key of the error page choices.</summary>
|
||||
/// <summary>The initial password (<c>ANUBIS_ADMIN_PASSWORD</c>), also the key of the error page choices.</summary>
|
||||
public string? AdminPassword { get; init; }
|
||||
|
||||
public required ISecretKeyStore SecretKey { get; init; }
|
||||
@@ -102,10 +91,7 @@ public sealed record StartupConfig
|
||||
/// <summary>Problems that stop the start: the error page lists them with what to do.</summary>
|
||||
public IReadOnlyList<ConfigProblem> Problems { get; init; } = [];
|
||||
|
||||
/// <summary>Desktop only: <c>config.toml</c> does not exist yet, the first-run wizard writes it.</summary>
|
||||
public bool NeedsFirstRun { get; init; }
|
||||
|
||||
public bool IsComplete => Problems.Count == 0 && Db is not null && !NeedsFirstRun;
|
||||
public bool IsComplete => Problems.Count == 0 && Db is not null;
|
||||
}
|
||||
|
||||
/// <summary>Something missing or wrong in the startup configuration, said in plain Italian with the remedy.</summary>
|
||||
|
||||
@@ -1,165 +0,0 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
|
||||
namespace Anubis.Platform;
|
||||
|
||||
/// <summary>
|
||||
/// The subset of TOML that <c>config.toml</c> needs (ADR 0003, no external parser): comments, tables
|
||||
/// <c>[name]</c>, and <c>key = value</c> with basic strings, integers and booleans. Anything else is an error
|
||||
/// with its line number, so a hand edit gone wrong shows on the error page instead of being guessed.
|
||||
/// </summary>
|
||||
public static class Toml
|
||||
{
|
||||
/// <summary>Parses into "table.key" → value (string, long or bool). Keys outside a table have no prefix.</summary>
|
||||
public static IReadOnlyDictionary<string, object> Parse(string text)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(text);
|
||||
var result = new Dictionary<string, object>(StringComparer.Ordinal);
|
||||
var table = "";
|
||||
var lineNumber = 0;
|
||||
foreach (var rawLine in text.Split('\n'))
|
||||
{
|
||||
lineNumber++;
|
||||
var line = StripComment(rawLine).Trim();
|
||||
if (line.Length == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (line.StartsWith('['))
|
||||
{
|
||||
if (!line.EndsWith(']') || line.StartsWith("[[", StringComparison.Ordinal))
|
||||
{
|
||||
throw new FormatException($"Riga {lineNumber}: intestazione di sezione non valida.");
|
||||
}
|
||||
|
||||
table = line[1..^1].Trim();
|
||||
if (!IsBareKey(table))
|
||||
{
|
||||
throw new FormatException($"Riga {lineNumber}: nome di sezione non valido.");
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
var equals = line.IndexOf('=', StringComparison.Ordinal);
|
||||
if (equals <= 0)
|
||||
{
|
||||
throw new FormatException($"Riga {lineNumber}: manca il segno '='.");
|
||||
}
|
||||
|
||||
var key = line[..equals].Trim();
|
||||
if (!IsBareKey(key))
|
||||
{
|
||||
throw new FormatException($"Riga {lineNumber}: nome non valido '{key}'.");
|
||||
}
|
||||
|
||||
var fullKey = table.Length == 0 ? key : table + "." + key;
|
||||
if (!result.TryAdd(fullKey, ParseValue(line[(equals + 1)..].Trim(), lineNumber)))
|
||||
{
|
||||
throw new FormatException($"Riga {lineNumber}: '{fullKey}' compare due volte.");
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private static object ParseValue(string value, int lineNumber)
|
||||
{
|
||||
if (value.StartsWith('"'))
|
||||
{
|
||||
return ParseString(value, lineNumber);
|
||||
}
|
||||
|
||||
if (value is "true")
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (value is "false")
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (long.TryParse(value.Replace("_", "", StringComparison.Ordinal), NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var number))
|
||||
{
|
||||
return number;
|
||||
}
|
||||
|
||||
throw new FormatException($"Riga {lineNumber}: valore non riconosciuto. Usa testo tra virgolette, un numero intero, true o false.");
|
||||
}
|
||||
|
||||
private static string ParseString(string value, int lineNumber)
|
||||
{
|
||||
var text = new StringBuilder();
|
||||
for (var i = 1; i < value.Length; i++)
|
||||
{
|
||||
var c = value[i];
|
||||
if (c == '"')
|
||||
{
|
||||
if (i != value.Length - 1)
|
||||
{
|
||||
throw new FormatException($"Riga {lineNumber}: testo dopo la chiusura delle virgolette.");
|
||||
}
|
||||
|
||||
return text.ToString();
|
||||
}
|
||||
|
||||
if (c == '\\')
|
||||
{
|
||||
if (++i >= value.Length)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
text.Append(value[i] switch
|
||||
{
|
||||
'"' => '"',
|
||||
'\\' => '\\',
|
||||
'n' => '\n',
|
||||
't' => '\t',
|
||||
'r' => '\r',
|
||||
_ => throw new FormatException($"Riga {lineNumber}: sequenza '\\{value[i]}' non ammessa."),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
text.Append(c);
|
||||
}
|
||||
|
||||
throw new FormatException($"Riga {lineNumber}: virgolette non chiuse.");
|
||||
}
|
||||
|
||||
// A '#' starts a comment unless it is inside a string.
|
||||
private static string StripComment(string line)
|
||||
{
|
||||
var inString = false;
|
||||
for (var i = 0; i < line.Length; i++)
|
||||
{
|
||||
if (line[i] == '\\' && inString)
|
||||
{
|
||||
i++;
|
||||
}
|
||||
else if (line[i] == '"')
|
||||
{
|
||||
inString = !inString;
|
||||
}
|
||||
else if (line[i] == '#' && !inString)
|
||||
{
|
||||
return line[..i];
|
||||
}
|
||||
}
|
||||
|
||||
return line;
|
||||
}
|
||||
|
||||
private static bool IsBareKey(string key) =>
|
||||
key.Length > 0 && key.All(c => char.IsAsciiLetterOrDigit(c) || c is '_' or '-');
|
||||
|
||||
public static string Quote(string value)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(value);
|
||||
return "\"" + value.Replace("\\", "\\\\", StringComparison.Ordinal).Replace("\"", "\\\"", StringComparison.Ordinal)
|
||||
.Replace("\n", "\\n", StringComparison.Ordinal).Replace("\r", "\\r", StringComparison.Ordinal).Replace("\t", "\\t", StringComparison.Ordinal) + "\"";
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,7 @@ Le cartelle nascono con il primo codice che le riempie:
|
||||
| Cartella | Namespace | Contenuto | Fase |
|
||||
|---|---|---|---|
|
||||
| `Core/` | `Anubis.Core` | orologio, bus degli eventi, pianificatore, impostazioni, segreti, registri, identificativi, guardia, formati | 1 |
|
||||
| `Platform/` | `Anubis.Platform` | configurazione d'avvio Docker e desktop, cartella dei dati, custodia dei segreti | 1 |
|
||||
| `Platform/` | `Anubis.Platform` | configurazione d'avvio del container, cartella dei dati, custodia dei segreti | 1 |
|
||||
| `Db/` | `Anubis.Db` | accesso ADO.NET, tipi portabili, migrazioni SQL, esportazione e importazione, salvataggi | 1 |
|
||||
| `Access/` | `Anubis.Access` | password, secondo fattore, sessioni, limite ai tentativi | 1 |
|
||||
| `Brokers/` | `Anubis.Brokers` | interfaccia, Alpaca, OKX, simulatore, batteria di conformità | 2–3 |
|
||||
|
||||
@@ -81,7 +81,7 @@ public static class GuardDrill
|
||||
IClock clock = SystemClock.Instance;
|
||||
var logger = new LineLogger(Say);
|
||||
var guardian = new Guardian(new GuardPaths(folder), clock, options,
|
||||
start => ChildEngine.Start(GuardLaunch.Dotnet(), [serverDll, "--platform", "docker", "--data-dir", folder], environment, start),
|
||||
start => ChildEngine.Start(GuardLaunch.Dotnet(), [serverDll, "--data-dir", folder], environment, start),
|
||||
(_, _) => null, (text, _, _) =>
|
||||
{
|
||||
Say("Avviso della guardia: " + text.ReplaceLineEndings(" "));
|
||||
@@ -212,7 +212,6 @@ public static class GuardDrill
|
||||
}
|
||||
}
|
||||
|
||||
environment["ANUBIS_PLATFORM"] = "docker";
|
||||
environment["ANUBIS_DB_ENGINE"] = "sqlite";
|
||||
environment["ANUBIS_SECRET_KEY"] = Convert.ToHexStringLower(RandomNumberGenerator.GetBytes(24));
|
||||
environment["ANUBIS_ADMIN_PASSWORD"] = Convert.ToHexStringLower(RandomNumberGenerator.GetBytes(12));
|
||||
|
||||
@@ -72,7 +72,7 @@ public static class GuardStages
|
||||
/// <summary>The main loop runs: watched for 2 minutes of silence.</summary>
|
||||
public const string Running = "running";
|
||||
|
||||
/// <summary>Error page or first run: waiting for the user, never a reason to intervene.</summary>
|
||||
/// <summary>Error page: waiting for the user, never a reason to intervene.</summary>
|
||||
public const string Waiting = "waiting";
|
||||
}
|
||||
|
||||
|
||||
@@ -3,8 +3,8 @@ using Anubis.Platform;
|
||||
namespace Anubis.Trading;
|
||||
|
||||
/// <summary>
|
||||
/// The startup consent for real money (SPEC 2.2, 15.1, 15.6): <c>ANUBIS_ALLOW_LIVE=1</c> in Docker,
|
||||
/// <c>allow_live = true</c> in <c>config.toml</c> on desktop. Only the startup configuration can give it.
|
||||
/// The startup consent for real money (SPEC 2.2, 15.1): <c>ANUBIS_ALLOW_LIVE=1</c> in the configuration of the
|
||||
/// container. Only the startup configuration can give it.
|
||||
/// </summary>
|
||||
public sealed class TradingConsent
|
||||
{
|
||||
@@ -25,7 +25,7 @@ public sealed class TradingConsent
|
||||
public static TradingConsent From(StartupConfig startup)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(startup);
|
||||
return new(startup.AllowLive, startup.Platform == PlatformKind.Docker ? "ANUBIS_ALLOW_LIVE" : "allow_live in config.toml");
|
||||
return new(startup.AllowLive, "ANUBIS_ALLOW_LIVE");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -43,7 +43,7 @@ public sealed class RiskEngine(Database db, IClock clock, Ledger ledger, StageBo
|
||||
internal static readonly JsonSerializerOptions Json = new() { PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower };
|
||||
private static readonly TimeZoneInfo NewYork = TimeZoneInfo.FindSystemTimeZoneById("America/New_York");
|
||||
|
||||
/// <summary>The file that stops the bot (SPEC 9.3): <c>/data/STOP</c> in Docker, the data folder on desktop.</summary>
|
||||
/// <summary>The file that stops the bot (SPEC 9.3): <c>STOP</c> in the data folder, <c>/data/STOP</c> in the container.</summary>
|
||||
public string? StopFile { get; init; }
|
||||
|
||||
/// <summary>The clock skew measured with a broker, when known (SPEC 9.2): beyond the limit no new entries.</summary>
|
||||
|
||||
@@ -40,12 +40,6 @@
|
||||
"Microsoft.Extensions.Logging.Abstractions": "10.0.0"
|
||||
}
|
||||
},
|
||||
"System.Security.Cryptography.ProtectedData": {
|
||||
"type": "Direct",
|
||||
"requested": "[10.0.14, )",
|
||||
"resolved": "10.0.14",
|
||||
"contentHash": "UuaBUHgmtc9h6CMxaQqFDDJxkS5JVy7XEB+DbtCvD68GFcVM9/AccuNwFpARx8nwCnvjaxzoOBjG3gPz32P1Eg=="
|
||||
},
|
||||
"Google.Protobuf": {
|
||||
"type": "Transitive",
|
||||
"resolved": "3.30.2",
|
||||
@@ -113,7 +107,7 @@
|
||||
"contentHash": "hyJB4UlpAi19Xr9AXzu2NuagKC4lPfHObNMEAA0HmqFz2rX7wKgzeYzO/jM/eBHDhnUGFFEjk5cOoJaxqg5J4A=="
|
||||
}
|
||||
},
|
||||
"net10.0/win-x64": {
|
||||
"net10.0/linux-x64": {
|
||||
"Microsoft.ML.OnnxRuntime": {
|
||||
"type": "Direct",
|
||||
"requested": "[1.31.1, )",
|
||||
|
||||
Reference in new issue
Block a user