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>
169 lines
7.7 KiB
C#
169 lines
7.7 KiB
C#
using System.Threading.Channels;
|
|
using Mimante.Logging;
|
|
using Mimante.Settings;
|
|
|
|
namespace Mimante.Telegram;
|
|
|
|
/// <summary>
|
|
/// Le notifiche Telegram (specifica §6.7): una coda con tre ritentativi e attesa crescente,
|
|
/// così un Telegram lento non rallenta mai il motore. Facoltativi i comandi in ingresso
|
|
/// (<c>/stato</c>, <c>/halt</c>, <c>/riprendi</c>, <c>/osserva</c>), letti con
|
|
/// <c>getUpdates</c> a polling lungo e accettati solo dalla chat configurata.
|
|
/// </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;
|
|
private readonly Task _commands;
|
|
private long _offset;
|
|
private bool _failureSaid;
|
|
|
|
/// <summary>Risponde a un comando ricevuto: il testo della risposta.</summary>
|
|
public Func<string, Task<string>>? CommandHandler { get; set; }
|
|
|
|
/// <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;
|
|
// 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));
|
|
}
|
|
|
|
public bool Configured
|
|
{
|
|
get
|
|
{
|
|
var s = _settings();
|
|
return !string.IsNullOrWhiteSpace(s.TelegramBotToken) && !string.IsNullOrWhiteSpace(s.TelegramChatId);
|
|
}
|
|
}
|
|
|
|
/// <summary>Accoda un messaggio già formattato (<see cref="TelegramFormat"/>). Senza token o chat non fa nulla.</summary>
|
|
public void Enqueue(string text)
|
|
{
|
|
if (Configured) _queue.Writer.TryWrite(text);
|
|
}
|
|
|
|
/// <summary>«Invia messaggio di prova» delle impostazioni: subito, senza coda, con l'esito.</summary>
|
|
public async Task<(bool Ok, string Message)> SendTestAsync(CancellationToken ct)
|
|
{
|
|
var s = _settings();
|
|
if (string.IsNullOrWhiteSpace(s.TelegramBotToken) || string.IsNullOrWhiteSpace(s.TelegramChatId))
|
|
return (false, "Scrivi token del bot e chat id, salva, poi riprova");
|
|
try
|
|
{
|
|
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
|
|
{
|
|
await foreach (var text in _queue.Reader.ReadAllAsync(ct).ConfigureAwait(false))
|
|
{
|
|
var s = _settings();
|
|
if (string.IsNullOrWhiteSpace(s.TelegramBotToken) || string.IsNullOrWhiteSpace(s.TelegramChatId)) continue;
|
|
|
|
var sent = false;
|
|
string? error = null;
|
|
for (var attempt = 0; attempt < 3 && !sent; attempt++)
|
|
{
|
|
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; }
|
|
}
|
|
|
|
if (!sent && !_failureSaid)
|
|
{
|
|
_failureSaid = true;
|
|
_log.Warn("TELEGRAM", $"Messaggio non inviato dopo tre tentativi{(error != null ? $": {error}" : "")}");
|
|
}
|
|
else if (sent) _failureSaid = false;
|
|
}
|
|
}
|
|
catch (OperationCanceledException) { }
|
|
}
|
|
|
|
private async Task CommandLoopAsync(CancellationToken ct)
|
|
{
|
|
while (!ct.IsCancellationRequested)
|
|
{
|
|
var s = _settings();
|
|
if (!s.TelegramCommandsEnabled || !Configured || CommandHandler == null)
|
|
{
|
|
try { await _delay(TimeSpan.FromSeconds(10), ct).ConfigureAwait(false); } catch (OperationCanceledException) { return; }
|
|
continue;
|
|
}
|
|
|
|
try
|
|
{
|
|
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);
|
|
if (u.ChatId != s.TelegramChatId.Trim() || string.IsNullOrWhiteSpace(u.Text)) continue;
|
|
var command = u.Text.Trim().Split(' ', '@')[0].ToLowerInvariant();
|
|
_log.Info("TELEGRAM", $"Comando ricevuto: {command}");
|
|
var reply = await CommandHandler(command).ConfigureAwait(false);
|
|
Enqueue(reply);
|
|
}
|
|
}
|
|
catch (OperationCanceledException) when (ct.IsCancellationRequested) { return; }
|
|
catch (Exception)
|
|
{
|
|
try { await _delay(TimeSpan.FromSeconds(30), ct).ConfigureAwait(false); } catch (OperationCanceledException) { return; }
|
|
}
|
|
}
|
|
}
|
|
|
|
public async ValueTask DisposeAsync()
|
|
{
|
|
_queue.Writer.TryComplete();
|
|
await _cts.CancelAsync().ConfigureAwait(false);
|
|
try { await Task.WhenAll(_sender, _commands).WaitAsync(TimeSpan.FromSeconds(3)).ConfigureAwait(false); } catch { }
|
|
_http.Dispose();
|
|
_cts.Dispose();
|
|
}
|
|
}
|