Make each deploy visible at once: versioned assets, no-cache HTML, build ETags on the API
Browse filesFiles changed (2)
- app.py+21-5
- tests/test_api.py+11
1234561 unmodified line89101112131419 unmodified lines3435363738394041424344469 unmodified lines514515516517518519520"""PyBot Data Explorer: read-only API + UI over the PyBot swarm run release artifacts."""from contextlib import asynccontextmanagerimport base64, json, os, re, sqlite3, subprocess, sys, threading, timefrom datetime import datetime, timezonefrom functools import cachefrom pathlib import Path1 unmodified linefrom fastapi import FastAPI, HTTPException, Queryfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.middleware.gzip import GZipMiddlewarefrom fastapi.responses import FileResponse, PlainTextResponsefrom fastapi.staticfiles import StaticFilesROOT = Path(__file__).parent19 unmodified linesapp.add_middleware(GZipMiddleware, minimum_size=2000)@app.middleware("http")async def cache_headers(request, call_next):response = await call_next(request)if request.url.path.startswith("/api/") and response.status_code == 200:response.headers["Cache-Control"] = "public, max-age=3600" # the data never changesreturn response469 unmodified lines@app.get("/commits", include_in_schema=False)@app.get("/agent/{name}", include_in_schema=False)def ui():return FileResponse(ROOT / "static" / "index.html")app.mount("/static", StaticFiles(directory=ROOT / "static"), name="static")1234561 unmodified line89101112131419 unmodified lines343536373839404142434445464748495051525354555657469 unmodified lines527528529530531532533534535536"""PyBot Data Explorer: read-only API + UI over the PyBot swarm run release artifacts."""from contextlib import asynccontextmanagerimport base64, hashlib, json, os, re, sqlite3, subprocess, sys, threading, timefrom datetime import datetime, timezonefrom functools import cachefrom pathlib import Path1 unmodified linefrom fastapi import FastAPI, HTTPException, Queryfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.middleware.gzip import GZipMiddlewarefrom fastapi.responses import FileResponse, HTMLResponse, PlainTextResponse, Responsefrom fastapi.staticfiles import StaticFilesROOT = Path(__file__).parent19 unmodified linesapp.add_middleware(GZipMiddleware, minimum_size=2000)# One id per deploy, from the code and data that shipped; it versions asset URLs and API ETags,# so a redeploy shows at once while unchanged answers still revalidate with a cheap 304.BUILD = hashlib.sha1(b"".join(p.read_bytes() for p in sorted((ROOT / "static").glob("*.*")) + [ROOT / "app.py"])+ "".join(f"{p.name}:{p.stat().st_size}:{p.stat().st_mtime_ns}" for p in sorted(DATA.glob("*.sqlite"))).encode()).hexdigest()[:12]ETAG = f'"{BUILD}"'@app.middleware("http")async def cache_headers(request, call_next):path = request.url.pathif path.startswith("/api/") and request.headers.get("if-none-match") == ETAG:return Response(status_code=304, headers={"ETag": ETAG, "Cache-Control": "no-cache"})response = await call_next(request)if path.startswith("/api/") and response.status_code == 200:response.headers["ETag"], response.headers["Cache-Control"] = ETAG, "no-cache"elif path.startswith("/static/"):response.headers["Cache-Control"] = "public, max-age=31536000, immutable" if request.query_params.get("v") == BUILD else "no-cache"return response469 unmodified lines@app.get("/commits", include_in_schema=False)@app.get("/agent/{name}", include_in_schema=False)def ui():return HTMLResponse(INDEX, headers={"Cache-Control": "no-cache"})INDEX = re.sub(r'(/static/[\w.]+\.(?:js|css))"', rf'\1?v={BUILD}"', (ROOT / "static" / "index.html").read_text())app.mount("/static", StaticFiles(directory=ROOT / "static"), name="static")
126 unmodified lines127128129126 unmodified linesassert {x["title"]: x["agent"] for x in h["highlights"]}["Most tool calls"] == "ann"assert any(m["text"].startswith("First merged PR: #7") for m in h["moments"])assert c.get("/api/agents?sort=drop").status_code == 400 and c.get("/api/agents/nobody").status_code == 404126 unmodified lines127128129130131132133134135136137138139140126 unmodified linesassert {x["title"]: x["agent"] for x in h["highlights"]}["Most tool calls"] == "ann"assert any(m["text"].startswith("First merged PR: #7") for m in h["moments"])assert c.get("/api/agents?sort=drop").status_code == 400 and c.get("/api/agents/nobody").status_code == 404def test_caching_by_build(client):c, _ = clientimport apphtml = c.get("/").textassert f"/static/app.js?v={app.BUILD}" in html and c.get("/").headers["cache-control"] == "no-cache"r = c.get("/api/scores")assert r.headers["etag"] == app.ETAG and c.get("/api/scores", headers={"If-None-Match": app.ETAG}).status_code == 304assert "immutable" in c.get(f"/static/app.js?v={app.BUILD}").headers["cache-control"]assert c.get("/static/app.js").headers["cache-control"] == "no-cache"
app.py+21-5
tests/test_api.py+11