Scaricamento dei dati per l'analisi: tools/Mimante.Dati (#26)
verifica / controlli (push) Successful in 59s
verifica / prove (push) Successful in 2m28s
verifica / immagine (push) Canceled after 10s

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 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-24 12:47:30 +01:00
1 parent b0901c0248
commit f2eb86be86
15 files changed
+1969 -38

No files matched your search

@@ -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;
/// <summary>
/// Porta l'archivio PostgreSQL in una cartella di file da analizzare (con Claude o con qualunque strumento):
/// tabelle divise per giorno in <c>.csv.gz</c>, riassunti piccoli già leggibili, un dossier per asta, il manifesto
/// e il <c>LEGGIMI.md</c>. Solo letture, su una connessione in sola lettura (<see cref="ReadOnlyBuilder"/>);
/// riprendibile (salta i file definitivi già scaricati); i nomi degli altri utenti diventano pseudonimi.
/// </summary>
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; }
/// <summary>Solo queste tabelle (null = tutte quelle del catalogo).</summary>
public IReadOnlySet<string>? Tables { get; init; }
/// <summary>Velocità massima di lettura in MB/s di testo (0 = nessun limite).</summary>
public double MegabytesPerSecond { get; init; } = 20;
/// <summary>Spazio da lasciare libero sul disco della cartella, in GB.</summary>
public double ReserveGb { get; init; } = 5;
/// <summary>Un giorno diventa definitivo quando ne sono passati più di questi (gli esiti arrivano alla chiusura delle aste).</summary>
public int FinalAfterDays { get; init; } = 2;
public bool RealNames { get; init; }
/// <summary>Aspetta la fine della manutenzione notturna del bot (dalle 4:20 alle 5:40) prima di ogni file.</summary>
public bool PauseForMaintenance { get; init; } = true;
/// <summary>Quante aste osservate per intero (senza mie puntate) entrano nei dossier, oltre a tutte quelle con mie puntate.</summary>
public int Sample { get; init; } = 200;
/// <summary>Il giorno di oggi (per le prove); null = oggi nel fuso del bot.</summary>
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);
/// <summary>Rapporto tipico fra il file .csv.gz e lo spazio della tabella, finché non ci sono file veri da cui ricavarlo.</summary>
private const double TypicalRatio = 0.15;
private readonly NpgsqlConnection _conn;
private readonly Options _o;
private readonly Action<string> _say;
private readonly TimeZoneInfo _zone;
private readonly BulkCopy.Throttle? _throttle;
private readonly Dictionary<string, List<(string Name, string Type)>> _columns = new(StringComparer.Ordinal);
private Manifest _manifest = null!;
private Pseudonyms _names = null!;
public ArchiveDownloader(NpgsqlConnection conn, Options options, Action<string> 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;
}
/// <summary>
/// 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.
/// </summary>
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<int>("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<List<(string Name, string Type)>> 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);
}
/// <summary>I giorni da scaricare: dal primo dell'archivio a ieri, dentro --da e --a.</summary>
internal static IEnumerable<DateOnly> 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;
}
/// <summary>Definitivo se sono passati più di <see cref="Options.FinalAfterDays"/> giorni.</summary>
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<string> 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<string> columns, Manifest.TableEntry entry, CancellationToken ct)
{
var key = table.Key!;
var first = await ScalarAsync<DateTime?>($"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<string> 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<string>? 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]); };
};
}
/// <summary>Prima di ogni file: niente durante la manutenzione notturna del bot, e mai sotto la riserva di spazio.</summary>
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 ────────────────────────────────────────────────────────
/// <summary>Un riassunto: file piccolo in <c>riassunti/</c>, leggibile subito, calcolato da PostgreSQL.</summary>
public sealed record Summary(string Name, string Description, string Sql, IReadOnlyList<string>? TextWithNames = null);
public IReadOnlyList<Summary> 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")
};
/// <summary>
/// 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.
/// </summary>
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<string, string>(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<string>? 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<string>(out var s)) node[c] = _names.Text(s);
return node.ToJsonString();
}
// ── verifica, stima, stato ───────────────────────────────────────────
/// <summary>
/// Ogni file del manifesto c'è, ha la dimensione e l'impronta registrate; con <paramref name="againstDb"/> le righe dei
/// file del giorno definitivi sono quelle che il database conta con la stessa condizione. Restituisce i problemi.
/// </summary>
public static async Task<List<string>> VerifyAsync(string folder, NpgsqlConnection? againstDb, Action<string> say, CancellationToken ct)
{
var manifest = Manifest.Load(folder) ?? throw new InvalidOperationException($"In {folder} non c'è {Manifest.FileName}: prima scarica.");
var problems = new List<string>();
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<List<EstimateRow>> EstimateAsync(CancellationToken ct)
{
var manifest = Manifest.Load(_o.Folder);
var rows = new List<EstimateRow>();
foreach (var table in ArchiveTable.All)
{
if (_o.Tables != null && !_o.Tables.Contains(table.Name)) continue;
var exists = await ScalarAsync<bool>($"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<DateTime?>(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<string, Manifest.FileEntry>();
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<string> Status(string folder)
{
var m = Manifest.Load(folder);
if (m == null) return new List<string> { $"In {folder} non c'è ancora nulla: comincia con «stima» e «scarica»." };
var lines = new List<string>
{
$"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<List<string>> ListAsync(string sql, CancellationToken ct)
{
var list = new List<string>();
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<T> ScalarAsync<T>(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));
}
/// <summary>Un istante come letterale SQL timestamptz in UTC (i COPY non accettano parametri).</summary>
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();
}
+89
View File
@@ -0,0 +1,89 @@
using System.Text;
namespace Mimante.Data.Archive;
public sealed partial class ArchiveDownloader
{
/// <summary>
/// <c>LEGGIMI.md</c> 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.
/// </summary>
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/<asta>.jsonl` | Tutto di un'asta su cui il bot ha puntato davvero, una riga JSON per fatto. |");
s.AppendLine("| `dossier/osservate/<asta>.jsonl` | Lo stesso per un campione stabile di aste seguite dall'inizio alla fine, senza mie puntate. |");
s.AppendLine("| `tabelle/<tabella>/<aaaa-mm>/<aaaa-mm-gg>.csv.gz` | Le tabelle grandi, un file per giorno locale (Europe/Rome). |");
s.AppendLine("| `tabelle/<tabella>.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);
}
}
+88
View File
@@ -0,0 +1,88 @@
namespace Mimante.Data.Archive;
/// <summary>Come si divide una tabella nei file dello scaricamento.</summary>
public enum ArchiveSplit
{
/// <summary>Un file solo, riscaricato ogni volta (tabelle piccole o che cambiano).</summary>
Whole,
/// <summary>Un file per giorno locale, per intervallo di id (l'id cresce con created_at; nessun indice sul tempo).</summary>
IdDay,
/// <summary>Un file per giorno locale, per intervallo sulla colonna del tempo (che ha il suo indice).</summary>
TsDay
}
/// <summary>
/// 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.
/// </summary>
public sealed record ArchiveTable(
string Name, ArchiveSplit Split, string? Key, string Order, string Description,
string? Where = null,
Func<Pseudonyms, IReadOnlyDictionary<string, string>>? Expressions = null,
IReadOnlyList<string>? TextWithNames = null,
bool PartitionedByCreatedAt = false)
{
/// <summary>
/// Le tabelle che si scaricano. Una tabella che non è qui non esce mai (potrebbe contenere segreti): lo
/// scaricamento la segnala e la salta.
/// </summary>
public static readonly IReadOnlyList<ArchiveTable> 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<string, string> { ["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<string, string> { ["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<string, string> { ["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<string, string>
{
["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<string, string> { ["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<string, string> { ["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<string, string> { ["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);
/// <summary>L'elenco delle colonne per la SELECT, con le riscritture al posto delle colonne originali.</summary>
public string SelectList(IReadOnlyList<string> columns, Pseudonyms names)
{
var map = Expressions?.Invoke(names) ?? new Dictionary<string, string>();
return string.Join(", ", columns.Select(c => map.TryGetValue(c, out var e) ? $"{e} AS {c}" : c));
}
/// <summary>Il percorso relativo (con «/») del file di un giorno o della tabella intera.</summary>
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";
}
+37
View File
@@ -0,0 +1,37 @@
namespace Mimante.Data.Archive;
/// <summary>
/// I confini dei giorni nelle tabelle grandi senza indice sul tempo (<c>bids</c>, <c>resets</c>): l'id cresce con
/// <c>created_at</c> (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).
/// </summary>
public static class DayRanges
{
/// <summary>La prima riga con id ≥ del dato: (id, created_at in UTC), null se non ce n'è.</summary>
public delegate Task<(long Id, DateTime CreatedUtc)?> Probe(long atLeast, CancellationToken ct);
/// <summary>
/// Il primo id con <c>created_at</c> ≥ <paramref name="instantUtc"/> fra <paramref name="minId"/> e
/// <paramref name="endId"/> (escluso); <paramref name="endId"/> se non c'è. I buchi nella numerazione si saltano.
/// </summary>
public static async Task<long> 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;
}
/// <summary>Inizio (UTC) del giorno locale <paramref name="day"/> nel fuso <paramref name="zone"/>.</summary>
public static DateTime StartUtc(DateOnly day, TimeZoneInfo zone) =>
TimeZoneInfo.ConvertTimeToUtc(day.ToDateTime(TimeOnly.MinValue, DateTimeKind.Unspecified), zone);
}
+100
View File
@@ -0,0 +1,100 @@
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Mimante.Data.Archive;
/// <summary>
/// <c>manifesto.json</c> 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; <c>verifica</c> rilegge le impronte (e, a richiesta, i conteggi nel database).
/// </summary>
public sealed class Manifest
{
public const string FileName = "manifesto.json";
/// <summary>Versione del formato della cartella: cambia solo se cambia la disposizione dei file.</summary>
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; }
/// <summary>Per tabella: come è divisa e i suoi file (percorso relativo con «/»).</summary>
public SortedDictionary<string, TableEntry> Tables { get; set; } = new(StringComparer.Ordinal);
/// <summary>I riassunti e i dossier, per percorso relativo.</summary>
public SortedDictionary<string, FileEntry> Other { get; set; } = new(StringComparer.Ordinal);
public sealed class TableEntry
{
public string Split { get; set; } = "";
public List<string> Columns { get; set; } = new();
public SortedDictionary<string, FileEntry> 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; }
/// <summary>Giorno locale del file (aaaa-mm-gg), per le tabelle divise per giorno.</summary>
public string? Day { get; set; }
/// <summary>La condizione WHERE con cui il file è stato scritto: <c>verifica --contro-db</c> riconta con la stessa.</summary>
public string? Filter { get; set; }
/// <summary>Intervallo di id [IdFrom, IdTo), per le tabelle divise per id.</summary>
public long? IdFrom { get; set; }
public long? IdTo { get; set; }
/// <summary>
/// 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.
/// </summary>
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<Manifest>(File.ReadAllText(path), Json);
}
/// <summary>Scrive su .tmp e rinomina: un'interruzione non lascia un manifesto a metà.</summary>
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;
}
/// <summary>Un file da non riscaricare: definitivo, presente e della stessa dimensione registrata.</summary>
public static bool IsDone(FileEntry? entry, string fullPath) =>
entry is { Final: true } && File.Exists(fullPath) && new FileInfo(fullPath).Length == entry.Bytes;
}
+73
View File
@@ -0,0 +1,73 @@
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
namespace Mimante.Data.Archive;
/// <summary>
/// Gli pseudonimi degli altri utenti di Bidoo nei dati scaricati: <c>u_</c> 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
/// (<see cref="Sql"/>, dentro i COPY) o il programma (<see cref="Of"/>, nei testi). I miei utenti
/// diventano <c>io</c>. Spenti (<c>--nomi-veri</c>) restituiscono i nomi come sono.
/// </summary>
public sealed partial class Pseudonyms
{
public const string Me = "io";
private readonly string _salt;
private readonly HashSet<string> _mine;
public bool Enabled { get; }
public Pseudonyms(string salt, IEnumerable<string> 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<string>(mine.Where(m => !string.IsNullOrEmpty(m)), StringComparer.Ordinal);
Enabled = enabled;
}
/// <summary>Un sale nuovo: 32 cifre esadecimali casuali.</summary>
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];
}
/// <summary>L'espressione SQL che dà lo pseudonimo di <paramref name="expr"/> (una colonna di testo).</summary>
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)";
}
/// <summary>Un oggetto jsonb con i nomi come chiavi (per esempio <c>auctions.bids_by_user</c>) con gli pseudonimi al loro posto.</summary>
public string SqlJsonKeys(string expr) => Enabled
? $"(SELECT jsonb_object_agg({Sql("e.k")}, e.v) FROM jsonb_each({expr}) AS e(k, v))"
: expr;
/// <summary>Un campo di testo di un oggetto jsonb (per esempio <c>state.lastBidder</c>) sostituito dal suo pseudonimo.</summary>
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;
/// <summary>
/// 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).
/// </summary>
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();
}
+305
View File
@@ -0,0 +1,305 @@
using System.IO.Compression;
using System.Security.Cryptography;
using System.Text;
using Npgsql;
namespace Mimante.Data;
/// <summary>
/// Copia in blocco da PostgreSQL a file: <c>COPY (…) TO STDOUT (FORMAT csv, HEADER)</c> scritto su
/// <c>nome.tmp</c> e rinominato alla fine, compresso in gzip se il nome finisce in <c>.gz</c>. Lo usano il
/// backup notturno e lo strumento dei dati (<c>tools/Mimante.Dati</c>).
///
/// <para>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
/// (<see cref="Transform"/>: per esempio i nomi dentro un testo) leggendo il CSV record per record.</para>
/// </summary>
public static class BulkCopy
{
/// <summary>Righe di dati (senza l'intestazione), byte del file, impronta SHA-256 in esadecimale minuscolo.</summary>
public sealed record Outcome(long Rows, long Bytes, string Sha256);
/// <summary>
/// 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.
/// </summary>
public delegate Action<string?[]>? Transform(IReadOnlyList<string> header);
public static async Task<Outcome> 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;
}
}
/// <summary>Copia il testo così com'è contando i record; restituisce le righe di dati.</summary>
private static async Task<long> 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<long> 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;
}
/// <summary>Un record nel CSV di COPY: NULL vuoto senza virgolette, il testo vuoto come <c>""</c>.</summary>
internal static void WriteRecord(StringBuilder sb, IReadOnlyList<string?> 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');
}
/// <summary>Conta i record di un CSV a pezzi: un a capo fuori dalle virgolette chiude un record.</summary>
internal sealed class RecordCounter
{
private bool _quoted;
private bool _pending;
public long Records { get; private set; }
public void Feed(ReadOnlySpan<char> chunk)
{
foreach (var c in chunk)
{
if (c == '"') _quoted = !_quoted;
if (c == '\n' && !_quoted)
{
Records++;
_pending = false;
}
else _pending = true;
}
}
/// <summary>I record, contando anche l'ultimo se il testo non finisce con un a capo.</summary>
public long Total => Records + (_pending ? 1 : 0);
}
/// <summary>Lettore dei record del CSV di COPY (virgola, virgolette raddoppiate, NULL = campo vuoto senza virgolette).</summary>
internal sealed class CsvRecords(TextReader reader)
{
private readonly char[] _buffer = new char[1 << 16];
private int _pos, _len;
private bool _eof;
private async ValueTask<int> 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<string?[]?> NextAsync(CancellationToken ct)
{
if (await PeekAsync(ct).ConfigureAwait(false) < 0) return null;
var fields = new List<string?>();
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;
}
}
}
}
/// <summary>Limite di velocità in byte al secondo sul testo letto (0 o meno = nessun limite).</summary>
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);
}
}
/// <summary>
/// Lo spazio libero del volume che contiene <paramref name="dir"/>: 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.
/// </summary>
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;
}
}
/// <summary>L'impronta SHA-256 di un file già scritto, in esadecimale minuscolo.</summary>
public static async Task<string> 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));
}
/// <summary>Passa i byte al file e all'impronta.</summary>
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<byte> 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());
}
/// <summary>Un flusso che non chiude quello sotto (per il file senza gzip, come <c>leaveOpen</c>).</summary>
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<byte> 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());
}
}
+1 -23
View File
@@ -60,7 +60,7 @@ public sealed class CsvExport
_paths = paths;
_settings = settings;
_learning = learning;
_freeBytes = freeBytes ?? FreeBytes;
_freeBytes = freeBytes ?? BulkCopy.FreeBytes;
}
/// <summary>
@@ -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).");
}
/// <summary>
/// Lo spazio libero del volume che contiene <paramref name="dir"/>: 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.
/// </summary>
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<string> WriteLegendAsync(string prefix, DateTime from, DateTime to, Request req, long total, long exported, string? note,
List<string> columns, CancellationToken ct)
{
+3 -14
View File
@@ -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;
}
}