#!/usr/bin/env python3
"""Job #4545 (route 148 step check): fetch the served record this comparison needs.
Public, credential-free endpoints only:
GET /projects/twin-primes/return/
GET /projects/twin-primes/research-routes/
GET /files/
Writes every retrieved record verbatim into ./served/ plus a manifest of what exists, so the
step check can be re-read from raw bytes. The comparison window is rebuilt over a public id
range (routeless returns included) rather than trusting the brief's named list.
"""
import json
import os
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(HERE, "..", "..", ".solveathome", "private", "lib"))
from served import served_evidence as se # noqa: E402
DEST = os.path.join(HERE, "served")
# route 148's own returns and the step-setter; then everything that could have been recorded
# after the step-setter (inclusive scan past the live head at fetch time).
IDS = [1541, 1549, 1562, 1837, 2019, 2026]
RANGE = range(1838, 2071)
def get(url, path, binary=False):
try:
raw = se.fetch_bytes(url, timeout=60)
except Exception as exc: # missing ids 404; record the absence, do not invent
return {"path": path, "error": "%s" % type(exc).__name__}
with open(os.path.join(DEST, os.path.basename(path)), "wb") as fh:
fh.write(raw)
if binary:
return {"path": path, "bytes": len(raw)}
try:
body = json.loads(raw)
except Exception:
return {"path": path, "bytes": len(raw), "error": "not-json"}
return {"path": path, "bytes": len(raw), "id": body.get("id"),
"route": body.get("research_route_id"), "created_at": body.get("created_at"),
"type": body.get("type"), "status": body.get("status")}
def main():
os.makedirs(DEST, exist_ok=True)
manifest = []
for rid in sorted(set(list(IDS) + list(RANGE))):
manifest.append(get(se.return_url(se.DEFAULT_BASE, rid), "return-%d.json" % rid))
manifest.append(get(se.route_url(se.DEFAULT_BASE, 148), "route-148.json"))
# the files served with route 148's own returns, by published sha256
for rid in IDS:
rp = os.path.join(DEST, "return-%d.json" % rid)
if not os.path.exists(rp):
continue
rec = json.load(open(rp, encoding="utf-8"))
for f in (rec.get("files") or []):
sha = f.get("sha256")
name = f.get("name") or "unnamed"
manifest.append(get(se.file_url(se.DEFAULT_BASE, sha),
"f%d_%s" % (rid, name), binary=True))
with open(os.path.join(HERE, "fetch_manifest.json"), "w", encoding="utf-8",
newline="\n") as fh:
json.dump(manifest, fh, indent=1)
present = [m for m in manifest if "error" not in m]
print("fetched %d records (%d return records, %d attached files)"
% (len(present),
len([m for m in present if m["path"].startswith("return")]),
len([m for m in present if m["path"].startswith("f") and "_" in m["path"]])))
if __name__ == "__main__":
main()