From ea6ba274624cf2f662ddde4432a0cb58486a0ab8 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Fri, 27 Nov 2026 09:26:10 +0100 Subject: [PATCH] =?UTF-8?q?Telegram:=20il=20messaggio=20di=20prova=20dice?= =?UTF-8?q?=20sempre=20il=20motivo=20vero,=20e=20la=20coda=20=C3=A8=20sott?= =?UTF-8?q?o=20test=20(#35)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit L'interfaccia aspettava la risposta di «Invia messaggio di prova» 30 s, mentre il client verso Telegram scadeva a 40 s: con Telegram irraggiungibile compariva «Il bot non ha risposto in tempo» invece di «Telegram non raggiungibile». Ora ogni richiesta a Telegram ha il suo tempo massimo, la nuova impostazione «Tempo massimo di una richiesta» (TelegramTimeoutSeconds, 15 s, da 5 a 60, vale subito), e oltre quel tempo l'esito è «Telegram non raggiungibile: nessuna risposta in N s». L'interfaccia aspetta 15 s in più del valore salvato, così l'errore vero arriva sempre; la lettura dei comandi aspetta il polling lungo più lo stesso tempo. Il client non ha più un tempo suo. Le attese del notificatore (fra i tentativi e nei cicli) si possono iniettare, senza cambiare il comportamento, e TelegramNotifierTests le prova contro un Telegram finto: messaggio di prova riuscito, rifiutato, con errore di rete, senza risposta, senza token o chat; i tre tentativi della coda con attese di 4 e 8 s e una sola riga nel registro finché un messaggio non riparte; una scadenza nella coda, che scrive «nessuna risposta in N s» e non chiude il ciclo di invio (il messaggio dopo parte); i comandi accettati solo dalla chat configurata. Guida: Telegram e Impostazioni. Co-Authored-By: Claude Opus 5.5 --- docs/guida/Impostazioni.md | 7 +- docs/guida/Telegram.md | 11 +- src/Mimante/Settings/AppSettings.cs | 8 + src/Mimante/Settings/SettingsStore.cs | 1 + src/Mimante/Telegram/TelegramNotifier.cs | 46 ++- src/Mimante/wwwroot/js/pages/impostazioni.js | 12 +- tests/Mimante.Tests/TelegramNotifierTests.cs | 324 +++++++++++++++++++ 7 files changed, 391 insertions(+), 18 deletions(-) create mode 100644 tests/Mimante.Tests/TelegramNotifierTests.cs diff --git a/docs/guida/Impostazioni.md b/docs/guida/Impostazioni.md index 67b704e..4a71811 100644 --- a/docs/guida/Impostazioni.md +++ b/docs/guida/Impostazioni.md @@ -121,9 +121,10 @@ Puntate gratis, dove ci sono anche le spiegazioni dei tetti, delle ore e delle p ## Telegram -Token del bot, chat, quali messaggi mandare, riepilogo, comandi, e il bottone **«Invia messaggio di prova»**. Accanto -al bottone leggi «token e chat impostati» oppure «token o chat mancanti». Il token, una volta salvato, si vede solo come -asterischi. Tutto in [Telegram](Telegram). +Token del bot, chat, quali messaggi mandare, riepilogo, comandi, il **Tempo massimo di una richiesta** (15 s di +fabbrica, da 5 a 60: oltre, il messaggio conta come «Telegram non raggiungibile») e il bottone **«Invia messaggio di +prova»**. Accanto al bottone leggi «token e chat impostati» oppure «token o chat mancanti». Il token, una volta salvato, +si vede solo come asterischi. Tutto in [Telegram](Telegram). ## Dati e conservazione diff --git a/docs/guida/Telegram.md b/docs/guida/Telegram.md index 4daacba..91a42a9 100644 --- a/docs/guida/Telegram.md +++ b/docs/guida/Telegram.md @@ -46,7 +46,9 @@ pagina può restare vuota. L'indirizzo contiene il token: non condividerlo. le notifiche arrivano.». Se non arriva, Mimante dice perché: - «Scrivi token del bot e chat id, salva, poi riprova»: manca uno dei due, o non hai salvato; - «Telegram ha rifiutato il messaggio: controlla token e chat id (scrivi prima un messaggio al bot)»; - - «Telegram non raggiungibile», con l'errore di rete. + - «Telegram non raggiungibile», con l'errore di rete, oppure «nessuna risposta in 15 s» se Telegram non risponde + entro il **Tempo massimo di una richiesta** (15 secondi di fabbrica, da 5 a 60). L'interfaccia aspetta 15 + secondi in più, così vedi sempre il motivo vero e non un generico «Il bot non ha risposto in tempo». Accanto al bottone leggi «token e chat impostati» oppure «token o chat mancanti». @@ -104,9 +106,10 @@ Usalo solo se sai perché le puntate si erano fermate (vedi [Paletti e rischio]( ## Se un messaggio non parte I messaggi passano da una coda, così un Telegram lento non rallenta mai il motore. Ogni messaggio si prova tre volte, -con un'attesa che cresce. Se non parte nemmeno alla terza, il registro scrive una riga `[TELEGRAM]` «Messaggio non -inviato dopo tre tentativi» (una sola, finché un messaggio non torna a partire). Mimante non riprova oltre: controlla -le impostazioni e usa «Invia messaggio di prova». +con un'attesa che cresce (4 secondi prima del secondo tentativo, 8 prima del terzo); ogni tentativo aspetta Telegram al +più il **Tempo massimo di una richiesta**. Se non parte nemmeno alla terza, il registro scrive una riga `[TELEGRAM]` +«Messaggio non inviato dopo tre tentativi» (una sola, finché un messaggio non torna a partire). Mimante non riprova +oltre: controlla le impostazioni e usa «Invia messaggio di prova». ## Dove sta il token diff --git a/src/Mimante/Settings/AppSettings.cs b/src/Mimante/Settings/AppSettings.cs index be22752..aff35f9 100644 --- a/src/Mimante/Settings/AppSettings.cs +++ b/src/Mimante/Settings/AppSettings.cs @@ -249,6 +249,14 @@ public sealed class AppSettings /// Comandi in ingresso (/stato, /halt, /riprendi, /osserva) dal solo chat id configurato. public bool TelegramCommandsEnabled { get; set; } + /// + /// Tempo massimo di una richiesta a Telegram, in secondi: un messaggio (in coda o di prova) + /// che non ha risposta entro questo tempo conta come «Telegram non raggiungibile». La lettura + /// dei comandi aspetta questo tempo in più del suo polling lungo. L'interfaccia aspetta la + /// risposta del messaggio di prova un po' più a lungo, così l'errore vero arriva sempre. + /// + public int TelegramTimeoutSeconds { get; set; } = 15; + // ── Dati e conservazione ───────────────────────────────────────────── public double DataCapGb { get; set; } = 50; diff --git a/src/Mimante/Settings/SettingsStore.cs b/src/Mimante/Settings/SettingsStore.cs index 8968593..56be9cd 100644 --- a/src/Mimante/Settings/SettingsStore.cs +++ b/src/Mimante/Settings/SettingsStore.cs @@ -225,6 +225,7 @@ public sealed class SettingsStore s.TelegramBotToken = (s.TelegramBotToken ?? "").Trim(); s.TelegramChatId = (s.TelegramChatId ?? "").Trim(); s.TelegramSummaryMinutes = Math.Clamp(s.TelegramSummaryMinutes, 0, 24 * 60); + s.TelegramTimeoutSeconds = Math.Clamp(s.TelegramTimeoutSeconds, 5, 60); s.DataCapGb = Math.Clamp(s.DataCapGb, 1, 10_000); s.LogRetentionDays = Math.Clamp(s.LogRetentionDays, 0, 3650); diff --git a/src/Mimante/Telegram/TelegramNotifier.cs b/src/Mimante/Telegram/TelegramNotifier.cs index a21ab60..8372849 100644 --- a/src/Mimante/Telegram/TelegramNotifier.cs +++ b/src/Mimante/Telegram/TelegramNotifier.cs @@ -12,9 +12,13 @@ namespace Mimante.Telegram; /// public sealed class TelegramNotifier : IAsyncDisposable { + /// Quanto aspetta Telegram con getUpdates prima di rispondere senza messaggi nuovi. + private const int LongPollSeconds = 25; + private readonly Func _settings; private readonly AppLog _log; private readonly HttpClient _http; + private readonly Func _delay; private readonly Channel _queue = Channel.CreateBounded(new BoundedChannelOptions(200) { FullMode = BoundedChannelFullMode.DropOldest }); private readonly CancellationTokenSource _cts = new(); private readonly Task _sender; @@ -25,11 +29,16 @@ public sealed class TelegramNotifier : IAsyncDisposable /// Risponde a un comando ricevuto: il testo della risposta. public Func>? CommandHandler { get; set; } - public TelegramNotifier(Func settings, AppLog log, HttpClient? http = null) + /// Il client verso Telegram; i test ne passano uno con un gestore finto. + /// Le attese fra i tentativi e dei cicli (di serie ); i test le accorciano. + public TelegramNotifier(Func settings, AppLog log, HttpClient? http = null, Func? delay = null) { _settings = settings; _log = log; - _http = http ?? new HttpClient { Timeout = TimeSpan.FromSeconds(40) }; + // Nessun tempo massimo sul client: ogni richiesta ha il suo (TelegramTimeoutSeconds), + // che vale dal vivo e dà un errore leggibile invece della scadenza generica del client. + _http = http ?? new HttpClient { Timeout = Timeout.InfiniteTimeSpan }; + _delay = delay ?? Task.Delay; _sender = Task.Run(() => SendLoopAsync(_cts.Token)); _commands = Task.Run(() => CommandLoopAsync(_cts.Token)); } @@ -57,16 +66,29 @@ public sealed class TelegramNotifier : IAsyncDisposable return (false, "Scrivi token del bot e chat id, salva, poi riprova"); try { - var ok = await TelegramApi.SendAsync(_http, s.TelegramBotToken, s.TelegramChatId, - TelegramFormat.Message("Messaggio di prova da Mimante", "Se lo leggi, le notifiche arrivano."), ct).ConfigureAwait(false); + var ok = await SendOnceAsync(s, TelegramFormat.Message("Messaggio di prova da Mimante", "Se lo leggi, le notifiche arrivano."), ct).ConfigureAwait(false); return ok ? (true, "Messaggio inviato") : (false, "Telegram ha rifiutato il messaggio: controlla token e chat id (scrivi prima un messaggio al bot)"); } + catch (OperationCanceledException) when (!ct.IsCancellationRequested) + { + return (false, $"Telegram non raggiungibile: {NoAnswer(s)}"); + } catch (Exception ex) { return (false, $"Telegram non raggiungibile: {ex.Message}"); } } + /// Un solo invio, con il tempo massimo delle impostazioni sopra quello di chi chiama. + private async Task SendOnceAsync(AppSettings s, string text, CancellationToken ct) + { + using var limit = CancellationTokenSource.CreateLinkedTokenSource(ct); + limit.CancelAfter(TimeSpan.FromSeconds(s.TelegramTimeoutSeconds)); + return await TelegramApi.SendAsync(_http, s.TelegramBotToken, s.TelegramChatId, text, limit.Token).ConfigureAwait(false); + } + + private static string NoAnswer(AppSettings s) => $"nessuna risposta in {s.TelegramTimeoutSeconds} s"; + private async Task SendLoopAsync(CancellationToken ct) { try @@ -80,9 +102,10 @@ public sealed class TelegramNotifier : IAsyncDisposable string? error = null; for (var attempt = 0; attempt < 3 && !sent; attempt++) { - if (attempt > 0) await Task.Delay(TimeSpan.FromSeconds(2 << attempt), ct).ConfigureAwait(false); - try { sent = await TelegramApi.SendAsync(_http, s.TelegramBotToken, s.TelegramChatId, text, ct).ConfigureAwait(false); } + if (attempt > 0) await _delay(TimeSpan.FromSeconds(2 << attempt), ct).ConfigureAwait(false); + try { sent = await SendOnceAsync(s, text, ct).ConfigureAwait(false); } catch (OperationCanceledException) when (ct.IsCancellationRequested) { return; } + catch (OperationCanceledException) { error = NoAnswer(s); } catch (Exception ex) { error = ex.Message; } } @@ -104,13 +127,18 @@ public sealed class TelegramNotifier : IAsyncDisposable var s = _settings(); if (!s.TelegramCommandsEnabled || !Configured || CommandHandler == null) { - try { await Task.Delay(TimeSpan.FromSeconds(10), ct).ConfigureAwait(false); } catch (OperationCanceledException) { return; } + try { await _delay(TimeSpan.FromSeconds(10), ct).ConfigureAwait(false); } catch (OperationCanceledException) { return; } continue; } try { - var updates = await TelegramApi.GetUpdatesAsync(_http, s.TelegramBotToken, _offset, 25, ct).ConfigureAwait(false); + IReadOnlyList updates; + using (var limit = CancellationTokenSource.CreateLinkedTokenSource(ct)) + { + limit.CancelAfter(TimeSpan.FromSeconds(LongPollSeconds + s.TelegramTimeoutSeconds)); + updates = await TelegramApi.GetUpdatesAsync(_http, s.TelegramBotToken, _offset, LongPollSeconds, limit.Token).ConfigureAwait(false); + } foreach (var u in updates) { _offset = Math.Max(_offset, u.UpdateId + 1); @@ -124,7 +152,7 @@ public sealed class TelegramNotifier : IAsyncDisposable catch (OperationCanceledException) when (ct.IsCancellationRequested) { return; } catch (Exception) { - try { await Task.Delay(TimeSpan.FromSeconds(30), ct).ConfigureAwait(false); } catch (OperationCanceledException) { return; } + try { await _delay(TimeSpan.FromSeconds(30), ct).ConfigureAwait(false); } catch (OperationCanceledException) { return; } } } } diff --git a/src/Mimante/wwwroot/js/pages/impostazioni.js b/src/Mimante/wwwroot/js/pages/impostazioni.js index 0345321..4a469a0 100644 --- a/src/Mimante/wwwroot/js/pages/impostazioni.js +++ b/src/Mimante/wwwroot/js/pages/impostazioni.js @@ -107,7 +107,8 @@ const sections = [ ['TelegramNotifySession', 'Sessione scaduta', B, 'Un messaggio quando Bidoo non riconosce più l\'utente collegato'], ['TelegramNotifyRisk', 'HALT, ripresa, spazio dati', B, 'Un messaggio quando le puntate si bloccano o ripartono, o quando il database è quasi pieno'], ['TelegramSummaryMinutes', 'Riepilogo ogni min', I, '0 = mai'], - ['TelegramCommandsEnabled', 'Comandi /stato /halt /riprendi /osserva', B, 'Solo dalla chat configurata'] + ['TelegramCommandsEnabled', 'Comandi /stato /halt /riprendi /osserva', B, 'Solo dalla chat configurata'], + ['TelegramTimeoutSeconds', 'Tempo massimo di una richiesta s', I, 'Da 5 a 60. Un messaggio senza risposta di Telegram entro questo tempo conta come «Telegram non raggiungibile»'] ] }, { title: 'Dati e conservazione', hint: 'Spazio del database, registri su file, backup ed esportazioni', data: true, fields: [ ['DataCapGb', 'Spazio massimo del database GB', N, 'Oltre, ogni notte si tolgono le partizioni più vecchie fino al 90%'], @@ -208,7 +209,7 @@ function render() { body.append(...sec.fields.map(field)); if (sec.risk) body.append(el('div', { id: 'risk-box', class: 'full extra' })); if (sec.telegram) body.append(el('div', { class: 'row full extra' }, - el('button', { class: 'btn', type: 'button', title: 'Manda un messaggio di prova con token e chat salvati', onclick: async () => report(await send({ t: 'telegram.test' }, 30000), { important: true }) }, 'Invia messaggio di prova'), + el('button', { class: 'btn', type: 'button', title: 'Manda un messaggio di prova con token e chat salvati', onclick: testTelegram }, 'Invia messaggio di prova'), el('span', { class: 'help', title: 'Se token del bot e chat ID sono salvati' }, system.telegramReady ? 'token e chat impostati' : 'token o chat mancanti'))); if (sec.data) body.append(el('div', { id: 'data-box', class: 'full extra' })); if (sec.net) body.append(el('div', { id: 'net-box', class: 'full extra' })); @@ -222,6 +223,13 @@ function render() { renderRisk(); renderData(); renderNet(); renderSystem(); } +// Il bot aspetta Telegram al più TelegramTimeoutSeconds (salvato); l'interfaccia aspetta 15 s in più, +// così l'esito vero («Telegram non raggiungibile: …») arriva sempre prima di «non ha risposto in tempo». +async function testTelegram() { + const seconds = Number(values.TelegramTimeoutSeconds) || 15; + report(await send({ t: 'telegram.test' }, (seconds + 15) * 1000), { important: true }); +} + /** Coppie nome-valore nella stessa griglia a colonne dei campi: [nome, valore, title, lungo]. */ function pairs(list, cls = '') { return el('dl', { class: ('kv-grid ' + cls).trim() }, list.map(([name, value, title, long]) => diff --git a/tests/Mimante.Tests/TelegramNotifierTests.cs b/tests/Mimante.Tests/TelegramNotifierTests.cs new file mode 100644 index 0000000..23bbf4a --- /dev/null +++ b/tests/Mimante.Tests/TelegramNotifierTests.cs @@ -0,0 +1,324 @@ +using System.Collections.Concurrent; +using System.Net; +using System.Text; +using Mimante.Logging; +using Mimante.Settings; +using Mimante.Telegram; +using Xunit; + +namespace Mimante.Tests; + +/// +/// contro un Telegram finto (un +/// che risponde come la Bot API): il messaggio di prova, la coda con i tre tentativi e il filtro +/// dei comandi. Le attese sono iniettate e brevissime, così i test non aspettano i secondi veri. +/// Il formato dei messaggi è in TelegramFormatTests. +/// +public class TelegramNotifierTests +{ + private const string Token = "123:finto"; + private const string Chat = "42"; + + /// Una richiesta arrivata al Telegram finto: metodo della Bot API, indirizzo e corpo. + private sealed record Call(string Method, string Url, string Body); + + /// Il Telegram finto: registra ogni richiesta e risponde con . + private sealed class FakeTelegram(Func> respond) : HttpMessageHandler + { + public ConcurrentQueue Calls { get; } = new(); + + public IReadOnlyList Sends => Calls.Where(c => c.Method == "sendMessage").ToList(); + + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken ct) + { + var url = request.RequestUri!.ToString(); + var method = request.RequestUri.AbsolutePath.Split('/').Last(); + var body = request.Content == null ? "" : await request.Content.ReadAsStringAsync(ct); + var call = new Call(method, url, body); + Calls.Enqueue(call); + return await respond(call, ct); + } + } + + private static HttpResponseMessage Json(HttpStatusCode status, string json) => + new(status) { Content = new StringContent(json, Encoding.UTF8, "application/json") }; + + private static HttpResponseMessage Ok() => Json(HttpStatusCode.OK, """{"ok":true,"result":{}}"""); + + private static AppSettings Configured(bool commands = false) => + new() { TelegramBotToken = Token, TelegramChatId = Chat, TelegramCommandsEnabled = commands }; + + /// Le attese chieste dal notificatore; ognuna dura pochi millisecondi. + private sealed class Delays + { + public ConcurrentQueue Asked { get; } = new(); + + public Task Wait(TimeSpan d, CancellationToken ct) + { + Asked.Enqueue(d); + return Task.Delay(TimeSpan.FromMilliseconds(5), ct); + } + + /// Solo le attese fra un tentativo e l'altro (quelle dei cicli dei comandi sono di 10 e 30 s). + public List Retries => Asked.Where(d => d < TimeSpan.FromSeconds(10)).ToList(); + } + + private static (TelegramNotifier Notifier, FakeTelegram Fake, AppLog Log, Delays Delays) Make( + AppSettings settings, Func> respond) + { + var fake = new FakeTelegram(respond); + var log = new AppLog(null) { WriteToFile = false, Capacity = 200 }; + var delays = new Delays(); + var notifier = new TelegramNotifier(() => settings, log, new HttpClient(fake) { Timeout = Timeout.InfiniteTimeSpan }, delays.Wait); + return (notifier, fake, log, delays); + } + + private static async Task Until(Func condition, string what) + { + var deadline = DateTime.UtcNow.AddSeconds(10); + while (!condition()) + { + if (DateTime.UtcNow > deadline) Assert.Fail("Non è successo in tempo: " + what); + await Task.Delay(10); + } + } + + private static List Warnings(AppLog log) => + log.Snapshot().Where(e => e.Level == LogLevel.Warning && e.Tag == "TELEGRAM").Select(e => e.Message).ToList(); + + // ── Messaggio di prova ────────────────────────────────────────────── + + [Fact] + public async Task Il_messaggio_di_prova_riuscito_va_alla_chat_configurata() + { + var (n, fake, _, _) = Make(Configured(), (_, _) => Task.FromResult(Ok())); + await using var _n = n; + + var (ok, msg) = await n.SendTestAsync(CancellationToken.None); + + Assert.True(ok); + Assert.Equal("Messaggio inviato", msg); + var send = Assert.Single(fake.Sends); + Assert.Equal($"{TelegramApi.BaseUrl}/bot{Token}/sendMessage", send.Url); + Assert.Contains("\"chat_id\":\"42\"", send.Body, StringComparison.Ordinal); + Assert.Contains("Messaggio di prova da Mimante", send.Body, StringComparison.Ordinal); + } + + [Theory] + [InlineData(HttpStatusCode.BadRequest, """{"ok":false,"error_code":400,"description":"Bad Request: chat not found"}""")] + [InlineData(HttpStatusCode.Unauthorized, """{"ok":false,"error_code":401,"description":"Unauthorized"}""")] + [InlineData(HttpStatusCode.OK, """{"ok":false}""")] + public async Task Il_rifiuto_di_Telegram_dice_di_controllare_token_e_chat(HttpStatusCode status, string json) + { + var (n, _, _, _) = Make(Configured(), (_, _) => Task.FromResult(Json(status, json))); + await using var _n = n; + + var (ok, msg) = await n.SendTestAsync(CancellationToken.None); + + Assert.False(ok); + Assert.Equal("Telegram ha rifiutato il messaggio: controlla token e chat id (scrivi prima un messaggio al bot)", msg); + } + + [Fact] + public async Task Un_errore_di_rete_arriva_con_il_suo_messaggio() + { + var (n, _, _, _) = Make(Configured(), (_, _) => throw new HttpRequestException("host sconosciuto")); + await using var _n = n; + + var (ok, msg) = await n.SendTestAsync(CancellationToken.None); + + Assert.False(ok); + Assert.Equal("Telegram non raggiungibile: host sconosciuto", msg); + } + + [Fact] + public async Task Senza_risposta_entro_il_tempo_massimo_e_non_raggiungibile() + { + // Il valore vero va da 5 a 60 s (SettingsStore.Normalize); qui 1 s, per non aspettare. + var s = Configured(); + s.TelegramTimeoutSeconds = 1; + var (n, _, _, _) = Make(s, async (_, ct) => { await Task.Delay(Timeout.Infinite, ct); return Ok(); }); + await using var _n = n; + + var started = DateTime.UtcNow; + var (ok, msg) = await n.SendTestAsync(CancellationToken.None); + + Assert.False(ok); + Assert.Equal("Telegram non raggiungibile: nessuna risposta in 1 s", msg); + Assert.True(DateTime.UtcNow - started < TimeSpan.FromSeconds(8), "il tempo massimo non ha fermato la richiesta"); + } + + [Theory] + [InlineData("", Chat)] + [InlineData(" ", Chat)] + [InlineData(Token, "")] + [InlineData(Token, " ")] + public async Task Senza_token_o_chat_non_parte_nessuna_richiesta(string token, string chat) + { + var (n, fake, _, _) = Make(new AppSettings { TelegramBotToken = token, TelegramChatId = chat }, (_, _) => Task.FromResult(Ok())); + await using var _n = n; + + var (ok, msg) = await n.SendTestAsync(CancellationToken.None); + n.Enqueue("non deve partire"); + await Task.Delay(50); + + Assert.False(ok); + Assert.Equal("Scrivi token del bot e chat id, salva, poi riprova", msg); + Assert.False(n.Configured); + Assert.Empty(fake.Calls); + } + + [Fact] + public void Il_tempo_massimo_si_normalizza_fra_5_e_60_secondi() + { + Assert.Equal(15, new AppSettings().TelegramTimeoutSeconds); + Assert.Equal(5, SettingsStore.Normalize(new AppSettings { TelegramTimeoutSeconds = 0 }).TelegramTimeoutSeconds); + Assert.Equal(60, SettingsStore.Normalize(new AppSettings { TelegramTimeoutSeconds = 600 }).TelegramTimeoutSeconds); + Assert.Equal(20, SettingsStore.Normalize(new AppSettings { TelegramTimeoutSeconds = 20 }).TelegramTimeoutSeconds); + } + + // ── Coda ──────────────────────────────────────────────────────────── + + [Fact] + public async Task La_coda_prova_tre_volte_con_attese_di_4_e_8_secondi_e_lo_scrive_una_volta() + { + var (n, fake, log, delays) = Make(Configured(), (_, _) => throw new HttpRequestException("rete giù")); + await using var _n = n; + + n.Enqueue("uno"); + await Until(() => Warnings(log).Count == 1, "la riga dopo tre tentativi"); + + Assert.Equal(3, fake.Sends.Count); + Assert.Equal(new[] { TimeSpan.FromSeconds(4), TimeSpan.FromSeconds(8) }, delays.Retries); + Assert.Equal("Messaggio non inviato dopo tre tentativi: rete giù", Assert.Single(Warnings(log))); + + // Un secondo messaggio che non parte non ripete la riga. + n.Enqueue("due"); + await Until(() => fake.Sends.Count == 6 && delays.Retries.Count == 4, "i tre tentativi del secondo messaggio"); + n.Enqueue("tre"); + await Until(() => fake.Sends.Count == 9, "i tre tentativi del terzo messaggio"); + Assert.Single(Warnings(log)); + } + + [Fact] + public async Task Una_scadenza_nella_coda_si_scrive_e_non_ferma_gli_invii_successivi() + { + // Il valore vero va da 5 a 60 s (SettingsStore.Normalize); qui 1 s, per non aspettare. + // Il primo messaggio non riceve mai risposta: i tre tentativi scadono uno dopo l'altro. + var s = Configured(); + s.TelegramTimeoutSeconds = 1; + var (n, fake, log, delays) = Make(s, async (c, ct) => + { + if (c.Body.Contains("muto", StringComparison.Ordinal)) await Task.Delay(Timeout.Infinite, ct); + return Ok(); + }); + await using var _n = n; + + n.Enqueue("muto"); + await Until(() => Warnings(log).Count == 1, "la riga dopo tre scadenze"); + + Assert.Equal("Messaggio non inviato dopo tre tentativi: nessuna risposta in 1 s", Assert.Single(Warnings(log))); + Assert.Equal(3, fake.Sends.Count); + Assert.Equal(new[] { TimeSpan.FromSeconds(4), TimeSpan.FromSeconds(8) }, delays.Retries); + + // La scadenza non ha chiuso il ciclo di invio: il messaggio dopo parte al primo tentativo. + n.Enqueue("riparte"); + await Until(() => fake.Sends.Count == 4, "il messaggio dopo la scadenza"); + Assert.Contains("riparte", fake.Sends[3].Body, StringComparison.Ordinal); + await Task.Delay(50); + Assert.Equal(4, fake.Sends.Count); + Assert.Equal(2, delays.Retries.Count); + } + + [Fact] + public async Task Un_messaggio_che_riparte_rimette_la_riga_al_prossimo_guasto() + { + var (n, fake, log, _) = Make(Configured(), (c, _) => + c.Body.Contains("guasto", StringComparison.Ordinal) + ? Task.FromResult(Json(HttpStatusCode.InternalServerError, """{"ok":false}""")) + : Task.FromResult(Ok())); + await using var _n = n; + + n.Enqueue("guasto uno"); + await Until(() => Warnings(log).Count == 1, "la prima riga"); + Assert.Equal("Messaggio non inviato dopo tre tentativi", Warnings(log)[0]); + + n.Enqueue("riparte"); + await Until(() => fake.Sends.Count == 4, "il messaggio che riparte"); + + n.Enqueue("guasto due"); + await Until(() => Warnings(log).Count == 2, "la seconda riga dopo la ripresa"); + Assert.Equal(7, fake.Sends.Count); + } + + [Fact] + public async Task La_coda_si_ferma_al_primo_tentativo_riuscito() + { + var calls = 0; + var (n, fake, log, delays) = Make(Configured(), (_, _) => + Interlocked.Increment(ref calls) == 1 + ? throw new HttpRequestException("rete giù") + : Task.FromResult(Ok())); + await using var _n = n; + + n.Enqueue("uno"); + n.Enqueue("due"); + await Until(() => fake.Sends.Count == 3, "i due messaggi"); + await Task.Delay(50); + + Assert.Equal(3, fake.Sends.Count); + Assert.Equal(new[] { TimeSpan.FromSeconds(4) }, delays.Retries); + Assert.Empty(Warnings(log)); + } + + // ── Comandi ───────────────────────────────────────────────────────── + + [Fact] + public async Task I_comandi_si_accettano_solo_dalla_chat_configurata() + { + const string updates = """ + {"ok":true,"result":[ + {"update_id":10,"message":{"chat":{"id":999},"text":"/halt"}}, + {"update_id":11,"message":{"chat":{"id":42},"text":" /Stato@mimante_bot "}}, + {"update_id":12,"message":{"chat":{"id":42}}}, + {"update_id":13,"message":{"chat":{"id":-42},"text":"/osserva"}} + ]} + """; + var polls = 0; + var (n, fake, log, _) = Make(Configured(commands: true), async (c, ct) => + { + if (c.Method != "getUpdates") return Ok(); + if (Interlocked.Increment(ref polls) == 1) return Json(HttpStatusCode.OK, updates); + await Task.Delay(Timeout.Infinite, ct); // il polling lungo: nessun messaggio nuovo + return Ok(); + }); + await using var _n = n; + var received = new ConcurrentQueue(); + n.CommandHandler = command => { received.Enqueue(command); return Task.FromResult("risposta a " + command); }; + + await Until(() => fake.Sends.Count == 1 && Volatile.Read(ref polls) >= 2, "la risposta al comando e la lettura successiva"); + + Assert.Equal(new[] { "/stato" }, received.ToList()); + Assert.Contains("risposta a /stato", fake.Sends[0].Body, StringComparison.Ordinal); + Assert.Contains("\"chat_id\":\"42\"", fake.Sends[0].Body, StringComparison.Ordinal); + + var gets = fake.Calls.Where(c => c.Method == "getUpdates").ToList(); + Assert.StartsWith($"{TelegramApi.BaseUrl}/bot{Token}/getUpdates?offset=0&timeout=25", gets[0].Url, StringComparison.Ordinal); + Assert.Contains("offset=14&", gets[1].Url, StringComparison.Ordinal); + + var commands = log.Snapshot().Where(e => e.Tag == "TELEGRAM").Select(e => e.Message).ToList(); + Assert.Equal(new[] { "Comando ricevuto: /stato" }, commands); + } + + [Fact] + public async Task Con_i_comandi_spenti_non_si_leggono_i_messaggi() + { + var (n, fake, _, delays) = Make(Configured(commands: false), (_, _) => Task.FromResult(Ok())); + await using var _n = n; + n.CommandHandler = _ => Task.FromResult("no"); + + await Until(() => delays.Asked.Count(d => d == TimeSpan.FromSeconds(10)) >= 3, "qualche giro del ciclo dei comandi"); + + Assert.Empty(fake.Calls); + } +}