Telegram: via /halt, /riprendi con conferma, spesa del giorno nel riepilogo e avviso dell'errore ripetuto del motore (#47)
Il comando /halt era l'ultimo modo di mettere un HALT a mano, contro la regola «HALT solo automatico» (ADR 0011): si toglie, e il freno a distanza resta /osserva. /riprendi da solo non toglie più un blocco nato da stop-loss o drawdown: risponde con il motivo e chiede «/riprendi si» (anche «sì», maiuscole indifferenti), come «Togli il blocco» chiede conferma nell'interfaccia; un HALT manuale salvato in passato si legge e si toglie come prima. Il riepilogo torna a dire spesa e saldo netto del giorno, che la specifica §6.7 chiede e che il record portava già senza scriverli. Gli errori del motore restavano solo nei registri: ora passano da EngineErrorWatch, una finestra scorrevole per asta (O(1) ammortizzato, lock breve sulla sola asta, nessun disco né database sul percorso caldo), e N errori della stessa asta in M minuti (5 in 10 di fabbrica, impostazioni nuove con validazione) danno un solo messaggio Telegram, il successivo solo dopo una finestra intera senza errori. Infine la sessione illeggibile all'avvio non dice più «si parte dal simulatore» sul sito vero, dove il bot segue le aste senza puntare. Guida, come-funziona e una nota in fondo all'ADR 0011 seguono il codice. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit ef372fe14aff6eafebeefe2e760e355de7ffc630)
This commit is contained in:
1 parent
b78e544610
commit
2d74aed552
24 files changed
+575
-48
No files matched your search
@@ -0,0 +1,189 @@
|
||||
using Mimante.Engine;
|
||||
using Mimante.Settings;
|
||||
using Mimante.Telegram;
|
||||
using Xunit;
|
||||
|
||||
namespace Mimante.Tests;
|
||||
|
||||
/// <summary>L'avviso «errore ripetuto del motore»: N errori della stessa asta in M minuti, un solo messaggio per serie.</summary>
|
||||
public class EngineErrorWatchTests
|
||||
{
|
||||
private const long Minute = 60_000;
|
||||
|
||||
private sealed class Clock
|
||||
{
|
||||
public long Now = 1_000_000;
|
||||
public void Advance(long ms) => Now += ms;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Avvisa_una_volta_sola_al_quinto_errore_in_dieci_minuti()
|
||||
{
|
||||
var clock = new Clock();
|
||||
var watch = new EngineErrorWatch(() => clock.Now);
|
||||
var alerts = new List<int>();
|
||||
for (var i = 1; i <= 20; i++)
|
||||
{
|
||||
if (watch.Record("a", 5, 10)) alerts.Add(i);
|
||||
clock.Advance(10_000);
|
||||
}
|
||||
Assert.Equal(new[] { 5 }, alerts);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Errori_sparsi_oltre_la_finestra_non_avvisano()
|
||||
{
|
||||
var clock = new Clock();
|
||||
var watch = new EngineErrorWatch(() => clock.Now);
|
||||
// Uno ogni 3 minuti: dentro 10 minuti ce ne stanno al più 4.
|
||||
for (var i = 0; i < 30; i++)
|
||||
{
|
||||
Assert.False(watch.Record("a", 5, 10));
|
||||
clock.Advance(3 * Minute);
|
||||
}
|
||||
Assert.Equal(3, watch.Count("a", 10)); // gli ultimi tre, a 3, 6 e 9 minuti
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Un_errore_continuo_avvisa_una_volta_e_dopo_una_pausa_intera_si_riavvisa()
|
||||
{
|
||||
var clock = new Clock();
|
||||
var watch = new EngineErrorWatch(() => clock.Now);
|
||||
var alerts = 0;
|
||||
// Un errore al minuto per tre ore: la finestra non si svuota mai, un solo avviso.
|
||||
for (var i = 0; i < 180; i++)
|
||||
{
|
||||
if (watch.Record("a", 5, 10)) alerts++;
|
||||
clock.Advance(Minute);
|
||||
}
|
||||
Assert.Equal(1, alerts);
|
||||
|
||||
// Nove minuti di pausa non bastano: la serie è la stessa.
|
||||
clock.Advance(8 * Minute);
|
||||
for (var i = 0; i < 5; i++) Assert.False(watch.Record("a", 5, 10));
|
||||
|
||||
// Dieci minuti interi senza errori chiudono la serie: la prossima raffica avvisa di nuovo.
|
||||
clock.Advance(10 * Minute);
|
||||
var again = Enumerable.Range(0, 5).Select(_ => watch.Record("a", 5, 10)).ToList();
|
||||
Assert.Equal(new[] { false, false, false, false, true }, again);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Ogni_asta_ha_il_suo_conteggio()
|
||||
{
|
||||
var clock = new Clock();
|
||||
var watch = new EngineErrorWatch(() => clock.Now);
|
||||
for (var i = 0; i < 4; i++)
|
||||
{
|
||||
Assert.False(watch.Record("a", 5, 10));
|
||||
Assert.False(watch.Record("b", 5, 10));
|
||||
}
|
||||
Assert.True(watch.Record("b", 5, 10));
|
||||
Assert.True(watch.Record("a", 5, 10));
|
||||
|
||||
watch.Forget("a");
|
||||
Assert.Equal(0, watch.Count("a", 10));
|
||||
Assert.Equal(5, watch.Count("b", 10));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void La_soglia_cambiata_vale_subito_e_zero_spegne()
|
||||
{
|
||||
var clock = new Clock();
|
||||
var watch = new EngineErrorWatch(() => clock.Now);
|
||||
for (var i = 0; i < 4; i++) Assert.False(watch.Record("a", 10, 10));
|
||||
// Abbassata a 5: i quattro errori già contati restano, il quinto avvisa.
|
||||
Assert.True(watch.Record("a", 5, 10));
|
||||
|
||||
Assert.False(watch.Record("b", 0, 10));
|
||||
Assert.False(watch.Record("b", 5, 0));
|
||||
Assert.Equal(0, watch.Count("b", 10));
|
||||
|
||||
// Abbassata sotto gli errori contati: si tengono i più recenti.
|
||||
for (var i = 0; i < 3; i++) { watch.Record("c", 8, 10); clock.Advance(1000); }
|
||||
watch.Record("c", 2, 10);
|
||||
Assert.Equal(2, watch.Count("c", 10));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Le_soglie_si_normalizzano_e_di_fabbrica_sono_cinque_in_dieci_minuti()
|
||||
{
|
||||
var s = new AppSettings();
|
||||
Assert.True(s.TelegramNotifyEngineErrors);
|
||||
Assert.Equal(5, s.EngineErrorAlertCount);
|
||||
Assert.Equal(10, s.EngineErrorAlertMinutes);
|
||||
|
||||
s.EngineErrorAlertCount = 0;
|
||||
s.EngineErrorAlertMinutes = 0;
|
||||
SettingsStore.Normalize(s);
|
||||
Assert.Equal(2, s.EngineErrorAlertCount);
|
||||
Assert.Equal(1, s.EngineErrorAlertMinutes);
|
||||
|
||||
s.EngineErrorAlertCount = 1_000_000;
|
||||
s.EngineErrorAlertMinutes = 1_000_000;
|
||||
SettingsStore.Normalize(s);
|
||||
Assert.Equal(1000, s.EngineErrorAlertCount);
|
||||
Assert.Equal(24 * 60, s.EngineErrorAlertMinutes);
|
||||
Assert.DoesNotContain(nameof(AppSettings.EngineErrorAlertCount), SettingsStore.RestartRequired);
|
||||
Assert.DoesNotContain(nameof(AppSettings.EngineErrorAlertMinutes), SettingsStore.RestartRequired);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Molte_chiamate_da_piu_thread_avvisano_una_volta_per_asta()
|
||||
{
|
||||
var watch = new EngineErrorWatch();
|
||||
var alerts = 0;
|
||||
Parallel.For(0, 4000, i =>
|
||||
{
|
||||
if (watch.Record("asta-" + (i % 4), 5, 10)) Interlocked.Increment(ref alerts);
|
||||
});
|
||||
Assert.Equal(4, alerts);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>I comandi di Telegram: nome, argomento e la conferma di /riprendi.</summary>
|
||||
public class TelegramCommandTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData("/stato", "/stato", "")]
|
||||
[InlineData(" /Stato@mimante_bot ", "/stato", "")]
|
||||
[InlineData("/riprendi si", "/riprendi", "si")]
|
||||
[InlineData("/RIPRENDI@mimante_bot Sì ", "/riprendi", "Sì")]
|
||||
[InlineData("/riprendi\nsi", "/riprendi", "si")]
|
||||
[InlineData("ciao a tutti", "ciao", "a tutti")]
|
||||
public void Separa_nome_e_argomento(string text, string name, string argument)
|
||||
{
|
||||
var c = TelegramCommand.Parse(text);
|
||||
Assert.NotNull(c);
|
||||
Assert.Equal(name, c!.Name);
|
||||
Assert.Equal(argument, c.Argument);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)]
|
||||
[InlineData("")]
|
||||
[InlineData(" ")]
|
||||
public void Un_testo_vuoto_non_e_un_comando(string? text) => Assert.Null(TelegramCommand.Parse(text));
|
||||
|
||||
[Theory]
|
||||
[InlineData("/riprendi si", true)]
|
||||
[InlineData("/riprendi SI", true)]
|
||||
[InlineData("/riprendi sì", true)]
|
||||
[InlineData("/riprendi SÌ", true)]
|
||||
[InlineData("/riprendi sì", true)] // «ì» scritta come «i» più l'accento a parte
|
||||
[InlineData("/riprendi", false)]
|
||||
[InlineData("/riprendi no", false)]
|
||||
[InlineData("/riprendi sicuro", false)]
|
||||
[InlineData("/riprendi si grazie", false)]
|
||||
[InlineData("/riprendi yes", false)]
|
||||
public void Riprendi_vuole_la_conferma_esplicita(string text, bool confirmed) =>
|
||||
Assert.Equal(confirmed, TelegramCommand.Parse(text)!.Confirmed);
|
||||
|
||||
[Fact]
|
||||
public void L_aiuto_non_elenca_piu_halt()
|
||||
{
|
||||
Assert.DoesNotContain("/halt", TelegramCommand.Help);
|
||||
Assert.Contains("/riprendi si", TelegramCommand.Help);
|
||||
Assert.Contains("/osserva", TelegramCommand.Help);
|
||||
}
|
||||
}
|
||||
@@ -334,6 +334,8 @@ public class RunnerAgainstSimulatorTests
|
||||
public bool IsFinished(AuctionInfo auction) => auction.IsFinished;
|
||||
public readonly List<string> NotFired = new();
|
||||
public void NoteNotFired(AuctionInfo auction, string note) => NotFired.Add(note);
|
||||
public void NoteEngineError(AuctionInfo auction, string message, AuctionLogCategory category) =>
|
||||
auction.Log.Add(message, LogLevel.Error, category);
|
||||
public bool IsShadow(AuctionInfo auction) => false;
|
||||
public int EffectiveLeadMs(AuctionInfo auction) => Lead;
|
||||
|
||||
|
||||
@@ -150,6 +150,27 @@ public class MonitorAgainstSimulatorTests
|
||||
Assert.NotEmpty(why);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Gli_errori_ripetuti_del_motore_danno_un_solo_avviso_per_asta()
|
||||
{
|
||||
var world = new SimWorld(seed: 25, populate: false);
|
||||
var settings = new AppSettings { EngineErrorAlertCount = 3, EngineErrorAlertMinutes = 10 };
|
||||
await using var rig = await StartAsync(world, settings);
|
||||
var alerts = new List<(string Id, string Last)>();
|
||||
rig.Monitor.EngineErrorRepeated += (a, last) => alerts.Add((a.Id, last));
|
||||
var one = new AuctionInfo("1") { Name = "Uno" };
|
||||
var two = new AuctionInfo("2") { Name = "Due" };
|
||||
|
||||
for (var i = 1; i <= 6; i++) rig.Monitor.NoteEngineError(one, $"Errore nel polling: prova {i}", AuctionLogCategory.Polling);
|
||||
rig.Monitor.NoteEngineError(two, "Errore nel cecchino: prova", AuctionLogCategory.Bid);
|
||||
|
||||
Assert.Equal(new[] { ("1", "Errore nel polling: prova 3") }, alerts);
|
||||
// Ogni errore resta nel registro dell'asta; nel registro generale una riga sola per serie.
|
||||
Assert.Equal(6, one.Log.Snapshot().Count(e => e.Level == LogLevel.Error));
|
||||
var engine = rig.Log.Snapshot().Where(e => e.Tag == "MOTORE").Select(e => e.Message).ToList();
|
||||
Assert.Equal(new[] { "Uno: 3 errori del motore in 10 min, l'ultimo: Errore nel polling: prova 3" }, engine);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Dopo_un_riavvio_ogni_asta_riprende_da_dove_era()
|
||||
{
|
||||
|
||||
@@ -220,6 +220,27 @@ public class TelegramFormatTests
|
||||
Assert.StartsWith("HALT automatico", TelegramFormat.Halt("stop-loss", automatic: true));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Riprendere_senza_conferma_spiega_come_si_conferma()
|
||||
{
|
||||
var text = TelegramFormat.ResumeNeedsConfirmation("Stop-loss del giorno superato");
|
||||
Assert.StartsWith("HALT ancora attivo", text);
|
||||
Assert.Contains("Stop-loss del giorno superato", text);
|
||||
Assert.Contains("/riprendi si", text);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void L_avviso_degli_errori_del_motore_dice_asta_soglia_e_ultimo_errore()
|
||||
{
|
||||
var text = TelegramFormat.EngineErrors("Dyson V15", 5, 10, "Errore nel polling: timeout\r\nseconda riga");
|
||||
var lines = text.Split('\n');
|
||||
Assert.Equal("Errore ripetuto del motore: Dyson V15", lines[0]);
|
||||
Assert.Contains("5 errori in 10 minuti", text);
|
||||
// L'ultimo errore su una riga sola, senza a capo che rompano il messaggio.
|
||||
Assert.Contains("L'ultimo: Errore nel polling: timeout seconda riga", text);
|
||||
Assert.Contains("10 minuti senza errori", text);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Il_riepilogo_dice_utente_saldo_e_roi_e_si_tronca()
|
||||
{
|
||||
@@ -231,8 +252,12 @@ public class TelegramFormatTests
|
||||
Assert.DoesNotContain("pagamento", text);
|
||||
Assert.Contains("Osserva -0,08 €", text);
|
||||
Assert.Contains("Attive n.d.", text);
|
||||
// Guadagno e perdita del giorno non si dicono più.
|
||||
Assert.DoesNotContain("Oggi", text);
|
||||
// Spesa e saldo netto del giorno, in euro all'italiana e con il segno sul saldo.
|
||||
Assert.Contains("\nSpesa oggi 3,80 €, saldo netto oggi -3,80 €.", text);
|
||||
var positive = TelegramFormat.SummaryText(new TelegramFormat.Summary(1, 0, null, 1234.5, 46, null, null, null, true, false));
|
||||
Assert.Contains("Spesa oggi 1234,50 €, saldo netto oggi +46,00 €.", positive);
|
||||
var zero = TelegramFormat.SummaryText(new TelegramFormat.Summary(1, 0, null, 0, 0, null, null, null, true, false));
|
||||
Assert.Contains("Spesa oggi 0,00 €, saldo netto oggi 0,00 €.", zero);
|
||||
|
||||
var halted = TelegramFormat.SummaryText(new TelegramFormat.Summary(1, 1, null, 0, 0, null, null, null, true, true));
|
||||
Assert.StartsWith("Mimante, riepilogo, puntate ferme (HALT)", halted);
|
||||
|
||||
@@ -278,8 +278,8 @@ public class TelegramNotifierTests
|
||||
{
|
||||
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":10,"message":{"chat":{"id":999},"text":"/riprendi si"}},
|
||||
{"update_id":11,"message":{"chat":{"id":42},"text":" /Riprendi@mimante_bot Sì "}},
|
||||
{"update_id":12,"message":{"chat":{"id":42}}},
|
||||
{"update_id":13,"message":{"chat":{"id":-42},"text":"/osserva"}}
|
||||
]}
|
||||
@@ -293,13 +293,13 @@ public class TelegramNotifierTests
|
||||
return Ok();
|
||||
});
|
||||
await using var _n = n;
|
||||
var received = new ConcurrentQueue<string>();
|
||||
n.CommandHandler = command => { received.Enqueue(command); return Task.FromResult("risposta a " + command); };
|
||||
var received = new ConcurrentQueue<TelegramCommand>();
|
||||
n.CommandHandler = command => { received.Enqueue(command); return Task.FromResult("risposta a " + command.Name); };
|
||||
|
||||
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.Equal(new[] { new TelegramCommand("/riprendi", "Sì") }, received.ToList());
|
||||
Assert.Contains("risposta a /riprendi", 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();
|
||||
@@ -307,7 +307,8 @@ public class TelegramNotifierTests
|
||||
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);
|
||||
// Solo il nome del comando, non il resto del testo.
|
||||
Assert.Equal(new[] { "Comando ricevuto: /riprendi" }, commands);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
||||
Reference in new issue
Block a user