News, the economic calendar and earnings dates no longer change any decision (ADR 0023, choices in ADR 0027). The outside rules are measured in the shadow; a switch in the settings turns them back on. refs #116, refs #117 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
571 lines
29 KiB
C#
571 lines
29 KiB
C#
using System.Net.WebSockets;
|
|
using System.Reflection;
|
|
using System.Security.Cryptography;
|
|
using System.Text;
|
|
using System.Text.Json;
|
|
using Anubis.Access;
|
|
using Anubis.Core;
|
|
using Anubis.Data;
|
|
using Anubis.Db;
|
|
using Anubis.Platform;
|
|
using Microsoft.AspNetCore.Antiforgery;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
|
|
namespace Anubis.Server;
|
|
|
|
/// <summary>Answer of <c>GET /health</c>.</summary>
|
|
internal sealed record HealthResponse(string Status, string Name, string Version, string? Mode = null, IReadOnlyDictionary<string, string>? Checks = null);
|
|
|
|
internal sealed record SettingBody(string Value);
|
|
|
|
/// <summary>
|
|
/// The REST and WebSocket skeleton (issue #12) and the form actions of the service pages. The API answers JSON with
|
|
/// Italian messages, needs a session, and every request that changes something carries the CSRF token in a header.
|
|
/// </summary>
|
|
internal static partial class Endpoints
|
|
{
|
|
public const string CsrfHeader = "X-Anubis-Csrf";
|
|
|
|
private static readonly JsonSerializerOptions _json = new(JsonSerializerDefaults.Web);
|
|
|
|
public static void Map(WebApplication app)
|
|
{
|
|
app.MapGet("/health", HealthAsync).AllowAnonymous();
|
|
app.MapGet("/brand/{file}", Brand).AllowAnonymous();
|
|
app.MapGet("/assets/{file}", Asset).AllowAnonymous();
|
|
app.MapGet("/favicon.ico", () => Brand("anubis.ico")).AllowAnonymous();
|
|
|
|
MapApi(app);
|
|
app.Map("/ws", StatusSocketAsync).RequireAuthorization();
|
|
Forms.Map(app);
|
|
}
|
|
|
|
// Healthy only when the database answers, the loops turn and the prices arrive (SPEC 15.2); the body says why not.
|
|
private static async Task<IResult> HealthAsync(AnubisHost host, CancellationToken cancellationToken)
|
|
{
|
|
var status = host.Status;
|
|
var checks = new Dictionary<string, string>(StringComparer.Ordinal) { ["mode"] = status.Mode.ToString() };
|
|
var healthy = status.Mode == HostMode.Ready;
|
|
if (host.Services is { } services)
|
|
{
|
|
try
|
|
{
|
|
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
|
timeout.CancelAfter(TimeSpan.FromSeconds(5));
|
|
await services.Db.PingAsync(timeout.Token).ConfigureAwait(false);
|
|
checks["database"] = "ok";
|
|
}
|
|
catch (Exception ex) when (ex is not OperationCanceledException || !cancellationToken.IsCancellationRequested)
|
|
{
|
|
checks["database"] = "non risponde";
|
|
healthy = false;
|
|
}
|
|
|
|
checks["scheduler"] = host.SchedulerRunning ? "ok" : "fermo";
|
|
healthy &= host.SchedulerRunning;
|
|
var (loop, loopOk) = HealthRules.Loop(host.Clock.UtcNow, services.Trading is null ? null : status.Since, services.Trading is { IsStarted: true },
|
|
services.Trading is { StartFailed: true }, services.Trading?.LastTurnAt);
|
|
var (feed, feedOk) = HealthRules.Feed(host.Clock.UtcNow, services.MarketData?.LiveFeed.Since, services.MarketData?.LiveFeed.LastDataAt);
|
|
checks["motore"] = loop;
|
|
checks["dati"] = feed;
|
|
healthy &= loopOk && feedOk;
|
|
}
|
|
|
|
var body = new HealthResponse(healthy ? "ok" : "unavailable", AnubisInfo.Name, AnubisInfo.Version, status.Mode.ToString(), checks);
|
|
return Results.Json(body, _json, statusCode: healthy ? StatusCodes.Status200OK : StatusCodes.Status503ServiceUnavailable);
|
|
}
|
|
|
|
// The logo comes only from docs/design/logo, embedded at build time (ADR 0005).
|
|
private static IResult Brand(string file) => Embedded("Anubis.Server.Brand." + file, file);
|
|
|
|
private static IResult Asset(string file) => Embedded("Anubis.Server.Assets." + file, file);
|
|
|
|
private static IResult Embedded(string resource, string file)
|
|
{
|
|
var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resource);
|
|
if (stream is null)
|
|
{
|
|
return Results.NotFound();
|
|
}
|
|
|
|
var type = Path.GetExtension(file) switch
|
|
{
|
|
".svg" => "image/svg+xml",
|
|
".png" => "image/png",
|
|
".ico" => "image/x-icon",
|
|
".css" => "text/css; charset=utf-8",
|
|
".js" => "text/javascript; charset=utf-8",
|
|
".ttf" => "font/ttf",
|
|
".txt" => "text/plain; charset=utf-8",
|
|
_ => "application/octet-stream",
|
|
};
|
|
return Results.Stream(stream, type);
|
|
}
|
|
|
|
private static void MapApi(WebApplication app)
|
|
{
|
|
var api = app.MapGroup("/api").RequireAuthorization().AddEndpointFilter(CsrfFilterAsync);
|
|
|
|
api.MapGet("/antiforgery", (HttpContext context, IAntiforgery antiforgery) =>
|
|
{
|
|
var tokens = antiforgery.GetAndStoreTokens(context);
|
|
return Results.Json(new { header = CsrfHeader, token = tokens.RequestToken }, _json);
|
|
});
|
|
|
|
api.MapGet("/status", async (AnubisHost host, ShellData shell, CancellationToken ct) => Results.Json(await shell.SnapshotAsync(ct).ConfigureAwait(false), _json));
|
|
|
|
api.MapGet("/me", (HttpContext context) => Results.Json(new
|
|
{
|
|
username = context.User.Identity?.Name,
|
|
mustChangePassword = CurrentUser.MustChangePassword(context.User),
|
|
hasSecondFactor = CurrentUser.HasSecondFactor(context.User),
|
|
}, _json));
|
|
|
|
api.MapGet("/settings", async (AnubisHost host, CancellationToken ct) =>
|
|
{
|
|
var services = host.Services!;
|
|
var values = new List<SettingValue>();
|
|
foreach (var definition in SettingsStore.All)
|
|
{
|
|
values.Add(await services.Settings.GetAsync(definition.Key, ct).ConfigureAwait(false));
|
|
}
|
|
|
|
return Results.Json(values, _json);
|
|
});
|
|
|
|
api.MapPut("/settings/{key}", async (string key, SettingBody body, AnubisHost host, HttpContext context, CancellationToken ct) =>
|
|
{
|
|
if (key == SettingsStore.BotState.Key)
|
|
{
|
|
return Error(StatusCodes.Status400BadRequest, "usa_i_comandi", "Lo stato del bot si cambia con pausa, ripresa e Ferma tutto.");
|
|
}
|
|
|
|
// Risk limits go only through the settings page, which checks their order and asks for the confirmation of
|
|
// SPEC 12.4 when a limit goes up while a strategy uses real money: the check holds on the API too.
|
|
if (Anubis.Risk.RiskSettings.All.Any(d => d.Key == key))
|
|
{
|
|
return Error(StatusCodes.Status400BadRequest, "usa_le_impostazioni", "I limiti di rischio si cambiano da Impostazioni, con la conferma quando servono soldi veri.");
|
|
}
|
|
|
|
// The same for what lets the model shrink less.
|
|
if (Anubis.Learning.LearningSettings.All.Any(d => d.Key == key))
|
|
{
|
|
return Error(StatusCodes.Status400BadRequest, "usa_le_impostazioni", "Le soglie del modello si cambiano da Impostazioni, con la conferma quando servono soldi veri.");
|
|
}
|
|
|
|
// And for the rules of the news, and where the model's key goes: the page asks for the password.
|
|
if (Anubis.News.NewsRuleSettings.All.Any(d => d.Key == key) || Anubis.News.NewsModelSettings.All.Any(d => d.Key == key) || key == Anubis.News.ExternalRules.Setting.Key)
|
|
{
|
|
return Error(StatusCodes.Status400BadRequest, "usa_le_impostazioni", "Le regole delle notizie e il modello linguistico si cambiano da Impostazioni, con la password quando serve.");
|
|
}
|
|
|
|
return await SetSettingAsync(host, key, body.Value, context, ct).ConfigureAwait(false);
|
|
});
|
|
|
|
api.MapGet("/settings/history", async (AnubisHost host, CancellationToken ct) =>
|
|
Results.Json(await host.Services!.Settings.HistoryAsync(null, 100, ct).ConfigureAwait(false), _json));
|
|
|
|
// Data quality report (SPEC 6.4): JSON, or Markdown with ?format=md.
|
|
api.MapGet("/data/quality", async (AnubisHost host, IClock clock, int? days, string? format, CancellationToken ct) =>
|
|
{
|
|
var report = await QualityReport.BuildAsync(host.Services!.Db, clock, TimeSpan.FromDays(Math.Clamp(days ?? 7, 1, 3650)), ct).ConfigureAwait(false);
|
|
return format == "md" ? Results.Text(report.ToMarkdown(), "text/markdown; charset=utf-8") : Results.Json(report, _json);
|
|
});
|
|
|
|
// The open positions of the Conti screen as CSV (SPEC 13.6), all accounts or one broker's.
|
|
api.MapGet("/conti/posizioni.csv", async (AnubisHost host, ShellData shell, IClock clock, string? conto, CancellationToken ct) =>
|
|
{
|
|
var view = await AccountsView.LoadAsync(host.Services!, clock, shell.Zone, ct).ConfigureAwait(false);
|
|
var broker = conto is Anubis.Data.Venues.Okx or Anubis.Data.Venues.Alpaca ? conto : null;
|
|
var day = TimeZoneInfo.ConvertTime(clock.UtcNow, shell.Zone).ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
|
|
return Results.File(System.Text.Encoding.UTF8.GetPreamble().Concat(System.Text.Encoding.UTF8.GetBytes(view.Csv(broker))).ToArray(),
|
|
"text/csv; charset=utf-8", $"anubis-posizioni-{day}.csv");
|
|
});
|
|
|
|
// The closed trades of the Operazioni screen as CSV (SPEC 13.6), with the same filters as the page.
|
|
api.MapGet("/operazioni.csv", async (AnubisHost host, ShellData shell, IClock clock, string? cerca, string? conto, string? strategia, string? esito, string? periodo,
|
|
CancellationToken ct) =>
|
|
{
|
|
var filter = TradeFilter.Parse(cerca, conto, strategia, esito, periodo, null);
|
|
var view = await TradesView.LoadAsync(host.Services!, clock, filter, int.MaxValue, ct).ConfigureAwait(false);
|
|
var day = TimeZoneInfo.ConvertTime(clock.UtcNow, shell.Zone).ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
|
|
return Results.File(System.Text.Encoding.UTF8.GetPreamble().Concat(System.Text.Encoding.UTF8.GetBytes(view.Csv())).ToArray(),
|
|
"text/csv; charset=utf-8", $"anubis-operazioni-{day}.csv");
|
|
});
|
|
|
|
// The operations for the tax return (SPEC 4.6, 13.5): one world and one Italian year, or all of them.
|
|
api.MapGet("/dichiarazione.csv", async (AnubisHost host, IClock clock, string? anno, string? mondo, string? dettaglio, CancellationToken ct) =>
|
|
{
|
|
int? year = null;
|
|
if (!string.IsNullOrEmpty(anno) && anno != "tutti")
|
|
{
|
|
if (!int.TryParse(anno, System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out var parsed) || parsed is < 1999 or > 9999)
|
|
{
|
|
return Error(StatusCodes.Status400BadRequest, "valore_non_valido", "L'anno non è valido.");
|
|
}
|
|
|
|
year = parsed;
|
|
}
|
|
|
|
if (mondo is not (null or "" or "reale" or "simulazione") || dettaglio is not (null or "" or "lotti"))
|
|
{
|
|
return Error(StatusCodes.Status400BadRequest, "valore_non_valido", "La scelta non è valida.");
|
|
}
|
|
|
|
var world = mondo == "reale" ? Anubis.Trading.Worlds.Real : Anubis.Trading.Worlds.Simulated;
|
|
var services = host.Services!;
|
|
var method = Anubis.Trading.TaxExport.Method((await services.Settings.GetAsync(Anubis.Trading.TaxExport.MethodSetting.Key, ct).ConfigureAwait(false)).Value);
|
|
var report = await Anubis.Trading.TaxExport.LoadAsync(services.Db, world, year, method, ct).ConfigureAwait(false);
|
|
var name = $"anubis-dichiarazione-{year?.ToString(System.Globalization.CultureInfo.InvariantCulture) ?? "tutti"}{(dettaglio == "lotti" ? "-lotti" : "")}{(world == Anubis.Trading.Worlds.Real ? "" : "-simulazione")}.csv";
|
|
return Results.File(dettaglio == "lotti" ? report.LotsCsv() : report.Csv(), "text/csv; charset=utf-8", name);
|
|
});
|
|
|
|
// The technical logs of the data folder as one zip (SPEC 13.6, "Diario e sistema"). They are redacted when
|
|
// written (JsonLog); only the files the log writer names, read while it keeps writing the newest one.
|
|
api.MapGet("/registri.zip", (AnubisHost host, ShellData shell, IClock clock) =>
|
|
{
|
|
var folder = host.Config.Data.Logs;
|
|
var day = TimeZoneInfo.ConvertTime(clock.UtcNow, shell.Zone).ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
|
|
return Results.File(LogArchive(folder), "application/zip", $"anubis-registri-{day}.zip");
|
|
});
|
|
|
|
// The data collected for the analysis of a long run, as one Markdown report to paste (issue #95, ADR 0013).
|
|
// 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, 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");
|
|
});
|
|
|
|
// The external sources and the live feed: what is on, what is off and why (SPEC 4.4).
|
|
api.MapGet("/data/sources", async (AnubisHost host, IClock clock, CancellationToken ct) =>
|
|
{
|
|
var services = host.Services!;
|
|
var market = services.MarketData;
|
|
return Results.Json(new
|
|
{
|
|
enabled = market is not null,
|
|
live = market?.LiveConnected ?? false,
|
|
lastHistoryRun = market?.LastHistoryRun,
|
|
sources = await new SourceStateStore(services.Db, clock).ListAsync(ct).ConfigureAwait(false),
|
|
freshness = market?.Freshness.Snapshot() ?? [],
|
|
}, _json);
|
|
});
|
|
|
|
// Only whether a secret is set and where it comes from: the value never leaves the server (SPEC 15.4).
|
|
api.MapGet("/secrets/{name}", async (string name, AnubisHost host, CancellationToken ct) =>
|
|
Results.Json(await host.Services!.Secrets.StatusAsync(name, ct).ConfigureAwait(false), _json));
|
|
|
|
api.MapPost("/bot/{command}", async (string command, AnubisHost host, HttpContext context, CancellationToken ct) =>
|
|
{
|
|
var (ok, message) = await BotCommandAsync(host, command, context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false);
|
|
return ok ? Results.Json(new { state = message }, _json) : Error(StatusCodes.Status409Conflict, "comando_non_ammesso", message);
|
|
});
|
|
|
|
api.MapGet("/jobs", async (AnubisHost host, CancellationToken ct) =>
|
|
{
|
|
var services = host.Services!;
|
|
var last = await services.Db.ReadAsync(s => s.QueryAsync(
|
|
"SELECT name, description, last_due_at, last_finished_at, last_outcome, last_error FROM jobs ORDER BY name",
|
|
r => new
|
|
{
|
|
name = r.Text("name"),
|
|
description = r.Text("description"),
|
|
lastDue = r.MomentOrNull("last_due_at"),
|
|
lastFinished = r.MomentOrNull("last_finished_at"),
|
|
outcome = r.TextOrNull("last_outcome"),
|
|
error = r.TextOrNull("last_error")
|
|
}), ct).ConfigureAwait(false);
|
|
return Results.Json(new { upcoming = services.Scheduler.Upcoming(20), last }, _json);
|
|
});
|
|
}
|
|
|
|
internal static IResult Error(int status, string code, string message) => Results.Json(new ApiError(code, message), _json, statusCode: status);
|
|
|
|
/// <summary>The daily log files (anubis-*.log) of a folder in a zip, newest first; an empty zip when there are none yet.</summary>
|
|
internal static byte[] LogArchive(string folder)
|
|
{
|
|
using var buffer = new MemoryStream();
|
|
using (var zip = new System.IO.Compression.ZipArchive(buffer, System.IO.Compression.ZipArchiveMode.Create, leaveOpen: true))
|
|
{
|
|
var files = Directory.Exists(folder) ? Directory.EnumerateFiles(folder, "anubis-*.log").OrderDescending(StringComparer.Ordinal).ToList() : [];
|
|
foreach (var file in files)
|
|
{
|
|
try
|
|
{
|
|
using var source = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
|
|
var entry = zip.CreateEntry(Path.GetFileName(file), System.IO.Compression.CompressionLevel.Optimal);
|
|
using var target = entry.Open();
|
|
source.CopyTo(target);
|
|
}
|
|
catch (IOException)
|
|
{
|
|
// A file removed by the rotation in the meantime: the others still go.
|
|
}
|
|
}
|
|
}
|
|
|
|
return buffer.ToArray();
|
|
}
|
|
|
|
private static async ValueTask<object?> CsrfFilterAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next)
|
|
{
|
|
var http = context.HttpContext;
|
|
if (!HttpMethods.IsGet(http.Request.Method) && !HttpMethods.IsHead(http.Request.Method))
|
|
{
|
|
var antiforgery = http.RequestServices.GetRequiredService<IAntiforgery>();
|
|
if (!await antiforgery.IsRequestValidAsync(http).ConfigureAwait(false))
|
|
{
|
|
return Error(StatusCodes.Status400BadRequest, "csrf", "Richiesta senza il gettone di sicurezza: ricarica la pagina e riprova.");
|
|
}
|
|
}
|
|
|
|
return await next(context).ConfigureAwait(false);
|
|
}
|
|
|
|
internal static async Task<IResult> SetSettingAsync(AnubisHost host, string key, string value, HttpContext context, CancellationToken ct)
|
|
{
|
|
try
|
|
{
|
|
await host.Services!.Settings.SetAsync(key, value, context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false);
|
|
return Results.NoContent();
|
|
}
|
|
catch (ReadOnlySettingException ex)
|
|
{
|
|
return Error(StatusCodes.Status409Conflict, "sola_lettura", ex.Message);
|
|
}
|
|
catch (ArgumentException ex)
|
|
{
|
|
return Error(StatusCodes.Status400BadRequest, "valore_non_valido", ex.Message);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Pause blocks new entries and keeps stops and exits; "Ferma tutto" is the switch of SPEC 9.3 (its full effect
|
|
/// arrives with the engine). Resume works only from a pause, never after "Ferma tutto" (SPEC 14).
|
|
/// </summary>
|
|
internal static async Task<(bool Ok, string Message)> BotCommandAsync(AnubisHost host, string command, string by, CancellationToken ct)
|
|
{
|
|
var settings = host.Services!.Settings;
|
|
var current = (await settings.GetAsync(SettingsStore.BotState.Key, ct).ConfigureAwait(false)).Value;
|
|
|
|
// A switch tripped by the fall from the high stops only its world and leaves the bot "active": the restart is
|
|
// the user's confirmation for that world too (SPEC 9.2, 9.3).
|
|
var tripped = host.Services.Trading?.Risk is { } engine && await engine.AnyTrippedAsync(ct).ConfigureAwait(false);
|
|
var target = command switch
|
|
{
|
|
"pause" or "pausa" when current == "active" => "paused",
|
|
"resume" or "riprendi" when current == "paused" => "active",
|
|
"stop" or "ferma" => "stopped",
|
|
"close" or "chiudi" => "stopped",
|
|
"restart" or "riattiva" when current == "stopped" => "active",
|
|
"restart" or "riattiva" when tripped => current,
|
|
_ => null,
|
|
};
|
|
if (target is null)
|
|
{
|
|
return (false, current == "stopped"
|
|
? "Dopo \"Ferma tutto\" il bot non riprende da solo: riattivalo dalla pagina Rischio."
|
|
: "Comando non ammesso nello stato attuale del bot.");
|
|
}
|
|
|
|
var protectedRestart = await Platform.Installation.ReadRowAsync(host.Services.Db, ct).ConfigureAwait(false) is { ProtectedRestart: true };
|
|
var restart = protectedRestart && command is "restart" or "riattiva";
|
|
if (protectedRestart && command is "restart" or "riattiva" or "close" or "chiudi"
|
|
&& (host.Services.Trading is not { Risk: not null, Started: true } engineOn || engineOn.AccountsToRebuild.Count > 0))
|
|
{
|
|
// SPEC 15.1: first the executions after the archive, then the user's confirmation.
|
|
var waiting = host.Services.Trading?.AccountsToRebuild ?? [];
|
|
return (false, "Dopo il ripristino devo prima ricostruire dal broker le esecuzioni successive al salvataggio" +
|
|
(waiting.Count == 0 ? "." : $". Aspetto: {string.Join(", ", waiting)}."));
|
|
}
|
|
|
|
if (host.Services.Trading is { Risk: { } risk } trading)
|
|
{
|
|
// The switch of SPEC 9.3 goes through the risk engine: it cancels the orders under way and keeps the stops.
|
|
switch (command)
|
|
{
|
|
case "stop" or "ferma":
|
|
await risk.StopAllAsync(trading.Managers, by, "manual_stop", "Ferma tutto dall'interfaccia: annullo gli ordini in attesa e non apro posizioni. Gli stop restano.", ct)
|
|
.ConfigureAwait(false);
|
|
return (true, target);
|
|
case "close" or "chiudi":
|
|
await risk.CloseAllAsync(trading.Managers, by, ct).ConfigureAwait(false);
|
|
return (true, target);
|
|
case "restart" or "riattiva":
|
|
try
|
|
{
|
|
await risk.RestartAsync(by, ct).ConfigureAwait(false);
|
|
if (restart)
|
|
{
|
|
await Platform.Installation.ClearProtectedRestartAsync(host.Services.Db, ct).ConfigureAwait(false);
|
|
}
|
|
|
|
await NotifyBotAsync(host, "bot_restarted", $"Il bot è ripartito dopo «Ferma tutto» (da {by}).", ct).ConfigureAwait(false);
|
|
return (true, target);
|
|
}
|
|
catch (InvalidOperationException ex)
|
|
{
|
|
return (false, ex.Message);
|
|
}
|
|
}
|
|
}
|
|
|
|
await settings.SetAsync(SettingsStore.BotState.Key, target, by, ct).ConfigureAwait(false);
|
|
if (target != current)
|
|
{
|
|
// Blocks and unblocks reach the phone (SPEC 14), whoever gave the command.
|
|
await NotifyBotAsync(host, "bot_" + target, target switch
|
|
{
|
|
"paused" => $"Bot in pausa (da {by}): niente nuovi acquisti, stop e uscite proseguono.",
|
|
"active" => $"Bot ripartito dalla pausa (da {by}).",
|
|
"stopped" => $"«Ferma tutto» (da {by}): niente nuove posizioni, gli stop restano. Si riparte solo dall'interfaccia.",
|
|
_ => $"Stato del bot: {target} (da {by}).",
|
|
}, ct).ConfigureAwait(false);
|
|
}
|
|
|
|
return (true, target);
|
|
}
|
|
|
|
private static Task NotifyBotAsync(AnubisHost host, string code, string message, CancellationToken ct) =>
|
|
host.Services!.Db.WriteAsync(s => Anubis.Trading.Diary.NotifyAsync(s, host.Clock, code, message, ct), ct);
|
|
|
|
// Live status (SPEC 13.4): one message on connect, one at every change and a heartbeat every few seconds, so the
|
|
// page can tell how old its data are and warn when the link drops.
|
|
private static async Task StatusSocketAsync(HttpContext context, AnubisHost host, ShellData shell, EventBus bus)
|
|
{
|
|
if (!context.WebSockets.IsWebSocketRequest)
|
|
{
|
|
context.Response.StatusCode = StatusCodes.Status400BadRequest;
|
|
return;
|
|
}
|
|
|
|
// Cross-site WebSocket hijacking: the page must come from this same server.
|
|
var origin = context.Request.Headers.Origin.ToString();
|
|
if (origin.Length > 0 && (!Uri.TryCreate(origin, UriKind.Absolute, out var originUri) ||
|
|
!string.Equals(originUri.Authority, context.Request.Host.Value, StringComparison.OrdinalIgnoreCase)))
|
|
{
|
|
context.Response.StatusCode = StatusCodes.Status403Forbidden;
|
|
return;
|
|
}
|
|
|
|
context.Request.Cookies.TryGetValue(SessionAuthentication.Cookie, out var token);
|
|
using var socket = await context.WebSockets.AcceptWebSocketAsync().ConfigureAwait(false);
|
|
using var settings = bus.Subscribe<SettingChanged>(16);
|
|
using var modes = bus.Subscribe<HostChanged>(16);
|
|
var aborted = context.RequestAborted;
|
|
var receive = DrainAsync(socket, aborted);
|
|
try
|
|
{
|
|
while (socket.State == WebSocketState.Open && !aborted.IsCancellationRequested)
|
|
{
|
|
// The live status ends with the session: signed out, expired, or closed by a new password.
|
|
if (!host.IsDemo && (host.Services is not { } services || await services.Access.ValidateAsync(token, refresh: false, aborted).ConfigureAwait(false) is null))
|
|
{
|
|
break;
|
|
}
|
|
|
|
var snapshot = await shell.SnapshotAsync(aborted).ConfigureAwait(false);
|
|
var bytes = JsonSerializer.SerializeToUtf8Bytes(new { type = "status", status = snapshot }, _json);
|
|
await socket.SendAsync(bytes, WebSocketMessageType.Text, true, aborted).ConfigureAwait(false);
|
|
|
|
using var wait = CancellationTokenSource.CreateLinkedTokenSource(aborted);
|
|
wait.CancelAfter(TimeSpan.FromSeconds(5));
|
|
var changed = Task.WhenAny(Next(settings, wait.Token), Next(modes, wait.Token));
|
|
await Task.WhenAny(changed, receive, Task.Delay(Timeout.Infinite, wait.Token)).ConfigureAwait(false);
|
|
|
|
// Stop the reader that lost, or it would swallow the next event of its kind.
|
|
await wait.CancelAsync().ConfigureAwait(false);
|
|
if (receive.IsCompleted)
|
|
{
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
catch (Exception ex) when (ex is OperationCanceledException or WebSocketException)
|
|
{
|
|
}
|
|
|
|
// Answer the client's close, or start ours. Output only: the drain loop may still be receiving.
|
|
if (socket.State is WebSocketState.Open or WebSocketState.CloseReceived)
|
|
{
|
|
try
|
|
{
|
|
using var closing = new CancellationTokenSource(TimeSpan.FromSeconds(2));
|
|
await socket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, null, closing.Token).ConfigureAwait(false);
|
|
}
|
|
catch (Exception ex) when (ex is OperationCanceledException or WebSocketException)
|
|
{
|
|
}
|
|
}
|
|
|
|
await Task.WhenAny(receive, Task.Delay(TimeSpan.FromSeconds(2), CancellationToken.None)).ConfigureAwait(false);
|
|
}
|
|
|
|
private static async Task Next<T>(EventSubscription<T> subscription, CancellationToken cancellationToken)
|
|
{
|
|
await foreach (var _ in subscription.ReadAllAsync(cancellationToken).ConfigureAwait(false))
|
|
{
|
|
return;
|
|
}
|
|
}
|
|
|
|
private static async Task DrainAsync(WebSocket socket, CancellationToken cancellationToken)
|
|
{
|
|
var buffer = new byte[1024];
|
|
try
|
|
{
|
|
while (socket.State == WebSocketState.Open)
|
|
{
|
|
var result = await socket.ReceiveAsync(buffer, cancellationToken).ConfigureAwait(false);
|
|
if (result.MessageType == WebSocketMessageType.Close)
|
|
{
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
catch (Exception ex) when (ex is OperationCanceledException or WebSocketException)
|
|
{
|
|
}
|
|
}
|
|
|
|
/// <summary>Compares two secrets in constant time.</summary>
|
|
internal static bool SameSecret(string? given, string? expected) =>
|
|
given is not null && expected is not null &&
|
|
CryptographicOperations.FixedTimeEquals(SHA256.HashData(Encoding.UTF8.GetBytes(given)), SHA256.HashData(Encoding.UTF8.GetBytes(expected)));
|
|
}
|
|
|
|
/// <summary>What the health check of the container says about the engine's loop and the live prices (SPEC 15.2).</summary>
|
|
internal static class HealthRules
|
|
{
|
|
/// <summary>The same silence after which the guard steps in (SPEC 9.3).</summary>
|
|
public static readonly TimeSpan LoopLimit = TimeSpan.FromMinutes(2);
|
|
|
|
/// <summary>A start of the engine this long is stalled, as for the guard (SPEC 9.3).</summary>
|
|
public static readonly TimeSpan StartLimit = TimeSpan.FromMinutes(10);
|
|
|
|
/// <summary>Longer than the silence that blocks new entries (SPEC 6.5): a line that drops for a moment is not an ill container.</summary>
|
|
public static readonly TimeSpan FeedLimit = TimeSpan.FromMinutes(5);
|
|
|
|
/// <summary>The engine's loop; <paramref name="since"/> is when the services became ready, null where there is no engine to start.</summary>
|
|
public static (string Text, bool Ok) Loop(DateTimeOffset now, DateTimeOffset? since, bool started, bool failed, DateTimeOffset? lastTurn) => (since, started, lastTurn) switch
|
|
{
|
|
(null, _, _) => ("non avviato", true),
|
|
({ } from, false, _) when failed || now - from > StartLimit => ("non avviato", false),
|
|
(_, false, _) or (_, _, null) => ("in avvio", true),
|
|
(_, _, { } at) when now - at > LoopLimit => ("fermo", false),
|
|
_ => ("ok", true),
|
|
};
|
|
|
|
public static (string Text, bool Ok) Feed(DateTimeOffset now, DateTimeOffset? since, DateTimeOffset? lastData) => (since, lastData) switch
|
|
{
|
|
(null, _) => ("in attesa", true),
|
|
({ } from, null) when now - from <= FeedLimit => ("in attesa", true),
|
|
(_, { } at) when now - at <= FeedLimit => ("ok", true),
|
|
_ => ("fermi", false),
|
|
};
|
|
}
|