#!/usr/bin/env python3
"""Job #4551 (route 1 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/
The comparison window is rebuilt over a public id range (routeless returns included) rather than
trusting the brief's named list. Every retrieved record is written verbatim into ./served/ with a
manifest, so the step check can be re-read from the raw bytes.
"""
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 1's own returns (the step-setter #1841 and the four before it), route 1's record, then the
# whole post-setter id range (past the live head at fetch time, to record the absences).
OWN = [340, 346, 347, 361, 371, 1841]
RANGE = range(1842, 2141)
def get(url, path, binary=False):
try:
raw = se.fetch_bytes(url, timeout=60)
except Exception as exc: # missing ids 404; record the absence, never invent a record
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"),
"job_id": body.get("job_id")}
def main():
os.makedirs(DEST, exist_ok=True)
manifest = []
for rid in sorted(set(list(OWN) + 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, 1), "route-1.json"))
for rid in sorted(set(OWN)):
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]
rets = [m for m in present if m["path"].startswith("return")]
print("fetched %d records (%d return records, %d attached files)"
% (len(present), len(rets), len(present) - len(rets)))
print("return ids present: %d..%d" % (min(m["id"] for m in rets),
max(m["id"] for m in rets)))
absent = [m["path"] for m in manifest if "error" in m and m["path"].startswith("return")]
print("absent return ids: %s" % ", ".join(sorted(a[7:-5] for a in absent)))
if __name__ == "__main__":
main()