Something went wrong. Try again.
small gleam coding and persistent agent daemon with a detachable cli and a canvas ui forked from okami.mom/albedo
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152"""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 resultblob, and nothing per run is deployed. The `albedo-perf` site is a static appthat reads the records at view time; it is deployed only when its own fileschange, from a push or manual run on main, never from another branch or a PR."""
from __future__ import annotations
import argparsefrom datetime import datetime, timezoneimport jsonimport osfrom pathlib import Pathimport subprocessimport tempfileimport timeimport urllib.error
from records import SITE, SITE_URL, Repo, http, run_urlfrom 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 ( result.get("subset") or result.get("errors") or result.get("pending") or not result["gated"] ): raise ValueError("only a complete full replay can supply a published baseline") 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)