Files
Anubis/src/Anubis.Server/AnubisHost.cs
T
Alby96andClaude Opus 5.5 e9ac6dccc9 Phase 10: new course and Docker only
Record the course the user chose on 2 December 2026 and make the
container the only form of Anubis.

- ADR 0021-0026: new roadmap (phases 10-24, readings per phase, the
  spec-to-ADR table, merge and tag only after the user's yes),
  Docker only, maths-only decisions, bans turned into limits on margin
  accounts, eToro Demo as currency venue and forward tests, strategy
  championship. ROADMAP rewritten from phase 10; STATE, CLAUDE.md,
  SVILUPPO, README, API-NOTES and the manuals without the desktop.
- Remove the desktop: Anubis.Desktop, Anubis.Setup, deploy/windows,
  release-win and desktop-win, config.toml, PlatformKind,
  ANUBIS_PLATFORM, DPAPI with the ProtectedData package and the
  first-run wizard. Outside a container the server needs --data-dir,
  listens on 127.0.0.1 only and refuses foreign hosts; server and guard
  refuse --platform desktop with an Italian message and exit code 2.
  The demo keeps its key in a file and its error-page choices need no
  startup password. The diagnostics report says where the server runs
  from its own environment.
- Lighter image: restore and publish for linux-x64 only, and leave out
  the Windows libraries ONNX Runtime copies anyway (829 MB to 410 MB on
  disk, /app from 282 MB to 42 MB). Rotating Docker logs in the Unraid
  template, the manual and the compose; backtest and learning run as
  one-shot commands. tasks dev uses artifacts/dev-data.

refs #113 #114 #115 #78 #80 #81

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 17:35:17 +01:00

889 lines
37 KiB
C#

using Anubis.Access;
using Anubis.Backtest;
using Anubis.Core;
using Anubis.Data;
using Anubis.Db;
using Anubis.Demo;
using Anubis.Diagnostics;
using Anubis.Platform;
using Anubis.Supervision;
using Anubis.Trading;
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>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,
MarketDataService? MarketData = null, TradingService? Trading = null, Laboratory? Lab = null, TelegramServices? Telegram = null);
/// <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
{
/// <summary>A scheduler silent this long is stuck: the engine stops beating, so the guard steps in.</summary>
public static readonly TimeSpan SchedulerSilence = TimeSpan.FromMinutes(30);
private readonly AccessGuards _accessGuards = new(clock);
private readonly TimeSpan _interval = overrides?.DatabaseCheckInterval ?? TimeSpan.FromSeconds(5);
private readonly TimeSpan _tradingRetry = overrides?.TradingRetry ?? TimeSpan.FromMinutes(1);
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 MarketDataService? _market;
private TradingService? _trading;
private TelegramServices? _telegram;
private Laboratory? _lab;
private DiagnosticSampler? _sampler;
private volatile HostStatus _status = new(HostMode.Starting, null, null, clock.UtcNow, 0);
private volatile AppServices? _services;
public StartupConfig Config { get; } = initialConfig;
/// <summary>The channel to the guard that started this engine (SPEC 9.3); null without one.</summary>
public GuardLink? Guard { get; init; }
public bool IsDemo => options.Demo;
/// <summary>Where this server answers from, in plain Italian: the container, the demo or a development run (ADR 0022).</summary>
public string Where => options.Where;
public HostStatus Status => _status;
public IClock Clock => clock;
/// <summary>The running services; null until the first successful start.</summary>
public AppServices? Services => _status.Mode == HostMode.Ready ? _services : null;
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 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>SQLite, and the file of an installation that exists is not in its place.</summary>
internal bool SqliteFileMissing =>
Config.Db is { Engine: DbEngine.Sqlite, SqlitePath: { } path } && !File.Exists(path) && File.Exists(Config.Data.InstallationFile);
/// <summary>
/// For an error-page choice that writes into a missing SQLite file: the only place where a known installation gets a
/// new one. Called while the choice holds <see cref="ExclusiveAsync"/>.
/// </summary>
internal Database OpenForChoice()
{
if (_db is null)
{
_createdByChoice = SqliteFileMissing;
_db = Database.Open(Config.Db!, allowCreate: _createdByChoice);
}
return _db;
}
private bool _createdByChoice;
/// <summary>
/// A choice that failed or was cut halfway leaves nothing open that could create the missing file, and what it had
/// begun to write steps aside, moved and not deleted. In the meantime the true file may have come back: that one is
/// not touched, and the loop finds it.
/// </summary>
internal async Task AbandonChoiceAsync()
{
if (!_createdByChoice || _db is null)
{
return;
}
await _db.DisposeAsync().ConfigureAwait(false);
_db = null;
_createdByChoice = false;
var path = Config.Db!.SqlitePath!;
if (!File.Exists(path) || !await IsLeftoverAsync().ConfigureAwait(false))
{
return;
}
var aside = path + ".incompleto-" + clock.UtcNow.ToString("yyyyMMdd-HHmmss", System.Globalization.CultureInfo.InvariantCulture);
foreach (var part in new[] { "", "-wal", "-shm" })
{
try
{
if (File.Exists(path + part))
{
File.Move(path + part, aside + part, overwrite: true);
}
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
LogStepFailed(logger, ex);
}
}
}
/// <summary>
/// A file a choice left halfway: without an installation, or with the sealed one of an import not renewed yet. One
/// that cannot be read is not certainly that.
/// </summary>
private async Task<bool> IsLeftoverAsync()
{
try
{
await using var db = Database.Open(Config.Db!, allowCreate: false);
if ((await Migrations.StatusAsync(db, CancellationToken.None).ConfigureAwait(false)).IsEmpty)
{
return true;
}
var row = await Installation.ReadRowAsync(db, CancellationToken.None).ConfigureAwait(false);
return row is null ? !await Installation.HasDataAsync(db, CancellationToken.None).ConfigureAwait(false)
: row.ProtectedRestart && row.Fingerprint != Installation.ReadFile(Config.Data)?.Fingerprint;
}
catch (Exception ex) when (ex is System.Data.Common.DbException or IOException or UnauthorizedAccessException or InvalidOperationException or InvalidDataException)
{
LogStepFailed(logger, ex);
return false;
}
}
/// <summary>The choice is done: the database it opened is the one in use.</summary>
internal void KeepChoice() => _createdByChoice = false;
/// <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);
}
// From the first moment: every exception and every outbound call of the process is counted (issue #95).
ExceptionCounter.Start();
_ = HttpCallMeter.Shared;
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));
}
// With trading the beat of a running engine comes from the trading loop, so a blocked loop is noticed.
if (_status.Mode != HostMode.Ready || _trading is null)
{
Guard?.Beat();
}
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)
{
if (!Config.IsComplete)
{
SetStatus(HostMode.ConfigProblem, null);
return;
}
if (_services is not null)
{
await CheckRunningAsync(cancellationToken).ConfigureAwait(false);
return;
}
Config.Data.Ensure();
Guard?.Step("database");
// 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)
{
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;
}
if (SqliteFileMissing)
{
// SPEC 15.1: without the file the user may restore, import or start over, as with an empty database. The
// file is created only by that choice, and a file that comes back meanwhile is used without one.
SetStatus(HostMode.IdentityProblem, Redactor.Redact(ex.Message), new IdentityCheck(IdentityVerdict.EmptyDatabase, Installation.ReadFile(Config.Data), null));
return;
}
SetStatus(HostMode.DatabaseUnavailable, Redactor.Redact(ex.Message));
return;
}
Guard?.Step("migrazioni e identità");
// 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, Redactor.Redact(ex.Message));
return;
}
if (!identity.CanStart)
{
SetStatus(HostMode.IdentityProblem, null, identity);
return;
}
Guard?.Step("servizi");
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, _accessGuards);
if (options.Demo && identity.Verdict == IdentityVerdict.Created)
{
await DemoMode.SeedAsync(_db, Config.Data, clock, cancellationToken).ConfigureAwait(false);
}
await EnsureUserAsync(access, cancellationToken).ConfigureAwait(false);
var scheduler = new Scheduler(clock, bus);
// The guard drill's engine: prices from the drill's local OKX, and then nothing else leaves the computer either
// (no news, no model, no other source: ADR 0016). Honored only under a guard, like the drill's OKX itself.
var drill = Guard is null ? null : GuardDrill.DrillOkx(environment);
_market = MarketDataEnabled
? new MarketDataService(_db, clock, bus, settings, secrets, Config.Data, overrides?.MarketHttp, overrides?.MarketSockets, logger, drill,
offline: drill is not null)
: null;
_trading = TradingEnabled && (identity.File ?? Installation.ReadFile(Config.Data)) is { } file
? new TradingService(_db, clock, bus, secrets, _market, new FxStore(_db, clock), TradingConsent.From(Config), file.InstallationId,
overrides?.MarketHttp, overrides?.MarketSockets, logger, settings, (password, code, ct) => access.ReauthenticateAsync(password, code, ct),
Path.Combine(Config.Data.Root, "STOP"))
{
Guard = Guard,
GuardFiles = Guard is null ? null : new GuardPaths(Config.Data.Root),
// The drill's fault is honored only under a guard, which never passes it to an engine it restarts.
Fault = Guard is null ? null : environment.GetValueOrDefault(GuardChannel.FaultVariable),
// The decisions run in the scheduler: a scheduler silent for half an hour is stuck (its longest jobs take
// minutes), and the guard must hear it (SPEC 9.3).
OthersAlive = () => scheduler.LastBeatUtc is not { } beat || clock.UtcNow - beat < SchedulerSilence,
}
: null;
if (_trading is not null)
{
// Before "ready": the Strategie page must never show a strategy without its backtest outcome (SPEC 12.3).
// A failure here is logged and left to the trading start, which repeats it: the interface still opens.
try
{
await _trading.PrepareAsync(cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
LogTradingFailed(logger, ex);
}
}
// The laboratory computes on its own thread and reads only local data; the demo shows appendix F and runs none.
_lab = options.Demo ? null : new Laboratory(_db, clock, Config.Data.Research, logger);
if (_lab is { } laboratory && _trading is { } running && _market is { } market)
{
var review = new QuarterlyReview(_db, clock, laboratory, running.Stages, running.Learning, Config.Data.Research, market.PrepareReviewHistoryAsync, logger);
laboratory.ReviewTrialEnded = review.ConcludeAsync;
running.QuarterlyReview = review.RunIfDueAsync;
}
// Telegram and the sign of life (SPEC 14): not in the demo, and in tests only with their fake network.
_telegram = options.Demo || (overrides is not null && overrides.TelegramHttp is null)
? null
: new TelegramServices(this, _db, clock, settings, secrets, Config.HeartbeatUrl, overrides?.TelegramHttp, logger);
_services = new AppServices(_db, settings, secrets, access, backups, scheduler, _market, _trading, _lab, _telegram);
// The data for the analysis of a long run (issue #95, ADR 0013); the demo has nothing to analyse.
_sampler = options.Demo ? null : new DiagnosticSampler(_db, clock, HttpCallMeter.Shared);
// Before the scheduler writes its first run: how long the bot was away, and which runs it missed (SPEC 5.6).
var lastDues = new Dictionary<string, DateTimeOffset>(StringComparer.Ordinal);
try
{
if (!options.Demo)
{
await new AbsenceBook(_db, clock) { Zone = Config.TimeZone }.RecordAsync(cancellationToken).ConfigureAwait(false);
}
foreach (var (name, due) in await _db.ReadAsync(s => s.QueryAsync("SELECT name, last_due_at FROM jobs WHERE last_due_at IS NOT NULL",
r => (r.Text("name"), r.Moment("last_due_at"))), cancellationToken).ConfigureAwait(false))
{
lastDues[name] = due;
}
if (!options.Demo)
{
await StartCountingAsync([.. SchedulerJobs(backups)], lastDues, cancellationToken).ConfigureAwait(false);
}
if (_sampler is not null)
{
await _sampler.TakeAsync(SampleKinds.Start, cancellationToken).ConfigureAwait(false);
}
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
LogStepFailed(logger, ex);
}
StartScheduler(scheduler, backups, lastDues);
SetStatus(HostMode.Ready, null);
}
internal async Task MigrateAsync(Backups backups, CancellationToken cancellationToken)
{
// SPEC 9.4: after a migration that failed the engine stays off. It is not tried again by itself, because every
// attempt would take one more backup; the user tries again from the error page or with a restart.
if (MigrationFailed is { } failed)
{
throw new SchemaException(failed);
}
int applied;
try
{
applied = await Migrations.MigrateAsync(_db!, clock, ct => backups.TakeAsync(_db!, Backups.BeforeMigration, ct), cancellationToken).ConfigureAwait(false);
}
catch (SchemaException ex) when (ex.InnerException is not null)
{
LogMigrationFailed(logger, ex);
MigrationFailed = ex.Message;
throw;
}
if (applied > 0)
{
LogMigrated(logger, applied, Migrations.Latest);
}
}
// 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;
}
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;
}
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
// 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. Called while
/// the choice still holds <see cref="ExclusiveAsync"/>.
/// </summary>
internal async Task ResetAsync()
{
await StopSchedulerAsync().ConfigureAwait(false);
_services = null;
SetStatus(HostMode.Starting, null);
Wake();
}
/// <summary>Stops and rebuilds the services, so that new broker keys take effect: a few seconds of "avvio".</summary>
internal async Task RestartServicesAsync(CancellationToken cancellationToken)
{
using (await ExclusiveAsync(cancellationToken).ConfigureAwait(false))
{
await ResetAsync().ConfigureAwait(false);
}
}
/// <summary>
/// Market data needs the network: off in demo mode (SPEC 13.7), when <c>ANUBIS_MARKET_DATA</c> is <c>off</c>, and
/// in tests unless they bring their own fake network.
/// </summary>
private bool MarketDataEnabled =>
!options.Demo && overrides?.MarketData != false &&
environment.GetValueOrDefault("ANUBIS_MARKET_DATA") is not ("0" or "off" or "false");
/// <summary>
/// Accounts and orders: off in demo mode (the demo shows appendix F and sends nothing), when
/// <c>ANUBIS_TRADING</c> is <c>off</c>, and in tests unless they ask for it.
/// </summary>
private bool TradingEnabled =>
!options.Demo && (overrides is null ? true : overrides.Trading == true) &&
environment.GetValueOrDefault("ANUBIS_TRADING") is not ("0" or "off" or "false");
private IEnumerable<ScheduledJob> SchedulerJobs(Backups backups)
{
// A backup missed while the bot was off is taken once at the restart, whenever it comes (SPEC 5.6).
var backup = 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), CatchUpWithin = TimeSpan.FromDays(3650) };
return new[] { backup }.Concat(_sampler is { } sampler ? new[] { sampler.Job() } : []).Concat(_market?.Jobs() ?? []).Concat(_trading?.Jobs() ?? []).Concat(_telegram?.Jobs() ?? []);
}
/// <summary>
/// A job to make up for after an absence counts from the first start that knows it. Otherwise a computer always off at
/// its hour would never make it: without a first run there would be no run to find missed (SPEC 5.6).
/// </summary>
private Task StartCountingAsync(IReadOnlyList<ScheduledJob> jobs, Dictionary<string, DateTimeOffset> lastDues, CancellationToken cancellationToken) => _db!.WriteAsync(async s =>
{
foreach (var job in jobs.Where(j => j.CatchUpWithin is not null && !lastDues.ContainsKey(j.Name)))
{
await s.ExecuteAsync("INSERT INTO jobs (id, name, description, last_due_at, created_at, updated_at) VALUES (@id, @n, @d, @now, @now, @now) ON CONFLICT (name) DO NOTHING", cancellationToken,
("id", Ids.NewId(clock)), ("n", job.Name), ("d", job.Description), ("now", clock.UtcNow)).ConfigureAwait(false);
}
}, cancellationToken);
private void StartScheduler(Scheduler scheduler, Backups backups, Dictionary<string, DateTimeOffset> lastDues)
{
foreach (var job in SchedulerJobs(backups))
{
scheduler.Add(job, lastDues.TryGetValue(job.Name, out var due) ? due : null);
}
_schedulerStop = new CancellationTokenSource();
var token = _schedulerStop.Token;
var market = _market;
var trading = _trading;
var lab = _lab;
var telegram = _telegram;
_schedulerLoop = Task.Run(async () =>
{
using var runs = bus.Subscribe<JobRun>();
var recorder = RecordJobsAsync(runs, token);
var collecting = market is null ? Task.CompletedTask : RunMarketDataAsync(market, token);
var dealing = trading is null ? Task.CompletedTask : RunTradingAsync(trading, token);
var testing = lab is null ? Task.CompletedTask : RunLabAsync(lab, token);
var writing = telegram is null ? Task.CompletedTask : RunTelegramAsync(telegram, token);
try
{
await scheduler.RunAsync(token).ConfigureAwait(false);
}
catch (OperationCanceledException) when (token.IsCancellationRequested)
{
}
await collecting.ConfigureAwait(false);
await dealing.ConfigureAwait(false);
await testing.ConfigureAwait(false);
await writing.ConfigureAwait(false);
await recorder.ConfigureAwait(false);
}, CancellationToken.None);
}
private async Task RunMarketDataAsync(MarketDataService market, CancellationToken cancellationToken)
{
try
{
await market.RunAsync(cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
}
catch (Exception ex)
{
LogMarketDataFailed(logger, ex);
}
}
private async Task RunLabAsync(Laboratory lab, CancellationToken cancellationToken)
{
try
{
await lab.RunAsync(cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
}
catch (Exception ex)
{
LogLabFailed(logger, ex);
}
}
private async Task RunTelegramAsync(TelegramServices telegram, CancellationToken cancellationToken)
{
try
{
await telegram.RunAsync(cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
}
catch (Exception ex)
{
LogTelegramFailed(logger, ex);
}
}
private async Task RunTradingAsync(TradingService trading, CancellationToken cancellationToken)
{
try
{
while (!await TryStartAsync(trading, cancellationToken).ConfigureAwait(false))
{
await Task.Delay(_tradingRetry, cancellationToken).ConfigureAwait(false);
}
await trading.RunAsync(cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
}
catch (Exception ex)
{
LogTradingFailed(logger, ex);
}
}
private async Task<bool> TryStartAsync(TradingService trading, CancellationToken cancellationToken)
{
try
{
await trading.StartAsync(cancellationToken).ConfigureAwait(false);
return true;
}
catch (Exception ex) when (ex is not OperationCanceledException || !cancellationToken.IsCancellationRequested)
{
LogTradingStartFailed(logger, ex, _tradingRetry);
return false;
}
}
// 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 = run.Description ?? _services?.Scheduler.Upcoming(100).FirstOrDefault(u => u.Name == run.Name)?.Description ?? run.Name;
if (AbsenceBook.MissedLine(run with { Description = description }, Config.TimeZone) is { } line)
{
await Diary.WriteAsync(s, clock, DiaryKinds.System, run.Outcome == JobOutcome.Completed ? "job_recovered" : "job_skipped", line,
new { job = run.Name, due = run.DueUtc }, cancellationToken).ConfigureAwait(false);
}
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);
}
// Every run, for the lateness and the durations in the diagnostics report (issue #95).
await s.ExecuteAsync(
"INSERT INTO job_runs (id, job, due_at, started_at, finished_at, outcome, missed, error, created_at) VALUES (@id, @n, @d, @s, @f, @o, @m, @e, @f)",
("id", Ids.NewId(clock)), ("n", run.Name), ("d", run.DueUtc), ("s", run.StartedUtc), ("f", run.FinishedUtc),
("o", run.Outcome.ToString().ToLowerInvariant()), ("m", run.Missed), ("e", run.Error is null ? null : Redactor.Redact(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;
_market?.Dispose();
_market = null;
_trading?.Dispose();
_trading = null;
_lab?.Dispose();
_lab = null;
_telegram?.Dispose();
_telegram = 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 (mode == HostMode.Ready)
{
// Trading tells the guard by itself when its own startup steps are done.
if (_trading is null || _trading.IsStarted)
{
Guard?.Set(GuardStages.Running);
}
}
else
{
Guard?.Set(mode == HostMode.Starting ? GuardStages.Starting : GuardStages.Waiting);
}
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.Error, Message = "Migration failed: the engine stays off until the user tries again")]
private static partial void LogMigrationFailed(ILogger logger, Exception exception);
[LoggerMessage(Level = LogLevel.Information, Message = "Applied {Count} migrations, schema version {Version}")]
private static partial void LogMigrated(ILogger logger, int count, int version);
[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.Error, Message = "Market data stopped")]
private static partial void LogMarketDataFailed(ILogger logger, Exception exception);
[LoggerMessage(Level = LogLevel.Error, Message = "Telegram stopped")]
private static partial void LogTelegramFailed(ILogger logger, Exception exception);
[LoggerMessage(Level = LogLevel.Error, Message = "Laboratory stopped")]
private static partial void LogLabFailed(ILogger logger, Exception exception);
[LoggerMessage(Level = LogLevel.Error, Message = "Trading stopped")]
private static partial void LogTradingFailed(ILogger logger, Exception exception);
[LoggerMessage(Level = LogLevel.Error, Message = "Trading could not start: tried again in {Delay}")]
private static partial void LogTradingStartFailed(ILogger logger, Exception exception, TimeSpan delay);
[LoggerMessage(Level = LogLevel.Warning, Message = "Could not record the run of job {Job}")]
private static partial void LogJobRecordFailed(ILogger logger, Exception exception, string job);
}