#!/usr/bin/env python3 """Fetch CODE final GIM daily files in batches through one curl process (connection reuse), at most one request per second, stopping on the first HTTP error. Usage: python3 -I fetch_code_gim_batch.py [--batch N] [--rate R] Same names, URLs, client name and logging as fetch_code_gim.py. After each batch every new file is checked (size > 1000 bytes, not an HTML/XML error page) and hashed. A 404 is logged and skipped (the batch resumes after it); a 403, 429, 5xx or an HTML/XML page stops the run. """ import datetime as dt import json import os import subprocess import sys import tempfile import time sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from fetch_code_gim import UA, BASE, name_for, sha256 # noqa: E402 def main(): dates_file, out_dir, log_path = sys.argv[1], sys.argv[2], sys.argv[3] batch = int(sys.argv[sys.argv.index("--batch") + 1]) if "--batch" in sys.argv else 25 rate = sys.argv[sys.argv.index("--rate") + 1] if "--rate" in sys.argv else "1/s" done = set() if os.path.exists(log_path): with open(log_path, encoding="utf-8") as f: for line in f: r = json.loads(line) if r.get("status") in (200, 404): done.add(r["file"]) todo = [] with open(dates_file, encoding="utf-8") as f: for line in f: line = line.strip() if not line: continue d = dt.date.fromisoformat(line) rel = "%04d/%s" % (d.year, name_for(d)) if rel in done: continue todo.append((d, rel)) print("to fetch: %d files" % len(todo), flush=True) t_start = time.time() n_ok = 0 k = 0 with open(log_path, "a", encoding="utf-8", newline="\n") as log: while k < len(todo): chunk = todo[k:k + batch] for d, rel in chunk: os.makedirs(os.path.join(out_dir, "%04d" % d.year), exist_ok=True) cfg = tempfile.NamedTemporaryFile("w", suffix=".curlrc", delete=False, encoding="utf-8", newline="\n") for d, rel in chunk: url = "%s/%04d/%s" % (BASE, d.year, name_for(d)) dest = os.path.join(out_dir, rel).replace("\\", "/") + ".part" cfg.write('url = "%s"\noutput = "%s"\n' % (url, dest)) cfg.close() t0 = time.time() p = subprocess.run( ["curl", "-sS", "-L", "-A", UA, "--fail", "--fail-early", "--rate", rate, "--max-time", "120", "-K", cfg.name, "-w", "%{http_code} %{size_download} %{content_type} %{url_effective}\\n"], capture_output=True, text=True) os.remove(cfg.name) secs = time.time() - t0 lines = [ln for ln in (p.stdout or "").splitlines() if ln.strip()] stop = None advanced = 0 for idx, (d, rel) in enumerate(chunk): if idx >= len(lines): break parts = lines[idx].split(" ", 3) status = int(parts[0]) if parts[0].isdigit() else -1 url = "%s/%04d/%s" % (BASE, d.year, name_for(d)) dest = os.path.join(out_dir, rel) part = dest + ".part" rec = {"date": d.isoformat(), "file": rel, "url": url, "final_url": parts[3] if len(parts) > 3 else "", "status": status, "content_type": parts[2] if len(parts) > 2 else "", "fetched_utc": dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), "batch_seconds": round(secs, 1)} bad_body = False if os.path.exists(part): with open(part, "rb") as f: head = f.read(256).lstrip().lower() bad_body = head.startswith(b"<") or os.path.getsize(part) <= 1000 if status == 200 and os.path.exists(part) and not bad_body: os.replace(part, dest) rec["bytes"] = os.path.getsize(dest) rec["sha256"] = sha256(dest) n_ok += 1 elif status == 404: rec["bytes"] = 0 rec["error"] = "404: no such file on the server (logged, skipped)" if os.path.exists(part): os.remove(part) else: rec["bytes"] = os.path.getsize(part) if os.path.exists(part) else 0 if os.path.exists(part): os.remove(part) rec["error"] = "HTML/XML or tiny answer instead of data" if bad_body else "unexpected status" stop = (status, url) log.write(json.dumps(rec) + "\n") advanced = idx + 1 if stop: break log.flush() print("%s batch %d-%d: %d lines, %.1f s, total ok %d" % ( dt.datetime.now(dt.timezone.utc).strftime("%H:%M:%SZ"), k, k + len(chunk) - 1, len(lines), secs, n_ok), flush=True) if stop: print("STOP: status %s for %s; stderr: %s" % (stop[0], stop[1], (p.stderr or "").strip()[:300]), flush=True) sys.exit(2) if advanced == 0: print("STOP: curl returned no transfer lines; rc=%s stderr: %s" % (p.returncode, (p.stderr or "").strip()[:300]), flush=True) sys.exit(3) if p.returncode != 0 and advanced < len(chunk) and lines and lines[-1].split(" ", 1)[0] == "200": # curl stopped after a transfer that printed no status line: stop rather than loop print("STOP: curl rc=%s after %d transfers without a status for the next; stderr: %s" % ( p.returncode, advanced, (p.stderr or "").strip()[:300]), flush=True) sys.exit(4) k += advanced print("done: %d new files in %.1f s" % (n_ok, time.time() - t_start), flush=True) if __name__ == "__main__": main()