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)
301 lines
14 KiB
C#
301 lines
14 KiB
C#
using Mimante.Bidoo;
|
|
using Mimante.Data;
|
|
using Mimante.Engine;
|
|
using Mimante.Logging;
|
|
using Mimante.Ml;
|
|
using Mimante.Net;
|
|
using Mimante.Products;
|
|
using Mimante.Session;
|
|
using Mimante.Settings;
|
|
using Mimante.Simulator;
|
|
using Mimante.Strategy;
|
|
using Xunit;
|
|
|
|
namespace Mimante.Tests;
|
|
|
|
/// <summary>Il monitor intero (motori, verdetto, puntata, chiusura) contro il simulatore, senza database.</summary>
|
|
public class MonitorAgainstSimulatorTests
|
|
{
|
|
private sealed class Rig : IAsyncDisposable
|
|
{
|
|
public required SimulatedBidoo Sim { get; init; }
|
|
public required AuctionMonitor Monitor { get; init; }
|
|
public required BidooTransport Transport { get; init; }
|
|
public required BidLane Lane { get; init; }
|
|
public required AppLog Log { get; init; }
|
|
public required RiskManager Risk { get; init; }
|
|
public required AccountState Account { get; init; }
|
|
public SimWorld World => Sim.World;
|
|
|
|
public async ValueTask DisposeAsync()
|
|
{
|
|
await Monitor.DisposeAsync();
|
|
Lane.Dispose();
|
|
Transport.Dispose();
|
|
await Sim.DisposeAsync();
|
|
}
|
|
}
|
|
|
|
private static async Task<Rig> StartAsync(SimWorld world, AppSettings settings, Func<bool>? canBid = null, bool knownUser = true)
|
|
{
|
|
var sim = await SimulatedBidoo.StartAsync(world);
|
|
var refs = sim.References();
|
|
var transport = new BidooTransport(() => refs, 0);
|
|
var lane = new BidLane(transport, () => refs, keepWarm: false);
|
|
var api = new BidooApi(transport, lane, () => refs) { Username = knownUser ? world.MyUsername : null };
|
|
var docs = new MemoryDocumentStore();
|
|
var log = new AppLog(null);
|
|
var account = new AccountState();
|
|
if (knownUser) account.SetUser(world.MyUsername, world.MyUserId);
|
|
var risk = new RiskManager(docs, new ListLedger());
|
|
var learning = new LearningService(docs, new MemoryLearningData(), () => settings, log);
|
|
var products = new ProductStore(null);
|
|
|
|
var monitor = new AuctionMonitor(new MonitorDeps
|
|
{
|
|
Settings = () => settings,
|
|
References = () => refs,
|
|
Api = api,
|
|
Clock = new ServerClock(),
|
|
Strategy = new BidStrategy(risk, learning, products, () => account.Balance),
|
|
Risk = risk,
|
|
Learning = learning,
|
|
Latency = new LatencyModel(docs),
|
|
Recorder = new AuctionRecorder(null, null, () => settings, () => world.MyUsername, Worlds.Simulator),
|
|
Products = products,
|
|
Account = account,
|
|
Log = log,
|
|
Documents = docs,
|
|
World = Worlds.Simulator,
|
|
CanBid = canBid ?? (() => true)
|
|
});
|
|
return new Rig { Sim = sim, Monitor = monitor, Transport = transport, Lane = lane, Log = log, Risk = risk, Account = account };
|
|
}
|
|
|
|
private static async Task<(AuctionInfo A, CloseSummary C, string Line)> RunToCompletionAsync(Rig rig, AuctionInfo a, int seconds = 30)
|
|
{
|
|
var done = new TaskCompletionSource<(AuctionInfo, CloseSummary, string)>(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
rig.Monitor.AuctionCompleted += (x, c, line) => { if (x.Id == a.Id) done.TrySetResult((x, c, line)); };
|
|
rig.Monitor.Start();
|
|
return await done.Task.WaitAsync(TimeSpan.FromSeconds(seconds));
|
|
}
|
|
|
|
[Fact]
|
|
public async Task In_Attiva_punta_una_volta_vince_e_chiude_con_il_riepilogo()
|
|
{
|
|
var world = new SimWorld(seed: 21, populate: false);
|
|
var settings = new AppSettings { QuietHoursEnabled = false, DefaultMaxPrice = 0, DefaultMaxClicks = 0 };
|
|
await using var rig = await StartAsync(world, settings);
|
|
var target = world.AddRunningAuction(seconds: 5, freq: 4);
|
|
|
|
var (a, message) = await rig.Monitor.AddAsync(new AddAuctionRequest(target.Id, Mode: RunMode.Active), CancellationToken.None);
|
|
Assert.NotNull(a);
|
|
Assert.Contains("Attiva", message);
|
|
Assert.True(a!.ProductInfoLoaded);
|
|
Assert.Equal(target.Value, a.BuyNowPrice);
|
|
|
|
var (done, summary, line) = await RunToCompletionAsync(rig, a);
|
|
|
|
Assert.Equal("won", done.Outcome);
|
|
Assert.True(summary.WonByMe);
|
|
Assert.Equal(1, summary.MyBids);
|
|
Assert.Equal(1, done.SuccessfulBids);
|
|
Assert.Single(world.MyBids, b => b.AuctionId == target.Id && b.Accepted);
|
|
Assert.StartsWith("Vinta a", line);
|
|
Assert.Contains("resta in elenco", line);
|
|
Assert.NotNull(rig.Monitor.Find(target.Id));
|
|
Assert.Contains(rig.Log.Snapshot(), e => e.Tag == "PUNTATA");
|
|
Assert.Contains(rig.Log.Snapshot(), e => e.Tag == "FINE");
|
|
// Il conto si aggiorna dalla risposta di bid.php.
|
|
Assert.NotNull(rig.Account.Total);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task In_Osserva_decide_senza_puntare_e_la_conclusa_esce_dall_elenco()
|
|
{
|
|
var world = new SimWorld(seed: 22, populate: false);
|
|
var settings = new AppSettings { QuietHoursEnabled = false, DefaultMaxPrice = 0, DefaultMaxClicks = 0 };
|
|
await using var rig = await StartAsync(world, settings);
|
|
var target = world.AddRunningAuction(seconds: 4, freq: 4);
|
|
|
|
var (a, _) = await rig.Monitor.AddAsync(new AddAuctionRequest(target.Id, Mode: RunMode.Watch), CancellationToken.None);
|
|
var (done, summary, line) = await RunToCompletionAsync(rig, a!);
|
|
|
|
Assert.Empty(world.MyBids);
|
|
Assert.False(summary.WonByMe);
|
|
Assert.Equal("lost", done.Outcome);
|
|
Assert.NotNull(done.LastDecision);
|
|
Assert.True(done.LastDecision!.Shadow);
|
|
Assert.Contains(done.Log.Snapshot(), e => e.Message.StartsWith("Avrei puntato", StringComparison.Ordinal));
|
|
Assert.Contains("tolta dall'elenco", line);
|
|
Assert.Null(rig.Monitor.Find(target.Id));
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Il_rischio_fermo_blocca_la_puntata_dal_vivo_ma_non_la_decisione()
|
|
{
|
|
var world = new SimWorld(seed: 23, populate: false);
|
|
var settings = new AppSettings { QuietHoursEnabled = false, DefaultMaxPrice = 0, DefaultMaxClicks = 0, AutoRemoveFinished = false };
|
|
await using var rig = await StartAsync(world, settings);
|
|
rig.Risk.SetHalt("prova", automatic: false);
|
|
var target = world.AddRunningAuction(seconds: 4, freq: 4);
|
|
|
|
var (a, _) = await rig.Monitor.AddAsync(new AddAuctionRequest(target.Id, Mode: RunMode.Active), CancellationToken.None);
|
|
var (done, _, _) = await RunToCompletionAsync(rig, a!);
|
|
|
|
Assert.Empty(world.MyBids);
|
|
Assert.Equal(LossReasons.Kind.Rischio, done.LastDecision?.Kind);
|
|
var (ok, why) = await rig.Monitor.BidNowAsync(target.Id, CancellationToken.None);
|
|
Assert.False(ok);
|
|
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()
|
|
{
|
|
var world = new SimWorld(seed: 24, populate: false);
|
|
var settings = new AppSettings { QuietHoursEnabled = false };
|
|
var target = world.AddRunningAuction(seconds: 600, freq: 10);
|
|
var other = world.AddRunningAuction(seconds: 600, freq: 10);
|
|
|
|
string? saved;
|
|
await using (var rig = await StartAsync(world, settings))
|
|
{
|
|
var (a, _) = await rig.Monitor.AddAsync(new AddAuctionRequest(target.Id, Mode: RunMode.Active), CancellationToken.None);
|
|
rig.Monitor.SetLimits(a!.Id, 2.5, 12.5, 30, 450, quietHours: false);
|
|
a.ResetCount = 17;
|
|
a.MyBidsPlaced = 3;
|
|
a.MyBidsCost = 0.39;
|
|
await rig.Monitor.AddAsync(new AddAuctionRequest(other.Id, Mode: RunMode.Watch), CancellationToken.None);
|
|
await rig.Monitor.DisposeAsync();
|
|
saved = rig.Monitor.Deps.Documents.Get(rig.Monitor.Deps.DocumentKey);
|
|
}
|
|
Assert.NotNull(saved);
|
|
|
|
await using var again = await StartAsync(world, settings);
|
|
again.Monitor.Deps.Documents.Set(again.Monitor.Deps.DocumentKey, saved!);
|
|
Assert.Equal(2, await again.Monitor.RestoreAsync());
|
|
var restored = again.Monitor.Find(target.Id)!;
|
|
Assert.Equal(RunMode.Active, restored.Mode);
|
|
Assert.Equal(RunMode.Watch, again.Monitor.Find(other.Id)!.Mode);
|
|
Assert.Equal(2.5, restored.MinPrice);
|
|
Assert.Equal(12.5, restored.MaxPrice);
|
|
Assert.Equal(30, restored.MaxBids);
|
|
Assert.False(restored.LimitsFromProduct);
|
|
Assert.True(restored.LeadIsManual);
|
|
Assert.Equal(450, restored.LeadMs);
|
|
Assert.False(restored.QuietHoursOverride);
|
|
Assert.Equal(17, restored.ResetCount);
|
|
Assert.Equal(3, restored.MyBidsPlaced);
|
|
Assert.Equal(0.39, restored.MyBidsCost, 6);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Senza_utente_collegato_l_asta_Attiva_decide_ma_non_punta()
|
|
{
|
|
var world = new SimWorld(seed: 25, populate: false);
|
|
var settings = new AppSettings { QuietHoursEnabled = false, DefaultMaxPrice = 0, DefaultMaxClicks = 0, AutoRemoveFinished = false };
|
|
await using var rig = await StartAsync(world, settings, canBid: () => false);
|
|
var target = world.AddRunningAuction(seconds: 4, freq: 4);
|
|
|
|
var (a, _) = await rig.Monitor.AddAsync(new AddAuctionRequest(target.Id, Mode: RunMode.Active), CancellationToken.None);
|
|
Assert.True(rig.Monitor.IsShadow(a!));
|
|
var (done, _, _) = await RunToCompletionAsync(rig, a!);
|
|
|
|
Assert.Empty(world.MyBids);
|
|
Assert.NotNull(done.LastDecision);
|
|
Assert.True(done.LastDecision!.Shadow);
|
|
var (ok, why) = await rig.Monitor.BidNowAsync(target.Id, CancellationToken.None);
|
|
Assert.False(ok);
|
|
Assert.Contains("Accesso a Bidoo", why);
|
|
// «Può puntare: no», e non perché manchi l'utente della sessione: manca proprio la sessione.
|
|
Assert.False(rig.Monitor.CanBidNow);
|
|
Assert.False(rig.Monitor.UserPending);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Con_la_sessione_ma_senza_sapere_chi_sono_l_asta_Attiva_non_punta_e_dice_perche()
|
|
{
|
|
// Una sessione incollata non porta l'utente: finché buy_bids.php non lo dice, il bot non distinguerebbe
|
|
// le sue puntate da quelle degli altri e punterebbe contro sé stesso.
|
|
var world = new SimWorld(seed: 27, populate: false);
|
|
var settings = new AppSettings { QuietHoursEnabled = false, DefaultMaxPrice = 0, DefaultMaxClicks = 0, AutoRemoveFinished = false };
|
|
await using var rig = await StartAsync(world, settings, knownUser: false);
|
|
var target = world.AddRunningAuction(seconds: 4, freq: 4);
|
|
|
|
// L'interfaccia («Può puntare», la barriera di «Punta adesso») dice la stessa cosa della strategia.
|
|
Assert.True(rig.Monitor.CanBid);
|
|
Assert.False(rig.Monitor.CanBidNow);
|
|
Assert.True(rig.Monitor.UserPending);
|
|
|
|
var (a, _) = await rig.Monitor.AddAsync(new AddAuctionRequest(target.Id, Mode: RunMode.Active), CancellationToken.None);
|
|
Assert.False(rig.Monitor.IsShadow(a!));
|
|
var (done, _, _) = await RunToCompletionAsync(rig, a!);
|
|
|
|
Assert.Empty(world.MyBids);
|
|
Assert.NotNull(done.LastDecision);
|
|
Assert.Equal(LossReasons.Kind.SenzaUtente, done.LastDecision!.Kind);
|
|
Assert.False(done.LastDecision.Shadow);
|
|
Assert.Single(done.Log.Snapshot(), e => e.Message.StartsWith("Non punto: utente della sessione non ancora riconosciuto", StringComparison.Ordinal));
|
|
|
|
var (ok, why) = await rig.Monitor.BidNowAsync(target.Id, CancellationToken.None);
|
|
Assert.False(ok);
|
|
Assert.Contains("non ancora riconosciuto", why);
|
|
Assert.Empty(world.MyBids);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task In_Osserva_senza_puntate_virtuali_segue_ma_non_decide()
|
|
{
|
|
var world = new SimWorld(seed: 26, populate: false);
|
|
var settings = new AppSettings { QuietHoursEnabled = false, ShadowDecisionsInWatch = false, AutoRemoveFinished = false };
|
|
await using var rig = await StartAsync(world, settings);
|
|
var target = world.AddRunningAuction(seconds: 4, freq: 4);
|
|
|
|
var (a, _) = await rig.Monitor.AddAsync(new AddAuctionRequest(target.Id, Mode: RunMode.Watch), CancellationToken.None);
|
|
var (done, _, _) = await RunToCompletionAsync(rig, a!);
|
|
|
|
Assert.Empty(world.MyBids);
|
|
Assert.Null(done.LastDecision);
|
|
Assert.Equal("lost", done.Outcome);
|
|
}
|
|
|
|
[Fact]
|
|
public void Gli_errori_di_puntata_tardiva_si_riconoscono()
|
|
{
|
|
Assert.True(AuctionMonitor.IsLateBidError("timer scaduto"));
|
|
Assert.True(AuctionMonitor.IsLateBidError("auction closed"));
|
|
Assert.False(AuctionMonitor.IsLateBidError("saldo insufficiente"));
|
|
Assert.False(AuctionMonitor.IsLateBidError(null));
|
|
}
|
|
|
|
[Fact]
|
|
public void Dopo_una_puntata_il_registro_dice_solo_il_totale_delle_puntate()
|
|
{
|
|
Assert.Equal(", 1.406 puntate residue", AuctionMonitor.RemainingText(1406));
|
|
Assert.Equal(", 12 puntate residue", AuctionMonitor.RemainingText(12));
|
|
Assert.Equal("", AuctionMonitor.RemainingText(null));
|
|
}
|
|
}
|