diff --git a/Mimante/src/BidooBidBot/Data/AuctionRecorder.cs b/Mimante/src/BidooBidBot/Data/AuctionRecorder.cs index 5752a7c..d4d4a68 100644 --- a/Mimante/src/BidooBidBot/Data/AuctionRecorder.cs +++ b/Mimante/src/BidooBidBot/Data/AuctionRecorder.cs @@ -74,18 +74,24 @@ public sealed class AuctionRecorder private readonly ConcurrentDictionary _open = new(StringComparer.Ordinal); private long _nextDecisionId; + private readonly string _world; + /// - /// Senza coda ( null) non si scrive nulla: il simulatore segue le - /// sue aste senza toccare l'archivio vero. + /// Senza coda ( null) non si scrive nulla. + /// finisce in auctions.type: normal per il sito vero, sim per il + /// simulatore, così le due storie non si mescolano mai (storico, statistiche, modello). /// - public AuctionRecorder(WriteQueue? queue, Db? db, Func settings, Func me) + public AuctionRecorder(WriteQueue? queue, Db? db, Func settings, Func me, string world = Worlds.Real) { _queue = queue; _db = db; _settings = settings; _me = me; + _world = world; } + public string World => _world; + public bool Enabled => _queue != null && _settings().RecordAuctions; public int OpenCount => _open.Count; @@ -145,9 +151,9 @@ public sealed class AuctionRecorder new object?[] { a.ProductKey, a.BidooProductId > 0 ? a.BidooProductId.ToString(System.Globalization.CultureInfo.InvariantCulture) : null, a.Name, a.ImageUrl, a.BuyNowPrice, a.Shipping }), - ("INSERT INTO auctions(auction_id, item_id, product_key, name, url, status, me, app_version, added_at, first_seen_at, " + + ("INSERT INTO auctions(auction_id, item_id, product_key, name, url, status, me, app_version, added_at, first_seen_at, type, " + " buy_now_price, shipping, market_value, has_win_limit, win_limit, configured_lead_ms, lead_is_manual, config) " + - "VALUES($1, (SELECT item_id FROM items WHERE product_key = $2), $2, $3, $4, 'open', $5, $6, $7, now(), $8, $9, " + + "VALUES($1, (SELECT item_id FROM items WHERE product_key = $2), $2, $3, $4, 'open', $5, $6, $7, now(), $15, $8, $9, " + " (SELECT market_price_est FROM items WHERE product_key = $2), $10, $11, $12, $13, $14) " + "ON CONFLICT(auction_id) DO UPDATE SET me = COALESCE(excluded.me, auctions.me), app_version = excluded.app_version, " + " name = CASE WHEN excluded.name <> '' THEN excluded.name ELSE auctions.name END, " + @@ -155,7 +161,7 @@ public sealed class AuctionRecorder " has_win_limit = excluded.has_win_limit OR auctions.has_win_limit, win_limit = COALESCE(excluded.win_limit, auctions.win_limit), " + " configured_lead_ms = excluded.configured_lead_ms, lead_is_manual = excluded.lead_is_manual, config = excluded.config", new object?[] { a.Id, a.ProductKey, a.Name, a.Url, _me(), AppInfo.Version, a.AddedAtUtc, a.BuyNowPrice, a.Shipping, - !string.IsNullOrEmpty(a.WinLimit), a.WinLimit, a.LeadMs, a.LeadIsManual, new Jsonb(config) }) + !string.IsNullOrEmpty(a.WinLimit), a.WinLimit, a.LeadMs, a.LeadIsManual, new Jsonb(config), _world }) }); } diff --git a/Mimante/src/BidooBidBot/Data/CsvExport.cs b/Mimante/src/BidooBidBot/Data/CsvExport.cs new file mode 100644 index 0000000..df39e42 --- /dev/null +++ b/Mimante/src/BidooBidBot/Data/CsvExport.cs @@ -0,0 +1,524 @@ +using System.Globalization; +using System.Text; +using System.Text.Json; +using BidooBidBot.Config; +using BidooBidBot.Ml; +using BidooBidBot.Products; +using BidooBidBot.Settings; + +namespace BidooBidBot.Data; + +/// +/// Le esportazioni per la revisione con Claude (specifica §9.6, Appendice H): delimitatore +/// ;, UTF-8 con BOM, virgola decimale, intestazioni in italiano, una colonna +/// motivazione per riga e un legenda.txt accanto che spiega ogni colonna, i +/// filtri, le righe totali ed esportate e, se si è campionato, come. +/// +public sealed class CsvExport +{ + public sealed record Request(string What, DateTime? From, DateTime? To, bool OnlyMyBids, int MaxRows, string World); + + public sealed record Result(bool Ok, string Message, IReadOnlyList Files, int Rows, bool Sampled); + + public const string ModelData = "dati_modello"; + public const string AuctionHistory = "storico_aste"; + public const string ProductsWhat = "prodotti"; + + private static readonly CultureInfo It = CultureInfo.GetCultureInfo("it-IT"); + private static readonly UTF8Encoding Bom = new(encoderShouldEmitUTF8Identifier: true); + + private readonly Db _db; + private readonly WriteQueue _queue; + private readonly ConfigPaths _paths; + private readonly Func _settings; + private readonly Func _learning; + + public CsvExport(Db db, WriteQueue queue, ConfigPaths paths, Func settings, Func learning) + { + _db = db; + _queue = queue; + _paths = paths; + _settings = settings; + _learning = learning; + } + + public async Task RunAsync(Request req, CancellationToken ct) + { + Directory.CreateDirectory(_paths.Exports); + await _queue.FlushAsync(TimeSpan.FromSeconds(30)).ConfigureAwait(false); + var to = (req.To ?? AppInfo.LocalNow.Date).Date; + var from = (req.From ?? to.AddDays(-30)).Date; + if (from > to) (from, to) = (to, from); + var maxRows = req.MaxRows <= 0 ? int.MaxValue : req.MaxRows; + + return req.What switch + { + ModelData => await ModelDataAsync(req, from, to, maxRows, ct).ConfigureAwait(false), + AuctionHistory => await HistoryAsync(req, from, to, maxRows, ct).ConfigureAwait(false), + ProductsWhat => await ProductsAsync(ct).ConfigureAwait(false), + _ => new Result(false, $"Esportazione sconosciuta: {req.What}", Array.Empty(), 0, false) + }; + } + + // ── dati del modello ───────────────────────────────────────────────── + + private static readonly string[] ModelHead = + { + "id_decisione", "quando", "id_asta", "prodotto", "chiave_prodotto", "categoria", "modo", "dal_vivo", "prezzo", "timer_s", "valore", + "compralo_ora", "spedizione", "costo_puntata", "puntate_residue", "pagate", "gratis" + }; + + private static readonly string[] ModelTail = + { + "p_modello", "p_bandit", "correzione_mie_puntate", "p_finale", "ev", "verdetto", "tipo_decisione", "motivo", "campione", + "brier_corrente", "calibrazione", "esito_senza_risposta", "risposto_da", "risposto_tipo", "risposto_dopo_s", "mia_puntata", + "mia_puntata_ok", "anticipo_pianificato_ms", "anticipo_effettivo_ms", "ping_ms", "rtt_puntata_ms", "puntate_usate_asta", + "previsione_chiusura", "previsione_p10", "previsione_p90", "chiusura_reale", "esito_asta", "motivazione" + }; + + private async Task ModelDataAsync(Request req, DateTime from, DateTime to, int maxRows, CancellationToken ct) + { + const string sql = + "SELECT d.decision_id, d.ts, d.auction_id, a.name, a.product_key, d.state::text AS state, d.shadow, d.executed, d.price, d.timer, " + + " d.value, a.buy_now_price, a.shipping, d.bid_cost, d.p_model, d.p_bandit, d.own_bid_factor, d.p_win, d.ev, d.action, d.kind, " + + " d.reason_detail, d.champion, d.outcome, a.final_price, a.won_by_me, a.my_bids AS auction_my_bids, " + + " mb.success AS mb_success, mb.planned_lead_ms, mb.actual_lead_ms, mb.ping_ms AS mb_ping, mb.rtt_ms, mb.bids_used, " + + " nb.username AS next_user, nb.bid_type AS next_type, nb.server_ts AS next_ts, pb.server_ts AS prev_ts, " + + " f.forecast_close, f.forecast_close_p10, f.forecast_close_p90 " + + "FROM bot_decisions d JOIN auctions a ON a.auction_id = d.auction_id " + + "LEFT JOIN my_bids mb ON mb.decision_id = d.decision_id " + + "LEFT JOIN LATERAL (SELECT b.username, b.bid_type, b.server_ts FROM bids b WHERE b.auction_id = d.auction_id " + + " AND ABS(b.price_after - (d.price + CASE WHEN mb.success THEN 0.02 ELSE 0.01 END)) < 0.005 LIMIT 1) nb ON true " + + "LEFT JOIN LATERAL (SELECT b.server_ts FROM bids b WHERE b.auction_id = d.auction_id " + + " AND ABS(b.price_after - (d.price + CASE WHEN mb.success THEN 0.01 ELSE 0 END)) < 0.005 LIMIT 1) pb ON true " + + "LEFT JOIN LATERAL (SELECT forecast_close, forecast_close_p10, forecast_close_p90 FROM auction_forecasts x " + + " WHERE x.auction_id = d.auction_id AND x.ts <= d.ts ORDER BY x.ts DESC LIMIT 1) f ON true " + + "WHERE a.type = $1 AND d.ts >= $2 AND d.ts < $3 AND ($4 = false OR a.my_bids > 0) ORDER BY d.ts"; + + var rows = await _db.QueryAsync(sql, r => r.ToDictionary(), req.World, Utc(from), Utc(to.AddDays(1)), req.OnlyMyBids).ConfigureAwait(false); + ct.ThrowIfCancellationRequested(); + var total = rows.Count; + var (kept, sampled, sampleNote) = Stratify(rows, maxRows, r => (r.GetValueOrDefault("outcome") as string) ?? "senza esito"); + + var learning = _learning(req.World); + var brier = learning?.BrierScores; + var calibration = learning?.CalibrationFactor; + var name = $"dati-modello-{from:yyyy-MM-dd}-{to:yyyy-MM-dd}.csv"; + + var sb = new StringBuilder(); + Line(sb, ModelHead.Concat(BidFeatures.Names).Concat(ModelTail)); + foreach (var r in kept) + { + var ctx = ReadContext(r.GetValueOrDefault("state") as string, out var stateBalance, out var statePaid, out var stateFree); + var features = ctx is { } c ? BidFeatures.Build(c) : null; + var shadow = (bool)(r["shadow"] ?? true); + var executed = (bool)(r["executed"] ?? false); + var outcome = r.GetValueOrDefault("outcome") as string; + var unanswered = outcome != null ? ShadowReport.Unanswered(outcome) : (bool?)null; + var verdict = (r["action"] as string) == "BID" ? ((r["kind"] as string) == LossReasons.Kind.Esplora ? "esplora" : "punta") : "no"; + var nextTs = Long(r, "next_ts"); + var prevTs = Long(r, "prev_ts"); + double? after = nextTs is > 0 && prevTs is > 0 ? nextTs - prevTs : null; + var champion = r.GetValueOrDefault("champion") as string; + var wonByMe = (bool)(r["won_by_me"] ?? false); + var outcomeAuction = r["final_price"] == null ? "in corso" : wonByMe ? "vinta" : Int(r, "auction_my_bids") > 0 ? "persa" : "osservata"; + + var cells = new List + { + Str(r, "decision_id"), Ts(r, "ts"), Str(r, "auction_id"), Str(r, "name"), Str(r, "product_key"), "", + shadow ? "osserva" : "attiva", shadow ? "no" : "si", Num(r, "price", 2), Num(r, "timer", 2), Num(r, "value", 2), + Num(r, "buy_now_price", 2), Num(r, "shipping", 2), Num(r, "bid_cost", 3), stateBalance?.ToString(It), statePaid?.ToString(It), + stateFree?.ToString(It) + }; + if (features != null) cells.AddRange(features.Select(v => v.ToString("0.####", It))); + else cells.AddRange(Enumerable.Repeat("", BidFeatures.Size)); + + var motivation = Motivation(verdict, r, unanswered, after); + cells.AddRange(new[] + { + Num(r, "p_model", 5), Num(r, "p_bandit", 5), Num(r, "own_bid_factor", 3), Num(r, "p_win", 5), Num(r, "ev", 3), verdict, + KindLabel(r["kind"] as string), Str(r, "reason_detail"), champion == "rete" ? "rete" : champion == null ? "" : "logit", + brier is { } b ? Fmt(champion == "rete" ? b.Net : b.Logit, 5) : "", calibration is { } cal ? Fmt(cal, 3) : "", + unanswered is { } u ? (u ? "si" : "no") : "", Str(r, "next_user"), TypeLabel(r.GetValueOrDefault("next_type") as string), + after is { } a ? Fmt(a, 0) : "", executed ? "si" : "no", r["mb_success"] is bool ok ? (ok ? "si" : "no") : "", + Num(r, "planned_lead_ms", 0), Num(r, "actual_lead_ms", 1), Num(r, "mb_ping", 0), Num(r, "rtt_ms", 0), Num(r, "bids_used", 0), + Num(r, "forecast_close", 2), Num(r, "forecast_close_p10", 2), Num(r, "forecast_close_p90", 2), Num(r, "final_price", 2), + outcomeAuction, motivation + }); + Line(sb, cells); + } + + await WriteAsync(name, sb, ct).ConfigureAwait(false); + var legend = await WriteLegendAsync("dati-modello", from, to, req, total, kept.Count, sampleNote, ModelLegend(), ct).ConfigureAwait(false); + return new Result(true, Summary(name, kept.Count, total, sampled), new[] { name, legend }, kept.Count, sampled); + } + + private static string Motivation(string verdict, Dictionary r, bool? unanswered, double? after) + { + var shadow = (bool)(r["shadow"] ?? true); + var price = Num(r, "price", 2); + var head = verdict switch + { + "punta" => shadow ? $"Avrebbe puntato a {price} €" : $"Ha puntato a {price} €", + "esplora" => shadow ? $"Avrebbe esplorato a {price} €" : $"Ha esplorato a {price} €", + _ => shadow ? $"Non avrebbe puntato a {price} €" : $"Non ha puntato a {price} €" + }; + var sb = new StringBuilder(head); + if (r["reason_detail"] is string reason && reason.Length > 0) sb.Append(": ").Append(reason); + sb.Append(". "); + if (unanswered == true) sb.Append("Esito: una puntata lì sarebbe rimasta l'ultima."); + else if (unanswered == false) + { + sb.Append("Esito: qualcuno ha risposto"); + if (r["next_user"] is string u && u.Length > 0) sb.Append($" ({u}{(TypeLabel(r["next_type"] as string) is { Length: > 0 } t ? ", " + t : "")}{(after is { } a ? $", dopo {a:0} s" : "")})"); + sb.Append('.'); + } + else sb.Append("Esito non ancora noto (asta in corso o non registrata)."); + return sb.ToString(); + } + + private static List ModelLegend() + { + var lines = new List + { + "id_decisione: numero progressivo della decisione (bot_decisions.decision_id)", + "quando: istante della decisione, ora locale", + "id_asta, prodotto, chiave_prodotto: l'asta e il prodotto (chiave normalizzata dal nome)", + "categoria: vuota (Bidoo non la espone con affidabilità)", + "modo: osserva = decisione solo registrata; attiva = puntata vera possibile", + "dal_vivo: si se la decisione poteva far partire una puntata vera", + "prezzo, timer_s: prezzo e secondi al termine del ciclo nell'istante della decisione (60 ms prima del fuoco)", + "valore: valore reale usato dal modello (scheda del prodotto o Compralo Ora)", + "compralo_ora, spedizione: dalla pagina dell'asta", + "costo_puntata: costo effettivo di una puntata (media fra pagate e gratis)", + "puntate_residue, pagate, gratis: saldo del conto in quell'istante" + }; + lines.Add($"Da {BidFeatures.Names[0]} a {BidFeatures.Names[^1]}: le {BidFeatures.Size} variabili del modello (BidFeatures versione {BidFeatures.Version}), 1 = la fascia vale, 0 = no; vuote se la decisione è stata presa prima di avere un contesto"); + lines.AddRange(new[] + { + "p_modello: probabilità che una puntata resti senza risposta secondo il modello campione", + "p_bandit: probabilità estratta dal bandit di Thompson (politica alternativa, solo registrata)", + "correzione_mie_puntate: fattore che corregge il modello sulle mie puntate vere", + "p_finale: p_modello x correzione, quella usata per il valore atteso", + "ev: valore atteso in euro della puntata", + "verdetto: punta, esplora o no", + "tipo_decisione: il perché del verdetto (Punta, Esplora, No = valore atteso negativo, NonPronto, SenzaStima, SoloLimiti, PrezzoMax, PuntateAsta, PuntateSessione, Soglia, FasciaOraria, Rischio, InTesta, Pausa, NonAperta)", + "motivo: il testo del motore, lo stesso del registro dell'asta", + "campione: quale modello rispondeva (logit o rete)", + "brier_corrente, calibrazione: valori del modello al momento dell'esportazione (non della decisione)", + "esito_senza_risposta: si se una puntata lì sarebbe rimasta l'ultima", + "risposto_da, risposto_tipo, risposto_dopo_s: chi ha puntato dopo, se auto o manuale, e dopo quanti secondi (orologio del server)", + "mia_puntata, mia_puntata_ok: se la decisione ha fatto partire una puntata e se Bidoo l'ha accettata", + "anticipo_pianificato_ms, anticipo_effettivo_ms: quanto prima della scadenza doveva partire e quanto prima è partita", + "ping_ms, rtt_puntata_ms: ritardo dell'ultima lettura e tempo di andata e ritorno della puntata", + "puntate_usate_asta: puntate mie su quell'asta secondo Bidoo", + "previsione_chiusura, previsione_p10, previsione_p90: la previsione dell'asta in vigore in quell'istante", + "chiusura_reale: prezzo finale dell'asta (vuoto se non ancora conclusa)", + "esito_asta: vinta, persa (con mie puntate), osservata (senza mie puntate)", + "motivazione: frase che unisce verdetto, motivo ed esito" + }); + return lines; + } + + private static readonly JsonSerializerOptions StateJson = new() { PropertyNameCaseInsensitive = true }; + + private static BidContext? ReadContext(string? json, out int? balance, out int? paid, out int? free) + { + balance = paid = free = null; + if (string.IsNullOrEmpty(json)) return null; + try + { + var state = JsonSerializer.Deserialize(json, StateJson); + if (state == null) return null; + balance = state.Balance; + paid = state.Paid; + free = state.Free; + return state.Ctx; + } + catch (JsonException) + { + return null; + } + } + + // ── storico aste ───────────────────────────────────────────────────── + + private static readonly string[] HistoryHead = + { + "id_asta", "prodotto", "chiave_prodotto", "categoria", "aperta_il", "chiusa_il", "minuti_osservati", "seguita_dall_inizio", + "seguita_fino_alla_fine", "modo_alla_chiusura", "prezzo_finale", "vincitore", "vinta_da_me", "mie_puntate", "costo_mie_puntate", + "puntate_vincitore_pagate", "puntate_vincitore_gratis", "rilanci_osservati", "puntatori_distinti", "quota_primo_puntatore", "reset", + "compralo_ora", "valore_reale", "spedizione", "fee", "costo_reale_se_vinta", "risparmio", "velocita_prezzo_al_minuto", "ping_medio_ms", + "ping_p95_ms", "ping_p99_ms", "anticipo_impostato_ms", "anticipo_manuale", "puntate_riuscite", "puntate_fallite", "decisioni_totali", + "decisioni_punta", "decisioni_esplora", "decisioni_no", "previsione_chiusura_iniziale", "previsione_p10", "previsione_p90", + "errore_previsione", "nell_intervallo", "motivo_perdita", "motivazione" + }; + + private async Task HistoryAsync(Request req, DateTime from, DateTime to, int maxRows, CancellationToken ct) + { + const string sql = + "SELECT a.*, " + + " (SELECT COUNT(*) FROM bot_decisions d WHERE d.auction_id = a.auction_id) AS dec_total, " + + " (SELECT COUNT(*) FROM bot_decisions d WHERE d.auction_id = a.auction_id AND d.action = 'BID' AND d.kind <> 'esplora') AS dec_bid, " + + " (SELECT COUNT(*) FROM bot_decisions d WHERE d.auction_id = a.auction_id AND d.kind = 'esplora') AS dec_explore, " + + " f.forecast_close AS f_close, f.forecast_close_p10 AS f_p10, f.forecast_close_p90 AS f_p90 " + + "FROM auctions a LEFT JOIN LATERAL (SELECT forecast_close, forecast_close_p10, forecast_close_p90 FROM auction_forecasts x " + + " WHERE x.auction_id = a.auction_id ORDER BY x.is_initial DESC, x.ts LIMIT 1) f ON true " + + "WHERE a.type = $1 AND a.outcome IS NOT NULL AND a.end_time >= $2 AND a.end_time < $3 AND ($4 = false OR a.my_bids > 0) " + + "ORDER BY a.end_time"; + + var rows = await _db.QueryAsync(sql, r => r.ToDictionary(), req.World, Utc(from), Utc(to.AddDays(1)), req.OnlyMyBids).ConfigureAwait(false); + ct.ThrowIfCancellationRequested(); + var total = rows.Count; + var (kept, sampled, note) = Stratify(rows, maxRows, r => (bool)(r["won_by_me"] ?? false) ? "vinta" : Int(r, "my_bids") > 0 ? "persa" : "osservata"); + var fee = _settings().TransactionFeeEuro; + var name = $"storico-aste-{from:yyyy-MM-dd}-{to:yyyy-MM-dd}.csv"; + + var sb = new StringBuilder(); + Line(sb, HistoryHead); + foreach (var r in kept) + { + var final = Dbl(r, "final_price") ?? 0; + var myCost = Dbl(r, "my_bids_cost") ?? 0; + var ship = Dbl(r, "shipping") ?? 0; + var f = Dbl(r, "transaction_fee") ?? fee; + var value = Dbl(r, "market_value") ?? Dbl(r, "buy_now_price"); + var won = (bool)(r["won_by_me"] ?? false); + var realCost = final + myCost + f + ship; + var fClose = Dbl(r, "f_close"); + var p10 = Dbl(r, "f_p10"); + var p90 = Dbl(r, "f_p90"); + var decTotal = Int(r, "dec_total") ?? 0; + var decBid = Int(r, "dec_bid") ?? 0; + var decExplore = Int(r, "dec_explore") ?? 0; + var loss = Str(r, "loss_reason"); + + Line(sb, new[] + { + Str(r, "auction_id"), Str(r, "name"), Str(r, "product_key"), "", Ts(r, "opened_at") is { Length: > 0 } o ? o : Ts(r, "first_seen_at"), Ts(r, "end_time"), + Num(r, "observed_minutes", 1), YesNo(r, "observed_from_start"), YesNo(r, "observed_to_end"), Str(r, "mode_at_close"), + Fmt(final, 2), Str(r, "winner_user"), won ? "si" : "no", Num(r, "my_bids", 0), Fmt(myCost, 2), Num(r, "winner_bids_paid", 0), + Num(r, "winner_bids_free", 0), Num(r, "total_observed_bids", 0), Num(r, "distinct_bidders", 0), Num(r, "top_bidder_share", 3), + Num(r, "resets", 0), Num(r, "buy_now_price", 2), value is { } v ? Fmt(v, 2) : "", Fmt(ship, 2), Fmt(f, 2), Fmt(realCost, 2), + won && value is { } vv ? Fmt(vv - realCost, 2) : "", Num(r, "price_velocity_per_minute", 3), Num(r, "avg_ping_ms", 0), + Num(r, "p95_ping_ms", 0), Num(r, "p99_ping_ms", 0), Num(r, "configured_lead_ms", 0), YesNo(r, "lead_is_manual"), + Num(r, "successful_bids", 0), Num(r, "failed_bids", 0), decTotal.ToString(It), decBid.ToString(It), decExplore.ToString(It), + (decTotal - decBid - decExplore).ToString(It), fClose is { } fc ? Fmt(fc, 2) : "", p10 is { } a ? Fmt(a, 2) : "", + p90 is { } b ? Fmt(b, 2) : "", fClose is { } fc2 ? Fmt(final - fc2, 2) : "", + p10 is { } lo && p90 is { } hi ? (final >= lo - 0.005 && final <= hi + 0.005 ? "si" : "no") : "", + loss, HistoryMotivation(r, won, final, value, realCost, fClose, loss) + }); + } + + await WriteAsync(name, sb, ct).ConfigureAwait(false); + var legend = await WriteLegendAsync("storico-aste", from, to, req, total, kept.Count, note, HistoryLegend(), ct).ConfigureAwait(false); + return new Result(true, Summary(name, kept.Count, total, sampled), new[] { name, legend }, kept.Count, sampled); + } + + private static string HistoryMotivation(Dictionary r, bool won, double final, double? value, double realCost, double? forecast, string? loss) + { + var sb = new StringBuilder(); + var winner = Str(r, "winner_user"); + if (won) + { + sb.Append($"Vinta a {Fmt(final, 2)} € con {Num(r, "my_bids", 0)} puntate mie, costo reale {Fmt(realCost, 2)} €"); + if (value is { } v) sb.Append($" su un valore di {Fmt(v, 2)} € (risparmio {Fmt(v - realCost, 2)} €)"); + } + else if ((Int(r, "my_bids") ?? 0) > 0) sb.Append($"Persa a {Fmt(final, 2)} € contro {winner}, dopo {Num(r, "my_bids", 0)} puntate mie ({Num(r, "my_bids_cost", 2)} €)"); + else sb.Append($"Osservata: chiusa a {Fmt(final, 2)} €, vinta da {winner}"); + sb.Append('.'); + if (forecast is { } f) sb.Append($" Previsione iniziale {Fmt(f, 2)} €, scarto {Fmt(final - f, 2)} €."); + if (!string.IsNullOrEmpty(loss)) sb.Append($" Perché: {loss}."); + return sb.ToString(); + } + + private static List HistoryLegend() => new() + { + "id_asta, prodotto, chiave_prodotto: l'asta e il prodotto; categoria vuota", + "aperta_il: quando l'asta è partita (o quando il bot ha cominciato a seguirla); chiusa_il: fine vera secondo il server", + "minuti_osservati: da quando il bot l'ha vista a quando è finita", + "seguita_dall_inizio, seguita_fino_alla_fine: copertura dell'osservazione (le aste complete valgono di più per il modello)", + "modo_alla_chiusura: ferma, osserva o attiva", + "prezzo_finale, vincitore, vinta_da_me", + "mie_puntate, costo_mie_puntate: puntate mie e il loro costo effettivo", + "puntate_vincitore_pagate, puntate_vincitore_gratis: dichiarate dal server alla fine", + "rilanci_osservati, puntatori_distinti, quota_primo_puntatore: quante puntate ha visto il bot, di quanti utenti, e la quota del più attivo", + "reset: quante volte il timer è ripartito mentre il bot guardava", + "compralo_ora, valore_reale, spedizione, fee: i numeri del prodotto", + "costo_reale_se_vinta: prezzo finale + mie puntate + fee + spedizione; risparmio: valore meno costo reale (solo se vinta)", + "velocita_prezzo_al_minuto: centesimi al minuto nella parte osservata", + "ping_medio_ms, ping_p95_ms, ping_p99_ms: ritardo delle letture durante l'asta", + "anticipo_impostato_ms, anticipo_manuale: anticipo della puntata e se era scritto a mano", + "puntate_riuscite, puntate_fallite: esito delle puntate del motore", + "decisioni_totali, decisioni_punta, decisioni_esplora, decisioni_no: i verdetti del modello sull'asta", + "previsione_chiusura_iniziale, previsione_p10, previsione_p90: la prima previsione, con il suo intervallo", + "errore_previsione: prezzo finale meno previsione; nell_intervallo: se il finale è caduto fra p10 e p90", + "motivo_perdita: il perché scritto dall'apprendimento", + "motivazione: il «perché» dello storico per esteso" + }; + + // ── prodotti ───────────────────────────────────────────────────────── + + private async Task ProductsAsync(CancellationToken ct) + { + var settings = _settings(); + var products = await _db.QueryAsync("SELECT * FROM products ORDER BY display_name", r => r.ToDictionary()).ConfigureAwait(false); + var stats = await ProductStatsRepository.LoadAllAsync(_db).ConfigureAwait(false); + var keys = products.Select(p => Str(p, "product_key")).Union(stats.Keys).Where(k => !string.IsNullOrEmpty(k)).Distinct().ToList(); + var name = $"prodotti-{AppInfo.LocalNow:yyyy-MM-dd}.csv"; + var sb = new StringBuilder(); + Line(sb, new[] + { + "chiave_prodotto", "prodotto", "seguito", "prezzo_max", "puntate_max", "valore_reale", "orizzonte_min", "modo_aggiunta", + "aste_concluse", "vinte", "con_mie_puntate", "mie_puntate", "costo_mie_puntate", "chiusura_media", "chiusura_min", "chiusura_max", + "ultima_chiusura", "compralo_ora", "spedizione", "puntate_vincitore_media", "costo_reale_medio_vinte", "risparmio_medio_vinte", + "consigliato_prezzo_max", "consigliato_puntate_max", "motivazione" + }); + foreach (var key in keys) + { + ct.ThrowIfCancellationRequested(); + var p = products.FirstOrDefault(x => Str(x, "product_key") == key); + stats.TryGetValue(key!, out var s); + var value = p != null ? Dbl(p, "market_value") : null; + var maxBids = p != null ? Int(p, "max_bids") : null; + var advice = s == null ? (ProductAdvice.Advice?)null : ProductAdvice.Suggest(new ProductAdvice.Input( + s.RecentCloses, s.RecentWinnerBids, value ?? s.BuyNow, s.Shipping, maxBids ?? settings.DefaultMaxClicks, + settings.AverageBidCostEuro, settings.SuggestedValueTolerancePercent, settings.SuggestedCoveragePercent / 100.0, + settings.SuggestedMinPercentile / 100.0)); + Line(sb, new[] + { + key, p != null ? Str(p, "display_name") : s?.Name, p != null ? YesNo(p, "followed") : "no", p != null ? Num(p, "max_price", 2) : "", + maxBids?.ToString(It), value is { } v ? Fmt(v, 2) : "", p != null ? Num(p, "horizon_minutes", 0) : "", p != null ? Str(p, "auto_state") : "", + s?.Auctions.ToString(It), s?.Won.ToString(It), s?.WithMyBids.ToString(It), s?.MyBidsTotal.ToString(It), s != null ? Fmt(s.MyBidsCost, 2) : "", + s != null ? Fmt(s.AvgFinal, 2) : "", s != null ? Fmt(s.MinFinal, 2) : "", s != null ? Fmt(s.MaxFinal, 2) : "", + s?.LastFinal is { } lf ? Fmt(lf, 2) : "", s?.BuyNow is { } bn ? Fmt(bn, 2) : "", s?.Shipping is { } sh ? Fmt(sh, 2) : "", + s?.AvgWinnerBids is { } wb ? Fmt(wb, 1) : "", s?.AvgRealCostWon is { } rc ? Fmt(rc, 2) : "", s?.AvgSavingWon is { } sv ? Fmt(sv, 2) : "", + advice is { HasAdvice: true, MaxPrice: { } am } ? Fmt(am, 2) : "", advice?.MaxBids?.ToString(It), advice?.Explanation + }); + } + await WriteAsync(name, sb, ct).ConfigureAwait(false); + var legend = await WriteLegendAsync("prodotti", AppInfo.LocalNow.Date, AppInfo.LocalNow.Date, + new Request(ProductsWhat, null, null, false, 0, Worlds.Real), keys.Count, keys.Count, null, new List + { + "chiave_prodotto, prodotto, seguito: la scheda del prodotto e se le sue aste entrano da sole", + "prezzo_max, puntate_max, valore_reale, orizzonte_min, modo_aggiunta: i paletti scritti sulla scheda", + "aste_concluse, vinte, con_mie_puntate, mie_puntate, costo_mie_puntate: storico del prodotto", + "chiusura_media, chiusura_min, chiusura_max, ultima_chiusura: prezzi finali", + "puntate_vincitore_media: puntate spese dai vincitori (solo dati coerenti col prezzo)", + "costo_reale_medio_vinte, risparmio_medio_vinte: sulle aste vinte da me", + "consigliato_prezzo_max, consigliato_puntate_max, motivazione: il consiglio e il suo ragionamento (solo un consiglio)" + }, ct).ConfigureAwait(false); + return new Result(true, $"Esportati {keys.Count} prodotti in {name}", new[] { name, legend }, keys.Count, false); + } + + // ── aiuti ──────────────────────────────────────────────────────────── + + /// + /// Se le righe superano il tetto si tiene, per ogni gruppo (esito), una quota proporzionale + /// (almeno una riga per gruppo), prendendo righe equidistanti nel tempo: il campione + /// conserva sia le proporzioni sia la distribuzione nel periodo. + /// + internal static (List Kept, bool Sampled, string? Note) Stratify(List rows, int max, Func group) + { + if (rows.Count <= max) return (rows, false, null); + var groups = rows.Select((r, i) => (r, i)).GroupBy(x => group(x.r)).ToList(); + var kept = new List<(T Row, int Index)>(); + var notes = new List(); + foreach (var g in groups) + { + var items = g.ToList(); + var quota = Math.Max(1, (int)Math.Round((double)items.Count * max / rows.Count)); + quota = Math.Min(quota, items.Count); + var step = (double)items.Count / quota; + for (var k = 0; k < quota; k++) kept.Add((items[(int)(k * step)].r, items[(int)(k * step)].i)); + notes.Add($"{g.Key}: {quota} su {items.Count}"); + } + var list = kept.OrderBy(x => x.Index).Select(x => x.Row).ToList(); + return (list, true, $"Campionamento stratificato per esito (righe equidistanti nel tempo dentro ogni gruppo): {string.Join("; ", notes)}"); + } + + private async Task WriteAsync(string name, StringBuilder sb, CancellationToken ct) => + await File.WriteAllTextAsync(Path.Combine(_paths.Exports, name), sb.ToString(), Bom, ct).ConfigureAwait(false); + + private async Task WriteLegendAsync(string prefix, DateTime from, DateTime to, Request req, int total, int exported, string? note, + List columns, CancellationToken ct) + { + var name = $"{prefix}-{from:yyyy-MM-dd}-{to:yyyy-MM-dd}-legenda.txt"; + var sb = new StringBuilder(); + sb.AppendLine($"{AppInfo.Name} {AppInfo.Version}, variabili del modello versione {BidFeatures.Version}"); + sb.AppendLine($"Esportato il {AppInfo.LocalNow:dd/MM/yyyy HH:mm}"); + sb.AppendLine($"Periodo: dal {from:dd/MM/yyyy} al {to:dd/MM/yyyy} compreso; mondo: {(req.World == Worlds.Simulator ? "simulatore" : "sito vero")}"); + sb.AppendLine($"Filtri: {(req.OnlyMyBids ? "solo aste con mie puntate" : "tutte le aste")}; limite di righe {(req.MaxRows > 0 ? req.MaxRows.ToString("N0", It) : "nessuno")}"); + sb.AppendLine($"Righe trovate: {total.ToString("N0", It)}; esportate: {exported.ToString("N0", It)}"); + if (note != null) sb.AppendLine(note); + sb.AppendLine("Formato: delimitatore punto e virgola, UTF-8 con BOM, virgola decimale, date in ora locale (gg/mm/aaaa hh:mm:ss)"); + sb.AppendLine(); + sb.AppendLine("Colonne:"); + foreach (var c in columns) sb.AppendLine("- " + c); + await File.WriteAllTextAsync(Path.Combine(_paths.Exports, name), sb.ToString(), Bom, ct).ConfigureAwait(false); + return name; + } + + private static string Summary(string name, int kept, int total, bool sampled) => + sampled ? $"Esportate {kept:N0} righe su {total:N0} (campione stratificato) in {name}" : $"Esportate {kept:N0} righe in {name}"; + + internal static void Line(StringBuilder sb, IEnumerable cells) + { + var first = true; + foreach (var c in cells) + { + if (!first) sb.Append(';'); + first = false; + sb.Append(Escape(c)); + } + sb.Append("\r\n"); + } + + internal static string Escape(string? v) + { + if (string.IsNullOrEmpty(v)) return ""; + var clean = v.Replace("\r", " ").Replace("\n", " "); + return clean.IndexOfAny(new[] { ';', '"' }) >= 0 ? "\"" + clean.Replace("\"", "\"\"") + "\"" : clean; + } + + private static DateTime Utc(DateTime localDate) => TimeZoneInfo.ConvertTimeToUtc(DateTime.SpecifyKind(localDate, DateTimeKind.Unspecified), AppInfo.TimeZone); + + private static string? Str(Dictionary r, string k) => r.GetValueOrDefault(k) is { } v ? Convert.ToString(v, CultureInfo.InvariantCulture) : null; + private static double? Dbl(Dictionary r, string k) => r.GetValueOrDefault(k) is { } v and not DBNull ? Convert.ToDouble(v, CultureInfo.InvariantCulture) : null; + private static int? Int(Dictionary r, string k) => r.GetValueOrDefault(k) is { } v and not DBNull ? Convert.ToInt32(v, CultureInfo.InvariantCulture) : null; + private static long? Long(Dictionary r, string k) => r.GetValueOrDefault(k) is { } v and not DBNull ? Convert.ToInt64(v, CultureInfo.InvariantCulture) : null; + private static string Num(Dictionary r, string k, int digits) => Dbl(r, k) is { } d ? Fmt(d, digits) : ""; + private static string Fmt(double v, int digits) => double.IsNaN(v) ? "" : v.ToString(digits == 0 ? "0" : "0." + new string('#', digits), It); + private static string YesNo(Dictionary r, string k) => r.GetValueOrDefault(k) is bool b ? (b ? "si" : "no") : ""; + + private static string Ts(Dictionary r, string k) => r.GetValueOrDefault(k) switch + { + DateTime d => AppInfo.ToLocal(d.Kind == DateTimeKind.Utc ? d : DateTime.SpecifyKind(d, DateTimeKind.Utc)).ToString("dd/MM/yyyy HH:mm:ss", It), + DateTimeOffset o => AppInfo.ToLocal(o.UtcDateTime).ToString("dd/MM/yyyy HH:mm:ss", It), + _ => "" + }; + + private static string TypeLabel(string? t) => t switch { "Auto" => "auto", "Manuale" => "manuale", _ => "" }; + + internal static string KindLabel(string? kind) => kind switch + { + LossReasons.Kind.Punta => "Punta", + LossReasons.Kind.Esplora => "Esplora", + LossReasons.Kind.EvNegativo => "No", + LossReasons.Kind.NonPronto => "NonPronto", + LossReasons.Kind.SenzaStima => "SenzaStima", + LossReasons.Kind.SoloLimiti => "SoloLimiti", + LossReasons.Kind.PrezzoMassimo => "PrezzoMax", + LossReasons.Kind.PuntateAsta => "PuntateAsta", + LossReasons.Kind.PuntateSessione => "PuntateSessione", + LossReasons.Kind.PuntateResidue => "Soglia", + LossReasons.Kind.FasciaOraria => "FasciaOraria", + LossReasons.Kind.Rischio => "Rischio", + LossReasons.Kind.InTesta => "InTesta", + LossReasons.Kind.Cooldown => "Pausa", + LossReasons.Kind.NonAperta => "NonAperta", + LossReasons.Kind.Manuale => "Manuale", + null => "", + _ => kind + }; +} diff --git a/Mimante/src/BidooBidBot/Data/DataRetention.cs b/Mimante/src/BidooBidBot/Data/DataRetention.cs new file mode 100644 index 0000000..85f61b6 --- /dev/null +++ b/Mimante/src/BidooBidBot/Data/DataRetention.cs @@ -0,0 +1,123 @@ +using System.Globalization; +using BidooBidBot.Logging; + +namespace BidooBidBot.Data; + +/// +/// Il tetto dei dati (specifica §8.4): se il database supera DataCapGb si libera spazio +/// dalle partizioni più vecchie, in un ordine che sacrifica prima ciò che serve meno al +/// modello, e ci si ferma sotto il 90% del tetto. +/// +/// +/// decisioni delle aste senza mie puntate (righe filtrate, poi la partizione si compatta); +/// reset (partizioni intere); +/// puntate delle aste senza mie puntate (righe filtrate, poi compattazione); +/// puntate restanti (partizioni intere); +/// decisioni restanti (partizioni intere). +/// +/// +/// Le partizioni del mese corrente e del prossimo non si toccano mai; nemmeno le tabelle +/// di riepilogo (aste, mie puntate, previsioni, prodotti, puntatori, rischio, documenti, +/// impostazioni). Una cancellazione filtrata non restituisce spazio con il solo +/// DELETE: la partizione, vecchia e ormai ferma, si riscrive con VACUUM FULL. +/// +public sealed class DataRetention +{ + private readonly Db _db; + private readonly AppLog _log; + private readonly Func> _measure; + + /// Dimensione del database in byte; nei test la si simula. + public DataRetention(Db db, AppLog log, Func>? measure = null) + { + _db = db; + _log = log; + _measure = measure ?? (() => MeasureAsync(db)); + } + + public static async Task MeasureAsync(Db db) => + await db.ScalarAsync("SELECT pg_database_size(current_database())").ConfigureAwait(false); + + public sealed record Step(string Table, string? KeepFilter, string Description); + + /// L'ordine dei sacrifici. KeepFilter null = partizione intera. + public static readonly IReadOnlyList Order = new[] + { + new Step("bot_decisions", "NOT has_my_bid", "decisioni delle aste senza mie puntate"), + new Step("resets", null, "reset"), + new Step("bids", "NOT EXISTS (SELECT 1 FROM my_bids m WHERE m.auction_id = {0}.auction_id)", "puntate delle aste senza mie puntate"), + new Step("bids", null, "puntate"), + new Step("bot_decisions", null, "decisioni") + }; + + public sealed record Result(long BytesBefore, long BytesAfter, long CapBytes, int Actions, IReadOnlyList Lines) + { + public double UsedFraction => CapBytes > 0 ? (double)BytesAfter / CapBytes : 0; + } + + /// Un giro di rotazione. fissa il mese corrente (protetto). + public async Task RunAsync(double capGb, DateTime today, CancellationToken ct) + { + var cap = (long)(Math.Max(0.001, capGb) * 1024 * 1024 * 1024); + var target = (long)(cap * 0.9); + var before = await _measure().ConfigureAwait(false); + var lines = new List(); + var size = before; + + if (size <= cap) + return new Result(before, size, cap, 0, lines); + + _log.Warn("MANUTENZIONE", $"Database a {Gb(size)} oltre il tetto di {Gb(cap)}: libero spazio dalle partizioni più vecchie"); + var protectedFrom = new DateTime(today.Year, today.Month, 1, 0, 0, 0, DateTimeKind.Utc); + var touched = new HashSet(StringComparer.Ordinal); + + foreach (var step in Order) + { + if (size < target) break; + var partitions = await Partitions.ListAsync(_db, step.Table).ConfigureAwait(false); + foreach (var p in partitions.Where(x => x.Month < protectedFrom)) + { + ct.ThrowIfCancellationRequested(); + if (size < target) break; + + string line; + if (step.KeepFilter != null) + { + var where = string.Format(CultureInfo.InvariantCulture, step.KeepFilter, p.Name); + var deleted = await _db.ExecuteAsync($"DELETE FROM {p.Name} WHERE {where}").ConfigureAwait(false); + if (deleted == 0) continue; + await _db.ExecuteAsync($"VACUUM FULL {p.Name}").ConfigureAwait(false); + line = $"{p.Name}: tolte {deleted.ToString("N0", It)} righe di {step.Description}"; + } + else + { + await _db.ExecuteAsync($"ALTER TABLE {step.Table} DETACH PARTITION {p.Name}").ConfigureAwait(false); + await _db.ExecuteAsync($"DROP TABLE {p.Name}").ConfigureAwait(false); + line = $"{p.Name}: partizione di {step.Description} cancellata ({Gb(p.Bytes)})"; + } + + touched.Add(step.Table); + lines.Add(line); + _log.Info("MANUTENZIONE", line); + size = await _measure().ConfigureAwait(false); + } + } + + foreach (var table in touched) + { + try { await _db.ExecuteAsync($"VACUUM (ANALYZE) {table}").ConfigureAwait(false); } + catch (Exception ex) { _log.Warn("MANUTENZIONE", $"VACUUM su {table} non riuscito: {ex.Message}"); } + } + + var summary = size < target + ? $"Rotazione finita: da {Gb(before)} a {Gb(size)} (tetto {Gb(cap)})" + : $"Rotazione finita ma il database resta a {Gb(size)}: restano solo dati protetti (mese corrente e riepiloghi); alza il tetto"; + _log.Write(size < target ? LogLevel.Info : LogLevel.Warning, "MANUTENZIONE", summary); + return new Result(before, size, cap, lines.Count, lines); + } + + private static readonly CultureInfo It = CultureInfo.GetCultureInfo("it-IT"); + + public static string Gb(long bytes) => + bytes >= 1L << 30 ? (bytes / (double)(1L << 30)).ToString("0.00", It) + " GB" : (bytes / (double)(1L << 20)).ToString("0.0", It) + " MB"; +} diff --git a/Mimante/src/BidooBidBot/Data/Db.cs b/Mimante/src/BidooBidBot/Data/Db.cs index 7fcb2af..454643b 100644 --- a/Mimante/src/BidooBidBot/Data/Db.cs +++ b/Mimante/src/BidooBidBot/Data/Db.cs @@ -198,3 +198,10 @@ public static class RowExtensions return d; } } + +/// I due mondi dell'archivio: il sito vero e il simulatore (auctions.type). +public static class Worlds +{ + public const string Real = "normal"; + public const string Simulator = "sim"; +} diff --git a/Mimante/src/BidooBidBot/Data/Maintenance.cs b/Mimante/src/BidooBidBot/Data/Maintenance.cs new file mode 100644 index 0000000..e05d1ec --- /dev/null +++ b/Mimante/src/BidooBidBot/Data/Maintenance.cs @@ -0,0 +1,195 @@ +using System.Globalization; +using System.IO.Compression; +using System.Text; +using BidooBidBot.Config; +using BidooBidBot.Logging; +using BidooBidBot.Settings; + +namespace BidooBidBot.Data; + +/// +/// Il copione notturno (specifica §8.4-8.5): alle 04:30, quando Bidoo è fermo, partizioni del +/// mese prossimo, rotazione dei dati sotto il tetto, pulizia dei registri su file, backup +/// logico delle tabelle di riepilogo. All'avvio gira solo la parte leggera (partizioni e +/// rotazione). Il registro della manutenzione va nel file applicativo, non nel database. +/// +public sealed class Maintenance +{ + private readonly Db _db; + private readonly WriteQueue _queue; + private readonly ConfigPaths _paths; + private readonly Func _settings; + private readonly AppLog _log; + private readonly DataRetention _retention; + private readonly SemaphoreSlim _gate = new(1, 1); + + public Maintenance(Db db, WriteQueue queue, ConfigPaths paths, Func settings, AppLog log) + { + _db = db; + _queue = queue; + _paths = paths; + _settings = settings; + _log = log; + _retention = new DataRetention(db, log); + } + + /// Tabelle salvate ogni notte: le non partizionate più mie puntate e previsioni. + public static readonly string[] BackupTables = + { + "schema_migrations", "settings", "documents", "items", "auctions", "my_bids", "auction_forecasts", "bidders", + "risk_ledger", "products", "watched_products", "product_stats" + }; + + public long? LastSizeBytes { get; private set; } + public long CapBytes => (long)(Math.Max(0.001, _settings().DataCapGb) * 1024 * 1024 * 1024); + public DateTime? LastRunUtc { get; private set; } + public string? LastSummary { get; private set; } + public bool Running => _gate.CurrentCount == 0; + + /// Scatta quando l'uso supera il 90% del tetto (Telegram, barra). + public event Action? NearCap; + + /// Il copione ogni giorno alle 04:30 locali, più la parte leggera subito. + public Task RunAsync(CancellationToken ct) => Task.Run(async () => + { + await RunOnceAsync(full: false, ct).ConfigureAwait(false); + while (!ct.IsCancellationRequested) + { + var now = AppInfo.LocalNow; + var next = now.Date.AddHours(4).AddMinutes(30); + if (next <= now) next = next.AddDays(1); + try { await Task.Delay(next - now, ct).ConfigureAwait(false); } + catch (OperationCanceledException) { return; } + await RunOnceAsync(full: true, ct).ConfigureAwait(false); + } + }, ct); + + /// Un giro. aggiunge registri e backup. + public async Task RunOnceAsync(bool full, CancellationToken ct) + { + if (!await _gate.WaitAsync(0, ct).ConfigureAwait(false)) return "Manutenzione già in corso"; + var parts = new List(); + try + { + var settings = _settings(); + var today = DateTime.UtcNow; + + var created = await Partitions.EnsureAsync(_db, today).ConfigureAwait(false); + if (created > 0) parts.Add($"{created} partizioni nuove"); + + await _queue.FlushAsync(TimeSpan.FromSeconds(30)).ConfigureAwait(false); + var result = await _retention.RunAsync(settings.DataCapGb, today, ct).ConfigureAwait(false); + LastSizeBytes = result.BytesAfter; + parts.Add($"database {DataRetention.Gb(result.BytesAfter)} su {DataRetention.Gb(result.CapBytes)}"); + if (result.Actions > 0) parts.Add($"{result.Actions} passi di rotazione"); + if (result.BytesAfter > result.CapBytes * 0.9) NearCap?.Invoke(result.BytesAfter, result.CapBytes); + + if (full) + { + var logs = CleanLogs(settings.LogRetentionDays); + if (logs > 0) parts.Add($"{logs} registri vecchi cancellati"); + var backup = await BackupAsync(settings.BackupRetentionDays, ct).ConfigureAwait(false); + parts.Add(backup); + } + + LastRunUtc = DateTime.UtcNow; + LastSummary = string.Join("; ", parts); + _log.Info("MANUTENZIONE", LastSummary); + return LastSummary; + } + catch (OperationCanceledException) + { + return "Manutenzione interrotta"; + } + catch (Exception ex) + { + LastSummary = $"Manutenzione non riuscita: {ex.Message}"; + _log.Error("MANUTENZIONE", LastSummary); + return LastSummary; + } + finally + { + _gate.Release(); + } + } + + /// Solo la misura, per la barra (non tocca nulla). + public async Task MeasureAsync() + { + try + { + LastSizeBytes = await DataRetention.MeasureAsync(_db).ConfigureAwait(false); + return LastSizeBytes; + } + catch + { + return LastSizeBytes; + } + } + + /// Cancella i file di registro più vecchi di giorni (0 = mai). + public int CleanLogs(int days) => CleanLogs(_paths.Logs, days, DateTime.Today); + + internal static int CleanLogs(string folder, int days, DateTime today) + { + if (days <= 0 || !Directory.Exists(folder)) return 0; + var limit = today.AddDays(-days); + var n = 0; + foreach (var file in Directory.EnumerateFiles(folder, "*.log")) + { + var name = Path.GetFileNameWithoutExtension(file); + if (name.Length < 10) continue; + if (!DateTime.TryParseExact(name[^10..], "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var day)) continue; + if (day >= limit) continue; + try { File.Delete(file); n++; } catch (IOException) { } + } + return n; + } + + /// + /// Il backup logico: una cartella per giorno con un .csv.gz per tabella + /// (COPY … TO STDOUT). Il grosso (bids) resta al backup del container PostgreSQL. + /// + public async Task BackupAsync(int keepDays, CancellationToken ct) + { + var day = AppInfo.LocalNow.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture); + var folder = Path.Combine(_paths.Backups, day); + Directory.CreateDirectory(folder); + long total = 0; + + await using (var conn = await _db.Writer.OpenConnectionAsync(ct).ConfigureAwait(false)) + { + foreach (var table in BackupTables) + { + var file = Path.Combine(folder, table + ".csv.gz"); + var tmp = file + ".tmp"; + using (var reader = await conn.BeginTextExportAsync($"COPY {table} TO STDOUT (FORMAT csv, HEADER)", ct).ConfigureAwait(false)) + await using (var fs = File.Create(tmp)) + await using (var gz = new GZipStream(fs, CompressionLevel.Optimal)) + await using (var w = new StreamWriter(gz, new UTF8Encoding(false))) + { + var buffer = new char[64 * 1024]; + int read; + while ((read = await reader.ReadAsync(buffer, ct).ConfigureAwait(false)) > 0) + await w.WriteAsync(buffer.AsMemory(0, read), ct).ConfigureAwait(false); + } + File.Move(tmp, file, overwrite: true); + total += new FileInfo(file).Length; + } + } + + var removed = 0; + if (keepDays > 0) + { + var limit = AppInfo.LocalNow.Date.AddDays(-keepDays); + foreach (var dir in Directory.EnumerateDirectories(_paths.Backups)) + { + if (!DateTime.TryParseExact(Path.GetFileName(dir), "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var d)) continue; + if (d >= limit) continue; + try { Directory.Delete(dir, recursive: true); removed++; } catch (IOException) { } + } + } + + return $"backup {day} ({DataRetention.Gb(total)}, {BackupTables.Length} tabelle)" + (removed > 0 ? $", {removed} backup vecchi tolti" : ""); + } +} diff --git a/Mimante/src/BidooBidBot/Engine/AuctionMonitor.Bidding.cs b/Mimante/src/BidooBidBot/Engine/AuctionMonitor.Bidding.cs new file mode 100644 index 0000000..b84a6ce --- /dev/null +++ b/Mimante/src/BidooBidBot/Engine/AuctionMonitor.Bidding.cs @@ -0,0 +1,215 @@ +using BidooBidBot.Bidoo; +using BidooBidBot.Data; +using BidooBidBot.Logging; +using BidooBidBot.Ml; +using BidooBidBot.Strategy; + +namespace BidooBidBot.Engine; + +public sealed partial class AuctionMonitor +{ + /// + /// Il verdetto del ciclo, 60 ms prima del fuoco (portato dal legacy). La strategia decide; + /// qui si registra la decisione (anche in Osserva: è ciò di cui il modello si nutre), si + /// scrive una riga per tipo nel registro dell'asta e si prepara la puntata. + /// + public bool EvaluateBid(AuctionInfo a, AuctionState s, bool shadow) + { + a.PendingDecisionId = null; + a.PendingDecisionKind = null; + a.PendingPWin = null; + + if (s.IsMyBid) return false; + + if (s.Status is not (AuctionStatus.Running or AuctionStatus.Pending)) + { + a.Log.AddDecision(LossReasons.Kind.NonAperta, $"Asta non aperta ({s.Status}): niente puntata", LogLevel.Warning); + return false; + } + + var settings = Settings; + var nowLocal = AppInfo.LocalNow; + BidDecision decision; + try + { + decision = _d.Strategy.Decide(a, s, settings, _auctions.Values.ToList(), shadow, _d.Account.Username, nowLocal); + } + catch (Exception ex) + { + a.Log.Add($"Decisione non riuscita: {ex.Message}", LogLevel.Error, AuctionLogCategory.Decision); + return false; + } + + var action = decision.ShouldBid ? "BID" : "NO-OP"; + var forecast = a.Forecast as ForecastResult; + var balance = _d.Account.Balance; + var lead = a.LeadMs; + + var state = new DecisionState + { + Ctx = decision.Context, Price = s.Price, Timer = Math.Round(s.Timer, 2), LastBidder = s.LastBidder, PingMs = s.PollingLatencyMs, + BidsUsed = a.MyBidsForLimits, Resets = a.ResetCount, Balance = balance.Total, Paid = balance.Paid, Free = balance.Free, + Mode = RunModes.ToKey(a.Mode), Live = !shadow, BuyNow = a.BuyNowPrice, Shipping = a.Shipping, + ForecastClose = forecast?.Close, ForecastP10 = forecast?.P10, ForecastP90 = forecast?.P90 + }; + + var id = _d.Recorder.RecordDecision(a, s, new DecisionRecord( + decision.Kind, action, decision.PModel, decision.PBandit, decision.OwnBidFactor, decision.PWin, decision.Ev, + decision.BidCost, decision.Value, decision.Reason, decision.ContextKey, + decision.FromModel ? _d.Learning.Champion : null, decision.FromModel ? _d.Learning.ModelVersion : null, + decision.AltAction, lead, shadow, state)); + + var verb = !decision.ShouldBid ? "no" : decision.Kind == LossReasons.Kind.Esplora ? "esplora" : "punta"; + _d.Learning.RecordDecision(new LearningService.Decision(DateTime.UtcNow, a.Id, a.Name, s.Price, decision.PWin ?? 0, + decision.Ev ?? 0, verb, decision.Kind, decision.Reason, shadow)); + + a.LastDecision = new DecisionView(decision.Kind, decision.ShouldBid, shadow, decision.PModel, decision.PWin, decision.Ev, + decision.BidCost, decision.Reason, DateTime.UtcNow); + a.Touch(); + + if (!decision.ShouldBid) + { + a.Log.AddDecision(decision.Kind, (shadow ? "Non avrei puntato: " : "Non punto: ") + decision.Reason); + return false; + } + + if (shadow) + { + a.Log.AddDecision(decision.Kind, $"Avrei puntato a {Euro(s.Price)}: {decision.Reason}"); + return false; + } + + a.PendingDecisionId = id; + a.PendingDecisionKind = decision.Kind; + a.PendingPWin = decision.PWin; + a.Log.AddDecision(decision.Kind, + (decision.Kind == LossReasons.Kind.Esplora ? "Esploro" : "Punto") + $" a {Euro(s.Price)}: {decision.Reason}", LogLevel.Success); + return true; + } + + /// + /// La puntata, sul thread del cecchino: la chiamata è sincrona perché il thread esiste solo + /// per questo. Si misura l'errore d'attesa, si invia sulla corsia (con un solo ripiego sul + /// pool se la corsia cade e c'è tempo), e si registra tutto. + /// + public void FireBid(AuctionInfo a, AuctionState s, int leadMs, long fireTicks) + { + var waitErrorMs = -PrecisionWait.MsUntil(fireTicks); + var actualLeadMs = a.EstimatedRemainingMs(); + var p50 = Math.Max(60, _d.Latency.Snapshot().P50); + + BidAttempt? result; + try + { + result = _d.Api.PlaceBidAsync(a.Id, a.Url, a.EstimatedRemainingMs, p50, _life.Token).GetAwaiter().GetResult(); + } + catch (OperationCanceledException) + { + return; + } + catch (Exception ex) + { + a.Log.Add($"Puntata non inviata: {ex.Message}", LogLevel.Error, AuctionLogCategory.Bid); + _d.Log.Error("PUNTATA", $"{a.Name}: non inviata ({ex.Message})", a.Id); + return; + } + + CompleteBid(a, s, result, leadMs, actualLeadMs, waitErrorMs, manual: false); + } + + /// + /// «Punta adesso» dall'interfaccia: una puntata fuori dal modello, registrata come + /// manuale (non entra nel giudizio del modello). Bloccata in modalità OSSERVA, con il + /// rischio fermo, e sulle aste Ferma, concluse o già in testa. + /// + public async Task<(bool Ok, string Message)> BidNowAsync(string id, CancellationToken ct) + { + var a = Find(id); + if (a == null) return (false, "Asta non in elenco"); + if (World == Worlds.Real && !Settings.LiveBiddingEnabled) + return (false, "Modalità OSSERVA: nessuna puntata parte. Passa a DAL VIVO dalle impostazioni per puntare davvero"); + if (_d.Risk.Halted) return (false, "Il gestore del rischio ha fermato le puntate: riprendi dalla barra in alto"); + if (a.IsFinished) return (false, "Asta conclusa"); + if (a.Mode == RunMode.Stopped) return (false, "Asta Ferma: mettila in Osserva o Attiva"); + var s = a.LastState; + if (s == null) return (false, "Asta non ancora letta: aspetta la prima risposta"); + if (s.IsMyBid) return (false, "Sei già in testa"); + if (s.Status is not (AuctionStatus.Running or AuctionStatus.Pending)) return (false, "Asta non aperta"); + + var p50 = Math.Max(60, _d.Latency.Snapshot().P50); + var result = await _d.Api.PlaceBidAsync(a.Id, a.Url, a.EstimatedRemainingMs, p50, ct).ConfigureAwait(false); + a.PendingDecisionId = null; + a.PendingDecisionKind = LossReasons.Kind.Manuale; + a.PendingPWin = null; + CompleteBid(a, s, result, 0, a.EstimatedRemainingMs(), 0, manual: true); + return result.Success ? (true, $"Puntata a {Euro(s.Price)} riuscita") : (false, $"Puntata rifiutata: {result.Error}"); + } + + private void CompleteBid(AuctionInfo a, AuctionState s, BidAttempt result, int leadMs, double actualLeadMs, double waitErrorMs, bool manual) + { + var settings = Settings; + var cost = BidStrategy.EffectiveBidCost(settings, _d.Account.Balance); + var late = !result.Success && IsLateBidError(result.Error); + + a.LastClickAtUtc = DateTime.UtcNow; + _d.Strategy.NoteBidSent(a, result.Success); + if (!manual) _d.Latency.NoteBid(result.LatencyMs, late); + if (late) a.TimerExpiredCount++; + + var r = result.Response; + if (result.Success) + { + _d.Risk.NoteBidSpent(a.Id, cost); + a.MyBidsPlaced++; + a.MyBidsCost += cost; + a.BidsUsedOnAuction = r.UsedOnAuction ?? (a.BidsUsedOnAuction ?? 0) + 1; + if (r.PaidRemaining is { } paid && r.FreeRemaining is { } free) _d.Account.SetBids(paid, free); + else if (r.Remaining is { } total) _d.Account.SetTotal(total); + if (a.PendingDecisionKind == LossReasons.Kind.Esplora) _d.Learning.NoteExplorationBid(); + } + + _d.Recorder.For(a.Id)?.MyBid(s.Price, leadMs, actualLeadMs, waitErrorMs, s.PollingLatencyMs, result.LatencyMs, result.Success, + result.Error, a.BidsUsedOnAuction, r.Remaining, r.PaidRemaining, r.FreeRemaining, a.PendingDecisionId, a.PendingPWin, + a.PendingDecisionKind, manual); + + var how = manual ? "Puntata manuale" : "Puntata"; + if (result.Success) + { + var account = r.Remaining is { } rem + ? $", {rem:N0} puntate residue" + (r.PaidRemaining is { } p && r.FreeRemaining is { } f ? $" ({p} a pagamento + {f} gratis)" : "") + : ""; + var fallback = result.UsedFallback ? " (ripiego sul pool)" : ""; + a.Log.Add($"{how} a {Euro(s.Price)} riuscita in {result.LatencyMs} ms{fallback}{account}, {a.BidsUsedOnAuction} usate su questa asta", + LogLevel.Success, AuctionLogCategory.Bid); + _d.Log.Success("PUNTATA", $"{a.Name}: {Euro(s.Price)} in {result.LatencyMs} ms{account}", a.Id); + } + else + { + a.Log.Add($"{how} a {Euro(s.Price)} rifiutata: {result.Error}", LogLevel.Error, AuctionLogCategory.Bid); + _d.Log.Warn("PUNTATA", $"{a.Name}: rifiutata ({result.Error})", a.Id); + + if (late && settings.ShowLateBidWarning) + { + var adaptive = _d.Latency.RecommendedLeadMs(settings); + var net = s.PollingLatencyMs + result.LatencyMs; + a.Log.Add(a.LeadIsManual && a.LeadMs > 0 + ? $"Arrivata tardi (rete circa {net} ms). L'anticipo di quest'asta è fisso a {a.LeadMs} ms: il modello consiglierebbe {adaptive} ms" + : $"Arrivata tardi (rete circa {net} ms): anticipo adattivo portato a {adaptive} ms", + LogLevel.Warning, AuctionLogCategory.Timing); + } + } + + a.Touch(); + try { BidPlaced?.Invoke(a, result); } catch { /* chi ascolta non ferma il motore */ } + } + + /// Un rifiuto che dice «troppo tardi»: il ciclo era già chiuso quando la puntata è arrivata. + internal static bool IsLateBidError(string? error) + { + if (string.IsNullOrEmpty(error)) return false; + return error.Contains("timer", StringComparison.OrdinalIgnoreCase) || + error.Contains("scadut", StringComparison.OrdinalIgnoreCase) || + error.Contains("closed", StringComparison.OrdinalIgnoreCase) || + error.Contains("ended", StringComparison.OrdinalIgnoreCase); + } +} diff --git a/Mimante/src/BidooBidBot/Engine/AuctionMonitor.Commands.cs b/Mimante/src/BidooBidBot/Engine/AuctionMonitor.Commands.cs new file mode 100644 index 0000000..1fefb81 --- /dev/null +++ b/Mimante/src/BidooBidBot/Engine/AuctionMonitor.Commands.cs @@ -0,0 +1,293 @@ +using System.Text.Json; +using BidooBidBot.Bidoo; +using BidooBidBot.Data; +using BidooBidBot.Logging; +using BidooBidBot.Products; + +namespace BidooBidBot.Engine; + +/// Un'asta da aggiungere: l'indirizzo (o il numero) e, se viene dal catalogo, ciò che già se ne sa. +public sealed record AddAuctionRequest( + string Input, string Origin = "mano", RunMode? Mode = null, string? Name = null, string? ImageUrl = null, + double? BuyNowPrice = null, int ProductId = 0); + +public sealed partial class AuctionMonitor +{ + // ── Aggiunta e rimozione ───────────────────────────────────────────── + + /// + /// Aggiunge un'asta: legge la pagina (nome, Compralo Ora, spedizione, limite di vincita, + /// foto), applica i paletti del prodotto o i predefiniti, prepara la registrazione. Il + /// motore parte al giro successivo del supervisore, se il modo non è Ferma. + /// + public async Task<(AuctionInfo? Auction, string Message)> AddAsync(AddAuctionRequest req, CancellationToken ct) + { + var parsed = AuctionUrl.Parse(req.Input, References); + if (parsed is not { } p) return (null, "Indirizzo o numero d'asta non riconosciuto"); + if (Find(p.AuctionId) is { } existing) return (existing, $"'{existing.Name}' è già in elenco"); + + AuctionPageInfo? page = null; + try { page = await _d.Api.GetAuctionPageAsync(p.AuctionId, p.Url, ct).ConfigureAwait(false); } + catch (OperationCanceledException) { throw; } + catch (Exception ex) { _d.Log.Debug("ASTE", $"Pagina dell'asta {p.AuctionId} non letta: {ex.Message}"); } + + var settings = Settings; + var name = FirstNonEmpty(page?.Name, req.Name, p.ProductName) ?? $"Asta {p.AuctionId}"; + var key = ProductKey.From(name); + var product = _d.Products.Find(key); + var limits = ProductRules.Resolve(product, settings, autoAdded: req.Origin != "mano"); + + var a = new AuctionInfo(p.AuctionId) + { + Name = name, + Url = p.Url, + ProductKey = key, + BidooProductId = page?.ProductId ?? req.ProductId, + ImageUrl = FirstNonEmpty(page?.ImageUrl, req.ImageUrl), + Origin = req.Origin, + BuyNowPrice = page?.BuyNowPrice ?? req.BuyNowPrice, + Shipping = page?.Shipping, + WinLimit = page?.WinLimit, + ProductInfoLoaded = page != null, + MaxPrice = limits.MaxPrice, + MaxBids = limits.MaxBids, + Mode = req.Mode ?? limits.Mode + }; + + if (!_auctions.TryAdd(a.Id, a)) return (Find(a.Id), $"'{name}' è già in elenco"); + WireLog(a); + await _d.Recorder.PrepareAsync(a).ConfigureAwait(false); + + var from = limits.FromProduct ? "paletti del prodotto" : "paletti predefiniti"; + a.Log.Add($"Aggiunta ({OriginLabel(a.Origin)}) in {RunModes.Label(a.Mode)}: {from}, prezzo max {LimitText(a.MaxPrice)}, puntate max {LimitText(a.MaxBids)}", + LogLevel.Info, AuctionLogCategory.Status); + if (page == null) a.Log.Add("Pagina dell'asta non letta: Compralo Ora e spedizione ignoti per ora", LogLevel.Warning, AuctionLogCategory.Product); + _d.Log.Info("ASTE", $"Aggiunta '{name}' ({OriginLabel(a.Origin)}, {RunModes.Label(a.Mode)})", a.Id); + MarkDirty(); + return (a, $"'{name}' aggiunta in {RunModes.Label(a.Mode)}"); + } + + /// + /// Toglie un'asta: il motore si ferma al giro del supervisore; se non era conclusa la + /// registrazione resta marcata come interrotta, e la sorveglianza dei prodotti non la + /// ripropone. + /// + public bool Remove(string id, string reason = "tolta dall'utente", bool markProduct = true) + { + if (!_auctions.TryRemove(id, out var a)) return false; + if (!a.IsFinished) _d.Recorder.Abandon(id, reason); + if (markProduct && !string.IsNullOrEmpty(a.ProductKey)) _d.Products.MarkRemoved(a.ProductKey, id); + _d.Log.Info("ASTE", $"Tolta '{a.Name}' ({reason})", id); + MarkDirty(); + return true; + } + + /// Toglie tutte le aste concluse; restituisce quante. + public int RemoveFinished() + { + var n = 0; + foreach (var a in _auctions.Values.Where(x => x.IsFinished).ToList()) + if (Remove(a.Id, "pulizia delle concluse", markProduct: false)) n++; + return n; + } + + // ── Modo e paletti ─────────────────────────────────────────────────── + + public (bool Ok, string Message) SetMode(string id, RunMode mode) + { + var a = Find(id); + if (a == null) return (false, "Asta non in elenco"); + if (a.IsFinished) return (false, "Asta conclusa"); + if (a.Mode == mode) return (true, $"Già in {RunModes.Label(mode)}"); + + var before = a.Mode; + a.Mode = mode; + a.Log.Add($"Modo: {RunModes.Label(before)} -> {RunModes.Label(mode)}", LogLevel.Info, AuctionLogCategory.Status); + + var note = ""; + if (mode == RunMode.Active && World == Worlds.Real && !Settings.LiveBiddingEnabled) + { + note = ": la modalità globale è OSSERVA, quindi l'asta decide e registra ma non punta"; + a.Log.Add("Attiva con modalità globale OSSERVA: nessuna puntata parte finché non passi a DAL VIVO", LogLevel.Warning, AuctionLogCategory.Status); + } + MarkDirty(); + return (true, $"'{a.Name}' in {RunModes.Label(mode)}{note}"); + } + + /// Lo stesso modo per tutte le aste non concluse; restituisce quante sono cambiate. + public int SetAllModes(RunMode mode) + { + var n = 0; + foreach (var a in _auctions.Values.Where(x => !x.IsFinished && x.Mode != mode)) + { + var before = a.Mode; + a.Mode = mode; + a.Log.Add($"Modo: {RunModes.Label(before)} -> {RunModes.Label(mode)} (tutte le aste)", LogLevel.Info, AuctionLogCategory.Status); + n++; + } + if (n > 0) + { + _d.Log.Info("ASTE", $"{n} aste in {RunModes.Label(mode)}"); + MarkDirty(); + } + return n; + } + + /// + /// I paletti di un'asta dal pannello. null o 0 = anticipo + /// adattivo; null = come il prodotto o le impostazioni. + /// + public (bool Ok, string Message) SetLimits(string id, double maxPrice, int maxBids, int? manualLeadMs, bool? quietHours) + { + var a = Find(id); + if (a == null) return (false, "Asta non in elenco"); + if (maxPrice < 0 || maxBids < 0) return (false, "I paletti non possono essere negativi"); + + var s = Settings; + a.MaxPrice = Math.Round(maxPrice, 2); + a.MaxBids = maxBids; + a.QuietHoursOverride = quietHours; + if (manualLeadMs is > 0 and var lead) + { + a.LeadIsManual = true; + a.LeadMs = Math.Clamp(lead, Math.Max(50, s.LeadMinMs / 2), Math.Max(s.LeadMaxMs, 3000)); + } + else + { + a.LeadIsManual = false; + } + a.Touch(); + + var leadText = a.LeadIsManual ? $"{a.LeadMs} ms fisso" : "adattivo"; + var quiet = quietHours is { } q ? (q ? "sì" : "no") : "come il prodotto"; + a.Log.Add($"Paletti: prezzo max {LimitText(a.MaxPrice)}, puntate max {LimitText(a.MaxBids)}, anticipo {leadText}, fascia oraria {quiet}", + LogLevel.Info, AuctionLogCategory.Status); + _d.Recorder.UpdateProductInfo(a); + MarkDirty(); + return (true, "Paletti salvati"); + } + + /// + /// Tutte le aste Attive passano in Osserva: database giù, sessione scaduta, arresto del + /// rischio. Restituisce quante. + /// + public int ForceAllObserve(string reason) + { + var n = 0; + foreach (var a in _auctions.Values.Where(x => x.Mode == RunMode.Active && !x.IsFinished)) + { + a.Mode = RunMode.Watch; + a.Log.Add($"Passata in Osserva: {reason}", LogLevel.Warning, AuctionLogCategory.Status); + n++; + } + if (n > 0) + { + _d.Log.Warn("ASTE", $"{n} aste Attive passate in Osserva: {reason}"); + MarkDirty(); + } + return n; + } + + /// Rilegge la pagina dell'asta (Compralo Ora, spedizione, foto) se all'aggiunta non era riuscito. + public async Task RefreshProductInfoAsync(string id, CancellationToken ct) + { + var a = Find(id); + if (a == null) return false; + var page = await _d.Api.GetAuctionPageAsync(a.Id, a.Url, ct).ConfigureAwait(false); + if (page == null) return false; + + if (!string.IsNullOrWhiteSpace(page.Name)) a.Name = page.Name; + a.BuyNowPrice = page.BuyNowPrice ?? a.BuyNowPrice; + a.Shipping = page.Shipping ?? a.Shipping; + a.WinLimit = page.WinLimit ?? a.WinLimit; + a.ImageUrl = FirstNonEmpty(page.ImageUrl, a.ImageUrl); + if (page.ProductId is > 0) a.BidooProductId = page.ProductId.Value; + a.ProductInfoLoaded = true; + a.Touch(); + a.Log.Add($"Pagina letta: Compralo Ora {(a.BuyNowPrice is { } b ? Euro(b) : "ignoto")}, spedizione {(a.Shipping is { } sh ? Euro(sh) : "ignota")}", + LogLevel.Info, AuctionLogCategory.Product); + _d.Recorder.UpdateProductInfo(a); + MarkDirty(); + return true; + } + + // ── Ripristino all'avvio ───────────────────────────────────────────── + + /// + /// Rimette in elenco le aste salvate. Il modo è quello salvato se «ricorda gli stati» è + /// acceso, altrimenti quello scelto per l'avvio (predefinito Ferma: dopo un riavvio non + /// parte nulla senza che l'utente lo veda). + /// + public async Task RestoreAsync() + { + var json = _d.Documents.Get(_d.DocumentKey); + if (string.IsNullOrWhiteSpace(json)) return 0; + + List? list; + try { list = JsonSerializer.Deserialize>(json); } + catch (JsonException ex) + { + _d.Log.Warn("ASTE", $"Elenco salvato illeggibile, si riparte vuoti: {ex.Message}"); + return 0; + } + if (list == null) return 0; + + var settings = Settings; + var startMode = RunModes.Parse(settings.DefaultStartAuctionsOnLoad, RunMode.Stopped); + var n = 0; + foreach (var snap in list.Where(x => !string.IsNullOrEmpty(x.Id))) + { + var a = new AuctionInfo(snap.Id) + { + Name = snap.Name, Url = snap.Url, ProductKey = string.IsNullOrEmpty(snap.ProductKey) ? ProductKey.From(snap.Name) : snap.ProductKey, + BidooProductId = snap.BidooProductId, ImageUrl = snap.ImageUrl, Origin = snap.Origin, AddedAtUtc = snap.AddedAtUtc, + LeadMs = snap.LeadMs, LeadIsManual = snap.LeadIsManual, MaxPrice = snap.MaxPrice, MaxBids = snap.MaxBids, + QuietHoursOverride = snap.QuietHoursOverride, BuyNowPrice = snap.BuyNowPrice, Shipping = snap.Shipping, WinLimit = snap.WinLimit, + ProductInfoLoaded = snap.BuyNowPrice != null, EndedWhileActive = snap.EndedWhileActive, + Mode = settings.RememberAuctionStates ? RunModes.Parse(snap.Mode) : startMode + }; + WireLog(a); + + if (snap.Outcome != null) + { + a.Outcome = snap.Outcome; + a.MyBidsPlaced = snap.MyBids; + a.TryMarkCompletionReported(); + a.LastState = new AuctionState + { + AuctionId = a.Id, Price = snap.FinalPrice ?? 0, LastBidder = snap.Winner ?? "", Timer = 0, + Status = snap.Outcome == "won" ? AuctionStatus.EndedWon : snap.Outcome == "lost" ? AuctionStatus.EndedLost : AuctionStatus.Closed + }; + } + else + { + await _d.Recorder.PrepareAsync(a).ConfigureAwait(false); + } + + if (_auctions.TryAdd(a.Id, a)) n++; + } + + if (n > 0) + { + var modes = settings.RememberAuctionStates ? "con il modo salvato" : $"in {RunModes.Label(startMode)}"; + _d.Log.Info("ASTE", $"{n} aste ripristinate {modes}"); + ListChanged?.Invoke(); + } + return n; + } + + // ── Aiuti ──────────────────────────────────────────────────────────── + + private static string? FirstNonEmpty(params string?[] values) => values.FirstOrDefault(v => !string.IsNullOrWhiteSpace(v)); + + private static string OriginLabel(string origin) => origin switch + { + "catalogo" => "dal catalogo", + "seguito" => "prodotto seguito", + _ => "a mano" + }; + + private string LimitText(double v) => v > 0 ? Euro(v) : "nessuno"; + + private static string LimitText(int v) => v > 0 ? v.ToString(System.Globalization.CultureInfo.InvariantCulture) : "nessuno"; +} diff --git a/Mimante/src/BidooBidBot/Engine/AuctionMonitor.Completion.cs b/Mimante/src/BidooBidBot/Engine/AuctionMonitor.Completion.cs new file mode 100644 index 0000000..4a580ff --- /dev/null +++ b/Mimante/src/BidooBidBot/Engine/AuctionMonitor.Completion.cs @@ -0,0 +1,184 @@ +using System.Text.Json; +using BidooBidBot.Bidoo; +using BidooBidBot.Data; +using BidooBidBot.Logging; +using BidooBidBot.Ml; +using BidooBidBot.Products; +using BidooBidBot.Strategy; + +namespace BidooBidBot.Engine; + +public sealed partial class AuctionMonitor +{ + /// + /// L'asta è finita (due risposte terminali di fila). Qui, sull'anello di polling, si + /// fissano soltanto esito e ora; il resto (storico, rischio, apprendimento, pulizia) + /// gira fuori, perché la chiusura non deve rallentare nessun altro motore. + /// + private void HandleAuctionEnded(AuctionInfo a, AuctionState s) + { + if (!a.TryMarkCompletionReported()) return; + + var won = s.Status == AuctionStatus.EndedWon; + a.EndedWhileActive = a.Mode == RunMode.Active; + a.ObservedToEnd = true; + a.ConcludedAtUtc ??= s.ExpiryUnixSeconds > 0 + ? DateTimeOffset.FromUnixTimeSeconds(s.ExpiryUnixSeconds).UtcDateTime + : s.SnapshotTimeUtc; + a.Outcome = won ? "won" : s.Status == AuctionStatus.EndedLost ? "lost" : "closed"; + a.DeadlineTicks = 0; + + var label = won ? "VINTA" : s.Status == AuctionStatus.EndedLost ? "persa" : "chiusa"; + a.Log.Add($"Asta terminata: {label} a {Euro(s.Price)}, ultima puntata di {(s.LastBidder.Length > 0 ? s.LastBidder : "nessuno")}", + won ? LogLevel.Success : LogLevel.Warning, AuctionLogCategory.Status); + a.Touch(); + MarkDirty(); + + var summary = BuildSummary(a, s, won); + _ = Task.Run(() => CompleteAsync(a, s, summary)); + } + + private CloseSummary BuildSummary(AuctionInfo a, AuctionState s, bool won) + { + var settings = Settings; + var product = _d.Products.Find(a.ProductKey); + var ended = a.ConcludedAtUtc ?? DateTime.UtcNow; + var firstSeen = a.FirstSeenAtUtc ?? a.TrackingStartedAtUtc ?? a.AddedAtUtc; + var bidders = a.SnapshotBidders(); + var totalBids = bidders.Sum(b => b.Total); + var top = bidders.Count > 0 ? bidders.Max(b => b.Total) : 0; + var series = a.SnapshotPriceSeries(); + var minutes = Math.Max(0, (ended - firstSeen).TotalMinutes); + + double velocity = 0; + if (series.Count >= 2 && series[^1].T > series[0].T) + velocity = (series[^1].Price - series[0].Price) / ((series[^1].T - series[0].T) / 60.0); + + var seriesJson = JsonSerializer.Serialize(series.Select(p => new[] { Math.Round(p.T, 1), Math.Round(p.Price, 2) })); + var byUser = JsonSerializer.Serialize(bidders.ToDictionary(b => b.User, b => b.Total, StringComparer.OrdinalIgnoreCase)); + + return new CloseSummary( + EndedAtUtc: ended, + Outcome: a.Outcome ?? "closed", + FinalStatus: s.Status.ToString(), + WonByMe: won, + Winner: s.LastBidder, + FinalPrice: s.Price, + BuyNow: a.BuyNowPrice, + Shipping: a.Shipping, + MarketValue: product?.MarketValue, + BidCost: BidStrategy.EffectiveBidCost(settings, _d.Account.Balance), + TransactionFee: settings.TransactionFeeEuro, + MyBids: a.MyBidsForLimits, + MyBidsCost: a.MyBidsCost, + WinnerBidsPaid: s.WinnerBidsPaid, + WinnerBidsFree: s.WinnerBidsFree, + Resets: a.ResetCount, + DistinctBidders: bidders.Count, + TotalObservedBids: totalBids, + TopBidderShare: totalBids > 0 ? (double)top / totalBids : 0, + ObservedFromStart: a.ObservedFromStart, + ObservedToEnd: a.ObservedToEnd, + ObservedMinutes: minutes, + FirstSeenUtc: firstSeen, + OpenedUtc: a.OpenedAtUtc, + AvgPing: a.Latency.Average() is { } avg ? Math.Round(avg, 1) : null, + P95Ping: a.Latency.Percentile(0.95), + P99Ping: a.Latency.Percentile(0.99), + Polls: Interlocked.Read(ref a.PollCount), + PollErrors: Interlocked.Read(ref a.PollErrors), + LeadMs: a.LeadMs, + LeadManual: a.LeadIsManual, + TimerExpired: a.TimerExpiredCount, + SuccessfulBids: a.SuccessfulBids, + FailedBids: a.FailedBids, + PriceVelocityPerMinute: velocity, + PriceSeriesJson: seriesJson, + BidsByUserJson: byUser, + ModeAtClose: RunModes.ToKey(a.Mode), + Category: null); + } + + /// + /// Il giro di chiusura, nell'ordine del legacy: registrazione chiusa con il riepilogo, + /// rischio (una vincita), statistiche del prodotto, apprendimento, pulizia dell'elenco. + /// Alla fine una riga sola nel registro generale. + /// + private async Task CompleteAsync(AuctionInfo a, AuctionState s, CloseSummary c) + { + var parts = new List { $"{Outcome(c)} a {Euro(c.FinalPrice)}" }; + try + { + _d.Recorder.Close(a, c); + + var winnerBids = c.WinnerBidsPaid.HasValue || c.WinnerBidsFree.HasValue ? (c.WinnerBidsPaid ?? 0) + (c.WinnerBidsFree ?? 0) : (int?)null; + if (winnerBids is { } wb) + parts.Add(AuctionIntegrity.Trusted(c.FinalPrice, wb) is { } t ? $"{t} puntate del vincitore" : "puntate del vincitore scartate (incoerenti col prezzo)"); + + if (c.WonByMe) + { + var value = ProductRules.ValueOf(_d.Products.Find(a.ProductKey), a.BuyNowPrice) ?? 0; + var net = Theory.RealizedWinProfit(value, c.FinalPrice, 0, c.TransactionFee, c.Shipping ?? 0); + _d.Risk.NoteWin(a.Id, net, $"vinta a {Euro(c.FinalPrice)}, valore reale {Euro(value)}"); + } + + if (_d.Db != null && _d.Queue != null && World == Worlds.Real && !string.IsNullOrEmpty(a.ProductKey)) + { + try + { + await _d.Queue.FlushAsync(TimeSpan.FromSeconds(30)).ConfigureAwait(false); + await ProductStatsRepository.RefreshAsync(_d.Db, _d.Queue, a.ProductKey, c.TransactionFee).ConfigureAwait(false); + } + catch (Exception ex) + { + _d.Log.Warn("PRODOTTI", $"Statistiche di '{a.Name}' non aggiornate: {ex.Message}"); + } + } + + string? learned; + try + { + learned = await _d.Learning.OnAuctionClosedAsync(new ClosedAuctionInfo( + a.Id, a.Name, a.ProductKey, c.EndedAtUtc, c.FinalPrice, c.BuyNow, c.MarketValue, c.WinnerBidsPaid, c.WinnerBidsFree, + c.WonByMe, c.Winner, c.OpenedUtc is { } o ? (c.EndedAtUtc - o).TotalMinutes : c.ObservedFromStart ? c.ObservedMinutes : null)) + .ConfigureAwait(false); + } + catch (Exception ex) + { + learned = $"apprendimento non riuscito: {ex.Message}"; + } + if (!string.IsNullOrEmpty(learned)) parts.Add(learned); + + var cleanup = CleanupFinished(a, c.WonByMe); + if (cleanup != null) parts.Add(cleanup); + } + catch (Exception ex) + { + parts.Add($"chiusura incompleta: {ex.Message}"); + } + + var line = string.Join("; ", parts); + _d.Log.Write(c.WonByMe ? LogLevel.Success : LogLevel.Info, "FINE", $"{a.Name}: {line}", a.Id); + try { AuctionCompleted?.Invoke(a, c, line); } catch { /* chi ascolta non ferma la chiusura */ } + } + + /// Toglie l'asta conclusa se la regola lo consente; dice cosa ha fatto (null a regola spenta). + private string? CleanupFinished(AuctionInfo a, bool won) + { + var s = Settings; + var verdict = FinishedAuctionCleanup.Decide(true, won, a.MyBidsForLimits, a.EndedWhileActive, new FinishedAuctionCleanup.Options + { + Enabled = s.AutoRemoveFinished, + KeepWithMyBids = s.AutoRemoveKeepWithMyBids, + KeepWon = s.AutoRemoveKeepWon, + KeepEndedWhileActive = s.AutoRemoveKeepEndedWhileActive + }); + + if (!verdict.Remove) return s.AutoRemoveFinished ? $"resta in elenco ({verdict.Reason})" : null; + Remove(a.Id, "conclusa", markProduct: false); + return "tolta dall'elenco"; + } + + private static string Outcome(CloseSummary c) => + c.WonByMe ? "Vinta" : c.Outcome == "lost" ? "Persa" : "Chiusa"; +} diff --git a/Mimante/src/BidooBidBot/Engine/AuctionMonitor.Snapshot.cs b/Mimante/src/BidooBidBot/Engine/AuctionMonitor.Snapshot.cs new file mode 100644 index 0000000..4a5672c --- /dev/null +++ b/Mimante/src/BidooBidBot/Engine/AuctionMonitor.Snapshot.cs @@ -0,0 +1,202 @@ +using BidooBidBot.Bidoo; +using BidooBidBot.Logging; +using BidooBidBot.Ml; + +namespace BidooBidBot.Engine; + +public sealed partial class AuctionMonitor +{ + /// + /// Incorpora una risposta di data.php: orologio del server, scadenza assoluta del ciclo, + /// storico delle puntate (e registrazione), reset, fine asta, previsione. Gira sull'anello + /// di polling, mai sul cecchino. + /// + public void ApplySnapshot(AuctionInfo a, AuctionState s) + { + try + { + var clock = _d.Clock; + clock.AddSample(s.ServerUnixSeconds, s.ReceivedTicks, s.PollingLatencyMs); + + if (s.ExpiryUnixSeconds > 0) + { + a.DeadlineTicks = clock.IsSynced + ? clock.ToLocalTicks(s.ExpiryUnixSeconds) + : s.ReceivedTicks + PrecisionWait.MsToTicks(s.Timer * 1000 - s.PollingLatencyMs / 2.0); + } + + a.Latency.Add(s.PollingLatencyMs); + _d.Latency.NotePing(s.PollingLatencyMs); + a.TrackPrice(s.Price); + + if (a.TrackingStartedAtUtc == null) + { + a.TrackingStartedAtUtc = DateTime.UtcNow; + a.ObservedFromStart = s.Status is AuctionStatus.Scheduled or AuctionStatus.Pending || s.Price <= 0.02; + a.Log.Add($"Seguita da ora: timer {s.Timer:F0} s, prezzo {Euro(s.Price)}" + (a.ObservedFromStart ? ", dall'inizio" : ""), + LogLevel.Info, AuctionLogCategory.Status); + } + + if (a.OpenedAtUtc == null && a.ObservedFromStart && s.Status == AuctionStatus.Running) a.OpenedAtUtc = DateTime.UtcNow; + + var rec = _d.Recorder.For(a.Id); + rec?.Poll(s); + + var previous = a.LastState; + if (s.RecentBidsHistory is { Count: > 0 } history) MergeHistory(a, history, rec); + if (!string.IsNullOrEmpty(s.LastBidder) && s.Price > 0) EnsureCurrentBid(a, s, rec); + + if (s.IsTerminal) + { + a.LastState = s; + a.TerminalStreak++; + a.Touch(); + // Un singolo OFF isolato capita: servono due risposte terminali di fila. + if (a.TerminalStreak >= 2) HandleAuctionEnded(a, s); + return; + } + + a.TerminalStreak = 0; + + var isNewBid = previous != null && s.Price > previous.Price + 0.0001 || + previous != null && !string.IsNullOrEmpty(previous.LastBidder) && !string.IsNullOrEmpty(s.LastBidder) && + !previous.LastBidder.Equals(s.LastBidder, StringComparison.OrdinalIgnoreCase); + if (isNewBid) + { + a.ResetCount++; + rec?.Reset(a.ResetCount, s.Price, s.LastBidder); + } + + var changed = previous == null || Math.Abs(previous.Price - s.Price) > 0.0001 || previous.LastBidder != s.LastBidder || + previous.ExpiryUnixSeconds != s.ExpiryUnixSeconds || previous.Status != s.Status; + a.LastState = s; + if (changed) a.Touch(); + + RefreshForecast(a, s); + } + catch (Exception ex) + { + a.Log.Add($"Errore nella lettura della risposta: {ex.Message}", LogLevel.Error, AuctionLogCategory.Polling); + } + } + + /// + /// Unisce lo storico ricevuto con quello già visto: le puntate nuove (per prezzo in + /// centesimi, che su Bidoo le identifica) entrano in testa, contano per il loro utente e + /// vanno alla registrazione. Un tipo dichiarato dal server corregge quello ignoto. + /// + private void MergeHistory(AuctionInfo a, List history, Data.AuctionRecording? rec) + { + var me = _d.Account.Username; + var added = new List(); + + lock (a.BidsLock) + { + foreach (var bid in history) + { + if (!bid.IsMyBid && !string.IsNullOrEmpty(me) && bid.Username.Equals(me, StringComparison.OrdinalIgnoreCase)) + bid.IsMyBid = true; + + var cents = bid.PriceCents; + if (a.SeenBidCents.Add(cents)) + { + a.RecentBids.Add(bid); + a.BidderTotals[bid.Username] = a.BidderTotals.GetValueOrDefault(bid.Username) + 1; + added.Add(bid); + } + else if (bid.BidType.Length > 0) + { + var existing = a.RecentBids.FirstOrDefault(b => b.PriceCents == cents); + if (existing != null && existing.BidType.Length == 0) + { + existing.BidType = bid.BidType; + if (existing.Timestamp <= 0) existing.Timestamp = bid.Timestamp; + added.Add(existing); + } + } + } + + if (added.Count > 0) + { + a.RecentBids.Sort((x, y) => + { + var byTime = y.Timestamp.CompareTo(x.Timestamp); + return byTime != 0 ? byTime : y.Price.CompareTo(x.Price); + }); + if (a.RecentBids.Count > 50) a.RecentBids.RemoveRange(50, a.RecentBids.Count - 50); + } + } + + if (rec != null) foreach (var b in added) rec.ForeignBid(b); + if (added.Count > 0) a.Touch(); + } + + /// La puntata in testa c'è sempre nello storico, anche se l'API la omette (tipo ignoto). + private void EnsureCurrentBid(AuctionInfo a, AuctionState s, Data.AuctionRecording? rec) + { + var cents = (int)Math.Round(s.Price * 100); + BidHistoryEntry? entry = null; + lock (a.BidsLock) + { + if (!a.SeenBidCents.Add(cents)) return; + entry = new BidHistoryEntry + { + Price = cents / 100m, + Username = s.LastBidder, + Timestamp = s.ServerUnixSeconds, + BidType = BidHistoryEntry.TypeUnknown, + IsMyBid = s.IsMyBid + }; + a.RecentBids.Insert(0, entry); + a.BidderTotals[s.LastBidder] = a.BidderTotals.GetValueOrDefault(s.LastBidder) + 1; + if (a.RecentBids.Count > 50) a.RecentBids.RemoveRange(50, a.RecentBids.Count - 50); + } + rec?.ForeignBid(entry); + } + + /// + /// La previsione dell'asta (§7.7): all'aggancio, poi ogni tanti rilanci o minuti. È in + /// memoria e costa microsecondi; la registrazione accoda una riga. + /// + private void RefreshForecast(AuctionInfo a, AuctionState s) + { + var settings = Settings; + var due = a.Forecast == null || + a.ResetCount - a.ForecastResetCount >= settings.ForecastRefreshBids || + a.ForecastAtUtc is { } at && DateTime.UtcNow - at >= TimeSpan.FromMinutes(settings.ForecastRefreshMinutes); + if (!due) return; + + var product = _d.Products.Find(a.ProductKey); + var value = Products.ProductRules.ValueOf(product, a.BuyNowPrice); + var nowLocal = AppInfo.LocalNow; + var recent = a.SnapshotRecentBids(50); + + double? bidsPerMinute = null; + if (recent.Count >= 5 && recent[0].Timestamp > 0 && recent[^1].Timestamp > 0) + { + var span = (recent[0].Timestamp - recent[^1].Timestamp) / 60.0; + if (span > 0.2) bidsPerMinute = (recent.Count - 1) / span; + } + + double? perBid = null; + var ctx = _d.Learning.BuildContext(a, s, nowLocal, _d.Account.Username); + if (ctx is { } c) perBid = Math.Clamp(_d.Learning.PredictUnanswered(c) * _d.Learning.OwnBidFactor, 0, 1); + + var input = new ForecastInput( + a.ProductKey, s.Price, value, BidFeatures.HourBand(nowLocal.Hour), bidsPerMinute, perBid, + Strategy.BidStrategy.EffectiveBidCost(settings, _d.Account.Balance), settings.TransactionFeeEuro, a.Shipping ?? 0, + Math.Max(1, recent.Take(20).Select(b => b.Username).Distinct(StringComparer.OrdinalIgnoreCase).Count()), a.MaxBids); + + var forecast = _d.Learning.Forecast(input); + a.ForecastResetCount = a.ResetCount; + a.ForecastAtUtc = DateTime.UtcNow; + if (forecast == null) return; + + var initial = !a.InitialForecastRecorded; + a.Forecast = forecast; + a.InitialForecastRecorded = true; + a.Touch(); + _d.Recorder.RecordForecast(a, forecast, initial); + if (initial) a.Log.Add("Previsione: " + AuctionForecast.Describe(forecast), LogLevel.Info, AuctionLogCategory.Forecast); + } +} diff --git a/Mimante/src/BidooBidBot/Engine/AuctionMonitor.cs b/Mimante/src/BidooBidBot/Engine/AuctionMonitor.cs new file mode 100644 index 0000000..7eafdcb --- /dev/null +++ b/Mimante/src/BidooBidBot/Engine/AuctionMonitor.cs @@ -0,0 +1,271 @@ +using System.Collections.Concurrent; +using System.Globalization; +using BidooBidBot.Bidoo; +using BidooBidBot.Data; +using BidooBidBot.Logging; +using BidooBidBot.Ml; +using BidooBidBot.Products; +using BidooBidBot.Session; +using BidooBidBot.Settings; +using BidooBidBot.Strategy; + +namespace BidooBidBot.Engine; + +/// Ciò di cui il monitor ha bisogno: tutto dall'esterno, così i test lo montano sul simulatore. +public sealed class MonitorDeps +{ + public required Func Settings { get; init; } + public required Func References { get; init; } + public required BidooApi Api { get; init; } + public required ServerClock Clock { get; init; } + public required BidStrategy Strategy { get; init; } + public required RiskManager Risk { get; init; } + public required LearningService Learning { get; init; } + public required LatencyModel Latency { get; init; } + public required AuctionRecorder Recorder { get; init; } + public required ProductStore Products { get; init; } + public required AccountState Account { get; init; } + public required AppLog Log { get; init; } + public required IDocumentStore Documents { get; init; } + public Logging.FileLog? AuctionFile { get; init; } + public Db? Db { get; init; } + public WriteQueue? Queue { get; init; } + public string World { get; init; } = Worlds.Real; + public string DocumentKey { get; init; } = "monitor/auctions"; +} + +/// +/// Il monitor delle aste (specifica §6.2, portato dal legacy): coordina i motori, incorpora +/// le risposte, chiede il verdetto alla strategia, spara la puntata, chiude le aste +/// alimentando storico, apprendimento, prodotti e rischio, e tiene l'elenco nel documento +/// monitor/auctions. +/// +/// Ogni asta ha il suo ; un supervisore ogni 250 ms allinea +/// i motori al modo scelto (Ferma = nessun motore). Una risposta lenta su un'asta non ritarda +/// di un millisecondo la puntata sulle altre. +/// +public sealed partial class AuctionMonitor : IAuctionRunnerHost, IAsyncDisposable +{ + private readonly MonitorDeps _d; + private readonly ConcurrentDictionary _auctions = new(StringComparer.Ordinal); + private readonly ConcurrentDictionary _runners = new(StringComparer.Ordinal); + private readonly CancellationTokenSource _life = new(); + private Task? _supervisor; + private Task? _saver; + private volatile bool _dirty; + private int _disposed; + private static readonly CultureInfo It = CultureInfo.GetCultureInfo("it-IT"); + + public AuctionMonitor(MonitorDeps deps) => _d = deps; + + public MonitorDeps Deps => _d; + public string World => _d.World; + public ServerClock Clock => _d.Clock; + + /// Un'asta è finita: riepilogo e riga del registro (Telegram, interfaccia). + public event Action? AuctionCompleted; + + /// L'elenco è cambiato (aggiunta, rimozione, modo). + public event Action? ListChanged; + + /// Una puntata è partita (riuscita o no). + public event Action? BidPlaced; + + public AppSettings Settings => _d.Settings(); + public BidooReferences References => _d.References(); + + /// Le aste in elenco, nell'ordine in cui sono entrate. + public IReadOnlyList Auctions => _auctions.Values.OrderBy(a => a.AddedAtUtc).ToList(); + + public AuctionInfo? Find(string id) => _auctions.TryGetValue(id, out var a) ? a : null; + + public int ActiveRunners => _runners.Count; + + // ── Avvio e arresto ────────────────────────────────────────────────── + + public void Start() + { + if (_supervisor != null) return; + _supervisor = Task.Run(() => SupervisorLoopAsync(_life.Token)); + _saver = Task.Run(() => SaverLoopAsync(_life.Token)); + } + + private async Task SupervisorLoopAsync(CancellationToken ct) + { + while (!ct.IsCancellationRequested) + { + try + { + foreach (var a in _auctions.Values) + { + var shouldRun = a.Mode != RunMode.Stopped && !a.IsFinished; + if (shouldRun) + { + if (!_runners.ContainsKey(a.Id)) + { + var runner = new AuctionRunner(a, this); + if (_runners.TryAdd(a.Id, runner)) + { + runner.Start(); + a.Log.Add($"Motore avviato in {RunModes.Label(a.Mode)}", LogLevel.Info, AuctionLogCategory.Status); + } + } + } + else if (_runners.TryRemove(a.Id, out var stale)) + { + await stale.StopAsync().ConfigureAwait(false); + } + } + + foreach (var id in _runners.Keys.Where(k => !_auctions.ContainsKey(k)).ToList()) + if (_runners.TryRemove(id, out var orphan)) await orphan.StopAsync().ConfigureAwait(false); + + await Task.Delay(250, ct).ConfigureAwait(false); + } + catch (OperationCanceledException) { break; } + catch (Exception ex) + { + _d.Log.Error("MOTORE", $"Supervisore: {ex.Message}"); + try { await Task.Delay(500, ct).ConfigureAwait(false); } catch (OperationCanceledException) { break; } + } + } + } + + public async ValueTask DisposeAsync() + { + if (Interlocked.Exchange(ref _disposed, 1) == 1) return; + await _life.CancelAsync().ConfigureAwait(false); + foreach (var r in _runners.Values.ToList()) + { + try { await r.StopAsync().ConfigureAwait(false); } catch { } + } + _runners.Clear(); + if (_supervisor != null) try { await _supervisor.ConfigureAwait(false); } catch { } + if (_saver != null) try { await _saver.ConfigureAwait(false); } catch { } + SaveNow(); + _life.Dispose(); + } + + // ── IAuctionRunnerHost ─────────────────────────────────────────────── + + public async Task PollAsync(AuctionInfo auction, CancellationToken ct) + { + var settings = Settings; + var result = await _d.Api.PollAsync(auction.Id, auction.Url, Math.Max(settings.MaxBidHistoryEntries, 50), ct).ConfigureAwait(false); + if (result.State == null && result.Error != null && auction.ConsecutivePollErrors == 2) + auction.Log.Add($"data.php: {result.Error}", LogLevel.Warning, AuctionLogCategory.Polling); + return result.State; + } + + public bool IsFinished(AuctionInfo auction) => auction.IsFinished || auction.Mode == RunMode.Stopped; + + /// + /// La decisione si registra soltanto quando l'asta è in Osserva o quando la modalità + /// globale è OSSERVA. Nel simulatore si punta davvero (sono puntate finte). + /// + public bool IsShadow(AuctionInfo auction) => + auction.Mode != RunMode.Active || (!Settings.LiveBiddingEnabled && World == Worlds.Real); + + public int EffectiveLeadMs(AuctionInfo auction) + { + if (auction.LeadIsManual && auction.LeadMs > 0) return auction.LeadMs; + + var settings = Settings; + var lead = settings.AdaptiveLeadEnabled && settings.LearningEnabled + ? _d.Latency.RecommendedLeadMs(settings) + : settings.DefaultBidBeforeDeadlineMs; + + // Isteresi: il modello di latenza si muove di pochi ms a ogni campione; l'anticipo + // dell'asta cambia solo per salti di almeno 100 ms, e lo dice una volta. + if (auction.LeadMs <= 0 || Math.Abs(lead - auction.LeadMs) >= 100) + { + if (auction.LeadMs > 0) + auction.Log.Add($"Anticipo adattivo {auction.LeadMs} -> {lead} ms", LogLevel.Debug, AuctionLogCategory.Timing); + auction.LeadMs = lead; + auction.Touch(); + } + return auction.LeadMs; + } + + // ── Persistenza dell'elenco ────────────────────────────────────────── + + private void MarkDirty() + { + _dirty = true; + ListChanged?.Invoke(); + } + + private async Task SaverLoopAsync(CancellationToken ct) + { + while (!ct.IsCancellationRequested) + { + try { await Task.Delay(2000, ct).ConfigureAwait(false); } + catch (OperationCanceledException) { break; } + if (_dirty) SaveNow(); + } + } + + private void SaveNow() + { + _dirty = false; + try + { + var list = _auctions.Values.OrderBy(a => a.AddedAtUtc).Select(AuctionSnapshot.From).ToList(); + _d.Documents.Set(_d.DocumentKey, System.Text.Json.JsonSerializer.Serialize(list)); + } + catch (Exception ex) + { + _d.Log.Warn("ASTE", $"Elenco delle aste non salvato: {ex.Message}"); + } + } + + private void WireLog(AuctionInfo a) + { + a.Log.Capacity = Settings.MaxLogLinesPerAuction; + var file = _d.AuctionFile; + if (file == null) return; + a.Log.Sink = entry => + { + var local = entry.Ts.LocalDateTime; + file.Write("aste", local, $"{local.ToString("HH:mm:ss.fff", CultureInfo.InvariantCulture)} [{a.Id}] {a.Name}: {entry.Message}"); + }; + } + + private string Euro(double v) => v.ToString("0.00", It) + " EUR"; +} + +/// Un'asta come si salva nel documento dell'elenco. +public sealed class AuctionSnapshot +{ + public string Id { get; set; } = ""; + 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; } + public string Origin { get; set; } = "mano"; + public DateTime AddedAtUtc { get; set; } + public string Mode { get; set; } = "osserva"; + public int LeadMs { get; set; } + public bool LeadIsManual { get; set; } + public double MaxPrice { get; set; } + public int MaxBids { get; set; } + public bool? QuietHoursOverride { get; set; } + public double? BuyNowPrice { get; set; } + public double? Shipping { get; set; } + public string? WinLimit { get; set; } + public string? Outcome { get; set; } + public double? FinalPrice { get; set; } + public string? Winner { get; set; } + public int MyBids { get; set; } + public bool EndedWhileActive { get; set; } + + public static AuctionSnapshot From(AuctionInfo a) => new() + { + Id = a.Id, Name = a.Name, Url = a.Url, ProductKey = a.ProductKey, BidooProductId = a.BidooProductId, ImageUrl = a.ImageUrl, + Origin = a.Origin, AddedAtUtc = a.AddedAtUtc, Mode = RunModes.ToKey(a.Mode), LeadMs = a.LeadMs, LeadIsManual = a.LeadIsManual, + MaxPrice = a.MaxPrice, MaxBids = a.MaxBids, QuietHoursOverride = a.QuietHoursOverride, BuyNowPrice = a.BuyNowPrice, + Shipping = a.Shipping, WinLimit = a.WinLimit, Outcome = a.Outcome, FinalPrice = a.Outcome != null ? a.LastState?.Price : null, + Winner = a.Outcome != null ? a.LastState?.LastBidder : null, MyBids = a.MyBidsForLimits, EndedWhileActive = a.EndedWhileActive + }; +} diff --git a/Mimante/src/BidooBidBot/Engine/Warmup.cs b/Mimante/src/BidooBidBot/Engine/Warmup.cs new file mode 100644 index 0000000..e22ed55 --- /dev/null +++ b/Mimante/src/BidooBidBot/Engine/Warmup.cs @@ -0,0 +1,73 @@ +using System.Diagnostics; +using BidooBidBot.Bidoo; +using BidooBidBot.Logging; +using BidooBidBot.Net; +using BidooBidBot.Simulator; + +namespace BidooBidBot.Engine; + +/// +/// Il riscaldamento all'avvio (specifica §6.3): prima di seguire aste vere si percorre tutto +/// il percorso della puntata contro il simulatore interno (interrogazione, orologio, attesa +/// di precisione, corsia, lettura della risposta), così il codice è già compilato dal JIT e +/// la prima puntata vera non paga nulla di questo. +/// +public static class Warmup +{ + public sealed record Result(bool Ok, long ElapsedMs, int Polls, double WaitErrorMs, string? Error); + + public static async Task RunAsync(BidooReferences baseRefs, AppLog? log, CancellationToken ct) + { + var sw = Stopwatch.StartNew(); + try + { + var world = new SimWorld(seed: 1, populate: false); + await using var sim = await SimulatedBidoo.StartAsync(world).ConfigureAwait(false); + var target = world.AddRunningAuction(seconds: 30, freq: 10); + var refs = sim.References(baseRefs); + 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 clock = new ServerClock(); + + var polls = 0; + AuctionState? state = null; + for (var i = 0; i < 5; i++) + { + var r = await api.PollAsync(target.Id, null, 50, ct).ConfigureAwait(false); + if (r.State is { } s) + { + polls++; + state = s; + clock.AddSample(s.ServerUnixSeconds, s.ReceivedTicks, s.PollingLatencyMs); + } + } + if (state == null) return Done(log, sw, false, polls, 0, "il simulatore non ha risposto"); + + var fire = PrecisionWait.Now + PrecisionWait.MsToTicks(30); + PrecisionWait.Until(fire, ct); + var waitError = -PrecisionWait.MsUntil(fire); + var bid = await api.PlaceBidAsync(target.Id, null, null, 0, ct).ConfigureAwait(false); + DataResponseParser.ParseBidResponse(bid.RawBody); + return Done(log, sw, bid.Success, polls, waitError, bid.Success ? null : bid.Error); + } + catch (OperationCanceledException) + { + throw; + } + catch (Exception ex) + { + return Done(log, sw, false, 0, 0, ex.Message); + } + } + + private static Result Done(AppLog? log, Stopwatch sw, bool ok, int polls, double waitError, string? error) + { + var result = new Result(ok, sw.ElapsedMilliseconds, polls, waitError, error); + if (ok) + log?.Info("AVVIO", $"Riscaldamento: percorso della puntata provato sul simulatore in {result.ElapsedMs} ms ({polls} letture, errore d'attesa {waitError:F2} ms)"); + else + log?.Warn("AVVIO", $"Riscaldamento incompleto ({error}): la prima puntata vera potrà essere un filo più lenta"); + return result; + } +} diff --git a/Mimante/src/BidooBidBot/Host/Bot.Services.cs b/Mimante/src/BidooBidBot/Host/Bot.Services.cs index 53e4faa..b56d897 100644 --- a/Mimante/src/BidooBidBot/Host/Bot.Services.cs +++ b/Mimante/src/BidooBidBot/Host/Bot.Services.cs @@ -1,19 +1,294 @@ +using BidooBidBot.Bidoo; +using BidooBidBot.Data; +using BidooBidBot.Engine; +using BidooBidBot.Logging; +using BidooBidBot.Ml; +using BidooBidBot.Products; +using BidooBidBot.Session; +using BidooBidBot.Session.Cdp; +using BidooBidBot.Settings; +using BidooBidBot.Strategy; +using BidooBidBot.Telegram; using BidooBidBot.Web; namespace BidooBidBot.Host; +/// +/// I servizi condivisi fra i mondi e il passaggio da un mondo all'altro. Il mondo in uso è il +/// sito vero se c'è una sessione salvata, altrimenti il simulatore. +/// public sealed partial class Bot { - public WebSocketHub Hub { get; } = new(); + private readonly SemaphoreSlim _worldGate = new(1, 1); + private readonly List _jobs = new(); + private volatile BotWorld? _world; - /// Avvia i servizi dopo impostazioni e documenti. Cresce milestone dopo milestone. - private Task StartServicesAsync(CancellationToken ct) => Task.CompletedTask; + public WebSocketHub Hub { get; private set; } = null!; + public ReferencesProvider ReferencesProvider { get; private set; } = null!; + public ProductStore Products { get; private set; } = null!; + public RiskManager Risk { get; private set; } = null!; + public SessionStore Sessions { get; private set; } = null!; + public TelegramNotifier Telegram { get; private set; } = null!; + public Maintenance Maintenance { get; private set; } = null!; + public AssistedLogin Login { get; private set; } = null!; + public CsvExport Exports { get; private set; } = null!; - private Task StopServicesAsync() => Task.CompletedTask; + /// Il mondo in uso (sito vero o simulatore). + public BotWorld World => _world ?? throw new InvalidOperationException("servizi non ancora avviati"); + public BotWorld? WorldOrNull => _world; - private void OnDatabaseDown(TimeSpan elapsed) => - Log.Error("DB", $"Database non raggiungibile da {elapsed.TotalSeconds:N0} s"); + /// Il mondo è cambiato (accesso fatto, disconnessione): l'interfaccia rilegge tutto. + public event Action? WorldChanged; + + private async Task StartServicesAsync(CancellationToken ct) + { + Host.SetStartingStep("riferimenti del sito"); + ReferencesProvider = new ReferencesProvider(Paths.References, Log); + + Host.SetStartingStep("prodotti e rischio"); + Products = new ProductStore(Queue); + await Products.LoadAsync(Db).ConfigureAwait(false); + Risk = new RiskManager(Documents, new DbRiskLedger(Queue), log: Log); + await Risk.LoadAsync(Db).ConfigureAwait(false); + Risk.HaltChanged += OnHaltChanged; + + Telegram = new TelegramNotifier(() => Settings.Current, Log) { CommandHandler = HandleTelegramCommandAsync }; + Maintenance = new Maintenance(Db, Queue, Paths, () => Settings.Current, Log); + Maintenance.NearCap += (used, cap) => + { + if (Settings.Current.TelegramNotifyRisk) + Telegram.Enqueue(TelegramFormat.Message("Spazio dati quasi pieno", + $"Il database usa {DataRetention.Gb(used)} su un tetto di {DataRetention.Gb(cap)}. La rotazione notturna toglie i dati più vecchi; se non basta, alza il tetto.")); + }; + Sessions = new SessionStore(Paths.Session); + Hub = new WebSocketHub(this); + Exports = new CsvExport(Db, Queue, Paths, () => Settings.Current, name => _world is { } w && w.Name == name ? w.Learning : null); + + Login = new AssistedLogin(Paths.Browser, () => ReferencesProvider.Current, Log); + Login.Frame += (data, w, h, url) => Hub.Broadcast(new Dictionary + { + ["t"] = "login.frame", ["jpegBase64"] = data, ["w"] = w, ["h"] = h, ["url"] = url + }, page: "accesso"); + Login.State += (state, detail) => Hub.Broadcast(new Dictionary { ["t"] = "login.state", ["state"] = state, ["detail"] = detail }); + Login.LoggedIn += async session => + { + var (ok, msg) = await UseSessionAsync(session, Lifetime).ConfigureAwait(false); + Hub.Broadcast(new Dictionary { ["t"] = "login.state", ["state"] = ok ? "riuscito" : "errore", ["detail"] = msg }); + }; + + Host.SetStartingStep("riscaldamento del motore"); + await Warmup.RunAsync(ReferencesProvider.Current, Log, ct).ConfigureAwait(false); + + Host.SetStartingStep("aste"); + var (session, error) = Sessions.Load(); + if (error != null) Log.Warn("SESSIONE", $"{error}: si parte dal simulatore, rifai l'accesso"); + await SwitchWorldAsync(session, ct).ConfigureAwait(false); + + Settings.Changed += OnSettingsChanged; + _jobs.Add(Maintenance.RunAsync(Lifetime)); + _jobs.Add(SummaryLoopAsync(Lifetime)); + Hub.Start(Lifetime); + } + + private async Task StopServicesAsync() + { + if (Login != null) await Login.DisposeAsync().ConfigureAwait(false); + if (Hub != null) await Hub.DisposeAsync().ConfigureAwait(false); + var world = _world; + _world = null; + if (world != null) await world.DisposeAsync().ConfigureAwait(false); + try { await Task.WhenAll(_jobs).WaitAsync(TimeSpan.FromSeconds(5)).ConfigureAwait(false); } catch { } + if (Telegram != null) await Telegram.DisposeAsync().ConfigureAwait(false); + ReferencesProvider?.Dispose(); + } + + // ── Cambio di mondo ────────────────────────────────────────────────── + + /// + /// Costruisce il mondo per la sessione data (null = simulatore), lo avvia, lo mette in uso + /// e solo dopo spegne il precedente: l'interfaccia non resta mai senza mondo. + /// + public async Task SwitchWorldAsync(BidooSession? session, CancellationToken ct) + { + await _worldGate.WaitAsync(ct).ConfigureAwait(false); + try + { + var old = _world; + if (old != null) + { + // Il vecchio elenco si salva prima che il nuovo mondo lo rilegga. + await old.DisposeAsync().ConfigureAwait(false); + _world = null; + } + + var world = session != null + ? await BotWorld.CreateRealAsync(this, session, Lifetime).ConfigureAwait(false) + : await BotWorld.CreateSimulatorAsync(this, Lifetime).ConfigureAwait(false); + + world.Api.SessionInvalid += reason => OnSessionInvalid(world, reason); + world.Monitor.AuctionCompleted += (a, c, line) => OnAuctionCompleted(world, a, c, line); + await world.StartAsync(this).ConfigureAwait(false); + _world = world; + WorldChanged?.Invoke(world); + } + finally + { + _worldGate.Release(); + } + } + + /// Una sessione nuova (accesso assistito o cookie incollati): si salva, si verifica, si passa al sito vero. + public async Task<(bool Ok, string Message)> UseSessionAsync(BidooSession session, CancellationToken ct) + { + Sessions.Save(session); + Log.Info("SESSIONE", $"Sessione salvata ({session.Source}){(session.Username != null ? $" per {session.Username}" : "")}"); + await SwitchWorldAsync(session, ct).ConfigureAwait(false); + var ok = World.Checker != null && await World.Checker.VerifyAsync(full: true, ct).ConfigureAwait(false); + if (ok && World.Account.Username is { } user && user != session.Username) + { + session.Username = user; + session.UserId = World.Account.UserId; + session.CheckedAtUtc = DateTime.UtcNow; + Sessions.Save(session); + } + return ok + ? (true, $"Collegato come {World.Account.Username}: {World.Account.BalanceText()} puntate") + : (false, "Sessione salvata ma Bidoo non la riconosce: controlla i cookie o rifai l'accesso assistito"); + } + + /// «Disconnetti»: la sessione si cancella e si torna al simulatore. + public async Task LogoutAsync(CancellationToken ct) + { + Sessions.Delete(); + Log.Info("SESSIONE", "Sessione cancellata: si torna al simulatore"); + await SwitchWorldAsync(null, ct).ConfigureAwait(false); + } + + // ── Eventi ─────────────────────────────────────────────────────────── + + private void OnSessionInvalid(BotWorld world, string reason) + { + if (world.IsSimulator || world.Account.Status == SessionStatus.Expired) return; + world.Account.SetStatus(SessionStatus.Expired, reason); + Log.Error("SESSIONE", $"Sessione da rifare: {reason}"); + world.Monitor.ForceAllObserve("sessione Bidoo scaduta"); + if (Settings.Current.TelegramNotifySession) + Telegram.Enqueue(TelegramFormat.SessionExpired(world.Account.Username, reason)); + } + + private void OnAuctionCompleted(BotWorld world, AuctionInfo a, CloseSummary c, string line) + { + if (world.IsSimulator) return; + var s = Settings.Current; + if (c.WonByMe && s.TelegramNotifyWin) + { + var realCost = c.FinalPrice + c.MyBidsCost + c.TransactionFee + (c.Shipping ?? 0); + var value = ProductRules.ValueOf(Products.Find(a.ProductKey), a.BuyNowPrice); + Telegram.Enqueue(TelegramFormat.Won(a.Name, c.FinalPrice, c.MyBids, realCost, value)); + } + else if (!c.WonByMe && s.TelegramNotifyLoss && (c.MyBids > 0 || a.EndedWhileActive)) + { + var reason = line.Contains("; ", StringComparison.Ordinal) ? line[(line.IndexOf("; ", StringComparison.Ordinal) + 2)..] : null; + Telegram.Enqueue(TelegramFormat.Lost(a.Name, c.FinalPrice, c.Winner, c.MyBids, reason)); + } + } + + private void OnHaltChanged(RiskManager.HaltInfo? info) + { + if (!Settings.Current.TelegramNotifyRisk) return; + Telegram.Enqueue(info != null ? TelegramFormat.Halt(info.Reason, info.Automatic) : TelegramFormat.Resume()); + } + + private void OnSettingsChanged(AppSettings s) + { + var world = _world; + if (world != null && !world.IsSimulator) world.Transport.Configure(s.MaxRequestsPerSecond); + } + + private void OnDatabaseDown(TimeSpan elapsed) + { + Log.Error("DB", $"Database non raggiungibile da {elapsed.TotalSeconds:N0} s: tutte le aste passano in Osserva"); + _world?.Monitor.ForceAllObserve("database non raggiungibile"); + Telegram?.Enqueue(TelegramFormat.Message("Database non raggiungibile", + $"PostgreSQL non risponde da {elapsed.TotalSeconds:N0} s. Le aste sono in Osserva; dopo 10 minuti il bot si ferma e mostra la schermata d'errore.")); + } + + // ── Telegram: riepilogo e comandi ──────────────────────────────────── + + private Task SummaryLoopAsync(CancellationToken ct) => Task.Run(async () => + { + var last = DateTime.UtcNow; + while (!ct.IsCancellationRequested) + { + try { await Task.Delay(TimeSpan.FromMinutes(1), ct).ConfigureAwait(false); } + catch (OperationCanceledException) { return; } + var minutes = Settings.Current.TelegramSummaryMinutes; + if (minutes <= 0 || DateTime.UtcNow - last < TimeSpan.FromMinutes(minutes)) continue; + last = DateTime.UtcNow; + if (_world is { IsSimulator: false } && Telegram.Configured) + { + try { Telegram.Enqueue(TelegramFormat.SummaryText(await BuildSummaryAsync().ConfigureAwait(false))); } + catch (Exception ex) { Log.Warn("TELEGRAM", $"Riepilogo non preparato: {ex.Message}"); } + } + } + }, ct); + + public async Task BuildSummaryAsync() + { + var w = World; + var s = Settings.Current; + var risk = Risk.Snapshot(); + var cost = BidStrategy.EffectiveBidCost(s, w.Account.Balance); + var data = new DbLearningData(Db, Queue, w.Name); + + async Task Roi(bool shadow) + { + var rows = await data.ShadowRowsAsync(7, shadow, cost).ConfigureAwait(false); + if (rows.Count == 0) return null; + var acting = ShadowReport.Compute(rows, s.TransactionFeeEuro, 7).Policies[0]; + return acting.Bids > 0 ? acting.RoiPerBid : null; + } + + return new TelegramFormat.Summary( + w.Monitor.Auctions.Count, w.Monitor.Auctions.Count(a => a.Mode == RunMode.Active && !a.IsFinished), w.Account.Total, + risk.TodaySpent, risk.TodayNet, await Roi(true).ConfigureAwait(false), await Roi(false).ConfigureAwait(false), + w.Latency.Snapshot().P50 is > 0 and var p ? p : null, s.LiveBiddingEnabled, Risk.Halted); + } + + private async Task HandleTelegramCommandAsync(string command) + { + switch (command) + { + case "/stato": + return TelegramFormat.SummaryText(await BuildSummaryAsync().ConfigureAwait(false)); + case "/halt": + Risk.SetHalt("HALT chiesto da Telegram", automatic: false); + return TelegramFormat.Message("HALT attivo", "Nessuna puntata dal vivo parte finché non lo togli."); + case "/riprendi": + return Risk.Resume() + ? TelegramFormat.Resume() + : TelegramFormat.Message("Nessun HALT da togliere", null); + case "/osserva": + var n = _world?.Monitor.ForceAllObserve("chiesto da Telegram") ?? 0; + return TelegramFormat.Message($"{n} aste passate in Osserva", null); + default: + return TelegramFormat.Message("Comando sconosciuto", "Comandi: /stato, /halt, /riprendi, /osserva"); + } + } + + // ── Salute ─────────────────────────────────────────────────────────── /// Le voci di /salute oltre al database. - public IEnumerable> HealthDetails() => Array.Empty>(); + public IEnumerable> HealthDetails() + { + var w = _world; + if (w == null) yield break; + yield return new("mondo", w.IsSimulator ? "simulatore" : "sito"); + yield return new("sessione", w.Account.Status.ToString().ToLowerInvariant()); + yield return new("aste", w.Monitor.Auctions.Count); + yield return new("motori", w.Monitor.ActiveRunners); + yield return new("modalita", Settings.Current.LiveBiddingEnabled ? "dal-vivo" : "osserva"); + yield return new("halt", Risk.Halted); + yield return new("codaScritture", Queue.Pending); + } } diff --git a/Mimante/src/BidooBidBot/Host/Bot.cs b/Mimante/src/BidooBidBot/Host/Bot.cs index cf48572..a68db78 100644 --- a/Mimante/src/BidooBidBot/Host/Bot.cs +++ b/Mimante/src/BidooBidBot/Host/Bot.cs @@ -65,7 +65,7 @@ public sealed partial class Bot : IAsyncDisposable Log.MinLevel = AppLog.ParseLevel(s.MinLogLevel); Log.Capacity = s.MaxGlobalLogLines; Log.WriteToFile = s.WriteAppLog; - Telegram.TelegramCache.Write(Paths, s); + BidooBidBot.Telegram.TelegramCache.Write(Paths, s); } /// diff --git a/Mimante/src/BidooBidBot/Host/BotWorld.cs b/Mimante/src/BidooBidBot/Host/BotWorld.cs new file mode 100644 index 0000000..709e283 --- /dev/null +++ b/Mimante/src/BidooBidBot/Host/BotWorld.cs @@ -0,0 +1,204 @@ +using BidooBidBot.Bidoo; +using BidooBidBot.Data; +using BidooBidBot.Engine; +using BidooBidBot.Ml; +using BidooBidBot.Net; +using BidooBidBot.Products; +using BidooBidBot.Session; +using BidooBidBot.Simulator; +using BidooBidBot.Strategy; + +namespace BidooBidBot.Host; + +/// +/// I servizi legati a un mondo: il sito vero (con la sessione salvata) o il simulatore +/// interno (al primo avvio, senza sessione). Trasporto, conto, orologio, apprendimento, +/// registrazione, strategia, monitor e sorveglianza dei prodotti nascono e muoiono insieme; +/// passare dal simulatore al sito vero significa buttare una pila e costruirne un'altra. +/// +/// Il simulatore non contamina il sito vero: aste con type = 'sim', modello in +/// ml-sim/*, rischio e latenza solo in memoria, elenco in un documento suo. +/// +public sealed class BotWorld : IAsyncDisposable +{ + private readonly CancellationTokenSource _cts; + private readonly List _jobs = new(); + + public string Name { get; } + public bool IsSimulator => Name == Worlds.Simulator; + public SimulatedBidoo? Sim { get; private init; } + public required Func References { get; init; } + public required BidooTransport Transport { get; init; } + public required BidLane Lane { get; init; } + public required BidooApi Api { get; init; } + public required CatalogClient Catalog { get; init; } + public required AccountState Account { get; init; } + public required LatencyModel Latency { get; init; } + public required LearningService Learning { get; init; } + public required AuctionRecorder Recorder { get; init; } + public required RiskManager Risk { get; init; } + public required BidStrategy Strategy { get; init; } + public required AuctionMonitor Monitor { get; init; } + public required ProductWatcher Watcher { get; init; } + public SessionChecker? Checker { get; private init; } + + private BotWorld(string name, CancellationToken parent) + { + Name = name; + _cts = CancellationTokenSource.CreateLinkedTokenSource(parent); + } + + public CancellationToken Token => _cts.Token; + + /// Il sito vero con la sessione salvata. + public static async Task CreateRealAsync(Bot bot, BidooSession session, CancellationToken parent) + { + var settings = bot.Settings; + Func refs = () => bot.ReferencesProvider.Current; + var transport = new BidooTransport(refs, settings.Current.MaxRequestsPerSecond); + transport.SetSession(session.Cookie, session.UserAgent); + var lane = new BidLane(transport, refs); + var api = new BidooApi(transport, lane, refs) { Username = session.Username }; + + var account = new AccountState(); + account.SetUser(session.Username, session.UserId); + account.SetSessionInfo(session.SavedAtUtc, session.Source); + account.SetStatus(SessionStatus.Checking, null); + + var world = await BuildAsync(bot, Worlds.Real, refs, transport, lane, api, account, bot.Risk, new LatencyModel(bot.Documents), + "ml/", "monitor/auctions", null, parent).ConfigureAwait(false); + return world; + } + + /// Il simulatore interno: si vede il bot all'opera senza sessione. + public static async Task CreateSimulatorAsync(Bot bot, CancellationToken parent) + { + var sim = await SimulatedBidoo.StartAsync(new SimWorld(seed: Environment.TickCount)).ConfigureAwait(false); + var simRefs = sim.References(bot.ReferencesProvider.Current); + Func refs = () => simRefs; + var transport = new BidooTransport(refs, 0); + var lane = new BidLane(transport, refs, keepWarm: false); + var api = new BidooApi(transport, lane, refs) { Username = sim.World.MyUsername }; + + var account = new AccountState(); + account.SetUser(sim.World.MyUsername, sim.World.MyUserId); + account.SetBids(sim.World.PaidBids, sim.World.FreeBids); + account.SetCredit(sim.World.ShopCredit); + account.SetToConfirm(sim.World.WonToConfirm); + account.SetSessionInfo(DateTime.UtcNow, "simulatore"); + account.SetStatus(SessionStatus.Simulator, "nessuna sessione Bidoo: stai vedendo il simulatore"); + + var risk = new RiskManager(new MemoryDocumentStore(), new MemoryRiskLedger(), log: bot.Log); + return await BuildAsync(bot, Worlds.Simulator, refs, transport, lane, api, account, risk, new LatencyModel(new MemoryDocumentStore()), + "ml-sim/", "monitor/auctions-sim", sim, parent).ConfigureAwait(false); + } + + private static async Task BuildAsync(Bot bot, string name, Func refs, BidooTransport transport, BidLane lane, + BidooApi api, AccountState account, RiskManager risk, LatencyModel latency, string mlPrefix, string listKey, SimulatedBidoo? sim, + CancellationToken parent) + { + var settings = bot.Settings; + var learning = new LearningService(bot.Documents, new DbLearningData(bot.Db, bot.Queue, name), () => settings.Current, bot.Log, mlPrefix); + var recorder = new AuctionRecorder(bot.Queue, bot.Db, () => settings.Current, () => account.Username, name); + var strategy = new BidStrategy(risk, learning, bot.Products, () => account.Balance); + var catalog = new CatalogClient(transport, refs, bot.Log); + + var monitor = new AuctionMonitor(new MonitorDeps + { + Settings = () => settings.Current, + References = refs, + Api = api, + Clock = new ServerClock(), + Strategy = strategy, + Risk = risk, + Learning = learning, + Latency = latency, + Recorder = recorder, + Products = bot.Products, + Account = account, + Log = bot.Log, + Documents = bot.Documents, + AuctionFile = bot.Host.FileLog, + Db = bot.Db, + Queue = bot.Queue, + World = name, + DocumentKey = listKey + }); + + var world = new BotWorld(name, parent) + { + Sim = sim, + References = refs, + Transport = transport, + Lane = lane, + Api = api, + Catalog = catalog, + Account = account, + Latency = latency, + Learning = learning, + Recorder = recorder, + Risk = risk, + Strategy = strategy, + Monitor = monitor, + Watcher = new ProductWatcher(catalog, bot.Products, monitor, () => settings.Current, bot.Log), + Checker = sim == null ? new SessionChecker(api, account, bot.Log) : null + }; + + await recorder.InitAsync().ConfigureAwait(false); + await learning.LoadAsync().ConfigureAwait(false); + return world; + } + + /// Ripristina l'elenco e avvia motori e lavori periodici del mondo. + public async Task StartAsync(Bot bot) + { + var ct = _cts.Token; + Learning.StartBootstrap(ct); + var restored = await Monitor.RestoreAsync().ConfigureAwait(false); + if (IsSimulator && restored == 0) await SeedSimulatorAsync(ct).ConfigureAwait(false); + Monitor.Start(); + + if (Checker != null) + { + _jobs.Add(Task.Run(() => Transport.WarmUpAsync(ct), ct)); + _jobs.Add(Checker.RunAsync(ct)); + } + _jobs.Add(Watcher.RunAsync(ct)); + bot.Log.Info("AVVIO", IsSimulator + ? "Stai vedendo il simulatore: nessuna sessione Bidoo salvata. Apri «Accesso a Bidoo» per collegarti al sito vero" + : $"Sito vero: sessione di {Account.Username ?? "utente da verificare"} ({Account.SessionSource}), {Monitor.Auctions.Count} aste in elenco"); + } + + /// Al primo giro nel simulatore l'elenco non è vuoto: qualche asta in ogni modo, per vedere il bot all'opera. + private async Task SeedSimulatorAsync(CancellationToken ct) + { + if (Sim == null) return; + var ids = Sim.World.Read(w => w.Auctions.Where(a => a.Status == "ON").Select(a => a.Id).Take(8).ToList()); + var i = 0; + foreach (var id in ids) + { + var mode = i switch { < 3 => RunMode.Active, 7 => RunMode.Stopped, _ => RunMode.Watch }; + await Monitor.AddAsync(new AddAuctionRequest(id, "catalogo", mode), ct).ConfigureAwait(false); + i++; + } + } + + public async ValueTask DisposeAsync() + { + if (!_cts.IsCancellationRequested) await _cts.CancelAsync().ConfigureAwait(false); + await Monitor.DisposeAsync().ConfigureAwait(false); + try { await Task.WhenAll(_jobs).WaitAsync(TimeSpan.FromSeconds(5)).ConfigureAwait(false); } catch { /* lavori già fermi o in errore */ } + Learning.Save(force: true); + Latency.Save(force: true); + Lane.Dispose(); + Transport.Dispose(); + if (Sim != null) await Sim.DisposeAsync().ConfigureAwait(false); + _cts.Dispose(); + } +} + +/// Il libro del rischio del simulatore: in memoria, non tocca risk_ledger. +internal sealed class MemoryRiskLedger : IRiskLedger +{ + public void Append(string kind, double amountEuro, string? auctionId, string? note) { } +} diff --git a/Mimante/src/BidooBidBot/Ml/LearningData.cs b/Mimante/src/BidooBidBot/Ml/LearningData.cs index 200c7ac..28f6933 100644 --- a/Mimante/src/BidooBidBot/Ml/LearningData.cs +++ b/Mimante/src/BidooBidBot/Ml/LearningData.cs @@ -44,25 +44,28 @@ public sealed class DbLearningData : ILearningData { private readonly Db _db; private readonly WriteQueue _queue; + private readonly string _world; - public DbLearningData(Db db, WriteQueue queue) + /// Il mondo da cui imparare: il sito vero o il simulatore (). + public DbLearningData(Db db, WriteQueue queue, string world = Worlds.Real) { _db = db; _queue = queue; + _world = world; } public Task FlushAsync() => _queue.FlushAsync(TimeSpan.FromSeconds(30)); public Task> PendingAuctionIdsAsync() => - _db.QueryAsync("SELECT auction_id FROM auctions WHERE outcome IS NOT NULL AND learned_at IS NULL ORDER BY end_time DESC", - r => r.Str("auction_id")); + _db.QueryAsync("SELECT auction_id FROM auctions WHERE outcome IS NOT NULL AND learned_at IS NULL AND type = $1 ORDER BY end_time DESC", + r => r.Str("auction_id"), _world); public async Task PendingCountAsync() => - (int)(await _db.ScalarAsync("SELECT COUNT(*) FROM auctions WHERE outcome IS NOT NULL AND learned_at IS NULL").ConfigureAwait(false)); + (int)(await _db.ScalarAsync("SELECT COUNT(*) FROM auctions WHERE outcome IS NOT NULL AND learned_at IS NULL AND type = $1", _world).ConfigureAwait(false)); public async Task> ClosedAuctionIdsAsync(int max) { - var ids = await _db.QueryAsync("SELECT auction_id FROM auctions WHERE outcome IS NOT NULL ORDER BY end_time", r => r.Str("auction_id")).ConfigureAwait(false); + var ids = await _db.QueryAsync("SELECT auction_id FROM auctions WHERE outcome IS NOT NULL AND type = $1 ORDER BY end_time", r => r.Str("auction_id"), _world).ConfigureAwait(false); return max > 0 && ids.Count > max ? ids.Skip(ids.Count - max).ToList() : ids; } @@ -105,23 +108,28 @@ public sealed class DbLearningData : ILearningData public async Task MarkAllUnlearnedAsync() { await FlushAsync().ConfigureAwait(false); - await _db.ExecuteAsync("UPDATE auctions SET learned_at = NULL").ConfigureAwait(false); + await _db.ExecuteAsync("UPDATE auctions SET learned_at = NULL WHERE type = $1", _world).ConfigureAwait(false); } public Task> OwnBidOutcomesAsync(string? auctionId) => - _db.QueryAsync( - "SELECT p_win, outcome FROM bot_decisions WHERE NOT shadow AND executed AND p_win IS NOT NULL AND outcome IN ('won', 'answered')" + - (auctionId != null ? " AND auction_id = $1" : ""), - r => (r.Dbl("p_win"), r.Str("outcome")), - auctionId != null ? new object?[] { auctionId } : Array.Empty()); + auctionId != null + ? _db.QueryAsync( + "SELECT p_win, outcome FROM bot_decisions WHERE auction_id = $1 AND NOT shadow AND executed AND p_win IS NOT NULL AND outcome IN ('won', 'answered')", + r => (r.Dbl("p_win"), r.Str("outcome")), auctionId) + : _db.QueryAsync( + "SELECT d.p_win, d.outcome FROM bot_decisions d JOIN auctions a ON a.auction_id = d.auction_id " + + "WHERE a.type = $1 AND NOT d.shadow AND d.executed AND d.p_win IS NOT NULL AND d.outcome IN ('won', 'answered')", + r => (r.Dbl("p_win"), r.Str("outcome")), _world); public Task> DecisionOutcomesAsync(string auctionId) => _db.QueryAsync("SELECT context_key, outcome FROM bot_decisions WHERE auction_id = $1 AND context_key IS NOT NULL AND outcome IS NOT NULL", r => (r.Str("context_key"), r.Str("outcome")), auctionId); public Task> AuctionsWithDecisionOutcomesAsync() => - _db.QueryAsync("SELECT DISTINCT auction_id FROM bot_decisions WHERE context_key IS NOT NULL AND outcome IS NOT NULL ORDER BY auction_id", - r => r.Str("auction_id")); + _db.QueryAsync( + "SELECT DISTINCT d.auction_id FROM bot_decisions d JOIN auctions a ON a.auction_id = d.auction_id " + + "WHERE a.type = $1 AND d.context_key IS NOT NULL AND d.outcome IS NOT NULL ORDER BY d.auction_id", + r => r.Str("auction_id"), _world); public Task> DecisionsForReasonAsync(string auctionId) => _db.QueryAsync("SELECT action, kind, p_win, shadow, outcome FROM bot_decisions WHERE auction_id = $1 ORDER BY decision_id", @@ -129,7 +137,7 @@ public sealed class DbLearningData : ILearningData auctionId); public Task> MyBidsForReasonAsync(string auctionId) => - _db.QueryAsync("SELECT price, answered_after_s, answered_by, answered_type, unanswered FROM my_bids WHERE auction_id = $1 AND success ORDER BY id", + _db.QueryAsync("SELECT price, answered_after_s, answered_by, answered_type, unanswered FROM my_bids WHERE auction_id = $1 AND success AND NOT manual ORDER BY id", r => new LossReasons.MyBidRow(r.Dbl("price"), r.DblOrNull("answered_after_s"), r.StrOrNull("answered_by"), r.StrOrNull("answered_type"), r.BoolOrNull("unanswered")), auctionId); @@ -139,17 +147,17 @@ public sealed class DbLearningData : ILearningData public Task> ClosedAuctionsAsync(int max) => _db.QueryAsync( "SELECT auction_id, product_key, end_time, final_price, buy_now_price, market_value, winner_bids_paid, winner_bids_free, opened_at, won_by_me, winner_user " + - "FROM auctions WHERE outcome IS NOT NULL AND final_price IS NOT NULL AND end_time IS NOT NULL ORDER BY end_time DESC LIMIT $1", + "FROM auctions WHERE outcome IS NOT NULL AND final_price IS NOT NULL AND end_time IS NOT NULL AND type = $2 ORDER BY end_time DESC LIMIT $1", r => new ClosedAuctionRow(r.Str("auction_id"), r.Str("product_key"), r.Date("end_time")!.Value, r.Dbl("final_price"), r.DblOrNull("buy_now_price"), r.DblOrNull("market_value"), r.IntOrNull("winner_bids_paid"), r.IntOrNull("winner_bids_free"), r.Date("opened_at"), r.Bool("won_by_me"), r.Str("winner_user")), - max <= 0 ? 1_000_000 : max); + max <= 0 ? 1_000_000 : max, _world); public async Task> LossReasonSummaryAsync(int days) { var rows = await _db.QueryAsync( - "SELECT loss_reason FROM auctions WHERE outcome IS NOT NULL AND loss_reason IS NOT NULL AND end_time >= now() - make_interval(days => $1)", - r => r.Str("loss_reason"), days).ConfigureAwait(false); + "SELECT loss_reason FROM auctions WHERE outcome IS NOT NULL AND loss_reason IS NOT NULL AND type = $2 AND end_time >= now() - make_interval(days => $1)", + r => r.Str("loss_reason"), days, _world).ConfigureAwait(false); return rows.GroupBy(LossReasons.Group).Select(g => (g.Key, g.Count())).OrderByDescending(t => t.Item2).ToList(); } @@ -158,9 +166,10 @@ public sealed class DbLearningData : ILearningData "SELECT d.action, d.alt_action, d.outcome, d.ev, d.price, d.shadow, d.executed, d.bid_cost, " + " COALESCE(a.market_value, a.buy_now_price, d.value, 0) AS v, COALESCE(a.shipping, 0) AS ship " + "FROM bot_decisions d JOIN auctions a ON a.auction_id = d.auction_id " + - "WHERE d.ts >= now() - make_interval(days => $1) AND d.outcome IS NOT NULL AND d.kind IN ('punta', 'esplora', 'ev-negativo', 'non-pronto')" + + "WHERE a.type = $2 AND d.ts >= now() - make_interval(days => $1) AND d.outcome IS NOT NULL " + + " AND d.kind IN ('punta', 'esplora', 'ev-negativo', 'non-pronto')" + (shadow is { } s ? (s ? " AND d.shadow" : " AND NOT d.shadow") : ""), r => new ShadowReport.Row(r.Str("action"), r.StrOrNull("alt_action"), r.Str("outcome"), r.DblOrNull("ev"), r.Dbl("price"), r.Dbl("v"), r.Dbl("ship"), r.DblOrNull("bid_cost") is > 0 ? r.Dbl("bid_cost") : defaultBidCost, r.Bool("shadow"), r.Bool("executed")), - days); + days, _world); } diff --git a/Mimante/src/BidooBidBot/Products/ProductStats.cs b/Mimante/src/BidooBidBot/Products/ProductStats.cs index fac21bf..6180f51 100644 --- a/Mimante/src/BidooBidBot/Products/ProductStats.cs +++ b/Mimante/src/BidooBidBot/Products/ProductStats.cs @@ -47,7 +47,7 @@ public static class ProductStatsRepository private static readonly JsonSerializerOptions Json = new(); /// Le statistiche di un prodotto, dalle aste concluse. - public static async Task ComputeAsync(Db db, string productKey, double transactionFee) + public static async Task ComputeAsync(Db db, string productKey, double transactionFee, string world = Worlds.Real) { var agg = await db.QueryOneAsync( "SELECT COUNT(*) AS n, SUM(CASE WHEN won_by_me THEN 1 ELSE 0 END) AS won, " + @@ -55,13 +55,13 @@ public static class ProductStatsRepository " COALESCE(SUM(my_bids_cost), 0) AS my_cost, AVG(final_price) AS avg_final, MIN(final_price) AS min_final, " + " MAX(final_price) AS max_final, SUM(CASE WHEN observed_from_start AND observed_to_end THEN 1 ELSE 0 END) AS complete, " + " AVG(observed_minutes) AS avg_minutes, MAX(end_time) AS last_end " + - "FROM auctions WHERE product_key = $1 AND outcome IS NOT NULL AND final_price IS NOT NULL", + "FROM auctions WHERE product_key = $1 AND type = $2 AND outcome IS NOT NULL AND final_price IS NOT NULL", r => new ProductStatsData { Auctions = r.Int("n"), Won = r.Int("won"), WithMyBids = r.Int("with_mine"), MyBidsTotal = r.Int("my_total"), MyBidsCost = r.Dbl("my_cost"), AvgFinal = r.Dbl("avg_final"), MinFinal = r.Dbl("min_final"), MaxFinal = r.Dbl("max_final"), CompleteObservations = r.Int("complete"), AvgObservedMinutes = r.Dbl("avg_minutes"), LastClosedAtUtc = r.Date("last_end") - }, productKey).ConfigureAwait(false); + }, productKey, world).ConfigureAwait(false); if (agg == null || agg.Auctions == 0) return null; @@ -69,11 +69,11 @@ public static class ProductStatsRepository "SELECT a.name, a.final_price, a.winner_bids_paid, a.winner_bids_free, a.buy_now_price, a.shipping, a.won_by_me, " + " a.my_bids_cost, a.market_value, a.end_time, a.transaction_fee, i.image_url " + "FROM auctions a LEFT JOIN items i ON i.product_key = a.product_key " + - "WHERE a.product_key = $1 AND a.outcome IS NOT NULL AND a.final_price IS NOT NULL ORDER BY a.end_time DESC LIMIT 300", + "WHERE a.product_key = $1 AND a.type = $2 AND a.outcome IS NOT NULL AND a.final_price IS NOT NULL ORDER BY a.end_time DESC LIMIT 300", r => (Name: r.Str("name"), Final: r.Dbl("final_price"), Paid: r.IntOrNull("winner_bids_paid"), Free: r.IntOrNull("winner_bids_free"), BuyNow: r.DblOrNull("buy_now_price"), Ship: r.DblOrNull("shipping"), Won: r.Bool("won_by_me"), MyCost: r.Dbl("my_bids_cost"), Value: r.DblOrNull("market_value"), End: r.Date("end_time"), Fee: r.DblOrNull("transaction_fee"), Img: r.StrOrNull("image_url")), - productKey).ConfigureAwait(false); + productKey, world).ConfigureAwait(false); var s = agg; s.Name = recent.FirstOrDefault().Name; @@ -137,7 +137,7 @@ public static class ProductStatsRepository } /// I prodotti con almeno un'asta conclusa: per il ricalcolo completo. - public static Task> ProductKeysAsync(Db db) => - db.QueryAsync("SELECT DISTINCT product_key FROM auctions WHERE outcome IS NOT NULL AND product_key <> '' ORDER BY product_key", - r => r.Str("product_key")); + public static Task> ProductKeysAsync(Db db, string world = Worlds.Real) => + db.QueryAsync("SELECT DISTINCT product_key FROM auctions WHERE outcome IS NOT NULL AND type = $1 AND product_key <> '' ORDER BY product_key", + r => r.Str("product_key"), world); } diff --git a/Mimante/src/BidooBidBot/Products/ProductWatcher.cs b/Mimante/src/BidooBidBot/Products/ProductWatcher.cs new file mode 100644 index 0000000..f50c019 --- /dev/null +++ b/Mimante/src/BidooBidBot/Products/ProductWatcher.cs @@ -0,0 +1,131 @@ +using BidooBidBot.Bidoo; +using BidooBidBot.Engine; +using BidooBidBot.Logging; +using BidooBidBot.Settings; + +namespace BidooBidBot.Products; + +/// +/// La sorveglianza dei prodotti seguiti (portata da ProductWatchService): ogni tanto +/// (90 s di fabbrica) legge il catalogo «Tutte le aste» e aggiunge le aste dei prodotti +/// seguiti, con i paletti del prodotto e nel modo scelto per l'aggiunta automatica. Un'asta +/// proposta o tolta a mano non si ripropone. +/// +public sealed class ProductWatcher +{ + private readonly CatalogClient _catalog; + private readonly ProductStore _products; + private readonly AuctionMonitor _monitor; + private readonly Func _settings; + private readonly AppLog _log; + private int _lastPostponed = -1; + private int _lastAlreadyRunning = -1; + private bool _limitSaid; + + public ProductWatcher(CatalogClient catalog, ProductStore products, AuctionMonitor monitor, Func settings, AppLog log) + { + _catalog = catalog; + _products = products; + _monitor = monitor; + _settings = settings; + _log = log; + } + + public DateTime? LastScanUtc { get; private set; } + + public Task RunAsync(CancellationToken ct) => Task.Run(async () => + { + try { await Task.Delay(5000, ct).ConfigureAwait(false); } catch (OperationCanceledException) { return; } + while (!ct.IsCancellationRequested) + { + var s = _settings(); + if (s.AutoAddProductsEnabled) await ScanOnceAsync(ct).ConfigureAwait(false); + try { await Task.Delay(TimeSpan.FromSeconds(Math.Max(30, s.AutoAddScanSeconds)), ct).ConfigureAwait(false); } + catch (OperationCanceledException) { return; } + } + }, ct); + + /// Un giro di sorveglianza. Restituisce quante aste ha aggiunto. + public async Task ScanOnceAsync(CancellationToken ct) + { + var followed = _products.Followed(); + if (followed.Count == 0) return 0; + + try + { + var settings = _settings(); + var depth = Math.Max(settings.CatalogMaxAuctions, settings.AutoAddScanMaxAuctions); + var auctions = await _catalog.GetAllAuctionsAsync(CatalogCategory.AllAuctions, depth, settings.CatalogCacheSeconds, ct).ConfigureAwait(false); + LastScanUtc = DateTime.UtcNow; + + var matches = new List<(CatalogAuction Auction, ProductRecord Product)>(); + foreach (var auction in auctions) + { + if (_products.IsHandled(auction.AuctionId) || _monitor.Find(auction.AuctionId) != null) continue; + var product = followed.FirstOrDefault(p => p.Matches(auction)); + if (product != null) matches.Add((auction, product)); + } + if (matches.Count == 0) return 0; + + if (settings.AutoAddOnlyNotStarted || matches.Any(m => ProductRules.HorizonSeconds(m.Product, settings) > 0)) + await _catalog.UpdateStatesAsync(matches.Select(m => m.Auction).ToList(), ct).ConfigureAwait(false); + + int added = 0, postponed = 0, running = 0; + var already = _monitor.Auctions.Count(a => a.Origin == "seguito" && !a.IsFinished); + + foreach (var (auction, product) in matches) + { + ct.ThrowIfCancellationRequested(); + var horizon = ProductRules.HorizonSeconds(product, settings); + if (horizon > 0 && auction.RemainingSeconds > horizon) + { + postponed++; + continue; + } + + if (settings.AutoAddOnlyNotStarted && ProductRules.HasStarted(auction)) + { + running++; + _products.MarkProposed(product.ProductKey, auction.AuctionId); + continue; + } + + if (settings.AutoAddMaxAuctions > 0 && already + added >= settings.AutoAddMaxAuctions) + { + if (!_limitSaid) _log.Info("SEGUITI", $"Raggiunto il limite di {settings.AutoAddMaxAuctions} aste aggiunte automaticamente"); + _limitSaid = true; + break; + } + _limitSaid = false; + + var (a, _) = await _monitor.AddAsync(new AddAuctionRequest( + string.IsNullOrEmpty(auction.Url) ? auction.AuctionId : auction.Url, "seguito", null, auction.Name, auction.ImageUrl, + auction.BuyNowPrice is { } b ? (double)b : null, auction.ProductId), ct).ConfigureAwait(false); + _products.MarkProposed(product.ProductKey, auction.AuctionId); + if (a == null) continue; + _products.CountAutoAdded(product.ProductKey); + added++; + } + + if (postponed > 0 && postponed != _lastPostponed) + _log.Info("SEGUITI", $"{postponed} aste rinviate: cominciano oltre l'orizzonte impostato; verranno riprese quando saranno più vicine"); + _lastPostponed = postponed; + + if (running > 0 && running != _lastAlreadyRunning) + _log.Info("SEGUITI", $"{running} aste saltate: erano già cominciate e l'opzione chiede di seguirle solo dall'inizio"); + _lastAlreadyRunning = running; + + if (added > 0) _log.Info("SEGUITI", $"{added} aste aggiunte dai prodotti seguiti"); + return added; + } + catch (OperationCanceledException) + { + return 0; + } + catch (Exception ex) + { + _log.Warn("SEGUITI", $"Scansione non riuscita: {ex.Message}"); + return 0; + } + } +} diff --git a/Mimante/src/BidooBidBot/Session/AccountState.cs b/Mimante/src/BidooBidBot/Session/AccountState.cs new file mode 100644 index 0000000..6198a52 --- /dev/null +++ b/Mimante/src/BidooBidBot/Session/AccountState.cs @@ -0,0 +1,161 @@ +using BidooBidBot.Strategy; + +namespace BidooBidBot.Session; + +/// Lo stato della sessione Bidoo, come lo mostra la barra. +public enum SessionStatus +{ + /// Nessuna sessione salvata: si vede il simulatore. + Missing, + + /// Sessione salvata, verifica in corso. + Checking, + + Valid, + + /// Bidoo risponde con la pagina di login o 403: la sessione va rifatta. + Expired, + + /// Il bot sta seguendo il simulatore interno (nessuna sessione, o scelta). + Simulator +} + +/// +/// Il conto Bidoo come lo conosce il bot: utente, saldo (a pagamento + gratis), credito, +/// aste da confermare, stato della sessione. Lo aggiornano la verifica periodica e ogni +/// risposta di bid.php; lo leggono motore, barra, Telegram. cresce a +/// ogni cambiamento. +/// +public sealed class AccountState +{ + private readonly object _sync = new(); + private int _version; + + public string? Username { get; private set; } + public string? UserId { get; private set; } + public int? Total { get; private set; } + public int? Paid { get; private set; } + public int? Free { get; private set; } + public double? ShopCredit { get; private set; } + public int? ToConfirm { get; private set; } + public SessionStatus Status { get; private set; } = SessionStatus.Missing; + public string? StatusDetail { get; private set; } + public DateTime? CheckedAtUtc { get; private set; } + public DateTime? SessionSince { get; private set; } + public string? SessionSource { get; private set; } + + public int Version => Volatile.Read(ref _version); + + public event Action? StatusChanged; + + public AccountBalance Balance + { + get { lock (_sync) return new AccountBalance(Total, Paid, Free); } + } + + private void Bump() => Interlocked.Increment(ref _version); + + public void SetUser(string? username, string? userId) + { + lock (_sync) + { + if (!string.IsNullOrWhiteSpace(username)) Username = username.Trim(); + if (!string.IsNullOrWhiteSpace(userId)) UserId = userId.Trim(); + } + Bump(); + } + + /// Dal saldo diviso di bid.php: il totale è la somma. + public bool SetBids(int paid, int free) + { + bool changed; + lock (_sync) + { + changed = Paid != paid || Free != free || Total != paid + free; + Paid = paid; + Free = free; + Total = paid + free; + } + if (changed) Bump(); + return changed; + } + + /// + /// Il saldo totale letto da una pagina. La divisione resta solo se torna con il totale; + /// altrimenti non si sa più com'è diviso (dal legacy). + /// + public bool SetTotal(int total) + { + bool changed; + lock (_sync) + { + changed = Total != total; + if (Paid is { } p && Free is { } f && p + f != total) + { + Paid = null; + Free = null; + } + Total = total; + } + if (changed) Bump(); + return changed; + } + + public void SetCredit(double? credit) + { + lock (_sync) ShopCredit = credit; + Bump(); + } + + public void SetToConfirm(int? count) + { + if (count == null) return; // «non lo so» non cancella una vincita vera + lock (_sync) ToConfirm = count; + Bump(); + } + + public void SetStatus(SessionStatus status, string? detail) + { + bool changed; + lock (_sync) + { + changed = Status != status; + Status = status; + StatusDetail = detail; + CheckedAtUtc = DateTime.UtcNow; + } + Bump(); + if (changed) StatusChanged?.Invoke(status, detail); + } + + public void SetSessionInfo(DateTime? since, string? source) + { + lock (_sync) + { + SessionSince = since; + SessionSource = source; + } + Bump(); + } + + public void Clear() + { + lock (_sync) + { + Username = null; UserId = null; Total = null; Paid = null; Free = null; ShopCredit = null; ToConfirm = null; + SessionSince = null; SessionSource = null; + } + Bump(); + } + + /// «1.407 (927 + 480)», o solo il totale se la divisione non è nota. + public string BalanceText() + { + var it = System.Globalization.CultureInfo.GetCultureInfo("it-IT"); + lock (_sync) + { + if (Total is not { } t) return "n.d."; + return Paid is { } p && Free is { } f ? $"{t.ToString("N0", it)} ({p.ToString("N0", it)} + {f.ToString("N0", it)})" : t.ToString("N0", it); + } + } +} diff --git a/Mimante/src/BidooBidBot/Session/Cdp/AssistedLogin.cs b/Mimante/src/BidooBidBot/Session/Cdp/AssistedLogin.cs new file mode 100644 index 0000000..f9368dc --- /dev/null +++ b/Mimante/src/BidooBidBot/Session/Cdp/AssistedLogin.cs @@ -0,0 +1,249 @@ +using System.Text.Json; +using BidooBidBot.Bidoo; +using BidooBidBot.Logging; +using BidooBidBot.Net; + +namespace BidooBidBot.Session.Cdp; + +/// Un gesto dell'utente sul riquadro del browser, in pixel della pagina. +public sealed record LoginInput( + string Kind, string? Type, double X, double Y, string? Button, int ClickCount, string? Key, string? Code, string? Text, + int Modifiers, double DeltaX, double DeltaY, int KeyCode) +{ + public static LoginInput From(JsonElement m) + { + string? S(string n) => m.TryGetProperty(n, out var v) && v.ValueKind == JsonValueKind.String ? v.GetString() : null; + double D(string n) => m.TryGetProperty(n, out var v) && v.ValueKind == JsonValueKind.Number ? v.GetDouble() : 0; + return new LoginInput(S("kind") ?? "", S("type"), D("x"), D("y"), S("button"), (int)D("clickCount"), S("key"), S("code"), S("text"), + (int)D("modifiers"), D("deltaX"), D("deltaY"), (int)D("keyCode")); + } +} + +/// +/// L'accesso assistito (specifica §6.5): Chromium senza finestra apre la pagina di login di +/// Bidoo, l'interfaccia ne mostra lo screencast e inoltra clic e tasti; quando l'indirizzo +/// esce dal login e c'è il cookie di sessione, i cookie si salvano e il browser si chiude. +/// La password di Bidoo passa solo dal browser del bot a Bidoo: il bot non la vede come +/// campo, vede soltanto tasti. +/// +public sealed class AssistedLogin : IAsyncDisposable +{ + private readonly string _profileDir; + private readonly Func _refs; + private readonly AppLog _log; + private readonly SemaphoreSlim _gate = new(1, 1); + private ChromiumProcess? _chromium; + private CdpClient? _cdp; + private string? _session; + private string? _userAgent; + private string _url = ""; + private CancellationTokenSource? _watch; + private long _lastInput; + private volatile bool _done; + + public AssistedLogin(string profileDir, Func refs, AppLog log) + { + _profileDir = profileDir; + _refs = refs; + _log = log; + } + + /// Un fotogramma JPEG (base64), le sue dimensioni in pixel della pagina, l'indirizzo. + public event Action? Frame; + + /// «aperto», «riuscito», «chiuso», «errore», con il dettaglio. + public event Action? State; + + /// L'accesso è riuscito: la sessione da salvare. + public event Func? LoggedIn; + + public bool IsOpen => _cdp != null && !_cdp.IsClosed; + public string CurrentUrl => _url; + + public static bool Available => ChromiumProcess.FindExecutable() != null; + + public async Task<(bool Ok, string Message)> OpenAsync(CancellationToken ct) + { + await _gate.WaitAsync(ct).ConfigureAwait(false); + try + { + if (IsOpen) + { + State?.Invoke("aperto", _url); + return (true, "Il browser del bot è già aperto"); + } + await CloseCoreAsync(null).ConfigureAwait(false); + _done = false; + + var refs = _refs(); + _chromium = await ChromiumProcess.StartAsync(_profileDir, ct).ConfigureAwait(false); + _cdp = await CdpClient.ConnectAsync(_chromium.Endpoint, ct).ConfigureAwait(false); + _cdp.Event += OnEvent; + _cdp.Closed += () => { if (!_done) State?.Invoke("chiuso", "il browser del bot si è chiuso"); }; + + var version = await _cdp.SendAsync("Browser.getVersion", ct: ct).ConfigureAwait(false); + _userAgent = (version.TryGetProperty("userAgent", out var ua) ? ua.GetString() : null)?.Replace("HeadlessChrome", "Chrome", StringComparison.Ordinal); + + var target = await _cdp.SendAsync("Target.createTarget", new { url = "about:blank" }, ct: ct).ConfigureAwait(false); + var targetId = target.GetProperty("targetId").GetString(); + var attached = await _cdp.SendAsync("Target.attachToTarget", new { targetId, flatten = true }, ct: ct).ConfigureAwait(false); + _session = attached.GetProperty("sessionId").GetString(); + + await _cdp.SendAsync("Page.enable", sessionId: _session, ct: ct).ConfigureAwait(false); + await _cdp.SendAsync("Network.enable", sessionId: _session, ct: ct).ConfigureAwait(false); + if (_userAgent != null) + await _cdp.SendAsync("Network.setUserAgentOverride", new { userAgent = _userAgent, acceptLanguage = "it-IT,it;q=0.9,en;q=0.7" }, _session, ct).ConfigureAwait(false); + await _cdp.SendAsync("Emulation.setDeviceMetricsOverride", new { width = 1280, height = 900, deviceScaleFactor = 1, mobile = false }, _session, ct).ConfigureAwait(false); + await _cdp.SendAsync("Page.navigate", new { url = refs.Url(refs.Endpoints.Login) }, _session, ct).ConfigureAwait(false); + await _cdp.SendAsync("Page.startScreencast", new { format = "jpeg", quality = 60, maxWidth = 1280, maxHeight = 900, everyNthFrame = 1 }, _session, ct).ConfigureAwait(false); + + _lastInput = Environment.TickCount64; + _watch = new CancellationTokenSource(); + _ = Task.Run(() => WatchAsync(_watch.Token)); + _log.Info("SESSIONE", "Accesso assistito: browser del bot aperto sulla pagina di login di Bidoo"); + State?.Invoke("aperto", refs.Url(refs.Endpoints.Login)); + return (true, "Browser del bot aperto: accedi a Bidoo nel riquadro"); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + await CloseCoreAsync(null).ConfigureAwait(false); + var msg = $"Browser del bot non avviato: {ex.Message}"; + _log.Warn("SESSIONE", msg); + State?.Invoke("errore", msg); + return (false, msg); + } + finally + { + _gate.Release(); + } + } + + private void OnEvent(string method, JsonElement p, string? session) + { + switch (method) + { + case "Page.screencastFrame": + var frameSession = p.GetProperty("sessionId").GetInt32(); + _cdp?.Post("Page.screencastFrameAck", new { sessionId = frameSession }, _session); + var meta = p.GetProperty("metadata"); + var w = (int)Math.Round(meta.GetProperty("deviceWidth").GetDouble()); + var h = (int)Math.Round(meta.GetProperty("deviceHeight").GetDouble()); + Frame?.Invoke(p.GetProperty("data").GetString() ?? "", w, h, _url); + break; + case "Page.frameNavigated": + var frame = p.GetProperty("frame"); + if (!frame.TryGetProperty("parentId", out _)) _url = frame.GetProperty("url").GetString() ?? ""; + break; + } + } + + /// Ogni secondo: siamo usciti dal login con il cookie di sessione? Dieci minuti fermi chiudono il browser. + private async Task WatchAsync(CancellationToken ct) + { + while (!ct.IsCancellationRequested && IsOpen) + { + try { await Task.Delay(1000, ct).ConfigureAwait(false); } catch (OperationCanceledException) { return; } + if (Environment.TickCount64 - _lastInput > 10 * 60 * 1000) + { + await CloseAsync("dieci minuti senza attività").ConfigureAwait(false); + return; + } + + try + { + var refs = _refs(); + if (_url.Length == 0 || refs.Recognizers.LoginPageMarkers.Any(m => _url.Contains(m, StringComparison.OrdinalIgnoreCase))) continue; + if (!_url.StartsWith(refs.BaseUrl, StringComparison.OrdinalIgnoreCase)) continue; + + var result = await _cdp!.SendAsync("Network.getCookies", new { urls = new[] { refs.BaseUrl + "/" } }, _session, ct).ConfigureAwait(false); + var cookies = new List<(string, string)>(); + foreach (var c in result.GetProperty("cookies").EnumerateArray()) + cookies.Add((c.GetProperty("name").GetString() ?? "", c.GetProperty("value").GetString() ?? "")); + if (!cookies.Any(c => c.Item1 == refs.Recognizers.SessionCookie)) continue; + + _done = true; + var session = new BidooSession { Cookie = CookieText.Join(cookies), UserAgent = _userAgent, Source = SessionStore.SourceAssisted }; + State?.Invoke("riuscito", "Accesso riuscito: salvo la sessione e chiudo il browser del bot"); + _log.Success("SESSIONE", "Accesso assistito riuscito: cookie di sessione ricevuti"); + await CloseAsync(null).ConfigureAwait(false); + if (LoggedIn != null) await LoggedIn(session).ConfigureAwait(false); + return; + } + catch (OperationCanceledException) { return; } + catch (CdpException) { /* pagina in caricamento: si riprova */ } + } + } + + public async Task InputAsync(LoginInput input, CancellationToken ct) + { + var cdp = _cdp; + if (cdp == null || !IsOpen) return; + _lastInput = Environment.TickCount64; + switch (input.Kind) + { + case "mouse": + var type = input.Type is "mousePressed" or "mouseReleased" or "mouseMoved" or "mouseWheel" ? input.Type : "mouseMoved"; + await cdp.SendAsync("Input.dispatchMouseEvent", new + { + type, x = input.X, y = input.Y, button = input.Button ?? (type == "mouseMoved" ? "none" : "left"), + clickCount = Math.Max(input.ClickCount, type is "mousePressed" or "mouseReleased" ? 1 : 0), + modifiers = input.Modifiers, deltaX = input.DeltaX, deltaY = input.DeltaY + }, _session, ct).ConfigureAwait(false); + break; + case "key": + var keyType = input.Type == "keyUp" ? "keyUp" : "keyDown"; + // I tasti che scrivono passano da insertText (più affidabile con le tastiere italiane); + // qui restano quelli di controllo: Invio, Tab, frecce, cancellazione. + await cdp.SendAsync("Input.dispatchKeyEvent", new + { + type = keyType == "keyDown" ? "rawKeyDown" : "keyUp", key = input.Key, code = input.Code, + windowsVirtualKeyCode = input.KeyCode, nativeVirtualKeyCode = input.KeyCode, modifiers = input.Modifiers + }, _session, ct).ConfigureAwait(false); + if (keyType == "keyDown" && input.Key == "Enter") + await cdp.SendAsync("Input.dispatchKeyEvent", new { type = "char", text = "\r", key = "Enter" }, _session, ct).ConfigureAwait(false); + break; + case "text": + if (!string.IsNullOrEmpty(input.Text)) + await cdp.SendAsync("Input.insertText", new { text = input.Text }, _session, ct).ConfigureAwait(false); + break; + } + } + + public async Task ReloadAsync(CancellationToken ct) + { + if (_cdp == null || !IsOpen) return; + _lastInput = Environment.TickCount64; + await _cdp.SendAsync("Page.reload", new { ignoreCache = false }, _session, ct).ConfigureAwait(false); + } + + public async Task CloseAsync(string? reason) + { + await _gate.WaitAsync().ConfigureAwait(false); + try { await CloseCoreAsync(reason).ConfigureAwait(false); } + finally { _gate.Release(); } + } + + private async Task CloseCoreAsync(string? reason) + { + _watch?.Cancel(); + _watch = null; + var cdp = _cdp; + _cdp = null; + if (cdp != null) + { + try { await cdp.SendAsync("Browser.close", timeout: TimeSpan.FromSeconds(3)).ConfigureAwait(false); } catch { } + await cdp.DisposeAsync().ConfigureAwait(false); + } + var chromium = _chromium; + _chromium = null; + if (chromium != null) await chromium.DisposeAsync().ConfigureAwait(false); + _session = null; + if (reason != null) + { + _log.Info("SESSIONE", $"Browser del bot chiuso: {reason}"); + State?.Invoke("chiuso", reason); + } + } + + public async ValueTask DisposeAsync() => await CloseAsync(null).ConfigureAwait(false); +} diff --git a/Mimante/src/BidooBidBot/Session/Cdp/CdpClient.cs b/Mimante/src/BidooBidBot/Session/Cdp/CdpClient.cs new file mode 100644 index 0000000..11b6948 --- /dev/null +++ b/Mimante/src/BidooBidBot/Session/Cdp/CdpClient.cs @@ -0,0 +1,178 @@ +using System.Collections.Concurrent; +using System.Net.WebSockets; +using System.Text; +using System.Text.Json; +using System.Text.Json.Nodes; + +namespace BidooBidBot.Session.Cdp; + +/// Un errore restituito da Chromium a un comando CDP. +public sealed class CdpException(string method, string message) : Exception($"{method}: {message}"); + +/// Il canale verso Chromium: in produzione un WebSocket, nei test una coda in memoria. +public interface ICdpTransport : IAsyncDisposable +{ + Task SendAsync(string json, CancellationToken ct); + + /// Il prossimo messaggio intero; null quando il canale si chiude. + Task ReceiveAsync(CancellationToken ct); +} + +/// +/// Client del Chrome DevTools Protocol scritto a mano (specifica §6.5): JSON-RPC su +/// WebSocket, id incrementale, mappa delle risposte in attesa, eventi con +/// sessionId (sessioni piatte, Target.attachToTarget con flatten: true). +/// Niente Playwright: servono una decina di comandi. +/// +public sealed class CdpClient : IAsyncDisposable +{ + private readonly ICdpTransport _transport; + private readonly ConcurrentDictionary Tcs)> _pending = new(); + private readonly CancellationTokenSource _cts = new(); + private readonly Task _reader; + private int _nextId; + + /// Un evento: metodo, parametri, sessione (null = browser). + public event Action? Event; + + /// Il canale si è chiuso (Chromium uscito). + public event Action? Closed; + + public CdpClient(ICdpTransport transport) + { + _transport = transport; + _reader = Task.Run(() => ReadLoopAsync(_cts.Token)); + } + + public static async Task ConnectAsync(Uri endpoint, CancellationToken ct) + { + var ws = new ClientWebSocket(); + ws.Options.KeepAliveInterval = TimeSpan.FromSeconds(20); + await ws.ConnectAsync(endpoint, ct).ConfigureAwait(false); + return new CdpClient(new WebSocketCdpTransport(ws)); + } + + public bool IsClosed { get; private set; } + + /// Un comando; la risposta è il campo result. Un error diventa . + public async Task SendAsync(string method, object? parameters = null, string? sessionId = null, + CancellationToken ct = default, TimeSpan? timeout = null) + { + if (IsClosed) throw new CdpException(method, "browser chiuso"); + var id = Interlocked.Increment(ref _nextId); + var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + _pending[id] = (method, tcs); + + var message = new JsonObject { ["id"] = id, ["method"] = method }; + if (parameters != null) message["params"] = JsonSerializer.SerializeToNode(parameters); + if (sessionId != null) message["sessionId"] = sessionId; + + try + { + await _transport.SendAsync(message.ToJsonString(), ct).ConfigureAwait(false); + return await tcs.Task.WaitAsync(timeout ?? TimeSpan.FromSeconds(15), ct).ConfigureAwait(false); + } + catch (TimeoutException) + { + throw new CdpException(method, "nessuna risposta dal browser"); + } + finally + { + _pending.TryRemove(id, out _); + } + } + + /// Un comando di cui non interessa la risposta (conferme dei frame, input). + public void Post(string method, object? parameters = null, string? sessionId = null) => + _ = SendAsync(method, parameters, sessionId).ContinueWith(t => _ = t.Exception, TaskScheduler.Default); + + private async Task ReadLoopAsync(CancellationToken ct) + { + try + { + while (!ct.IsCancellationRequested) + { + var text = await _transport.ReceiveAsync(ct).ConfigureAwait(false); + if (text == null) break; + Handle(text); + } + } + catch (OperationCanceledException) { } + catch (WebSocketException) { } + finally + { + IsClosed = true; + foreach (var (_, p) in _pending) p.Tcs.TrySetException(new CdpException(p.Method, "browser chiuso")); + _pending.Clear(); + Closed?.Invoke(); + } + } + + /// Smista un messaggio in arrivo: risposta a un comando o evento. + internal void Handle(string text) + { + using var doc = JsonDocument.Parse(text); + var root = doc.RootElement; + if (root.TryGetProperty("id", out var idEl) && idEl.TryGetInt32(out var id)) + { + if (!_pending.TryGetValue(id, out var p)) return; + if (root.TryGetProperty("error", out var err)) + p.Tcs.TrySetException(new CdpException(p.Method, err.TryGetProperty("message", out var msg) ? msg.GetString() ?? "errore" : "errore")); + else + p.Tcs.TrySetResult(root.TryGetProperty("result", out var result) ? result.Clone() : default); + return; + } + + if (root.TryGetProperty("method", out var method)) + { + var session = root.TryGetProperty("sessionId", out var s) ? s.GetString() : null; + var parameters = root.TryGetProperty("params", out var pr) ? pr.Clone() : default; + try { Event?.Invoke(method.GetString() ?? "", parameters, session); } + catch { /* un gestore rotto non chiude il canale */ } + } + } + + public async ValueTask DisposeAsync() + { + await _cts.CancelAsync().ConfigureAwait(false); + await _transport.DisposeAsync().ConfigureAwait(false); + try { await _reader.WaitAsync(TimeSpan.FromSeconds(2)).ConfigureAwait(false); } catch { } + _cts.Dispose(); + } +} + +/// Il WebSocket di Chromium (ws://127.0.0.1:porta/devtools/browser/…). +internal sealed class WebSocketCdpTransport(ClientWebSocket ws) : ICdpTransport +{ + private readonly SemaphoreSlim _sendGate = new(1, 1); + + public async Task SendAsync(string json, CancellationToken ct) + { + await _sendGate.WaitAsync(ct).ConfigureAwait(false); + try { await ws.SendAsync(Encoding.UTF8.GetBytes(json), WebSocketMessageType.Text, true, ct).ConfigureAwait(false); } + finally { _sendGate.Release(); } + } + + public async Task ReceiveAsync(CancellationToken ct) + { + var buffer = new byte[64 * 1024]; + using var ms = new MemoryStream(); + while (true) + { + var r = await ws.ReceiveAsync(buffer, ct).ConfigureAwait(false); + if (r.MessageType == WebSocketMessageType.Close) return null; + ms.Write(buffer, 0, r.Count); + if (r.EndOfMessage) return Encoding.UTF8.GetString(ms.GetBuffer(), 0, (int)ms.Length); + } + } + + public async ValueTask DisposeAsync() + { + if (ws.State == WebSocketState.Open) + { + try { await ws.CloseAsync(WebSocketCloseStatus.NormalClosure, "fine", CancellationToken.None).WaitAsync(TimeSpan.FromSeconds(2)).ConfigureAwait(false); } + catch { } + } + ws.Dispose(); + } +} diff --git a/Mimante/src/BidooBidBot/Session/Cdp/ChromiumProcess.cs b/Mimante/src/BidooBidBot/Session/Cdp/ChromiumProcess.cs new file mode 100644 index 0000000..1e96e40 --- /dev/null +++ b/Mimante/src/BidooBidBot/Session/Cdp/ChromiumProcess.cs @@ -0,0 +1,124 @@ +using System.Diagnostics; +using System.Globalization; + +namespace BidooBidBot.Session.Cdp; + +/// +/// Chromium senza finestra per l'accesso assistito (specifica §6.5). Il profilo sta in +/// /config/browser e resta fra un accesso e l'altro; l'indirizzo del protocollo si +/// legge da DevToolsActivePort (porta scelta dal browser: nessun conflitto). +/// +public sealed class ChromiumProcess : IAsyncDisposable +{ + private readonly Process _process; + + public Uri Endpoint { get; } + + private ChromiumProcess(Process process, Uri endpoint) + { + _process = process; + Endpoint = endpoint; + } + + public bool HasExited => _process.HasExited; + + /// Dove cercare il browser: l'immagine Docker ha /usr/bin/chromium; in sviluppo Chrome o Edge. + public static IEnumerable Candidates() + { + yield return "/usr/bin/chromium"; + yield return "/usr/bin/chromium-browser"; + yield return "/usr/bin/google-chrome"; + yield return "/usr/bin/google-chrome-stable"; + if (OperatingSystem.IsWindows()) + { + foreach (var root in new[] { Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), + Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) }) + { + if (string.IsNullOrEmpty(root)) continue; + yield return Path.Combine(root, "Google", "Chrome", "Application", "chrome.exe"); + yield return Path.Combine(root, "Chromium", "Application", "chrome.exe"); + yield return Path.Combine(root, "Microsoft", "Edge", "Application", "msedge.exe"); + } + } + if (OperatingSystem.IsMacOS()) yield return "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"; + } + + public static string? FindExecutable() => Candidates().FirstOrDefault(File.Exists); + + public static IReadOnlyList Arguments(string profileDir) => new[] + { + "--headless=new", "--remote-debugging-port=0", $"--user-data-dir={profileDir}", "--no-sandbox", "--disable-gpu", + "--window-size=1280,900", "--lang=it-IT", "--no-first-run", "--no-default-browser-check", "--disable-dev-shm-usage", + "--disable-background-networking", "--disable-sync", "--mute-audio", "about:blank" + }; + + public static async Task StartAsync(string profileDir, CancellationToken ct) + { + var exe = FindExecutable() ?? throw new InvalidOperationException("Chromium non trovato nell'immagine: usa «incolla i cookie»"); + Directory.CreateDirectory(profileDir); + var portFile = Path.Combine(profileDir, "DevToolsActivePort"); + try { if (File.Exists(portFile)) File.Delete(portFile); } catch (IOException) { } + // Un blocco lasciato da un Chromium ucciso impedisce di riaprire il profilo. + foreach (var lockName in new[] { "SingletonLock", "SingletonSocket", "SingletonCookie" }) + { + try { var p = Path.Combine(profileDir, lockName); if (File.Exists(p) || Directory.Exists(p)) File.Delete(p); } catch { } + } + + var psi = new ProcessStartInfo(exe) + { + UseShellExecute = false, + RedirectStandardError = true, + RedirectStandardOutput = true, + CreateNoWindow = true + }; + foreach (var a in Arguments(profileDir)) psi.ArgumentList.Add(a); + + var process = Process.Start(psi) ?? throw new InvalidOperationException("Chromium non si è avviato"); + process.ErrorDataReceived += (_, _) => { }; + process.OutputDataReceived += (_, _) => { }; + process.BeginErrorReadLine(); + process.BeginOutputReadLine(); + + var deadline = DateTime.UtcNow.AddSeconds(20); + while (DateTime.UtcNow < deadline) + { + ct.ThrowIfCancellationRequested(); + if (process.HasExited) throw new InvalidOperationException($"Chromium si è chiuso subito (codice {process.ExitCode})"); + if (TryReadPort(portFile) is { } endpoint) return new ChromiumProcess(process, endpoint); + await Task.Delay(100, ct).ConfigureAwait(false); + } + + try { process.Kill(entireProcessTree: true); } catch { } + throw new InvalidOperationException("Chromium non ha aperto il protocollo di controllo in 20 secondi"); + } + + /// Riga 1 la porta, riga 2 il percorso del WebSocket del browser. + internal static Uri? TryReadPort(string file) + { + try + { + if (!File.Exists(file)) return null; + var lines = File.ReadAllLines(file); + if (lines.Length < 2 || !int.TryParse(lines[0].Trim(), NumberStyles.None, CultureInfo.InvariantCulture, out var port) || port <= 0) return null; + return new Uri($"ws://127.0.0.1:{port}{lines[1].Trim()}"); + } + catch (IOException) + { + return null; + } + } + + public async ValueTask DisposeAsync() + { + try + { + if (!_process.HasExited) + { + await _process.WaitForExitAsync(new CancellationTokenSource(TimeSpan.FromSeconds(3)).Token).ConfigureAwait(false); + } + } + catch (OperationCanceledException) { } + try { if (!_process.HasExited) _process.Kill(entireProcessTree: true); } catch { } + _process.Dispose(); + } +} diff --git a/Mimante/src/BidooBidBot/Session/SessionChecker.cs b/Mimante/src/BidooBidBot/Session/SessionChecker.cs new file mode 100644 index 0000000..be041d8 --- /dev/null +++ b/Mimante/src/BidooBidBot/Session/SessionChecker.cs @@ -0,0 +1,77 @@ +using BidooBidBot.Bidoo; +using BidooBidBot.Logging; + +namespace BidooBidBot.Session; + +/// +/// La verifica periodica della sessione e del conto (specifica §6.5): ogni 5 minuti il saldo +/// leggero (update_credits_status.php), ogni 30 la pagina del conto +/// (buy_bids.php: utente, saldo, credito) e le aste da confermare. Una pagina di login +/// al posto dei dati la fa scattare . +/// +public sealed class SessionChecker +{ + private readonly BidooApi _api; + private readonly AccountState _account; + private readonly AppLog _log; + private DateTime _lastFull = DateTime.MinValue; + + public SessionChecker(BidooApi api, AccountState account, AppLog log) + { + _api = api; + _account = account; + _log = log; + } + + public static readonly TimeSpan LightEvery = TimeSpan.FromMinutes(5); + public static readonly TimeSpan FullEvery = TimeSpan.FromMinutes(30); + + public Task RunAsync(CancellationToken ct) => Task.Run(async () => + { + while (!ct.IsCancellationRequested) + { + try { await VerifyAsync(DateTime.UtcNow - _lastFull >= FullEvery, ct).ConfigureAwait(false); } + catch (OperationCanceledException) { return; } + catch (Exception ex) { _log.Warn("SESSIONE", $"Verifica non riuscita: {ex.Message}"); } + + try { await Task.Delay(LightEvery, ct).ConfigureAwait(false); } + catch (OperationCanceledException) { return; } + } + }, ct); + + /// + /// Una verifica: completa (utente, saldo, credito, aste da confermare) o leggera (saldo). + /// Vero se la sessione risponde da utente collegato. + /// + public async Task VerifyAsync(bool full, CancellationToken ct) + { + if (full) + { + _account.SetStatus(_account.Status == SessionStatus.Valid ? SessionStatus.Valid : SessionStatus.Checking, null); + var info = await _api.GetUserInfoAsync(ct).ConfigureAwait(false); + if (info?.Username == null) + { + if (_account.Status != SessionStatus.Expired) + _account.SetStatus(SessionStatus.Checking, "la pagina del conto non ha risposto: riprovo fra 5 minuti"); + return false; + } + + _lastFull = DateTime.UtcNow; + var changedUser = !string.Equals(_account.Username, info.Username, StringComparison.OrdinalIgnoreCase); + _account.SetUser(info.Username, info.UserId); + _api.Username = info.Username; + if (info.RemainingBids is { } total) _account.SetTotal(total); + _account.SetCredit(info.ShopCredit); + _account.SetToConfirm(await _api.GetAuctionsWonAsync(ct).ConfigureAwait(false)); + _account.SetStatus(SessionStatus.Valid, null); + if (changedUser) _log.Info("SESSIONE", $"Collegato come {info.Username}, {_account.BalanceText()}"); + return true; + } + + var credits = await _api.GetCreditsAsync(ct).ConfigureAwait(false); + if (credits == null) return _account.Status == SessionStatus.Valid; + if (credits.RemainingBids is { } t) _account.SetTotal(t); + if (credits.ShopCredit is { } c) _account.SetCredit(c); + return true; + } +} diff --git a/Mimante/src/BidooBidBot/Session/SessionStore.cs b/Mimante/src/BidooBidBot/Session/SessionStore.cs new file mode 100644 index 0000000..34746c5 --- /dev/null +++ b/Mimante/src/BidooBidBot/Session/SessionStore.cs @@ -0,0 +1,153 @@ +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using BidooBidBot.Config; + +namespace BidooBidBot.Session; + +/// La sessione Bidoo salvata: cookie, User-Agent del browser che l'ha creata, utente. +public sealed class BidooSession +{ + public string Cookie { get; set; } = ""; + public string? UserAgent { get; set; } + public string? Username { get; set; } + public string? UserId { get; set; } + + /// «accesso assistito» o «cookie incollati». + public string Source { get; set; } = ""; + + public DateTime SavedAtUtc { get; set; } = DateTime.UtcNow; + public DateTime? CheckedAtUtc { get; set; } +} + +/// +/// L'archivio della sessione (specifica §6.5): /config/sessione/sessione.json cifrato +/// AES-256-GCM, chiave in chiave.bin generata al primo avvio, entrambi 0600. Uno solo: +/// l'ultimo importato sostituisce l'altro. «Disconnetti» cancella il file (la chiave resta). +/// +/// Il file cifrato è JSON: versione, nonce, tag e testo cifrato in base64. Una chiave +/// persa o un file manomesso non si leggono: si riparte senza sessione, e il registro lo dice. +/// +public sealed class SessionStore +{ + public const string SourceAssisted = "accesso assistito"; + public const string SourcePasted = "cookie incollati"; + + private readonly string _folder; + private readonly object _sync = new(); + + public SessionStore(string folder) => _folder = folder; + + public string FilePath => Path.Combine(_folder, "sessione.json"); + public string KeyPath => Path.Combine(_folder, "chiave.bin"); + + public bool Exists => File.Exists(FilePath); + + private sealed class Envelope + { + public int V { get; set; } = 1; + public string Nonce { get; set; } = ""; + public string Tag { get; set; } = ""; + public string Data { get; set; } = ""; + } + + /// La sessione salvata, o null se non c'è o non si legge (con il motivo). + public (BidooSession? Session, string? Error) Load() + { + lock (_sync) + { + if (!File.Exists(FilePath)) return (null, null); + try + { + var env = JsonSerializer.Deserialize(File.ReadAllText(FilePath)); + if (env == null || env.V != 1) return (null, "formato del file di sessione sconosciuto"); + if (!File.Exists(KeyPath)) return (null, "chiave della sessione mancante"); + + var key = File.ReadAllBytes(KeyPath); + var nonce = Convert.FromBase64String(env.Nonce); + var tag = Convert.FromBase64String(env.Tag); + var cipher = Convert.FromBase64String(env.Data); + var plain = new byte[cipher.Length]; + using (var aes = new AesGcm(key, tag.Length)) aes.Decrypt(nonce, cipher, tag, plain); + + var session = JsonSerializer.Deserialize(Encoding.UTF8.GetString(plain)); + return session == null || string.IsNullOrWhiteSpace(session.Cookie) + ? (null, "sessione salvata vuota") + : (session, null); + } + catch (AuthenticationTagMismatchException) + { + return (null, "sessione salvata non decifrabile (chiave diversa o file modificato)"); + } + catch (Exception ex) when (ex is JsonException or FormatException or CryptographicException or IOException) + { + return (null, $"sessione salvata illeggibile: {ex.Message}"); + } + } + } + + /// Salva (sostituisce) la sessione. Scrittura atomica: file temporaneo e rinomina. + public void Save(BidooSession session) + { + lock (_sync) + { + Directory.CreateDirectory(_folder); + var key = EnsureKey(); + var plain = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(session)); + var nonce = RandomNumberGenerator.GetBytes(AesGcm.NonceByteSizes.MaxSize); + var tag = new byte[AesGcm.TagByteSizes.MaxSize]; + var cipher = new byte[plain.Length]; + using (var aes = new AesGcm(key, tag.Length)) aes.Encrypt(nonce, plain, cipher, tag); + CryptographicOperations.ZeroMemory(plain); + + var env = new Envelope + { + Nonce = Convert.ToBase64String(nonce), Tag = Convert.ToBase64String(tag), Data = Convert.ToBase64String(cipher) + }; + var tmp = FilePath + ".tmp"; + File.WriteAllText(tmp, JsonSerializer.Serialize(env)); + ConfigPaths.RestrictToOwner(tmp); + File.Move(tmp, FilePath, overwrite: true); + ConfigPaths.RestrictToOwner(FilePath); + } + } + + /// «Disconnetti»: cancella la sessione salvata. + public void Delete() + { + lock (_sync) + { + try { if (File.Exists(FilePath)) File.Delete(FilePath); } + catch (IOException) { /* riprova al prossimo salvataggio: lo sostituisce */ } + } + } + + private byte[] EnsureKey() + { + if (File.Exists(KeyPath)) + { + var existing = File.ReadAllBytes(KeyPath); + if (existing.Length == 32) return existing; + } + var key = RandomNumberGenerator.GetBytes(32); + File.WriteAllBytes(KeyPath, key); + ConfigPaths.RestrictToOwner(KeyPath); + return key; + } + + /// + /// I cookie incollati dall'utente: la riga intera dell'intestazione Cookie, con o + /// senza il prefisso «Cookie:». Serve almeno __stattrb (il cookie di accesso). + /// + public static (string? Cookie, string? Error) NormalizePastedCookie(string? text, string sessionCookie = "__stattrb") + { + var t = (text ?? "").Trim(); + if (t.StartsWith("cookie:", StringComparison.OrdinalIgnoreCase)) t = t[7..].Trim(); + t = t.Replace("\r", "").Replace("\n", ""); + if (t.Length == 0) return (null, "Incolla la riga Cookie intera"); + var parts = Net.CookieText.Split(t); + if (parts.Count == 0) return (null, "Nessun cookie riconosciuto: il formato è nome=valore; nome=valore"); + if (!parts.Any(p => p.Name == sessionCookie)) return (null, $"Manca il cookie {sessionCookie}: non è la sessione di un utente collegato"); + return (Net.CookieText.Join(parts), null); + } +} diff --git a/Mimante/src/BidooBidBot/Telegram/TelegramNotifier.cs b/Mimante/src/BidooBidBot/Telegram/TelegramNotifier.cs new file mode 100644 index 0000000..3a6acd8 --- /dev/null +++ b/Mimante/src/BidooBidBot/Telegram/TelegramNotifier.cs @@ -0,0 +1,140 @@ +using System.Threading.Channels; +using BidooBidBot.Logging; +using BidooBidBot.Settings; + +namespace BidooBidBot.Telegram; + +/// +/// Le notifiche Telegram (specifica §6.7): una coda con tre ritentativi e attesa crescente, +/// così un Telegram lento non rallenta mai il motore. Facoltativi i comandi in ingresso +/// (/stato, /halt, /riprendi, /osserva), letti con +/// getUpdates a polling lungo e accettati solo dalla chat configurata. +/// +public sealed class TelegramNotifier : IAsyncDisposable +{ + private readonly Func _settings; + private readonly AppLog _log; + private readonly HttpClient _http; + private readonly Channel _queue = Channel.CreateBounded(new BoundedChannelOptions(200) { FullMode = BoundedChannelFullMode.DropOldest }); + private readonly CancellationTokenSource _cts = new(); + private readonly Task _sender; + private readonly Task _commands; + private long _offset; + private bool _failureSaid; + + /// Risponde a un comando ricevuto: il testo della risposta. + public Func>? CommandHandler { get; set; } + + public TelegramNotifier(Func settings, AppLog log, HttpClient? http = null) + { + _settings = settings; + _log = log; + _http = http ?? new HttpClient { Timeout = TimeSpan.FromSeconds(40) }; + _sender = Task.Run(() => SendLoopAsync(_cts.Token)); + _commands = Task.Run(() => CommandLoopAsync(_cts.Token)); + } + + public bool Configured + { + get + { + var s = _settings(); + return !string.IsNullOrWhiteSpace(s.TelegramBotToken) && !string.IsNullOrWhiteSpace(s.TelegramChatId); + } + } + + /// Accoda un messaggio già formattato (). Senza token o chat non fa nulla. + public void Enqueue(string text) + { + if (Configured) _queue.Writer.TryWrite(text); + } + + /// «Invia messaggio di prova» delle impostazioni: subito, senza coda, con l'esito. + public async Task<(bool Ok, string Message)> SendTestAsync(CancellationToken ct) + { + var s = _settings(); + if (string.IsNullOrWhiteSpace(s.TelegramBotToken) || string.IsNullOrWhiteSpace(s.TelegramChatId)) + return (false, "Scrivi token del bot e chat id, salva, poi riprova"); + try + { + var ok = await TelegramApi.SendAsync(_http, s.TelegramBotToken, s.TelegramChatId, + TelegramFormat.Message("Messaggio di prova da Bidoo BidBot", "Se lo leggi, le notifiche arrivano."), ct).ConfigureAwait(false); + return ok ? (true, "Messaggio inviato") : (false, "Telegram ha rifiutato il messaggio: controlla token e chat id (scrivi prima un messaggio al bot)"); + } + catch (Exception ex) + { + return (false, $"Telegram non raggiungibile: {ex.Message}"); + } + } + + private async Task SendLoopAsync(CancellationToken ct) + { + try + { + await foreach (var text in _queue.Reader.ReadAllAsync(ct).ConfigureAwait(false)) + { + var s = _settings(); + if (string.IsNullOrWhiteSpace(s.TelegramBotToken) || string.IsNullOrWhiteSpace(s.TelegramChatId)) continue; + + var sent = false; + string? error = null; + for (var attempt = 0; attempt < 3 && !sent; attempt++) + { + if (attempt > 0) await Task.Delay(TimeSpan.FromSeconds(2 << attempt), ct).ConfigureAwait(false); + try { sent = await TelegramApi.SendAsync(_http, s.TelegramBotToken, s.TelegramChatId, text, ct).ConfigureAwait(false); } + catch (OperationCanceledException) when (ct.IsCancellationRequested) { return; } + catch (Exception ex) { error = ex.Message; } + } + + if (!sent && !_failureSaid) + { + _failureSaid = true; + _log.Warn("TELEGRAM", $"Messaggio non inviato dopo tre tentativi{(error != null ? $": {error}" : "")}"); + } + else if (sent) _failureSaid = false; + } + } + catch (OperationCanceledException) { } + } + + private async Task CommandLoopAsync(CancellationToken ct) + { + while (!ct.IsCancellationRequested) + { + var s = _settings(); + if (!s.TelegramCommandsEnabled || !Configured || CommandHandler == null) + { + try { await Task.Delay(TimeSpan.FromSeconds(10), ct).ConfigureAwait(false); } catch (OperationCanceledException) { return; } + continue; + } + + try + { + var updates = await TelegramApi.GetUpdatesAsync(_http, s.TelegramBotToken, _offset, 25, ct).ConfigureAwait(false); + foreach (var u in updates) + { + _offset = Math.Max(_offset, u.UpdateId + 1); + if (u.ChatId != s.TelegramChatId.Trim() || string.IsNullOrWhiteSpace(u.Text)) continue; + var command = u.Text.Trim().Split(' ', '@')[0].ToLowerInvariant(); + _log.Info("TELEGRAM", $"Comando ricevuto: {command}"); + var reply = await CommandHandler(command).ConfigureAwait(false); + Enqueue(reply); + } + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) { return; } + catch (Exception) + { + try { await Task.Delay(TimeSpan.FromSeconds(30), ct).ConfigureAwait(false); } catch (OperationCanceledException) { return; } + } + } + } + + public async ValueTask DisposeAsync() + { + _queue.Writer.TryComplete(); + await _cts.CancelAsync().ConfigureAwait(false); + try { await Task.WhenAll(_sender, _commands).WaitAsync(TimeSpan.FromSeconds(3)).ConfigureAwait(false); } catch { } + _http.Dispose(); + _cts.Dispose(); + } +} diff --git a/Mimante/src/BidooBidBot/Web/Api.cs b/Mimante/src/BidooBidBot/Web/Api.cs new file mode 100644 index 0000000..f761b51 --- /dev/null +++ b/Mimante/src/BidooBidBot/Web/Api.cs @@ -0,0 +1,453 @@ +using System.Collections.Concurrent; +using System.Globalization; +using System.Text.Json; +using BidooBidBot.Bidoo; +using BidooBidBot.Data; +using BidooBidBot.Engine; +using BidooBidBot.Host; +using BidooBidBot.Ml; +using BidooBidBot.Products; +using BidooBidBot.Settings; +using BidooBidBot.Strategy; +using Microsoft.AspNetCore.Http; + +namespace BidooBidBot.Web; + +/// +/// Le letture delle pagine (GET /api/…, JSON): catalogo, prodotti, storico, +/// apprendimento, registro, esportazioni, foto. Lo stato vivo passa dal WebSocket; qui le +/// interrogazioni paginate sul pool di lettura (tempo massimo breve). +/// +public static class Api +{ + private static readonly CultureInfo Inv = CultureInfo.InvariantCulture; + + public static async Task HandleAsync(Bot bot, HttpContext ctx, string path) + { + if (!HttpMethods.IsGet(ctx.Request.Method)) + { + ctx.Response.StatusCode = 405; + return; + } + + var q = ctx.Request.Query; + var ct = ctx.RequestAborted; + try + { + object? result = path switch + { + "/api/catalogo/categorie" => await CategoriesAsync(bot, q["aggiorna"] == "1", ct).ConfigureAwait(false), + "/api/catalogo" => await CatalogAsync(bot, q["cat"].ToString(), IntQ(q["max"]), q["aggiorna"] == "1", ct).ConfigureAwait(false), + "/api/prodotti" => await ProductsAsync(bot).ConfigureAwait(false), + "/api/storico" => await HistoryAsync(bot, q).ConfigureAwait(false), + "/api/apprendimento" => await LearningAsync(bot).ConfigureAwait(false), + "/api/registro" => LogPage(bot, q), + "/api/esportazioni" => ExportList(bot), + "/api/immagine" => null, + _ when path.StartsWith("/api/prodotti/", StringComparison.Ordinal) => + await ProductAsync(bot, Uri.UnescapeDataString(path["/api/prodotti/".Length..])).ConfigureAwait(false), + _ when path.StartsWith("/api/storico/", StringComparison.Ordinal) => + await HistoryDetailAsync(bot, Uri.UnescapeDataString(path["/api/storico/".Length..])).ConfigureAwait(false), + _ => NotFound + }; + + if (path == "/api/immagine") + { + await ImageAsync(bot, ctx, q["u"].ToString()).ConfigureAwait(false); + return; + } + if (ReferenceEquals(result, NotFound)) + { + ctx.Response.StatusCode = 404; + return; + } + + ctx.Response.ContentType = "application/json; charset=utf-8"; + ctx.Response.Headers.CacheControl = "no-store"; + await JsonSerializer.SerializeAsync(ctx.Response.Body, result, WebSocketHub.Json, ct).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + } + catch (Exception ex) + { + bot.Log.Warn("INTERFACCIA", $"Lettura {path} non riuscita: {ex.Message}"); + if (!ctx.Response.HasStarted) + { + ctx.Response.StatusCode = 500; + ctx.Response.ContentType = "application/json; charset=utf-8"; + await JsonSerializer.SerializeAsync(ctx.Response.Body, new { error = ex.Message }, WebSocketHub.Json, CancellationToken.None).ConfigureAwait(false); + } + } + } + + private static readonly object NotFound = new(); + + private static int? IntQ(string? v) => int.TryParse(v, NumberStyles.Integer, Inv, out var i) ? i : null; + private static double? DblQ(string? v) => double.TryParse((v ?? "").Replace(',', '.'), NumberStyles.Float, Inv, out var d) ? d : null; + + // ── Catalogo ───────────────────────────────────────────────────────── + + private static async Task CategoriesAsync(Bot bot, bool refresh, CancellationToken ct) + { + var cats = await bot.World.Catalog.GetCategoriesAsync(refresh, ct).ConfigureAwait(false); + return cats.Select(c => new { key = c.Key, name = c.DisplayName, special = c.IsSpecial }).ToList(); + } + + private static async Task CatalogAsync(Bot bot, string key, int? max, bool refresh, CancellationToken ct) + { + var w = bot.World; + var s = bot.Settings.Current; + var cats = await w.Catalog.GetCategoriesAsync(false, ct).ConfigureAwait(false); + var cat = cats.FirstOrDefault(c => c.Key == key) ?? CatalogCategory.AllAuctions; + if (refresh) w.Catalog.InvalidateCache(); + var list = await w.Catalog.GetAllAuctionsAsync(cat, Math.Clamp(max ?? s.CatalogMaxAuctions, 10, 2000), refresh ? 0 : s.CatalogCacheSeconds, ct).ConfigureAwait(false); + return new + { + category = cat.DisplayName, + at = DateTime.UtcNow, + auctions = list.Select(a => + { + var product = bot.Products.FindFor(a); + return new + { + id = a.AuctionId, name = a.Name, url = a.Url, image = a.ImageUrl, price = (double)a.CurrentPrice, + buyNow = a.BuyNowPrice is { } b ? (double)b : (double?)null, lastBidder = a.LastBidder, remaining = a.RemainingSeconds, + status = a.Status, active = a.IsActive, manualOnly = a.IsManualOnly, credit = a.IsCreditAuction, productId = a.ProductId, + productKey = product?.ProductKey ?? ProductKey.From(a.Name), followed = product?.Followed ?? false, + value = ProductRules.ValueOf(product, a.BuyNowPrice is { } bb ? (double)bb : null), + inList = w.Monitor.Find(a.AuctionId) != null, started = ProductRules.HasStarted(a) + }; + }).ToList() + }; + } + + // ── Prodotti ───────────────────────────────────────────────────────── + + public static ProductAdvice.Advice? AdviceFor(ProductRecord? p, ProductStatsData? s, AppSettings settings) => + s == null ? null : ProductAdvice.Suggest(new ProductAdvice.Input( + s.RecentCloses, s.RecentWinnerBids, p?.MarketValue ?? s.BuyNow, s.Shipping, p?.MaxBids ?? settings.DefaultMaxClicks, + settings.AverageBidCostEuro, settings.SuggestedValueTolerancePercent, settings.SuggestedCoveragePercent / 100.0, + settings.SuggestedMinPercentile / 100.0)); + + private static async Task ProductsAsync(Bot bot) + { + var settings = bot.Settings.Current; + var stats = await ProductStatsRepository.LoadAllAsync(bot.Db).ConfigureAwait(false); + var records = bot.Products.All().ToDictionary(p => p.ProductKey, StringComparer.Ordinal); + var keys = records.Keys.Union(stats.Keys).Distinct().ToList(); + var inList = bot.WorldOrNull?.Monitor.Auctions.GroupBy(a => a.ProductKey).ToDictionary(g => g.Key, g => g.Count()) ?? new(); + + return keys.Select(k => + { + records.TryGetValue(k, out var p); + stats.TryGetValue(k, out var s); + var advice = AdviceFor(p, s, settings); + var changes = advice is { HasAdvice: true } a && (p?.MaxPrice != a.MaxPrice || (a.MaxBids != null && p?.MaxBids != a.MaxBids)); + return new + { + key = k, name = p?.DisplayName ?? s?.Name ?? k, followed = p?.Followed ?? false, bidooProductId = p?.BidooProductId ?? 0, + maxPrice = p?.MaxPrice, maxBids = p?.MaxBids, marketValue = p?.MarketValue, horizonMinutes = p?.HorizonMinutes, + autoState = p?.AutoState, quietHours = p?.QuietHours, autoAdded = p?.AutoAddedCount ?? 0, hasRecord = p != null, + auctions = s?.Auctions ?? 0, won = s?.Won ?? 0, avgFinal = s?.AvgFinal, lastFinal = s?.LastFinal, lastClosedAt = s?.LastClosedAtUtc, + buyNow = s?.BuyNow, shipping = s?.Shipping, image = s?.ImageUrl, avgWinnerBids = s?.AvgWinnerBids, myBids = s?.MyBidsTotal ?? 0, + avgRealCostWon = s?.AvgRealCostWon, avgSavingWon = s?.AvgSavingWon, inList = inList.GetValueOrDefault(k), + advice = advice is { HasAdvice: true } ad ? new { maxPrice = ad.MaxPrice, maxBids = ad.MaxBids, text = ad.Explanation, notWorthwhile = ad.NotWorthwhile } : null, + adviceChanges = changes + }; + }).OrderByDescending(x => x.followed).ThenByDescending(x => x.auctions).ThenBy(x => x.name, StringComparer.OrdinalIgnoreCase).ToList(); + } + + private static async Task ProductAsync(Bot bot, string key) + { + var settings = bot.Settings.Current; + var p = bot.Products.Find(key); + var world = bot.WorldOrNull?.Name ?? Worlds.Real; + var s = await ProductStatsRepository.ComputeAsync(bot.Db, key, settings.TransactionFeeEuro, world).ConfigureAwait(false); + var advice = AdviceFor(p, s, settings); + var auctions = await bot.Db.QueryAsync( + "SELECT auction_id, name, end_time, final_price, winner_user, won_by_me, my_bids, loss_reason, winner_bids_paid, winner_bids_free, outcome " + + "FROM auctions WHERE product_key = $1 AND type = $2 ORDER BY COALESCE(end_time, added_at) DESC LIMIT 100", + r => new + { + id = r.Str("auction_id"), name = r.Str("name"), end = r.Date("end_time"), final = r.DblOrNull("final_price"), winner = r.StrOrNull("winner_user"), + won = r.Bool("won_by_me"), myBids = r.Int("my_bids"), reason = r.StrOrNull("loss_reason"), outcome = r.StrOrNull("outcome"), + winnerBids = r.IntOrNull("winner_bids_paid") is { } wp ? wp + (r.IntOrNull("winner_bids_free") ?? 0) : (int?)null + }, key, world).ConfigureAwait(false); + + // Istogramma delle chiusure: 12 classi fra minimo e massimo. + var closes = s?.RecentCloses ?? new List(); + var hist = new List(); + if (closes.Count > 0) + { + double lo = closes.Min(), hi = closes.Max(); + var width = Math.Max(0.01, (hi - lo) / 12); + for (var i = 0; i < 12; i++) + { + var a = lo + i * width; + var b = i == 11 ? hi + 0.001 : a + width; + hist.Add(new { from = Math.Round(a, 2), to = Math.Round(b, 2), n = closes.Count(c => c >= a && c < b) }); + } + } + + return new + { + key, record = p, stats = s, histogram = hist, + bands = s?.MedianCloseByHourBand.OrderBy(kv => kv.Key).Select(kv => new { band = kv.Key, label = BidFeatures.HourBandLabel(kv.Key), median = kv.Value, n = s.CountByHourBand.GetValueOrDefault(kv.Key) }), + advice = advice is { } ad ? new { has = ad.HasAdvice, maxPrice = ad.MaxPrice, maxBids = ad.MaxBids, floor = ad.Floor, mode = ad.Mode, median = ad.Median, text = ad.Explanation, notWorthwhile = ad.NotWorthwhile } : null, + bidCost = BidStrategy.EffectiveBidCost(settings, bot.WorldOrNull?.Account.Balance ?? default), + auctions + }; + } + + /// «Usa consigliati su tutti»: scrive i limiti consigliati sulle schede che cambiano. + public static async Task ApplySuggestedAsync(Bot bot, CancellationToken ct) + { + var settings = bot.Settings.Current; + var stats = await ProductStatsRepository.LoadAllAsync(bot.Db).ConfigureAwait(false); + var n = 0; + foreach (var (key, s) in stats) + { + ct.ThrowIfCancellationRequested(); + var p = bot.Products.Find(key); + var advice = AdviceFor(p, s, settings); + if (advice is not { HasAdvice: true } a) continue; + if (p?.MaxPrice == a.MaxPrice && (a.MaxBids == null || p?.MaxBids == a.MaxBids)) continue; + var rec = p ?? new ProductRecord { ProductKey = key, DisplayName = s.Name ?? key }; + rec.MaxPrice = a.MaxPrice; + if (a.MaxBids != null) rec.MaxBids = a.MaxBids; + bot.Products.Upsert(rec); + n++; + } + bot.Log.Info("PRODOTTI", $"Limiti consigliati applicati a {n} prodotti"); + return n; + } + + // ── Storico ────────────────────────────────────────────────────────── + + private static async Task HistoryAsync(Bot bot, IQueryCollection q) + { + var world = bot.WorldOrNull?.Name ?? Worlds.Real; + var where = new List { "a.type = $1", "a.outcome IS NOT NULL" }; + var args = new List { world }; + void Add(string clause, object? value) + { + args.Add(value); + where.Add(clause.Replace("$n", "$" + args.Count.ToString(Inv), StringComparison.Ordinal)); + } + + if (DateTime.TryParseExact(q["da"], "yyyy-MM-dd", Inv, DateTimeStyles.None, out var from)) Add("a.end_time >= $n", ToUtc(from)); + if (DateTime.TryParseExact(q["a"], "yyyy-MM-dd", Inv, DateTimeStyles.None, out var to)) Add("a.end_time < $n", ToUtc(to.AddDays(1))); + if (!string.IsNullOrWhiteSpace(q["prodotto"])) Add("(a.product_key = $n OR a.name ILIKE '%' || $n || '%')", q["prodotto"].ToString()); + switch (q["esito"].ToString()) + { + case "vinte": where.Add("a.won_by_me"); break; + case "perse": where.Add("NOT a.won_by_me AND a.my_bids > 0"); break; + case "osservate": where.Add("a.my_bids = 0"); break; + } + if (DblQ(q["min"]) is { } min) Add("a.final_price >= $n", min); + if (DblQ(q["max"]) is { } max) Add("a.final_price <= $n", max); + if (q["complete"] == "1") where.Add("a.observed_from_start AND a.observed_to_end"); + if (q["mie"] == "1") where.Add("a.my_bids > 0"); + + var clause = string.Join(" AND ", where); + var count = await bot.Db.ScalarAsync($"SELECT COUNT(*) FROM auctions a WHERE {clause}", args.ToArray()).ConfigureAwait(false); + var limit = Math.Clamp(IntQ(q["limite"]) ?? 200, 1, 1000); + var offset = Math.Max(0, IntQ(q["da_riga"]) ?? 0); + + var rows = await bot.Db.QueryAsync( + "SELECT a.auction_id, a.name, a.product_key, a.end_time, a.final_price, a.winner_user, a.my_bids, a.my_bids_cost, a.winner_bids_paid, " + + " a.winner_bids_free, COALESCE(a.market_value, a.buy_now_price) AS value, a.loss_reason, a.outcome, a.won_by_me, " + + " a.observed_from_start, a.observed_to_end, f.forecast_close " + + "FROM auctions a LEFT JOIN LATERAL (SELECT forecast_close FROM auction_forecasts x WHERE x.auction_id = a.auction_id " + + " ORDER BY x.is_initial DESC, x.ts LIMIT 1) f ON true " + + $"WHERE {clause} ORDER BY a.end_time DESC NULLS LAST LIMIT {limit} OFFSET {offset}", + r => new + { + id = r.Str("auction_id"), name = r.Str("name"), productKey = r.Str("product_key"), end = r.Date("end_time"), final = r.DblOrNull("final_price"), + forecast = r.DblOrNull("forecast_close"), winner = r.StrOrNull("winner_user"), myBids = r.Int("my_bids"), myCost = r.Dbl("my_bids_cost"), + winnerBids = r.IntOrNull("winner_bids_paid") is { } wp ? wp + (r.IntOrNull("winner_bids_free") ?? 0) : (int?)null, + value = r.DblOrNull("value"), reason = r.StrOrNull("loss_reason"), outcome = r.StrOrNull("outcome"), won = r.Bool("won_by_me"), + complete = r.Bool("observed_from_start") && r.Bool("observed_to_end") + }, args.ToArray()).ConfigureAwait(false); + + return new { count, offset, limit, rows }; + } + + private static DateTime ToUtc(DateTime localDate) => + TimeZoneInfo.ConvertTimeToUtc(DateTime.SpecifyKind(localDate, DateTimeKind.Unspecified), AppInfo.TimeZone); + + private static async Task HistoryDetailAsync(Bot bot, string id) + { + var summary = await bot.Db.QueryOneAsync( + "SELECT auction_id, name, url, product_key, added_at, first_seen_at, opened_at, end_time, final_price, winner_user, won_by_me, outcome, " + + " my_bids, my_bids_cost, winner_bids_paid, winner_bids_free, resets, distinct_bidders, total_observed_bids, top_bidder_share, " + + " observed_from_start, observed_to_end, observed_minutes, buy_now_price, market_value, shipping, transaction_fee, avg_ping_ms, " + + " p95_ping_ms, p99_ping_ms, polls, poll_errors, configured_lead_ms, lead_is_manual, successful_bids, failed_bids, loss_reason, " + + " mode_at_close, price_series::text AS price_series, bids_by_user::text AS bids_by_user, status, abandon_reason " + + "FROM auctions WHERE auction_id = $1", r => r.ToDictionary(), id).ConfigureAwait(false); + if (summary == null) return NotFound; + + var forecasts = await bot.Db.QueryAsync( + "SELECT ts, is_initial, price_at, forecast_close, forecast_close_p10, forecast_close_p90, forecast_winner_bids, forecast_minutes, " + + " p_win_if_enter, ev_if_enter, actual_close, error_close, in_interval FROM auction_forecasts WHERE auction_id = $1 ORDER BY ts", + r => r.ToDictionary(), id).ConfigureAwait(false); + var decisions = await bot.Db.QueryAsync( + "SELECT ts, price, timer, kind, action, p_win, ev, reason_detail, shadow, executed, outcome FROM bot_decisions WHERE auction_id = $1 ORDER BY ts DESC LIMIT 300", + r => r.ToDictionary(), id).ConfigureAwait(false); + var myBids = await bot.Db.QueryAsync( + "SELECT local_ts, price, planned_lead_ms, actual_lead_ms, wait_error_ms, ping_ms, rtt_ms, success, error, answered_by, answered_type, " + + " answered_after_s, unanswered, kind, manual FROM my_bids WHERE auction_id = $1 ORDER BY id", + r => r.ToDictionary(), id).ConfigureAwait(false); + var bidders = await bot.Db.QueryAsync( + "SELECT username, COUNT(*) AS n, SUM(CASE WHEN bid_type = 'Auto' THEN 1 ELSE 0 END) AS auto, BOOL_OR(is_mine) AS mine " + + "FROM bids WHERE auction_id = $1 GROUP BY username ORDER BY n DESC LIMIT 50", + r => new { user = r.Str("username"), n = r.Int("n"), auto = r.Int("auto"), mine = r.Bool("mine") }, id).ConfigureAwait(false); + + return new { summary, forecasts, decisions, myBids, bidders }; + } + + // ── Apprendimento ──────────────────────────────────────────────────── + + private static async Task LearningAsync(Bot bot) + { + var w = bot.World; + var s = bot.Settings.Current; + var learning = w.Learning; + var status = await learning.GetStatusAsync(s).ConfigureAwait(false); + var data = new DbLearningData(bot.Db, bot.Queue, w.Name); + var cost = BidStrategy.EffectiveBidCost(s, w.Account.Balance); + + object Policy(ShadowReport.PolicyStats p) => new + { + name = p.Name, decisions = p.Decisions, bids = p.Bids, wins = p.Wins, spent = Math.Round(p.Spent, 2), gained = Math.Round(p.Gained, 2), + net = Math.Round(p.Net, 2), perBid = Math.Round(p.RoiPerBid, 3), ciLow = p.Ci95?.Low, ciHigh = p.Ci95?.High, beatsNull = p.BeatsNullModel + }; + + var shadowRows = await data.ShadowRowsAsync(7, true, cost).ConfigureAwait(false); + var liveRows = await data.ShadowRowsAsync(7, false, cost).ConfigureAwait(false); + var allRows = await data.ShadowRowsAsync(30, null, cost).ConfigureAwait(false); + var shadowReport = ShadowReport.Compute(shadowRows, s.TransactionFeeEuro, 7); + var liveReport = ShadowReport.Compute(liveRows, s.TransactionFeeEuro, 7); + var allReport = ShadowReport.Compute(allRows, s.TransactionFeeEuro, 30); + + var fcRows = await bot.Db.QueryAsync( + "SELECT f.forecast_close, f.forecast_close_p10, f.forecast_close_p90, f.actual_close, f.forecast_winner_bids, f.actual_winner_bids " + + "FROM auction_forecasts f JOIN auctions a ON a.auction_id = f.auction_id " + + "WHERE a.type = $1 AND f.is_initial AND f.actual_close IS NOT NULL AND f.ts >= now() - interval '7 days'", + r => new ForecastErrors.Row(r.Dbl("forecast_close"), r.Dbl("forecast_close_p10"), r.Dbl("forecast_close_p90"), r.Dbl("actual_close"), + r.DblOrNull("forecast_winner_bids"), r.IntOrNull("actual_winner_bids")), w.Name).ConfigureAwait(false); + var fc = ForecastErrors.Summarize(fcRows); + + var own = learning.OwnBidStats; + var brier = learning.BrierScores; + var lat = w.Latency.Snapshot(); + var losses = await data.LossReasonSummaryAsync(30).ConfigureAwait(false); + + return new + { + status = new { state = status.State.ToString(), headline = status.Headline, detail = status.Detail, learned = status.Learned, pending = status.Pending, threshold = status.Threshold, studying = learning.Studying }, + simulator = w.IsSimulator, + model = new + { + updates = learning.ModelUpdates, calibration = Math.Round(learning.CalibrationFactor, 3), profileAuctions = learning.ProfileAuctions, + champion = learning.Champion, network = learning.NetworkShape, version = learning.ModelVersion, featuresVersion = BidFeatures.Version, + brierLogit = Num(brier.Logit), brierNet = Num(brier.Net), brierSamples = brier.Samples, forecastObserved = learning.ForecastObserved + }, + ownBids = new { bids = own.Bids, predicted = Math.Round(own.Predicted, 2), observed = own.Observed, factor = Math.Round(learning.OwnBidFactor, 3), minimum = LearningService.OwnBidsMinimum }, + exploration = new { today = learning.ExplorationUsedToday, perDay = s.ExplorationBidsPerDay }, + lead = new { recommended = w.Latency.RecommendedLeadMs(s), samples = lat.Samples, p50 = lat.P50, p99 = lat.P99, margin = lat.MarginMs, late = lat.LateBids, bids = lat.Bids, adaptive = s.AdaptiveLeadEnabled }, + roiShadow7d = shadowReport.Policies.Select(Policy).ToList(), + roiLive7d = liveReport.Policies.Select(Policy).ToList(), + roi30d = new { text = allReport.Text, liveBids = allReport.LiveBids, liveWins = allReport.LiveWins, policies = allReport.Policies.Select(Policy).ToList() }, + forecast7d = new { auctions = fc.Auctions, medianAbsError = fc.MedianAbsError, medianErrorPct = fc.MedianAbsErrorPct, signedPct = fc.SignedMedianPct, coverage = fc.Coverage, bidsError = fc.MedianBidsError }, + decisions = learning.RecentDecisions(60).Select(d => new { at = d.AtUtc, id = d.AuctionId, auction = d.Auction, price = d.Price, p = d.Probability, ev = d.ExpectedValue, action = d.Action, kind = d.Kind, reason = d.Reason, shadow = d.Shadow }), + losses = losses.Select(l => new { reason = l.Reason, count = l.Count }), + weights = learning.Weights().Take(30).Select(x => new { name = x.Name, label = BidFeatures.Describe(x.Name), weight = Math.Round(x.Weight, 4) }), + followed = w.Monitor.Auctions.Where(a => !a.IsFinished).Select(a => new + { + id = a.Id, name = a.Name, mode = RunModes.ToKey(a.Mode), price = a.LastState?.Price, p = a.LastDecision?.PWin, ev = a.LastDecision?.Ev, + kind = a.LastDecision?.Kind, forecast = (a.Forecast as ForecastResult)?.Close + }), + evaluation = learning.LastEvaluation() + }; + } + + private static double? Num(double v) => double.IsNaN(v) || double.IsInfinity(v) ? null : Math.Round(v, 5); + + // ── Registro ed esportazioni ───────────────────────────────────────── + + private static object LogPage(Bot bot, IQueryCollection q) + { + var level = q["livello"].ToString(); + var tag = q["categoria"].ToString(); + var text = q["cerca"].ToString(); + var entries = bot.Log.Snapshot() + .Where(e => level.Length == 0 || Views.Level(e.Level) == level || level == "warn+" && e.Level >= Logging.LogLevel.Warning) + .Where(e => tag.Length == 0 || string.Equals(e.Tag, tag, StringComparison.OrdinalIgnoreCase)) + .Where(e => text.Length == 0 || e.Text.Contains(text, StringComparison.OrdinalIgnoreCase)) + .TakeLast(Math.Clamp(IntQ(q["max"]) ?? 1000, 1, 5000)) + .Select(WebSocketHub.EventMessage) + .ToList(); + var tags = bot.Log.Snapshot().Select(e => e.Tag).Where(t => t.Length > 0).Distinct(StringComparer.OrdinalIgnoreCase).OrderBy(t => t).ToList(); + var files = Directory.Exists(bot.Paths.Logs) + ? new DirectoryInfo(bot.Paths.Logs).EnumerateFiles("*.log").OrderByDescending(f => f.Name).Take(60) + .Select(f => new { name = f.Name, size = f.Length, at = f.LastWriteTimeUtc }).ToList() + : new List(); + return new { entries, tags, files }; + } + + private static object ExportList(Bot bot) => + Directory.Exists(bot.Paths.Exports) + ? new DirectoryInfo(bot.Paths.Exports).EnumerateFiles().Where(f => f.Extension is ".csv" or ".txt").OrderByDescending(f => f.LastWriteTimeUtc).Take(100) + .Select(f => new { name = f.Name, size = f.Length, at = f.LastWriteTimeUtc }).ToList() + : new List(); + + // ── Foto dei prodotti ──────────────────────────────────────────────── + + private static readonly HttpClient ImageHttp = new(new SocketsHttpHandler { AutomaticDecompression = System.Net.DecompressionMethods.All }) + { + Timeout = TimeSpan.FromSeconds(8) + }; + private static readonly ConcurrentDictionary ImageCache = new(StringComparer.Ordinal); + + /// + /// Le foto passano dal bot: il browser non chiede nulla a Bidoo (niente referer, niente + /// cookie) e le miniature restano in memoria. Solo indirizzi di Bidoo o del simulatore. + /// + private static async Task ImageAsync(Bot bot, HttpContext ctx, string url) + { + if (!Uri.TryCreate(url, UriKind.Absolute, out var uri) || uri.Scheme is not ("http" or "https") || + !(uri.Host.Contains("bidoo", StringComparison.OrdinalIgnoreCase) || uri.IsLoopback)) + { + ctx.Response.StatusCode = 400; + return; + } + + if (!ImageCache.TryGetValue(url, out var hit)) + { + using var request = new HttpRequestMessage(HttpMethod.Get, uri); + request.Headers.TryAddWithoutValidation("User-Agent", bot.WorldOrNull?.Transport.UserAgent ?? "Mozilla/5.0"); + using var response = await ImageHttp.SendAsync(request, ctx.RequestAborted).ConfigureAwait(false); + var type = response.Content.Headers.ContentType?.MediaType ?? ""; + if (!response.IsSuccessStatusCode || !type.StartsWith("image/", StringComparison.Ordinal)) + { + ctx.Response.StatusCode = 404; + return; + } + var data = await response.Content.ReadAsByteArrayAsync(ctx.RequestAborted).ConfigureAwait(false); + if (data.Length > 2 * 1024 * 1024) + { + ctx.Response.StatusCode = 413; + return; + } + hit = (data, type); + if (ImageCache.Count > 500) ImageCache.Clear(); + ImageCache[url] = hit; + } + + ctx.Response.ContentType = hit.Type; + ctx.Response.Headers.CacheControl = "private, max-age=86400"; + await ctx.Response.Body.WriteAsync(hit.Data, ctx.RequestAborted).ConfigureAwait(false); + } +} diff --git a/Mimante/src/BidooBidBot/Web/Views.cs b/Mimante/src/BidooBidBot/Web/Views.cs new file mode 100644 index 0000000..4a91241 --- /dev/null +++ b/Mimante/src/BidooBidBot/Web/Views.cs @@ -0,0 +1,251 @@ +using BidooBidBot.Bidoo; +using BidooBidBot.Data; +using BidooBidBot.Engine; +using BidooBidBot.Host; +using BidooBidBot.Ml; +using BidooBidBot.Products; +using BidooBidBot.Session; +using BidooBidBot.Settings; +using BidooBidBot.Strategy; + +namespace BidooBidBot.Web; + +/// +/// Ciò che l'interfaccia riceve, in forma di dizionari piatti: una riga della griglia si +/// confronta campo per campo con l'ultima spedita e si mandano solo i campi cambiati +/// (auction.delta). Nomi dei campi come nell'Appendice D. +/// +public static class Views +{ + public static Dictionary AuctionRow(AuctionInfo a, BotWorld world, AppSettings settings) + { + var s = a.LastState; + var d = a.LastDecision; + var f = a.Forecast as ForecastResult; + var product = world.Monitor.Deps.Products.Find(a.ProductKey); + return new Dictionary(32, StringComparer.Ordinal) + { + ["id"] = a.Id, + ["name"] = a.Name, + ["mode"] = RunModes.ToKey(a.Mode), + ["status"] = a.DisplayStatus(), + ["price"] = s != null ? Math.Round(s.Price, 2) : null, + ["expiryUnix"] = s is { ExpiryUnixSeconds: > 0, IsTerminal: false } ? s.ExpiryUnixSeconds : null, + ["lastBidder"] = s?.LastBidder, + ["isMe"] = s?.IsMyBid ?? false, + ["resets"] = a.ResetCount, + ["myBids"] = a.MyBidsForLimits, + ["pingMs"] = a.Latency.Percentile(0.5), + ["leadMs"] = a.LeadMs > 0 ? a.LeadMs : null, + ["leadManual"] = a.LeadIsManual, + ["pWin"] = Round(d?.PWin, 4), + ["ev"] = Round(d?.Ev, 3), + ["decision"] = d?.Kind, + ["shadow"] = d?.Shadow, + ["forecastClose"] = Round(f?.Close, 2), + ["forecastP10"] = Round(f?.P10, 2), + ["forecastP90"] = Round(f?.P90, 2), + ["buyNow"] = a.BuyNowPrice, + ["shipping"] = a.Shipping, + ["value"] = ProductRules.ValueOf(product, a.BuyNowPrice), + ["maxPrice"] = a.MaxPrice, + ["maxBids"] = a.MaxBids, + ["origin"] = a.Origin, + ["image"] = a.ImageUrl, + ["outcome"] = a.Outcome, + ["productKey"] = a.ProductKey, + ["followed"] = product?.Followed ?? false + }; + } + + public static Dictionary Account(AccountState acc) => new() + { + ["t"] = "account", + ["bids"] = acc.Total, + ["paid"] = acc.Paid, + ["free"] = acc.Free, + ["credit"] = acc.ShopCredit, + ["toConfirm"] = acc.ToConfirm + }; + + public static string SessionState(SessionStatus s) => s switch + { + SessionStatus.Valid => "ok", + SessionStatus.Checking => "verifica", + SessionStatus.Expired => "scaduta", + SessionStatus.Simulator => "simulatore", + _ => "assente" + }; + + public static Dictionary Session(BotWorld w) => new() + { + ["t"] = "session", + ["state"] = SessionState(w.Account.Status), + ["user"] = w.Account.Username, + ["detail"] = w.Account.StatusDetail, + ["since"] = w.Account.SessionSince, + ["source"] = w.Account.SessionSource, + ["checkedAt"] = w.Account.CheckedAtUtc, + ["simulator"] = w.IsSimulator + }; + + public static Dictionary Risk(RiskManager risk, AppSettings s) + { + var n = risk.Snapshot(); + var h = risk.Halt; + return new Dictionary + { + ["t"] = "risk", + ["halted"] = h != null, + ["reason"] = h?.Reason, + ["automatic"] = h?.Automatic, + ["haltedAt"] = h?.AtUtc, + ["todaySpent"] = Math.Round(n.TodaySpent, 2), + ["todayGained"] = Math.Round(n.TodayGained, 2), + ["todayNet"] = Math.Round(n.TodayNet, 2), + ["cumulative"] = Math.Round(n.Cumulative, 2), + ["drawdown"] = Math.Round(n.Drawdown, 2), + ["dailyBudget"] = s.DailyBudgetEuro, + ["stopLoss"] = s.DailyStopLossEuro, + ["maxDrawdown"] = s.MaxDrawdownEuro + }; + } + + public static Dictionary Mode(AppSettings s, BotWorld? w) => new() + { + ["t"] = "mode", + ["live"] = s.LiveBiddingEnabled, + ["simulator"] = w?.IsSimulator ?? false, + ["learning"] = s.LearningEnabled, + ["showForecast"] = s.ShowForecastColumn, + ["dark"] = s.DarkMode, + ["navCollapsed"] = s.NavCollapsed + }; + + public static Dictionary Net(BotWorld w) + { + var lat = w.Latency.Snapshot(); + var clock = w.Monitor.Clock; + return new Dictionary + { + ["t"] = "net", + ["pingP50"] = w.Transport.PollLatency.Percentile(0.5) ?? (lat.P50 > 0 ? lat.P50 : null), + ["pingP99"] = w.Transport.PollLatency.Percentile(0.99) ?? (lat.P99 > 0 ? lat.P99 : null), + ["synced"] = clock.IsSynced, + ["serverClockOffsetMs"] = Math.Round(clock.OffsetMs()), + ["nowUnixMs"] = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), + ["leadMs"] = w.Latency.RecommendedLeadMs(w.Monitor.Settings), + ["requests"] = w.Transport.RequestsSent, + ["failures"] = w.Transport.RequestsFailed, + ["brakeMs"] = w.Transport.BrakeRemainingMs + }; + } + + public static Dictionary Db(WriteQueue q, Maintenance m) => new() + { + ["t"] = "db", + ["ok"] = q.DownSince == null, + ["downSince"] = q.DownSince, + ["sizeBytes"] = m.LastSizeBytes, + ["capBytes"] = m.CapBytes, + ["queued"] = q.Pending, + ["dropped"] = q.Dropped, + ["lastError"] = q.DownSince != null ? q.LastError : null, + ["maintenance"] = m.LastSummary, + ["maintenanceAt"] = m.LastRunUtc + }; + + /// Il pannello dettagli dell'asta selezionata. + public static Dictionary AuctionDetail(AuctionInfo a, BotWorld world, AppSettings settings) + { + var s = a.LastState; + var d = a.LastDecision; + var f = a.Forecast as ForecastResult; + var product = world.Monitor.Deps.Products.Find(a.ProductKey); + var value = ProductRules.ValueOf(product, a.BuyNowPrice); + var cost = BidStrategy.EffectiveBidCost(settings, world.Account.Balance); + var recent = a.SnapshotRecentBids(50); + var bidders = a.SnapshotBidders(); + var total = bidders.Sum(b => b.Total); + + double? costIfWin = s != null ? Math.Round(s.Price + settings.TransactionFeeEuro + (a.Shipping ?? 0) + a.MyBidsCost, 2) : null; + var distinct20 = recent.Take(20).Select(b => b.Username).Distinct(StringComparer.OrdinalIgnoreCase).Count(); + var deep = BidFeatures.CountDeepCycles(recent.Take(11).Select(b => b.Timestamp).ToList()); + + return new Dictionary + { + ["t"] = "auction.detail", + ["id"] = a.Id, + ["name"] = a.Name, + ["url"] = a.Url, + ["image"] = a.ImageUrl, + ["origin"] = a.Origin, + ["addedAt"] = a.AddedAtUtc, + ["openedAt"] = a.OpenedAtUtc, + ["trackingSince"] = a.TrackingStartedAtUtc, + ["fromStart"] = a.ObservedFromStart, + ["productKey"] = a.ProductKey, + ["followed"] = product?.Followed ?? false, + ["status"] = a.DisplayStatus(), + ["serverStatus"] = s?.Status.ToString(), + ["decision"] = d == null ? null : new Dictionary + { + ["kind"] = d.Kind, ["bid"] = d.ShouldBid, ["shadow"] = d.Shadow, ["pModel"] = Round(d.PModel, 4), ["pWin"] = Round(d.PWin, 4), + ["ev"] = Round(d.Ev, 3), ["bidCost"] = Round(d.BidCost, 3), ["reason"] = d.Reason, ["at"] = d.AtUtc + }, + ["forecast"] = f == null ? null : new Dictionary + { + ["close"] = Round(f.Close, 2), ["p10"] = Round(f.P10, 2), ["p90"] = Round(f.P90, 2), ["winnerBids"] = Round(f.WinnerBids, 0), + ["minutesLeft"] = Round(f.MinutesLeft, 1), ["pWinIfEnter"] = Round(f.PWinIfEnter, 4), ["costIfEnter"] = Round(f.CostIfEnter, 2), + ["evIfEnter"] = Round(f.EvIfEnter, 2), ["basis"] = f.Basis, ["samples"] = f.Samples, ["at"] = f.AtUtc, ["priceAt"] = f.PriceAt + }, + ["limits"] = new Dictionary + { + ["leadMs"] = a.LeadMs, ["leadManual"] = a.LeadIsManual, ["adaptiveLeadMs"] = world.Latency.RecommendedLeadMs(settings), + ["maxPrice"] = a.MaxPrice, ["maxBids"] = a.MaxBids, ["quietHours"] = a.QuietHoursOverride, + ["value"] = value, ["valueFromProduct"] = ProductRules.HasExplicitValue(product), ["bidCost"] = Math.Round(cost, 3) + }, + ["counters"] = new Dictionary + { + ["resets"] = a.ResetCount, ["myBids"] = a.MyBidsForLimits, ["myCost"] = Math.Round(a.MyBidsCost, 2), + ["pingAvg"] = Round(a.Latency.Average(), 0), ["pingP95"] = a.Latency.Percentile(0.95), + ["polls"] = Interlocked.Read(ref a.PollCount), ["pollErrors"] = Interlocked.Read(ref a.PollErrors), + ["successful"] = a.SuccessfulBids, ["failed"] = a.FailedBids, ["timerExpired"] = a.TimerExpiredCount, + ["costIfWin"] = costIfWin, ["distinct20"] = distinct20, ["deepCycles"] = deep, ["deepOf"] = Math.Min(10, Math.Max(0, recent.Count - 1)), + ["price"] = s?.Price, ["fee"] = settings.TransactionFeeEuro, ["shipping"] = a.Shipping + }, + ["product"] = new Dictionary + { + ["buyNow"] = a.BuyNowPrice, ["shipping"] = a.Shipping, ["winLimit"] = a.WinLimit, ["value"] = value, + ["marketValue"] = product?.MarketValue, ["loaded"] = a.ProductInfoLoaded, ["bidooProductId"] = a.BidooProductId + }, + ["bids"] = recent.Select(b => new Dictionary + { + ["ts"] = b.Timestamp, ["price"] = (double)b.Price, ["user"] = b.Username, ["type"] = b.BidType, ["me"] = b.IsMyBid + }).ToList(), + ["bidders"] = bidders.Select(b => new Dictionary + { + ["user"] = b.User, ["total"] = b.Total, ["recent"] = b.Recent, + ["share"] = total > 0 ? Math.Round((double)b.Total / total, 3) : 0, + ["shareRecent"] = recent.Count > 0 ? Math.Round((double)b.Recent / recent.Count, 3) : 0 + }).ToList(), + ["log"] = a.Log.Snapshot(200).Select(e => new Dictionary + { + ["ts"] = e.Ts, ["level"] = Level(e.Level), ["cat"] = e.Category.ToString().ToLowerInvariant(), + ["msg"] = e.Message, ["count"] = e.Count + }).ToList() + }; + } + + /// Il livello come lo usa l'interfaccia (classi CSS e filtri). + public static string Level(Logging.LogLevel level) => level switch + { + Logging.LogLevel.Debug => "debug", + Logging.LogLevel.Success => "ok", + Logging.LogLevel.Warning => "warn", + Logging.LogLevel.Error => "error", + _ => "info" + }; + + private static double? Round(double? v, int digits) => v is { } x && !double.IsNaN(x) && !double.IsInfinity(x) ? Math.Round(x, digits) : null; +} diff --git a/Mimante/src/BidooBidBot/Web/WebServer.cs b/Mimante/src/BidooBidBot/Web/WebServer.cs index 48e3e0c..cc42073 100644 --- a/Mimante/src/BidooBidBot/Web/WebServer.cs +++ b/Mimante/src/BidooBidBot/Web/WebServer.cs @@ -143,6 +143,12 @@ public static class WebServer return; } + if (path.StartsWith("/api/", StringComparison.Ordinal)) + { + await Api.HandleAsync(host.Bot!, ctx, path).ConfigureAwait(false); + return; + } + if (path.StartsWith("/esportazioni/", StringComparison.Ordinal)) { await Downloads.ServeExportAsync(host, ctx, path["/esportazioni/".Length..]).ConfigureAwait(false); diff --git a/Mimante/src/BidooBidBot/Web/WebSocketHub.Commands.cs b/Mimante/src/BidooBidBot/Web/WebSocketHub.Commands.cs new file mode 100644 index 0000000..04c3d8f --- /dev/null +++ b/Mimante/src/BidooBidBot/Web/WebSocketHub.Commands.cs @@ -0,0 +1,355 @@ +using System.Globalization; +using System.Text.Json; +using BidooBidBot.Data; +using BidooBidBot.Engine; +using BidooBidBot.Ml; +using BidooBidBot.Products; +using BidooBidBot.Session; +using BidooBidBot.Session.Cdp; +using BidooBidBot.Settings; + +namespace BidooBidBot.Web; + +/// +/// I comandi dall'interfaccia (Appendice D, client → server). Ogni comando con rid +/// riceve una risposta {"t":"ack","rid":…,"ok":…,"msg":…}; i comandi con effetto +/// economico chiedono conferma già nel browser e qui la ricontrollano. +/// +public sealed partial class WebSocketHub +{ + private sealed record Ack(bool Ok, string? Msg = null, object? Data = null); + + private async Task DispatchAsync(Client c, JsonElement m, CancellationToken ct) + { + var t = Str(m, "t") ?? ""; + long? rid = m.TryGetProperty("rid", out var r) && r.TryGetInt64(out var id) ? id : null; + Ack ack; + try + { + ack = await HandleAsync(c, t, m, ct).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + return; + } + catch (Exception ex) + { + _bot.Log.Warn("INTERFACCIA", $"Comando {t} non riuscito: {ex.Message}"); + ack = new Ack(false, $"Non riuscito: {ex.Message}"); + } + + if (rid != null) + { + c.Send(Serialize(new Dictionary + { + ["t"] = "ack", ["rid"] = rid, ["ok"] = ack.Ok, ["msg"] = ack.Msg, ["data"] = ack.Data + })); + } + } + + private async Task HandleAsync(Client c, string t, JsonElement m, CancellationToken ct) + { + var world = _bot.World; + var monitor = world.Monitor; + switch (t) + { + // ── stato dell'interfaccia ──────────────────────────────── + case "snapshot": + c.NeedsSnapshot = true; + return new Ack(true); + case "page": + c.Page = Str(m, "name") ?? "aste"; + c.LearningSentAt = 0; + return new Ack(true); + case "auction.watch": + c.WatchId = Str(m, "id"); + c.WatchVersion = -1; + c.WatchSentAt = 0; + return new Ack(true); + + // ── aste ────────────────────────────────────────────────── + case "auction.add": + { + var input = Str(m, "urlOrId"); + if (string.IsNullOrWhiteSpace(input)) return new Ack(false, "Scrivi l'indirizzo o il numero dell'asta"); + RunMode? mode = Str(m, "mode") is { } ms ? RunModes.Parse(ms) : null; + var (a, msg) = await monitor.AddAsync(new AddAuctionRequest(input, Str(m, "origin") ?? "mano", mode, Str(m, "name"), + Str(m, "image"), Dbl(m, "buyNow"), Int(m, "productId") ?? 0), ct).ConfigureAwait(false); + if (a == null) return new Ack(false, msg); + + var maxPrice = Dbl(m, "maxPrice"); + var maxBids = Int(m, "maxBids"); + var lead = Int(m, "leadMs"); + if (maxPrice != null || maxBids != null || lead is > 0) + monitor.SetLimits(a.Id, maxPrice ?? a.MaxPrice, maxBids ?? a.MaxBids, lead, a.QuietHoursOverride); + + if (Dbl(m, "value") is > 0 and var value && !string.IsNullOrEmpty(a.ProductKey)) + { + var p = _bot.Products.Find(a.ProductKey) ?? new ProductRecord { ProductKey = a.ProductKey, DisplayName = a.Name, BidooProductId = a.BidooProductId }; + p.MarketValue = Math.Round(value, 2); + _bot.Products.Upsert(p); + } + return new Ack(true, msg, new { id = a.Id }); + } + case "auction.remove": + return monitor.Remove(Str(m, "id") ?? "") ? new Ack(true, "Asta tolta") : new Ack(false, "Asta non in elenco"); + case "auctions.remove_finished": + return new Ack(true, $"{monitor.RemoveFinished()} aste concluse tolte"); + case "auction.set_mode": + { + var (ok, msg) = monitor.SetMode(Str(m, "id") ?? "", RunModes.Parse(Str(m, "mode"))); + return new Ack(ok, msg); + } + case "all.set_mode": + { + var mode = RunModes.Parse(Str(m, "mode")); + return new Ack(true, $"{monitor.SetAllModes(mode)} aste in {RunModes.Label(mode)}"); + } + case "auction.bid_now": + { + if (!Bool(m, "confirm")) return new Ack(false, "Serve la conferma"); + var (ok, msg) = await monitor.BidNowAsync(Str(m, "id") ?? "", ct).ConfigureAwait(false); + return new Ack(ok, msg); + } + case "auction.set_limits": + { + var aid = Str(m, "id") ?? ""; + var a = monitor.Find(aid); + if (a == null) return new Ack(false, "Asta non in elenco"); + bool? quiet = m.TryGetProperty("quietHours", out var q) && q.ValueKind is JsonValueKind.True or JsonValueKind.False ? q.GetBoolean() : null; + var (ok, msg) = monitor.SetLimits(aid, Dbl(m, "maxPrice") ?? a.MaxPrice, Int(m, "maxBids") ?? a.MaxBids, Int(m, "leadMs"), quiet); + if (ok && Dbl(m, "value") is { } v && !string.IsNullOrEmpty(a.ProductKey)) + { + var p = _bot.Products.Find(a.ProductKey) ?? new ProductRecord { ProductKey = a.ProductKey, DisplayName = a.Name, BidooProductId = a.BidooProductId }; + p.MarketValue = v > 0 ? Math.Round(v, 2) : null; + _bot.Products.Upsert(p); + } + return new Ack(ok, msg); + } + case "auction.refresh_product": + return await monitor.RefreshProductInfoAsync(Str(m, "id") ?? "", ct).ConfigureAwait(false) + ? new Ack(true, "Pagina dell'asta riletta") + : new Ack(false, "Pagina dell'asta non letta"); + + // ── rischio ─────────────────────────────────────────────── + case "halt": + _bot.Risk.SetHalt(Str(m, "reason") is { Length: > 0 } reason ? $"HALT dall'interfaccia: {reason}" : "HALT dall'interfaccia", automatic: false); + monitor.ForceAllObserve("HALT"); + return new Ack(true, "HALT attivo: nessuna puntata dal vivo"); + case "resume": + if (!Bool(m, "confirm")) return new Ack(false, "Serve la conferma"); + return _bot.Risk.Resume() ? new Ack(true, "HALT tolto") : new Ack(false, "Nessun HALT da togliere"); + + // ── impostazioni ────────────────────────────────────────── + case "settings.get": + return new Ack(true, null, await SettingsPayloadAsync().ConfigureAwait(false)); + case "settings.save": + { + if (!m.TryGetProperty("patch", out var patchEl) || patchEl.ValueKind != JsonValueKind.Object) return new Ack(false, "Niente da salvare"); + var patch = patchEl.EnumerateObject().ToDictionary(p => p.Name, p => p.Value.Clone()); + var result = await _bot.Settings.SaveAsync(patch, Str(m, "confirmation")).ConfigureAwait(false); + if (!result.Ok) return new Ack(false, result.Error); + return new Ack(true, result.Changes.Count == 0 ? "Nessuna modifica" : $"Salvato: {result.Changes.Count} modifiche", + await SettingsPayloadAsync().ConfigureAwait(false)); + } + case "telegram.test": + { + var (ok, msg) = await _bot.Telegram.SendTestAsync(ct).ConfigureAwait(false); + return new Ack(ok, msg); + } + case "maintenance.run": + return new Ack(true, await _bot.Maintenance.RunOnceAsync(full: Bool(m, "full"), ct).ConfigureAwait(false)); + + // ── sessione e accesso assistito ────────────────────────── + case "session.verify": + if (world.Checker == null) return new Ack(false, "Nessuna sessione: stai vedendo il simulatore"); + return await world.Checker.VerifyAsync(full: true, ct).ConfigureAwait(false) + ? new Ack(true, $"Sessione valida: {world.Account.Username}, {world.Account.BalanceText()} puntate") + : new Ack(false, world.Account.StatusDetail ?? "Bidoo non riconosce la sessione"); + case "session.paste": + { + var (cookie, error) = SessionStore.NormalizePastedCookie(Str(m, "cookie"), world.References().Recognizers.SessionCookie); + if (cookie == null) return new Ack(false, error); + var ua = Str(m, "userAgent"); + var (ok, msg) = await _bot.UseSessionAsync(new BidooSession + { + Cookie = cookie, UserAgent = string.IsNullOrWhiteSpace(ua) ? null : ua.Trim(), Source = SessionStore.SourcePasted + }, ct).ConfigureAwait(false); + return new Ack(ok, msg); + } + case "session.logout": + await _bot.LogoutAsync(ct).ConfigureAwait(false); + return new Ack(true, "Sessione cancellata: stai vedendo il simulatore"); + case "login.open": + { + var (ok, msg) = await _bot.Login.OpenAsync(ct).ConfigureAwait(false); + return new Ack(ok, msg); + } + case "login.close": + await _bot.Login.CloseAsync("chiuso dall'utente").ConfigureAwait(false); + return new Ack(true); + case "login.reload": + await _bot.Login.ReloadAsync(ct).ConfigureAwait(false); + return new Ack(true); + case "login.input": + await _bot.Login.InputAsync(LoginInput.From(m), ct).ConfigureAwait(false); + return new Ack(true); + + // ── prodotti ────────────────────────────────────────────── + case "product.follow": + { + var key = Str(m, "key"); + var name = Str(m, "name") ?? ""; + if (string.IsNullOrEmpty(key)) key = ProductKey.From(name); + if (string.IsNullOrEmpty(key)) return new Ack(false, "Prodotto senza nome"); + var followed = Bool(m, "followed"); + var p = _bot.Products.SetFollowed(key, name, Int(m, "productId") ?? 0, followed); + return new Ack(true, followed ? $"'{p.DisplayName}' seguito: le sue aste entrano da sole" : $"'{p.DisplayName}' non più seguito"); + } + case "product.save": + { + var key = Str(m, "key"); + if (string.IsNullOrEmpty(key)) return new Ack(false, "Prodotto sconosciuto"); + var p = _bot.Products.Find(key) ?? new ProductRecord { ProductKey = key, DisplayName = Str(m, "name") ?? key }; + p.MaxPrice = Dbl(m, "maxPrice") is > 0 and var mp ? Math.Round(mp, 2) : null; + p.MaxBids = Int(m, "maxBids") is > 0 and var mb ? mb : null; + p.MarketValue = Dbl(m, "marketValue") is > 0 and var mv ? Math.Round(mv, 2) : null; + p.HorizonMinutes = Int(m, "horizonMinutes") is >= 0 and var h && m.TryGetProperty("horizonMinutes", out var he) && he.ValueKind == JsonValueKind.Number ? h : null; + p.AutoState = Str(m, "autoState") is { Length: > 0 } st ? RunModes.ToKey(RunModes.Parse(st)) : null; + p.QuietHours = m.TryGetProperty("quietHours", out var qh) && qh.ValueKind is JsonValueKind.True or JsonValueKind.False ? qh.GetBoolean() : null; + if (m.TryGetProperty("followed", out var fe) && fe.ValueKind is JsonValueKind.True or JsonValueKind.False) p.Followed = fe.GetBoolean(); + _bot.Products.Upsert(p); + return new Ack(true, $"Scheda di '{p.DisplayName}' salvata"); + } + case "product.delete": + _bot.Products.Delete(Str(m, "key") ?? ""); + return new Ack(true, "Scheda tolta (lo storico delle aste resta)"); + case "products.apply_suggested": + { + if (!Bool(m, "confirm")) return new Ack(false, "Serve la conferma"); + var n = await Api.ApplySuggestedAsync(_bot, ct).ConfigureAwait(false); + return new Ack(true, $"Limiti consigliati applicati a {n} prodotti"); + } + case "products.refresh_stats": + { + var n = 0; + foreach (var key in await ProductStatsRepository.ProductKeysAsync(_bot.Db).ConfigureAwait(false)) + { + await ProductStatsRepository.RefreshAsync(_bot.Db, _bot.Queue, key, _bot.Settings.Current.TransactionFeeEuro).ConfigureAwait(false); + n++; + } + return new Ack(true, $"Statistiche ricalcolate per {n} prodotti"); + } + + // ── apprendimento ───────────────────────────────────────── + case "learning.study_now": + { + var progress = new Progress(p => c.Send(Serialize(new Dictionary + { + ["t"] = "progress", ["op"] = "study", ["done"] = p.Done, ["total"] = p.Total, ["detail"] = p.Detail + }))); + var (done, usable) = await world.Learning.StudyNowAsync(progress, ct).ConfigureAwait(false); + return new Ack(true, $"Studiate {done:N0} aste, {usable:N0} utilizzabili dal modello"); + } + case "learning.recalc": + { + var (bids, factor) = await world.Learning.RebuildOwnCalibrationAsync().ConfigureAwait(false); + return new Ack(true, bids > 0 ? $"Correzione ricalcolata su {bids} mie puntate: {factor.ToString("N2", It)}" : "Nessuna mia puntata con esito: correzione a 1"); + } + case "learning.rebuild_bandit": + { + var (auctions, obs) = await world.Learning.RebuildBanditAsync(null, ct).ConfigureAwait(false); + return new Ack(true, $"Bandit ricostruito da {auctions} aste ({obs} esiti)"); + } + case "learning.reset_challenger": + world.Learning.ResetChallenger(); + return new Ack(true, "Rete sfidante azzerata"); + case "learning.evaluate": + { + var report = await world.Learning.EvaluateAsync(Int(m, "max") ?? 300, world.Account.Username, null, ct).ConfigureAwait(false); + return new Ack(true, "Valutazione fatta", report.Text); + } + case "learning.forget": + if (Str(m, "confirm") != "DIMENTICA") return new Ack(false, "Per dimenticare tutto scrivi DIMENTICA"); + await world.Learning.ForgetAsync().ConfigureAwait(false); + return new Ack(true, "Il modello ha dimenticato tutto: si riparte da zero (l'archivio resta)"); + + // ── esportazioni ────────────────────────────────────────── + case "export.run": + { + var req = new CsvExport.Request( + Str(m, "what") ?? "", Date(m, "from"), Date(m, "to"), Bool(m, "onlyMyBids"), + Int(m, "maxRows") ?? _bot.Settings.Current.ExportMaxRows, world.Name); + var result = await _bot.Exports.RunAsync(req, ct).ConfigureAwait(false); + return new Ack(result.Ok, result.Message, new { files = result.Files, rows = result.Rows, sampled = result.Sampled }); + } + + default: + return new Ack(false, $"Comando sconosciuto: {t}"); + } + } + + private async Task> SettingsPayloadAsync() + { + var s = _bot.Settings.Current; + int? schema = null; + try { schema = await Migrations.CurrentVersionAsync(_bot.Db).ConfigureAwait(false); } catch { } + return new Dictionary + { + ["values"] = SettingsStore.ForDisplay(s), + ["defaults"] = SettingsStore.ForDisplay(new AppSettings()), + ["system"] = new Dictionary + { + ["version"] = AppInfo.Version, + ["db"] = _bot.Db.Config.Describe(), + ["dbOk"] = _bot.Queue.DownSince == null, + ["schema"] = schema, + ["queued"] = _bot.Queue.Pending, + ["written"] = _bot.Queue.Written, + ["failed"] = _bot.Queue.Failed, + ["dropped"] = _bot.Queue.Dropped, + ["uiPassword"] = _bot.Host.Env.HasUiPassword, + ["configDir"] = _bot.Paths.Root, + ["references"] = _bot.ReferencesProvider.FilePath, + ["sizeBytes"] = _bot.Maintenance.LastSizeBytes, + ["capBytes"] = _bot.Maintenance.CapBytes, + ["maintenance"] = _bot.Maintenance.LastSummary, + ["telegramReady"] = _bot.Telegram.Configured, + ["simulator"] = _bot.WorldOrNull?.IsSimulator ?? false + } + }; + } + + // ── lettura dei campi ──────────────────────────────────────────────── + + private static readonly CultureInfo It = CultureInfo.GetCultureInfo("it-IT"); + + private static string? Str(JsonElement m, string name) => + m.TryGetProperty(name, out var v) ? v.ValueKind switch + { + JsonValueKind.String => v.GetString(), + JsonValueKind.Number => v.GetRawText(), + _ => null + } : null; + + private static double? Dbl(JsonElement m, string name) + { + if (!m.TryGetProperty(name, out var v)) return null; + if (v.ValueKind == JsonValueKind.Number) return v.GetDouble(); + if (v.ValueKind == JsonValueKind.String) + { + var s = (v.GetString() ?? "").Trim().Replace("€", "").Replace(" ", ""); + if (s.Length == 0) return null; + if (double.TryParse(s.Replace(',', '.'), NumberStyles.Float, CultureInfo.InvariantCulture, out var d)) return d; + } + return null; + } + + private static int? Int(JsonElement m, string name) => Dbl(m, name) is { } d ? (int)Math.Round(d) : null; + + private static bool Bool(JsonElement m, string name) => + m.TryGetProperty(name, out var v) && (v.ValueKind == JsonValueKind.True || v.ValueKind == JsonValueKind.String && v.GetString() == "true"); + + private static DateTime? Date(JsonElement m, string name) => + Str(m, name) is { Length: > 0 } s && DateTime.TryParseExact(s, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var d) ? d : null; +} diff --git a/Mimante/src/BidooBidBot/Web/WebSocketHub.cs b/Mimante/src/BidooBidBot/Web/WebSocketHub.cs index 1258eec..abc81b4 100644 --- a/Mimante/src/BidooBidBot/Web/WebSocketHub.cs +++ b/Mimante/src/BidooBidBot/Web/WebSocketHub.cs @@ -1,13 +1,370 @@ +using System.Collections.Concurrent; +using System.Net.WebSockets; +using System.Text; +using System.Text.Json; +using System.Threading.Channels; +using BidooBidBot.Host; +using BidooBidBot.Logging; using Microsoft.AspNetCore.Http; namespace BidooBidBot.Web; -/// Segnaposto fino a M6: il protocollo WebSocket completo arriva con l'interfaccia. -public sealed class WebSocketHub +/// +/// Il canale dell'interfaccia (specifica §6.6, Appendice D). Un giro ogni 100 ms confronta +/// lo stato del motore con quello già spedito e manda soltanto ciò che è cambiato: righe +/// della griglia campo per campo, conto, sessione, rischio, rete, database, righe di +/// registro. I countdown li anima il client: il server manda la scadenza, non i secondi. +/// +/// Ogni client ha la sua coda d'uscita: un browser lento non rallenta gli altri né il +/// motore; se la coda si riempie, al giro dopo riceve un'istantanea intera. +/// +public sealed partial class WebSocketHub : IAsyncDisposable { + public const int TickMs = 100; + + private readonly Bot _bot; + private readonly ConcurrentDictionary _clients = new(); + private readonly ConcurrentQueue _events = new(); + private readonly Dictionary> _sentRows = new(StringComparer.Ordinal); + private readonly Dictionary _sentBlocks = new(StringComparer.Ordinal); + private readonly CancellationTokenSource _cts = new(); + private Task? _loop; + private long _nextId; + private volatile bool _resync = true; + private long _tick; + + internal static readonly JsonSerializerOptions Json = new() { PropertyNamingPolicy = null }; + + public WebSocketHub(Bot bot) + { + _bot = bot; + bot.WorldChanged += _ => _resync = true; + bot.Log.Entry += e => { if (e.Level >= LogLevel.Info) _events.Enqueue(e); }; + } + + public int ClientCount => _clients.Count; + + internal sealed class Client + { + public long Id { get; init; } + public required WebSocket Socket { get; init; } + public Channel Out { get; } = Channel.CreateBounded(new BoundedChannelOptions(2000) { SingleReader = true, FullMode = BoundedChannelFullMode.Wait }); + public volatile bool NeedsSnapshot = true; + public volatile string Page = "aste"; + public volatile string? WatchId; + public int WatchVersion = -1; + public int WatchLogVersion = -1; + public long WatchSentAt; + public long LearningSentAt; + + public void Send(string json) + { + if (!Out.Writer.TryWrite(json)) NeedsSnapshot = true; + } + } + + public void Start(CancellationToken ct) + { + var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, _cts.Token); + _loop = Task.Run(() => LoopAsync(linked.Token)); + } + + // ── Connessione ────────────────────────────────────────────────────── + public async Task AcceptAsync(HttpContext ctx) { using var socket = await ctx.WebSockets.AcceptWebSocketAsync().ConfigureAwait(false); - await socket.CloseAsync(System.Net.WebSockets.WebSocketCloseStatus.NormalClosure, "non ancora disponibile", CancellationToken.None).ConfigureAwait(false); + var client = new Client { Id = Interlocked.Increment(ref _nextId), Socket = socket }; + _clients[client.Id] = client; + client.Send(Serialize(Hello())); + + using var cts = CancellationTokenSource.CreateLinkedTokenSource(ctx.RequestAborted, _cts.Token); + var sender = Task.Run(() => SendLoopAsync(client, cts.Token)); + try + { + await ReceiveLoopAsync(client, cts.Token).ConfigureAwait(false); + } + catch (OperationCanceledException) { } + catch (WebSocketException) { } + finally + { + _clients.TryRemove(client.Id, out _); + client.Out.Writer.TryComplete(); + await cts.CancelAsync().ConfigureAwait(false); + try { await sender.ConfigureAwait(false); } catch { } + if (socket.State == WebSocketState.Open) + { + try { await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "fine", CancellationToken.None).ConfigureAwait(false); } catch { } + } + } + } + + private static async Task SendLoopAsync(Client client, CancellationToken ct) + { + try + { + await foreach (var json in client.Out.Reader.ReadAllAsync(ct).ConfigureAwait(false)) + { + if (client.Socket.State != WebSocketState.Open) return; + var bytes = Encoding.UTF8.GetBytes(json); + await client.Socket.SendAsync(bytes, WebSocketMessageType.Text, true, ct).ConfigureAwait(false); + } + } + catch (OperationCanceledException) { } + catch (WebSocketException) { } + } + + private async Task ReceiveLoopAsync(Client client, CancellationToken ct) + { + var buffer = new byte[16 * 1024]; + using var message = new MemoryStream(); + while (client.Socket.State == WebSocketState.Open && !ct.IsCancellationRequested) + { + var result = await client.Socket.ReceiveAsync(buffer, ct).ConfigureAwait(false); + if (result.MessageType == WebSocketMessageType.Close) return; + message.Write(buffer, 0, result.Count); + if (message.Length > 256 * 1024) return; // nessun messaggio legittimo è così grande + if (!result.EndOfMessage) continue; + + var bytes = message.ToArray(); + message.SetLength(0); + JsonDocument doc; + try { doc = JsonDocument.Parse(bytes); } + catch (JsonException) { continue; } + + // I comandi lunghi (studio, esportazioni) non fermano la lettura dei messaggi dopo. + _ = Task.Run(async () => + { + using (doc) await DispatchAsync(client, doc.RootElement, ct).ConfigureAwait(false); + }, ct); + } + } + + // ── Il giro a 10 Hz ────────────────────────────────────────────────── + + private async Task LoopAsync(CancellationToken ct) + { + using var timer = new PeriodicTimer(TimeSpan.FromMilliseconds(TickMs)); + while (await SafeWait(timer, ct).ConfigureAwait(false)) + { + try { await TickAsync().ConfigureAwait(false); } + catch (Exception ex) { _bot.Log.Debug("INTERFACCIA", $"Giro dell'interfaccia: {ex.Message}"); } + } + } + + private static async Task SafeWait(PeriodicTimer t, CancellationToken ct) + { + try { return await t.WaitForNextTickAsync(ct).ConfigureAwait(false); } + catch (OperationCanceledException) { return false; } + } + + private async Task TickAsync() + { + _tick++; + var world = _bot.WorldOrNull; + if (world == null) return; + var settings = _bot.Settings.Current; + var clients = _clients.Values.ToList(); + + // Righe di registro: sempre, anche senza client (la coda non deve crescere). + var events = new List(); + while (events.Count < 100 && _events.TryDequeue(out var e)) events.Add(Serialize(EventMessage(e))); + if (clients.Count == 0) + { + _events.Clear(); + _resync = true; + return; + } + + if (_resync) + { + _resync = false; + _sentRows.Clear(); + _sentBlocks.Clear(); + foreach (var c in clients) c.NeedsSnapshot = true; + } + + // Righe della griglia: solo i campi cambiati. + var outgoing = new List(); + var current = new HashSet(StringComparer.Ordinal); + foreach (var a in world.Monitor.Auctions) + { + current.Add(a.Id); + var row = Views.AuctionRow(a, world, settings); + if (!_sentRows.TryGetValue(a.Id, out var sent)) + { + _sentRows[a.Id] = row; + var added = new Dictionary(row) { ["t"] = "auction.delta", ["new"] = true }; + outgoing.Add(Serialize(added)); + continue; + } + + Dictionary? delta = null; + foreach (var (k, v) in row) + { + if (Equals(sent.GetValueOrDefault(k), v)) continue; + delta ??= new Dictionary { ["t"] = "auction.delta", ["id"] = a.Id }; + delta[k] = v; + } + if (delta != null) + { + _sentRows[a.Id] = row; + outgoing.Add(Serialize(delta)); + } + } + foreach (var gone in _sentRows.Keys.Where(k => !current.Contains(k)).ToList()) + { + _sentRows.Remove(gone); + outgoing.Add(Serialize(new Dictionary { ["t"] = "auction.removed", ["id"] = gone })); + } + + // Blocchi della barra: si mandano quando cambiano (rete e database al più ogni 2 s). + Block(outgoing, "account", Views.Account(world.Account)); + Block(outgoing, "session", Views.Session(world)); + Block(outgoing, "risk", Views.Risk(_bot.Risk, settings)); + Block(outgoing, "mode", Views.Mode(settings, world)); + if (_tick % 20 == 0) + { + Block(outgoing, "net", Views.Net(world), ignore: "nowUnixMs"); + Block(outgoing, "db", Views.Db(_bot.Queue, _bot.Maintenance)); + } + if (_tick % 50 == 0) _ = _bot.Maintenance.MeasureAsync(); + + foreach (var c in clients) + { + if (c.NeedsSnapshot) + { + c.NeedsSnapshot = false; + c.WatchVersion = -1; + c.Send(Serialize(Snapshot(world, settings))); + } + else + { + foreach (var m in outgoing) c.Send(m); + } + foreach (var m in events) c.Send(m); + + await SendWatchedAsync(c, world, settings).ConfigureAwait(false); + if (c.Page == "apprendimento" && Environment.TickCount64 - c.LearningSentAt > 5000) + { + c.LearningSentAt = Environment.TickCount64; + c.Send(Serialize(await LearningMessageAsync(world, settings).ConfigureAwait(false))); + } + } + } + + private void Block(List outgoing, string key, Dictionary value, string? ignore = null) + { + var compare = ignore == null ? value : value.Where(kv => kv.Key != ignore).ToDictionary(kv => kv.Key, kv => kv.Value); + var json = Serialize(compare); + if (_sentBlocks.TryGetValue(key, out var old) && old == json) return; + _sentBlocks[key] = json; + outgoing.Add(ignore == null ? json : Serialize(value)); + } + + /// Il dettaglio dell'asta selezionata: quando cambia, al più ogni 250 ms. + private Task SendWatchedAsync(Client c, BotWorld world, Settings.AppSettings settings) + { + var id = c.WatchId; + if (id == null) return Task.CompletedTask; + var a = world.Monitor.Find(id); + if (a == null) return Task.CompletedTask; + if (a.Version == c.WatchVersion && a.Log.Version == c.WatchLogVersion) return Task.CompletedTask; + if (Environment.TickCount64 - c.WatchSentAt < 250) return Task.CompletedTask; + + c.WatchVersion = a.Version; + c.WatchLogVersion = a.Log.Version; + c.WatchSentAt = Environment.TickCount64; + c.Send(Serialize(Views.AuctionDetail(a, world, settings))); + return Task.CompletedTask; + } + + // ── Messaggi interi ────────────────────────────────────────────────── + + private Dictionary Hello() + { + var w = _bot.WorldOrNull; + var s = _bot.Settings.Current; + return new Dictionary + { + ["t"] = "hello", + ["version"] = AppInfo.Version, + ["nowUnixMs"] = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), + ["serverClockOffsetMs"] = w != null ? Math.Round(w.Monitor.Clock.OffsetMs()) : 0, + ["clockSynced"] = w?.Monitor.Clock.IsSynced ?? false, + ["mode"] = s.LiveBiddingEnabled ? "dal-vivo" : "osserva", + ["simulator"] = w?.IsSimulator ?? false, + ["db"] = _bot.Queue.DownSince == null ? "ok" : "giu" + }; + } + + private Dictionary Snapshot(BotWorld world, Settings.AppSettings settings) + { + var rows = world.Monitor.Auctions.Select(a => _sentRows.TryGetValue(a.Id, out var r) ? r : Views.AuctionRow(a, world, settings)).ToList(); + return new Dictionary + { + ["t"] = "snapshot", + ["auctions"] = rows, + ["account"] = Views.Account(world.Account), + ["session"] = Views.Session(world), + ["risk"] = Views.Risk(_bot.Risk, settings), + ["mode"] = Views.Mode(settings, world), + ["net"] = Views.Net(world), + ["db"] = Views.Db(_bot.Queue, _bot.Maintenance), + ["log"] = _bot.Log.Snapshot(200).Select(EventMessage).ToList() + }; + } + + internal static Dictionary EventMessage(LogEntry e) => new() + { + ["t"] = "event", + ["id"] = e.Id, + ["ts"] = e.Ts, + ["level"] = Views.Level(e.Level), + ["category"] = e.Tag, + ["auctionId"] = e.AuctionId, + ["msg"] = e.Text + }; + + private async Task> LearningMessageAsync(BotWorld w, Settings.AppSettings s) + { + var status = await w.Learning.GetStatusAsync(s).ConfigureAwait(false); + var brier = w.Learning.BrierScores; + return new Dictionary + { + ["t"] = "learning", + ["state"] = status.State.ToString(), + ["headline"] = status.Headline, + ["detail"] = status.Detail, + ["learned"] = status.Learned, + ["pending"] = status.Pending, + ["threshold"] = status.Threshold, + ["studying"] = w.Learning.Studying, + ["champion"] = w.Learning.Champion, + ["brier"] = new Dictionary { ["logit"] = Num(brier.Logit), ["nn"] = Num(brier.Net), ["samples"] = brier.Samples }, + ["ownBidFactor"] = Math.Round(w.Learning.OwnBidFactor, 3), + ["explorationToday"] = w.Learning.ExplorationUsedToday, + ["leadMs"] = w.Latency.RecommendedLeadMs(s) + }; + } + + private static double? Num(double v) => double.IsNaN(v) || double.IsInfinity(v) ? null : Math.Round(v, 5); + + internal static string Serialize(object value) => JsonSerializer.Serialize(value, Json); + + /// Un messaggio a tutti i client (o a quelli di una pagina). + public void Broadcast(Dictionary message, string? page = null) + { + var json = Serialize(message); + foreach (var c in _clients.Values) + if (page == null || c.Page == page) c.Send(json); + } + + public async ValueTask DisposeAsync() + { + await _cts.CancelAsync().ConfigureAwait(false); + if (_loop != null) try { await _loop.ConfigureAwait(false); } catch { } + foreach (var c in _clients.Values) c.Out.Writer.TryComplete(); + _cts.Dispose(); } } diff --git a/Mimante/tests/BidooBidBot.Tests/MonitorTests.cs b/Mimante/tests/BidooBidBot.Tests/MonitorTests.cs new file mode 100644 index 0000000..d13e2fd --- /dev/null +++ b/Mimante/tests/BidooBidBot.Tests/MonitorTests.cs @@ -0,0 +1,189 @@ +using BidooBidBot.Bidoo; +using BidooBidBot.Data; +using BidooBidBot.Engine; +using BidooBidBot.Logging; +using BidooBidBot.Ml; +using BidooBidBot.Net; +using BidooBidBot.Products; +using BidooBidBot.Session; +using BidooBidBot.Settings; +using BidooBidBot.Simulator; +using BidooBidBot.Strategy; +using Xunit; + +namespace BidooBidBot.Tests; + +/// Il monitor intero (motori, verdetto, puntata, chiusura) contro il simulatore, senza database. +public class MonitorAgainstSimulatorTests +{ + private sealed class Rig : IAsyncDisposable + { + public required SimulatedBidoo Sim { get; init; } + public required AuctionMonitor Monitor { get; init; } + public required BidooTransport Transport { get; init; } + public required BidLane Lane { get; init; } + public required AppLog Log { get; init; } + public required RiskManager Risk { get; init; } + public required AccountState Account { get; init; } + public SimWorld World => Sim.World; + + public async ValueTask DisposeAsync() + { + await Monitor.DisposeAsync(); + Lane.Dispose(); + Transport.Dispose(); + await Sim.DisposeAsync(); + } + } + + private static async Task StartAsync(SimWorld world, AppSettings settings) + { + var sim = await SimulatedBidoo.StartAsync(world); + var refs = sim.References(); + var transport = new BidooTransport(() => refs, 0); + var lane = new BidLane(transport, () => refs, keepWarm: false); + var api = new BidooApi(transport, lane, () => refs) { Username = world.MyUsername }; + var docs = new MemoryDocumentStore(); + var log = new AppLog(null); + var account = new AccountState(); + account.SetUser(world.MyUsername, world.MyUserId); + var risk = new RiskManager(docs, new ListLedger()); + var learning = new LearningService(docs, new MemoryLearningData(), () => settings, log); + var products = new ProductStore(null); + + var monitor = new AuctionMonitor(new MonitorDeps + { + Settings = () => settings, + References = () => refs, + Api = api, + Clock = new ServerClock(), + Strategy = new BidStrategy(risk, learning, products, () => account.Balance), + Risk = risk, + Learning = learning, + Latency = new LatencyModel(docs), + Recorder = new AuctionRecorder(null, null, () => settings, () => world.MyUsername, Worlds.Simulator), + Products = products, + Account = account, + Log = log, + Documents = docs, + World = Worlds.Simulator + }); + return new Rig { Sim = sim, Monitor = monitor, Transport = transport, Lane = lane, Log = log, Risk = risk, Account = account }; + } + + private static async Task<(AuctionInfo A, CloseSummary C, string Line)> RunToCompletionAsync(Rig rig, AuctionInfo a, int seconds = 30) + { + var done = new TaskCompletionSource<(AuctionInfo, CloseSummary, string)>(TaskCreationOptions.RunContinuationsAsynchronously); + rig.Monitor.AuctionCompleted += (x, c, line) => { if (x.Id == a.Id) done.TrySetResult((x, c, line)); }; + rig.Monitor.Start(); + return await done.Task.WaitAsync(TimeSpan.FromSeconds(seconds)); + } + + [Fact] + public async Task In_Attiva_punta_una_volta_vince_e_chiude_con_il_riepilogo() + { + var world = new SimWorld(seed: 21, populate: false); + var settings = new AppSettings { QuietHoursEnabled = false, DefaultMaxPrice = 0, DefaultMaxClicks = 0 }; + await using var rig = await StartAsync(world, settings); + var target = world.AddRunningAuction(seconds: 5, freq: 4); + + var (a, message) = await rig.Monitor.AddAsync(new AddAuctionRequest(target.Id, Mode: RunMode.Active), CancellationToken.None); + Assert.NotNull(a); + Assert.Contains("Attiva", message); + Assert.True(a!.ProductInfoLoaded); + Assert.Equal(target.Value, a.BuyNowPrice); + + var (done, summary, line) = await RunToCompletionAsync(rig, a); + + Assert.Equal("won", done.Outcome); + Assert.True(summary.WonByMe); + Assert.Equal(1, summary.MyBids); + Assert.Equal(1, done.SuccessfulBids); + Assert.Single(world.MyBids, b => b.AuctionId == target.Id && b.Accepted); + Assert.StartsWith("Vinta a", line); + Assert.Contains("resta in elenco", line); + Assert.NotNull(rig.Monitor.Find(target.Id)); + Assert.Contains(rig.Log.Snapshot(), e => e.Tag == "PUNTATA"); + Assert.Contains(rig.Log.Snapshot(), e => e.Tag == "FINE"); + // Il conto si aggiorna dalla risposta di bid.php. + Assert.NotNull(rig.Account.Total); + } + + [Fact] + public async Task In_Osserva_decide_senza_puntare_e_la_conclusa_esce_dall_elenco() + { + var world = new SimWorld(seed: 22, populate: false); + var settings = new AppSettings { QuietHoursEnabled = false, DefaultMaxPrice = 0, DefaultMaxClicks = 0 }; + await using var rig = await StartAsync(world, settings); + var target = world.AddRunningAuction(seconds: 4, freq: 4); + + var (a, _) = await rig.Monitor.AddAsync(new AddAuctionRequest(target.Id, Mode: RunMode.Watch), CancellationToken.None); + var (done, summary, line) = await RunToCompletionAsync(rig, a!); + + Assert.Empty(world.MyBids); + Assert.False(summary.WonByMe); + Assert.Equal("lost", done.Outcome); + Assert.NotNull(done.LastDecision); + Assert.True(done.LastDecision!.Shadow); + Assert.Contains(done.Log.Snapshot(), e => e.Message.StartsWith("Avrei puntato", StringComparison.Ordinal)); + Assert.Contains("tolta dall'elenco", line); + Assert.Null(rig.Monitor.Find(target.Id)); + } + + [Fact] + public async Task Il_rischio_fermo_blocca_la_puntata_dal_vivo_ma_non_la_decisione() + { + var world = new SimWorld(seed: 23, populate: false); + var settings = new AppSettings { QuietHoursEnabled = false, DefaultMaxPrice = 0, DefaultMaxClicks = 0, AutoRemoveFinished = false }; + await using var rig = await StartAsync(world, settings); + rig.Risk.SetHalt("prova", automatic: false); + var target = world.AddRunningAuction(seconds: 4, freq: 4); + + var (a, _) = await rig.Monitor.AddAsync(new AddAuctionRequest(target.Id, Mode: RunMode.Active), CancellationToken.None); + var (done, _, _) = await RunToCompletionAsync(rig, a!); + + Assert.Empty(world.MyBids); + Assert.Equal(LossReasons.Kind.Rischio, done.LastDecision?.Kind); + var (ok, why) = await rig.Monitor.BidNowAsync(target.Id, CancellationToken.None); + Assert.False(ok); + Assert.NotEmpty(why); + } + + [Fact] + public async Task L_elenco_si_salva_e_si_ripristina_con_il_modo_di_avvio() + { + var world = new SimWorld(seed: 24, populate: false); + var settings = new AppSettings { QuietHoursEnabled = false, RememberAuctionStates = false, DefaultStartAuctionsOnLoad = "Ferma" }; + var target = world.AddRunningAuction(seconds: 600, freq: 10); + + string? saved; + await using (var rig = await StartAsync(world, settings)) + { + var (a, _) = await rig.Monitor.AddAsync(new AddAuctionRequest(target.Id, Mode: RunMode.Active), CancellationToken.None); + rig.Monitor.SetLimits(a!.Id, 12.5, 30, 450, quietHours: false); + await rig.Monitor.DisposeAsync(); + saved = rig.Monitor.Deps.Documents.Get(rig.Monitor.Deps.DocumentKey); + } + Assert.NotNull(saved); + + await using var again = await StartAsync(world, settings); + again.Monitor.Deps.Documents.Set(again.Monitor.Deps.DocumentKey, saved!); + Assert.Equal(1, await again.Monitor.RestoreAsync()); + var restored = again.Monitor.Find(target.Id)!; + Assert.Equal(RunMode.Stopped, restored.Mode); + Assert.Equal(12.5, restored.MaxPrice); + Assert.Equal(30, restored.MaxBids); + Assert.True(restored.LeadIsManual); + Assert.Equal(450, restored.LeadMs); + Assert.False(restored.QuietHoursOverride); + } + + [Fact] + public void Gli_errori_di_puntata_tardiva_si_riconoscono() + { + Assert.True(AuctionMonitor.IsLateBidError("timer scaduto")); + Assert.True(AuctionMonitor.IsLateBidError("auction closed")); + Assert.False(AuctionMonitor.IsLateBidError("saldo insufficiente")); + Assert.False(AuctionMonitor.IsLateBidError(null)); + } +}