From f2eb86be861d79109b151c8e2ed9c03430d839ec Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 24 Nov 2026 12:47:30 +0100 Subject: [PATCH] Scaricamento dei dati per l'analisi: tools/Mimante.Dati (#26) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Serve a portare sul PC l'archivio del bot (decine di GB) in una forma che si analizza senza toccare il database: per migliorare la scelta delle puntate e il modello servono le decisioni, le puntate e le aste concluse, giorno per giorno. - Data/Archive: catalogo delle tabelle (una tabella nuova non esce finché non la si mette nel catalogo; un test lo impone), pseudonimi stabili uguali in SQL e in C#, nomi nei testi, segreti di settings e documenti monitor/* tolti. - bids e resets divisi per giorno locale con intervalli di id trovati per bisezione sulla chiave primaria, decisioni e previsioni per ts; manifesto con righe, byte, impronta e filtro; si riprende saltando i file definitivi. - Riassunti già aggregati, dossier JSONL per ogni asta con mie puntate più un campione di aste osservate, LEGGIMI.md generato dal catalogo. - Connessione in sola lettura per costruzione, velocità limitata, pausa durante la manutenzione notturna, riserva di spazio; verifica --contro-db. - Data/BulkCopy estratto dal backup notturno (righe esatte, impronta, .tmp). Provato sul database vero in sola lettura: stima (2,5 GB attesi) e riassunti. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 7 + Mimante.slnx | 1 + docs/architettura.md | 19 +- src/Mimante/Data/Archive/ArchiveDownloader.cs | 603 ++++++++++++++++++ src/Mimante/Data/Archive/ArchiveReadme.cs | 89 +++ src/Mimante/Data/Archive/ArchiveTables.cs | 88 +++ src/Mimante/Data/Archive/DayRanges.cs | 37 ++ src/Mimante/Data/Archive/Manifest.cs | 100 +++ src/Mimante/Data/Archive/Pseudonyms.cs | 73 +++ src/Mimante/Data/BulkCopy.cs | 305 +++++++++ src/Mimante/Data/CsvExport.cs | 24 +- src/Mimante/Data/Maintenance.cs | 17 +- tests/Mimante.Tests/ArchiveTests.cs | 398 ++++++++++++ tools/Mimante.Dati/Mimante.Dati.csproj | 19 + tools/Mimante.Dati/Program.cs | 227 +++++++ 15 files changed, 1969 insertions(+), 38 deletions(-) create mode 100644 src/Mimante/Data/Archive/ArchiveDownloader.cs create mode 100644 src/Mimante/Data/Archive/ArchiveReadme.cs create mode 100644 src/Mimante/Data/Archive/ArchiveTables.cs create mode 100644 src/Mimante/Data/Archive/DayRanges.cs create mode 100644 src/Mimante/Data/Archive/Manifest.cs create mode 100644 src/Mimante/Data/Archive/Pseudonyms.cs create mode 100644 src/Mimante/Data/BulkCopy.cs create mode 100644 tests/Mimante.Tests/ArchiveTests.cs create mode 100644 tools/Mimante.Dati/Mimante.Dati.csproj create mode 100644 tools/Mimante.Dati/Program.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 7d478a1..d3a2a7d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,13 @@ copia nella release la sezione della versione. alla volta, di fondo: la finestra mostra fase e righe, si chiude e si riapre, ha **Annulla** e non lascia file a metà. Le puntate di risposta si cercano con l'indice (anche alla chiusura delle aste), e la pagina Apprendimento legge i suoi tre rapporti con una sola lettura invece di tre. +- **Scaricamento dei dati** (`tools/Mimante.Dati`): porta l'archivio sul PC in una cartella da analizzare, + in sola lettura. Le tabelle grandi un file `.csv.gz` per giorno, i riassunti già aggregati (aste, + prodotti, mie puntate, latenza, calibrazione, previsioni, orari, avversari, cicli, qualità, rischio), + un dossier JSONL per ogni asta su cui il bot ha puntato e il `LEGGIMI.md` con ogni colonna. Riprende + da dove si era fermato, controlla le impronte (`verifica --contro-db`), rallenta e si ferma durante la + manutenzione notturna; gli altri utenti diventano pseudonimi e i segreti non escono. Il backup notturno + usa la stessa copia in blocco. ## 1.2.0 diff --git a/Mimante.slnx b/Mimante.slnx index bc5a8dc..96dcc19 100644 --- a/Mimante.slnx +++ b/Mimante.slnx @@ -6,6 +6,7 @@ + diff --git a/docs/architettura.md b/docs/architettura.md index 68c6c3f..bbcbaf9 100644 --- a/docs/architettura.md +++ b/docs/architettura.md @@ -300,7 +300,24 @@ riepilogo, non si toccano mai. Oltre il 90% del tetto parte un avviso Telegram. Dopo la manutenzione, `COPY … TO STDOUT` delle tabelle non partizionate più `my_bids` e `auction_forecasts` in `/config/backup/AAAA-MM-GG/*.csv.gz`, conservati 14 giorni. Il grosso (`bids`) si affida al backup del container PostgreSQL. I registri su file (`app-*.log`, `aste-*.log`) -si cancellano dopo `LogRetentionDays` (90). +si cancellano dopo `LogRetentionDays` (90). La copia passa da `Data/BulkCopy` (file `.tmp` rinominato +alla fine, righe esatte, impronta SHA-256). + +### Scaricamento per l'analisi (`Data/Archive`, `tools/Mimante.Dati`) + +Lo strumento da riga di comando legge l'archivio su una connessione propria in sola lettura +(`default_transaction_read_only`, `statement_timeout`, fuso UTC) e scrive in `dati/` (ignorata da git): + +- `ArchiveTable.All` è il catalogo: una tabella che non c'è non esce (il test + `Ogni_tabella_delle_migrazioni_e_nel_catalogo_o_esclusa_apposta` obbliga a decidere per ogni tabella + nuova). Per ognuna dice come si divide, l'ordine, i filtri e le colonne riscritte: pseudonimi + (`Pseudonyms`, uguali in SQL e in C#), i nomi nei testi, i segreti di `settings`, i documenti `monitor/*`. +- `bids` e `resets` (senza indice sul tempo) si dividono per giorno locale con intervalli di id: + `DayRanges` trova per bisezione sulla chiave primaria il primo id del giorno; la finestra su + `created_at` fa leggere solo le partizioni vicine. `bot_decisions` e `auction_forecasts` usano l'indice su `ts`. +- `Manifest` (`manifesto.json`) registra per ogni file righe, byte, impronta e filtro: si riprende saltando + i file definitivi (più vecchi di due giorni), `verifica --contro-db` riconta con lo stesso filtro. +- Velocità limitata (20 MB/s), pausa dalle 4:20 alle 5:40 (manutenzione del bot), riserva di spazio libero. ### Impostazioni dal vivo e dal riavvio (`Settings/SettingsStore`) diff --git a/src/Mimante/Data/Archive/ArchiveDownloader.cs b/src/Mimante/Data/Archive/ArchiveDownloader.cs new file mode 100644 index 0000000..9910b55 --- /dev/null +++ b/src/Mimante/Data/Archive/ArchiveDownloader.cs @@ -0,0 +1,603 @@ +using System.Diagnostics; +using System.Globalization; +using System.Text; +using System.Text.Json.Nodes; +using System.Text.RegularExpressions; +using Mimante.Ml; +using Npgsql; + +namespace Mimante.Data.Archive; + +/// +/// Porta l'archivio PostgreSQL in una cartella di file da analizzare (con Claude o con qualunque strumento): +/// tabelle divise per giorno in .csv.gz, riassunti piccoli già leggibili, un dossier per asta, il manifesto +/// e il LEGGIMI.md. Solo letture, su una connessione in sola lettura (); +/// riprendibile (salta i file definitivi già scaricati); i nomi degli altri utenti diventano pseudonimi. +/// +public sealed partial class ArchiveDownloader +{ + public sealed record Options + { + public required string Folder { get; init; } + public DateOnly? From { get; init; } + public DateOnly? To { get; init; } + + /// Solo queste tabelle (null = tutte quelle del catalogo). + public IReadOnlySet? Tables { get; init; } + + /// Velocità massima di lettura in MB/s di testo (0 = nessun limite). + public double MegabytesPerSecond { get; init; } = 20; + + /// Spazio da lasciare libero sul disco della cartella, in GB. + public double ReserveGb { get; init; } = 5; + + /// Un giorno diventa definitivo quando ne sono passati più di questi (gli esiti arrivano alla chiusura delle aste). + public int FinalAfterDays { get; init; } = 2; + + public bool RealNames { get; init; } + + /// Aspetta la fine della manutenzione notturna del bot (dalle 4:20 alle 5:40) prima di ogni file. + public bool PauseForMaintenance { get; init; } = true; + + /// Quante aste osservate per intero (senza mie puntate) entrano nei dossier, oltre a tutte quelle con mie puntate. + public int Sample { get; init; } = 200; + + /// Il giorno di oggi (per le prove); null = oggi nel fuso del bot. + public DateOnly? Today { get; init; } + } + + public sealed record EstimateRow(string Table, ArchiveSplit Split, long Rows, long TableBytes, DateOnly? FirstDay, int Days, int DaysDone, + long DownloadedBytes, long RemainingBytes); + + private static readonly TimeOnly MaintenanceFrom = new(4, 20); + private static readonly TimeOnly MaintenanceTo = new(5, 40); + + /// Rapporto tipico fra il file .csv.gz e lo spazio della tabella, finché non ci sono file veri da cui ricavarlo. + private const double TypicalRatio = 0.15; + + private readonly NpgsqlConnection _conn; + private readonly Options _o; + private readonly Action _say; + private readonly TimeZoneInfo _zone; + private readonly BulkCopy.Throttle? _throttle; + private readonly Dictionary> _columns = new(StringComparer.Ordinal); + private Manifest _manifest = null!; + private Pseudonyms _names = null!; + + public ArchiveDownloader(NpgsqlConnection conn, Options options, Action say, TimeZoneInfo? zone = null) + { + _conn = conn; + _o = options; + _say = say; + _zone = zone ?? AppInfo.TimeZone; + _throttle = options.MegabytesPerSecond > 0 ? new BulkCopy.Throttle(options.MegabytesPerSecond * 1024 * 1024) : null; + } + + /// + /// La connessione dello strumento: in sola lettura per costruzione (ogni transazione è READ ONLY: anche un + /// superutente non può scrivere), date in UTC e ISO (il formato dei file non dipende dal server), un tempo + /// massimo per istruzione, fuori dalle sorgenti del bot. + /// + public static NpgsqlConnectionStringBuilder ReadOnlyBuilder(DbConfig config, int statementTimeoutMinutes = 60) + { + var b = config.Builder(commandTimeoutSeconds: statementTimeoutMinutes * 60); + b.Pooling = false; + b.ApplicationName = "mimante-dati"; + b.Options = $"-c default_transaction_read_only=on -c TimeZone=UTC -c DateStyle=ISO,YMD -c statement_timeout={statementTimeoutMinutes * 60_000}"; + return b; + } + + private string Full(string relative) => Path.Combine(_o.Folder, relative.Replace('/', Path.DirectorySeparatorChar)); + + private DateOnly Today => _o.Today ?? DateOnly.FromDateTime(TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, _zone)); + + // ── preparazione ───────────────────────────────────────────────────── + + private async Task PrepareAsync(CancellationToken ct) + { + Directory.CreateDirectory(_o.Folder); + var saltFile = Path.Combine(_o.Folder, ".sale"); + if (!File.Exists(saltFile)) await File.WriteAllTextAsync(saltFile, Pseudonyms.NewSalt(), ct).ConfigureAwait(false); + var salt = (await File.ReadAllTextAsync(saltFile, ct).ConfigureAwait(false)).Trim(); + var mine = await ListAsync("SELECT DISTINCT me FROM auctions WHERE me IS NOT NULL AND me <> ''", ct).ConfigureAwait(false); + _names = new Pseudonyms(salt, mine, enabled: !_o.RealNames); + + _manifest = Manifest.Load(_o.Folder) ?? new Manifest { CreatedUtc = DateTime.UtcNow, Pseudonyms = !_o.RealNames }; + if ((_manifest.Tables.Count > 0 || _manifest.Other.Count > 0) && _manifest.Pseudonyms == _o.RealNames) + throw new InvalidOperationException(_manifest.Pseudonyms + ? "Questa cartella ha i dati con gli pseudonimi: per i nomi veri usa un'altra cartella (--cartella)." + : "Questa cartella ha i dati con i nomi veri: senza --nomi-veri usa un'altra cartella (--cartella)."); + _manifest.Pseudonyms = !_o.RealNames; + _manifest.Program = AppInfo.Version; + _manifest.FeaturesVersion = BidFeatures.Version; + _manifest.Schema = await ScalarAsync("SELECT coalesce(max(version), 0) FROM schema_migrations", ct).ConfigureAwait(false); + _manifest.Database = $"{_conn.Host}:{_conn.Port} database {_conn.Database}"; + _manifest.TimeZone = _zone.Id; + } + + private async Task> ColumnsAsync(string table, CancellationToken ct) + { + if (_columns.TryGetValue(table, out var cached)) return cached; + var list = new List<(string, string)>(); + await using var cmd = Db.Command(_conn, + "SELECT column_name, data_type FROM information_schema.columns WHERE table_schema = 'public' AND table_name = $1 ORDER BY ordinal_position", + new object?[] { table }); + await using var r = await cmd.ExecuteReaderAsync(ct).ConfigureAwait(false); + while (await r.ReadAsync(ct).ConfigureAwait(false)) list.Add((r.GetString(0), r.GetString(1))); + _columns[table] = list; + return list; + } + + // ── scaricamento delle tabelle ─────────────────────────────────────── + + public async Task DownloadAsync(CancellationToken ct) + { + await PrepareAsync(ct).ConfigureAwait(false); + _manifest.From = _o.From?.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture); + _manifest.To = _o.To?.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture); + var present = await ListAsync( + "SELECT c.relname FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace " + + "WHERE n.nspname = 'public' AND c.relkind IN ('r', 'p') AND NOT c.relispartition", ct).ConfigureAwait(false); + foreach (var unknown in present.Where(p => ArchiveTable.Find(p) == null).Order(StringComparer.Ordinal)) + _say($"Tabella {unknown} non prevista dallo strumento: saltata (aggiungila ad ArchiveTable.All se va scaricata)."); + + foreach (var table in ArchiveTable.All) + { + if (_o.Tables != null && !_o.Tables.Contains(table.Name)) continue; + if (!present.Contains(table.Name)) continue; + var columns = (await ColumnsAsync(table.Name, ct).ConfigureAwait(false)).Select(c => c.Name).ToList(); + var entry = _manifest.Table(table.Name, table.Split.ToString()); + entry.Columns = columns; + switch (table.Split) + { + case ArchiveSplit.Whole: + await CopyAsync(table, columns, entry, null, table.Where, false, null, null, ct).ConfigureAwait(false); + break; + case ArchiveSplit.IdDay: + await IdDaysAsync(table, columns, entry, ct).ConfigureAwait(false); + break; + case ArchiveSplit.TsDay: + await TsDaysAsync(table, columns, entry, ct).ConfigureAwait(false); + break; + } + } + _manifest.Save(_o.Folder); + await WriteReadmeAsync(ct).ConfigureAwait(false); + } + + /// I giorni da scaricare: dal primo dell'archivio a ieri, dentro --da e --a. + internal static IEnumerable Days(DateOnly first, DateOnly today, DateOnly? from, DateOnly? to) + { + var start = from is { } f && f > first ? f : first; + var end = today.AddDays(-1); + if (to is { } t && t < end) end = t; + for (var d = start; d <= end; d = d.AddDays(1)) yield return d; + } + + /// Definitivo se sono passati più di giorni. + internal static bool IsFinal(DateOnly day, DateOnly today, int finalAfterDays) => day.DayNumber < today.DayNumber - finalAfterDays; + + private DateOnly LocalDay(DateTime utc) => DateOnly.FromDateTime(TimeZoneInfo.ConvertTimeFromUtc(DateTime.SpecifyKind(utc, DateTimeKind.Utc), _zone)); + + private async Task IdDaysAsync(ArchiveTable table, List columns, Manifest.TableEntry entry, CancellationToken ct) + { + var key = table.Key!; + var (min, max) = await MinMaxAsync($"SELECT min({key}), max({key}) FROM {table.Name}", ct).ConfigureAwait(false); + if (min == null || max == null) { _say($"{table.Name}: vuota"); return; } + var end = max.Value + 1; + DayRanges.Probe probe = (atLeast, c) => ProbeAsync(table.Name, key, atLeast, c); + var first = await probe(min.Value, ct).ConfigureAwait(false); + long? cursor = null; + foreach (var day in Days(LocalDay(first!.Value.CreatedUtc), Today, _o.From, _o.To)) + { + var rel = table.RelativePath(day); + entry.Files.TryGetValue(rel, out var done); + if (Manifest.IsDone(done, Full(rel)) && done!.IdTo is { } to) { cursor = to; continue; } + var startUtc = DayRanges.StartUtc(day, _zone); + var nextUtc = DayRanges.StartUtc(day.AddDays(1), _zone); + var lo = cursor ?? await DayRanges.FirstIdAtOrAfterAsync(probe, min.Value, end, startUtc, ct).ConfigureAwait(false); + var hi = await DayRanges.FirstIdAtOrAfterAsync(probe, lo, end, nextUtc, ct).ConfigureAwait(false); + cursor = hi; + // L'intervallo di id decide il file; la finestra su created_at fa leggere solo le partizioni vicine. + var where = Inv($"{key} >= {lo} AND {key} < {hi} AND created_at >= {Ts(startUtc.AddDays(-1))} AND created_at < {Ts(nextUtc.AddDays(1))}"); + await CopyAsync(table, columns, entry, day, where, IsFinal(day, Today, _o.FinalAfterDays), lo, hi, ct).ConfigureAwait(false); + } + } + + private async Task TsDaysAsync(ArchiveTable table, List columns, Manifest.TableEntry entry, CancellationToken ct) + { + var key = table.Key!; + var first = await ScalarAsync($"SELECT min({key}) FROM {table.Name}", ct).ConfigureAwait(false); + if (first == null) { _say($"{table.Name}: vuota"); return; } + foreach (var day in Days(LocalDay(first.Value), Today, _o.From, _o.To)) + { + var rel = table.RelativePath(day); + entry.Files.TryGetValue(rel, out var done); + if (Manifest.IsDone(done, Full(rel))) continue; + var startUtc = DayRanges.StartUtc(day, _zone); + var nextUtc = DayRanges.StartUtc(day.AddDays(1), _zone); + var where = Inv($"{key} >= {Ts(startUtc)} AND {key} < {Ts(nextUtc)}"); + if (table.PartitionedByCreatedAt) where += Inv($" AND created_at >= {Ts(startUtc.AddDays(-1))} AND created_at < {Ts(nextUtc.AddDays(1))}"); + await CopyAsync(table, columns, entry, day, where, IsFinal(day, Today, _o.FinalAfterDays), null, null, ct).ConfigureAwait(false); + } + } + + private async Task CopyAsync(ArchiveTable table, List columns, Manifest.TableEntry entry, DateOnly? day, string? where, bool final, + long? idFrom, long? idTo, CancellationToken ct) + { + await BeforeFileAsync(ct).ConfigureAwait(false); + var rel = table.RelativePath(day); + var filter = where ?? "true"; + var sql = $"COPY (SELECT {table.SelectList(columns, _names)} FROM {table.Name} WHERE {filter} ORDER BY {table.Order}) TO STDOUT (FORMAT csv, HEADER)"; + var watch = Stopwatch.StartNew(); + var r = await BulkCopy.ToFileAsync(_conn, sql, Full(rel), TextTransform(table.TextWithNames), _throttle, ct).ConfigureAwait(false); + entry.Files[rel] = new Manifest.FileEntry + { + Rows = r.Rows, Bytes = r.Bytes, Sha256 = r.Sha256, DownloadedUtc = DateTime.UtcNow, Filter = filter, Final = final, + Day = day?.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), IdFrom = idFrom, IdTo = idTo + }; + _manifest.Save(_o.Folder); + _say(Inv($"{table.Name}{(day is { } d ? " " + d.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) : "")}: {r.Rows:N0} righe, {Mb(r.Bytes)} in {watch.Elapsed.TotalSeconds:0} s{(final || day == null ? "" : " (provvisorio)")}")); + } + + private BulkCopy.Transform? TextTransform(IReadOnlyList? textColumns) + { + if (textColumns == null || textColumns.Count == 0 || !_names.Enabled) return null; + return header => + { + var idx = textColumns.Select(c => header.ToList().IndexOf(c)).Where(i => i >= 0).ToArray(); + return idx.Length == 0 ? null : record => { foreach (var i in idx) record[i] = _names.Text(record[i]); }; + }; + } + + /// Prima di ogni file: niente durante la manutenzione notturna del bot, e mai sotto la riserva di spazio. + private async Task BeforeFileAsync(CancellationToken ct) + { + if (_o.PauseForMaintenance) + { + var now = TimeOnly.FromDateTime(TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, _zone)); + if (now >= MaintenanceFrom && now < MaintenanceTo) + { + var wait = MaintenanceTo - now; + _say($"Manutenzione notturna del bot in corso: riprendo alle {MaintenanceTo:HH\\:mm} (fra {wait.TotalMinutes:0} minuti)."); + await Task.Delay(wait, ct).ConfigureAwait(false); + } + } + if (_o.ReserveGb > 0 && BulkCopy.FreeBytes(_o.Folder) is { } free && free < _o.ReserveGb * (1L << 30)) + throw new IOException(Inv($"Spazio libero insufficiente: {free / (double)(1L << 30):0.0} GB, la riserva è {_o.ReserveGb:0.#} GB (--riserva-gb).")); + } + + // ── riassunti ──────────────────────────────────────────────────────── + + /// Un riassunto: file piccolo in riassunti/, leggibile subito, calcolato da PostgreSQL. + public sealed record Summary(string Name, string Description, string Sql, IReadOnlyList? TextWithNames = null); + + public IReadOnlyList Summaries() + { + var z = _zone.Id.Replace("'", "''"); + var unanswered = "outcome IN ('won', 'would_win', 'missed')"; + return new Summary[] + { + new("aste", "Una riga per asta conclusa, senza le colonne jsonb: prodotto, esito, prezzo, vincitore, copertura, puntate, ping, motivo.", + $"SELECT auction_id, type AS mondo, product_key, name, opened_at, end_time, final_price, outcome, won_by_me, my_bids, my_bids_cost, " + + $"{_names.Sql("winner_user")} AS winner_user, winner_bids_paid, winner_bids_free, observed_from_start, observed_to_end, observed_minutes, " + + "resets, distinct_bidders, total_observed_bids, top_bidder_share, buy_now_price, market_value, shipping, avg_ping_ms, p95_ping_ms, " + + "successful_bids, failed_bids, configured_lead_ms, mode_at_close, loss_reason FROM auctions WHERE outcome IS NOT NULL ORDER BY end_time, auction_id", + new[] { "loss_reason" }), + new("prodotti", "Per prodotto (sito vero): aste concluse, vinte, mie puntate, chiusure (media, mediana, 90° percentile), puntate del vincitore, puntatori.", + "SELECT product_key, min(name) AS nome, count(*) AS aste, count(*) FILTER (WHERE won_by_me) AS vinte, count(*) FILTER (WHERE my_bids > 0) AS con_mie_puntate, " + + "sum(my_bids) AS mie_puntate, round(avg(final_price), 2) AS chiusura_media, percentile_cont(0.5) WITHIN GROUP (ORDER BY final_price) AS chiusura_mediana, " + + "percentile_cont(0.9) WITHIN GROUP (ORDER BY final_price) AS chiusura_p90, min(final_price) AS chiusura_min, max(final_price) AS chiusura_max, " + + "round(avg(winner_bids_paid + coalesce(winner_bids_free, 0)), 1) AS puntate_vincitore_media, round(avg(distinct_bidders), 1) AS puntatori_medi, " + + "round(avg(observed_minutes)::numeric, 1) AS minuti_osservati_medi, max(buy_now_price) AS compralo_ora, max(market_value) AS valore " + + "FROM auctions WHERE outcome IS NOT NULL AND type = 'normal' GROUP BY product_key ORDER BY aste DESC, product_key"), + new("mie_puntate", "Le mie puntate vere con l'esito dell'asta e la decisione che le ha fatte partire (valore atteso, probabilità, motivo).", + $"SELECT mb.id, mb.auction_id, a.product_key, mb.local_ts, mb.price, mb.success, mb.error, mb.manual, mb.kind, mb.p_win, mb.planned_lead_ms, " + + $"mb.actual_lead_ms, mb.wait_error_ms, mb.ping_ms, mb.rtt_ms, mb.bids_used, mb.remaining_bids, mb.answered_after_s, {_names.Sql("mb.answered_by")} AS answered_by, " + + "mb.answered_type, mb.unanswered, a.final_price, a.won_by_me, d.ev, d.p_model, d.p_bandit, d.reason_detail " + + "FROM my_bids mb JOIN auctions a ON a.auction_id = mb.auction_id " + + "LEFT JOIN LATERAL (SELECT x.ev, x.p_model, x.p_bandit, x.reason_detail FROM bot_decisions x WHERE x.decision_id = mb.decision_id AND x.auction_id = mb.auction_id LIMIT 1) d ON true " + + "ORDER BY mb.id", new[] { "reason_detail" }), + new("latenza_giornaliera", "Per giorno: mie puntate, riuscite, tempo di andata e ritorno (medio, mediano, 95°), anticipo pianificato ed effettivo, errore dell'attesa, ping.", + $"SELECT (local_ts AT TIME ZONE '{z}')::date AS giorno, count(*) AS puntate, count(*) FILTER (WHERE success) AS riuscite, round(avg(rtt_ms)) AS rtt_medio_ms, " + + "percentile_cont(0.5) WITHIN GROUP (ORDER BY rtt_ms) AS rtt_p50_ms, percentile_cont(0.95) WITHIN GROUP (ORDER BY rtt_ms) AS rtt_p95_ms, " + + "round(avg(planned_lead_ms)) AS anticipo_pianificato_medio_ms, round(avg(actual_lead_ms)::numeric, 1) AS anticipo_effettivo_medio_ms, " + + "round(avg(wait_error_ms)::numeric, 2) AS errore_attesa_medio_ms, round(avg(ping_ms)) AS ping_medio_ms FROM my_bids WHERE local_ts IS NOT NULL GROUP BY 1 ORDER BY 1"), + new("decisioni_per_giorno", "Per giorno, tipo, verdetto, modo ed esito: quante decisioni, probabilità e valore atteso medi.", + $"SELECT (ts AT TIME ZONE '{z}')::date AS giorno, kind, action, shadow, executed, outcome, count(*) AS decisioni, " + + "round(avg(p_win)::numeric, 5) AS p_win_media, round(avg(ev)::numeric, 4) AS ev_medio FROM bot_decisions GROUP BY 1, 2, 3, 4, 5, 6 ORDER BY 1, 7 DESC"), + new("calibrazione", "La probabilità prevista contro la frequenza osservata che una puntata resti senza risposta, a fasce di 1 punto percentuale fino al 20%.", + "SELECT width_bucket(p_win, 0, 0.2, 20) AS fascia, round(min(p_win)::numeric, 4) AS p_min, round(max(p_win)::numeric, 4) AS p_max, count(*) AS decisioni, " + + $"round(avg(p_win)::numeric, 5) AS p_prevista, round(avg(CASE WHEN {unanswered} THEN 1.0 ELSE 0.0 END), 5) AS frequenza_osservata " + + "FROM bot_decisions WHERE p_win IS NOT NULL AND outcome IS NOT NULL AND outcome <> 'sent' AND kind IN ('punta', 'esplora', 'ev-negativo', 'non-pronto') " + + "GROUP BY 1 ORDER BY 1"), + new("previsioni", "Per prodotto: errore della prima previsione di chiusura (medio e assoluto) e quota di chiusure dentro l'intervallo 10-90.", + "SELECT a.product_key, count(*) AS previsioni, round(avg(f.error_close)::numeric, 3) AS errore_medio, round(avg(abs(f.error_close))::numeric, 3) AS errore_assoluto_medio, " + + "round(avg(CASE WHEN f.in_interval THEN 1.0 ELSE 0.0 END), 3) AS quota_nell_intervallo, round(avg(f.forecast_close)::numeric, 2) AS previsione_media, " + + "round(avg(f.actual_close)::numeric, 2) AS chiusura_media FROM auction_forecasts f JOIN auctions a ON a.auction_id = f.auction_id " + + "WHERE f.is_initial AND f.actual_close IS NOT NULL GROUP BY 1 ORDER BY 2 DESC, 1"), + new("orari", "Per ora di chiusura (ora locale, sito vero): aste, chiusura media, puntate del vincitore, puntatori, vinte da me.", + $"SELECT extract(hour FROM end_time AT TIME ZONE '{z}')::int AS ora, count(*) AS aste_chiuse, round(avg(final_price), 2) AS chiusura_media, " + + "round(avg(winner_bids_paid + coalesce(winner_bids_free, 0)), 1) AS puntate_vincitore_media, round(avg(distinct_bidders), 1) AS puntatori_medi, " + + "count(*) FILTER (WHERE won_by_me) AS vinte_da_me FROM auctions WHERE outcome IS NOT NULL AND type = 'normal' GROUP BY 1 ORDER BY 1"), + new("avversari", "I 500 puntatori più attivi (pseudonimi): aste, puntate, automatiche e a mano, vittorie, profilo.", + $"SELECT {_names.Sql("username")} AS username, first_seen, last_seen, n_auctions, n_bids, n_auto, n_manual, win_count, aggressiveness_score, profile_class " + + "FROM bidders ORDER BY n_bids DESC, username LIMIT 500"), + new("cicli_giornalieri", "Per giorno: ripartenze del timer, durata media del ciclo, timer minimo medio, quante sotto 1 s e sotto mezzo secondo.", + $"SELECT (created_at AT TIME ZONE '{z}')::date AS giorno, count(*) AS reset, round(avg(cycle_seconds)::numeric, 2) AS ciclo_medio_s, " + + "round(stddev(cycle_seconds)::numeric, 2) AS ciclo_deviazione_s, round(avg(min_timer)::numeric, 3) AS timer_minimo_medio_s, " + + "count(*) FILTER (WHERE min_timer < 1) AS sotto_1s, count(*) FILTER (WHERE min_timer < 0.5) AS sotto_mezzo_s FROM resets GROUP BY 1 ORDER BY 1"), + new("qualita_giornaliera", "Per giorno di chiusura: aste, quante seguite dall'inizio e fino alla fine, letture e letture fallite, timer scaduti, ping.", + $"SELECT (end_time AT TIME ZONE '{z}')::date AS giorno, count(*) AS aste_chiuse, count(*) FILTER (WHERE observed_from_start) AS dall_inizio, " + + "count(*) FILTER (WHERE observed_to_end) AS fino_alla_fine, sum(polls) AS letture, sum(poll_errors) AS letture_fallite, sum(timer_expired) AS timer_scaduti, " + + "round(avg(avg_ping_ms)::numeric, 1) AS ping_medio_ms, round(avg(p99_ping_ms)::numeric, 1) AS ping_p99_medio_ms FROM auctions WHERE outcome IS NOT NULL GROUP BY 1 ORDER BY 1"), + new("rischio", "Il registro del rischio per giorno e tipo: movimenti ed euro.", + $"SELECT (ts AT TIME ZONE '{z}')::date AS giorno, kind, count(*) AS movimenti, sum(amount_euro) AS euro FROM risk_ledger GROUP BY 1, 2 ORDER BY 1, 2"), + new("motivi_perdita", "Le forme dei motivi di perdita (numeri e nomi tolti) con quante aste ciascuna.", + "SELECT regexp_replace(regexp_replace(loss_reason, '(vinta|coperta|superata|ripresa) da [^\\s;,()]+', '\\1 da X', 'g'), '[0-9]+([.,][0-9]+)?', 'N', 'g') AS forma, " + + "count(*) AS aste FROM auctions WHERE loss_reason IS NOT NULL GROUP BY 1 ORDER BY 2 DESC, 1") + }; + } + + public async Task SummariesAsync(CancellationToken ct) + { + await PrepareAsync(ct).ConfigureAwait(false); + foreach (var s in Summaries()) + { + await BeforeFileAsync(ct).ConfigureAwait(false); + var rel = $"riassunti/{s.Name}.csv"; + var watch = Stopwatch.StartNew(); + var r = await BulkCopy.ToFileAsync(_conn, $"COPY ({s.Sql}) TO STDOUT (FORMAT csv, HEADER)", Full(rel), TextTransform(s.TextWithNames), null, ct) + .ConfigureAwait(false); + _manifest.Other[rel] = new Manifest.FileEntry { Rows = r.Rows, Bytes = r.Bytes, Sha256 = r.Sha256, DownloadedUtc = DateTime.UtcNow }; + _manifest.Save(_o.Folder); + _say(Inv($"riassunto {s.Name}: {r.Rows:N0} righe in {watch.Elapsed.TotalSeconds:0} s")); + } + await WriteReadmeAsync(ct).ConfigureAwait(false); + } + + // ── dossier ────────────────────────────────────────────────────────── + + private static readonly (string Kind, string Table, string Order)[] DossierSections = + { + ("asta", "auctions", "auction_id"), + ("previsione", "auction_forecasts", "ts, id"), + ("decisione", "bot_decisions", "ts, decision_id"), + ("mia_puntata", "my_bids", "id"), + ("puntata", "bids", "bid_id"), + ("reset", "resets", "reset_id") + }; + + /// + /// Un file JSONL per asta (una riga per fatto: l'asta, le previsioni, le decisioni, le mie puntate, le puntate, i + /// reset): tutte le aste del sito vero con mie puntate e un campione stabile di aste seguite dall'inizio alla fine. + /// + public async Task DossierAsync(CancellationToken ct) + { + await PrepareAsync(ct).ConfigureAwait(false); + var salt = (await File.ReadAllTextAsync(Path.Combine(_o.Folder, ".sale"), ct).ConfigureAwait(false)).Trim(); + var picks = new List<(string Id, bool Mine, bool Closed)>(); + await using (var cmd = Db.Command(_conn, + "(SELECT auction_id, true AS mine, outcome IS NOT NULL AS closed FROM auctions WHERE type = 'normal' AND my_bids > 0) UNION ALL " + + "(SELECT auction_id, false, true FROM auctions WHERE type = 'normal' AND my_bids = 0 AND observed_from_start AND observed_to_end " + + " AND outcome IS NOT NULL ORDER BY md5(auction_id || $1) LIMIT $2)", new object?[] { salt, _o.Sample })) + await using (var r = await cmd.ExecuteReaderAsync(ct).ConfigureAwait(false)) + while (await r.ReadAsync(ct).ConfigureAwait(false)) picks.Add((r.GetString(0), r.GetBoolean(1), r.GetBoolean(2))); + + var selects = new Dictionary(StringComparer.Ordinal); + foreach (var (_, table, _) in DossierSections) + selects[table] = ArchiveTable.Find(table)!.SelectList((await ColumnsAsync(table, ct).ConfigureAwait(false)).Select(c => c.Name).ToList(), _names); + + int written = 0, skipped = 0; + foreach (var (id, mine, closed) in picks) + { + var rel = $"dossier/{(mine ? "mie" : "osservate")}/{SafeName().Replace(id, "_")}.jsonl"; + if (_manifest.Other.TryGetValue(rel, out var done) && Manifest.IsDone(done, Full(rel))) { skipped++; continue; } + await BeforeFileAsync(ct).ConfigureAwait(false); + var full = Full(rel); + Directory.CreateDirectory(Path.GetDirectoryName(full)!); + long lines = 0; + try + { + await using (var w = new StreamWriter(full + ".tmp", false, new UTF8Encoding(false))) + { + foreach (var (kind, table, order) in DossierSections) + { + var spec = ArchiveTable.Find(table)!; + await using var cmd = Db.Command(_conn, + $"SELECT to_jsonb(x)::text FROM (SELECT '{kind}'::text AS tipo, {selects[table]} FROM {table} WHERE auction_id = $1 ORDER BY {order}) x", + new object?[] { id }); + await using var r = await cmd.ExecuteReaderAsync(ct).ConfigureAwait(false); + while (await r.ReadAsync(ct).ConfigureAwait(false)) + { + await w.WriteAsync(CleanJson(r.GetString(0), spec.TextWithNames)).ConfigureAwait(false); + await w.WriteAsync('\n').ConfigureAwait(false); + lines++; + } + } + } + File.Move(full + ".tmp", full, overwrite: true); + } + catch + { + try { File.Delete(full + ".tmp"); } catch (IOException) { } + throw; + } + _manifest.Other[rel] = new Manifest.FileEntry + { + Rows = lines, Bytes = new FileInfo(full).Length, Sha256 = await BulkCopy.Sha256Async(full, ct).ConfigureAwait(false), + DownloadedUtc = DateTime.UtcNow, Final = closed + }; + if (++written % 25 == 0) + { + _manifest.Save(_o.Folder); + _say($"dossier: {written:N0} scritti su {picks.Count - skipped:N0}"); + } + } + _manifest.Save(_o.Folder); + _say($"dossier: {written:N0} scritti, {skipped:N0} già presenti ({picks.Count(p => p.Mine):N0} aste con mie puntate, {picks.Count(p => !p.Mine):N0} osservate)"); + await WriteReadmeAsync(ct).ConfigureAwait(false); + } + + private string CleanJson(string json, IReadOnlyList? textColumns) + { + if (textColumns == null || !_names.Enabled) return json; + var node = JsonNode.Parse(json)!.AsObject(); + foreach (var c in textColumns) + if (node[c] is JsonValue v && v.TryGetValue(out var s)) node[c] = _names.Text(s); + return node.ToJsonString(); + } + + // ── verifica, stima, stato ─────────────────────────────────────────── + + /// + /// Ogni file del manifesto c'è, ha la dimensione e l'impronta registrate; con le righe dei + /// file del giorno definitivi sono quelle che il database conta con la stessa condizione. Restituisce i problemi. + /// + public static async Task> VerifyAsync(string folder, NpgsqlConnection? againstDb, Action say, CancellationToken ct) + { + var manifest = Manifest.Load(folder) ?? throw new InvalidOperationException($"In {folder} non c'è {Manifest.FileName}: prima scarica."); + var problems = new List(); + int checkedFiles = 0; + var all = manifest.Tables.SelectMany(t => t.Value.Files.Select(f => (Table: t.Key, Path: f.Key, Entry: f.Value))) + .Concat(manifest.Other.Select(f => (Table: "", Path: f.Key, Entry: f.Value))); + foreach (var (table, rel, entry) in all) + { + ct.ThrowIfCancellationRequested(); + var full = Path.Combine(folder, rel.Replace('/', Path.DirectorySeparatorChar)); + checkedFiles++; + if (!File.Exists(full)) { problems.Add($"{rel}: manca"); continue; } + if (new FileInfo(full).Length != entry.Bytes) { problems.Add($"{rel}: dimensione diversa da quella registrata"); continue; } + if (await BulkCopy.Sha256Async(full, ct).ConfigureAwait(false) != entry.Sha256) { problems.Add($"{rel}: impronta diversa (file cambiato o rovinato)"); continue; } + if (againstDb != null && table.Length > 0 && entry.Day != null && entry.Final && entry.Filter != null) + { + await using var cmd = new NpgsqlCommand($"SELECT count(*) FROM {table} WHERE {entry.Filter}", againstDb); + var n = (long)(await cmd.ExecuteScalarAsync(ct).ConfigureAwait(false))!; + if (n != entry.Rows) + problems.Add(Inv($"{rel}: {entry.Rows:N0} righe nel file, {n:N0} nel database{(n < entry.Rows ? " (la rotazione dello spazio ha tolto righe vecchie?)" : "")}")); + } + if (checkedFiles % 200 == 0) say($"verificati {checkedFiles:N0} file"); + } + say(problems.Count == 0 ? $"Verifica superata: {checkedFiles:N0} file integri." : $"Verifica: {problems.Count:N0} problemi su {checkedFiles:N0} file."); + return problems; + } + + public async Task> EstimateAsync(CancellationToken ct) + { + var manifest = Manifest.Load(_o.Folder); + var rows = new List(); + foreach (var table in ArchiveTable.All) + { + if (_o.Tables != null && !_o.Tables.Contains(table.Name)) continue; + var exists = await ScalarAsync($"SELECT to_regclass('public.{table.Name}') IS NOT NULL", ct).ConfigureAwait(false); + if (!exists) continue; + var (count, bytes) = await SizeAsync(table.Name, ct).ConfigureAwait(false); + DateOnly? first = null; + var days = 1; + if (table.Split != ArchiveSplit.Whole) + { + var sql = table.Split == ArchiveSplit.IdDay + ? $"SELECT created_at FROM {table.Name} ORDER BY {table.Key} LIMIT 1" + : $"SELECT min({table.Key}) FROM {table.Name}"; + if (await ScalarAsync(sql, ct).ConfigureAwait(false) is { } f) + { + first = LocalDay(f); + days = Days(first.Value, Today, _o.From, _o.To).Count(); + } + else days = 0; + } + var files = manifest?.Tables.GetValueOrDefault(table.Name)?.Files ?? new SortedDictionary(); + var done = files.Values.Count(f => f.Final); + var downloaded = files.Values.Sum(f => f.Bytes); + var totalDays = first is { } fd ? Math.Max(1, Today.DayNumber - fd.DayNumber) : 1; + long remaining = table.Split == ArchiveSplit.Whole + ? (long)(bytes * TypicalRatio) + : done > 0 + ? downloaded / Math.Max(1, files.Count) * Math.Max(0, days - done) + : (long)(bytes * TypicalRatio * days / totalDays); + rows.Add(new EstimateRow(table.Name, table.Split, count, bytes, first, days, Math.Min(done, days), downloaded, remaining)); + } + return rows; + } + + public static List Status(string folder) + { + var m = Manifest.Load(folder); + if (m == null) return new List { $"In {folder} non c'è ancora nulla: comincia con «stima» e «scarica»." }; + var lines = new List + { + $"Cartella {folder}", + $"Archivio {m.Database}, schema {m.Schema}, variabili del modello versione {m.FeaturesVersion}, scaricato con Mimante {m.Program}", + $"Nomi: {(m.Pseudonyms ? "pseudonimi" : "veri")}; aggiornato il {m.UpdatedUtc.ToLocalTime():dd/MM/yyyy HH:mm}" + }; + foreach (var (name, t) in m.Tables) + { + var days = t.Files.Values.Where(f => f.Day != null).Select(f => f.Day!).Order(StringComparer.Ordinal).ToList(); + var span = days.Count > 0 ? $", giorni {days[0]} → {days[^1]} ({days.Count}, {t.Files.Values.Count(f => f.Final)} definitivi)" : ""; + lines.Add(Inv($" {name}: {t.Files.Values.Sum(f => f.Rows):N0} righe, {Mb(t.Files.Values.Sum(f => f.Bytes))}{span}")); + } + var summaries = m.Other.Where(o => o.Key.StartsWith("riassunti/", StringComparison.Ordinal)).ToList(); + var dossier = m.Other.Where(o => o.Key.StartsWith("dossier/", StringComparison.Ordinal)).ToList(); + lines.Add(Inv($" riassunti: {summaries.Count}; dossier: {dossier.Count} ({Mb(dossier.Sum(d => d.Value.Bytes))})")); + lines.Add(Inv($" totale: {Mb(m.Tables.Values.SelectMany(t => t.Files.Values).Sum(f => f.Bytes) + m.Other.Values.Sum(f => f.Bytes))}")); + return lines; + } + + // ── aiuti ──────────────────────────────────────────────────────────── + + private async Task<(long Rows, long Bytes)> SizeAsync(string table, CancellationToken ct) + { + await using var cmd = Db.Command(_conn, + "SELECT coalesce(sum(greatest(c.reltuples, 0)), 0)::bigint, coalesce(sum(pg_table_size(c.oid)), 0)::bigint FROM pg_class c " + + "WHERE c.oid = to_regclass($1) OR c.oid IN (SELECT inhrelid FROM pg_inherits WHERE inhparent = to_regclass($1))", + new object?[] { "public." + table }); + await using var r = await cmd.ExecuteReaderAsync(ct).ConfigureAwait(false); + await r.ReadAsync(ct).ConfigureAwait(false); + return (r.GetInt64(0), r.GetInt64(1)); + } + + private async Task<(long Id, DateTime CreatedUtc)?> ProbeAsync(string table, string key, long atLeast, CancellationToken ct) + { + await using var cmd = Db.Command(_conn, $"SELECT {key}, created_at FROM {table} WHERE {key} >= $1 ORDER BY {key} LIMIT 1", new object?[] { atLeast }); + await using var r = await cmd.ExecuteReaderAsync(ct).ConfigureAwait(false); + if (!await r.ReadAsync(ct).ConfigureAwait(false)) return null; + return (r.GetInt64(0), DateTime.SpecifyKind(r.GetDateTime(1), DateTimeKind.Utc)); + } + + private async Task<(long? Min, long? Max)> MinMaxAsync(string sql, CancellationToken ct) + { + await using var cmd = new NpgsqlCommand(sql, _conn); + await using var r = await cmd.ExecuteReaderAsync(ct).ConfigureAwait(false); + await r.ReadAsync(ct).ConfigureAwait(false); + return (r.IsDBNull(0) ? null : r.GetInt64(0), r.IsDBNull(1) ? null : r.GetInt64(1)); + } + + private async Task> ListAsync(string sql, CancellationToken ct) + { + var list = new List(); + await using var cmd = new NpgsqlCommand(sql, _conn); + await using var r = await cmd.ExecuteReaderAsync(ct).ConfigureAwait(false); + while (await r.ReadAsync(ct).ConfigureAwait(false)) list.Add(r.GetString(0)); + return list; + } + + private async Task ScalarAsync(string sql, CancellationToken ct) + { + await using var cmd = new NpgsqlCommand(sql, _conn); + var v = await cmd.ExecuteScalarAsync(ct).ConfigureAwait(false); + if (v is null or DBNull) return default!; + if (v is DateTime d) v = DateTime.SpecifyKind(d, DateTimeKind.Utc); + var target = Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T); + return (T)(target.IsInstanceOfType(v) ? v : Convert.ChangeType(v, target, CultureInfo.InvariantCulture)); + } + + /// Un istante come letterale SQL timestamptz in UTC (i COPY non accettano parametri). + private static string Ts(DateTime utc) => "'" + utc.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture) + "+00'::timestamptz"; + + private static string Mb(long bytes) => (bytes / 1048576.0).ToString(bytes < 10 * 1048576 ? "0.0" : "0", CultureInfo.InvariantCulture) + " MB"; + + private static string Inv(FormattableString s) => s.ToString(CultureInfo.InvariantCulture); + + [GeneratedRegex("[^A-Za-z0-9_-]")] + private static partial Regex SafeName(); +} diff --git a/src/Mimante/Data/Archive/ArchiveReadme.cs b/src/Mimante/Data/Archive/ArchiveReadme.cs new file mode 100644 index 0000000..7c43adc --- /dev/null +++ b/src/Mimante/Data/Archive/ArchiveReadme.cs @@ -0,0 +1,89 @@ +using System.Text; + +namespace Mimante.Data.Archive; + +public sealed partial class ArchiveDownloader +{ + /// + /// LEGGIMI.md della cartella: disposizione dei file, convenzioni dei CSV, ogni tabella con le sue colonne e + /// i tipi letti dal catalogo, i riassunti e i dossier. Si riscrive a ogni comando, così segue lo schema. + /// + private async Task WriteReadmeAsync(CancellationToken ct) + { + var s = new StringBuilder(); + s.AppendLine("# Dati di Mimante"); + s.AppendLine(); + s.AppendLine(Inv($"Scaricati dall'archivio PostgreSQL del bot con `tools/Mimante.Dati` (Mimante {_manifest.Program}, schema {_manifest.Schema}, variabili del modello versione {_manifest.FeaturesVersion}). Aggiornato il {DateTime.UtcNow:yyyy-MM-dd HH:mm} UTC.")); + s.AppendLine("Solo letture, su una connessione in sola lettura. Il dettaglio di ogni file (righe, byte, impronta SHA-256, filtro usato) è in `manifesto.json`."); + s.AppendLine(); + s.AppendLine("## Disposizione"); + s.AppendLine(); + s.AppendLine("| Percorso | Contenuto |"); + s.AppendLine("|---|---|"); + s.AppendLine("| `riassunti/*.csv` | File piccoli, da leggere per primi: già aggregati da PostgreSQL. |"); + s.AppendLine("| `dossier/mie/.jsonl` | Tutto di un'asta su cui il bot ha puntato davvero, una riga JSON per fatto. |"); + s.AppendLine("| `dossier/osservate/.jsonl` | Lo stesso per un campione stabile di aste seguite dall'inizio alla fine, senza mie puntate. |"); + s.AppendLine("| `tabelle///.csv.gz` | Le tabelle grandi, un file per giorno locale (Europe/Rome). |"); + s.AppendLine("| `tabelle/.csv.gz` | Le tabelle piccole, intere. |"); + s.AppendLine("| `manifesto.json` | Che cosa c'è, da dove viene, con quali filtri, righe e impronte. |"); + s.AppendLine("| `.sale` | Il sale degli pseudonimi: tenerlo fa restare gli pseudonimi uguali fra uno scaricamento e l'altro. Non va condiviso. |"); + s.AppendLine(); + s.AppendLine("## Convenzioni"); + s.AppendLine(); + s.AppendLine("- CSV con intestazione, separatore virgola, testo fra virgolette quando serve, UTF-8; i `.csv.gz` sono gzip di quel testo."); + s.AppendLine("- NULL è un campo vuoto senza virgolette; un testo vuoto è `\"\"`."); + s.AppendLine("- Istanti in UTC, formato ISO (`2026-10-01 18:42:07.123+00`). I giorni dei file e dei riassunti sono giorni locali di Roma."); + s.AppendLine("- `jsonb` come testo JSON; booleani `t` e `f`."); + s.AppendLine("- Un file del giorno è **definitivo** quando il giorno è più vecchio di due giorni: prima, gli esiti delle decisioni e delle previsioni possono ancora arrivare (si scrivono alla chiusura dell'asta) e lo scaricamento successivo lo rifà."); + s.AppendLine("- `bids` e `resets` sono divisi per intervallo di id (l'id cresce con `created_at`): il file di un giorno ha le righe con id fra il primo del giorno e il primo del giorno dopo."); + s.AppendLine("- `bot_decisions` e `auction_forecasts` sono divisi per `ts`."); + s.AppendLine("- `type = 'sim'` nelle aste indica il simulatore: le analisi sul sito vero filtrano `type = 'normal'`."); + s.AppendLine(); + s.AppendLine("## Nomi"); + s.AppendLine(); + if (_manifest.Pseudonyms) + { + s.AppendLine("Gli altri utenti di Bidoo sono pseudonimi `u_` più 12 cifre esadecimali, uguali in tutte le tabelle, i riassunti e i dossier (stesso nome, stesso pseudonimo). I miei utenti sono `io`."); + s.AppendLine("Riscritti: `bids.username`, `resets.bidder`, `auctions.winner_user`, `auctions.me`, le chiavi di `auctions.bids_by_user`, `my_bids.answered_by`, `bidders.username`, `bot_decisions.state.lastBidder` e i nomi nei testi «vinta da …», «coperta da …» (`auctions.loss_reason`, `bot_decisions.reason_detail`)."); + } + else s.AppendLine("Nomi veri (`--nomi-veri`): questa cartella non va condivisa."); + s.AppendLine("Tolti sempre: il token e la chat di Telegram da `settings`, l'elenco delle aste in corso (`documents` con chiave `monitor/*`)."); + s.AppendLine(); + + s.AppendLine("## Riassunti"); + s.AppendLine(); + foreach (var r in Summaries()) s.AppendLine($"- `riassunti/{r.Name}.csv`: {r.Description}"); + s.AppendLine(); + s.AppendLine("## Dossier"); + s.AppendLine(); + s.AppendLine("Ogni riga è un oggetto JSON con il campo `tipo`: `asta` (la riga di `auctions`), `previsione`, `decisione`, `mia_puntata`, `puntata`, `reset`, nell'ordine e ciascuno in ordine di tempo. Le colonne sono quelle delle tabelle qui sotto."); + s.AppendLine(); + + s.AppendLine("## Tabelle"); + foreach (var t in ArchiveTable.All) + { + var columns = await ColumnsAsync(t.Name, ct).ConfigureAwait(false); + if (columns.Count == 0) continue; + s.AppendLine(); + s.AppendLine($"### {t.Name}"); + s.AppendLine(); + var how = t.Split switch + { + ArchiveSplit.IdDay => $"un file per giorno, per intervallo di `{t.Key}`", + ArchiveSplit.TsDay => $"un file per giorno, per `{t.Key}`", + _ => "un file solo, riscaricato ogni volta" + }; + s.AppendLine($"{t.Description} Divisione: {how}; ordine: `{t.Order}`."); + if (_manifest.Tables.TryGetValue(t.Name, out var entry) && entry.Files.Count > 0) + s.AppendLine(Inv($"Scaricati {entry.Files.Count:N0} file, {entry.Files.Values.Sum(f => f.Rows):N0} righe.")); + s.AppendLine(); + s.AppendLine("| Colonna | Tipo |"); + s.AppendLine("|---|---|"); + foreach (var (name, type) in columns) s.AppendLine($"| `{name}` | {type} |"); + } + s.AppendLine(); + s.AppendLine("Il significato di ogni tabella e colonna è in `docs/architettura.md` del repository Mimante."); + await File.WriteAllTextAsync(Path.Combine(_o.Folder, "LEGGIMI.md"), s.ToString().Replace("\r\n", "\n", StringComparison.Ordinal), new UTF8Encoding(false), ct) + .ConfigureAwait(false); + } +} diff --git a/src/Mimante/Data/Archive/ArchiveTables.cs b/src/Mimante/Data/Archive/ArchiveTables.cs new file mode 100644 index 0000000..50e6534 --- /dev/null +++ b/src/Mimante/Data/Archive/ArchiveTables.cs @@ -0,0 +1,88 @@ +namespace Mimante.Data.Archive; + +/// Come si divide una tabella nei file dello scaricamento. +public enum ArchiveSplit +{ + /// Un file solo, riscaricato ogni volta (tabelle piccole o che cambiano). + Whole, + + /// Un file per giorno locale, per intervallo di id (l'id cresce con created_at; nessun indice sul tempo). + IdDay, + + /// Un file per giorno locale, per intervallo sulla colonna del tempo (che ha il suo indice). + TsDay +} + +/// +/// Una tabella dello scaricamento: come si divide, l'ordine delle righe, un filtro e le colonne riscritte +/// (pseudonimi, segreti tolti). Le colonne si leggono dal catalogo di PostgreSQL a ogni scaricamento: una colonna +/// nuova arriva da sola. +/// +public sealed record ArchiveTable( + string Name, ArchiveSplit Split, string? Key, string Order, string Description, + string? Where = null, + Func>? Expressions = null, + IReadOnlyList? TextWithNames = null, + bool PartitionedByCreatedAt = false) +{ + /// + /// Le tabelle che si scaricano. Una tabella che non è qui non esce mai (potrebbe contenere segreti): lo + /// scaricamento la segnala e la salta. + /// + public static readonly IReadOnlyList All = new ArchiveTable[] + { + new("bids", ArchiveSplit.IdDay, "bid_id", "bid_id", + "Ogni puntata vista dal bot: chi (pseudonimo), prezzo dopo la puntata, tipo, orologio del server e del bot.", + Expressions: p => new Dictionary { ["username"] = p.Sql("username") }, + PartitionedByCreatedAt: true), + new("resets", ArchiveSplit.IdDay, "reset_id", "reset_id", + "Ogni ripartenza del timer vista dal bot: chi l'ha fatta ripartire, a che prezzo, dopo quanto e con quale timer minimo.", + Expressions: p => new Dictionary { ["bidder"] = p.Sql("bidder") }, + PartitionedByCreatedAt: true), + new("bot_decisions", ArchiveSplit.TsDay, "ts", "ts, decision_id", + "Ogni decisione del modello: contesto, probabilità, valore atteso, verdetto, motivo ed esito.", + Expressions: p => new Dictionary { ["state"] = p.SqlJsonField("state", "lastBidder") }, + TextWithNames: new[] { "reason_detail" }, + PartitionedByCreatedAt: true), + new("auction_forecasts", ArchiveSplit.TsDay, "ts", "ts, id", + "Le previsioni di chiusura di ogni asta (la prima e le successive) e, a asta chiusa, la realtà."), + new("auctions", ArchiveSplit.Whole, null, "auction_id", + "Una riga per asta seguita: prodotto, esito, prezzo finale, vincitore, copertura dell'osservazione, serie dei prezzi, riepiloghi.", + Expressions: p => new Dictionary + { + ["winner_user"] = p.Sql("winner_user"), ["me"] = p.Sql("me"), ["bids_by_user"] = p.SqlJsonKeys("bids_by_user") + }, + TextWithNames: new[] { "loss_reason" }), + new("my_bids", ArchiveSplit.Whole, null, "id", + "Le mie puntate vere: anticipo, tempi, esito, chi ha risposto.", + Expressions: p => new Dictionary { ["answered_by"] = p.Sql("answered_by") }), + new("bidders", ArchiveSplit.Whole, null, "n_bids DESC, username", + "Gli altri puntatori (pseudonimi): quante aste, puntate, automatiche e a mano, vittorie.", + Expressions: p => new Dictionary { ["username"] = p.Sql("username") }), + new("items", ArchiveSplit.Whole, null, "item_id", "Gli oggetti di Bidoo visti (prezzo del sito, spedizione)."), + new("products", ArchiveSplit.Whole, null, "product_key", "Le schede dei prodotti con i paletti scritti."), + new("watched_products", ArchiveSplit.Whole, null, "product_key", "I prodotti seguiti."), + new("product_stats", ArchiveSplit.Whole, null, "product_key", "Le statistiche calcolate per prodotto."), + new("risk_ledger", ArchiveSplit.Whole, null, "id", "Il registro del rischio: spese e vincite che contano per i tetti."), + new("schema_migrations", ArchiveSplit.Whole, null, "version", "Le migrazioni applicate all'archivio."), + new("settings", ArchiveSplit.Whole, null, "id", "Le impostazioni del bot, senza token e chat di Telegram.", + Expressions: _ => new Dictionary { ["value"] = "value - 'TelegramBotToken' - 'TelegramChatId'" }), + new("documents", ArchiveSplit.Whole, null, "key", + "Lo stato del modello (pesi, bandit, profili, latenza); senza l'elenco delle aste in corso (monitor/*), che contiene nomi.", + Where: "key NOT LIKE 'monitor/%'") + }; + + public static ArchiveTable? Find(string name) => All.FirstOrDefault(t => t.Name == name); + + /// L'elenco delle colonne per la SELECT, con le riscritture al posto delle colonne originali. + public string SelectList(IReadOnlyList columns, Pseudonyms names) + { + var map = Expressions?.Invoke(names) ?? new Dictionary(); + return string.Join(", ", columns.Select(c => map.TryGetValue(c, out var e) ? $"{e} AS {c}" : c)); + } + + /// Il percorso relativo (con «/») del file di un giorno o della tabella intera. + public string RelativePath(DateOnly? day) => day is { } d + ? string.Create(System.Globalization.CultureInfo.InvariantCulture, $"tabelle/{Name}/{d:yyyy-MM}/{d:yyyy-MM-dd}.csv.gz") + : $"tabelle/{Name}.csv.gz"; +} diff --git a/src/Mimante/Data/Archive/DayRanges.cs b/src/Mimante/Data/Archive/DayRanges.cs new file mode 100644 index 0000000..63c545c --- /dev/null +++ b/src/Mimante/Data/Archive/DayRanges.cs @@ -0,0 +1,37 @@ +namespace Mimante.Data.Archive; + +/// +/// I confini dei giorni nelle tabelle grandi senza indice sul tempo (bids, resets): l'id cresce con +/// created_at (verificato sull'archivio vero: nessuna inversione su 2 milioni di righe), quindi il primo id +/// di un giorno si trova per bisezione sulla chiave primaria, con poche letture da un indice invece di scorrere la +/// partizione del mese. Un file del giorno è l'intervallo di id [primo del giorno, primo del giorno dopo). +/// +public static class DayRanges +{ + /// La prima riga con id ≥ del dato: (id, created_at in UTC), null se non ce n'è. + public delegate Task<(long Id, DateTime CreatedUtc)?> Probe(long atLeast, CancellationToken ct); + + /// + /// Il primo id con created_at ≥ fra e + /// (escluso); se non c'è. I buchi nella numerazione si saltano. + /// + public static async Task FirstIdAtOrAfterAsync(Probe probe, long minId, long endId, DateTime instantUtc, CancellationToken ct) + { + // P(m) = «la prima riga con id ≥ m è del giorno o dopo (o non c'è)»: falsa e poi vera al crescere di m. + // Si cerca il primo m con P vera; se P(mid) è falsa lo è fino all'id trovato, e si riparte dal successivo. + long low = minId, high = endId; + while (low < high) + { + var mid = low + (high - low) / 2; + var row = await probe(mid, ct).ConfigureAwait(false); + if (row is not { } r || r.Id >= endId || r.CreatedUtc >= instantUtc) high = mid; + else low = r.Id + 1; + } + var first = await probe(low, ct).ConfigureAwait(false); + return first is { } f && f.Id < endId ? f.Id : endId; + } + + /// Inizio (UTC) del giorno locale nel fuso . + public static DateTime StartUtc(DateOnly day, TimeZoneInfo zone) => + TimeZoneInfo.ConvertTimeToUtc(day.ToDateTime(TimeOnly.MinValue, DateTimeKind.Unspecified), zone); +} diff --git a/src/Mimante/Data/Archive/Manifest.cs b/src/Mimante/Data/Archive/Manifest.cs new file mode 100644 index 0000000..b6b729d --- /dev/null +++ b/src/Mimante/Data/Archive/Manifest.cs @@ -0,0 +1,100 @@ +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Mimante.Data.Archive; + +/// +/// manifesto.json nella cartella dei dati: che cosa è stato scaricato, da quale archivio, con quali filtri, +/// e per ogni file righe, byte, impronta SHA-256 e intervallo. Riprendere uno scaricamento salta i file definitivi +/// già presenti e integri; verifica rilegge le impronte (e, a richiesta, i conteggi nel database). +/// +public sealed class Manifest +{ + public const string FileName = "manifesto.json"; + + /// Versione del formato della cartella: cambia solo se cambia la disposizione dei file. + public const int CurrentFormat = 1; + + public int Format { get; set; } = CurrentFormat; + public string Program { get; set; } = ""; + public int Schema { get; set; } + public int FeaturesVersion { get; set; } + public string Database { get; set; } = ""; + public bool Pseudonyms { get; set; } = true; + public string TimeZone { get; set; } = "Europe/Rome"; + public DateTime CreatedUtc { get; set; } + public DateTime UpdatedUtc { get; set; } + public string? From { get; set; } + public string? To { get; set; } + + /// Per tabella: come è divisa e i suoi file (percorso relativo con «/»). + public SortedDictionary Tables { get; set; } = new(StringComparer.Ordinal); + + /// I riassunti e i dossier, per percorso relativo. + public SortedDictionary Other { get; set; } = new(StringComparer.Ordinal); + + public sealed class TableEntry + { + public string Split { get; set; } = ""; + public List Columns { get; set; } = new(); + public SortedDictionary Files { get; set; } = new(StringComparer.Ordinal); + } + + public sealed class FileEntry + { + public long Rows { get; set; } + public long Bytes { get; set; } + public string Sha256 { get; set; } = ""; + public DateTime DownloadedUtc { get; set; } + + /// Giorno locale del file (aaaa-mm-gg), per le tabelle divise per giorno. + public string? Day { get; set; } + + /// La condizione WHERE con cui il file è stato scritto: verifica --contro-db riconta con la stessa. + public string? Filter { get; set; } + + /// Intervallo di id [IdFrom, IdTo), per le tabelle divise per id. + public long? IdFrom { get; set; } + public long? IdTo { get; set; } + + /// + /// Definitivo: il giorno è abbastanza lontano perché le righe non cambino più (gli esiti delle decisioni e + /// delle previsioni si scrivono alla chiusura dell'asta). Un file non definitivo si riscarica la volta dopo. + /// + public bool Final { get; set; } + } + + private static readonly JsonSerializerOptions Json = new() + { + WriteIndented = true, + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull + }; + + public static Manifest? Load(string folder) + { + var path = Path.Combine(folder, FileName); + if (!File.Exists(path)) return null; + return JsonSerializer.Deserialize(File.ReadAllText(path), Json); + } + + /// Scrive su .tmp e rinomina: un'interruzione non lascia un manifesto a metà. + public void Save(string folder) + { + UpdatedUtc = DateTime.UtcNow; + var path = Path.Combine(folder, FileName); + File.WriteAllText(path + ".tmp", JsonSerializer.Serialize(this, Json)); + File.Move(path + ".tmp", path, overwrite: true); + } + + public TableEntry Table(string name, string split) + { + if (!Tables.TryGetValue(name, out var t)) Tables[name] = t = new TableEntry(); + t.Split = split; + return t; + } + + /// Un file da non riscaricare: definitivo, presente e della stessa dimensione registrata. + public static bool IsDone(FileEntry? entry, string fullPath) => + entry is { Final: true } && File.Exists(fullPath) && new FileInfo(fullPath).Length == entry.Bytes; +} diff --git a/src/Mimante/Data/Archive/Pseudonyms.cs b/src/Mimante/Data/Archive/Pseudonyms.cs new file mode 100644 index 0000000..dc89251 --- /dev/null +++ b/src/Mimante/Data/Archive/Pseudonyms.cs @@ -0,0 +1,73 @@ +using System.Security.Cryptography; +using System.Text; +using System.Text.RegularExpressions; + +namespace Mimante.Data.Archive; + +/// +/// Gli pseudonimi degli altri utenti di Bidoo nei dati scaricati: u_ più 12 cifre esadecimali dello +/// SHA-256 di sale + nome. Stabili (lo stesso nome dà sempre lo stesso pseudonimo, anche fra uno +/// scaricamento e l'altro, finché il sale resta quello) e uguali che li calcoli PostgreSQL +/// (, dentro i COPY) o il programma (, nei testi). I miei utenti +/// diventano io. Spenti (--nomi-veri) restituiscono i nomi come sono. +/// +public sealed partial class Pseudonyms +{ + public const string Me = "io"; + + private readonly string _salt; + private readonly HashSet _mine; + + public bool Enabled { get; } + + public Pseudonyms(string salt, IEnumerable mine, bool enabled = true) + { + if (!SaltShape().IsMatch(salt)) throw new ArgumentException("Il sale deve essere esadecimale (da 16 a 128 cifre).", nameof(salt)); + _salt = salt; + _mine = new HashSet(mine.Where(m => !string.IsNullOrEmpty(m)), StringComparer.Ordinal); + Enabled = enabled; + } + + /// Un sale nuovo: 32 cifre esadecimali casuali. + public static string NewSalt() => Convert.ToHexStringLower(RandomNumberGenerator.GetBytes(16)); + + public string? Of(string? name) + { + if (!Enabled || string.IsNullOrEmpty(name)) return name; + if (_mine.Contains(name)) return Me; + return "u_" + Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(_salt + name)))[..12]; + } + + /// L'espressione SQL che dà lo pseudonimo di (una colonna di testo). + public string Sql(string expr) + { + if (!Enabled) return expr; + var mine = _mine.Count == 0 ? "ARRAY[]::text[]" : "ARRAY[" + string.Join(", ", _mine.Order(StringComparer.Ordinal).Select(Literal)) + "]::text[]"; + return $"(CASE WHEN {expr} IS NULL OR {expr} = '' THEN {expr} WHEN {expr} = ANY({mine}) THEN '{Me}' " + + $"ELSE 'u_' || left(encode(sha256(convert_to('{_salt}' || {expr}, 'UTF8')), 'hex'), 12) END)"; + } + + /// Un oggetto jsonb con i nomi come chiavi (per esempio auctions.bids_by_user) con gli pseudonimi al loro posto. + public string SqlJsonKeys(string expr) => Enabled + ? $"(SELECT jsonb_object_agg({Sql("e.k")}, e.v) FROM jsonb_each({expr}) AS e(k, v))" + : expr; + + /// Un campo di testo di un oggetto jsonb (per esempio state.lastBidder) sostituito dal suo pseudonimo. + public string SqlJsonField(string expr, string key) => Enabled + ? $"(CASE WHEN jsonb_typeof({expr}->'{key}') = 'string' THEN jsonb_set({expr}, '{{{key}}}', to_jsonb({Sql($"({expr}->>'{key}')")})) ELSE {expr} END)" + : expr; + + /// + /// I nomi dentro i testi del bot («vinta da X», «coperta da X (a mano)») sostituiti dagli pseudonimi. Sono le + /// sole forme con un nome che il bot scrive (motivi di perdita, testi delle decisioni). + /// + public string? Text(string? text) => !Enabled || string.IsNullOrEmpty(text) ? text : NameInText().Replace(text, m => Of(m.Value)!); + + private static string Literal(string s) => "'" + s.Replace("'", "''") + "'"; + + [GeneratedRegex(@"(?<=\b(?:vinta|coperta|superata|ripresa) da )[^\s;,()]+")] + private static partial Regex NameInText(); + + [GeneratedRegex("^[0-9a-f]{16,128}$")] + private static partial Regex SaltShape(); +} diff --git a/src/Mimante/Data/BulkCopy.cs b/src/Mimante/Data/BulkCopy.cs new file mode 100644 index 0000000..943e8fa --- /dev/null +++ b/src/Mimante/Data/BulkCopy.cs @@ -0,0 +1,305 @@ +using System.IO.Compression; +using System.Security.Cryptography; +using System.Text; +using Npgsql; + +namespace Mimante.Data; + +/// +/// Copia in blocco da PostgreSQL a file: COPY (…) TO STDOUT (FORMAT csv, HEADER) scritto su +/// nome.tmp e rinominato alla fine, compresso in gzip se il nome finisce in .gz. Lo usano il +/// backup notturno e lo strumento dei dati (tools/Mimante.Dati). +/// +/// Conta le righe esatte (un a capo dentro un campo fra virgolette non è una riga nuova), calcola +/// l'impronta SHA-256 del file scritto, può limitare la velocità e, se serve, riscrivere singoli campi +/// (: per esempio i nomi dentro un testo) leggendo il CSV record per record. +/// +public static class BulkCopy +{ + /// Righe di dati (senza l'intestazione), byte del file, impronta SHA-256 in esadecimale minuscolo. + public sealed record Outcome(long Rows, long Bytes, string Sha256); + + /// + /// Data l'intestazione, l'azione che riscrive i campi di un record (null = nessuna riscrittura). + /// Un campo null è NULL; una stringa vuota è il testo vuoto. + /// + public delegate Action? Transform(IReadOnlyList header); + + public static async Task ToFileAsync(NpgsqlConnection conn, string copySql, string file, Transform? transform = null, + Throttle? throttle = null, CancellationToken ct = default) + { + var dir = Path.GetDirectoryName(Path.GetFullPath(file)); + if (dir != null) Directory.CreateDirectory(dir); + var tmp = file + ".tmp"; + try + { + long rows; + string sha; + await using (var fs = new FileStream(tmp, FileMode.Create, FileAccess.Write, FileShare.None, 1 << 16, useAsync: true)) + { + using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + await using (var hashing = new HashingStream(fs, hash)) + await using (var body = file.EndsWith(".gz", StringComparison.OrdinalIgnoreCase) + ? new GZipStream(hashing, CompressionLevel.Optimal, leaveOpen: true) + : (Stream)new NonClosing(hashing)) + await using (var w = new StreamWriter(body, new UTF8Encoding(false), 1 << 16)) + { + using var reader = await conn.BeginTextExportAsync(copySql, ct).ConfigureAwait(false); + rows = transform == null + ? await PassThroughAsync(reader, w, throttle, ct).ConfigureAwait(false) + : await RewriteAsync(reader, w, transform, throttle, ct).ConfigureAwait(false); + } + sha = Convert.ToHexStringLower(hash.GetHashAndReset()); + } + File.Move(tmp, file, overwrite: true); + return new Outcome(rows, new FileInfo(file).Length, sha); + } + catch + { + try { File.Delete(tmp); } catch (IOException) { } catch (UnauthorizedAccessException) { } + throw; + } + } + + /// Copia il testo così com'è contando i record; restituisce le righe di dati. + private static async Task PassThroughAsync(TextReader reader, TextWriter w, Throttle? throttle, CancellationToken ct) + { + var counter = new RecordCounter(); + var buffer = new char[1 << 16]; + int read; + while ((read = await reader.ReadAsync(buffer, ct).ConfigureAwait(false)) > 0) + { + counter.Feed(buffer.AsSpan(0, read)); + await w.WriteAsync(buffer.AsMemory(0, read), ct).ConfigureAwait(false); + if (throttle != null) await throttle.WaitAsync(read, ct).ConfigureAwait(false); + } + return Math.Max(0, counter.Total - 1); + } + + private static async Task RewriteAsync(TextReader reader, TextWriter w, Transform transform, Throttle? throttle, CancellationToken ct) + { + var records = new CsvRecords(reader); + var header = await records.NextAsync(ct).ConfigureAwait(false); + if (header == null) return 0; + var names = header.Select(h => h ?? "").ToArray(); + var apply = transform(names); + var line = new StringBuilder(1024); + WriteRecord(line, header); + await w.WriteAsync(line, ct).ConfigureAwait(false); + long rows = 0; + while (await records.NextAsync(ct).ConfigureAwait(false) is { } record) + { + apply?.Invoke(record); + line.Clear(); + WriteRecord(line, record); + await w.WriteAsync(line, ct).ConfigureAwait(false); + rows++; + if (throttle != null) await throttle.WaitAsync(line.Length, ct).ConfigureAwait(false); + } + return rows; + } + + /// Un record nel CSV di COPY: NULL vuoto senza virgolette, il testo vuoto come "". + internal static void WriteRecord(StringBuilder sb, IReadOnlyList fields) + { + for (var i = 0; i < fields.Count; i++) + { + if (i > 0) sb.Append(','); + var f = fields[i]; + if (f == null) continue; + if (f.Length == 0 || f.AsSpan().IndexOfAny(",\"\r\n") >= 0) sb.Append('"').Append(f.Replace("\"", "\"\"")).Append('"'); + else sb.Append(f); + } + sb.Append('\n'); + } + + /// Conta i record di un CSV a pezzi: un a capo fuori dalle virgolette chiude un record. + internal sealed class RecordCounter + { + private bool _quoted; + private bool _pending; + + public long Records { get; private set; } + + public void Feed(ReadOnlySpan chunk) + { + foreach (var c in chunk) + { + if (c == '"') _quoted = !_quoted; + if (c == '\n' && !_quoted) + { + Records++; + _pending = false; + } + else _pending = true; + } + } + + /// I record, contando anche l'ultimo se il testo non finisce con un a capo. + public long Total => Records + (_pending ? 1 : 0); + } + + /// Lettore dei record del CSV di COPY (virgola, virgolette raddoppiate, NULL = campo vuoto senza virgolette). + internal sealed class CsvRecords(TextReader reader) + { + private readonly char[] _buffer = new char[1 << 16]; + private int _pos, _len; + private bool _eof; + + private async ValueTask PeekAsync(CancellationToken ct) + { + if (_pos < _len) return _buffer[_pos]; + if (_eof) return -1; + _len = await reader.ReadAsync(_buffer, ct).ConfigureAwait(false); + _pos = 0; + if (_len == 0) { _eof = true; return -1; } + return _buffer[_pos]; + } + + public async ValueTask NextAsync(CancellationToken ct) + { + if (await PeekAsync(ct).ConfigureAwait(false) < 0) return null; + var fields = new List(); + var field = new StringBuilder(); + bool quoted = false, wasQuoted = false; + while (true) + { + var c = await PeekAsync(ct).ConfigureAwait(false); + if (c < 0) + { + fields.Add(wasQuoted || field.Length > 0 ? field.ToString() : null); + return fields.ToArray(); + } + _pos++; + if (quoted) + { + if (c == '"') + { + if (await PeekAsync(ct).ConfigureAwait(false) == '"') { field.Append('"'); _pos++; } + else quoted = false; + } + else field.Append((char)c); + continue; + } + switch (c) + { + case '"': + quoted = wasQuoted = true; + break; + case ',': + fields.Add(wasQuoted || field.Length > 0 ? field.ToString() : null); + field.Clear(); + wasQuoted = false; + break; + case '\n': + fields.Add(wasQuoted || field.Length > 0 ? field.ToString() : null); + return fields.ToArray(); + case '\r': + break; + default: + field.Append((char)c); + break; + } + } + } + } + + /// Limite di velocità in byte al secondo sul testo letto (0 o meno = nessun limite). + public sealed class Throttle(double bytesPerSecond) + { + private readonly long _start = Environment.TickCount64; + private long _bytes; + + public async ValueTask WaitAsync(long bytes, CancellationToken ct) + { + if (bytesPerSecond <= 0) return; + _bytes += bytes; + var due = _bytes / bytesPerSecond * 1000; + var ahead = due - (Environment.TickCount64 - _start); + if (ahead > 20) await Task.Delay(TimeSpan.FromMilliseconds(ahead), ct).ConfigureAwait(false); + } + } + + /// + /// Lo spazio libero del volume che contiene : su Linux il punto di montaggio più lungo che lo + /// contiene (per /config/esportazioni è il volume di /config, non la radice del contenitore). Null se non si sa. + /// + public static long? FreeBytes(string dir) + { + try + { + var full = Path.GetFullPath(dir); + var comparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; + var drive = DriveInfo.GetDrives() + .Where(d => full.StartsWith(d.RootDirectory.FullName, comparison)) + .OrderByDescending(d => d.RootDirectory.FullName.Length) + .FirstOrDefault(d => d.IsReady); + return drive?.AvailableFreeSpace; + } + catch (Exception e) when (e is IOException or UnauthorizedAccessException) + { + return null; + } + } + + /// L'impronta SHA-256 di un file già scritto, in esadecimale minuscolo. + public static async Task Sha256Async(string file, CancellationToken ct = default) + { + await using var fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read, 1 << 16, useAsync: true); + return Convert.ToHexStringLower(await SHA256.HashDataAsync(fs, ct).ConfigureAwait(false)); + } + + /// Passa i byte al file e all'impronta. + private sealed class HashingStream(Stream inner, IncrementalHash hash) : Stream + { + public override bool CanRead => false; + public override bool CanSeek => false; + public override bool CanWrite => true; + public override long Length => inner.Length; + public override long Position { get => inner.Position; set => throw new NotSupportedException(); } + public override void Flush() => inner.Flush(); + public override Task FlushAsync(CancellationToken ct) => inner.FlushAsync(ct); + public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + public override void SetLength(long value) => throw new NotSupportedException(); + + public override void Write(byte[] buffer, int offset, int count) + { + hash.AppendData(buffer, offset, count); + inner.Write(buffer, offset, count); + } + + public override async ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken ct = default) + { + hash.AppendData(buffer.Span); + await inner.WriteAsync(buffer, ct).ConfigureAwait(false); + } + + public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken ct) => + WriteAsync(buffer.AsMemory(offset, count), ct).AsTask(); + + // Chiudere chi scrive non chiude il file: lo chiude il FileStream esterno, dopo l'impronta. + protected override void Dispose(bool disposing) => Flush(); + public override ValueTask DisposeAsync() => new(FlushAsync()); + } + + /// Un flusso che non chiude quello sotto (per il file senza gzip, come leaveOpen). + private sealed class NonClosing(Stream inner) : Stream + { + public override bool CanRead => false; + public override bool CanSeek => false; + public override bool CanWrite => true; + public override long Length => inner.Length; + public override long Position { get => inner.Position; set => throw new NotSupportedException(); } + public override void Flush() => inner.Flush(); + public override Task FlushAsync(CancellationToken ct) => inner.FlushAsync(ct); + public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + public override void SetLength(long value) => throw new NotSupportedException(); + public override void Write(byte[] buffer, int offset, int count) => inner.Write(buffer, offset, count); + public override ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken ct = default) => inner.WriteAsync(buffer, ct); + public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken ct) => inner.WriteAsync(buffer, offset, count, ct); + protected override void Dispose(bool disposing) => Flush(); + public override ValueTask DisposeAsync() => new(FlushAsync()); + } +} diff --git a/src/Mimante/Data/CsvExport.cs b/src/Mimante/Data/CsvExport.cs index 71bab04..8b0f6b5 100644 --- a/src/Mimante/Data/CsvExport.cs +++ b/src/Mimante/Data/CsvExport.cs @@ -60,7 +60,7 @@ public sealed class CsvExport _paths = paths; _settings = settings; _learning = learning; - _freeBytes = freeBytes ?? FreeBytes; + _freeBytes = freeBytes ?? BulkCopy.FreeBytes; } /// @@ -675,28 +675,6 @@ public sealed class CsvExport throw new IOException($"Spazio libero insufficiente per l'esportazione: {free >> 20} MB, ne servono almeno {settings.ExportMinFreeMb} (Impostazioni ▸ Dati e conservazione)."); } - /// - /// Lo spazio libero del volume che contiene : su Linux il punto di montaggio più lungo che lo - /// contiene (per /config/esportazioni è il volume di /config, non la radice del contenitore). Null se non si sa. - /// - internal static long? FreeBytes(string dir) - { - try - { - var full = System.IO.Path.GetFullPath(dir); - var comparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; - var drive = DriveInfo.GetDrives() - .Where(d => full.StartsWith(d.RootDirectory.FullName, comparison)) - .OrderByDescending(d => d.RootDirectory.FullName.Length) - .FirstOrDefault(d => d.IsReady); - return drive?.AvailableFreeSpace; - } - catch (Exception e) when (e is IOException or UnauthorizedAccessException) - { - return null; - } - } - private async Task WriteLegendAsync(string prefix, DateTime from, DateTime to, Request req, long total, long exported, string? note, List columns, CancellationToken ct) { diff --git a/src/Mimante/Data/Maintenance.cs b/src/Mimante/Data/Maintenance.cs index 6e36e98..d877541 100644 --- a/src/Mimante/Data/Maintenance.cs +++ b/src/Mimante/Data/Maintenance.cs @@ -161,20 +161,9 @@ public sealed class Maintenance { 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 copied = await BulkCopy.ToFileAsync(conn, $"COPY {table} TO STDOUT (FORMAT csv, HEADER)", + Path.Combine(folder, table + ".csv.gz"), ct: ct).ConfigureAwait(false); + total += copied.Bytes; } } diff --git a/tests/Mimante.Tests/ArchiveTests.cs b/tests/Mimante.Tests/ArchiveTests.cs new file mode 100644 index 0000000..6b562ef --- /dev/null +++ b/tests/Mimante.Tests/ArchiveTests.cs @@ -0,0 +1,398 @@ +using System.IO.Compression; +using System.Text; +using System.Text.Json.Nodes; +using System.Text.RegularExpressions; +using Mimante.Data; +using Mimante.Data.Archive; +using Npgsql; +using Xunit; + +namespace Mimante.Tests; + +public class PseudonymsTests +{ + private const string Salt = "00112233445566778899aabbccddeeff"; + + [Fact] + public void Lo_stesso_nome_da_sempre_lo_stesso_pseudonimo_e_i_miei_diventano_io() + { + var p = new Pseudonyms(Salt, new[] { "sirbietole23" }); + var anna = p.Of("anna")!; + Assert.Matches("^u_[0-9a-f]{12}$", anna); + Assert.Equal(anna, new Pseudonyms(Salt, Array.Empty()).Of("anna")); + Assert.NotEqual(anna, p.Of("bob")); + Assert.NotEqual(anna, new Pseudonyms("ffeeddccbbaa99887766554433221100", Array.Empty()).Of("anna")); + Assert.Equal(Pseudonyms.Me, p.Of("sirbietole23")); + Assert.Null(p.Of(null)); + Assert.Equal("", p.Of("")); + } + + [Fact] + public void Spenti_restituiscono_i_nomi_veri() + { + var p = new Pseudonyms(Salt, new[] { "io_vero" }, enabled: false); + Assert.Equal("anna", p.Of("anna")); + Assert.Equal("username", p.Sql("username")); + Assert.Equal("vinta da anna", p.Text("vinta da anna")); + } + + [Fact] + public void Nei_testi_cambiano_solo_i_nomi_dopo_vinta_da_e_coperta_da() + { + var p = new Pseudonyms(Salt, new[] { "sirbietole23" }); + Assert.Equal($"vinta da {p.Of("anna")} a 3,21 €", p.Text("vinta da anna a 3,21 €")); + Assert.Equal($"coperta da {p.Of("bob_77")} (a mano); poi vinta da io", p.Text("coperta da bob_77 (a mano); poi vinta da sirbietole23")); + Assert.Equal("coperta dall'autopuntata", p.Text("coperta dall'autopuntata")); + Assert.Equal("P bassa, serve 0,3%", p.Text("P bassa, serve 0,3%")); + Assert.Null(p.Text(null)); + } + + [Fact] + public void Il_sale_deve_essere_esadecimale() + { + Assert.Throws(() => new Pseudonyms("'; DROP TABLE bids; --", Array.Empty())); + Assert.Throws(() => new Pseudonyms("abc", Array.Empty())); + Assert.Matches("^[0-9a-f]{32}$", Pseudonyms.NewSalt()); + } + + [Fact] + public void I_nomi_miei_con_un_apice_restano_letterali_sql_validi() + { + var sql = new Pseudonyms(Salt, new[] { "o'brien" }).Sql("username"); + Assert.Contains("'o''brien'", sql); + } +} + +public class DayRangesTests +{ + /// Un archivio finto: id con buchi, tempi crescenti; conta le letture. + private sealed class FakeTable((long Id, DateTime At)[] rows) + { + public int Probes { get; private set; } + + public Task<(long Id, DateTime CreatedUtc)?> Probe(long atLeast, CancellationToken ct) + { + Probes++; + foreach (var r in rows) + if (r.Id >= atLeast) return Task.FromResult<(long, DateTime)?>((r.Id, r.At)); + return Task.FromResult<(long, DateTime)?>(null); + } + } + + private static readonly DateTime T0 = new(2026, 10, 1, 0, 0, 0, DateTimeKind.Utc); + + [Fact] + public async Task Trova_il_primo_id_di_ogni_giorno_saltando_i_buchi() + { + var rows = new[] + { + (10L, T0.AddHours(1)), (11L, T0.AddHours(20)), (50L, T0.AddDays(1).AddHours(2)), (51L, T0.AddDays(1).AddHours(3)), + (900L, T0.AddDays(3).AddHours(5)), (901L, T0.AddDays(3).AddHours(6)) + }; + var table = new FakeTable(rows); + Assert.Equal(10, await DayRanges.FirstIdAtOrAfterAsync(table.Probe, 10, 902, T0, CancellationToken.None)); + Assert.Equal(50, await DayRanges.FirstIdAtOrAfterAsync(table.Probe, 10, 902, T0.AddDays(1), CancellationToken.None)); + // Un giorno senza righe: il primo id «del giorno o dopo» è quello del giorno dopo, e il file del giorno è vuoto. + Assert.Equal(900, await DayRanges.FirstIdAtOrAfterAsync(table.Probe, 10, 902, T0.AddDays(2), CancellationToken.None)); + Assert.Equal(900, await DayRanges.FirstIdAtOrAfterAsync(table.Probe, 50, 902, T0.AddDays(3), CancellationToken.None)); + Assert.Equal(902, await DayRanges.FirstIdAtOrAfterAsync(table.Probe, 10, 902, T0.AddDays(4), CancellationToken.None)); + } + + [Fact] + public async Task Con_un_milione_di_id_bastano_poche_letture() + { + var rows = Enumerable.Range(0, 1_000_000).Select(i => ((long)i * 3 + 7, T0.AddSeconds(i))).ToArray(); + var table = new FakeTable(rows); + var target = T0.AddSeconds(654_321); + var id = await DayRanges.FirstIdAtOrAfterAsync(table.Probe, 7, rows[^1].Item1 + 1, target, CancellationToken.None); + Assert.Equal(654_321L * 3 + 7, id); + Assert.InRange(table.Probes, 1, 45); + } + + [Fact] + public void L_inizio_del_giorno_locale_segue_l_ora_legale() + { + var rome = TimeZoneInfo.FindSystemTimeZoneById("Europe/Rome"); + Assert.Equal(new DateTime(2026, 7, 9, 22, 0, 0, DateTimeKind.Utc), DayRanges.StartUtc(new DateOnly(2026, 7, 10), rome)); + Assert.Equal(new DateTime(2026, 11, 9, 23, 0, 0, DateTimeKind.Utc), DayRanges.StartUtc(new DateOnly(2026, 11, 10), rome)); + } + + [Fact] + public void I_giorni_vanno_dal_primo_a_ieri_dentro_da_e_a_e_sono_definitivi_dopo_il_margine() + { + var today = new DateOnly(2026, 11, 24); + var days = ArchiveDownloader.Days(new DateOnly(2026, 11, 20), today, null, null).ToList(); + Assert.Equal(new DateOnly(2026, 11, 20), days[0]); + Assert.Equal(new DateOnly(2026, 11, 23), days[^1]); + Assert.Equal(new[] { new DateOnly(2026, 11, 21), new DateOnly(2026, 11, 22) }, + ArchiveDownloader.Days(new DateOnly(2026, 11, 20), today, new DateOnly(2026, 11, 21), new DateOnly(2026, 11, 22))); + Assert.Empty(ArchiveDownloader.Days(new DateOnly(2026, 11, 24), today, null, null)); + Assert.True(ArchiveDownloader.IsFinal(new DateOnly(2026, 11, 21), today, 2)); + Assert.False(ArchiveDownloader.IsFinal(new DateOnly(2026, 11, 22), today, 2)); + } +} + +public class BulkCopyTests +{ + [Fact] + public async Task Un_record_scritto_si_rilegge_uguale_con_null_vuoti_virgolette_e_a_capo() + { + var records = new[] + { + new string?[] { "id", "testo", "nulla" }, + new string?[] { "1", "semplice", null }, + new string?[] { "2", "", "x" }, + new string?[] { "3", "con, virgola e \"virgolette\"", null }, + new string?[] { "4", "su\ndue righe\r\ne tre", "" } + }; + var sb = new StringBuilder(); + foreach (var r in records) BulkCopy.WriteRecord(sb, r); + var reader = new BulkCopy.CsvRecords(new StringReader(sb.ToString())); + foreach (var expected in records) + Assert.Equal(expected, await reader.NextAsync(CancellationToken.None)); + Assert.Null(await reader.NextAsync(CancellationToken.None)); + } + + [Fact] + public void Il_contatore_non_conta_gli_a_capo_fra_virgolette_anche_a_pezzi() + { + const string text = "a,b\n1,\"x\ny\"\n2,\"z\"\"\n\"\n3,w"; + foreach (var size in new[] { 1, 2, 3, 7, 100 }) + { + var c = new BulkCopy.RecordCounter(); + for (var i = 0; i < text.Length; i += size) c.Feed(text.AsSpan(i, Math.Min(size, text.Length - i))); + Assert.Equal(4, c.Total); + } + } +} + +public class ManifestTests +{ + [Fact] + public void Si_salva_si_rilegge_e_dice_quali_file_non_vanno_riscaricati() + { + using var dir = new TempDir(); + var m = new Manifest { Program = "2.0.0", Schema = 3 }; + var t = m.Table("bids", "IdDay"); + var file = Path.Combine(dir.Path, "a.csv.gz"); + File.WriteAllBytes(file, new byte[] { 1, 2, 3 }); + t.Files["tabelle/bids/2026-10/2026-10-01.csv.gz"] = new Manifest.FileEntry { Rows = 5, Bytes = 3, Sha256 = "ab", Final = true, IdFrom = 1, IdTo = 6, Day = "2026-10-01" }; + m.Save(dir.Path); + + var back = Manifest.Load(dir.Path)!; + var e = back.Tables["bids"].Files["tabelle/bids/2026-10/2026-10-01.csv.gz"]; + Assert.Equal(6, e.IdTo); + Assert.True(Manifest.IsDone(e, file)); + Assert.False(Manifest.IsDone(new Manifest.FileEntry { Bytes = 3, Final = false }, file)); + Assert.False(Manifest.IsDone(new Manifest.FileEntry { Bytes = 4, Final = true }, file)); + Assert.False(Manifest.IsDone(e, Path.Combine(dir.Path, "manca.csv.gz"))); + Assert.False(File.Exists(Path.Combine(dir.Path, Manifest.FileName + ".tmp"))); + } +} + +public class ArchiveTableTests +{ + /// Le tabelle che lo scaricamento non porta mai fuori, per scelta (oggi nessuna). + private static readonly HashSet NotExported = new(StringComparer.Ordinal); + + [Fact] + public void Ogni_tabella_delle_migrazioni_e_nel_catalogo_o_esclusa_apposta() + { + var asm = typeof(Migrations).Assembly; + var tables = new HashSet(StringComparer.Ordinal) { "schema_migrations" }; + foreach (var res in asm.GetManifestResourceNames().Where(r => r.EndsWith(".sql", StringComparison.Ordinal))) + { + using var reader = new StreamReader(asm.GetManifestResourceStream(res)!); + foreach (Match m in Regex.Matches(reader.ReadToEnd(), @"CREATE TABLE IF NOT EXISTS (\w+)\s*\(", RegexOptions.IgnoreCase)) + tables.Add(m.Groups[1].Value); + } + Assert.NotEmpty(tables); + foreach (var t in tables) + Assert.True(ArchiveTable.Find(t) != null || NotExported.Contains(t), $"La tabella {t} non è in ArchiveTable.All: aggiungila (con i nomi da pseudonimizzare) o escludila apposta."); + } + + [Fact] + public void I_percorsi_non_dipendono_dalla_cultura() + { + var bids = ArchiveTable.Find("bids")!; + Assert.Equal("tabelle/bids/2026-01/2026-01-05.csv.gz", bids.RelativePath(new DateOnly(2026, 1, 5))); + Assert.Equal("tabelle/items.csv.gz", ArchiveTable.Find("items")!.RelativePath(null)); + } + + [Fact] + public void La_select_riscrive_solo_le_colonne_con_un_nome_o_un_segreto() + { + var p = new Pseudonyms("00112233445566778899aabbccddeeff", Array.Empty()); + var list = ArchiveTable.Find("bids")!.SelectList(new[] { "bid_id", "username", "price_after" }, p); + Assert.StartsWith("bid_id, (CASE WHEN username", list); + Assert.EndsWith(" AS username, price_after", list); + Assert.Contains("value - 'TelegramBotToken' - 'TelegramChatId' AS value", ArchiveTable.Find("settings")!.SelectList(new[] { "id", "value" }, p)); + } +} + +[Collection("Database")] +public class ArchiveDownloaderTests(DatabaseFixture fx) +{ + private const string Salt = "00112233445566778899aabbccddeeff"; + private static readonly TimeZoneInfo Rome = TimeZoneInfo.FindSystemTimeZoneById("Europe/Rome"); + + private static async Task OpenAsync() + { + var conn = new NpgsqlConnection(ArchiveDownloader.ReadOnlyBuilder(TestDb.Config, 5).ConnectionString); + await conn.OpenAsync(); + return conn; + } + + [DbFact] + public async Task Gli_pseudonimi_di_postgresql_sono_quelli_del_programma() + { + await using var conn = await OpenAsync(); + var p = new Pseudonyms(Salt, new[] { "sirbietole23" }); + foreach (var name in new[] { "anna", "Bob_77", "ünïcode", "sirbietole23" }) + { + await using var cmd = new NpgsqlCommand($"SELECT {p.Sql("$1::text")}", conn) { Parameters = { new NpgsqlParameter { Value = name } } }; + Assert.Equal(p.Of(name), (string?)await cmd.ExecuteScalarAsync()); + } + await using (var keys = new NpgsqlCommand($"SELECT {p.SqlJsonKeys("'{\"anna\": 3, \"sirbietole23\": 1}'::jsonb")}::text", conn)) + { + var o = JsonNode.Parse((string)(await keys.ExecuteScalarAsync())!)!.AsObject(); + Assert.Equal(3, (int)o[p.Of("anna")!]!); + Assert.Equal(1, (int)o[Pseudonyms.Me]!); + } + await using (var field = new NpgsqlCommand($"SELECT {p.SqlJsonField("'{\"lastBidder\": \"anna\", \"price\": 1.5}'::jsonb", "lastBidder")}::text", conn)) + { + var o = JsonNode.Parse((string)(await field.ExecuteScalarAsync())!)!.AsObject(); + Assert.Equal(p.Of("anna"), (string?)o["lastBidder"]); + Assert.Equal(1.5, (double)o["price"]!); + } + } + + [DbFact] + public async Task La_connessione_dello_strumento_non_puo_scrivere() + { + await using var conn = await OpenAsync(); + await using var cmd = new NpgsqlCommand("INSERT INTO items(product_key) VALUES ('scrittura-vietata')", conn); + var e = await Assert.ThrowsAsync(() => cmd.ExecuteNonQueryAsync()); + Assert.Equal("25006", e.SqlState); // read_only_sql_transaction + } + + [DbFact] + public async Task Scarica_per_giorno_locale_con_pseudonimi_riassunti_dossier_e_verifica() + { + await fx.TruncateAsync(); + var db = fx.Db!; + foreach (var t in Partitions.Tables) + await db.ExecuteAsync($"CREATE TABLE IF NOT EXISTS {t}_2020_01 PARTITION OF {t} FOR VALUES FROM ('2020-01-01') TO ('2020-02-01')"); + + await db.ExecuteAsync("INSERT INTO settings(id, value) VALUES (1, '{\"TelegramBotToken\": \"123:segreto\", \"TelegramChatId\": \"42\", \"MaxBids\": 5}') " + + "ON CONFLICT (id) DO UPDATE SET value = excluded.value"); + await db.ExecuteAsync("INSERT INTO documents(key, value) VALUES ('ml/pesi', '{\"w\": [1, 2]}'), ('monitor/auctions', '[{\"winner\": \"anna\"}]')"); + await db.ExecuteAsync( + "INSERT INTO auctions(auction_id, name, product_key, type, outcome, final_price, end_time, me, winner_user, my_bids, observed_from_start, observed_to_end, bids_by_user, loss_reason) VALUES " + + "('A1', 'Buono', 'buono', 'normal', 'lost', 1.02, '2020-01-11 10:00:00+00', 'sirbietole23', 'anna', 1, true, true, '{\"anna\": 2, \"sirbietole23\": 1}', 'vinta da anna'), " + + "('A2', 'Buono', 'buono', 'normal', 'lost', 0.51, '2020-01-12 10:00:00+00', 'sirbietole23', 'bob', 0, true, true, '{\"bob\": 1}', 'coperta da bob (a mano)')"); + // Il 10 gennaio alle 23:30 UTC a Roma è già l'11: deve finire nel file dell'11. + await db.ExecuteAsync( + "INSERT INTO bids(auction_id, username, price_after, created_at) VALUES " + + "('A1', 'anna', 1.00, '2020-01-10 12:00:00+00'), ('A1', 'sirbietole23', 1.01, '2020-01-10 23:30:00+00'), ('A1', 'anna', 1.02, '2020-01-11 09:00:00+00'), " + + "('A2', 'bob', 0.51, '2020-01-12 09:00:00+00')"); + await db.ExecuteAsync("INSERT INTO resets(auction_id, t, bidder, created_at) VALUES ('A1', 1, 'anna', '2020-01-10 12:00:00+00'), ('A2', 2, 'bob', '2020-01-12 09:00:00+00')"); + await db.ExecuteAsync( + "INSERT INTO bot_decisions(decision_id, auction_id, ts, kind, p_win, outcome, reason_detail, state, created_at) VALUES " + + "(1, 'A1', '2020-01-10 12:00:01+00', 'punta', 0.05, 'covered', 'coperta da anna', '{\"lastBidder\": \"anna\"}', '2020-01-10 12:00:01+00'), " + + "(2, 'A2', '2020-01-12 09:00:01+00', 'esplora', 0.02, 'missed', 'P bassa', '{\"lastBidder\": \"bob\"}', '2020-01-12 09:00:01+00')"); + await db.ExecuteAsync("INSERT INTO auction_forecasts(auction_id, ts, is_initial, forecast_close, actual_close, error_close, in_interval) VALUES ('A1', '2020-01-10 12:00:00+00', true, 1.1, 1.02, 0.08, true)"); + await db.ExecuteAsync("INSERT INTO my_bids(auction_id, t, local_ts, price, success, answered_by, decision_id) VALUES ('A1', 5, '2020-01-10 23:30:00+00', 1.01, true, 'anna', 1)"); + await db.ExecuteAsync("INSERT INTO bidders(username, n_bids) VALUES ('anna', 2), ('bob', 1)"); + + using var dir = new TempDir(); + var lines = new List(); + var options = new ArchiveDownloader.Options + { + Folder = dir.Path, Today = new DateOnly(2020, 1, 20), MegabytesPerSecond = 0, ReserveGb = 0, PauseForMaintenance = false, Sample = 10 + }; + await File.WriteAllTextAsync(Path.Combine(dir.Path, ".sale"), Salt); + var p = new Pseudonyms(Salt, new[] { "sirbietole23" }); + + await using (var conn = await OpenAsync()) + { + var tool = new ArchiveDownloader(conn, options, lines.Add, Rome); + await tool.DownloadAsync(CancellationToken.None); + await tool.SummariesAsync(CancellationToken.None); + await tool.DossierAsync(CancellationToken.None); + + var manifest = Manifest.Load(dir.Path)!; + var bids = manifest.Tables["bids"].Files; + Assert.Equal(new long[] { 1, 2, 1 }, new[] { "10", "11", "12" }.Select(d => bids[$"tabelle/bids/2020-01/2020-01-{d}.csv.gz"].Rows)); + Assert.True(bids["tabelle/bids/2020-01/2020-01-17.csv.gz"].Final); + Assert.False(bids["tabelle/bids/2020-01/2020-01-18.csv.gz"].Final); // a due giorni da «oggi» gli esiti possono ancora arrivare + Assert.Equal(0, bids["tabelle/bids/2020-01/2020-01-19.csv.gz"].Rows); + Assert.False(bids.ContainsKey("tabelle/bids/2020-01/2020-01-20.csv.gz")); + Assert.Equal(1, manifest.Tables["bot_decisions"].Files["tabelle/bot_decisions/2020-01/2020-01-12.csv.gz"].Rows); + + var day11 = Gunzip(Path.Combine(dir.Path, "tabelle", "bids", "2020-01", "2020-01-11.csv.gz")); + Assert.StartsWith("bid_id,auction_id,username,", day11); + Assert.Contains($",{Pseudonyms.Me},1.01,", day11); + Assert.Contains($",{p.Of("anna")},1.02,", day11); + + var all = string.Join("\n", Directory.EnumerateFiles(dir.Path, "*.gz", SearchOption.AllDirectories).Select(Gunzip)) + + string.Join("\n", Directory.EnumerateFiles(dir.Path, "*.csv", SearchOption.AllDirectories).Select(File.ReadAllText)) + + string.Join("\n", Directory.EnumerateFiles(dir.Path, "*.jsonl", SearchOption.AllDirectories).Select(File.ReadAllText)); + foreach (var secret in new[] { "anna", "bob", "sirbietole23", "123:segreto", "monitor/auctions" }) + Assert.DoesNotContain(secret, all); + Assert.Contains("MaxBids", all); + Assert.Contains($"vinta da {p.Of("anna")}", all); + Assert.Contains($"coperta da {p.Of("bob")} (a mano)", all); + + Assert.True(File.Exists(Path.Combine(dir.Path, "riassunti", "calibrazione.csv"))); + Assert.Equal(1, manifest.Other["riassunti/mie_puntate.csv"].Rows); + var dossier = await File.ReadAllLinesAsync(Path.Combine(dir.Path, "dossier", "mie", "A1.jsonl")); + Assert.Equal(new[] { "asta", "previsione", "decisione", "mia_puntata", "puntata", "puntata", "puntata", "reset" }, + dossier.Select(l => (string)JsonNode.Parse(l)!["tipo"]!)); + Assert.True(File.Exists(Path.Combine(dir.Path, "dossier", "osservate", "A2.jsonl"))); + var readme = await File.ReadAllTextAsync(Path.Combine(dir.Path, "LEGGIMI.md")); + Assert.Contains("### bot_decisions", readme); + Assert.Contains("| `reason_detail` | text |", readme); + + Assert.Empty(await ArchiveDownloader.VerifyAsync(dir.Path, conn, lines.Add, CancellationToken.None)); + + // La seconda volta i file definitivi non si riscaricano; quelli interi sì. + var before = manifest.Tables["bids"].Files["tabelle/bids/2020-01/2020-01-11.csv.gz"].DownloadedUtc; + await tool.DownloadAsync(CancellationToken.None); + var again = Manifest.Load(dir.Path)!; + Assert.Equal(before, again.Tables["bids"].Files["tabelle/bids/2020-01/2020-01-11.csv.gz"].DownloadedUtc); + Assert.True(again.Tables["auctions"].Files["tabelle/auctions.csv.gz"].DownloadedUtc > manifest.Tables["auctions"].Files["tabelle/auctions.csv.gz"].DownloadedUtc); + + var estimate = await tool.EstimateAsync(CancellationToken.None); + Assert.Equal(new DateOnly(2020, 1, 10), estimate.Single(r => r.Table == "bids").FirstDay); + } + + // Un file rovinato si vede senza database. + var damaged = Path.Combine(dir.Path, "tabelle", "bids", "2020-01", "2020-01-10.csv.gz"); + var bytes = await File.ReadAllBytesAsync(damaged); + bytes[^1] ^= 0xFF; + await File.WriteAllBytesAsync(damaged, bytes); + var problems = await ArchiveDownloader.VerifyAsync(dir.Path, null, _ => { }, CancellationToken.None); + Assert.Single(problems); + Assert.Contains("2020-01-10", problems[0]); + } + + [DbFact] + public async Task Una_cartella_con_pseudonimi_non_riceve_i_nomi_veri() + { + await fx.TruncateAsync(); + using var dir = new TempDir(); + await using var conn = await OpenAsync(); + var options = new ArchiveDownloader.Options { Folder = dir.Path, Today = new DateOnly(2020, 1, 20), PauseForMaintenance = false, ReserveGb = 0, Tables = new HashSet { "items" } }; + await new ArchiveDownloader(conn, options, _ => { }, Rome).DownloadAsync(CancellationToken.None); + var real = new ArchiveDownloader(conn, options with { RealNames = true }, _ => { }, Rome); + await Assert.ThrowsAsync(() => real.DownloadAsync(CancellationToken.None)); + } + + private static string Gunzip(string file) + { + using var gz = new GZipStream(File.OpenRead(file), CompressionMode.Decompress); + using var r = new StreamReader(gz, Encoding.UTF8); + return r.ReadToEnd(); + } +} diff --git a/tools/Mimante.Dati/Mimante.Dati.csproj b/tools/Mimante.Dati/Mimante.Dati.csproj new file mode 100644 index 0000000..3a85609 --- /dev/null +++ b/tools/Mimante.Dati/Mimante.Dati.csproj @@ -0,0 +1,19 @@ + + + + + Exe + Mimante.Dati + false + + + + + + + + diff --git a/tools/Mimante.Dati/Program.cs b/tools/Mimante.Dati/Program.cs new file mode 100644 index 0000000..d1326ab --- /dev/null +++ b/tools/Mimante.Dati/Program.cs @@ -0,0 +1,227 @@ +using System.Globalization; +using System.Text; +using Mimante.Config; +using Mimante.Data.Archive; +using Npgsql; + +// Mimante.Dati: porta l'archivio del bot in una cartella di file (vedi Uso più sotto). +Console.OutputEncoding = Encoding.UTF8; +var inv = CultureInfo.InvariantCulture; + +const string Uso = """ + Uso: dotnet run --project tools/Mimante.Dati -- [opzioni] + + Comandi + stima quanto occupa l'archivio e quanto resta da scaricare + scarica le tabelle, un file per giorno (riprende da dove si era fermato) + riassunti i file piccoli già aggregati, da leggere per primi + dossier un file JSONL per asta su cui il bot ha puntato, più un campione di aste osservate + verifica impronte e dimensioni dei file; con --contro-db anche le righe nel database + stato che cosa c'è nella cartella (senza database) + tutto scarica, riassunti, dossier e verifica + + Opzioni + --cartella dove scrivere (predefinita: dati/ nella radice del repository) + --da primo giorno; --a ultimo giorno (mai oggi) + --tabelle a,b,c solo queste tabelle + --velocita lettura massima (predefinita 20; 0 = nessun limite) + --riserva-gb spazio da lasciare libero (predefinito 5) + --margine-giorni giorni dopo i quali un file del giorno è definitivo (predefinito 2) + --campione aste osservate nei dossier (predefinito 200) + --nomi-veri niente pseudonimi (cartella da non condividere) + --contro-db per verifica: riconta le righe nel database + --senza-pausa non aspettare la fine della manutenzione notturna del bot (4:20-5:40) + --env-file variabili DB_* da un file KEY=VALUE + + Database: DB_HOST (anche host:porta), DB_PORT, DB_USER, DB_NAME, DB_PASSWORD dall'ambiente o da --env-file; + senza DB_PASSWORD la chiede a schermo. La connessione è in sola lettura. + """; + +if (args.Length == 0 || args[0] is "-h" or "--help" or "aiuto") +{ + Console.WriteLine(Uso); + return 0; +} + +var command = args[0]; +var opts = new Dictionary(StringComparer.Ordinal); +var flags = new HashSet(StringComparer.Ordinal) { "--nomi-veri", "--contro-db", "--senza-pausa" }; +for (var i = 1; i < args.Length; i++) +{ + var a = args[i]; + if (!a.StartsWith("--", StringComparison.Ordinal)) return Fail($"Argomento non previsto: {a}"); + if (flags.Contains(a)) { opts[a] = null; continue; } + if (i + 1 >= args.Length) return Fail($"Manca il valore di {a}"); + opts[a] = args[++i]; +} +var known = new[] { "--cartella", "--da", "--a", "--tabelle", "--velocita", "--riserva-gb", "--margine-giorni", "--campione", "--env-file" }; +foreach (var k in opts.Keys) + if (!flags.Contains(k) && !known.Contains(k)) return Fail($"Opzione sconosciuta: {k}"); + +var folder = Path.GetFullPath(opts.GetValueOrDefault("--cartella") ?? Path.Combine(RepoRoot() ?? Directory.GetCurrentDirectory(), "dati")); +var zone = TimeZoneInfo.FindSystemTimeZoneById("Europe/Rome"); + +if (command == "stato") +{ + foreach (var line in ArchiveDownloader.Status(folder)) Console.WriteLine(line); + return 0; +} +if (command == "verifica" && !opts.ContainsKey("--contro-db")) +{ + try { return Report(await ArchiveDownloader.VerifyAsync(folder, null, l => Console.WriteLine(l), CancellationToken.None)); } + catch (InvalidOperationException e) { return Fail(e.Message); } +} +if (command is not ("stima" or "scarica" or "riassunti" or "dossier" or "verifica" or "tutto")) + return Fail($"Comando sconosciuto: {command}\n\n{Uso}"); + +DateOnly? Day(string key) +{ + var v = opts.GetValueOrDefault(key); + if (v == null) return null; + return DateOnly.TryParseExact(v, "yyyy-MM-dd", inv, DateTimeStyles.None, out var d) ? d : throw new ArgumentException($"{key}: data non valida ({v}), serve aaaa-mm-gg"); +} +double Num(string key, double fallback) => + opts.GetValueOrDefault(key) is { } v ? double.TryParse(v, NumberStyles.Float, inv, out var n) && n >= 0 ? n : throw new ArgumentException($"{key}: numero non valido ({v})") : fallback; + +ArchiveDownloader.Options options; +try +{ + options = new ArchiveDownloader.Options + { + Folder = folder, + From = Day("--da"), + To = Day("--a"), + Tables = opts.GetValueOrDefault("--tabelle") is { } t ? t.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).ToHashSet(StringComparer.Ordinal) : null, + MegabytesPerSecond = Num("--velocita", 20), + ReserveGb = Num("--riserva-gb", 5), + FinalAfterDays = (int)Num("--margine-giorni", 2), + Sample = (int)Num("--campione", 200), + RealNames = opts.ContainsKey("--nomi-veri"), + PauseForMaintenance = !opts.ContainsKey("--senza-pausa") + }; + if (options.Tables != null) + foreach (var name in options.Tables) + if (ArchiveTable.Find(name) == null) return Fail($"Tabella sconosciuta: {name} (previste: {string.Join(", ", ArchiveTable.All.Select(x => x.Name))})"); +} +catch (ArgumentException e) { return Fail(e.Message); } + +var env = new Dictionary(StringComparer.Ordinal); +if (opts.GetValueOrDefault("--env-file") is { } envFile) +{ + if (!File.Exists(envFile)) return Fail($"File delle variabili non trovato: {envFile}"); + foreach (var raw in File.ReadAllLines(envFile)) + { + var line = raw.Trim(); + if (line.Length == 0 || line.StartsWith('#')) continue; + var eq = line.IndexOf('='); + if (eq > 0) env[line[..eq].Trim()] = line[(eq + 1)..].Trim().Trim('"'); + } +} +var config = EnvConfig.Read(k => Environment.GetEnvironmentVariable(k) ?? env.GetValueOrDefault(k), Array.Empty()); +if (!config.HasDbHost) return Fail("Manca DB_HOST (per esempio DB_HOST=192.168.30.23:5432)."); +var db = config.ToDbConfig(); +if (!config.HasDbPassword) +{ + if (Console.IsInputRedirected) return Fail("Manca DB_PASSWORD."); + db = db with { Password = ReadHidden($"Password di {db.User} su {db.Host}: ") }; +} + +using var cts = new CancellationTokenSource(); +Console.CancelKeyPress += (_, e) => +{ + e.Cancel = true; + cts.Cancel(); + Console.WriteLine("Interruzione: finisco il file in corso senza tenerlo. Lo stesso comando riprende da qui."); +}; + +void Say(string line) => Console.WriteLine($"{DateTime.Now:HH:mm:ss} {line}"); + +try +{ + await using var conn = new NpgsqlConnection(ArchiveDownloader.ReadOnlyBuilder(db).ConnectionString); + await conn.OpenAsync(cts.Token); + Say($"Collegato a {db.Describe()} in sola lettura; cartella {folder}"); + var tool = new ArchiveDownloader(conn, options, Say, zone); + switch (command) + { + case "stima": + PrintEstimate(await tool.EstimateAsync(cts.Token)); + break; + case "scarica": + await tool.DownloadAsync(cts.Token); + break; + case "riassunti": + await tool.SummariesAsync(cts.Token); + break; + case "dossier": + await tool.DossierAsync(cts.Token); + break; + case "verifica": + return Report(await ArchiveDownloader.VerifyAsync(folder, opts.ContainsKey("--contro-db") ? conn : null, Say, cts.Token)); + case "tutto": + await tool.DownloadAsync(cts.Token); + await tool.SummariesAsync(cts.Token); + await tool.DossierAsync(cts.Token); + return Report(await ArchiveDownloader.VerifyAsync(folder, null, Say, cts.Token)); + } + foreach (var line in ArchiveDownloader.Status(folder)) Console.WriteLine(line); + return 0; +} +catch (OperationCanceledException) when (cts.IsCancellationRequested) +{ + Say("Interrotto. I file finiti restano; il resto si riprende con lo stesso comando."); + return 130; +} +catch (Exception e) when (e is NpgsqlException or PostgresException or IOException or InvalidOperationException or TimeoutException) +{ + return Fail(e.Message); +} + +static int Report(List problems) +{ + foreach (var p in problems.Take(100)) Console.WriteLine(" " + p); + if (problems.Count > 100) Console.WriteLine($" … e altri {problems.Count - 100}"); + return problems.Count == 0 ? 0 : 1; +} + +static void PrintEstimate(List rows) +{ + static string Gb(long b) => (b / 1073741824.0).ToString("0.00", CultureInfo.InvariantCulture) + " GB"; + Console.WriteLine(); + Console.WriteLine($"{"Tabella",-20} {"Righe",14} {"Nel database",13} {"Dal",11} {"Giorni",7} {"Fatti",6} {"Scaricato",10} {"Da scaricare",13}"); + foreach (var r in rows) + Console.WriteLine(string.Create(CultureInfo.InvariantCulture, + $"{r.Table,-20} {r.Rows,14:N0} {Gb(r.TableBytes),13} {r.FirstDay?.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) ?? "-",11} {r.Days,7} {r.DaysDone,6} {Gb(r.DownloadedBytes),10} {"~" + Gb(r.RemainingBytes),13}")); + Console.WriteLine(string.Create(CultureInfo.InvariantCulture, + $"{"Totale",-20} {rows.Sum(r => r.Rows),14:N0} {Gb(rows.Sum(r => r.TableBytes)),13} {"",11} {"",7} {"",6} {Gb(rows.Sum(r => r.DownloadedBytes)),10} {"~" + Gb(rows.Sum(r => r.RemainingBytes)),13}")); + Console.WriteLine(); + Console.WriteLine("La stima di ciò che resta usa i file già scaricati, o un rapporto tipico di compressione se non ce ne sono ancora."); +} + +static int Fail(string message) +{ + Console.Error.WriteLine(message); + return 2; +} + +static string? RepoRoot() +{ + for (var d = new DirectoryInfo(Directory.GetCurrentDirectory()); d != null; d = d.Parent) + if (File.Exists(Path.Combine(d.FullName, "Mimante.slnx"))) return d.FullName; + return null; +} + +static string ReadHidden(string prompt) +{ + Console.Write(prompt); + var s = new StringBuilder(); + while (true) + { + var k = Console.ReadKey(intercept: true); + if (k.Key == ConsoleKey.Enter) break; + if (k.Key == ConsoleKey.Backspace) { if (s.Length > 0) s.Length--; continue; } + if (!char.IsControl(k.KeyChar)) s.Append(k.KeyChar); + } + Console.WriteLine(); + return s.ToString(); +}