"""Publish runs to okami.mom's repo and keep the one perf site current. Records (rkey = commit sha) are the store: a run is its record and its result blob, and nothing per run is deployed. The `albedo-perf` site is a static app that reads the records at view time; it is deployed only when its own files change, from a push or manual run on main, never from another branch or a PR. """ from __future__ import annotations import argparse from datetime import datetime, timezone import json import os from pathlib import Path import subprocess import tempfile import time import urllib.error from records import SITE, SITE_URL, Repo, http, run_url from render import SCANNER, build_site, read_result, summary def committed_at(commit): return subprocess.check_output( ["git", "show", "-s", "--format=%cI", commit], text=True ).strip() def now(): return ( datetime.now(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z") ) def served_version(): """The version the site serves now, or None when it serves none.""" try: # The query keeps any cache between here and the site out of the answer. served = json.loads(http(f"{SITE_URL}version.json?t={time.time_ns()}")) except (urllib.error.HTTPError, ValueError): # An undeployed path answers index.html under SPA fallback: not JSON. return None return served.get("version") if isinstance(served, dict) else None def should_deploy(event, ref, served, built): """Deploy only a changed app, and only from a push or manual run on main.""" on_main = ref in ("main", "refs/heads/main") return on_main and event in ("push", "manual") and served != built def deploy(directory, password): try: deployment = subprocess.run( [ "wispctl", "deploy", "okami.mom", "--path", str(directory), "--site", SITE, "--spa", "--password", password, "--yes", "--quiet", ], timeout=600, ) except subprocess.TimeoutExpired: raise RuntimeError("wisp deploy timed out") from None if deployment.returncode: raise RuntimeError(f"wisp deploy exited {deployment.returncode}") def update_site(event, ref, password): """Deploy the site if this checkout's app differs from the served one.""" with tempfile.TemporaryDirectory(prefix="albedo-perf-site-") as scratch: built = build_site(scratch) served = served_version() if not should_deploy(event, ref, served, built): reason = "unchanged" if served == built else f"not deployed from {event}" print(f"perf site: {reason} ({(served or 'none')[:12]})", flush=True) return deploy(scratch, password) # A deploy is served within seconds; this reads, never redeploys. for _ in range(24): if served_version() == built: print(f"perf site: deployed {built[:12]} at {SITE_URL}", flush=True) return time.sleep(5) raise RuntimeError(f"{SITE_URL} did not serve version {built[:12]} in two minutes") def publish(result_path, password): """Record one replay run and return its page URL.""" result = read_result(result_path) if not result["gated"]: raise ValueError("an unfinished replay has no gated numbers to publish") repo = Repo(password) blobs = {"result": repo.upload(Path(result_path).read_bytes())} created = now() def value(rkey): record = { "commit": result["commit"], "baseCommit": result["base_commit"] or "", "event": result["event"], "ref": result["ref"], "verdict": result["verdict"], "url": run_url(rkey), "committedAt": committed_at(result["commit"]), "createdAt": created, # atproto records have no floats: numbers travel as JSON text. "summary": json.dumps(summary(result), separators=(",", ":")), **blobs, } SCANNER.check(record, label="run record") return record url = run_url(repo.claim(result["commit"], value)) print(f"perf report: {url}", flush=True) return url if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) modes = parser.add_subparsers(dest="mode", required=True) replay = modes.add_parser( "replay", help="record a replay run, then deploy the site if it changed" ) replay.add_argument("result", type=Path) site = modes.add_parser("site", help="deploy the site if it changed") site.add_argument("--event", required=True) site.add_argument("--ref", required=True) args = parser.parse_args() password = os.environ["WISP_APP_PASSWORD"] if args.mode == "replay": publish(args.result, password) result = read_result(args.result) update_site(result["event"], result["ref"], password) else: update_site(args.event, args.ref, password)