From 630d6983b5f08ec20c3a0574ed50f5cb8e9a7f33 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Sat, 26 Sep 2026 17:05:35 +0200 Subject: [PATCH] M3: motore di precisione e simulatore di Bidoo MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ServerClock portato 1:1 con i suoi test; attesa di precisione per Linux (sonno fino a 4 ms dal bersaglio, poi attesa attiva); cadenza del polling della specifica con il rallentamento delle aste programmate del legacy; runner per asta con polling asincrono e cecchino che nella finestra critica passa a un thread dedicato ad alta priorità, una sola puntata per ciclo. Simulatore HTTP interno con lo stesso formato del sito (data.php, bid.php, catalogo, conto, pagine) e avversari a profili; il cecchino vero lo batte in un test end-to-end. Co-Authored-By: Claude Opus 5.5 --- Mimante/src/BidooBidBot/BidooBidBot.csproj | 2 + Mimante/src/BidooBidBot/Engine/AuctionInfo.cs | 253 +++++++++++ Mimante/src/BidooBidBot/Engine/AuctionLog.cs | 128 ++++++ .../src/BidooBidBot/Engine/AuctionRunner.cs | 281 ++++++++++++ Mimante/src/BidooBidBot/Engine/PollCadence.cs | 54 +++ .../src/BidooBidBot/Engine/PrecisionWait.cs | 92 ++++ Mimante/src/BidooBidBot/Engine/ServerClock.cs | 103 +++++ Mimante/src/BidooBidBot/Simulator/SimWorld.cs | 412 ++++++++++++++++++ .../BidooBidBot/Simulator/SimulatedBidoo.cs | 222 ++++++++++ .../tests/BidooBidBot.Tests/EngineTests.cs | 378 ++++++++++++++++ 10 files changed, 1925 insertions(+) create mode 100644 Mimante/src/BidooBidBot/Engine/AuctionInfo.cs create mode 100644 Mimante/src/BidooBidBot/Engine/AuctionLog.cs create mode 100644 Mimante/src/BidooBidBot/Engine/AuctionRunner.cs create mode 100644 Mimante/src/BidooBidBot/Engine/PollCadence.cs create mode 100644 Mimante/src/BidooBidBot/Engine/PrecisionWait.cs create mode 100644 Mimante/src/BidooBidBot/Engine/ServerClock.cs create mode 100644 Mimante/src/BidooBidBot/Simulator/SimWorld.cs create mode 100644 Mimante/src/BidooBidBot/Simulator/SimulatedBidoo.cs create mode 100644 Mimante/tests/BidooBidBot.Tests/EngineTests.cs diff --git a/Mimante/src/BidooBidBot/BidooBidBot.csproj b/Mimante/src/BidooBidBot/BidooBidBot.csproj index 7a39cbc..f1a5153 100644 --- a/Mimante/src/BidooBidBot/BidooBidBot.csproj +++ b/Mimante/src/BidooBidBot/BidooBidBot.csproj @@ -22,6 +22,8 @@ + + diff --git a/Mimante/src/BidooBidBot/Engine/AuctionInfo.cs b/Mimante/src/BidooBidBot/Engine/AuctionInfo.cs new file mode 100644 index 0000000..e07de8f --- /dev/null +++ b/Mimante/src/BidooBidBot/Engine/AuctionInfo.cs @@ -0,0 +1,253 @@ +using BidooBidBot.Bidoo; +using BidooBidBot.Net; + +namespace BidooBidBot.Engine; + +/// I tre modi di un'asta in elenco. +public enum RunMode +{ + /// Ferma: nessuna richiesta verso Bidoo. + Stopped, + + /// Osserva: segue, decide e registra, ma non punta mai. È la modalità di allenamento. + Watch, + + /// Attiva: segue e punta secondo il modello, entro i paletti (solo con DAL VIVO). + Active +} + +public static class RunModes +{ + public static string ToKey(RunMode m) => m switch { RunMode.Active => "attiva", RunMode.Watch => "osserva", _ => "ferma" }; + + public static string Label(RunMode m) => m switch { RunMode.Active => "Attiva", RunMode.Watch => "Osserva", _ => "Ferma" }; + + public static RunMode Parse(string? s, RunMode fallback = RunMode.Watch) => (s ?? "").Trim().ToLowerInvariant() switch + { + "attiva" or "active" => RunMode.Active, + "osserva" or "watch" or "paused" => RunMode.Watch, + "ferma" or "stopped" or "stop" => RunMode.Stopped, + _ => fallback + }; +} + +/// L'ultima risposta del motore su un'asta, per il pannello e la griglia. +public sealed record DecisionView( + string Kind, bool ShouldBid, bool Shadow, double? PModel, double? PWin, double? Ev, double? BidCost, + string Reason, DateTime AtUtc); + +/// +/// Un'asta seguita: identità, paletti dell'utente, modo, e ciò che il motore osserva mentre +/// la segue. Il motore scrive, l'interfaccia legge: le liste stanno sotto +/// e si leggono solo con le istantanee; i campi semplici si leggono +/// senza lucchetto (valori atomici). cresce a ogni cambiamento che +/// l'interfaccia deve vedere. +/// +public sealed class AuctionInfo +{ + public AuctionInfo(string id) => Id = id; + + // ── Identità ───────────────────────────────────────────────────────── + public string Id { get; } + public string Name { get; set; } = ""; + public string Url { get; set; } = ""; + public string ProductKey { get; set; } = ""; + public int BidooProductId { get; set; } + public string? ImageUrl { get; set; } + + /// Da dove è entrata: «mano», «catalogo», «seguito». + public string Origin { get; set; } = "mano"; + + public DateTime AddedAtUtc { get; set; } = DateTime.UtcNow; + + // ── Paletti e modo ─────────────────────────────────────────────────── + private volatile int _mode = (int)RunMode.Watch; + + public RunMode Mode + { + get => (RunMode)_mode; + set { _mode = (int)value; Touch(); } + } + + /// Anticipo in ms: scritto a mano (se ) o l'ultimo deciso dalla rete. + public int LeadMs { get; set; } + public bool LeadIsManual { get; set; } + + /// Prezzo oltre il quale non si punta. 0 = nessun limite. + public double MaxPrice { get; set; } + + /// Puntate massime su quest'asta. 0 = nessun limite. + public int MaxBids { get; set; } + + /// Fascia oraria per quest'asta: null = come il prodotto o le impostazioni. + public bool? QuietHoursOverride { get; set; } + + // ── Prodotto (dalla pagina dell'asta) ──────────────────────────────── + public double? BuyNowPrice { get; set; } + public double? Shipping { get; set; } + public string? WinLimit { get; set; } + public bool ProductInfoLoaded { get; set; } + + // ── Stato vivo ─────────────────────────────────────────────────────── + private AuctionState? _lastState; + public AuctionState? LastState { get => _lastState; set { _lastState = value; } } + + private long _deadlineTicks; + + /// Scadenza del ciclo in tick di Stopwatch ancorata all'orologio del server. 0 = non nota. + public long DeadlineTicks + { + get => Interlocked.Read(ref _deadlineTicks); + set => Interlocked.Exchange(ref _deadlineTicks, value); + } + + public int TerminalStreak { get; set; } + public int ResetCount { get; set; } + public long PollCount; + public long PollErrors; + public int ConsecutivePollErrors { get; set; } + + public LatencyStats Latency { get; } = new(1000); + + // ── Storico visto ──────────────────────────────────────────────────── + public object BidsLock { get; } = new(); + + /// Le ultime puntate viste, dalla più recente (al massimo 50). Sotto . + public List RecentBids { get; } = new(); + + /// Puntate viste per utente da quando la si segue (cumulative). Sotto . + public Dictionary BidderTotals { get; } = new(StringComparer.OrdinalIgnoreCase); + + /// Prezzi (in centesimi) delle puntate già contate: evita i doppioni. Sotto . + public HashSet SeenBidCents { get; } = new(); + + public List SnapshotRecentBids(int max = 0) + { + lock (BidsLock) + return max > 0 && RecentBids.Count > max ? RecentBids.Take(max).ToList() : RecentBids.ToList(); + } + + public List<(string User, int Total, int Recent)> SnapshotBidders() + { + lock (BidsLock) + { + var recent = RecentBids.GroupBy(b => b.Username, StringComparer.OrdinalIgnoreCase) + .ToDictionary(g => g.Key, g => g.Count(), StringComparer.OrdinalIgnoreCase); + return BidderTotals + .Select(kv => (kv.Key, kv.Value, recent.GetValueOrDefault(kv.Key))) + .OrderByDescending(t => t.Item2) + .ToList(); + } + } + + // ── Serie del prezzo (per lo storico) ──────────────────────────────── + private readonly List<(double T, double Price)> _priceSeries = new(); + private const int MaxPricePoints = 600; + + public void TrackPrice(double price) + { + if (price <= 0) return; + FirstSeenAtUtc ??= DateTime.UtcNow; + lock (_priceSeries) + { + if (_priceSeries.Count > 0 && Math.Abs(_priceSeries[^1].Price - price) < 0.001) return; + if (_priceSeries.Count >= MaxPricePoints) + { + var thinned = _priceSeries.Where((_, i) => i % 2 == 0).ToList(); + _priceSeries.Clear(); + _priceSeries.AddRange(thinned); + } + _priceSeries.Add(((DateTime.UtcNow - FirstSeenAtUtc.Value).TotalSeconds, price)); + } + } + + public List<(double T, double Price)> SnapshotPriceSeries() + { + lock (_priceSeries) return _priceSeries.ToList(); + } + + // ── Le mie puntate ─────────────────────────────────────────────────── + + /// Puntate usate su quest'asta secondo il server (bid.php), di entrambi i tipi. + public int? BidsUsedOnAuction { get; set; } + + /// Puntate mie riuscite da quando la seguo. + public int MyBidsPlaced { get; set; } + + /// Euro spesi in puntate su quest'asta (costo effettivo). + public double MyBidsCost { get; set; } + + /// Puntate inviate dal motore in questa sessione, riuscite o no (paletto per asta). + public int SessionBidCount { get; set; } + public int SuccessfulBids { get; set; } + public int FailedBids { get; set; } + public int TimerExpiredCount { get; set; } + public DateTime? LastClickAtUtc { get; set; } + public DateTime? LastMyBidAtUtc { get; set; } + + /// Le puntate mie da contare per i paletti: il massimo fra server e motore. + public int MyBidsForLimits => Math.Max(BidsUsedOnAuction ?? 0, Math.Max(MyBidsPlaced, SessionBidCount)); + + // ── Decisioni ──────────────────────────────────────────────────────── + public DecisionView? LastDecision { get; set; } + + /// La decisione registrata per il ciclo in corso: la puntata che parte porta questo id. + public long? PendingDecisionId { get; set; } + public string? PendingDecisionKind { get; set; } + public double? PendingPWin { get; set; } + + // ── Previsione (Ml/AuctionForecast) ────────────────────────────────── + public object? Forecast { get; set; } + public int ForecastResetCount { get; set; } = -1; + public DateTime? ForecastAtUtc { get; set; } + public bool InitialForecastRecorded { get; set; } + + // ── Copertura e fine ───────────────────────────────────────────────── + public bool ObservedFromStart { get; set; } + public bool ObservedToEnd { get; set; } + public DateTime? TrackingStartedAtUtc { get; set; } + public DateTime? FirstSeenAtUtc { get; set; } + public DateTime? OpenedAtUtc { get; set; } + public DateTime? ConcludedAtUtc { get; set; } + public bool EndedWhileActive { get; set; } + + /// «won», «lost», «closed» a fine asta; null finché è in corso. + public string? Outcome { get; set; } + + private int _completionReported; + + /// Vero una volta sola: la chiusura si comunica a storico e apprendimento una volta. + public bool TryMarkCompletionReported() => Interlocked.Exchange(ref _completionReported, 1) == 0; + public bool CompletionReported => Volatile.Read(ref _completionReported) == 1; + + public bool IsFinished => Outcome != null; + + // ── Registro ───────────────────────────────────────────────────────── + public AuctionLog Log { get; } = new(); + + // ── Versione per l'interfaccia ─────────────────────────────────────── + private int _version; + public int Version => Volatile.Read(ref _version); + public void Touch() => Interlocked.Increment(ref _version); + + /// Millisecondi stimati alla scadenza; se non si sa. + public double EstimatedRemainingMs() + { + var d = DeadlineTicks; + return d == 0 ? double.MaxValue : PrecisionWait.MsUntil(d); + } + + /// Lo stato da mostrare nella griglia. + public string DisplayStatus() + { + if (Outcome == "won") return "vinta"; + if (Outcome == "lost") return "persa"; + if (Outcome == "closed") return "chiusa"; + var s = LastState; + if (s?.Status == AuctionStatus.Paused) return "sospesa"; + if (Mode == RunMode.Stopped) return "ferma"; + if (s?.IsMyBid == true) return "in-testa"; + if (s?.Status == AuctionStatus.Scheduled) return "programmata"; + return Mode == RunMode.Active ? "attiva" : "osserva"; + } +} diff --git a/Mimante/src/BidooBidBot/Engine/AuctionLog.cs b/Mimante/src/BidooBidBot/Engine/AuctionLog.cs new file mode 100644 index 0000000..b6f65bd --- /dev/null +++ b/Mimante/src/BidooBidBot/Engine/AuctionLog.cs @@ -0,0 +1,128 @@ +using BidooBidBot.Logging; + +namespace BidooBidBot.Engine; + +public enum AuctionLogCategory +{ + General, + Status, + Polling, + Timing, + Decision, + Bid, + Forecast, + Product +} + +/// Una riga del registro di un'asta. > 1 = la stessa riga ripetuta. +public sealed class AuctionLogEntry +{ + public long Id { get; init; } + public DateTimeOffset Ts { get; set; } + public LogLevel Level { get; init; } + public AuctionLogCategory Category { get; init; } + public string Message { get; set; } = ""; + public int Count { get; set; } = 1; + public string? DecisionKind { get; init; } +} + +/// +/// Il registro di un'asta: un anello in memoria per il pannello, e ogni riga nuova anche nel +/// file aste-AAAA-MM-GG.log (non nel database). Regole del legacy: tutto passa da +/// , due righe uguali di fila si contano, e le decisioni sono una +/// riga per tipo finché il tipo non cambia (). +/// +public sealed class AuctionLog +{ + private readonly object _sync = new(); + private readonly LinkedList _entries = new(); + private static long _nextId; + private string? _lastDecisionKind; + + public int Capacity { get; set; } = 500; + + /// Riga nuova (non l'aggiornamento di una esistente): va sul file del giorno. + public Action? Sink { get; set; } + + /// Cambia a ogni riga, nuova o aggiornata: l'interfaccia ridisegna solo se cambia. + public int Version { get; private set; } + + public void Add(string message, LogLevel level = LogLevel.Info, AuctionLogCategory category = AuctionLogCategory.General) + { + var clean = LogText.Clean(message); + AuctionLogEntry? added = null; + lock (_sync) + { + Version++; + var last = _entries.Last?.Value; + if (last != null && last.Message == clean && last.Category == category && last.DecisionKind == null) + { + last.Count++; + last.Ts = DateTimeOffset.Now; + return; + } + + _lastDecisionKind = null; + added = Append(new AuctionLogEntry { Id = Interlocked.Increment(ref _nextId), Ts = DateTimeOffset.Now, Level = level, Category = category, Message = clean }); + } + Publish(added); + } + + /// + /// Una decisione del motore: finché il tipo non cambia (per esempio «valore atteso + /// negativo» dieci cicli di fila) resta una riga sola, aggiornata con l'ultimo testo e il + /// conteggio. + /// + public void AddDecision(string kind, string message, LogLevel level = LogLevel.Info) + { + var clean = LogText.Clean(message); + AuctionLogEntry? added = null; + lock (_sync) + { + Version++; + var last = _entries.Last?.Value; + if (last != null && _lastDecisionKind == kind && last.Category == AuctionLogCategory.Decision) + { + last.Count++; + last.Ts = DateTimeOffset.Now; + last.Message = clean; + return; + } + + _lastDecisionKind = kind; + added = Append(new AuctionLogEntry + { + Id = Interlocked.Increment(ref _nextId), Ts = DateTimeOffset.Now, Level = level, + Category = AuctionLogCategory.Decision, Message = clean, DecisionKind = kind + }); + } + Publish(added); + } + + private AuctionLogEntry Append(AuctionLogEntry entry) + { + _entries.AddLast(entry); + while (_entries.Count > Math.Max(20, Capacity)) _entries.RemoveFirst(); + return entry; + } + + private void Publish(AuctionLogEntry? entry) + { + if (entry == null) return; + try { Sink?.Invoke(entry); } catch { /* il file non deve fermare il motore */ } + } + + public List Snapshot(int max = 0) + { + lock (_sync) + { + var skip = max > 0 && _entries.Count > max ? _entries.Count - max : 0; + return _entries.Skip(skip).Select(e => new AuctionLogEntry + { + Id = e.Id, Ts = e.Ts, Level = e.Level, Category = e.Category, Message = e.Message, Count = e.Count, DecisionKind = e.DecisionKind + }).ToList(); + } + } + + public int Count { get { lock (_sync) return _entries.Count; } } +} diff --git a/Mimante/src/BidooBidBot/Engine/AuctionRunner.cs b/Mimante/src/BidooBidBot/Engine/AuctionRunner.cs new file mode 100644 index 0000000..5ed045d --- /dev/null +++ b/Mimante/src/BidooBidBot/Engine/AuctionRunner.cs @@ -0,0 +1,281 @@ +using BidooBidBot.Bidoo; +using BidooBidBot.Logging; +using BidooBidBot.Settings; + +namespace BidooBidBot.Engine; + +/// +/// Ciò che il runner chiede al monitor. Il runner decide quando; il monitor decide +/// se e sa come puntare. +/// +public interface IAuctionRunnerHost +{ + AppSettings Settings { get; } + BidooReferences References { get; } + + /// Una interrogazione di data.php. Null = nessuna risposta utilizzabile. + Task PollAsync(AuctionInfo auction, CancellationToken ct); + + /// Incorpora la risposta: orologio, scadenza, storico, registrazione, interfaccia. + void ApplySnapshot(AuctionInfo auction, AuctionState snapshot); + + bool IsFinished(AuctionInfo auction); + + /// La decisione di questo ciclo si registra soltanto (Osserva, o modalità OSSERVA globale). + bool IsShadow(AuctionInfo auction); + + /// L'anticipo di quest'asta adesso: scritto a mano, o deciso dalla rete. + int EffectiveLeadMs(AuctionInfo auction); + + /// Il verdetto per questo ciclo, 60 ms prima del fuoco. In shadow risponde sempre «no». + bool EvaluateBid(AuctionInfo auction, AuctionState state, bool shadow); + + /// Invia la puntata e ne registra l'esito. Chiamato dal thread del cecchino. + void FireBid(AuctionInfo auction, AuctionState state, int leadMs, long fireTicks); +} + +/// +/// Il motore di una singola asta (portato dal legacy, specifica §6.2). Due anelli: +/// +/// +/// polling, asincrono, con la cadenza di ; +/// cecchino: un anello asincrono aspetta a basso costo; quando mancano pochi +/// centinaia di ms al fuoco passa la mano a un thread dedicato ad alta priorità, che +/// dorme fino a «scadenza − anticipo − 60 ms», chiede il verdetto, attende con precisione e +/// spara. Il thread nasce per il ciclo e muore dopo. +/// +/// Una sola puntata per ciclo, ancorata alla scadenza dichiarata dal server. Una risposta lenta +/// su un'asta non sposta di un millisecondo la puntata sulle altre. +/// +public sealed class AuctionRunner +{ + /// Da questi ms prima del fuoco il cecchino passa sul thread dedicato. + private const double HandOffMs = 300; + + private readonly AuctionInfo _auction; + private readonly IAuctionRunnerHost _host; + private CancellationTokenSource? _cts; + private Task? _pollTask; + private Task? _sniperTask; + + /// Scadenza (unix) del ciclo già deciso: garantisce una sola puntata per ciclo. + private long _handledCycle = -1; + + public AuctionRunner(AuctionInfo auction, IAuctionRunnerHost host) + { + _auction = auction; + _host = host; + } + + public AuctionInfo Auction => _auction; + public bool IsRunning => _pollTask is { IsCompleted: false }; + + public void Start() + { + if (IsRunning) return; + _cts = new CancellationTokenSource(); + var token = _cts.Token; + _pollTask = Task.Run(() => PollLoopAsync(token), token); + _sniperTask = Task.Run(() => SniperLoopAsync(token), token); + } + + public async Task StopAsync() + { + var cts = _cts; + if (cts == null) return; + _cts = null; + try { await cts.CancelAsync().ConfigureAwait(false); } catch { } + + var tasks = new[] { _pollTask, _sniperTask }.Where(t => t != null).Cast().ToArray(); + if (tasks.Length > 0) + { + try { await Task.WhenAll(tasks).WaitAsync(TimeSpan.FromSeconds(3)).ConfigureAwait(false); } + catch { /* uscita forzata */ } + } + _pollTask = null; + _sniperTask = null; + cts.Dispose(); + } + + // ── Polling ────────────────────────────────────────────────────────── + + private async Task PollLoopAsync(CancellationToken ct) + { + while (!ct.IsCancellationRequested) + { + try + { + var snapshot = await _host.PollAsync(_auction, ct).ConfigureAwait(false); + if (snapshot == null) + { + _auction.ConsecutivePollErrors++; + Interlocked.Increment(ref _auction.PollErrors); + if (_auction.ConsecutivePollErrors == 3) + _auction.Log.Add("Nessuna risposta utilizzabile da data.php: controlla rete e sessione", + LogLevel.Warning, AuctionLogCategory.Polling); + + var backoff = Math.Min(300 * _auction.ConsecutivePollErrors, 5000); + if (!await Delay(backoff, ct).ConfigureAwait(false)) return; + continue; + } + + _auction.ConsecutivePollErrors = 0; + Interlocked.Increment(ref _auction.PollCount); + _host.ApplySnapshot(_auction, snapshot); + if (_host.IsFinished(_auction)) return; + + var delay = PollCadence.NextDelayMs(_auction.Mode, snapshot.Status, _auction.EstimatedRemainingMs(), + _host.Settings, _host.References); + if (!await Delay(delay, ct).ConfigureAwait(false)) return; + } + catch (OperationCanceledException) + { + return; + } + catch (Exception ex) + { + _auction.Log.Add($"Errore nel polling: {ex.Message}", LogLevel.Error, AuctionLogCategory.Polling); + if (!await Delay(1000, ct).ConfigureAwait(false)) return; + } + } + } + + // ── Cecchino ───────────────────────────────────────────────────────── + + private async Task SniperLoopAsync(CancellationToken ct) + { + while (!ct.IsCancellationRequested) + { + try + { + if (_auction.Mode == RunMode.Stopped || _host.IsFinished(_auction)) + { + if (!await Delay(150, ct).ConfigureAwait(false)) return; + continue; + } + + var state = _auction.LastState; + var deadline = _auction.DeadlineTicks; + if (state == null || deadline == 0 || state.Status is not (AuctionStatus.Running or AuctionStatus.Pending)) + { + if (!await Delay(100, ct).ConfigureAwait(false)) return; + continue; + } + + var cycle = state.ExpiryUnixSeconds; + if (cycle == _handledCycle) + { + // Già deciso su questo ciclo: si dorme fino alla scadenza (tetto 1 s) invece + // di svegliarsi quaranta volte al secondo a vuoto. + var idle = Math.Clamp(PrecisionWait.MsUntil(deadline), 25, 1000); + if (!await Delay((int)idle, ct).ConfigureAwait(false)) return; + continue; + } + + if (PrecisionWait.MsUntil(deadline) <= 0) + { + _handledCycle = cycle; + _auction.TimerExpiredCount++; + _auction.Log.Add("Ciclo scaduto prima di arrivare all'anticipo", LogLevel.Debug, AuctionLogCategory.Timing); + if (!await Delay(25, ct).ConfigureAwait(false)) return; + continue; + } + + var lead = _host.EffectiveLeadMs(_auction); + var msToFire = PrecisionWait.MsUntil(deadline - PrecisionWait.MsToTicks(lead)); + var preCheck = _host.References.Timing.PreCheckMs; + + if (msToFire > HandOffMs + preCheck) + { + // Una puntata altrui sposta la scadenza in avanti: si ricontrolla spesso. + var sleep = Math.Clamp(msToFire - HandOffMs - preCheck, 5, 200); + if (!await Delay((int)sleep, ct).ConfigureAwait(false)) return; + continue; + } + + await RunCriticalWindowAsync(cycle, ct).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + return; + } + catch (Exception ex) + { + _auction.Log.Add($"Errore nel cecchino: {ex.Message}", LogLevel.Error, AuctionLogCategory.Bid); + if (!await Delay(250, ct).ConfigureAwait(false)) return; + } + } + } + + /// La finestra critica su un thread dedicato, nato per questo ciclo. + private Task RunCriticalWindowAsync(long cycle, CancellationToken ct) + { + var done = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var thread = new Thread(() => + { + try { CriticalWindow(cycle, ct); } + catch (Exception ex) { _auction.Log.Add($"Errore nel cecchino: {ex.Message}", LogLevel.Error, AuctionLogCategory.Bid); } + finally { done.TrySetResult(); } + }) + { + IsBackground = true, + Priority = ThreadPriority.Highest, + Name = $"cecchino-{_auction.Id}" + }; + thread.Start(); + return done.Task; + } + + private void CriticalWindow(long cycle, CancellationToken ct) + { + var preCheck = _host.References.Timing.PreCheckMs; + long fire; + int lead; + + // Fino a 60 ms dal fuoco: la scadenza può ancora spostarsi (puntata altrui). + while (true) + { + if (ct.IsCancellationRequested) return; + var s = _auction.LastState; + if (s == null || s.ExpiryUnixSeconds != cycle) return; // ciclo nuovo: ci pensa l'anello + + lead = _host.EffectiveLeadMs(_auction); + fire = _auction.DeadlineTicks - PrecisionWait.MsToTicks(lead); + var ms = PrecisionWait.MsUntil(fire); + if (ms <= preCheck) break; + Thread.Sleep(TimeSpan.FromMilliseconds(Math.Min(ms - preCheck, 50))); + } + + // Da qui il ciclo è nostro: nessun'altra iterazione lo riprenderà. + _handledCycle = cycle; + + var state = _auction.LastState; + if (state == null || state.ExpiryUnixSeconds != cycle) return; + + var shadow = _host.IsShadow(_auction); + if (!_host.EvaluateBid(_auction, state, shadow)) return; + + PrecisionWait.Until(fire, ct, _host.Settings.PrecisionTimerEnabled); + if (ct.IsCancellationRequested) return; + + // Ultimi controlli a costo zero: siamo già in testa, o qualcuno ha puntato negli + // ultimi 60 ms e il ciclo è ricominciato (una puntata adesso cadrebbe a 10 s dalla fine). + var now = _auction.LastState; + if (now?.IsMyBid == true || now?.ExpiryUnixSeconds != cycle) return; + + _host.FireBid(_auction, state, lead, fire); + } + + private static async Task Delay(int ms, CancellationToken ct) + { + try + { + await Task.Delay(ms, ct).ConfigureAwait(false); + return true; + } + catch (OperationCanceledException) + { + return false; + } + } +} diff --git a/Mimante/src/BidooBidBot/Engine/PollCadence.cs b/Mimante/src/BidooBidBot/Engine/PollCadence.cs new file mode 100644 index 0000000..58dfe4c --- /dev/null +++ b/Mimante/src/BidooBidBot/Engine/PollCadence.cs @@ -0,0 +1,54 @@ +using BidooBidBot.Bidoo; +using BidooBidBot.Settings; + +namespace BidooBidBot.Engine; + +/// +/// Ogni quanto interrogare un'asta (specifica §5): fitta solo dove serve. +/// +/// +/// oltre 60 s sul cronometro: 2000 ms; fra 10 e 60 s: 900 ms; sotto 10 s: 400 ms; +/// finestra critica (sotto 4 s, solo aste in Attiva): 220 ms; +/// aste programmate: oltre un'ora ogni 1200 s, fra 10 e 60 minuti ogni 120 s, negli +/// ultimi 10 minuti ogni 30 s, e alla cadenza normale da 120 s prima dell'apertura. +/// L'attesa non supera mai il momento del risveglio: l'ultima interrogazione cade sempre +/// prima dell'apertura (dal legacy); +/// aste sospese di notte (STOP): ogni 30 s. +/// +/// Classe pura: i numeri arrivano da impostazioni e riferimenti. +/// +public static class PollCadence +{ + public static int NextDelayMs(RunMode mode, AuctionStatus? status, double msToDeadline, AppSettings s, BidooReferences refs) + { + if (status is AuctionStatus.Scheduled or AuctionStatus.Pending) + { + var scheduled = NotStartedDelay(msToDeadline, s); + if (scheduled > 0) return scheduled; + } + + if (status == AuctionStatus.Paused && msToDeadline > 60_000) return 30_000; + + if (msToDeadline == double.MaxValue || msToDeadline > 60_000) return s.PollFarMs; + if (msToDeadline > 10_000) return s.PollMidMs; + if (mode == RunMode.Active && msToDeadline <= refs.Timing.CriticalWindowS * 1000) return s.PollCriticalMs; + return s.PollNearMs; + } + + /// Cadenza di un'asta che deve ancora cominciare, o 0 se si torna alla cadenza normale. + public static int NotStartedDelay(double msToStart, AppSettings s) + { + if (!s.ScheduledAuctionBackoffEnabled) return 0; + if (msToStart == double.MaxValue || msToStart <= 0) return 0; + + var wakeMs = Math.Max(30, s.ScheduledPollWakeSeconds) * 1000.0; + if (msToStart <= wakeMs) return 0; + + var desired = msToStart > 3_600_000 ? Math.Max(60, s.ScheduledPollFarSeconds) * 1000.0 + : msToStart > 600_000 ? Math.Max(30, s.ScheduledPollMidSeconds) * 1000.0 + : 30_000.0; + + var untilWake = msToStart - wakeMs; + return (int)Math.Clamp(Math.Min(desired, untilWake), 1000, 1_800_000); + } +} diff --git a/Mimante/src/BidooBidBot/Engine/PrecisionWait.cs b/Mimante/src/BidooBidBot/Engine/PrecisionWait.cs new file mode 100644 index 0000000..645d39d --- /dev/null +++ b/Mimante/src/BidooBidBot/Engine/PrecisionWait.cs @@ -0,0 +1,92 @@ +using System.Diagnostics; +using System.Runtime.CompilerServices; + +namespace BidooBidBot.Engine; + +/// +/// Attesa fino a un istante in tick di (specifica §6.3). +/// +/// Su Linux Thread.Sleep si sveglia con meno di un millisecondo di ritardo +/// tipico, quindi si dorme fino a 4 ms dal bersaglio e si copre l'ultimo tratto con attesa +/// attiva (cedendo il core finché mancano più di 2 ms). Niente timeBeginPeriod: su +/// Linux non serve. Su Windows (solo sviluppo) il timer di sistema scatta ogni 15,6 ms e il +/// margine si allarga a 20 ms. +/// +/// L'errore effettivo di ogni puntata si misura e si conserva (my_bids.wait_error_ms). +/// +public static class PrecisionWait +{ + /// Margine coperto in attesa attiva. + public static double SleepMarginMs { get; } = OperatingSystem.IsWindows() ? 20 : 4; + + /// Ultimo tratto in cui non si cede più il core. + private const double TightSpinMs = 2.0; + + /// + /// Attesa sincrona: per il thread dedicato del cecchino. falso = + /// solo sonno (impostazione PrecisionTimerEnabled spenta). + /// + public static void Until(long targetTicks, CancellationToken ct, bool precise = true) + { + while (!ct.IsCancellationRequested) + { + var remainingMs = MsUntil(targetTicks); + if (remainingMs <= 0) return; + + if (!precise) + { + Thread.Sleep(TimeSpan.FromMilliseconds(Math.Min(remainingMs, 1000))); + continue; + } + + if (remainingMs > SleepMarginMs) + { + Thread.Sleep(TimeSpan.FromMilliseconds(Math.Min(remainingMs - SleepMarginMs, 1000))); + continue; + } + + SpinUntil(targetTicks, ct); + return; + } + } + + /// Attesa asincrona: per i percorsi che non hanno un thread proprio. + public static async Task UntilAsync(long targetTicks, CancellationToken ct) + { + while (!ct.IsCancellationRequested) + { + var remainingMs = MsUntil(targetTicks); + if (remainingMs <= 0) return; + + if (remainingMs > SleepMarginMs + 16) + { + await Task.Delay(TimeSpan.FromMilliseconds(Math.Min(remainingMs - SleepMarginMs - 16, 1000)), ct).ConfigureAwait(false); + continue; + } + + Until(targetTicks, ct); + return; + } + } + + [MethodImpl(MethodImplOptions.AggressiveOptimization)] + private static void SpinUntil(long targetTicks, CancellationToken ct) + { + while (true) + { + var remainingMs = MsUntil(targetTicks); + if (remainingMs <= 0 || ct.IsCancellationRequested) return; + if (remainingMs > TightSpinMs) Thread.Yield(); + else Thread.SpinWait(40); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static double MsUntil(long targetTicks) => + (targetTicks - Stopwatch.GetTimestamp()) * 1000.0 / Stopwatch.Frequency; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static long MsToTicks(double ms) => (long)(ms / 1000.0 * Stopwatch.Frequency); + + public static long Now => Stopwatch.GetTimestamp(); +} diff --git a/Mimante/src/BidooBidBot/Engine/ServerClock.cs b/Mimante/src/BidooBidBot/Engine/ServerClock.cs new file mode 100644 index 0000000..deaa2fe --- /dev/null +++ b/Mimante/src/BidooBidBot/Engine/ServerClock.cs @@ -0,0 +1,103 @@ +using System.Diagnostics; + +namespace BidooBidBot.Engine; + +/// +/// Allinea l'orologio monotono locale a quello del server Bidoo (portato 1:1 dal legacy). +/// +/// data.php dà i timestamp in secondi interi: un campione da solo vale ±1 s. Ma ogni +/// risposta dice «il mio secondo corrente è S» ed è stata generata prima di arrivare qui. +/// Detto A l'istante locale del secondo server 0, ogni campione dà un limite superiore per A; +/// il minimo su molti campioni (256) converge al valore vero, come il filtro di NTP. +/// +/// L'errore residuo è per costruzione verso il basso, cioè verso una scadenza stimata +/// leggermente in anticipo: si punta un filo prima, mai dopo. Una finestra di ~1000 ms +/// () è normale: è la quantizzazione al secondo, non l'errore. +/// +public sealed class ServerClock +{ + private const int WindowSize = 256; + + private readonly long[] _samples = new long[WindowSize]; + private readonly int[] _latencies = new int[WindowSize]; + private readonly object _sync = new(); + private int _index; + private int _count; + private long _latencySum; + private long _origin; + private double _spreadMs; + + public int SampleCount { get { lock (_sync) return _count; } } + + /// Agganciato da tre campioni in su. + public bool IsSynced { get { lock (_sync) return _count >= 3; } } + + /// Ampiezza della finestra dei campioni in ms (quantizzazione al secondo, ~1000 ms). + public double SpreadMs { get { lock (_sync) return _spreadMs; } } + + public double AverageLatencyMs { get { lock (_sync) return _count == 0 ? 0 : (double)_latencySum / _count; } } + + /// Tick locale del secondo unix 0 del server. + public long Origin { get { lock (_sync) return _origin; } } + + /// Registra una risposta del server. + public void AddSample(long serverUnixSeconds, long receivedTicks, int latencyMs) + { + if (serverUnixSeconds <= 0 || receivedTicks <= 0) return; + + var f = Stopwatch.Frequency; + var generatedTicks = receivedTicks - (long)(latencyMs / 2.0 / 1000.0 * f); + var candidate = generatedTicks - serverUnixSeconds * f; + + lock (_sync) + { + if (_count == WindowSize) _latencySum -= _latencies[_index]; + + _samples[_index] = candidate; + _latencies[_index] = latencyMs < 0 ? 0 : latencyMs; + _latencySum += _latencies[_index]; + _index = (_index + 1) % WindowSize; + if (_count < WindowSize) _count++; + + long min = long.MaxValue, max = long.MinValue; + for (var i = 0; i < _count; i++) + { + var v = _samples[i]; + if (v < min) min = v; + if (v > max) max = v; + } + + _origin = min; + _spreadMs = (max - min) * 1000.0 / f; + } + } + + /// Un istante unix del server in tick locali di . + public long ToLocalTicks(long serverUnixSeconds) + { + lock (_sync) return _origin + serverUnixSeconds * Stopwatch.Frequency; + } + + /// Scarto stimato fra ora del server e ora locale (ms), per l'interfaccia: server − locale. + public double OffsetMs() + { + if (!IsSynced) return 0; + var serverNowTicks = Stopwatch.GetTimestamp() - Origin; + var serverNowMs = serverNowTicks * 1000.0 / Stopwatch.Frequency; + return serverNowMs - DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + } + + public void Reset() + { + lock (_sync) + { + Array.Clear(_samples); + Array.Clear(_latencies); + _index = 0; + _count = 0; + _latencySum = 0; + _origin = 0; + _spreadMs = 0; + } + } +} diff --git a/Mimante/src/BidooBidBot/Simulator/SimWorld.cs b/Mimante/src/BidooBidBot/Simulator/SimWorld.cs new file mode 100644 index 0000000..1df9c4f --- /dev/null +++ b/Mimante/src/BidooBidBot/Simulator/SimWorld.cs @@ -0,0 +1,412 @@ +using System.Globalization; + +namespace BidooBidBot.Simulator; + +/// Come si comporta un avversario simulato. +public enum SimProfile +{ + /// L'autopuntata del sito: scatta a 2 secondi esatti dalla fine, fino al suo massimo. + AutoBid, + + /// Punta a mano negli ultimi secondi, non a ogni ciclo. + Sniper, + + /// Punta presto nel ciclo, spesso. + Aggressive, + + /// Punta a caso e smette presto. + Beginner, + + /// Più ha speso, meno smette: il costo affondato di Augenblick. + SunkCost +} + +/// Un avversario in un'asta simulata. +public sealed class SimBidder +{ + public string Name { get; init; } = ""; + public SimProfile Profile { get; init; } + public int MaxBids { get; init; } + public int Spent { get; set; } + public bool Quit { get; set; } + + /// Millisecondi dalla fine a cui punterà in questo ciclo; null = in questo ciclo non punta. + public double? PlannedAtMs { get; set; } +} + +/// Una puntata nello storico simulato. +public readonly record struct SimBid(int PriceCents, string User, long Unix, bool Auto); + +/// Un'asta simulata. +public sealed class SimAuction +{ + public string Id { get; init; } = ""; + public int ProductId { get; init; } + public string Name { get; init; } = ""; + public string Slug { get; init; } = ""; + public int CategoryTag { get; init; } + public double Value { get; init; } + public double Shipping { get; init; } + public int FreqSeconds { get; init; } = 10; + + /// ON, OFF, STOP. + public string Status { get; set; } = "ON"; + + /// Secondo unix a cui scade il ciclo (per un'asta programmata: l'apertura). + public long ExpiryUnix { get; set; } + + public int PriceCents { get; set; } = 1; + public string LastBidder { get; set; } = ""; + public List History { get; } = new(); + public List Bidders { get; } = new(); + public Dictionary SpentByUser { get; } = new(StringComparer.OrdinalIgnoreCase); + public DateTimeOffset? EndedAt { get; set; } + public bool Started => History.Count > 0; + public int CycleNumber { get; set; } +} + +/// Una puntata mia arrivata al simulatore: serve a misurare la precisione. +public readonly record struct SimMyBid(string AuctionId, long DeadlineUnixMs, long ArrivalUnixMs, bool Accepted, string Result) +{ + /// Anticipo effettivo sulla scadenza, misurato dal «server». + public double LeadMs => DeadlineUnixMs - ArrivalUnixMs; +} + +/// +/// Il mondo del simulatore: aste sintetiche con avversari dai profili calibrati sui dati del +/// legacy (il grosso punta con circa tre secondi sul cronometro, l'autopuntata a due, sotto i +/// due la concorrenza si dirada; il 75% dei puntatori abbandona prima di 50 puntate). Le aste +/// concluse restano visibili qualche minuto, poi ne nasce una nuova. +/// +/// Il simulatore non è la realtà: serve a test, riscaldamento, schermate e prove al primo +/// avvio. Ciò che il modello impara qui non contamina il modello vero. +/// +public sealed class SimWorld +{ + private readonly object _sync = new(); + private readonly Random _rng; + private readonly Func _now; + private int _nextId = 85559700; + private readonly List _myBids = new(); + + public string MyUsername { get; set; } = "utente_demo"; + public string MyUserId { get; set; } = "6707664"; + public int PaidBids { get; set; } = 927; + public int FreeBids { get; set; } = 480; + public double ShopCredit { get; set; } = 15.00; + public int WonToConfirm { get; set; } = 1; + + /// Quante aste tenere in vita (le concluse vengono sostituite). + public int TargetAuctions { get; set; } = 14; + + /// Probabilità per ciclo che un'asta resti senza avversari (e chiuda). + public double Fatigue { get; set; } = 1.0; + + public List Auctions { get; } = new(); + + public SimWorld(int seed = 42, Func? clock = null, bool populate = true) + { + _rng = new Random(seed); + _now = clock ?? (() => DateTimeOffset.UtcNow); + if (populate) Populate(); + } + + public DateTimeOffset Now => _now(); + public long NowUnix => _now().ToUnixTimeSeconds(); + public long NowUnixMs => _now().ToUnixTimeMilliseconds(); + + public IReadOnlyList MyBids { get { lock (_sync) return _myBids.ToList(); } } + + // ── Catalogo dei prodotti ──────────────────────────────────────────── + + public sealed record Product(int Id, string Name, int Tag, double Value, double Shipping, int Freq); + + public static readonly IReadOnlyList<(int Tag, string Slug, string Name)> Categories = new[] + { + (6, "buoni", "Buoni"), (5, "smartphone", "Smartphone"), (7, "apple", "Apple"), + (8, "cucina", "Cucina"), (9, "videogame", "Videogame"), (11, "elettrodomestici", "Elettrodomestici") + }; + + public static readonly IReadOnlyList Products = new[] + { + new Product(41127, "Buono Amazon 50 €", 6, 50, 1, 10), + new Product(41130, "Buono Idea Shopping 250 €", 6, 250, 1, 15), + new Product(41131, "Buono carburante 100 €", 6, 100, 1, 10), + new Product(41140, "Buono Zalando 100 €", 6, 100, 1, 10), + new Product(26283, "Apple AirPods Pro 2", 7, 279, 9.9, 10), + new Product(26290, "PlayStation 5 Slim", 9, 549, 9.9, 15), + new Product(26295, "Nintendo Switch 2", 9, 469, 9.9, 10), + new Product(33010, "Dyson V15 Detect", 11, 699, 9.9, 15), + new Product(33020, "Philips Airfryer XXL", 8, 249, 9.9, 10), + new Product(33030, "Samsung Galaxy S25", 5, 929, 9.9, 15), + new Product(33040, "Bosch trapano GSR 12V", 11, 139, 9.9, 10), + new Product(33050, "Stanley Quencher 1,2 L", 8, 45, 5.9, 5) + }; + + private static readonly string[] Names = + { + "marco_82", "lulu_bid", "gigi72", "auto_stella", "pippo_c", "sara_m", "kingbid", "andre_91", "mimmo74", + "fede_k", "redberri", "semoricci", "kikisi9", "casmeride", "paola_z", "tony_b", "elisa88", "robbie" + }; + + // ── Popolamento ────────────────────────────────────────────────────── + + public void Populate() + { + lock (_sync) + { + var now = NowUnix; + for (var i = 0; i < TargetAuctions; i++) + { + var product = Products[i % Products.Count]; + // Tre aste programmate più avanti, una sospesa per la notte, le altre in corso a prezzi diversi. + var a = NewAuction(product, i switch + { + 3 => now + 1800 + _rng.Next(600), + 9 => now + 5400, + 12 => now + 900, + _ => now + 8 + _rng.Next(20) + }); + + if (i is not (3 or 9 or 12)) + { + var preBids = 20 + _rng.Next(i % 3 == 0 ? 900 : 300); + FakeHistory(a, preBids, now); + } + if (i == 6) a.Status = "STOP"; + Auctions.Add(a); + } + } + } + + private SimAuction NewAuction(Product p, long openAt) + { + var id = (_nextId++).ToString(CultureInfo.InvariantCulture); + var slug = Slug(p.Name) + "_" + id; + var a = new SimAuction + { + Id = id, ProductId = p.Id, Name = p.Name, Slug = slug, CategoryTag = p.Tag, Value = p.Value, + Shipping = p.Shipping, FreqSeconds = p.Freq, ExpiryUnix = openAt + }; + + var count = 2 + _rng.Next(6); + var names = Names.OrderBy(_ => _rng.Next()).Take(count).ToList(); + for (var i = 0; i < names.Count; i++) + { + var profile = (SimProfile)_rng.Next(5); + a.Bidders.Add(new SimBidder + { + Name = names[i], + Profile = profile, + MaxBids = profile switch + { + SimProfile.AutoBid => 20 + _rng.Next(150), + SimProfile.Beginner => 3 + _rng.Next(15), + SimProfile.Aggressive => 40 + _rng.Next(200), + SimProfile.SunkCost => 60 + _rng.Next(400), + _ => 30 + _rng.Next(120) + } + }); + } + return a; + } + + /// Una storia già scritta per le aste che «erano già in corso» all'avvio. + private void FakeHistory(SimAuction a, int bids, long now) + { + var t = now - bids * 7L; + for (var i = 0; i < bids; i++) + { + var b = a.Bidders[_rng.Next(a.Bidders.Count)]; + t += 3 + _rng.Next(9); + AddBid(a, b.Name, Math.Min(t, now - 1), b.Profile == SimProfile.AutoBid, paid: _rng.NextDouble() < 0.3); + b.Spent++; + } + a.ExpiryUnix = now + 3 + _rng.Next(a.FreqSeconds); + } + + private static string Slug(string name) + { + var chars = name.Where(c => char.IsLetterOrDigit(c) || c == ' ').ToArray(); + return string.Join('_', new string(chars).Split(' ', StringSplitOptions.RemoveEmptyEntries)); + } + + private void AddBid(SimAuction a, string user, long unix, bool auto, bool paid) + { + a.PriceCents++; + a.LastBidder = user; + a.History.Add(new SimBid(a.PriceCents, user, unix, auto)); + var (p, f) = a.SpentByUser.GetValueOrDefault(user); + a.SpentByUser[user] = paid ? (p + 1, f) : (p, f + 1); + } + + // ── Il tempo che passa ─────────────────────────────────────────────── + + /// Fa avanzare il mondo fino ad adesso. Lo chiama un timer e ogni richiesta. + public void Tick() + { + lock (_sync) + { + var nowMs = NowUnixMs; + var nowUnix = nowMs / 1000; + + foreach (var a in Auctions.ToList()) + { + if (a.Status == "OFF") + { + if (a.EndedAt is { } ended && Now - ended > TimeSpan.FromMinutes(4)) + { + Auctions.Remove(a); + var p = Products[_rng.Next(Products.Count)]; + Auctions.Add(NewAuction(p, nowUnix + 60 + _rng.Next(600))); + } + continue; + } + if (a.Status == "STOP") continue; + + var deadlineMs = a.ExpiryUnix * 1000; + + // Programmata: all'apertura parte il primo ciclo. + if (!a.Started && nowMs < deadlineMs) continue; + + if (!a.Started) + { + // Apertura: il primo avversario punta subito, parte il cronometro. + var first = a.Bidders.First(b => !b.Quit); + AddBid(a, first.Name, nowUnix, first.Profile == SimProfile.AutoBid, paid: _rng.NextDouble() < 0.3); + first.Spent++; + StartCycle(a, nowUnix); + continue; + } + + if (nowMs >= deadlineMs) + { + a.Status = "OFF"; + a.EndedAt = Now; + continue; + } + + var remaining = deadlineMs - nowMs; + SimBidder? winner = null; + foreach (var b in a.Bidders) + { + if (b.Quit || b.PlannedAtMs is not { } at || b.Name == a.LastBidder) continue; + if (remaining <= at && (winner == null || at > winner.PlannedAtMs)) winner = b; + } + + if (winner != null) + { + AddBid(a, winner.Name, nowUnix, winner.Profile == SimProfile.AutoBid, paid: _rng.NextDouble() < 0.3); + winner.Spent++; + if (winner.Spent >= winner.MaxBids) winner.Quit = true; + StartCycle(a, nowUnix); + } + } + } + } + + /// Nuovo ciclo: scadenza al secondo intero e piani degli avversari. + private void StartCycle(SimAuction a, long nowUnix) + { + a.ExpiryUnix = nowUnix + a.FreqSeconds; + a.CycleNumber++; + var depth = a.PriceCents; + + foreach (var b in a.Bidders) + { + b.PlannedAtMs = null; + if (b.Quit) continue; + + // Stanchezza: il 75% smette prima di 50 puntate; chi ha speso tanto resta. + var quit = b.Profile switch + { + SimProfile.Beginner => 0.08, + SimProfile.SunkCost => 0.03 * Math.Exp(-b.Spent / 25.0), + SimProfile.AutoBid => 0.004, + SimProfile.Aggressive => 0.01 + depth / 200_000.0, + _ => 0.012 + } * Fatigue; + if (_rng.NextDouble() < quit) { b.Quit = true; continue; } + + var freqMs = a.FreqSeconds * 1000.0; + b.PlannedAtMs = b.Profile switch + { + SimProfile.AutoBid => 2000 + (_rng.NextDouble() - 0.5) * 60, + SimProfile.Sniper => _rng.NextDouble() < 0.55 ? 700 + _rng.NextDouble() * 2300 : null, + SimProfile.Aggressive => _rng.NextDouble() < 0.35 ? freqMs * (0.3 + _rng.NextDouble() * 0.5) : null, + SimProfile.Beginner => _rng.NextDouble() < 0.12 ? _rng.NextDouble() * freqMs : null, + SimProfile.SunkCost => _rng.NextDouble() < 0.5 + Math.Min(0.4, b.Spent / 200.0) ? 1000 + _rng.NextDouble() * 2000 : null, + _ => null + }; + } + } + + // ── Le mie puntate ─────────────────────────────────────────────────── + + /// La risposta di bid.php a una mia puntata. + public string MyBid(string auctionId) + { + lock (_sync) + { + Tick(); + var a = Auctions.FirstOrDefault(x => x.Id == auctionId); + var nowMs = NowUnixMs; + if (a == null) return "error|Asta non trovata"; + + var deadline = a.ExpiryUnix * 1000; + if (a.Status != "ON" || !a.Started || nowMs >= deadline) + { + _myBids.Add(new SimMyBid(auctionId, deadline, nowMs, false, "chiusa")); + return a.Status == "OFF" || nowMs >= deadline ? "error|Tempo scaduto: l'asta è terminata" : "error|Asta non ancora iniziata"; + } + if (a.LastBidder.Equals(MyUsername, StringComparison.OrdinalIgnoreCase)) + { + _myBids.Add(new SimMyBid(auctionId, deadline, nowMs, false, "in testa")); + return "no|Sei già il miglior offerente"; + } + if (PaidBids + FreeBids <= 0) return "error|Puntate esaurite"; + + // Bidoo alterna pagate e gratis: qui si usano le gratis finché ce ne sono in proporzione. + var useFree = FreeBids > 0 && _rng.NextDouble() < (double)FreeBids / (PaidBids + FreeBids); + if (useFree) FreeBids--; else PaidBids--; + + AddBid(a, MyUsername, nowMs / 1000, auto: false, paid: !useFree); + var (paidHere, freeHere) = a.SpentByUser[MyUsername]; + _myBids.Add(new SimMyBid(auctionId, deadline, nowMs, true, "ok")); + StartCycle(a, nowMs / 1000); + return $"ok|{PaidBids}|{FreeBids}|{freeHere}|{paidHere}|0|{a.Id}|0|0"; + } + } + + public SimAuction? Find(string id) + { + lock (_sync) return Auctions.FirstOrDefault(a => a.Id == id); + } + + /// Esegue una lettura coerente del mondo. + public T Read(Func reader) + { + lock (_sync) + { + Tick(); + return reader(this); + } + } + + /// Solo per i test: un'asta nuova in corso, con scadenza fra s. + public SimAuction AddRunningAuction(int seconds = 10, int freq = 10, bool withOpponents = false) + { + lock (_sync) + { + var p = Products[0] with { Freq = freq }; + var a = NewAuction(p, NowUnix); + if (!withOpponents) a.Bidders.Clear(); + a.Bidders.Insert(0, new SimBidder { Name = "apri_asta", Profile = SimProfile.Beginner, MaxBids = 1 }); + AddBid(a, "apri_asta", NowUnix - 1, auto: false, paid: true); + a.Bidders[0].Quit = true; + a.ExpiryUnix = NowUnix + seconds; + Auctions.Add(a); + return a; + } + } +} diff --git a/Mimante/src/BidooBidBot/Simulator/SimulatedBidoo.cs b/Mimante/src/BidooBidBot/Simulator/SimulatedBidoo.cs new file mode 100644 index 0000000..3a65f27 --- /dev/null +++ b/Mimante/src/BidooBidBot/Simulator/SimulatedBidoo.cs @@ -0,0 +1,222 @@ +using System.Globalization; +using System.Net; +using System.Text; +using System.Text.Json; +using BidooBidBot.Bidoo; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting.Server; +using Microsoft.AspNetCore.Hosting.Server.Features; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +namespace BidooBidBot.Simulator; + +/// +/// Un Bidoo finto su una porta locale (specifica §6.8): risponde a data.php, +/// bid.php, get_auctions.php, get_auction_updates.php, +/// buy_bids.php, update_credits_status.php, check_auctions_won.php, alla +/// pagina principale e alle pagine delle aste con lo stesso formato del sito vero (i +/// test lo verificano con i parser veri). Serve a test d'integrazione, riscaldamento +/// all'avvio, schermate del README e alla modalità simulatore al primo avvio. +/// +public sealed class SimulatedBidoo : IAsyncDisposable +{ + private readonly WebApplication _app; + private readonly Timer _ticker; + + public SimWorld World { get; } + + /// L'indirizzo base, per esempio http://127.0.0.1:41733. + public string BaseUrl { get; private set; } = ""; + + private SimulatedBidoo(WebApplication app, SimWorld world) + { + _app = app; + World = world; + _ticker = new Timer(_ => { try { World.Tick(); } catch { } }, null, 50, 50); + } + + public static async Task StartAsync(SimWorld? world = null, int port = 0) + { + world ??= new SimWorld(); + var builder = WebApplication.CreateSlimBuilder(new WebApplicationOptions { Args = Array.Empty() }); + builder.Logging.ClearProviders(); + builder.WebHost.ConfigureKestrel(o => o.Listen(IPAddress.Loopback, port)); + var app = builder.Build(); + + var sim = new SimulatedBidoo(app, world); + sim.Map(app); + await app.StartAsync().ConfigureAwait(false); + + var addresses = app.Services.GetRequiredService().Features.Get()!.Addresses; + sim.BaseUrl = addresses.First().Replace("[::1]", "127.0.0.1", StringComparison.Ordinal).TrimEnd('/'); + return sim; + } + + /// I riferimenti del sito puntati sul simulatore. + public BidooReferences References(BidooReferences? baseRefs = null) + { + var refs = BidooReferences.Parse(JsonSerializer.Serialize(new { baseUrl = BaseUrl })); + if (baseRefs != null) + { + // Stesse espressioni del file dell'utente, indirizzo del simulatore. + refs = BidooReferences.Parse(JsonSerializer.Serialize(baseRefs, BidooReferences.JsonOptions)); + refs.BaseUrl = BaseUrl; + } + return refs; + } + + private static string It(double v) => v.ToString("0.00", CultureInfo.GetCultureInfo("it-IT")); + + private void Map(WebApplication app) + { + app.MapGet("/data.php", (HttpContext ctx) => + { + var q = ctx.Request.Query; + return Results.Text(q.ContainsKey("ALL") ? DataOne(q["ALL"].ToString()) : DataList(q["LISTID"].ToString()), "text/plain"); + }); + + app.MapGet("/bid.php", (HttpContext ctx) => Results.Text(World.MyBid(ctx.Request.Query["AID"].ToString()), "text/plain")); + + app.MapGet("/get_auctions.php", (HttpContext ctx) => + Results.Text(CatalogPage(ctx.Request.Query["tab"], ctx.Request.Query["tag"], Array.Empty(), first: true), "application/json")); + + app.MapPost("/get_auction_updates.php", async (HttpContext ctx) => + { + var form = await ctx.Request.ReadFormAsync().ConfigureAwait(false); + var view = form["view"].ToString().Split(',', StringSplitOptions.RemoveEmptyEntries); + return Results.Text(CatalogPage(form["tab"], form["tag"], view, first: false), "application/json"); + }); + + app.MapGet("/buy_bids.php", () => Results.Content(UserPage(), "text/html; charset=utf-8")); + app.MapGet("/update_credits_status.php", () => Results.Text(World.Read(w => (w.PaidBids + w.FreeBids).ToString(CultureInfo.InvariantCulture)), "text/plain")); + app.MapGet("/check_auctions_won.php", () => Results.Text(World.Read(w => w.WonToConfirm.ToString(CultureInfo.InvariantCulture)), "text/plain")); + app.MapGet("/", () => Results.Content(HomePage(), "text/html; charset=utf-8")); + app.MapGet("/auction.php", (HttpContext ctx) => Results.Content(AuctionPage(ctx.Request.Query["a"].ToString()), "text/html; charset=utf-8")); + app.MapGet("/favicon.ico", () => Results.Bytes(Array.Empty(), "image/x-icon")); + app.MapGet("/products/{file}", (string file) => Results.Text(ProductSvg(file), "image/svg+xml")); + app.MapGet("/login.php", () => Results.Content("
Simulatore: nessun accesso da fare
", "text/html")); + } + + // ── data.php ───────────────────────────────────────────────────────── + + private string DataOne(string id) => World.Read(w => + { + var now = w.NowUnix; + var a = w.Auctions.FirstOrDefault(x => x.Id == id); + if (a == null) return $"{now}*[]"; + + var sb = new StringBuilder(); + sb.Append(now).Append("*[").Append(a.Id).Append(';').Append(a.Status).Append(';').Append(a.ExpiryUnix).Append(';') + .Append(a.PriceCents).Append(';').Append(a.LastBidder).Append(';').Append(a.Started ? "1" : ""); + + if (a.Status == "OFF" && a.Started) + { + var (paid, free) = a.SpentByUser.GetValueOrDefault(a.LastBidder); + var span = a.History.Count > 1 ? a.History[^1].Unix - a.History[0].Unix : 0; + sb.Append(';').Append(span / 3600).Append("h ").Append(span % 3600 / 60).Append("m;|") + .Append(paid).Append('|').Append(free).Append("|0|0|0|0|"); + } + + sb.Append(','); + var first = true; + foreach (var b in Enumerable.Reverse(a.History).Take(50)) + { + if (!first) sb.Append('|'); + first = false; + sb.Append(b.PriceCents).Append(';').Append(b.User).Append(';').Append(b.Unix).Append(';').Append(b.Auto ? '3' : '1'); + } + sb.Append(']'); + return sb.ToString(); + }); + + private string DataList(string ids) => World.Read(w => + { + var now = w.NowUnix; + var set = ids.Split(',', StringSplitOptions.RemoveEmptyEntries).ToHashSet(StringComparer.Ordinal); + var parts = w.Auctions.Where(a => set.Contains(a.Id)) + .Select(a => $"{a.Id};{a.Status};{a.ExpiryUnix};{a.PriceCents};{a.LastBidder}"); + return $"{now}*({string.Join('#', parts)})"; + }); + + // ── Catalogo ───────────────────────────────────────────────────────── + + private string CatalogPage(string? tabText, string? tagText, IReadOnlyCollection view, bool first) => World.Read(w => + { + _ = int.TryParse(tabText, out var tab); + _ = int.TryParse(tagText, out var tag); + var seen = view.ToHashSet(StringComparer.Ordinal); + + var items = w.Auctions + .Where(a => a.Status != "OFF") + .Where(a => tab != 4 || a.CategoryTag == tag) + .OrderBy(a => a.ExpiryUnix) + .Where(a => !seen.Contains(a.Id)) + .Take(50) + .ToList(); + + var cards = items.Select(Card).ToList(); + var attributes = items.ToDictionary(a => a.Id, a => new Dictionary + { + ["data-url"] = a.Slug, ["data-freq"] = a.FreqSeconds, ["data-credit"] = 0, ["data-credit-value"] = 0, ["data-id-product"] = a.ProductId + }); + var ids = items.Select(a => long.Parse(a.Id, CultureInfo.InvariantCulture)).ToList(); + + var payload = first + ? new Dictionary { ["status"] = "200", ["content"] = cards, ["list"] = ids, ["auctions_attributes"] = attributes } + : new Dictionary { ["gc"] = Array.Empty(), ["list"] = ids, ["items"] = cards, ["attributes"] = attributes }; + return JsonSerializer.Serialize(payload); + }); + + private string Card(SimAuction a) => + $"
" + + $"" + + $"
{It(a.Value)} €
"; + + private static string HomePage() + { + var sb = new StringBuilder("Bidoo simulato"); + return sb.ToString(); + } + + private string UserPage() => World.Read(w => + "Acquista puntate - Bidoo
" + + $"{w.PaidBids + w.FreeBids} {w.ShopCredit.ToString("0.00", CultureInfo.InvariantCulture)}" + + "
Pagina simulata del conto, abbastanza lunga da essere riconosciuta come pagina vera.
"); + + private string AuctionPage(string slugOrId) => World.Read(w => + { + var a = w.Auctions.FirstOrDefault(x => x.Slug == slugOrId || x.Id == slugOrId || slugOrId.EndsWith("_" + x.Id, StringComparison.Ordinal)); + if (a == null) return "Asta non trovata - Bidoo"; + return "" + + $"{WebUtility.HtmlEncode(a.Name)} - Bidoo" + + $"" + + $"Valore: {It(a.Value)} €" + + $"
  • Spese di {(a.CategoryTag == 6 ? "transazione" : "spedizione")}: {It(a.Shipping)} €
  • " + + (a.CategoryTag == 6 ? "
  • Limiti di vincita: 1 ogni 30 giorni
  • " : "") + + $"
    "; + }); + + private static string ProductSvg(string file) + { + var product = SimWorld.Products.FirstOrDefault(p => file.Contains(p.Id.ToString(CultureInfo.InvariantCulture), StringComparison.Ordinal)); + var label = WebUtility.HtmlEncode(product?.Name ?? "Prodotto"); + return $"" + + $"{label}"; + } + + public async ValueTask DisposeAsync() + { + await _ticker.DisposeAsync().ConfigureAwait(false); + await _app.StopAsync().ConfigureAwait(false); + await _app.DisposeAsync().ConfigureAwait(false); + } +} diff --git a/Mimante/tests/BidooBidBot.Tests/EngineTests.cs b/Mimante/tests/BidooBidBot.Tests/EngineTests.cs new file mode 100644 index 0000000..c9a13c8 --- /dev/null +++ b/Mimante/tests/BidooBidBot.Tests/EngineTests.cs @@ -0,0 +1,378 @@ +using System.Diagnostics; +using BidooBidBot.Bidoo; +using BidooBidBot.Engine; +using BidooBidBot.Logging; +using BidooBidBot.Net; +using BidooBidBot.Settings; +using BidooBidBot.Simulator; +using Xunit; + +namespace BidooBidBot.Tests; + +/// L'orologio del server: l'errore residuo resta piccolo e non cresce (portati dal legacy). +public class ServerClockTests +{ + private static readonly long Freq = Stopwatch.Frequency; + + [Fact] + public void Serve_piu_di_un_campione_prima_di_fidarsi() + { + var clock = new ServerClock(); + clock.AddSample(1000, Freq * 1000, 0); + clock.AddSample(1001, Freq * 1001, 0); + Assert.False(clock.IsSynced); + clock.AddSample(1002, Freq * 1002, 0); + Assert.True(clock.IsSynced); + Assert.Equal(3, clock.SampleCount); + } + + [Fact] + public void La_media_segue_la_finestra_e_dimentica_il_passato() + { + var clock = new ServerClock(); + for (var i = 0; i < 256; i++) clock.AddSample(1000 + i, Freq * (1000 + i), 500); + Assert.Equal(500, clock.AverageLatencyMs, 3); + for (var i = 0; i < 256; i++) clock.AddSample(2000 + i, Freq * (2000 + i), 50); + Assert.Equal(50, clock.AverageLatencyMs, 3); + Assert.Equal(256, clock.SampleCount); + } + + [Fact] + public void Ignora_i_campioni_privi_di_senso() + { + var clock = new ServerClock(); + clock.AddSample(0, Freq, 0); + clock.AddSample(-5, Freq, 0); + clock.AddSample(1000, 0, 0); + Assert.Equal(0, clock.SampleCount); + } + + [Fact] + public void Con_zero_latenza_ricostruisce_esattamente_l_origine() + { + const long origin = 500; + var clock = new ServerClock(); + for (var sec = 1000; sec < 1010; sec++) clock.AddSample(sec, origin + sec * Freq, 0); + Assert.Equal(origin, clock.Origin); + Assert.Equal(origin + 2000 * Freq, clock.ToLocalTicks(2000)); + } + + [Fact] + public void Sottrae_meta_del_tempo_di_andata_e_ritorno() + { + const int latency = 100; + var half = (long)(latency / 2.0 / 1000.0 * Freq); + var clock = new ServerClock(); + for (var sec = 1000; sec < 1005; sec++) clock.AddSample(sec, sec * Freq + half, latency); + Assert.Equal(0, clock.Origin); + } + + [Fact] + public void Il_filtro_al_minimo_scarta_le_risposte_lente() + { + const long origin = 1_000_000; + var clock = new ServerClock(); + clock.AddSample(1000, origin + 1000 * Freq, 0); + for (var sec = 1001; sec < 1010; sec++) clock.AddSample(sec, origin + sec * Freq + Freq / 2, 0); + Assert.Equal(origin, clock.Origin); + } + + [Fact] + public void L_errore_resta_entro_il_millisecondo_dal_campione_migliore() + { + const long origin = 5_000_000; + var clock = new ServerClock(); + var delays = new long[] { 3, 17, 5, 40, 9, 22, 1, 31 }; + for (var i = 0; i < delays.Length; i++) + { + var sec = 2000 + i; + clock.AddSample(sec, origin + sec * Freq + delays[i] * Freq / 1000, 0); + } + Assert.True(clock.Origin <= origin + Freq / 1000); + } + + [Fact] + public void La_dispersione_misura_la_finestra_dei_campioni() + { + var clock = new ServerClock(); + clock.AddSample(1000, 1000 * Freq, 0); + clock.AddSample(1001, 1001 * Freq + Freq / 100, 0); + clock.AddSample(1002, 1002 * Freq, 0); + Assert.InRange(clock.SpreadMs, 9.0, 11.0); + } + + [Fact] + public void Reset_e_finestra_scorrevole() + { + var clock = new ServerClock(); + for (var sec = 1000; sec < 1400; sec++) clock.AddSample(sec, sec * Freq, 0); + Assert.Equal(256, clock.SampleCount); + clock.Reset(); + Assert.False(clock.IsSynced); + Assert.Equal(0, clock.Origin); + Assert.Equal(0, clock.AverageLatencyMs); + } +} + +public class PollCadenceTests +{ + private static readonly AppSettings S = new(); + private static readonly BidooReferences R = BidooReferences.Default; + + [Theory] + [InlineData(RunMode.Watch, 120_000, 2000)] + [InlineData(RunMode.Watch, 30_000, 900)] + [InlineData(RunMode.Watch, 8_000, 400)] + [InlineData(RunMode.Watch, 3_000, 400)] // la finestra critica vale solo in Attiva + [InlineData(RunMode.Active, 3_000, 220)] + [InlineData(RunMode.Active, 8_000, 400)] + public void La_cadenza_si_stringe_verso_la_scadenza(RunMode mode, double ms, int expected) + { + Assert.Equal(expected, PollCadence.NextDelayMs(mode, AuctionStatus.Running, ms, S, R)); + } + + [Fact] + public void Un_asta_programmata_non_si_interroga_di_continuo_ma_non_si_perde_l_apertura() + { + Assert.Equal(1_200_000, PollCadence.NextDelayMs(RunMode.Watch, AuctionStatus.Scheduled, 3 * 3_600_000, S, R)); + Assert.Equal(120_000, PollCadence.NextDelayMs(RunMode.Watch, AuctionStatus.Scheduled, 30 * 60_000, S, R)); + Assert.Equal(30_000, PollCadence.NextDelayMs(RunMode.Watch, AuctionStatus.Scheduled, 8 * 60_000, S, R)); + + // A 130 s dall'apertura: al massimo fino al risveglio (120 s prima), cioè 10 s. + Assert.Equal(10_000, PollCadence.NextDelayMs(RunMode.Watch, AuctionStatus.Scheduled, 130_000, S, R)); + + // Dentro il risveglio: cadenza normale. + Assert.Equal(900, PollCadence.NextDelayMs(RunMode.Watch, AuctionStatus.Pending, 50_000, S, R)); + } + + [Fact] + public void Un_asta_sospesa_di_notte_si_guarda_ogni_30_secondi() + { + Assert.Equal(30_000, PollCadence.NextDelayMs(RunMode.Active, AuctionStatus.Paused, 8 * 3_600_000, S, R)); + } +} + +public class PrecisionWaitTests +{ + [Fact] + public void L_attesa_arriva_puntuale() + { + var errors = new List(); + for (var i = 0; i < 25; i++) + { + var target = Stopwatch.GetTimestamp() + PrecisionWait.MsToTicks(30 + i % 7); + PrecisionWait.Until(target, CancellationToken.None); + errors.Add(-PrecisionWait.MsUntil(target)); + } + + errors.Sort(); + // Mai in anticipo; in ritardo di poco. Soglia larga: in CI i core sono condivisi. + Assert.All(errors, e => Assert.True(e >= 0)); + Assert.True(errors.Average() < 3, $"errore medio {errors.Average():F3} ms"); + Assert.True(errors[^2] < 15, $"errore quasi massimo {errors[^2]:F3} ms"); + } +} + +public class AuctionLogTests +{ + [Fact] + public void Una_decisione_ripetuta_e_una_riga_sola() + { + var log = new AuctionLog(); + log.AddDecision("ev-negativo", "Non punto: valore atteso -0,10 EUR"); + log.AddDecision("ev-negativo", "Non punto: valore atteso -0,12 EUR"); + log.AddDecision("ev-negativo", "Non punto: valore atteso -0,08 EUR"); + + var rows = log.Snapshot(); + Assert.Single(rows); + Assert.Equal(3, rows[0].Count); + Assert.Contains("-0,08", rows[0].Message); + + log.AddDecision("punta", "Punto a 1,20 EUR"); + log.AddDecision("ev-negativo", "Non punto: valore atteso -0,20 EUR"); + Assert.Equal(3, log.Snapshot().Count); + } + + [Fact] + public void Le_righe_passano_dal_pulitore_e_le_uguali_si_contano() + { + var log = new AuctionLog(); + var sunk = new List(); + log.Sink = sunk.Add; + + log.Add("Puntata ✓ riuscita → 1,20 €", LogLevel.Success, AuctionLogCategory.Bid); + log.Add("Ciclo scaduto", LogLevel.Debug, AuctionLogCategory.Timing); + log.Add("Ciclo scaduto", LogLevel.Debug, AuctionLogCategory.Timing); + + var rows = log.Snapshot(); + Assert.Equal("Puntata riuscita -> 1,20 EUR", rows[0].Message); + Assert.Equal(2, rows[1].Count); + Assert.Equal(2, sunk.Count); // sul file solo le righe nuove + } +} + +/// Il simulatore risponde con lo stesso formato del sito: lo leggono i parser veri. +public class SimulatorTests +{ + [Fact] + public async Task Le_risposte_del_simulatore_si_leggono_con_i_parser_veri() + { + await using var sim = await SimulatedBidoo.StartAsync(new SimWorld(seed: 7)); + var refs = sim.References(); + using var transport = new BidooTransport(() => refs, 0); + using var lane = new BidLane(transport, () => refs, keepWarm: false); + var api = new BidooApi(transport, lane, () => refs) { Username = "utente_demo" }; + + var running = sim.World.Read(w => w.Auctions.First(a => a.Started && a.Status == "ON")); + var poll = await api.PollAsync(running.Id, null, 50, CancellationToken.None); + Assert.NotNull(poll.State); + Assert.Equal(AuctionStatus.Running, poll.State!.Status); + Assert.Equal(running.PriceCents / 100.0, poll.State.Price, 3); + Assert.NotNull(poll.State.RecentBidsHistory); + Assert.Equal(running.LastBidder, poll.State.RecentBidsHistory![0].Username); + + var scheduled = sim.World.Read(w => w.Auctions.First(a => !a.Started)); + var sched = await api.PollAsync(scheduled.Id, null, 50, CancellationToken.None); + Assert.Equal(AuctionStatus.Scheduled, sched.State!.Status); + + var account = await api.GetUserInfoAsync(CancellationToken.None); + Assert.Equal("utente_demo", account!.Username); + Assert.Equal(1407, account.RemainingBids); + Assert.Equal(1, await api.GetAuctionsWonAsync(CancellationToken.None)); + + var page = await api.GetAuctionPageAsync(running.Id, null, CancellationToken.None); + Assert.Equal(running.Name, page!.Name); + Assert.Equal(running.Value, page.BuyNowPrice); + + var catalog = new CatalogClient(transport, () => refs, null); + var categories = await catalog.GetCategoriesAsync(true, CancellationToken.None); + Assert.Contains(categories, c => c.DisplayName == "Buoni" && c.TagId == 6); + var all = await catalog.GetAllAuctionsAsync(CatalogCategory.AllAuctions, 500, 0, CancellationToken.None); + Assert.Equal(sim.World.Read(w => w.Auctions.Count(a => a.Status != "OFF")), all.Count); + await catalog.UpdateStatesAsync(all, CancellationToken.None); + Assert.Contains(all, a => a.CurrentPrice > 0.01m); + } + + [Fact] + public async Task Un_asta_conclusa_porta_le_puntate_del_vincitore() + { + var world = new SimWorld(seed: 3, populate: false); + await using var sim = await SimulatedBidoo.StartAsync(world); + var a = world.AddRunningAuction(seconds: 1); + await Task.Delay(1600); + + var refs = sim.References(); + using var transport = new BidooTransport(() => refs, 0); + using var lane = new BidLane(transport, () => refs, keepWarm: false); + var poll = await new BidooApi(transport, lane, () => refs).PollAsync(a.Id, null, 50, CancellationToken.None); + + Assert.Equal(AuctionStatus.EndedLost, poll.State!.Status); + Assert.Equal(1, poll.State.WinnerBidsTotal); + } + + [Fact] + public async Task La_mia_puntata_da_la_risposta_di_bid_php() + { + var world = new SimWorld(seed: 3, populate: false); + await using var sim = await SimulatedBidoo.StartAsync(world); + var a = world.AddRunningAuction(seconds: 8); + + var refs = sim.References(); + using var transport = new BidooTransport(() => refs, 0); + using var lane = new BidLane(transport, () => refs, keepWarm: false); + var api = new BidooApi(transport, lane, () => refs); + + var bid = await api.PlaceBidAsync(a.Id, null, null, 0, CancellationToken.None); + Assert.True(bid.Success, bid.Error); + Assert.Equal(1406, bid.Response.Remaining); + Assert.Equal(1, bid.Response.UsedOnAuction); + + var again = await api.PlaceBidAsync(a.Id, null, null, 0, CancellationToken.None); + Assert.False(again.Success); + Assert.Contains("miglior offerente", again.Error); + } +} + +/// +/// Il motore vero contro il simulatore: una sola puntata per ciclo, partita all'anticipo +/// voluto (misurato dal «server») e con l'attesa di precisione che sbaglia di poco. +/// +public class RunnerAgainstSimulatorTests +{ + private sealed class Host : IAuctionRunnerHost + { + private readonly BidooApi _api; + public readonly ServerClock Clock = new(); + public readonly List WaitErrors = new(); + public int Evaluations; + + public Host(BidooApi api, BidooReferences refs) + { + _api = api; + References = refs; + } + + public AppSettings Settings { get; } = new(); + public BidooReferences References { get; } + public int Lead { get; set; } = 400; + + public async Task PollAsync(AuctionInfo auction, CancellationToken ct) => + (await _api.PollAsync(auction.Id, null, 50, ct)).State; + + public void ApplySnapshot(AuctionInfo auction, AuctionState s) + { + Clock.AddSample(s.ServerUnixSeconds, s.ReceivedTicks, s.PollingLatencyMs); + if (s.ExpiryUnixSeconds > 0 && Clock.IsSynced) auction.DeadlineTicks = Clock.ToLocalTicks(s.ExpiryUnixSeconds); + auction.LastState = s; + if (s.IsTerminal) auction.Outcome = s.Status == AuctionStatus.EndedWon ? "won" : "lost"; + } + + public bool IsFinished(AuctionInfo auction) => auction.IsFinished; + public bool IsShadow(AuctionInfo auction) => false; + public int EffectiveLeadMs(AuctionInfo auction) => Lead; + + public bool EvaluateBid(AuctionInfo auction, AuctionState state, bool shadow) + { + Evaluations++; + return true; + } + + public void FireBid(AuctionInfo auction, AuctionState state, int leadMs, long fireTicks) + { + lock (WaitErrors) WaitErrors.Add((Stopwatch.GetTimestamp() - fireTicks) * 1000.0 / Stopwatch.Frequency); + _api.PlaceBidAsync(auction.Id, null, null, 0, CancellationToken.None).GetAwaiter().GetResult(); + } + } + + [Fact] + public async Task Il_cecchino_punta_una_volta_per_ciclo_prima_della_scadenza() + { + var world = new SimWorld(seed: 11, populate: false); + await using var sim = await SimulatedBidoo.StartAsync(world); + var target = world.AddRunningAuction(seconds: 6, freq: 4); + + var refs = sim.References(); + using var transport = new BidooTransport(() => refs, 0); + using var lane = new BidLane(transport, () => refs, keepWarm: false); + var api = new BidooApi(transport, lane, () => refs) { Username = world.MyUsername }; + var host = new Host(api, refs); + + var auction = new AuctionInfo(target.Id) { Name = target.Name, Mode = RunMode.Active }; + var runner = new AuctionRunner(auction, host); + runner.Start(); + + // Nessun avversario: la nostra puntata resta l'ultima e l'asta chiude vinta. + var deadline = DateTime.UtcNow.AddSeconds(20); + while (!auction.IsFinished && DateTime.UtcNow < deadline) await Task.Delay(100); + await runner.StopAsync(); + + var mine = world.MyBids.Where(b => b.AuctionId == target.Id).ToList(); + Assert.Equal("won", auction.Outcome); + Assert.Single(mine, b => b.Accepted); + + var bid = mine.First(b => b.Accepted); + // Arrivata prima della scadenza, non prima del doppio dell'anticipo voluto. + Assert.InRange(bid.LeadMs, 1, host.Lead * 2 + 1000); + Assert.All(host.WaitErrors, e => Assert.InRange(e, 0, 5)); + } +}