Fase 6 — Motore dal vivo in simulazione #92

Merged
Alby96 merged 12 commits from fase-6 into main 2026-11-11 22:30:56 +01:00
16 changed files with 1416 additions and 17 deletions
Showing only changes of commit 84c540786c - Show all commits

No files matched your search

+33 -3
View File
@@ -39,7 +39,7 @@ 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);
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
@@ -67,6 +67,7 @@ internal sealed partial class AnubisHost(
private CancellationTokenSource? _schedulerStop;
private MarketDataService? _market;
private TradingService? _trading;
private TelegramServices? _telegram;
private Laboratory? _lab;
private volatile HostStatus _status = new(HostMode.Starting, null, null, clock.UtcNow, 0);
private volatile AppServices? _services;
@@ -80,6 +81,8 @@ internal sealed partial class AnubisHost(
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;
@@ -333,7 +336,11 @@ internal sealed partial class AnubisHost(
// 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);
_services = new AppServices(_db, settings, secrets, access, backups, scheduler, _market, _trading, _lab);
// 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);
// 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);
@@ -480,7 +487,7 @@ internal sealed partial class AnubisHost(
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) };
foreach (var job in new[] { backup }.Concat(_market?.Jobs() ?? []).Concat(_trading?.Jobs() ?? []))
foreach (var job in new[] { backup }.Concat(_market?.Jobs() ?? []).Concat(_trading?.Jobs() ?? []).Concat(_telegram?.Jobs() ?? []))
{
scheduler.Add(job, lastDues.TryGetValue(job.Name, out var due) ? due : null);
}
@@ -490,6 +497,7 @@ internal sealed partial class AnubisHost(
var market = _market;
var trading = _trading;
var lab = _lab;
var telegram = _telegram;
_schedulerLoop = Task.Run(async () =>
{
using var runs = bus.Subscribe<JobRun>();
@@ -497,6 +505,7 @@ internal sealed partial class AnubisHost(
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);
@@ -508,6 +517,7 @@ internal sealed partial class AnubisHost(
await collecting.ConfigureAwait(false);
await dealing.ConfigureAwait(false);
await testing.ConfigureAwait(false);
await writing.ConfigureAwait(false);
await recorder.ConfigureAwait(false);
}, CancellationToken.None);
}
@@ -542,6 +552,21 @@ internal sealed partial class AnubisHost(
}
}
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
@@ -621,6 +646,8 @@ internal sealed partial class AnubisHost(
_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).
@@ -673,6 +700,9 @@ internal sealed partial class AnubisHost(
[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);
@@ -23,6 +23,11 @@
"capitale" => "Capitale affidato aggiornato e diviso tra le strategie.",
"limiti" => "Limiti di rischio salvati.",
"rischio" => "Impostazione del rischio salvata.",
"telegram" => "Telegram funziona: ti ho mandato un messaggio di prova e ho salvato token e chat.",
"telegram-prova" => "Messaggio di prova partito: controlla il telefono.",
"telegram-tolto" => "Telegram tolto: non ti scrivo più finché non lo rimetti.",
"segnale" => "Segnale di vita salvato: la prima chiamata è andata bene, da adesso lo chiamo ogni minuto.",
"segnale-tolto" => "Segnale di vita tolto.",
_ => "Fatto.",
})</p>
@@ -33,7 +38,7 @@
}
<nav class="tabs" aria-label="Sezioni delle impostazioni">
<a href="#aspetto">Aspetto</a><a href="#conti">Conti</a><a href="#rischio">Rischio</a><a href="#dati">Dati</a><a href="#sicurezza">Sicurezza</a><a href="#sistema">Sistema</a><a href="#modifiche">Modifiche</a>
<a href="#aspetto">Aspetto</a><a href="#conti">Conti</a><a href="#rischio">Rischio</a><a href="#telegram">Telegram</a><a href="#dati">Dati</a><a href="#sicurezza">Sicurezza</a><a href="#sistema">Sistema</a><a href="#modifiche">Modifiche</a>
</nav>
<section class="panel" id="aspetto">
@@ -186,6 +191,93 @@
}
</section>
<section class="panel" id="telegram">
<h2>Telegram e segnale di vita</h2>
<p class="hint">Su Telegram ti scrivo il riepilogo del mattino, ogni acquisto e vendita con il risultato, gli avvisi di rischio, i blocchi e gli errori. Dalla stessa chat accetto /stato, /posizioni, /oggi, /pausa, /riprendi, /ferma (con conferma) e /aiuto; da altre chat nessun comando. Soldi veri, limiti e chiavi non si cambiano da Telegram.</p>
<dl class="facts">
<dt>Token del bot</dt><dd>@KeyState(_telegramToken)</dd>
<dt>Chat</dt><dd>@KeyState(_telegramChat)</dd>
<dt>Ultimo messaggio partito</dt><dd>@(_queue?.LastSentAt is { } sent ? Format.ShortDate(sent, Shell.Now, Shell.Zone) : "Nessuno")</dd>
@if (_queue is { } q && (q.Pending > 0 || q.Retrying > 0 || q.GaveUp > 0))
{
<dt>In attesa</dt><dd>@q.Pending in coda@(q.Retrying > 0 ? $", {q.Retrying} da ritentare" : "")@(q.GaveUp > 0 ? $", {q.GaveUp} non partiti" : "")</dd>
}
@if (_queue?.LastError is { } lastError)
{
<dt>Ultimo errore</dt><dd class="loss">@lastError</dd>
}
</dl>
@if (Shell.IsDemo)
{
<p class="hint">Nella modalità dimostrativa Telegram non si usa.</p>
}
else if (_telegramToken.FromEnvironment || _telegramChat.FromEnvironment)
{
<p class="hint">Token e chat arrivano dalle variabili d'ambiente: si cambiano nella configurazione del container.</p>
}
else
{
<form method="post" action="/azioni/telegram" class="form" autocomplete="off">
<AntiforgeryToken />
<label for="tg-token">Token del bot (da @@BotFather)</label>
<input id="tg-token" name="token" type="password" autocomplete="off" spellcheck="false" maxlength="200" required />
<label for="tg-chat">Numero della chat</label>
<input id="tg-chat" name="chat" inputmode="numeric" autocomplete="off" spellcheck="false" maxlength="40" required />
<button class="btn" type="submit">Prova e salva</button>
</form>
<p class="hint">Prima di salvarli mando un messaggio di prova: se non parte, non salvo nulla. Il token non lo rimostro mai.</p>
}
@if (!Shell.IsDemo && _telegramToken.IsSet && _telegramChat.IsSet)
{
<form method="post" action="/azioni/telegram/prova" class="form-inline"><AntiforgeryToken /><button class="btn btn-small" type="submit">Manda un messaggio di prova</button></form>
@if (!_telegramToken.FromEnvironment && !_telegramChat.FromEnvironment)
{
<form method="post" action="/azioni/telegram/togli" class="form-inline"><AntiforgeryToken /><button class="btn btn-small" type="submit" data-confirm="Tolgo token e chat? Non ti scrivo più su Telegram finché non li rimetti.">Togli Telegram</button></form>
}
}
<h3>Stato periodico</h3>
<form method="post" action="/azioni/impostazioni/@SettingsStore.TelegramStatus.Key" class="form-inline">
<AntiforgeryToken />
<input type="hidden" name="ritorno" value="/impostazioni#telegram" />
<label for="tg-status">@SettingsStore.TelegramStatus.Label</label>
<select id="tg-status" name="valore" disabled="@(_telegramStatus.ReadOnly || Shell.IsDemo)" data-autosubmit>
@foreach (var value in SettingsStore.TelegramStatus.Allowed!)
{
<option value="@value" selected="@(value == _telegramStatus.Value)">@(value switch { "hourly" => "Ogni ora", "daily" => "Ogni sera alle 20:00", _ => "Mai" })</option>
}
</select>
<button class="btn btn-small" type="submit">Salva</button>
</form>
<h3>Segnale di vita</h3>
<p class="hint">Facoltativo. Se metti l'indirizzo di un servizio di controllo esterno (per esempio healthchecks.io), lo chiamo ogni minuto. Quando le chiamate si fermano è quel servizio ad avvisarti: è l'unico modo per sapere che il bot è spento quando è spento.</p>
<dl class="facts">
<dt>Indirizzo</dt><dd>@(Host.Services!.Telegram?.ConfiguredHeartbeat is not null ? "Dalla configurazione d'avvio (ANUBIS_HEARTBEAT_URL)" : KeyState(_heartbeat))</dd>
@if (Host.Services.Telegram is { } tg)
{
<dt>Ultima chiamata riuscita</dt><dd>@(tg.Heartbeat.LastOk is { } beat ? Format.ShortDate(beat, Shell.Now, Shell.Zone) : "Nessuna da quando il bot è partito")</dd>
@if (tg.Heartbeat.LastError is { } beatError)
{
<dt>Ultimo errore</dt><dd class="loss">@beatError</dd>
}
}
</dl>
@if (!Shell.IsDemo && Host.Services.Telegram is { ConfiguredHeartbeat: null })
{
<form method="post" action="/azioni/segnale-di-vita" class="form-inline" autocomplete="off">
<AntiforgeryToken />
<label for="hb-url">Indirizzo</label>
<input id="hb-url" name="indirizzo" type="url" autocomplete="off" spellcheck="false" maxlength="500" placeholder="https://hc-ping.com/…" required />
<button class="btn btn-small" type="submit">Prova e salva</button>
</form>
@if (_heartbeat.IsSet)
{
<form method="post" action="/azioni/segnale-di-vita/togli" class="form-inline"><AntiforgeryToken /><button class="btn btn-small" type="submit">Togli il segnale di vita</button></form>
}
}
</section>
<section class="panel" id="dati">
<h2>Dati</h2>
@@ -365,6 +457,11 @@
private List<SettingChange> _history = [];
private IReadOnlyList<BackupInfo> _backups = [];
private bool _hasSecondFactor;
private SecretStatus _telegramToken = new(Anubis.Notifications.TelegramSettings.TokenSecret, false, false, null);
private SecretStatus _telegramChat = new(Anubis.Notifications.TelegramSettings.ChatSecret, false, false, null);
private SecretStatus _heartbeat = new(TelegramServices.HeartbeatSecret, false, false, null);
private SettingValue _telegramStatus = new(SettingsStore.TelegramStatus.Key, "never", false, null);
private Anubis.Notifications.NotificationSummary? _queue;
private string? _draft;
private string? _draftUri;
@@ -397,6 +494,11 @@
_anyLive = await (services.Trading?.Stages ?? new StageBook(services.Db, Clock, TradingConsent.None, (_, _, _) => Task.FromResult(false))).AnyLiveAsync(null, ct);
_backups = services.Backups.List();
_telegramToken = await services.Secrets.StatusAsync(Anubis.Notifications.TelegramSettings.TokenSecret, ct);
_telegramChat = await services.Secrets.StatusAsync(Anubis.Notifications.TelegramSettings.ChatSecret, ct);
_heartbeat = await services.Secrets.StatusAsync(TelegramServices.HeartbeatSecret, ct);
_telegramStatus = await services.Settings.GetAsync(SettingsStore.TelegramStatus.Key, ct);
_queue = services.Telegram is { } telegram ? await telegram.Sender.SummaryAsync(ct) : null;
var ledger = new Ledger(services.Db, Clock);
var capital = new Capital(services.Db, Clock, ledger, new FxStore(services.Db, Clock));
var reconciler = new Reconciler(services.Db, Clock, ledger);
@@ -445,6 +547,12 @@
"frase-rischio" => $"Una strategia usa soldi veri: per aggiungere rischio scrivi la frase «{StageBook.RaisePhrase}». Non ho cambiato nulla.",
"password-rischio" => "Password o codice non corretti. Dopo cinque tentativi sbagliati devi aspettare 15 minuti. Non ho cambiato nulla.",
"retrocessione-rischio" => "Una strategia con soldi veri ha una condizione di retrocessione in corso: finché dura non si aggiunge rischio. Non ho cambiato nulla.",
"telegram-rifiutato" => "Telegram non ha accettato token o chat, o non ha risposto: il messaggio di prova non è partito e non ho salvato nulla. Controlla il token di @BotFather e il numero della chat.",
"telegram-prova" => "Il messaggio di prova non è partito: controlla token e chat, o riprova tra poco.",
"telegram-vuoto" => "Servono il token del bot e il numero della chat.",
"telegram-ambiente" => "Token e chat arrivano dalle variabili d'ambiente: si cambiano nella configurazione del container.",
"segnale" => "L'indirizzo non va bene: serve https:// (http solo nella rete di casa).",
"segnale-fallito" => "Il servizio di controllo non ha risposto bene alla prova: non ho salvato l'indirizzo.",
"scenari" => "Gli scenari non sono validi: una riga ciascuno, con descrizione e tre percentuali separate da punto e virgola.",
_ => PasswordMessages.For(Errore),
@@ -12,7 +12,11 @@
}
else
{
<p>Due passi: dove tenere i dati e la password per entrare. Conti, capitale e Telegram si aggiungono dopo, dalle Impostazioni.</p>
<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>
+18 -3
View File
@@ -195,7 +195,7 @@ internal static partial class Endpoints
api.MapPost("/bot/{command}", async (string command, AnubisHost host, HttpContext context, CancellationToken ct) =>
{
var (ok, message) = await BotCommandAsync(host, command, context, ct).ConfigureAwait(false);
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);
});
@@ -255,7 +255,7 @@ internal static partial class Endpoints
/// 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, HttpContext context, CancellationToken ct)
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;
@@ -280,7 +280,6 @@ internal static partial class Endpoints
: "Comando non ammesso nello stato attuale del bot.");
}
var by = context.User.Identity?.Name ?? "utente";
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.
@@ -297,6 +296,7 @@ internal static partial class Endpoints
try
{
await risk.RestartAsync(by, 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)
@@ -307,9 +307,24 @@ internal static partial class Endpoints
}
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)
+107 -2
View File
@@ -34,6 +34,11 @@ internal static partial class Forms
signed.MapPost("/chiavi/{broker}", SaveKeysAsync);
signed.MapPost("/chiavi/{broker}/togli", RemoveKeysAsync);
signed.MapPost("/capitale/{broker}", SetCapitalAsync);
signed.MapPost("/telegram", SaveTelegramAsync);
signed.MapPost("/telegram/prova", TestTelegramAsync);
signed.MapPost("/telegram/togli", RemoveTelegramAsync);
signed.MapPost("/segnale-di-vita", SaveHeartbeatAsync);
signed.MapPost("/segnale-di-vita/togli", RemoveHeartbeatAsync);
signed.MapPost("/laboratorio", PlanTrialAsync);
signed.MapPost("/strategie/{strategy}/{choice}", StrategyStageAsync);
signed.MapPost("/rischio/limiti", SetLimitsAsync);
@@ -159,7 +164,7 @@ internal static partial class Forms
private static async Task<IResult> SetSettingAsync(string key, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
{
var back = Back(form, "/impostazioni");
if (key != SettingsStore.Theme.Key && key != SettingsStore.Currency.Key && key != SettingsStore.CentralBankMeetings.Key)
if (key != SettingsStore.Theme.Key && key != SettingsStore.Currency.Key && key != SettingsStore.CentralBankMeetings.Key && key != SettingsStore.TelegramStatus.Key)
{
return Results.Redirect(With(back, "errore", "impostazione"));
}
@@ -176,7 +181,7 @@ internal static partial class Forms
private static async Task<IResult> BotAsync(string command, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
{
var back = Back(form, "/");
var (ok, message) = await Endpoints.BotCommandAsync(host, command, context, ct).ConfigureAwait(false);
var (ok, message) = await Endpoints.BotCommandAsync(host, command, context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false);
return Results.Redirect(ok ? back : With(back, "errore", message.Contains("STOP", StringComparison.Ordinal) ? "file-stop" : "bot"));
}
@@ -274,6 +279,106 @@ internal static partial class Forms
return Results.Redirect(back + "?ok=chiavi#conti");
}
/// <summary>
/// The bot's Telegram (SPEC 14): a test message first, sent at once; token and chat are saved only when it left.
/// </summary>
private static async Task<IResult> SaveTelegramAsync(IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
{
const string back = "/impostazioni";
if (host.IsDemo || host.Services is not { Telegram: { } telegram } services)
{
return Results.Redirect(back + "?errore=motore#telegram");
}
if ((await services.Secrets.StatusAsync(Anubis.Notifications.TelegramSettings.TokenSecret, ct).ConfigureAwait(false)).FromEnvironment
|| (await services.Secrets.StatusAsync(Anubis.Notifications.TelegramSettings.ChatSecret, ct).ConfigureAwait(false)).FromEnvironment)
{
return Results.Redirect(back + "?errore=telegram-ambiente#telegram");
}
var token = form["token"].ToString().Trim();
var chat = form["chat"].ToString().Trim();
if (token.Length is 0 or > 200 || chat.Length is 0 or > 40)
{
return Results.Redirect(back + "?errore=telegram-vuoto#telegram");
}
if (await telegram.TestAsync(new Anubis.Notifications.TelegramSettings(token, chat), ct).ConfigureAwait(false) is not null)
{
return Results.Redirect(back + "?errore=telegram-rifiutato#telegram");
}
var who = context.User.Identity?.Name ?? "utente";
await services.Secrets.SetAsync(Anubis.Notifications.TelegramSettings.TokenSecret, token, who, ct).ConfigureAwait(false);
await services.Secrets.SetAsync(Anubis.Notifications.TelegramSettings.ChatSecret, chat, who, ct).ConfigureAwait(false);
return Results.Redirect(back + "?ok=telegram#telegram");
}
// The form is bound even when unused: binding it is what makes the antiforgery check run on the route.
private static async Task<IResult> TestTelegramAsync(IFormCollection form, AnubisHost host, CancellationToken ct)
{
const string back = "/impostazioni";
if (host.IsDemo || host.Services is not { Telegram: { } telegram }
|| await telegram.ReadAsync(ct).ConfigureAwait(false) is not { } settings)
{
return Results.Redirect(back + "?errore=telegram-vuoto#telegram");
}
return Results.Redirect(await telegram.TestAsync(settings, ct).ConfigureAwait(false) is null ? back + "?ok=telegram-prova#telegram" : back + "?errore=telegram-prova#telegram");
}
private static async Task<IResult> RemoveTelegramAsync(IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
{
const string back = "/impostazioni";
if (host.IsDemo || host.Services is not { } services)
{
return Results.Redirect(back + "?errore=motore#telegram");
}
var who = context.User.Identity?.Name ?? "utente";
await services.Secrets.RemoveAsync(Anubis.Notifications.TelegramSettings.TokenSecret, who, ct).ConfigureAwait(false);
await services.Secrets.RemoveAsync(Anubis.Notifications.TelegramSettings.ChatSecret, who, ct).ConfigureAwait(false);
return Results.Redirect(back + "?ok=telegram-tolto#telegram");
}
/// <summary>The address of the checking service (SPEC 14): called once as a test, saved encrypted only when it answered.</summary>
private static async Task<IResult> SaveHeartbeatAsync(IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
{
const string back = "/impostazioni";
if (host.IsDemo || host.Services is not { Telegram: { ConfiguredHeartbeat: null } telegram } services)
{
return Results.Redirect(back + "?errore=motore#telegram");
}
var address = form["indirizzo"].ToString().Trim();
if (address.Length is 0 or > 500 || Anubis.Notifications.Heartbeat.Check(address) is not null)
{
return Results.Redirect(back + "?errore=segnale#telegram");
}
var probe = new Anubis.Notifications.Heartbeat(telegram.Http, host.Clock, _ => Task.FromResult<Uri?>(new Uri(address)), Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance);
if (!await probe.BeatAsync(ct).ConfigureAwait(false))
{
return Results.Redirect(back + "?errore=segnale-fallito#telegram");
}
await services.Secrets.SetAsync(TelegramServices.HeartbeatSecret, address, context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false);
await telegram.Heartbeat.BeatAsync(ct).ConfigureAwait(false);
return Results.Redirect(back + "?ok=segnale#telegram");
}
private static async Task<IResult> RemoveHeartbeatAsync(IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
{
const string back = "/impostazioni";
if (host.IsDemo || host.Services is not { } services)
{
return Results.Redirect(back + "?errore=motore#telegram");
}
await services.Secrets.RemoveAsync(TelegramServices.HeartbeatSecret, context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false);
return Results.Redirect(back + "?ok=segnale-tolto#telegram");
}
private static async Task<IResult> RemoveKeysAsync(string broker, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
{
const string back = "/impostazioni";
+3
View File
@@ -76,6 +76,9 @@ internal sealed record ServerOverrides
public Func<Anubis.Brokers.IWebSocketTransport>? MarketSockets { get; init; }
/// <summary>Answers the Telegram calls and the sign of life instead of the network; tests without it have no Telegram.</summary>
public HttpMessageHandler? TelegramHttp { get; init; }
/// <summary>True starts the accounts and the order managers in a test; off by default in tests.</summary>
public bool? Trading { get; init; }
}
+176
View File
@@ -0,0 +1,176 @@
using System.Text;
using Anubis.Core;
using Anubis.Data;
using Anubis.Notifications;
using Anubis.Trading;
namespace Anubis.Server;
/// <summary>
/// The answers of the Telegram commands and the messages the bot writes by itself (SPEC 14), from the same data as
/// the Panoramica: one world, the simulated one until there is a real account.
/// </summary>
internal sealed class TelegramDesk(AnubisHost host) : ITelegramDesk
{
private const string By = "Telegram";
private AppServices Services => host.Services ?? throw new InvalidOperationException("Il bot sta ancora partendo: riprova tra poco.");
private TimeZoneInfo Zone => host.Config.TimeZone;
public async Task<string> StatusAsync(CancellationToken cancellationToken)
{
var services = Services;
var now = host.Clock.UtcNow;
var bot = (await services.Settings.GetAsync(SettingsStore.BotState.Key, cancellationToken).ConfigureAwait(false)).Value;
var overview = await Overview.LoadAsync(services, "oggi", now, Zone, cancellationToken).ConfigureAwait(false);
var text = new StringBuilder();
text.Append(bot switch { "paused" => "Bot in pausa", "stopped" => "Bot fermo («Ferma tutto»)", _ => "Bot attivo" })
.Append(" · solo denaro finto").AppendLine(".");
if (overview.HasData)
{
var today = overview.Cells[0];
text.Append("Patrimonio ").Append(Format.Money(overview.Points[^1].Equity)).Append(", oggi ").Append(Format.Money(today.Amount, withSign: true))
.Append(" (").Append(Format.Percent(today.Percent, 2, withSign: true)).AppendLine(").");
}
text.Append(Positions(overview.Positions, overview.PositionsWithoutStop));
if (overview.OpenOrders > 0)
{
text.Append(' ').Append(overview.OpenOrders == 1 ? "1 ordine in corso." : $"{overview.OpenOrders} ordini in corso.");
}
text.AppendLine();
if (overview.Next.Count > 0 && overview.Next[0] is var next)
{
text.Append("Prossima mossa: ").Append(next.Time).Append(' ').Append(next.Text).AppendLine(".");
}
return text.ToString().TrimEnd();
}
public async Task<string> PositionsAsync(CancellationToken cancellationToken)
{
var services = Services;
var rows = await services.Db.ReadAsync(s => s.QueryAsync(
"SELECT a.name, a.environment, a.base_currency, i.symbol, p.strategy, p.quantity, p.average_price, p.last_price, p.stop_price FROM positions p " +
"JOIN accounts a ON a.id = p.account_id JOIN instruments i ON i.id = p.instrument_id WHERE p.quantity > 0 ORDER BY a.name, i.symbol",
r => (Account: r.Text("name"), Environment: r.Text("environment"), Currency: r.Text("base_currency"), Symbol: r.Text("symbol"), Strategy: r.Text("strategy"),
Quantity: r.Money("quantity"), Average: r.Money("average_price"), Last: r.MoneyOrNull("last_price"), Stop: r.MoneyOrNull("stop_price"))), cancellationToken)
.ConfigureAwait(false);
var world = rows.Any(r => TradingEnvironments.World(r.Environment) == Worlds.Real) ? Worlds.Real : Worlds.Simulated;
rows = [.. rows.Where(r => TradingEnvironments.World(r.Environment) == world)];
if (rows.Count == 0)
{
return "Nessuna posizione aperta.";
}
var text = new StringBuilder();
foreach (var r in rows)
{
var last = r.Last ?? r.Average;
var gain = (last - r.Average) * r.Quantity;
text.Append(DiaryText.Shown(r.Symbol)).Append(": ").Append(Format.Quantity(r.Quantity)).Append(" a ").Append(Format.Money(r.Average, r.Currency))
.Append(", ora ").Append(Format.Money(last, r.Currency)).Append(" (").Append(Format.Money(gain, r.Currency, withSign: true)).Append("), ")
.Append(r.Stop is { } stop ? "stop a " + Format.Money(stop, r.Currency) : "SENZA STOP")
.Append(" · ").Append(StrategyNames.Label(r.Strategy)).Append(", ").Append(r.Account).AppendLine();
}
return text.ToString().TrimEnd();
}
public async Task<string> TodayAsync(CancellationToken cancellationToken)
{
var services = Services;
var now = host.Clock.UtcNow;
var local = TimeZoneInfo.ConvertTime(now, Zone);
var midnight = new DateTimeOffset(local.Date, local.Offset).ToUniversalTime();
var entries = await services.Db.ReadAsync(s => s.QueryAsync(
"SELECT occurred_at, message FROM journal WHERE kind = @k AND occurred_at >= @from ORDER BY occurred_at",
r => (At: r.Moment("occurred_at"), Text: r.Text("message")), ("k", DiaryKinds.Orders), ("from", midnight)), cancellationToken).ConfigureAwait(false);
var overview = await Overview.LoadAsync(services, "oggi", now, Zone, cancellationToken).ConfigureAwait(false);
var text = new StringBuilder();
if (overview.HasData)
{
text.Append("Oggi ").Append(Format.Money(overview.Cells[0].Amount, withSign: true)).Append(" (").Append(Format.Percent(overview.Cells[0].Percent, 2, withSign: true))
.AppendLine(").");
}
if (entries.Count == 0)
{
text.Append("Nessun ordine oggi.");
return text.ToString();
}
const int Shown = 15;
foreach (var e in entries.TakeLast(Shown))
{
text.Append(TimeZoneInfo.ConvertTime(e.At, Zone).ToString("HH:mm", System.Globalization.CultureInfo.InvariantCulture)).Append(' ').AppendLine(e.Text);
}
if (entries.Count > Shown)
{
text.Append("…e altre ").Append(entries.Count - Shown).Append(" righe nel Diario.");
}
return text.ToString().TrimEnd();
}
public Task<string> PauseAsync(CancellationToken cancellationToken) =>
CommandAsync("pausa", "In pausa: niente nuovi acquisti; stop e uscite proseguono. /riprendi per ripartire.", cancellationToken);
public Task<string> ResumeAsync(CancellationToken cancellationToken) => CommandAsync("riprendi", "Ripartito dalla pausa.", cancellationToken);
public Task<string> StopAllAsync(CancellationToken cancellationToken) =>
CommandAsync("ferma", "«Ferma tutto» fatto: ordini in attesa annullati, niente nuove posizioni, gli stop restano. Si riparte solo dall'interfaccia, pagina Rischio.",
cancellationToken);
/// <summary>The morning summary (SPEC 14): the night, the positions, what comes today.</summary>
public async Task<string> MorningAsync(CancellationToken cancellationToken)
{
var services = Services;
var now = host.Clock.UtcNow;
var overview = await Overview.LoadAsync(services, "oggi", now, Zone, cancellationToken).ConfigureAwait(false);
var text = new StringBuilder("Buongiorno.").AppendLine();
if (overview.HasData)
{
text.Append("Patrimonio ").Append(Format.Money(overview.Points[^1].Equity)).Append("; ultimi 7 giorni ").Append(Format.Money(overview.Cells[1].Amount, withSign: true))
.AppendLine(".");
}
text.AppendLine(Positions(overview.Positions, overview.PositionsWithoutStop));
var local = TimeZoneInfo.ConvertTime(now, Zone).Date;
var today = overview.Next.Count == 0 ? [] : services.Scheduler.Upcoming(20)
.Where(u => TimeZoneInfo.ConvertTime(u.DueUtc, Zone).Date == local)
.Select(u => TimeZoneInfo.ConvertTime(u.DueUtc, Zone).ToString("HH:mm", System.Globalization.CultureInfo.InvariantCulture) + " " + u.Description)
.ToList();
if (today.Count > 0)
{
text.AppendLine("Oggi:");
foreach (var line in today)
{
text.AppendLine(line);
}
}
return text.ToString().TrimEnd();
}
private static string Positions(int count, int withoutStop) => count switch
{
0 => "Nessuna posizione aperta.",
1 => withoutStop == 0 ? "1 posizione, con il suo stop." : "1 posizione, SENZA STOP.",
_ => withoutStop == 0 ? $"{count} posizioni, tutte con lo stop." : $"{count} posizioni, {withoutStop} SENZA STOP.",
};
private async Task<string> CommandAsync(string command, string done, CancellationToken cancellationToken)
{
if (host.IsDemo)
{
return "Nella modalità dimostrativa il bot non si comanda.";
}
var (ok, message) = await Endpoints.BotCommandAsync(host, command, By, cancellationToken).ConfigureAwait(false);
return ok ? done : message;
}
}
+159
View File
@@ -0,0 +1,159 @@
using Anubis.Core;
using Anubis.Db;
using Anubis.Notifications;
namespace Anubis.Server;
/// <summary>
/// Telegram and the sign of life (SPEC 14): the queue sent every few seconds, the commands read as they arrive, the
/// call to the checking service every minute, the morning summary and the optional periodic status.
/// </summary>
internal sealed class TelegramServices : IDisposable
{
/// <summary>The secret that keeps the address of the checking service when the configuration does not give one.</summary>
public const string HeartbeatSecret = "HEARTBEAT_URL";
public static readonly TimeOnly MorningAt = new(8, 0);
public static readonly TimeOnly EveningAt = new(20, 0);
private readonly HttpClient _http;
private readonly Database _db;
private readonly IClock _clock;
private readonly SettingsStore _settings;
private readonly SecretStore _secrets;
private readonly TimeZoneInfo _zone;
public TelegramServices(AnubisHost host, Database db, IClock clock, SettingsStore settings, SecretStore secrets, string? configuredHeartbeat, HttpMessageHandler? handler,
Microsoft.Extensions.Logging.ILogger logger)
{
ArgumentNullException.ThrowIfNull(host);
_db = db;
_clock = clock;
_settings = settings;
_secrets = secrets;
_zone = host.Config.TimeZone;
_http = handler is null ? new HttpClient() : new HttpClient(handler, disposeHandler: false);
// Longer than the wait of the commands' long polling.
_http.Timeout = TimeSpan.FromSeconds(60);
Desk = new TelegramDesk(host);
Sender = new NotificationSender(db, clock, ReadAsync, Client);
Bot = new TelegramBot(clock, ReadAsync, Client, new TelegramCommands(Desk, clock), logger);
ConfiguredHeartbeat = configuredHeartbeat;
Heartbeat = new Heartbeat(_http, clock, HeartbeatAddressAsync, logger);
}
public TelegramDesk Desk { get; }
public NotificationSender Sender { get; }
public TelegramBot Bot { get; }
public Heartbeat Heartbeat { get; }
/// <summary>The address from the startup configuration (ANUBIS_HEARTBEAT_URL): it wins over the one saved here.</summary>
public string? ConfiguredHeartbeat { get; }
/// <summary>How often the queue is looked at.</summary>
public TimeSpan SendEvery { get; init; } = TimeSpan.FromSeconds(10);
/// <summary>The client of Telegram and of the checking service.</summary>
public HttpClient Http => _http;
public TelegramClient Client(string token) => new(_http, token);
public Task<TelegramSettings?> ReadAsync(CancellationToken cancellationToken) => TelegramSettings.ReadAsync(_secrets, cancellationToken);
public async Task<Uri?> HeartbeatAddressAsync(CancellationToken cancellationToken)
{
var text = ConfiguredHeartbeat ?? await _secrets.RevealAsync(HeartbeatSecret, cancellationToken).ConfigureAwait(false);
return string.IsNullOrWhiteSpace(text) || Heartbeat.Check(text) is not null ? null : new Uri(text.Trim());
}
public IReadOnlyList<ScheduledJob> Jobs() =>
[
new("segnale-di-vita", "Segnale di vita al servizio di controllo", Schedule.Every(TimeSpan.FromMinutes(1)), async ct => await Heartbeat.BeatAsync(ct).ConfigureAwait(false))
{
MaxLateness = TimeSpan.FromMinutes(2),
},
// The summary is still useful a little late; after four hours the day has moved on (SPEC 5.6).
new("riepilogo-mattino", "Riepilogo del mattino su Telegram", Schedule.Daily(MorningAt, _zone), MorningAsync)
{
MaxLateness = TimeSpan.FromHours(4),
CatchUpWithin = TimeSpan.FromHours(4),
},
new("stato-ogni-ora", "Stato periodico su Telegram, se scelto ogni ora", Schedule.Every(TimeSpan.FromHours(1)), ct => PeriodicAsync("hourly", ct)),
new("stato-ogni-giorno", "Stato periodico su Telegram, se scelto ogni giorno", Schedule.Daily(EveningAt, _zone), ct => PeriodicAsync("daily", ct)),
];
/// <summary>Sends the queue and reads the commands until the services stop.</summary>
public async Task RunAsync(CancellationToken cancellationToken)
{
var commands = Bot.RunAsync(cancellationToken);
try
{
while (!cancellationToken.IsCancellationRequested)
{
await Sender.SendDueAsync(cancellationToken).ConfigureAwait(false);
await Task.Delay(SendEvery, cancellationToken).ConfigureAwait(false);
}
}
finally
{
try
{
await commands.ConfigureAwait(false);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
}
}
}
/// <summary>
/// The test of Impostazioni: a message to the chat, sent at once and not through the queue, so the answer says
/// whether Telegram took it. Null when it went; otherwise the reason, in the user's words.
/// </summary>
public async Task<string?> TestAsync(TelegramSettings telegram, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(telegram);
try
{
var client = Client(telegram.Token);
var name = await client.GetMeAsync(cancellationToken).ConfigureAwait(false);
await client.SendAsync(telegram.ChatId, $"Anubis: messaggio di prova. Da qui ti scrivo{(name.Length > 0 ? " come @" + name : "")}; scrivi /aiuto per i comandi.",
cancellationToken).ConfigureAwait(false);
return null;
}
catch (TelegramException ex)
{
return ex.Message;
}
}
public void Dispose() => _http.Dispose();
private async Task MorningAsync(CancellationToken cancellationToken)
{
if (await ReadAsync(cancellationToken).ConfigureAwait(false) is null)
{
return;
}
var text = await Desk.MorningAsync(cancellationToken).ConfigureAwait(false);
await _db.WriteAsync(s => NotificationSender.EnqueueAsync(s, _clock, "morning_summary", text, cancellationToken), cancellationToken).ConfigureAwait(false);
}
private async Task PeriodicAsync(string every, CancellationToken cancellationToken)
{
if ((await _settings.GetAsync(SettingsStore.TelegramStatus.Key, cancellationToken).ConfigureAwait(false)).Value != every
|| await ReadAsync(cancellationToken).ConfigureAwait(false) is null)
{
return;
}
var text = await Desk.StatusAsync(cancellationToken).ConfigureAwait(false);
await _db.WriteAsync(s => NotificationSender.EnqueueAsync(s, _clock, "periodic_status", text, cancellationToken), cancellationToken).ConfigureAwait(false);
}
}
+4 -1
View File
@@ -41,8 +41,11 @@ public sealed class SettingsStore(Database db, IClock clock, EventBus bus, IRead
public static readonly SettingDefinition CentralBankMeetings = new("calendar.central_banks", "Riunioni di Fed e BCE",
Data.CentralBanks.DefaultList, Check: Data.CentralBanks.Check);
/// <summary>The optional periodic status on Telegram (SPEC 14): never, every hour or every evening.</summary>
public static readonly SettingDefinition TelegramStatus = new("telegram.status", "Stato periodico su Telegram", "never", ["never", "hourly", "daily"]);
public static readonly IReadOnlyList<SettingDefinition> All =
[Theme, Currency, BotState, CentralBankMeetings, .. Risk.RiskSettings.All, Risk.Scenarios.Setting];
[Theme, Currency, BotState, CentralBankMeetings, TelegramStatus, .. Risk.RiskSettings.All, Risk.Scenarios.Setting];
private readonly IReadOnlyDictionary<string, StartupOverride> _overrides = overrides ?? new Dictionary<string, StartupOverride>();
+133
View File
@@ -0,0 +1,133 @@
using Anubis.Core;
using Anubis.Db;
namespace Anubis.Notifications;
/// <summary>The state of a notification (SPEC 14): never "sent" before Telegram said ok.</summary>
public static class NotificationStates
{
/// <summary>In the queue: not tried yet, or Telegram is not configured.</summary>
public const string Pending = "pending";
public const string Sent = "sent";
/// <summary>Tried and refused; tried again at <c>next_attempt_at</c>, or never again when that is empty.</summary>
public const string Failed = "failed";
}
/// <summary>The bot's Telegram: the token and the one chat it writes to and takes commands from.</summary>
public sealed record TelegramSettings(string Token, string ChatId)
{
public const string TokenSecret = "TELEGRAM_BOT_TOKEN";
public const string ChatSecret = "TELEGRAM_CHAT_ID";
/// <summary>Both secrets, or null while either is missing.</summary>
public static async Task<TelegramSettings?> ReadAsync(SecretStore secrets, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(secrets);
var token = await secrets.RevealAsync(TokenSecret, cancellationToken).ConfigureAwait(false);
var chat = await secrets.RevealAsync(ChatSecret, cancellationToken).ConfigureAwait(false);
return string.IsNullOrWhiteSpace(token) || string.IsNullOrWhiteSpace(chat) ? null : new TelegramSettings(token.Trim(), chat.Trim());
}
}
/// <summary>What Impostazioni shows of the queue: the last message that left, what waits, what failed and why.</summary>
public sealed record NotificationSummary(DateTimeOffset? LastSentAt, int Pending, int Retrying, int GaveUp, string? LastError);
/// <summary>
/// The Telegram queue (SPEC 14). Every message is written first, then sent: a refusal or a network failure is
/// recorded and tried again with growing pauses; a message that could not leave within a day is given up, with the
/// reason, rather than arriving late as if it were news.
/// </summary>
public sealed class NotificationSender(Database db, IClock clock, Func<CancellationToken, Task<TelegramSettings?>> settings, Func<string, TelegramClient> client)
{
/// <summary>Older than this, a message is no longer worth sending.</summary>
public static readonly TimeSpan MaxAge = TimeSpan.FromHours(24);
public const int MaxAttempts = 8;
/// <summary>At most this many messages per pass: Telegram limits the messages to one chat.</summary>
public const int Batch = 20;
/// <summary>Writes a message in the queue, in the same transaction as what it tells.</summary>
public static Task EnqueueAsync(DbSession s, IClock clock, string kind, string message, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(s);
ArgumentNullException.ThrowIfNull(clock);
return s.ExecuteAsync(
"INSERT INTO notifications (id, channel, kind, message, status, attempts, created_at) VALUES (@id, 'telegram', @k, @m, @st, 0, @at)", cancellationToken,
("id", Ids.NewId(clock)), ("k", kind), ("m", message), ("st", NotificationStates.Pending), ("at", clock.UtcNow));
}
/// <summary>The pause before attempt <paramref name="attempts"/> + 1: 1, 2, 4, 8, 16, 32, then 60 minutes.</summary>
public static TimeSpan Pause(int attempts) => TimeSpan.FromMinutes(Math.Min(60, 1 << Math.Clamp(attempts - 1, 0, 6)));
/// <summary>Sends what is due; the answer is how many left. Without Telegram configured everything stays in the queue.</summary>
public async Task<int> SendDueAsync(CancellationToken cancellationToken)
{
if (await settings(cancellationToken).ConfigureAwait(false) is not { } telegram)
{
return 0;
}
var now = clock.UtcNow;
var due = await db.ReadAsync(s => s.QueryAsync(
"SELECT id, message, attempts, created_at FROM notifications WHERE channel = 'telegram' AND (status = @p OR (status = @f AND next_attempt_at IS NOT NULL AND next_attempt_at <= @now)) " +
"ORDER BY created_at, id LIMIT " + Batch.ToString(System.Globalization.CultureInfo.InvariantCulture),
r => (Id: r.Id("id"), Message: r.Text("message"), Attempts: r.IsNull("attempts") ? 0 : (int)r.Number("attempts"), Created: r.Moment("created_at")),
("p", NotificationStates.Pending), ("f", NotificationStates.Failed), ("now", now)), cancellationToken).ConfigureAwait(false);
var bot = client(telegram.Token);
var sent = 0;
foreach (var item in due)
{
if (now - item.Created > MaxAge)
{
await MarkAsync(item.Id, NotificationStates.Failed, item.Attempts, null, "Non partito entro un giorno: non lo mando più.", cancellationToken).ConfigureAwait(false);
continue;
}
try
{
await bot.SendAsync(telegram.ChatId, item.Message, cancellationToken).ConfigureAwait(false);
await MarkAsync(item.Id, NotificationStates.Sent, item.Attempts + 1, null, null, cancellationToken).ConfigureAwait(false);
sent++;
}
catch (TelegramException ex)
{
var attempts = item.Attempts + 1;
DateTimeOffset? next = ex.Retryable && attempts < MaxAttempts
? clock.UtcNow + (ex.RetryAfter is { } wait && wait > Pause(attempts) ? wait : Pause(attempts))
: null;
await MarkAsync(item.Id, NotificationStates.Failed, attempts, next, ex.Message, cancellationToken).ConfigureAwait(false);
if (ex.Retryable)
{
// Telegram unreachable or asking to slow down: the others wait for the next pass.
break;
}
}
}
return sent;
}
public Task<NotificationSummary> SummaryAsync(CancellationToken cancellationToken) =>
db.ReadAsync(async s =>
{
var last = await s.FirstOrDefaultAsync("SELECT MAX(sent_at) AS at FROM notifications WHERE channel = 'telegram' AND status = @s",
r => r.MomentOrNull("at"), ("s", NotificationStates.Sent)).ConfigureAwait(false);
var pending = await s.CountAsync("SELECT COUNT(*) FROM notifications WHERE channel = 'telegram' AND status = @p", ("p", NotificationStates.Pending)).ConfigureAwait(false);
var retrying = await s.CountAsync("SELECT COUNT(*) FROM notifications WHERE channel = 'telegram' AND status = @f AND next_attempt_at IS NOT NULL",
("f", NotificationStates.Failed)).ConfigureAwait(false);
var gaveUp = await s.CountAsync("SELECT COUNT(*) FROM notifications WHERE channel = 'telegram' AND status = @f AND next_attempt_at IS NULL",
("f", NotificationStates.Failed)).ConfigureAwait(false);
var error = await s.FirstOrDefaultAsync(
"SELECT last_error FROM notifications WHERE channel = 'telegram' AND status = @f ORDER BY created_at DESC, id DESC LIMIT 1",
r => r.TextOrNull("last_error"), ("f", NotificationStates.Failed)).ConfigureAwait(false);
return new NotificationSummary(last, (int)pending, (int)retrying, (int)gaveUp, error);
}, cancellationToken);
private Task<int> MarkAsync(Guid id, string status, int attempts, DateTimeOffset? next, string? error, CancellationToken cancellationToken) =>
db.WriteAsync(s => s.ExecuteAsync(
"UPDATE notifications SET status = @s, attempts = @a, next_attempt_at = @n, last_error = @e, sent_at = @sent WHERE id = @id", cancellationToken,
("s", status), ("a", attempts), ("n", next), ("e", error), ("sent", status == NotificationStates.Sent ? clock.UtcNow : (DateTimeOffset?)null), ("id", id)), cancellationToken);
}
+258
View File
@@ -0,0 +1,258 @@
using Anubis.Core;
using Microsoft.Extensions.Logging;
namespace Anubis.Notifications;
/// <summary>
/// What the Telegram commands read and do (SPEC 14), answered in plain Italian. Nothing here turns on real money,
/// changes a limit or shows a secret: the interface does those, never the phone.
/// </summary>
public interface ITelegramDesk
{
Task<string> StatusAsync(CancellationToken cancellationToken);
Task<string> PositionsAsync(CancellationToken cancellationToken);
Task<string> TodayAsync(CancellationToken cancellationToken);
Task<string> PauseAsync(CancellationToken cancellationToken);
/// <summary>Only from a pause, never after "Ferma tutto" (SPEC 9.3, 14).</summary>
Task<string> ResumeAsync(CancellationToken cancellationToken);
/// <summary>"Ferma tutto", already confirmed.</summary>
Task<string> StopAllAsync(CancellationToken cancellationToken);
}
/// <summary>The commands of SPEC 14 and the confirmation of /ferma: two minutes to send /conferma.</summary>
public sealed class TelegramCommands(ITelegramDesk desk, IClock clock)
{
public static readonly TimeSpan ConfirmWithin = TimeSpan.FromMinutes(2);
public const string Help =
"Comandi:\n" +
"/stato – come sta il bot\n" +
"/posizioni – cosa ho in mano, con gli stop\n" +
"/oggi – cosa ho fatto oggi\n" +
"/pausa – niente nuovi acquisti, stop e uscite proseguono\n" +
"/riprendi – riparto dalla pausa\n" +
"/ferma – «Ferma tutto», con conferma\n" +
"/aiuto – questo elenco\n" +
"Soldi veri, limiti e chiavi si cambiano solo dall'interfaccia.";
private DateTimeOffset? _stopAskedAt;
/// <summary>The answer to one message; null for a message that is not a command.</summary>
public async Task<string?> AnswerAsync(string text, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(text);
var word = text.Trim().Split((char[])[' ', '\n', '\t'], 2)[0];
if (!word.StartsWith('/'))
{
return null;
}
// In a group Telegram adds the bot's name: "/stato@AnubisBot".
var command = word[1..].Split('@')[0].ToLowerInvariant();
if (command != "conferma")
{
_stopAskedAt = null;
}
switch (command)
{
case "start" or "aiuto" or "help":
return Help;
case "stato":
return await desk.StatusAsync(cancellationToken).ConfigureAwait(false);
case "posizioni":
return await desk.PositionsAsync(cancellationToken).ConfigureAwait(false);
case "oggi":
return await desk.TodayAsync(cancellationToken).ConfigureAwait(false);
case "pausa":
return await desk.PauseAsync(cancellationToken).ConfigureAwait(false);
case "riprendi":
return await desk.ResumeAsync(cancellationToken).ConfigureAwait(false);
case "ferma":
_stopAskedAt = clock.UtcNow;
return "Vuoi davvero «Ferma tutto»? Annullo gli ordini in attesa e non apro nuove posizioni; gli stop restano. " +
"Da qui non si riparte: si riparte solo dall'interfaccia, pagina Rischio.\nPer confermare scrivi /conferma entro 2 minuti.";
case "conferma":
if (_stopAskedAt is { } asked && clock.UtcNow - asked <= ConfirmWithin)
{
_stopAskedAt = null;
return await desk.StopAllAsync(cancellationToken).ConfigureAwait(false);
}
_stopAskedAt = null;
return "Non c'è niente da confermare: scrivi prima /ferma.";
default:
return "Non conosco questo comando.\n" + Help;
}
}
}
/// <summary>
/// Reads the messages sent to the bot and answers the commands (SPEC 14). Only the chat of the settings is obeyed;
/// the others get no answer at all. A message older than five minutes, found after a stop of the bot, is not
/// obeyed: a /pausa of yesterday must not pause today.
/// </summary>
public sealed partial class TelegramBot(IClock clock, Func<CancellationToken, Task<TelegramSettings?>> settings, Func<string, TelegramClient> client,
TelegramCommands commands, ILogger logger)
{
public static readonly TimeSpan StaleAfter = TimeSpan.FromMinutes(5);
/// <summary>How long one call waits for a message on Telegram's side.</summary>
public int WaitSeconds { get; init; } = 25;
/// <summary>The pause after a failure, or while Telegram is not configured.</summary>
public TimeSpan Retry { get; init; } = TimeSpan.FromSeconds(30);
private long _offset;
/// <summary>One read of the messages; the answer is how many commands were obeyed.</summary>
public async Task<int> PollOnceAsync(CancellationToken cancellationToken)
{
if (await settings(cancellationToken).ConfigureAwait(false) is not { } telegram)
{
return -1;
}
var bot = client(telegram.Token);
var updates = await bot.GetUpdatesAsync(_offset, WaitSeconds, cancellationToken).ConfigureAwait(false);
var obeyed = 0;
foreach (var update in updates)
{
_offset = Math.Max(_offset, update.UpdateId + 1);
if (update.ChatId != telegram.ChatId)
{
LogStranger(logger, update.ChatId ?? "?");
continue;
}
if (update.Text is not { } text || update.Date is not { } date || clock.UtcNow - date > StaleAfter)
{
continue;
}
string? answer;
try
{
answer = await commands.AnswerAsync(text, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
LogCommandFailed(logger, ex);
answer = "Non ci sono riuscito: " + Redactor.Redact(ex.Message);
}
if (answer is not null)
{
obeyed++;
await bot.SendAsync(telegram.ChatId, answer, cancellationToken).ConfigureAwait(false);
}
}
return obeyed;
}
/// <summary>The loop: reads, answers, and after a failure waits and tries again.</summary>
public async Task RunAsync(CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
TimeSpan? pause = null;
try
{
if (await PollOnceAsync(cancellationToken).ConfigureAwait(false) < 0)
{
pause = Retry;
}
}
catch (TelegramException ex)
{
LogPollFailed(logger, ex.Message);
pause = ex.RetryAfter is { } after && after > Retry ? after : Retry;
}
if (pause is { } wait)
{
await Task.Delay(wait, cancellationToken).ConfigureAwait(false);
}
}
}
[LoggerMessage(Level = LogLevel.Warning, Message = "Telegram message from another chat ignored: {Chat}")]
private static partial void LogStranger(ILogger logger, string chat);
[LoggerMessage(Level = LogLevel.Warning, Message = "Telegram read failed: {Error}")]
private static partial void LogPollFailed(ILogger logger, string error);
[LoggerMessage(Level = LogLevel.Error, Message = "Telegram command failed")]
private static partial void LogCommandFailed(ILogger logger, Exception ex);
}
/// <summary>
/// The sign of life (SPEC 14): a call to an outside checking service every minute. When the calls stop, that
/// service warns the user: the only way to know the bot is off while it is off.
/// </summary>
public sealed partial class Heartbeat(HttpClient http, IClock clock, Func<CancellationToken, Task<Uri?>> address, ILogger logger)
{
public DateTimeOffset? LastOk { get; private set; }
public string? LastError { get; private set; }
/// <summary>True when the call went through; false when there is no address or it failed.</summary>
public async Task<bool> BeatAsync(CancellationToken cancellationToken)
{
if (await address(cancellationToken).ConfigureAwait(false) is not { } url)
{
return false;
}
try
{
using var response = await http.GetAsync(url, cancellationToken).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
LastOk = clock.UtcNow;
LastError = null;
return true;
}
LastError = $"Il servizio ha risposto {(int)response.StatusCode}.";
}
catch (HttpRequestException ex)
{
LastError = "Il servizio non risponde: " + Redactor.Redact(ex.Message);
}
catch (TaskCanceledException) when (!cancellationToken.IsCancellationRequested)
{
LastError = "Il servizio non ha risposto in tempo.";
}
LogFailed(logger, LastError);
return false;
}
/// <summary>An address the interface accepts: https, or http only on this computer or the local network.</summary>
public static string? Check(string value)
{
if (string.IsNullOrWhiteSpace(value))
{
return null;
}
if (!Uri.TryCreate(value.Trim(), UriKind.Absolute, out var uri) || uri.Scheme is not ("https" or "http"))
{
return "Serve un indirizzo che inizi con https://.";
}
return uri.Scheme == "http" && !(uri.IsLoopback || uri.Host.EndsWith(".local", StringComparison.OrdinalIgnoreCase) || System.Net.IPAddress.TryParse(uri.Host, out _))
? "Fuori dalla rete di casa serve https://."
: null;
}
[LoggerMessage(Level = LogLevel.Warning, Message = "Heartbeat failed: {Error}")]
private static partial void LogFailed(ILogger logger, string error);
}
@@ -35,6 +35,9 @@ public sealed class TelegramException : Exception
public TimeSpan? RetryAfter { get; }
}
/// <summary>A message to the bot: who wrote it (the chat), what and when.</summary>
public sealed record TelegramUpdate(long UpdateId, string? ChatId, string? Text, DateTimeOffset? Date);
/// <summary>
/// The Telegram Bot API (SPEC 14): plain text messages to the user's chat. The token is part of the address, so the
/// address is never logged; errors carry only Telegram's own description.
@@ -43,6 +46,8 @@ public sealed class TelegramClient
{
public static readonly Uri DefaultBase = new("https://api.telegram.org/");
private static readonly string[] MessagesOnly = ["message"];
private readonly HttpClient _http;
private readonly string _token;
private readonly Uri _base;
@@ -70,6 +75,40 @@ public sealed class TelegramClient
cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The messages sent to the bot after <paramref name="offset"/>, waiting up to <paramref name="waitSeconds"/> for
/// one (long polling). The next call passes the last update's id plus one, which tells Telegram they were read.
/// </summary>
public async Task<IReadOnlyList<TelegramUpdate>> GetUpdatesAsync(long offset, int waitSeconds, CancellationToken cancellationToken)
{
using var answer = await CallAsync("getUpdates", new Dictionary<string, object> { ["offset"] = offset, ["timeout"] = waitSeconds, ["allowed_updates"] = MessagesOnly },
cancellationToken).ConfigureAwait(false);
var updates = new List<TelegramUpdate>();
foreach (var item in answer.RootElement.GetProperty("result").EnumerateArray())
{
string? chat = null;
string? text = null;
DateTimeOffset? date = null;
if (item.TryGetProperty("message", out var message))
{
chat = message.TryGetProperty("chat", out var c) && c.TryGetProperty("id", out var id) ? id.GetRawText().Trim('"') : null;
text = message.TryGetProperty("text", out var t) && t.ValueKind == JsonValueKind.String ? t.GetString() : null;
date = message.TryGetProperty("date", out var d) && d.TryGetInt64(out var seconds) ? DateTimeOffset.FromUnixTimeSeconds(seconds) : null;
}
updates.Add(new TelegramUpdate(item.GetProperty("update_id").GetInt64(), chat, text, date));
}
return updates;
}
/// <summary>The bot's own name: the test of Impostazioni, which proves the token works without writing to anyone.</summary>
public async Task<string> GetMeAsync(CancellationToken cancellationToken)
{
using var answer = await CallAsync("getMe", new Dictionary<string, object>(), cancellationToken).ConfigureAwait(false);
return answer.RootElement.GetProperty("result").TryGetProperty("username", out var name) ? name.GetString() ?? "" : "";
}
/// <summary>One call of the Bot API; the answer's <c>result</c> when Telegram says ok.</summary>
public async Task<JsonDocument> CallAsync(string method, object body, CancellationToken cancellationToken)
{
+2 -3
View File
@@ -18,7 +18,7 @@ public static class DiaryKinds
/// <summary>
/// The bot's diary and its notices (SPEC 13.6): short sentences in Italian, in the first person. A notice is also
/// queued for Telegram; the sender arrives with Phase 6, the queue is kept from now.
/// queued for Telegram (SPEC 14), in the same transaction.
/// </summary>
public static class Diary
{
@@ -36,7 +36,6 @@ public static class Diary
ArgumentNullException.ThrowIfNull(s);
ArgumentNullException.ThrowIfNull(clock);
await WriteAsync(s, clock, DiaryKinds.System, code, message, null, cancellationToken).ConfigureAwait(false);
await s.ExecuteAsync("INSERT INTO notifications (id, channel, kind, message, status, created_at) VALUES (@id, 'telegram', @k, @m, 'pending', @at)", cancellationToken,
("id", Ids.NewId(clock)), ("k", code), ("m", message), ("at", clock.UtcNow)).ConfigureAwait(false);
await Notifications.NotificationSender.EnqueueAsync(s, clock, code, message, cancellationToken).ConfigureAwait(false);
}
}
+5 -2
View File
@@ -786,9 +786,12 @@ public sealed partial class OrderManager : IDisposable
}
var reason = fill.Side == OrderSide.Sell && row.Purpose is OrderPurpose.Stop or OrderPurpose.Protective ? ReasonCatalog.Text("stop") : null;
await Diary.WriteAsync(s, _clock, DiaryKinds.Orders, "fill",
DiaryText.Fill(fill.Side, fill.Quantity, instrument?.Symbol ?? "?", instrument?.IsCrypto ?? false, fill.Price, _account.Currency, reason, closed),
var text = DiaryText.Fill(fill.Side, fill.Quantity, instrument?.Symbol ?? "?", instrument?.IsCrypto ?? false, fill.Price, _account.Currency, reason, closed);
await Diary.WriteAsync(s, _clock, DiaryKinds.Orders, "fill", text,
new { fill.ExecutionId, row.ClientOrderId, outcome.SlippageBp, outcome.TradeId, Account = _account.Name }, cancellationToken).ConfigureAwait(false);
// Every purchase and sale reaches the phone, with the result when it closes a trade (SPEC 14).
await Notifications.NotificationSender.EnqueueAsync(s, _clock, "fill", _account.Name + ": " + text, cancellationToken).ConfigureAwait(false);
}, cancellationToken).ConfigureAwait(false);
if (row.Purpose == OrderPurpose.Stop && outcome.Quantity > 0m && instrument is not null)
{
+2 -1
View File
@@ -76,7 +76,7 @@ internal sealed partial class ServerHarness : IAsyncDisposable
}
public static async Task<ServerHarness> StartAsync(string platform, IReadOnlyDictionary<string, string?> environment, string? dataDir = null,
string[]? extraArgs = null, bool waitReady = true, HttpMessageHandler? marketHttp = null, bool trading = false)
string[]? extraArgs = null, bool waitReady = true, HttpMessageHandler? marketHttp = null, bool trading = false, HttpMessageHandler? telegramHttp = null)
{
var owns = dataDir is null;
dataDir ??= TempFolder.Create("server");
@@ -90,6 +90,7 @@ internal sealed partial class ServerHarness : IAsyncDisposable
MarketHttp = marketHttp,
MarketSockets = marketHttp is null ? null : () => new FakeSocket(),
Trading = trading,
TelegramHttp = telegramHttp,
});
await app.StartAsync().ConfigureAwait(false);
var cookies = new CookieContainer();
+363
View File
@@ -0,0 +1,363 @@
using System.Collections.Concurrent;
using System.Net;
using System.Text;
using System.Text.Json;
using Anubis.Core;
using Anubis.Notifications;
using Anubis.Server;
using Microsoft.Extensions.Logging.Abstractions;
namespace Anubis.Tests;
/// <summary>Telegram and the sign of life (issue #52, SPEC 14), against a fake Telegram server.</summary>
[TestClass]
public sealed class TelegramTests
{
private const string Token = "123456:fake-token-for-tests_abcdefghijklmnop";
private const string Chat = "424242";
private static readonly CancellationToken _none = CancellationToken.None;
[TestMethod]
[TestCategory(Category.Unit)]
public async Task EveryMessageHasItsStateAndAFailureIsTriedAgainLater()
{
await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false);
var telegram = new FakeTelegram();
TelegramSettings? configured = null;
using var http = new HttpClient(telegram);
var sender = new NotificationSender(rig.Db, rig.Clock, _ => Task.FromResult(configured), token => new TelegramClient(http, token));
await EnqueueAsync(rig, "uno", "due").ConfigureAwait(false);
// Without Telegram the messages wait in the queue: never "sent".
Assert.AreEqual(0, await sender.SendDueAsync(_none).ConfigureAwait(false));
Assert.AreEqual(new NotificationSummary(null, 2, 0, 0, null), await sender.SummaryAsync(_none).ConfigureAwait(false));
// Telegram slows us down: the first fails, the second waits for the next pass.
configured = new TelegramSettings(Token, Chat);
telegram.Refuse = "sendMessage";
telegram.RefusalStatus = HttpStatusCode.TooManyRequests;
Assert.AreEqual(0, await sender.SendDueAsync(_none).ConfigureAwait(false));
var states = await StatesAsync(rig).ConfigureAwait(false);
Assert.AreEqual("failed/1/Telegram ha risposto 429: Too Many Requests: retry after 90", states["uno"].Text);
Assert.AreEqual(rig.Clock.UtcNow.AddSeconds(90), states["uno"].Next, "Telegram's own wait, longer than the first pause of a minute.");
Assert.AreEqual("pending/0/", states["due"].Text);
// Back up: what is due leaves, the failed one when its time comes.
telegram.Refuse = null;
Assert.AreEqual(1, await sender.SendDueAsync(_none).ConfigureAwait(false));
rig.Clock.Advance(TimeSpan.FromSeconds(90));
Assert.AreEqual(1, await sender.SendDueAsync(_none).ConfigureAwait(false));
states = await StatesAsync(rig).ConfigureAwait(false);
Assert.AreEqual(("sent/2/", "sent/1/"), (states["uno"].Text, states["due"].Text));
Assert.AreEqual(2, telegram.Sent.Count(m => m.Chat == Chat));
Assert.AreEqual(new NotificationSummary(rig.Clock.UtcNow, 0, 0, 0, null), await sender.SummaryAsync(_none).ConfigureAwait(false));
}
[TestMethod]
[TestCategory(Category.Unit)]
public async Task ARefusalIsNotTriedAgainAndAMessageOlderThanADayIsGivenUp()
{
await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false);
var telegram = new FakeTelegram { Refuse = "sendMessage", RefusalStatus = HttpStatusCode.BadRequest };
using var http = new HttpClient(telegram);
var sender = new NotificationSender(rig.Db, rig.Clock, _ => Task.FromResult<TelegramSettings?>(new TelegramSettings(Token, Chat)),
token => new TelegramClient(http, token));
await EnqueueAsync(rig, "rifiutato").ConfigureAwait(false);
await sender.SendDueAsync(_none).ConfigureAwait(false);
var states = await StatesAsync(rig).ConfigureAwait(false);
Assert.AreEqual("failed/1/Telegram ha risposto 400: Bad Request: chat not found", states["rifiutato"].Text);
Assert.IsNull(states["rifiutato"].Next, "A refusal is final: the same message would be refused again.");
telegram.Refuse = null;
await EnqueueAsync(rig, "vecchio").ConfigureAwait(false);
rig.Clock.Advance(TimeSpan.FromHours(25));
Assert.AreEqual(0, await sender.SendDueAsync(_none).ConfigureAwait(false));
states = await StatesAsync(rig).ConfigureAwait(false);
Assert.AreEqual("failed/0/Non partito entro un giorno: non lo mando più.", states["vecchio"].Text);
Assert.IsEmpty(telegram.Sent);
var summary = await sender.SummaryAsync(_none).ConfigureAwait(false);
Assert.AreEqual((0, 0, 2), (summary.Pending, summary.Retrying, summary.GaveUp));
// The pauses between attempts grow up to an hour.
Assert.AreEqual("1 2 4 8 16 32 60 60", string.Join(" ", Enumerable.Range(1, 8).Select(a => NotificationSender.Pause(a).TotalMinutes)));
}
[TestMethod]
[TestCategory(Category.Unit)]
public async Task FermaWantsAConfirmationWithinTwoMinutes()
{
var clock = new ManualClock(new DateTimeOffset(2026, 11, 11, 9, 0, 0, TimeSpan.Zero));
var desk = new FakeDesk();
var commands = new TelegramCommands(desk, clock);
Assert.Contains("/conferma entro 2 minuti", (await commands.AnswerAsync("/ferma", _none).ConfigureAwait(false))!);
Assert.AreEqual(0, desk.Stops);
clock.Advance(TimeSpan.FromSeconds(100));
Assert.AreEqual("fermato", await commands.AnswerAsync("/conferma", _none).ConfigureAwait(false));
Assert.AreEqual(1, desk.Stops);
// Too late, or another command in between: nothing to confirm.
await commands.AnswerAsync("/ferma", _none).ConfigureAwait(false);
clock.Advance(TimeSpan.FromMinutes(3));
Assert.Contains("niente da confermare", (await commands.AnswerAsync("/conferma", _none).ConfigureAwait(false))!);
await commands.AnswerAsync("/ferma", _none).ConfigureAwait(false);
await commands.AnswerAsync("/stato", _none).ConfigureAwait(false);
Assert.Contains("niente da confermare", (await commands.AnswerAsync("/conferma", _none).ConfigureAwait(false))!);
Assert.AreEqual(1, desk.Stops);
// The other commands, the bot's name of a group, help, and plain text that is no command.
Assert.AreEqual("stato", await commands.AnswerAsync("/stato@AnubisBot", _none).ConfigureAwait(false));
Assert.AreEqual("posizioni", await commands.AnswerAsync("/POSIZIONI", _none).ConfigureAwait(false));
Assert.AreEqual("oggi", await commands.AnswerAsync(" /oggi grazie", _none).ConfigureAwait(false));
Assert.AreEqual("pausa", await commands.AnswerAsync("/pausa", _none).ConfigureAwait(false));
Assert.AreEqual("riprendi", await commands.AnswerAsync("/riprendi", _none).ConfigureAwait(false));
Assert.AreEqual(TelegramCommands.Help, await commands.AnswerAsync("/aiuto", _none).ConfigureAwait(false));
Assert.StartsWith("Non conosco questo comando.", (await commands.AnswerAsync("/compra BTC", _none).ConfigureAwait(false))!);
Assert.IsNull(await commands.AnswerAsync("ciao", _none).ConfigureAwait(false));
Assert.DoesNotContain("limiti", TelegramCommands.Help.Split('\n')[0]);
}
[TestMethod]
[TestCategory(Category.Unit)]
public async Task OnlyTheChatOfTheSettingsIsObeyedAndOldMessagesAreNot()
{
var clock = new ManualClock(new DateTimeOffset(2026, 11, 11, 9, 0, 0, TimeSpan.Zero));
var telegram = new FakeTelegram();
using var http = new HttpClient(telegram);
var desk = new FakeDesk();
var bot = new TelegramBot(clock, _ => Task.FromResult<TelegramSettings?>(new TelegramSettings(Token, Chat)), token => new TelegramClient(http, token),
new TelegramCommands(desk, clock), NullLogger.Instance);
telegram.Write("999", "/pausa", clock.UtcNow);
telegram.Write(Chat, "/pausa", clock.UtcNow - TimeSpan.FromHours(20));
telegram.Write(Chat, "/stato", clock.UtcNow);
Assert.AreEqual(1, await bot.PollOnceAsync(_none).ConfigureAwait(false));
Assert.AreEqual((Chat, "stato"), telegram.Sent.Single());
Assert.AreEqual(0, desk.Pauses, "Neither the stranger's /pausa nor yesterday's.");
// The next read tells Telegram the first three were read.
Assert.AreEqual(0, await bot.PollOnceAsync(_none).ConfigureAwait(false));
Assert.AreEqual(4, telegram.LastOffset);
// Without Telegram configured the loop only waits.
var idle = new TelegramBot(clock, _ => Task.FromResult<TelegramSettings?>(null), token => new TelegramClient(http, token), new TelegramCommands(desk, clock),
NullLogger.Instance);
Assert.AreEqual(-1, await idle.PollOnceAsync(_none).ConfigureAwait(false));
}
[TestMethod]
[TestCategory(Category.Unit)]
public async Task TheSignOfLifeCallsTheServiceAndSaysWhenItFails()
{
var clock = new ManualClock(new DateTimeOffset(2026, 11, 11, 9, 0, 0, TimeSpan.Zero));
var calls = 0;
var fake = new FakeHttp().On(u => u.Host == "hc.example", _ => FakeHttp.Respond("OK", ++calls == 2 ? HttpStatusCode.ServiceUnavailable : HttpStatusCode.OK));
using var http = fake.Client();
Uri? address = null;
var beat = new Heartbeat(http, clock, _ => Task.FromResult(address), NullLogger.Instance);
Assert.IsFalse(await beat.BeatAsync(_none).ConfigureAwait(false), "No address, no call.");
Assert.IsEmpty(fake.Requests);
address = new Uri("https://hc.example/ping/abc");
Assert.IsTrue(await beat.BeatAsync(_none).ConfigureAwait(false));
Assert.AreEqual(clock.UtcNow, beat.LastOk);
clock.Advance(TimeSpan.FromMinutes(1));
Assert.IsFalse(await beat.BeatAsync(_none).ConfigureAwait(false));
Assert.AreEqual(("Il servizio ha risposto 503.", clock.UtcNow - TimeSpan.FromMinutes(1)), (beat.LastError, beat.LastOk));
Assert.IsNull(Heartbeat.Check("https://hc-ping.com/uuid"));
Assert.IsNull(Heartbeat.Check("http://192.168.30.23:8000/ping/x"));
Assert.IsNotNull(Heartbeat.Check("http://hc-ping.com/uuid"));
Assert.IsNotNull(Heartbeat.Check("ftp://example.com"));
Assert.IsNotNull(Heartbeat.Check("non è un indirizzo"));
}
/// <summary>
/// The acceptance criterion of SPEC 14 with the real server: commands from the phone change the bot's state, the
/// changes reach the phone, a stranger is ignored, and after "Ferma tutto" the phone cannot restart the bot.
/// </summary>
[TestMethod]
[TestCategory(Category.Integration)]
public async Task TheCommandsWorkFromThePhoneThroughTheRealServer()
{
var telegram = new FakeTelegram();
var env = ServerHarness.DockerSqlite();
env["TELEGRAM_BOT_TOKEN"] = Token;
env["TELEGRAM_CHAT_ID"] = Chat;
await using var server = await ServerHarness.StartAsync("docker", env, telegramHttp: telegram).ConfigureAwait(false);
var services = server.Host.Services!;
async Task<string> AskAsync(string text, string chat = Chat)
{
var before = telegram.Sent.Count;
telegram.Write(chat, text, DateTimeOffset.UtcNow);
var until = DateTimeOffset.UtcNow.AddSeconds(20);
while (DateTimeOffset.UtcNow < until)
{
if (telegram.Sent.Skip(before).FirstOrDefault(m => m.Chat == chat && !m.Text.Contains("(da Telegram)", StringComparison.Ordinal)) is { Text: { } answer })
{
return answer;
}
await Task.Delay(50).ConfigureAwait(false);
}
return "(nessuna risposta)";
}
async Task<string> StateAsync() => (await services.Settings.GetAsync(SettingsStore.BotState.Key, _none).ConfigureAwait(false)).Value;
Assert.StartsWith("Bot attivo", await AskAsync("/stato").ConfigureAwait(false));
Assert.AreEqual("Nessuna posizione aperta.", await AskAsync("/posizioni").ConfigureAwait(false));
Assert.AreEqual("Nessun ordine oggi.", await AskAsync("/oggi").ConfigureAwait(false));
Assert.StartsWith("In pausa", await AskAsync("/pausa").ConfigureAwait(false));
Assert.AreEqual("paused", await StateAsync().ConfigureAwait(false));
await WaitForAsync(() => telegram.Sent.Any(m => m.Text.StartsWith("Bot in pausa (da Telegram)", StringComparison.Ordinal))).ConfigureAwait(false);
Assert.AreEqual("(nessuna risposta)", await AskAsync("/riprendi", "777").ConfigureAwait(false), "Another chat gets nothing.");
Assert.AreEqual("paused", await StateAsync().ConfigureAwait(false));
Assert.AreEqual("Ripartito dalla pausa.", await AskAsync("/riprendi").ConfigureAwait(false));
Assert.AreEqual("active", await StateAsync().ConfigureAwait(false));
Assert.Contains("/conferma", await AskAsync("/ferma").ConfigureAwait(false));
Assert.AreEqual("active", await StateAsync().ConfigureAwait(false));
Assert.StartsWith("«Ferma tutto» fatto", await AskAsync("/conferma").ConfigureAwait(false));
Assert.AreEqual("stopped", await StateAsync().ConfigureAwait(false));
Assert.Contains("riattivalo dalla pagina Rischio", await AskAsync("/riprendi").ConfigureAwait(false));
Assert.AreEqual("stopped", await StateAsync().ConfigureAwait(false));
// Every notice has its state, and the Impostazioni page shows the last message that left.
await WaitForAsync(() => telegram.Sent.Any(m => m.Text.StartsWith("«Ferma tutto» (da Telegram)", StringComparison.Ordinal))).ConfigureAwait(false);
var notices = await services.Db.ReadAsync(s => s.QueryAsync("SELECT kind, status FROM notifications", r => r.Text("kind") + "/" + r.Text("status")), _none)
.ConfigureAwait(false);
Assert.Contains("bot_paused/sent", notices);
Assert.Contains("bot_active/sent", notices);
Assert.IsFalse(telegram.Sent.Any(m => m.Text.Contains(Token, StringComparison.Ordinal)));
await server.SignInFirstTimeAsync().ConfigureAwait(false);
var page = await server.TextAsync("/impostazioni").ConfigureAwait(false);
Assert.Contains("Telegram e segnale di vita", page);
Assert.Contains("Token e chat arrivano dalle variabili", page);
Assert.DoesNotContain(Token, page);
}
private static async Task WaitForAsync(Func<bool> condition)
{
var until = DateTimeOffset.UtcNow.AddSeconds(20);
while (!condition())
{
Assert.IsLessThan(until, DateTimeOffset.UtcNow, "Timed out.");
await Task.Delay(50).ConfigureAwait(false);
}
}
private static Task EnqueueAsync(TradingRig rig, params string[] messages) =>
rig.Db.WriteAsync(async s =>
{
foreach (var message in messages)
{
await NotificationSender.EnqueueAsync(s, rig.Clock, "test", message, _none).ConfigureAwait(false);
rig.Clock.Advance(TimeSpan.FromMilliseconds(1));
}
}, _none);
private static async Task<Dictionary<string, (string Text, DateTimeOffset? Next)>> StatesAsync(TradingRig rig) =>
(await rig.QueryAsync("SELECT message, status, attempts, last_error, next_attempt_at FROM notifications",
r => (Message: r.Text("message"), Text: r.Text("status") + "/" + r.Number("attempts") + "/" + r.TextOrNull("last_error"), Next: r.MomentOrNull("next_attempt_at")))
.ConfigureAwait(false)).ToDictionary(x => x.Message, x => (x.Text, x.Next));
private sealed class FakeDesk : ITelegramDesk
{
public int Stops { get; private set; }
public int Pauses { get; private set; }
public Task<string> StatusAsync(CancellationToken cancellationToken) => Task.FromResult("stato");
public Task<string> PositionsAsync(CancellationToken cancellationToken) => Task.FromResult("posizioni");
public Task<string> TodayAsync(CancellationToken cancellationToken) => Task.FromResult("oggi");
public Task<string> PauseAsync(CancellationToken cancellationToken)
{
Pauses++;
return Task.FromResult("pausa");
}
public Task<string> ResumeAsync(CancellationToken cancellationToken) => Task.FromResult("riprendi");
public Task<string> StopAllAsync(CancellationToken cancellationToken)
{
Stops++;
return Task.FromResult("fermato");
}
}
}
/// <summary>
/// A Telegram Bot API on the test's side: messages written by the test come back from getUpdates, sendMessage is
/// recorded, and one method can be made to refuse. getUpdates answers at once (no long wait) after a short pause.
/// </summary>
internal sealed class FakeTelegram : HttpMessageHandler
{
private readonly ConcurrentQueue<(long Id, string Chat, string Text, DateTimeOffset Date)> _updates = new();
private long _nextId = 1;
public List<(string Chat, string Text)> Sent { get; } = [];
public long LastOffset { get; private set; }
/// <summary>The method that fails, with <see cref="RefusalStatus"/>.</summary>
public string? Refuse { get; set; }
public HttpStatusCode RefusalStatus { get; set; } = HttpStatusCode.BadRequest;
public void Write(string chat, string text, DateTimeOffset at) => _updates.Enqueue((Interlocked.Increment(ref _nextId) - 1, chat, text, at));
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var method = request.RequestUri!.AbsolutePath.Split('/')[^1];
using var body = JsonDocument.Parse(request.Content is null ? "{}" : await request.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false));
if (method == Refuse)
{
return RefusalStatus == HttpStatusCode.TooManyRequests
? Json(RefusalStatus, """{"ok":false,"error_code":429,"description":"Too Many Requests: retry after 90","parameters":{"retry_after":90}}""")
: Json(RefusalStatus, """{"ok":false,"error_code":400,"description":"Bad Request: chat not found"}""");
}
switch (method)
{
case "getMe":
return Json(HttpStatusCode.OK, """{"ok":true,"result":{"id":1,"is_bot":true,"username":"AnubisProvaBot"}}""");
case "sendMessage":
lock (Sent)
{
Sent.Add((body.RootElement.GetProperty("chat_id").GetString()!, body.RootElement.GetProperty("text").GetString()!));
}
return Json(HttpStatusCode.OK, """{"ok":true,"result":{"message_id":1}}""");
case "getUpdates":
var offset = body.RootElement.TryGetProperty("offset", out var o) ? o.GetInt64() : 0;
LastOffset = offset;
while (_updates.TryPeek(out var first) && first.Id < offset)
{
_updates.TryDequeue(out _);
}
if (_updates.IsEmpty)
{
await Task.Delay(30, cancellationToken).ConfigureAwait(false);
}
var items = _updates.ToArray().Where(u => u.Id >= offset).Select(u => new
{
update_id = u.Id,
message = new { message_id = u.Id, date = u.Date.ToUnixTimeSeconds(), chat = new { id = long.Parse(u.Chat, System.Globalization.CultureInfo.InvariantCulture) }, text = u.Text },
});
return Json(HttpStatusCode.OK, JsonSerializer.Serialize(new { ok = true, result = items }));
default:
return Json(HttpStatusCode.NotFound, """{"ok":false,"description":"Not Found"}""");
}
}
private static HttpResponseMessage Json(HttpStatusCode status, string json) => new(status) { Content = new StringContent(json, Encoding.UTF8, "application/json") };
}