|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""One-time import of contest recap datasets into the PostgreSQL serving layer. |
| 3 | +
|
| 4 | + import_recaps.py --contest-dir /var/tmp/contests # import every recap in recaps.yaml |
| 5 | + import_recaps.py --contest-dir /var/tmp/contests --dry-run |
| 6 | +
|
| 7 | +WHY THIS IS A ONE-TIME IMPORT AND NOT A REFRESH JOB. |
| 8 | +
|
| 9 | +Contest recaps are static. ARRL DX CW and SSB ran in March 2026; the contests are over, the |
| 10 | +signatures are frozen, and no amount of re-reading will change a number. There is nothing to |
| 11 | +keep fresh — so this is not part of refresh.py's cadence groups. It runs once per contest, |
| 12 | +when that contest's dataset is built, and never again. |
| 13 | +
|
| 14 | +WHY IT READS SQLITE RATHER THAN REBUILDING FROM CLICKHOUSE. |
| 15 | +
|
| 16 | +The datasets are built from ClickHouse by ionis-devel/contests/export_contest_sqlite.py, so |
| 17 | +rebuilding looks tempting. It is not safe: that script's current PSKR query hardcodes |
| 18 | +avg_distance = 0, while the published recap pages show real distances (160m: 3,476 km). The |
| 19 | +files on disk do not match what the current script would produce, and reproducing them means |
| 20 | +resolving that provenance question first. Importing the artifact that actually rendered the |
| 21 | +published pages has no such risk. |
| 22 | +
|
| 23 | +WHAT THIS ENDS. |
| 24 | +
|
| 25 | +publish.py read 1.3 GB of SQLite at render time, off a filesystem that existed only on the |
| 26 | +9975. That coupling is what broke the contest pages when publishing moved to publish-1 — the |
| 27 | +loader warned, returned None, and the run still reported "2 recap(s) loaded" and exited 0. |
| 28 | +After this import nothing reads SQLite at render time, on any host. |
| 29 | +""" |
| 30 | +from __future__ import annotations |
| 31 | + |
| 32 | +import argparse |
| 33 | +import datetime as dt |
| 34 | +import json |
| 35 | +import os |
| 36 | +import sqlite3 |
| 37 | +import sys |
| 38 | +from pathlib import Path |
| 39 | + |
| 40 | +import psycopg |
| 41 | +import yaml |
| 42 | + |
| 43 | +ROOT = Path(os.environ.get("HAMSTATS_ROOT") or Path(__file__).parent) |
| 44 | +DB_FILE = os.environ.get("HAMSTATS_DB_FILE", "/etc/hamstats/db-rw.dsn") |
| 45 | + |
| 46 | +sys.path.insert(0, str(ROOT)) |
| 47 | +from publish import load_recap_data_sqlite # noqa: E402 |
| 48 | + |
| 49 | +# Static data does not expire. The serving layer's staleness check compares refreshed_at |
| 50 | +# against max_age, and a recap that is a year old is exactly as correct as one imported today. |
| 51 | +STATIC = "100 years" |
| 52 | + |
| 53 | +DATASETS = ("band_summary", "hourly_activity", "solar_timeline", "distance_stats") |
| 54 | + |
| 55 | + |
| 56 | +def main() -> int: |
| 57 | + ap = argparse.ArgumentParser(description=__doc__) |
| 58 | + ap.add_argument("--contest-dir", required=True, |
| 59 | + help="directory holding the recap .sqlite files") |
| 60 | + ap.add_argument("--dry-run", action="store_true", help="read and report, write nothing") |
| 61 | + args = ap.parse_args() |
| 62 | + |
| 63 | + os.environ["CONTEST_DATA_DIR"] = args.contest_dir |
| 64 | + import publish |
| 65 | + publish.CONTEST_DATA_DIR = Path(args.contest_dir) |
| 66 | + |
| 67 | + recaps = yaml.safe_load((ROOT / "data" / "recaps.yaml").read_text()) or [] |
| 68 | + print(f"Importing {len(recaps)} recap(s) from {args.contest_dir}") |
| 69 | + |
| 70 | + staged, missing = [], [] |
| 71 | + for recap in recaps: |
| 72 | + slug = recap.get("slug") |
| 73 | + # load_recap_data is publish.py's OWN loader, unchanged. Whatever it produced when |
| 74 | + # rendering from SQLite is exactly what lands in PostgreSQL — the import cannot drift |
| 75 | + # from the thing it is replacing, because it is the same code. |
| 76 | + data = load_recap_data_sqlite(recap) |
| 77 | + if data is None: |
| 78 | + print(f" MISSING {slug}: no dataset at {args.contest_dir}/{recap.get('dataset')}") |
| 79 | + missing.append(slug) |
| 80 | + continue |
| 81 | + for key in DATASETS: |
| 82 | + rows = data.get(key) or [] |
| 83 | + staged.append((f"recap:{slug}:{key}", rows)) |
| 84 | + print(f" {slug:22} {key:18} {len(rows):>5} rows") |
| 85 | + |
| 86 | + if missing: |
| 87 | + # Importing a partial set would leave some recaps rendering empty with no indication |
| 88 | + # that anything is wrong -- the exact failure this import exists to end. |
| 89 | + print(f"ERROR: {len(missing)} recap(s) had no dataset: {', '.join(missing)}. " |
| 90 | + f"Nothing written.", file=sys.stderr) |
| 91 | + return 1 |
| 92 | + |
| 93 | + if args.dry_run: |
| 94 | + print("Dry run — nothing written.") |
| 95 | + return 0 |
| 96 | + |
| 97 | + dsn = Path(DB_FILE).read_text().strip() |
| 98 | + with psycopg.connect(dsn, autocommit=False) as conn: |
| 99 | + conn.execute((ROOT / "sql" / "serving_schema.sql").read_text()) |
| 100 | + for name, rows in staged: |
| 101 | + conn.execute( |
| 102 | + """ |
| 103 | + INSERT INTO serving.query_results |
| 104 | + (name, payload, row_count, refreshed_at, max_age, |
| 105 | + source_rows_read, source_elapsed_ms) |
| 106 | + VALUES (%s, %s::jsonb, %s, now(), %s::interval, NULL, NULL) |
| 107 | + ON CONFLICT (name) DO UPDATE SET |
| 108 | + payload = EXCLUDED.payload, |
| 109 | + row_count = EXCLUDED.row_count, |
| 110 | + refreshed_at = EXCLUDED.refreshed_at, |
| 111 | + max_age = EXCLUDED.max_age |
| 112 | + """, |
| 113 | + (name, json.dumps(rows, default=_json_default), len(rows), STATIC), |
| 114 | + ) |
| 115 | + conn.commit() |
| 116 | + print(f"Wrote {len(staged)} recap dataset(s) to the serving layer.") |
| 117 | + return 0 |
| 118 | + |
| 119 | + |
| 120 | +def _json_default(o): |
| 121 | + if isinstance(o, (dt.datetime, dt.date)): |
| 122 | + return o.isoformat() |
| 123 | + raise TypeError(f"{type(o).__name__} is not JSON-serialisable: {o!r}") |
| 124 | + |
| 125 | + |
| 126 | +if __name__ == "__main__": |
| 127 | + sys.exit(main()) |
0 commit comments