Telegram: il messaggio di prova dice sempre il motivo vero, e la coda è sotto test (#35)
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 <noreply@anthropic.com>
This commit is contained in:
1 parent
bac49d3fc4
commit
ea6ba27462
7 files changed
+391
-18
No files matched your search
@@ -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
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -249,6 +249,14 @@ public sealed class AppSettings
|
||||
/// <summary>Comandi in ingresso (/stato, /halt, /riprendi, /osserva) dal solo chat id configurato.</summary>
|
||||
public bool TelegramCommandsEnabled { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public int TelegramTimeoutSeconds { get; set; } = 15;
|
||||
|
||||
// ── Dati e conservazione ─────────────────────────────────────────────
|
||||
|
||||
public double DataCapGb { get; set; } = 50;
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -12,9 +12,13 @@ namespace Mimante.Telegram;
|
||||
/// </summary>
|
||||
public sealed class TelegramNotifier : IAsyncDisposable
|
||||
{
|
||||
/// <summary>Quanto aspetta Telegram con <c>getUpdates</c> prima di rispondere senza messaggi nuovi.</summary>
|
||||
private const int LongPollSeconds = 25;
|
||||
|
||||
private readonly Func<AppSettings> _settings;
|
||||
private readonly AppLog _log;
|
||||
private readonly HttpClient _http;
|
||||
private readonly Func<TimeSpan, CancellationToken, Task> _delay;
|
||||
private readonly Channel<string> _queue = Channel.CreateBounded<string>(new BoundedChannelOptions(200) { FullMode = BoundedChannelFullMode.DropOldest });
|
||||
private readonly CancellationTokenSource _cts = new();
|
||||
private readonly Task _sender;
|
||||
@@ -25,11 +29,16 @@ public sealed class TelegramNotifier : IAsyncDisposable
|
||||
/// <summary>Risponde a un comando ricevuto: il testo della risposta.</summary>
|
||||
public Func<string, Task<string>>? CommandHandler { get; set; }
|
||||
|
||||
public TelegramNotifier(Func<AppSettings> settings, AppLog log, HttpClient? http = null)
|
||||
/// <param name="http">Il client verso Telegram; i test ne passano uno con un gestore finto.</param>
|
||||
/// <param name="delay">Le attese fra i tentativi e dei cicli (di serie <see cref="Task.Delay(TimeSpan, CancellationToken)"/>); i test le accorciano.</param>
|
||||
public TelegramNotifier(Func<AppSettings> settings, AppLog log, HttpClient? http = null, Func<TimeSpan, CancellationToken, Task>? 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}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Un solo invio, con il tempo massimo delle impostazioni sopra quello di chi chiama.</summary>
|
||||
private async Task<bool> 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<TelegramApi.Update> 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; }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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]) =>
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="TelegramNotifier"/> contro un Telegram finto (un <see cref="HttpMessageHandler"/>
|
||||
/// 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 <c>TelegramFormatTests</c>.
|
||||
/// </summary>
|
||||
public class TelegramNotifierTests
|
||||
{
|
||||
private const string Token = "123:finto";
|
||||
private const string Chat = "42";
|
||||
|
||||
/// <summary>Una richiesta arrivata al Telegram finto: metodo della Bot API, indirizzo e corpo.</summary>
|
||||
private sealed record Call(string Method, string Url, string Body);
|
||||
|
||||
/// <summary>Il Telegram finto: registra ogni richiesta e risponde con <paramref name="respond"/>.</summary>
|
||||
private sealed class FakeTelegram(Func<Call, CancellationToken, Task<HttpResponseMessage>> respond) : HttpMessageHandler
|
||||
{
|
||||
public ConcurrentQueue<Call> Calls { get; } = new();
|
||||
|
||||
public IReadOnlyList<Call> Sends => Calls.Where(c => c.Method == "sendMessage").ToList();
|
||||
|
||||
protected override async Task<HttpResponseMessage> 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 };
|
||||
|
||||
/// <summary>Le attese chieste dal notificatore; ognuna dura pochi millisecondi.</summary>
|
||||
private sealed class Delays
|
||||
{
|
||||
public ConcurrentQueue<TimeSpan> Asked { get; } = new();
|
||||
|
||||
public Task Wait(TimeSpan d, CancellationToken ct)
|
||||
{
|
||||
Asked.Enqueue(d);
|
||||
return Task.Delay(TimeSpan.FromMilliseconds(5), ct);
|
||||
}
|
||||
|
||||
/// <summary>Solo le attese fra un tentativo e l'altro (quelle dei cicli dei comandi sono di 10 e 30 s).</summary>
|
||||
public List<TimeSpan> Retries => Asked.Where(d => d < TimeSpan.FromSeconds(10)).ToList();
|
||||
}
|
||||
|
||||
private static (TelegramNotifier Notifier, FakeTelegram Fake, AppLog Log, Delays Delays) Make(
|
||||
AppSettings settings, Func<Call, CancellationToken, Task<HttpResponseMessage>> 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<bool> 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<string> 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<string>();
|
||||
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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user