Every notice is written to the queue in the same transaction as what it tells, then sent every ten seconds. Each has a state: pending, sent, or failed with its error. Network failures and 429s are retried with growing pauses (Telegram's own wait when it gives one). Refusals are final. A notice that could not leave within a day is given up instead of arriving late. Every fill now also reaches the phone, and so do pause, resume and restart. Commands are read by long polling and obeyed only from the configured chat and only when fresh, so yesterday's /pausa never pauses today. They are /stato, /posizioni, /oggi, /pausa, /riprendi, /ferma (confirmed with /conferma within two minutes) and /aiuto. Restarting after "Ferma tutto", real money, limits and keys stay in the interface. Also added: - the heartbeat call every minute when an address is configured; - the morning summary at 08:00, caught up within four hours; - an optional hourly or evening status; - a Telegram section in Impostazioni: test-before-save, a test button, the queue's state and the last successful heartbeat; - on desktop, the first-run page recommends the heartbeat. Tests run against a fake Telegram server, including the commands through the real server. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
364 lines
19 KiB
C#
364 lines
19 KiB
C#
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") };
|
|
}
|