Something went wrong. Try again.
small gleam coding and (not yet) persistent agent daemon with a detachable cli forked from okami.mom/albedo
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135"""Build the perf site, one static app that reads every run from okami.mom's records."""
from __future__ import annotations
import argparseimport hashlibimport htmlimport http.serverimport jsonfrom pathlib import Pathimport reimport sys
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))from safety import SecretScanner # noqa: E402
from records import COLLECTION, DID # noqa: E402
SCANNER = SecretScanner()
def write_file(path, content): SCANNER.check(content, label=str(path)) if isinstance(content, bytes): Path(path).write_bytes(content) else: Path(path).write_text(content)
def read_result(path): content = Path(path).read_text() SCANNER.check(content, label=str(path)) result = json.loads(content) if result["schema"] != 1 or result["mode"] != "replay": raise ValueError(f"unsupported performance result: {path}") if not re.fullmatch(r"[0-9a-f]{40}", result["commit"]): raise ValueError("commit must be a full lowercase SHA") return result
ECHARTS = "https://cdn.jsdelivr.net/npm/echarts@6.1.0/dist/echarts.min.js"# sha384 of dist/echarts.min.js from the npm tarball, checked against the# registry's sha512 and against jsDelivr's copy (byte-identical).ECHARTS_SRI = "sha384-C2iskrW/uPW46KzOjrvJIQo4YkV8lkD+QS0CrDN18IIPIpT/g2USu8bTP3nvmIAD"
def summary(result): """The numbers pages compare across runs, small enough for every record.""" return { "gated": result["gated"], "scenarios": { name: { "memory": {m: v["median"] for m, v in scenario["memory"].items()}, "wire": scenario["wire"], } for name, scenario in result["scenarios"].items() }, }
ASSETS = ("app.js", "routes.js", "style.css")
def page(config, assets_version): """The one HTML page every route is served; the app draws the route.""" payload = json.dumps(config, separators=(",", ":")).replace("<", "\\u003c") # Absolute paths: wisp rewrites them to the site's root on sites.wisp.place. v = html.escape(assets_version, quote=True) return f"""<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>albedo perf</title><link rel="stylesheet" href="/style.css?v={v}"></head><body><div id="app"></div><noscript><main><p>This page draws albedo's perf runs from the<code>{html.escape(COLLECTION)}</code> records in okami.mom's repo and needs JavaScript.</p></main></noscript><script type="application/json" id="config">{payload}</script><script src="{ECHARTS}" integrity="{ECHARTS_SRI}" crossorigin="anonymous"></script><script src="/routes.js?v={v}"></script><script src="/app.js?v={v}"></script></body></html>"""
def digest(named): """sha256 over (name, bytes) pairs in name order, as hex.""" hasher = hashlib.sha256() for name, content in sorted(named.items()): hasher.update(f"{name}\0{len(content)}\0".encode()) hasher.update(content) return hasher.hexdigest()
def build_site(directory, did=DID, pds=None): """Write the site and return its version, a hash of everything it serves.""" directory = Path(directory) directory.mkdir(parents=True, exist_ok=True) here = Path(__file__).parent named = {name: (here / name).read_bytes() for name in ASSETS} config = {"did": did, "pds": pds, "collection": COLLECTION} named["index.html"] = page(config, digest(named)[:12]).encode() version = digest(named) named["version.json"] = json.dumps({"version": version}).encode() for name, content in named.items(): write_file(directory / name, content) return version
def serve(directory, port): """Serve a built site locally, answering unknown paths with index.html as wisp does.""" directory = Path(directory)
class Handler(http.server.SimpleHTTPRequestHandler): def __init__(self, *args, **kwargs): super().__init__(*args, directory=str(directory), **kwargs)
def send_head(self): path = self.path.split("?", 1)[0] if not (directory / path.lstrip("/")).is_file(): self.path = "/index.html" return super().send_head()
print(f"serving http://127.0.0.1:{port}/", flush=True) http.server.ThreadingHTTPServer(("127.0.0.1", port), Handler).serve_forever()
if __name__ == "__main__": parser = argparse.ArgumentParser( description="Build the perf site for a local preview." ) parser.add_argument("site", type=Path) parser.add_argument("--did", default=DID, help="repo to read runs from") parser.add_argument("--pds", help="PDS used when the DID does not resolve") parser.add_argument("--serve", type=int, metavar="PORT", help="then serve it") args = parser.parse_args() print(build_site(args.site, args.did, args.pds)) if args.serve: serve(args.site, args.serve)