]+id=\"divAsta(\\d+)\"",
+ "catalogDataUrl": "data-url=\"([^\"]+)\"",
+ "catalogDataFreq": "data-freq=\"(\\d+)\"",
+ "catalogDataCredit": "data-credit=\"(\\d+)\"",
+ "catalogDataCreditValue": "data-credit-value=\"(\\d+)\"",
+ "catalogDataProduct": "data-id-product=\"(\\d+)\"",
+ "catalogImage": "
![]()
]+src=\"(https?://[^\"]+/products/[^\"]+)\"",
+ "catalogName": "
]+class=\"name[^\"]*\"[^>]*>([^<]+)",
+ "catalogBuyNow": "buy-rapid-now[^>]*>[\\s\\S]{0,400}?([0-9]{1,3}(?:\\.[0-9]{3})+(?:,[0-9]{1,2})?|[0-9]+(?:[,.][0-9]{1,2})?)\\s*(?:€|€|€)",
+ "catalogManualOnlyMarker": "bi-noauto",
+ "catalogCategory": "javascript:selectBids\\(4,\\s*true,\\s*false,\\s*(\\d+)\\);\\s*\"\\s+data-tab=\"4\"\\s+data-slug=\"([^\"]*)\"\\s+data-tag=\"\\d+\">
]*>([^<]+)",
+
+ "auctionIdInPath": [ "/asta/[^/]*-(\\d{6,})", "/asta/(\\d{6,})" ],
+ "auctionIdInQuery": "[?&]a=([^]+)",
+ "auctionIdDigits": "(\\d{6,})$"
+ },
+
+ "timing": {
+ // I controlli di strategia partono questo tanto prima dell'istante di fuoco.
+ "preCheckMs": 60,
+ // Sotto questi secondi sul cronometro, in Attiva, il polling passa alla cadenza critica.
+ "criticalWindowS": 4,
+ // Un'asta ON senza vincitore con il cronometro oltre questa soglia è programmata.
+ "scheduledIfTimerAboveS": 1800
+ },
+
+ "limits": {
+ "maxConcurrency": 24,
+ "bidLaneConnections": 3,
+ "bidLaneKeepAliveSeconds": 20,
+ "bidTimeoutMs": 3000,
+ "requestTimeoutMs": 8000,
+ "brakeMinMs": 1000,
+ "brakeMaxMs": 8000,
+ "historyMaxEntries": 50,
+ "bulkPricesChunk": 60,
+ "catalogPageSize": 50,
+ "catalogMaxPages": 200
+ },
+
+ "parsing": {
+ "coreSeparator": ";",
+ "historySeparator": "|",
+ "coreHistorySeparator": ",",
+ "listSeparator": "#",
+ "bidTypeManual": "1",
+ "bidTypeAuto": "3",
+ "statusOn": "ON",
+ "statusOff": "OFF",
+ "statusStop": "STOP"
+ }
+}
diff --git a/Mimante/src/BidooBidBot/Net/BidLane.cs b/Mimante/src/BidooBidBot/Net/BidLane.cs
new file mode 100644
index 0000000..8dc133f
--- /dev/null
+++ b/Mimante/src/BidooBidBot/Net/BidLane.cs
@@ -0,0 +1,85 @@
+using System.Net;
+using BidooBidBot.Bidoo;
+
+namespace BidooBidBot.Net;
+
+///
+/// La corsia dedicata alle puntate (specifica §6.4): un handler tutto suo con poche
+/// connessioni (3) tenute calde da una richiesta leggera ogni 20 s, nessun limitatore,
+/// nessuna coda, tempo massimo 3 s. Così una puntata parte sempre su una connessione già
+/// aperta e non aspetta mai dietro al polling di altre aste.
+///
+/// Se la corsia fallisce per un errore di rete, chi chiama può ritentare una sola
+/// volta sul pool normale nello stesso ciclo, se c'è ancora tempo.
+///
+public sealed class BidLane : IDisposable
+{
+ private readonly BidooTransport _transport;
+ private readonly Func
_refs;
+ private readonly HttpClient _client;
+ private readonly Timer? _keepAlive;
+ private long _bids;
+ private long _failures;
+
+ public BidLane(BidooTransport transport, Func refs, HttpMessageHandler? handler = null, bool keepWarm = true)
+ {
+ _transport = transport;
+ _refs = refs;
+ var limits = refs().Limits;
+
+ var h = handler ?? BidooTransport.CreateHandler(Math.Max(1, limits.BidLaneConnections));
+ _client = new HttpClient(h, disposeHandler: handler == null)
+ {
+ Timeout = TimeSpan.FromMilliseconds(Math.Max(500, limits.BidTimeoutMs)),
+ DefaultRequestVersion = HttpVersion.Version20,
+ DefaultVersionPolicy = HttpVersionPolicy.RequestVersionOrLower
+ };
+
+ if (keepWarm)
+ {
+ var period = TimeSpan.FromSeconds(Math.Max(5, limits.BidLaneKeepAliveSeconds));
+ _keepAlive = new Timer(_ => _ = WarmAsync(), null, TimeSpan.FromSeconds(1), period);
+ }
+ }
+
+ public long Bids => Interlocked.Read(ref _bids);
+ public long Failures => Interlocked.Read(ref _failures);
+
+ /// Latenze delle puntate (andata e ritorno di bid.php).
+ public LatencyStats BidLatency { get; } = new(300);
+
+ ///
+ /// Invia la puntata sulla corsia. La richiesta ha le stesse intestazioni del trasporto
+ /// (cookie, User-Agent), più Origin e Referer alla pagina dell'asta.
+ ///
+ public async Task SendBidAsync(string url, string referer, CancellationToken ct)
+ {
+ var request = _transport.BuildGet(url, referer);
+ request.Headers.TryAddWithoutValidation("Origin", _refs().BaseUrl);
+
+ Interlocked.Increment(ref _bids);
+ var outcome = await _transport.ExecuteAsync(_client, request, ct).ConfigureAwait(false);
+ if (outcome.IsNetworkError) Interlocked.Increment(ref _failures);
+ else BidLatency.Add(outcome.LatencyMs);
+ return outcome;
+ }
+
+ /// Tiene aperte le connessioni della corsia con una richiesta leggera.
+ public async Task WarmAsync()
+ {
+ try
+ {
+ var refs = _refs();
+ var tasks = Enumerable.Range(0, Math.Max(1, refs.Limits.BidLaneConnections)).Select(_ =>
+ _transport.ExecuteAsync(_client, _transport.BuildGet(refs.Url(refs.Endpoints.WarmUp), ajax: false), CancellationToken.None));
+ await Task.WhenAll(tasks).ConfigureAwait(false);
+ }
+ catch { /* riscaldamento facoltativo */ }
+ }
+
+ public void Dispose()
+ {
+ _keepAlive?.Dispose();
+ _client.Dispose();
+ }
+}
diff --git a/Mimante/src/BidooBidBot/Net/BidooTransport.cs b/Mimante/src/BidooBidBot/Net/BidooTransport.cs
new file mode 100644
index 0000000..03890ae
--- /dev/null
+++ b/Mimante/src/BidooBidBot/Net/BidooTransport.cs
@@ -0,0 +1,332 @@
+using System.Diagnostics;
+using System.Net;
+using System.Net.Security;
+using System.Text;
+using BidooBidBot.Bidoo;
+
+namespace BidooBidBot.Net;
+
+///
+/// Trasporto HTTP verso Bidoo, dimensionato per un flusso continuo di richieste
+/// (specifica §6.4, portato da Net/BidooHttpClient del legacy).
+///
+///
+/// - Un solo con pool ampio e connessioni calde,
+/// HTTP/2 con ripiego, decompressione automatica, cookie a mano.
+/// - User-Agent: lo stesso del browser dell'accesso assistito, salvato con la sessione.
+/// - Token bucket (40 richieste/s di fabbrica) con riserva per il polling, semaforo di
+/// concorrenza; le richieste saltano entrambi.
+/// - Freno del server: su 429/503 si aspetta 1 s, poi il doppio fino a 8 s; si
+/// rilascia alla prima risposta buona. Le puntate non passano dal freno.
+///
+///
+public sealed class BidooTransport : IDisposable
+{
+ private readonly Func _refs;
+ private readonly HttpMessageHandler _handler;
+ private readonly HttpClient _client;
+ private readonly SemaphoreSlim _concurrency;
+ private readonly TokenBucket _limiter;
+
+ private volatile string _cookie = "";
+ private volatile string _sessionUserAgent = "";
+
+ private long _sent;
+ private long _failed;
+ private long _brakes;
+
+ private long _brakeUntil;
+ private int _brakeMs;
+
+ public BidooTransport(Func refs, double requestsPerSecond, HttpMessageHandler? handler = null)
+ {
+ _refs = refs;
+ var limits = refs().Limits;
+ _brakeMs = limits.BrakeMinMs;
+
+ _handler = handler ?? CreateHandler(64);
+ _client = new HttpClient(_handler, disposeHandler: handler == null)
+ {
+ Timeout = TimeSpan.FromMilliseconds(Math.Max(1000, limits.RequestTimeoutMs)),
+ DefaultRequestVersion = HttpVersion.Version20,
+ DefaultVersionPolicy = HttpVersionPolicy.RequestVersionOrLower
+ };
+ _client.DefaultRequestHeaders.ConnectionClose = false;
+
+ _concurrency = new SemaphoreSlim(Math.Max(1, limits.MaxConcurrency), Math.Max(1, limits.MaxConcurrency));
+ _limiter = new TokenBucket(requestsPerSecond);
+ }
+
+ /// Un handler come serve a Bidoo: pool caldo, HTTP/2, cookie gestiti a mano.
+ public static SocketsHttpHandler CreateHandler(int maxConnections) => new()
+ {
+ UseCookies = false,
+ UseProxy = false,
+ AutomaticDecompression = DecompressionMethods.All,
+ // Bidoo risponde 302 su diverse pagine: i redirect sono sulla stessa origine e
+ // l'intestazione Cookie scritta a mano resta.
+ AllowAutoRedirect = true,
+ MaxAutomaticRedirections = 5,
+ MaxConnectionsPerServer = maxConnections,
+ PooledConnectionLifetime = TimeSpan.FromMinutes(10),
+ PooledConnectionIdleTimeout = TimeSpan.FromMinutes(2),
+ ConnectTimeout = TimeSpan.FromSeconds(5),
+ EnableMultipleHttp2Connections = true,
+ ResponseDrainTimeout = TimeSpan.FromSeconds(2),
+ SslOptions = new SslClientAuthenticationOptions
+ {
+ ApplicationProtocols = new List { SslApplicationProtocol.Http2, SslApplicationProtocol.Http11 }
+ }
+ };
+
+ public long RequestsSent => Interlocked.Read(ref _sent);
+ public long RequestsFailed => Interlocked.Read(ref _failed);
+ public long Brakes => Interlocked.Read(ref _brakes);
+
+ /// Latenze delle richieste di polling andate a buon fine.
+ public LatencyStats PollLatency { get; } = new(300);
+
+ public string Cookie => _cookie;
+ public bool HasCookie => _cookie.Length > 0;
+ public string UserAgent => _refs().EffectiveUserAgent(_sessionUserAgent);
+
+ /// Scatta quando il server ha rinnovato un cookie della sessione (Set-Cookie).
+ public event Action? CookieChanged;
+
+ public void SetSession(string? cookie, string? userAgent)
+ {
+ _cookie = cookie?.Trim() ?? "";
+ _sessionUserAgent = userAgent?.Trim() ?? "";
+ }
+
+ /// Limiti di ritmo a caldo, senza ricreare il trasporto.
+ public void Configure(double requestsPerSecond) => _limiter.SetRate(requestsPerSecond);
+
+ /// Millisecondi di freno ancora da scontare. Zero quando si va liberi.
+ public int BrakeRemainingMs
+ {
+ get
+ {
+ var left = (Interlocked.Read(ref _brakeUntil) - Stopwatch.GetTimestamp()) * 1000 / Stopwatch.Frequency;
+ return left > 0 ? (int)left : 0;
+ }
+ }
+
+ private void Brake()
+ {
+ var limits = _refs().Limits;
+ var duration = Volatile.Read(ref _brakeMs);
+ Interlocked.Exchange(ref _brakeUntil, Stopwatch.GetTimestamp() + duration * Stopwatch.Frequency / 1000);
+ Volatile.Write(ref _brakeMs, Math.Min(limits.BrakeMaxMs, duration * 2));
+ Interlocked.Increment(ref _brakes);
+ }
+
+ private void ReleaseBrake() => Volatile.Write(ref _brakeMs, _refs().Limits.BrakeMinMs);
+
+ /// Una GET completa di cookie, User-Agent e intestazioni di contesto.
+ public HttpRequestMessage BuildGet(string url, string? referer = null, bool ajax = true)
+ {
+ var refs = _refs();
+ var request = new HttpRequestMessage(HttpMethod.Get, url);
+ AddCommonHeaders(request, refs, referer);
+
+ var h = request.Headers;
+ if (ajax)
+ {
+ h.TryAddWithoutValidation("Accept", refs.Headers.AjaxAccept);
+ h.TryAddWithoutValidation("X-Requested-With", refs.Headers.XRequestedWith);
+ h.TryAddWithoutValidation("Sec-Fetch-Dest", "empty");
+ h.TryAddWithoutValidation("Sec-Fetch-Mode", "cors");
+ h.TryAddWithoutValidation("Sec-Fetch-Site", "same-origin");
+ }
+ else
+ {
+ h.TryAddWithoutValidation("Accept", refs.Headers.DocumentAccept);
+ h.TryAddWithoutValidation("Sec-Fetch-Dest", "document");
+ h.TryAddWithoutValidation("Sec-Fetch-Mode", "navigate");
+ h.TryAddWithoutValidation("Sec-Fetch-Site", "same-origin");
+ }
+ return request;
+ }
+
+ /// Una POST con corpo già codificato (application/x-www-form-urlencoded).
+ public HttpRequestMessage BuildPost(string url, string formBody, string? referer = null)
+ {
+ var refs = _refs();
+ var request = new HttpRequestMessage(HttpMethod.Post, url)
+ {
+ Content = new StringContent(formBody, Encoding.UTF8, "application/x-www-form-urlencoded")
+ };
+ AddCommonHeaders(request, refs, referer);
+ var h = request.Headers;
+ h.TryAddWithoutValidation("Accept", refs.Headers.AjaxAccept);
+ h.TryAddWithoutValidation("X-Requested-With", refs.Headers.XRequestedWith);
+ h.TryAddWithoutValidation("Origin", refs.BaseUrl);
+ h.TryAddWithoutValidation("Sec-Fetch-Dest", "empty");
+ h.TryAddWithoutValidation("Sec-Fetch-Mode", "cors");
+ h.TryAddWithoutValidation("Sec-Fetch-Site", "same-origin");
+ return request;
+ }
+
+ private void AddCommonHeaders(HttpRequestMessage request, BidooReferences refs, string? referer)
+ {
+ var h = request.Headers;
+ h.TryAddWithoutValidation("User-Agent", refs.EffectiveUserAgent(_sessionUserAgent));
+ h.TryAddWithoutValidation("Accept-Language", refs.Headers.AcceptLanguage);
+ var cookie = _cookie;
+ if (cookie.Length > 0) h.TryAddWithoutValidation("Cookie", cookie);
+ h.TryAddWithoutValidation("Referer", referer ?? refs.BaseUrl.TrimEnd('/') + "/");
+ }
+
+ /// Invia rispettando ritmo, freno e concorrenza (salvo le Critical).
+ public async Task SendAsync(HttpRequestMessage request, RequestPriority priority, CancellationToken ct)
+ {
+ var critical = priority == RequestPriority.Critical;
+
+ if (!critical)
+ {
+ var brake = BrakeRemainingMs;
+ if (brake > 0) await Task.Delay(brake, ct).ConfigureAwait(false);
+ await _limiter.WaitAsync(priority == RequestPriority.Background, ct).ConfigureAwait(false);
+ await _concurrency.WaitAsync(ct).ConfigureAwait(false);
+ }
+
+ try
+ {
+ var outcome = await ExecuteAsync(_client, request, ct).ConfigureAwait(false);
+ Interlocked.Increment(ref _sent);
+ if (!outcome.Success) Interlocked.Increment(ref _failed);
+
+ if (outcome.StatusCode is 429 or 503) Brake();
+ else if (outcome.Success) ReleaseBrake();
+
+ if (outcome.Success && priority == RequestPriority.Normal) PollLatency.Add(outcome.LatencyMs);
+ return outcome;
+ }
+ finally
+ {
+ if (!critical) _concurrency.Release();
+ }
+ }
+
+ ///
+ /// La richiesta vera e propria: corpo, stato, latenza misurata con Stopwatch, cookie
+ /// rinnovati dal server. Usata anche dalla corsia delle puntate.
+ ///
+ public async Task ExecuteAsync(HttpClient client, HttpRequestMessage request, CancellationToken ct)
+ {
+ var start = Stopwatch.GetTimestamp();
+ try
+ {
+ using var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, ct).ConfigureAwait(false);
+ var body = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
+ var received = Stopwatch.GetTimestamp();
+
+ if (response.Headers.TryGetValues("Set-Cookie", out var setCookies)) MergeCookies(setCookies);
+
+ return new HttpOutcome
+ {
+ Success = response.IsSuccessStatusCode,
+ StatusCode = (int)response.StatusCode,
+ Body = body,
+ LatencyMs = (int)((received - start) * 1000 / Stopwatch.Frequency),
+ SentTicks = start,
+ ReceivedTicks = received
+ };
+ }
+ catch (OperationCanceledException) when (ct.IsCancellationRequested)
+ {
+ throw;
+ }
+ catch (Exception ex)
+ {
+ return HttpOutcome.Failure(ex is TaskCanceledException ? "nessuna risposta nel tempo massimo" : ex.Message, start);
+ }
+ finally
+ {
+ request.Dispose();
+ }
+ }
+
+ ///
+ /// Il server rinnova un cookie: lo si aggiorna nella stringa della sessione, come farebbe
+ /// il browser. I cookie cancellati (valore vuoto o scaduti) si tolgono.
+ ///
+ private void MergeCookies(IEnumerable setCookies)
+ {
+ var current = _cookie;
+ if (current.Length == 0) return;
+
+ var merged = CookieText.Merge(current, setCookies);
+ if (merged == current) return;
+ _cookie = merged;
+ try { CookieChanged?.Invoke(merged); } catch { /* chi salva non deve fermare la richiesta */ }
+ }
+
+ /// Apre in anticipo qualche connessione, così le prime richieste non pagano TCP+TLS.
+ public async Task WarmUpAsync(CancellationToken ct = default)
+ {
+ var refs = _refs();
+ var tasks = Enumerable.Range(0, 4)
+ .Select(_ => SendAsync(BuildGet(refs.Url(refs.Endpoints.WarmUp), ajax: false), RequestPriority.Background, ct))
+ .ToArray();
+ try { await Task.WhenAll(tasks).ConfigureAwait(false); }
+ catch { /* il riscaldamento è facoltativo */ }
+ }
+
+ public void Dispose()
+ {
+ _client.Dispose();
+ _concurrency.Dispose();
+ }
+}
+
+/// Operazioni sulla stringa dei cookie («a=1; b=2»). Pura, sotto test.
+public static class CookieText
+{
+ public static List<(string Name, string Value)> Split(string? cookie)
+ {
+ var list = new List<(string, string)>();
+ foreach (var part in (cookie ?? "").Split(';'))
+ {
+ var p = part.Trim();
+ var eq = p.IndexOf('=');
+ if (eq <= 0) continue;
+ list.Add((p[..eq].Trim(), p[(eq + 1)..].Trim()));
+ }
+ return list;
+ }
+
+ public static string Join(IEnumerable<(string Name, string Value)> cookies) =>
+ string.Join("; ", cookies.Select(c => $"{c.Name}={c.Value}"));
+
+ public static bool Contains(string? cookie, string name) =>
+ Split(cookie).Any(c => c.Name.Equals(name, StringComparison.Ordinal) && c.Value.Length > 0);
+
+ /// Applica le intestazioni Set-Cookie di una risposta alla stringa corrente.
+ public static string Merge(string current, IEnumerable setCookies)
+ {
+ var jar = Split(current);
+ foreach (var header in setCookies)
+ {
+ var first = header.Split(';')[0].Trim();
+ var eq = first.IndexOf('=');
+ if (eq <= 0) continue;
+ var name = first[..eq].Trim();
+ var value = first[(eq + 1)..].Trim();
+
+ var expired = value.Length == 0 || value.Equals("deleted", StringComparison.OrdinalIgnoreCase) ||
+ header.Contains("Max-Age=0", StringComparison.OrdinalIgnoreCase) ||
+ header.Contains("expires=Thu, 01 Jan 1970", StringComparison.OrdinalIgnoreCase);
+
+ var index = jar.FindIndex(c => c.Name.Equals(name, StringComparison.Ordinal));
+ if (expired)
+ {
+ if (index >= 0) jar.RemoveAt(index);
+ }
+ else if (index >= 0) jar[index] = (name, value);
+ else jar.Add((name, value));
+ }
+ return Join(jar);
+ }
+}
diff --git a/Mimante/src/BidooBidBot/Net/HttpOutcome.cs b/Mimante/src/BidooBidBot/Net/HttpOutcome.cs
new file mode 100644
index 0000000..dfed6a0
--- /dev/null
+++ b/Mimante/src/BidooBidBot/Net/HttpOutcome.cs
@@ -0,0 +1,109 @@
+using System.Diagnostics;
+
+namespace BidooBidBot.Net;
+
+/// Priorità di una richiesta. Le puntate non si accodano mai dietro al polling.
+public enum RequestPriority
+{
+ /// Catalogo, dati del conto, recuperi storici: cedono il passo, lasciano una riserva di gettoni.
+ Background = 0,
+
+ /// Polling delle aste.
+ Normal,
+
+ /// Salta limitatore, freno e coda. Riservato alle puntate.
+ Critical
+}
+
+/// Esito di una richiesta HTTP: corpo, stato, latenza, istante di ricezione.
+public sealed class HttpOutcome
+{
+ public bool Success { get; init; }
+ public int StatusCode { get; init; }
+ public string Body { get; init; } = "";
+ public string? Error { get; init; }
+ public int LatencyMs { get; init; }
+
+ /// Tick di Stopwatch all'arrivo della risposta (monotono).
+ public long ReceivedTicks { get; init; }
+
+ /// Tick di Stopwatch alla partenza: con dà il giro completo.
+ public long SentTicks { get; init; }
+
+ public bool IsNetworkError => StatusCode == 0;
+
+ public string Describe() => Error ?? $"HTTP {StatusCode}";
+
+ public static HttpOutcome Failure(string error, long sent) => new()
+ {
+ Success = false,
+ StatusCode = 0,
+ Error = error,
+ SentTicks = sent,
+ ReceivedTicks = Stopwatch.GetTimestamp(),
+ LatencyMs = (int)((Stopwatch.GetTimestamp() - sent) * 1000 / Stopwatch.Frequency)
+ };
+}
+
+///
+/// Latenze recenti in una finestra circolare, con i percentili a richiesta. Vive in memoria:
+/// nel database finiscono solo le aggregazioni per asta e per puntata.
+///
+public sealed class LatencyStats
+{
+ private readonly int[] _window;
+ private readonly object _sync = new();
+ private int _index;
+ private int _count;
+
+ public LatencyStats(int size = 300) => _window = new int[Math.Max(10, size)];
+
+ public int Count { get { lock (_sync) return _count; } }
+
+ public void Add(int ms)
+ {
+ if (ms <= 0 || ms > 30_000) return;
+ lock (_sync)
+ {
+ _window[_index] = ms;
+ _index = (_index + 1) % _window.Length;
+ if (_count < _window.Length) _count++;
+ }
+ }
+
+ /// Il percentile richiesto (0-1); null senza campioni.
+ public int? Percentile(double p)
+ {
+ int[] copy;
+ lock (_sync)
+ {
+ if (_count == 0) return null;
+ copy = new int[_count];
+ Array.Copy(_window, copy, _count);
+ }
+ Array.Sort(copy);
+ var i = (int)Math.Ceiling(p * copy.Length) - 1;
+ return copy[Math.Clamp(i, 0, copy.Length - 1)];
+ }
+
+ public double? Average()
+ {
+ lock (_sync)
+ {
+ if (_count == 0) return null;
+ long sum = 0;
+ for (var i = 0; i < _count; i++) sum += _window[i];
+ return (double)sum / _count;
+ }
+ }
+
+ public int[] Snapshot()
+ {
+ lock (_sync)
+ {
+ var copy = new int[_count];
+ Array.Copy(_window, copy, _count);
+ return copy;
+ }
+ }
+}
diff --git a/Mimante/src/BidooBidBot/Net/TokenBucket.cs b/Mimante/src/BidooBidBot/Net/TokenBucket.cs
new file mode 100644
index 0000000..d176caf
--- /dev/null
+++ b/Mimante/src/BidooBidBot/Net/TokenBucket.cs
@@ -0,0 +1,76 @@
+using System.Diagnostics;
+
+namespace BidooBidBot.Net;
+
+///
+/// Token bucket a rilascio continuo: un gettone per richiesta, e si aspetta solo il tempo
+/// di rigenerarlo. Nessun timer, nessun thread.
+///
+/// Le richieste di fondo (catalogo, conto) lasciano una riserva di gettoni alle
+/// interrogazioni delle aste: nel legacy un tetto di 40 al secondo spartito alla pari fra
+/// tutto faceva interrogare ogni ~600 ms le aste negli ultimi secondi, dove il ritardo costa
+/// l'asta. Zero o meno = nessun limite.
+///
+public sealed class TokenBucket
+{
+ private readonly object _sync = new();
+ private double _capacity;
+ private double _rate;
+ private double _tokens;
+ private long _lastTicks;
+
+ /// Quota di capacità che le richieste di fondo non possono toccare.
+ public double BackgroundReserve { get; set; } = 0.25;
+
+ public TokenBucket(double ratePerSecond)
+ {
+ SetRate(ratePerSecond);
+ _tokens = _capacity;
+ _lastTicks = Stopwatch.GetTimestamp();
+ }
+
+ public double Rate { get { lock (_sync) return _rate; } }
+
+ public void SetRate(double ratePerSecond)
+ {
+ lock (_sync)
+ {
+ _rate = ratePerSecond;
+ _capacity = Math.Max(8, Math.Abs(ratePerSecond));
+ if (_tokens > _capacity) _tokens = _capacity;
+ }
+ }
+
+ /// Millisecondi da aspettare prima di poter partire (e prenota il gettone).
+ public double Reserve(bool background)
+ {
+ lock (_sync)
+ {
+ if (_rate <= 0) return 0;
+
+ var now = Stopwatch.GetTimestamp();
+ var elapsed = (now - _lastTicks) / (double)Stopwatch.Frequency;
+ _lastTicks = now;
+ _tokens = Math.Min(_capacity, _tokens + elapsed * _rate);
+
+ var floor = background ? _capacity * BackgroundReserve : 0;
+ var needed = 1 + floor;
+
+ if (_tokens >= needed)
+ {
+ _tokens -= 1;
+ return 0;
+ }
+
+ var waitMs = (needed - _tokens) / _rate * 1000.0;
+ _tokens -= 1; // la richiesta è già in coda: il gettone è suo
+ return waitMs;
+ }
+ }
+
+ public ValueTask WaitAsync(bool background, CancellationToken ct)
+ {
+ var ms = Reserve(background);
+ return ms <= 0 ? ValueTask.CompletedTask : new ValueTask(Task.Delay(TimeSpan.FromMilliseconds(Math.Min(ms, 5000)), ct));
+ }
+}
diff --git a/Mimante/src/BidooBidBot/Program.cs b/Mimante/src/BidooBidBot/Program.cs
index 36088a0..9037583 100644
--- a/Mimante/src/BidooBidBot/Program.cs
+++ b/Mimante/src/BidooBidBot/Program.cs
@@ -53,9 +53,10 @@ log.Info("AVVIO", $"{AppInfo.Name} {AppInfo.Version}, .NET {Environment.Version}
await using var host = new BotHost(env, paths, log, fileLog);
var app = WebServer.Build(host);
+// SIGTERM (docker stop) e Ctrl+C arrivano al ciclo di vita del server web: da lì si ferma
+// anche il bot, e il processo esce solo dopo lo spegnimento ordinato qui sotto.
using var shutdown = new CancellationTokenSource();
-Console.CancelKeyPress += (_, e) => { e.Cancel = true; shutdown.Cancel(); };
-AppDomain.CurrentDomain.ProcessExit += (_, _) => { try { shutdown.Cancel(); } catch (ObjectDisposedException) { } };
+app.Lifetime.ApplicationStopping.Register(() => { try { shutdown.Cancel(); } catch (ObjectDisposedException) { } });
await app.StartAsync(shutdown.Token);
log.Info("AVVIO", $"Interfaccia in ascolto su http://0.0.0.0:{env.HttpPort}");
diff --git a/Mimante/tests/BidooBidBot.Tests/Fixtures/bid-errore.txt b/Mimante/tests/BidooBidBot.Tests/Fixtures/bid-errore.txt
new file mode 100644
index 0000000..ed1af69
--- /dev/null
+++ b/Mimante/tests/BidooBidBot.Tests/Fixtures/bid-errore.txt
@@ -0,0 +1 @@
+error|Timer scaduto
Riprova
\ No newline at end of file
diff --git a/Mimante/tests/BidooBidBot.Tests/Fixtures/bid-ok.txt b/Mimante/tests/BidooBidBot.Tests/Fixtures/bid-ok.txt
new file mode 100644
index 0000000..8478e68
--- /dev/null
+++ b/Mimante/tests/BidooBidBot.Tests/Fixtures/bid-ok.txt
@@ -0,0 +1 @@
+ok|927|480|3|5|0|1234567|0|0
\ No newline at end of file
diff --git a/Mimante/tests/BidooBidBot.Tests/Fixtures/data-conclusa.txt b/Mimante/tests/BidooBidBot.Tests/Fixtures/data-conclusa.txt
new file mode 100644
index 0000000..086b336
--- /dev/null
+++ b/Mimante/tests/BidooBidBot.Tests/Fixtures/data-conclusa.txt
@@ -0,0 +1 @@
+1785597295*[95235087;OFF;1784757333;838;redberri;1;1h 24m;|0|25|0|0|0|0|,838;redberri;1784757325;1|837;semoricci;1784757318;3|836;redberri;1784757312;1]
\ No newline at end of file
diff --git a/Mimante/tests/BidooBidBot.Tests/Fixtures/data-in-corso.txt b/Mimante/tests/BidooBidBot.Tests/Fixtures/data-in-corso.txt
new file mode 100644
index 0000000..e0f6ffb
--- /dev/null
+++ b/Mimante/tests/BidooBidBot.Tests/Fixtures/data-in-corso.txt
@@ -0,0 +1 @@
+1785597356*[95755813;ON;1785597364;4;kikisi9;1,4;kikisi9;1785597356;1|3;casmeride;1785597348;1|2;kikisi9;1785597340;1]
\ No newline at end of file
diff --git a/Mimante/tests/BidooBidBot.Tests/Fixtures/data-lista.txt b/Mimante/tests/BidooBidBot.Tests/Fixtures/data-lista.txt
new file mode 100644
index 0000000..7674d5b
--- /dev/null
+++ b/Mimante/tests/BidooBidBot.Tests/Fixtures/data-lista.txt
@@ -0,0 +1 @@
+1764068200*(95216992;ON;1764068210;342;fedekikka2323#95216993;OFF;1764068100;120;tizio#95216994;ON;1764075000;1;)
\ No newline at end of file
diff --git a/Mimante/tests/BidooBidBot.Tests/Fixtures/data-vergine.txt b/Mimante/tests/BidooBidBot.Tests/Fixtures/data-vergine.txt
new file mode 100644
index 0000000..73d00d2
--- /dev/null
+++ b/Mimante/tests/BidooBidBot.Tests/Fixtures/data-vergine.txt
@@ -0,0 +1 @@
+1785597337*[95760550;ON;1785597351;1;;,]
\ No newline at end of file
diff --git a/Mimante/tests/BidooBidBot.Tests/ProtocolTests.cs b/Mimante/tests/BidooBidBot.Tests/ProtocolTests.cs
new file mode 100644
index 0000000..e671062
--- /dev/null
+++ b/Mimante/tests/BidooBidBot.Tests/ProtocolTests.cs
@@ -0,0 +1,557 @@
+using System.Diagnostics;
+using BidooBidBot.Bidoo;
+using BidooBidBot.Net;
+using Xunit;
+
+namespace BidooBidBot.Tests;
+
+internal static class Fixture
+{
+ public static string Read(string name) =>
+ File.ReadAllText(Path.Combine(AppContext.BaseDirectory, "Fixtures", name));
+}
+
+///
+/// data.php è posizionale e non documentato: se cambia forma l'unico sintomo è uno stato
+/// sbagliato. Questi test fissano il contratto osservato sul campo (portati dal legacy).
+///
+public class DataResponseParserTests
+{
+ private const string Sample =
+ "1764068200*[95216992;ON;1764068210;342;fedekikka2323;1," +
+ "342;fedekikka2323;1764068204;3|341;chamorro1984;1764068194;1]";
+
+ [Fact]
+ public void Legge_i_campi_principali()
+ {
+ var r = DataResponseParser.Parse("95216992", Sample, 50, 1000, "tizio");
+ Assert.True(r.Success);
+ var s = r.State!;
+ Assert.Equal("95216992", s.AuctionId);
+ Assert.Equal(3.42, s.Price, 3);
+ Assert.Equal("fedekikka2323", s.LastBidder);
+ Assert.Equal(AuctionStatus.Running, s.Status);
+ Assert.False(s.IsMyBid);
+ }
+
+ [Fact]
+ public void Espone_gli_istanti_assoluti_del_server()
+ {
+ var r = DataResponseParser.Parse("1", Sample, 50, 1000, null);
+ Assert.Equal(1764068200, r.State!.ServerUnixSeconds);
+ Assert.Equal(1764068210, r.State.ExpiryUnixSeconds);
+ Assert.Equal(10, r.State.Timer, 3);
+ }
+
+ [Fact]
+ public void Riconosce_le_puntate_dell_utente_senza_badare_alle_maiuscole()
+ {
+ var r = DataResponseParser.Parse("1", Sample, 50, 1000, "FEDEKIKKA2323");
+ Assert.True(r.State!.IsMyBid);
+ }
+
+ [Fact]
+ public void Legge_lo_storico_con_tipo_e_prezzo()
+ {
+ var history = DataResponseParser.Parse("1", Sample, 50, 1000, "chamorro1984").State!.RecentBidsHistory!;
+ Assert.Equal(2, history.Count);
+ Assert.Equal(3.42m, history[0].Price);
+ Assert.Equal(BidHistoryEntry.TypeAuto, history[0].BidType);
+ Assert.False(history[0].IsMyBid);
+ Assert.Equal(BidHistoryEntry.TypeManual, history[1].BidType);
+ Assert.True(history[1].IsMyBid);
+ }
+
+ [Fact]
+ public void Rispetta_il_tetto_sullo_storico()
+ {
+ var r = DataResponseParser.Parse("1", Sample, 50, 1000, null, maxHistoryEntries: 1);
+ Assert.Single(r.State!.RecentBidsHistory!);
+ }
+
+ [Theory]
+ [InlineData("")]
+ [InlineData(" ")]
+ [InlineData("senza-asterisco")]
+ [InlineData("1764068200*nessuna-parentesi")]
+ [InlineData("1764068200*[troppo;pochi;campi]")]
+ public void Rifiuta_le_risposte_malformate_senza_eccezioni(string bad)
+ {
+ var r = DataResponseParser.Parse("1", bad, 50, 1000, null);
+ Assert.False(r.Success);
+ Assert.False(string.IsNullOrEmpty(r.Error));
+ }
+
+ [Fact]
+ public void Ignora_i_campi_extra_prima_dell_asterisco()
+ {
+ var r = DataResponseParser.Parse("1", "1764068200|altro|ancora*[1;ON;1764068210;342;tizio]", 50, 1000, null);
+ Assert.True(r.Success);
+ Assert.Equal(1764068200, r.State!.ServerUnixSeconds);
+ Assert.Null(r.State.RecentBidsHistory);
+ }
+
+ [Theory]
+ [InlineData("ON", true, false, 10, AuctionStatus.Running)]
+ [InlineData("ON", true, true, 10, AuctionStatus.Running)]
+ [InlineData("ON", false, false, 10, AuctionStatus.Pending)]
+ [InlineData("ON", false, false, 3600, AuctionStatus.Scheduled)]
+ [InlineData("OFF", true, true, 0, AuctionStatus.EndedWon)]
+ [InlineData("OFF", true, false, 0, AuctionStatus.EndedLost)]
+ [InlineData("OFF", false, false, 0, AuctionStatus.Closed)]
+ [InlineData("STOP", true, false, 0, AuctionStatus.Paused)]
+ [InlineData("BOH", false, false, 0, AuctionStatus.Unknown)]
+ public void Traduce_lo_stato_del_server(string api, bool hasWinner, bool iAmWinner, double timer, AuctionStatus expected)
+ {
+ Assert.Equal(expected, DataResponseParser.DetermineStatus(api, hasWinner, iAmWinner, timer));
+ }
+
+ [Fact]
+ public void Una_vittoria_richiede_che_il_vincitore_sia_l_utente()
+ {
+ Assert.Equal(AuctionStatus.EndedWon, DataResponseParser.Parse("1", "100*[1;OFF;100;500;ioStesso]", 10, 0, "ioStesso").State!.Status);
+ Assert.Equal(AuctionStatus.EndedLost, DataResponseParser.Parse("1", "100*[1;OFF;100;500;unAltro]", 10, 0, "ioStesso").State!.Status);
+ }
+
+ // ── Risposte vere registrate dal server (Fixtures) ──────────────────
+
+ [Fact]
+ public void Asta_conclusa_con_le_puntate_del_vincitore()
+ {
+ var r = DataResponseParser.Parse("95235087", Fixture.Read("data-conclusa.txt"), 50, 0, null);
+ Assert.True(r.Success);
+ Assert.Equal("redberri", r.State!.LastBidder);
+ Assert.Equal(8.38, r.State.Price, 2);
+ Assert.Equal(AuctionStatus.EndedLost, r.State.Status);
+ Assert.Equal(0, r.State.WinnerBidsPaid);
+ Assert.Equal(25, r.State.WinnerBidsFree);
+ Assert.Equal(25, r.State.WinnerBidsTotal);
+ }
+
+ [Fact]
+ public void La_puntata_piu_recente_non_si_perde()
+ {
+ var r = DataResponseParser.Parse("95755813", Fixture.Read("data-in-corso.txt"), 50, 0, null);
+ var history = r.State!.RecentBidsHistory!;
+ Assert.Equal(3, history.Count);
+ Assert.Equal("kikisi9", history[0].Username);
+ Assert.Equal(0.04m, history[0].Price);
+ Assert.Null(r.State.WinnerBidsTotal);
+ Assert.Equal(AuctionStatus.Running, r.State.Status);
+ }
+
+ [Fact]
+ public void Unasta_senza_puntate_si_legge_lo_stesso()
+ {
+ var r = DataResponseParser.Parse("95760550", Fixture.Read("data-vergine.txt"), 50, 0, null);
+ Assert.True(r.Success);
+ Assert.Equal("", r.State!.LastBidder);
+ Assert.Null(r.State.RecentBidsHistory);
+ Assert.Equal(AuctionStatus.Pending, r.State.Status);
+ }
+
+ [Theory]
+ [InlineData("0|25|0|0|0|0|", 0, 25)]
+ [InlineData("371|0|0|0|0|0|", 371, 0)]
+ [InlineData("12|3", 12, 3)]
+ public void Legge_pagate_e_gratis(string tail, int paid, int free)
+ {
+ var (p, f) = DataResponseParser.ParseWinnerBids(tail);
+ Assert.Equal(paid, p);
+ Assert.Equal(free, f);
+ }
+
+ [Theory]
+ [InlineData("")]
+ [InlineData("42")]
+ [InlineData("x|y")]
+ public void Una_coda_incomprensibile_non_inventa_numeri(string tail)
+ {
+ var (p, f) = DataResponseParser.ParseWinnerBids(tail);
+ Assert.True(p is null || f is null);
+ }
+
+ [Fact]
+ public void La_risposta_a_piu_aste_si_legge_riga_per_riga()
+ {
+ var list = DataResponseParser.ParseList(Fixture.Read("data-lista.txt"));
+ Assert.Equal(3, list.Count);
+ Assert.Equal("95216992", list[0].AuctionId);
+ Assert.Equal(3.42, list[0].Price, 3);
+ Assert.Equal(10, list[0].RemainingSeconds);
+ Assert.Equal("OFF", list[1].Status);
+ Assert.Equal("", list[2].LastBidder);
+ }
+
+ [Theory]
+ [InlineData("