"""Build the perf site, one static app that reads every run from okami.mom's records.""" from __future__ import annotations import argparse import hashlib import html import http.server import json from pathlib import Path import re import 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""" albedo perf
""" 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)