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;
namespace Anubis.Server;
/// Answer of GET /health.
internal sealed record HealthResponse(string Status, string Name, string Version, string? Mode = null, IReadOnlyDictionary? Checks = null);
internal sealed record SettingBody(string Value);
///
/// 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.
///
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 and the scheduler loop is alive (SPEC 15.2); the body says why not.
private static async Task HealthAsync(AnubisHost host, CancellationToken cancellationToken)
{
var status = host.Status;
var checks = new Dictionary(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 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();
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.");
}
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 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, 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);
private static async ValueTask