feat(server): web server, interface shell, demo mode and Docker image (refs #11 #12 #13 #14 #15 #16 #17)
Phase 1 completed on top of the library foundations: - Server: startup state machine (config, first run, database down, schema, identity, ready) with an error page that retries by itself; the configured database is the only one ever opened, and a vanished SQLite file is never recreated. REST API and status WebSocket; session cookie auth, CSRF on every form and write call; desktop and demo answer only the computer itself. - Interface: static Blazor rendering with plain forms (no interactive runtime), menu, top bar and phone bottom bar as in the mockups, light and dark themes with appendix C tokens and a contrast test, Panoramica, Diario, Rischio, Impostazioni; service pages for sign-in, first access, desktop first run and the database error page with its choices. - Demo mode (tasks seed-demo): appendix F in a database of its own under the temp folder, frozen clock, never touches the configured installation. - Docker: entrypoint gives /data to PUID:PGID and drops root with setpriv, HEALTHCHECK through bash /dev/tcp; proven with SQLite, PostgreSQL, a wrong configuration and a database that goes away and comes back. - tasks screenshots drives the installed Edge/Chrome through DevTools for exact 1440 and 390 pixel shots; anubis db export|import on the command line. Fixes from the independent review: return paths without control characters, Host check against DNS rebinding, attempt limit counted before the check and also on the error-page password, one-use TOTP codes and a code to switch the second factor off, error-page choices serialized with the startup loop, identity checked before migrating, restore restarts with "Ferma tutto" on, damaged archives reported instead of crashing. Running the server tests on PostgreSQL exposed pages rendered before their data arrived; data-loading components now load first (LoadedComponent). Decisions in ADR 0007. Tests: 100 on SQLite and on PostgreSQL. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
53ca01b7c3
commit
f9d71559e8
71 files changed
+5853
-80
No files matched your search
@@ -0,0 +1,486 @@
|
||||
using Anubis.Access;
|
||||
using Anubis.Core;
|
||||
using Anubis.Db;
|
||||
using Anubis.Demo;
|
||||
using Anubis.Platform;
|
||||
|
||||
namespace Anubis.Server;
|
||||
|
||||
public enum HostMode
|
||||
{
|
||||
Starting,
|
||||
|
||||
/// <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,
|
||||
|
||||
/// <summary>The database schema is newer than this version or was altered.</summary>
|
||||
SchemaProblem,
|
||||
|
||||
/// <summary>Database and data folder do not belong together (SPEC 15.1): the user chooses.</summary>
|
||||
IdentityProblem,
|
||||
|
||||
Ready,
|
||||
}
|
||||
|
||||
public sealed record HostStatus(HostMode Mode, string? Detail, IdentityCheck? Identity, DateTimeOffset Since, int Attempts);
|
||||
|
||||
/// <summary>Published on the bus whenever the host changes mode.</summary>
|
||||
internal sealed record HostChanged(HostMode Mode);
|
||||
|
||||
/// <summary>Everything that needs the database, built once it is reachable and the installation checks out.</summary>
|
||||
internal sealed record AppServices(Database Db, SettingsStore Settings, SecretStore Secrets, AccessStore Access, Backups Backups, Scheduler Scheduler);
|
||||
|
||||
/// <summary>
|
||||
/// The startup state machine of the server (SPEC 15.1, 15.6): reads the startup configuration, opens the configured
|
||||
/// database and nothing else, migrates it after a backup, checks the installation identity, then runs. While anything
|
||||
/// is wrong the interface shows the error page and the host retries by itself; when the database comes back the
|
||||
/// application resumes without a restart.
|
||||
/// </summary>
|
||||
internal sealed partial class AnubisHost(
|
||||
ServerOptions options,
|
||||
StartupConfig initialConfig,
|
||||
IReadOnlyDictionary<string, string?> environment,
|
||||
IClock clock,
|
||||
EventBus bus,
|
||||
ILogger<AnubisHost> logger,
|
||||
ServerOverrides? overrides = null) : BackgroundService
|
||||
{
|
||||
private readonly TimeSpan _interval = overrides?.DatabaseCheckInterval ?? TimeSpan.FromSeconds(5);
|
||||
private readonly Lock _gate = new();
|
||||
|
||||
// One step of the loop or one error-page choice at a time: a restore must not race the start that would follow it.
|
||||
private readonly SemaphoreSlim _exclusive = new(1, 1);
|
||||
private TaskCompletionSource _wake = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
private Database? _db;
|
||||
private Task? _schedulerLoop;
|
||||
private CancellationTokenSource? _schedulerStop;
|
||||
private volatile HostStatus _status = new(HostMode.Starting, null, null, clock.UtcNow, 0);
|
||||
private volatile AppServices? _services;
|
||||
|
||||
public StartupConfig Config { get; private set; } = initialConfig;
|
||||
|
||||
public bool IsDemo => options.Demo;
|
||||
|
||||
public HostStatus Status => _status;
|
||||
|
||||
/// <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>Asks the loop to check again now (after the wizard or an error-page choice).</summary>
|
||||
public void Wake()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_wake.TrySetResult();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Waits until the host reaches <paramref name="mode"/>; for tests and the CLI.</summary>
|
||||
public async Task WaitForAsync(HostMode mode, TimeSpan timeout)
|
||||
{
|
||||
using var cts = new CancellationTokenSource(timeout);
|
||||
while (_status.Mode != mode)
|
||||
{
|
||||
await Task.Delay(20, cts.Token).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Last time the database answered: the "Dati aggiornati" of the top bar.</summary>
|
||||
public DateTimeOffset? LastCheckUtc { get; private set; }
|
||||
|
||||
/// <summary>The scheduler loop is alive (health check).</summary>
|
||||
public bool SchedulerRunning => _schedulerLoop is { IsCompleted: false };
|
||||
|
||||
/// <summary>The database even when not ready (error-page choices need it to restore or import).</summary>
|
||||
internal Database? Database => _db;
|
||||
|
||||
/// <summary>Holds the loop still while an error-page choice works on the database.</summary>
|
||||
internal async Task<IDisposable> ExclusiveAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
await _exclusive.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
return new Releaser(_exclusive);
|
||||
}
|
||||
|
||||
private sealed class Releaser(SemaphoreSlim semaphore) : IDisposable
|
||||
{
|
||||
private int _released;
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _released, 1) == 0)
|
||||
{
|
||||
semaphore.Release();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public override void Dispose()
|
||||
{
|
||||
base.Dispose();
|
||||
_exclusive.Dispose();
|
||||
_schedulerStop?.Dispose();
|
||||
}
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
if (options.Demo)
|
||||
{
|
||||
LogDemo(logger, Config.Data.Root);
|
||||
}
|
||||
|
||||
while (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
Task wake;
|
||||
lock (_gate)
|
||||
{
|
||||
if (_wake.Task.IsCompleted)
|
||||
{
|
||||
_wake = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
}
|
||||
|
||||
wake = _wake.Task;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
using (await ExclusiveAsync(stoppingToken).ConfigureAwait(false))
|
||||
{
|
||||
await StepAsync(stoppingToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
break;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogStepFailed(logger, ex);
|
||||
SetStatus(HostMode.DatabaseUnavailable, Redactor.Redact(ex.Message));
|
||||
}
|
||||
|
||||
await Task.WhenAny(wake, Task.Delay(_interval, stoppingToken)).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await StopSchedulerAsync().ConfigureAwait(false);
|
||||
if (_db is not null)
|
||||
{
|
||||
await _db.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
return;
|
||||
}
|
||||
|
||||
if (_services is not null)
|
||||
{
|
||||
await CheckRunningAsync(cancellationToken).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
Config.Data.Ensure();
|
||||
|
||||
// A data folder that belongs to an installation never gets a new empty SQLite file by itself (trap 20).
|
||||
_db ??= Database.Open(Config.Db!, allowCreate: !File.Exists(Config.Data.InstallationFile));
|
||||
try
|
||||
{
|
||||
await _db.PingAsync(cancellationToken).ConfigureAwait(false);
|
||||
LastCheckUtc = clock.UtcNow;
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
SetStatus(HostMode.DatabaseUnavailable, Redactor.Redact(ex.Message));
|
||||
if (Config.Db!.Engine == DbEngine.Sqlite)
|
||||
{
|
||||
// Reopen next time: the file may come back, or the folder may be released.
|
||||
await _db.DisposeAsync().ConfigureAwait(false);
|
||||
_db = null;
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Identity first, migration after: a database that belongs elsewhere is never written to, and an empty one stays
|
||||
// empty, so a backup taken with an older schema can still be restored into it.
|
||||
var backups = new Backups(Config.Data, clock);
|
||||
IdentityCheck identity;
|
||||
try
|
||||
{
|
||||
var schema = await Migrations.StatusAsync(_db, cancellationToken).ConfigureAwait(false);
|
||||
if (schema.IsEmpty && File.Exists(Config.Data.InstallationFile))
|
||||
{
|
||||
identity = new IdentityCheck(IdentityVerdict.EmptyDatabase, Installation.ReadFile(Config.Data), null);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (schema.IsEmpty)
|
||||
{
|
||||
await MigrateAsync(backups, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
identity = await Installation.CheckAsync(_db, Config.Data, clock, cancellationToken).ConfigureAwait(false);
|
||||
if (identity.CanStart)
|
||||
{
|
||||
await MigrateAsync(backups, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (SchemaException ex)
|
||||
{
|
||||
SetStatus(HostMode.SchemaProblem, ex.Message);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!identity.CanStart)
|
||||
{
|
||||
SetStatus(HostMode.IdentityProblem, null, identity);
|
||||
return;
|
||||
}
|
||||
|
||||
var key = Config.SecretKey.GetOrCreateKey();
|
||||
var settings = new SettingsStore(_db, clock, bus, StartupOverrides());
|
||||
var secrets = new SecretStore(_db, clock, key, Config.EnvironmentKeys);
|
||||
var access = new AccessStore(_db, clock, secrets, PasswordIterations);
|
||||
if (options.Demo && identity.Verdict == IdentityVerdict.Created)
|
||||
{
|
||||
await DemoMode.SeedAsync(_db, Config.Data, clock, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (!await EnsureUserAsync(access, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
SetStatus(HostMode.FirstRun, null);
|
||||
return;
|
||||
}
|
||||
|
||||
var scheduler = new Scheduler(clock, bus);
|
||||
_services = new AppServices(_db, settings, secrets, access, backups, scheduler);
|
||||
StartScheduler(scheduler, backups);
|
||||
SetStatus(HostMode.Ready, null);
|
||||
}
|
||||
|
||||
private async Task MigrateAsync(Backups backups, CancellationToken cancellationToken)
|
||||
{
|
||||
var applied = await Migrations.MigrateAsync(_db!, clock, ct => backups.TakeAsync(_db!, "prima-della-migrazione", ct), cancellationToken).ConfigureAwait(false);
|
||||
if (applied > 0)
|
||||
{
|
||||
LogMigrated(logger, applied, Migrations.Latest);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<bool> EnsureUserAsync(AccessStore access, CancellationToken cancellationToken)
|
||||
{
|
||||
if (await access.HasUserAsync(cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
// While running: the database is checked every few seconds. If it stops answering, the error page shows and the
|
||||
// engine waits; when it answers again the installation is checked again (it might be another copy) and the
|
||||
// application resumes by itself.
|
||||
private async Task CheckRunningAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
await _db!.PingAsync(cancellationToken).ConfigureAwait(false);
|
||||
LastCheckUtc = clock.UtcNow;
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
if (_status.Mode != HostMode.DatabaseUnavailable)
|
||||
{
|
||||
LogLost(logger, Redactor.Redact(ex.Message));
|
||||
}
|
||||
|
||||
SetStatus(HostMode.DatabaseUnavailable, Redactor.Redact(ex.Message));
|
||||
return;
|
||||
}
|
||||
|
||||
if (_status.Mode == HostMode.Ready)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var identity = await Installation.CheckAsync(_db, Config.Data, clock, cancellationToken).ConfigureAwait(false);
|
||||
if (!identity.CanStart)
|
||||
{
|
||||
await StopSchedulerAsync().ConfigureAwait(false);
|
||||
_services = null;
|
||||
SetStatus(HostMode.IdentityProblem, null, identity);
|
||||
return;
|
||||
}
|
||||
|
||||
LogBack(logger);
|
||||
SetStatus(HostMode.Ready, null);
|
||||
}
|
||||
|
||||
/// <summary>After an error-page choice changed the database: forget the services so the next step starts over.</summary>
|
||||
internal async Task ResetAsync()
|
||||
{
|
||||
await StopSchedulerAsync().ConfigureAwait(false);
|
||||
_services = null;
|
||||
Wake();
|
||||
}
|
||||
|
||||
private void StartScheduler(Scheduler scheduler, Backups backups)
|
||||
{
|
||||
scheduler.Add(new ScheduledJob("backup", "Salvataggio del database", Schedule.Daily(new TimeOnly(3, 30), Config.TimeZone),
|
||||
async ct => await backups.TakeAsync(_db!, "notturno", ct).ConfigureAwait(false))
|
||||
{ MaxLateness = TimeSpan.FromHours(2) });
|
||||
_schedulerStop = new CancellationTokenSource();
|
||||
var token = _schedulerStop.Token;
|
||||
_schedulerLoop = Task.Run(async () =>
|
||||
{
|
||||
using var runs = bus.Subscribe<JobRun>();
|
||||
var recorder = RecordJobsAsync(runs, token);
|
||||
try
|
||||
{
|
||||
await scheduler.RunAsync(token).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException) when (token.IsCancellationRequested)
|
||||
{
|
||||
}
|
||||
|
||||
await recorder.ConfigureAwait(false);
|
||||
}, CancellationToken.None);
|
||||
}
|
||||
|
||||
// The jobs table keeps the outcome of the last run of each job (Diario e sistema, SPEC 13.6).
|
||||
private async Task RecordJobsAsync(EventSubscription<JobRun> runs, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
await foreach (var run in runs.ReadAllAsync(cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
try
|
||||
{
|
||||
await _db!.WriteAsync(async s =>
|
||||
{
|
||||
var description = _services?.Scheduler.Upcoming(100).FirstOrDefault(u => u.Name == run.Name)?.Description ?? run.Name;
|
||||
var updated = await s.ExecuteAsync(
|
||||
"UPDATE jobs SET last_due_at = @d, last_started_at = @s, last_finished_at = @f, last_outcome = @o, last_error = @e, updated_at = @f WHERE name = @n",
|
||||
("d", run.DueUtc), ("s", run.StartedUtc), ("f", run.FinishedUtc), ("o", run.Outcome.ToString().ToLowerInvariant()), ("e", run.Error), ("n", run.Name)).ConfigureAwait(false);
|
||||
if (updated == 0)
|
||||
{
|
||||
await s.ExecuteAsync(
|
||||
"INSERT INTO jobs (id, name, description, last_due_at, last_started_at, last_finished_at, last_outcome, last_error, created_at, updated_at) VALUES (@id, @n, @desc, @d, @s, @f, @o, @e, @f, @f)",
|
||||
("id", Ids.NewId(clock)), ("n", run.Name), ("desc", description), ("d", run.DueUtc), ("s", run.StartedUtc), ("f", run.FinishedUtc),
|
||||
("o", run.Outcome.ToString().ToLowerInvariant()), ("e", run.Error)).ConfigureAwait(false);
|
||||
}
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
LogJobRecordFailed(logger, ex, run.Name);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
private async Task StopSchedulerAsync()
|
||||
{
|
||||
if (_schedulerStop is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await _schedulerStop.CancelAsync().ConfigureAwait(false);
|
||||
if (_schedulerLoop is not null)
|
||||
{
|
||||
await _schedulerLoop.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
_schedulerStop.Dispose();
|
||||
_schedulerStop = null;
|
||||
_schedulerLoop = null;
|
||||
}
|
||||
|
||||
// Values of the startup configuration that also exist as settings are read-only in the interface (SPEC 13.5).
|
||||
private static Dictionary<string, StartupOverride> StartupOverrides() => [];
|
||||
|
||||
private void SetStatus(HostMode mode, string? detail, IdentityCheck? identity = null)
|
||||
{
|
||||
var previous = _status;
|
||||
var attempts = previous.Mode == mode ? previous.Attempts + 1 : 1;
|
||||
var since = previous.Mode == mode ? previous.Since : clock.UtcNow;
|
||||
_status = new HostStatus(mode, detail, identity, since, attempts);
|
||||
if (previous.Mode != mode)
|
||||
{
|
||||
LogMode(logger, mode);
|
||||
bus.Publish(new HostChanged(mode));
|
||||
}
|
||||
}
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Information, Message = "Mode: {Mode}")]
|
||||
private static partial void LogMode(ILogger logger, HostMode mode);
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Warning, Message = "Demo mode: separate database in {Folder}")]
|
||||
private static partial void LogDemo(ILogger logger, string folder);
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Information, Message = "Applied {Count} migrations, schema version {Version}")]
|
||||
private static partial void LogMigrated(ILogger logger, int count, int version);
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Error, Message = "Database lost: {Reason}")]
|
||||
private static partial void LogLost(ILogger logger, string reason);
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Information, Message = "Database back: resuming")]
|
||||
private static partial void LogBack(ILogger logger);
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Error, Message = "Startup step failed")]
|
||||
private static partial void LogStepFailed(ILogger logger, Exception exception);
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Warning, Message = "Could not record the run of job {Job}")]
|
||||
private static partial void LogJobRecordFailed(ILogger logger, Exception exception, string job);
|
||||
}
|
||||
Reference in new issue
Block a user