feat(admin dashboard): add admin dashboard

This commit is contained in:
shay
2026-05-11 18:25:09 -04:00
parent ab7c9b32aa
commit 00bf46968a
18 changed files with 426 additions and 6 deletions
+4
View File
@@ -3,6 +3,7 @@ import './index.css'
import { SearchScreen } from './screens/SearchScreen'
import { WorkshopScreen } from './screens/WorkshopScreen'
import { ResultScreen } from './screens/ResultScreen'
import { DevScreen } from './screens/DevScreen'
import { AuthButton } from './components/AuthButton'
import type { WidgetData } from './lib/renderWidgets'
import { DEMO_WIDGET_DATA } from './lib/demoData'
@@ -69,6 +70,9 @@ function readWidgetStatus(r: Response): WidgetStatus {
}
export default function App() {
if (typeof window !== 'undefined' && window.location.pathname === '/dev') {
return <DevScreen />
}
const [me, setMe] = useState<Me>({ login: null })
const [step, setStep] = useState<Step>('search')
const [username, setUsername] = useState('')
+57 -1
View File
@@ -25,7 +25,7 @@ from functools import wraps
from threading import BoundedSemaphore, Lock
from flask import Flask, jsonify, request, Response, send_from_directory, session
from . import auth, config, db, fetcher_client, placeholder, processor
from . import analytics, auth, config, db, fetcher_client, placeholder, processor
from .themes import THEMES
from .utils import is_valid_username, settings_size_ok
from .widgets import render_grade_widget
@@ -600,6 +600,21 @@ def internal_data_ready():
return jsonify({"queued": True, "job_id": job_id}), 200
@app.route("/internal/analytics/events", methods=["POST"])
def internal_analytics_events():
token = request.headers.get("X-Internal-Token", "")
if not config.FETCHER_INTERNAL_TOKEN or not hmac.compare_digest(
token, config.FETCHER_INTERNAL_TOKEN
):
return jsonify({"error": "unauthorized"}), 401
body = request.get_json(silent=True) or {}
events = body.get("events", [])
if not isinstance(events, list):
return jsonify({"error": "bad_request"}), 400
n = analytics.ingest_batch(events)
return jsonify({"ingested": n})
@app.route("/api/<username>", methods=["GET"])
@rate_limited("read")
def get_widget(username: str):
@@ -828,12 +843,15 @@ def _serve_profile_widget(username: str) -> Response:
payload = result.get("data") or {}
if payload.get("error") == "not_found":
return _placeholder_response("not_found", username, theme=theme)
t0 = time.monotonic()
grade = processor.compute_grade(
payload,
custom_tags=settings_row["settings"].get("custom_tags"),
)
ws = (settings_row["settings"].get("widget_settings") or {}).get("grade")
svg = render_grade_widget(grade, theme, settings=ws)
analytics.record_render(username, "grade",
int((time.monotonic() - t0) * 1000))
except Exception:
log.exception("profile widget render failed for %s", username)
return _placeholder_response("building", username, theme=theme)
@@ -957,6 +975,32 @@ def refresh(username: str):
return jsonify({"refreshed": True, "job_id": job_id})
@app.route("/api/dev/summary", methods=["GET"])
@auth.require_basic_auth
def dev_summary():
return jsonify(analytics.query_summary())
@app.route("/api/dev/users", methods=["GET"])
@auth.require_basic_auth
def dev_users():
q = request.args.get("q", "")
sort = request.args.get("sort", "requests")
return jsonify(analytics.query_users(q=q, sort=sort))
@app.route("/api/dev/latency", methods=["GET"])
@auth.require_basic_auth
def dev_latency():
return jsonify(analytics.query_latency())
@app.route("/api/dev/health", methods=["GET"])
@auth.require_basic_auth
def dev_health():
return jsonify(analytics.query_health())
@app.errorhandler(413)
def _too_large(_e):
return jsonify({"error": "payload_too_large"}), 413
@@ -983,8 +1027,20 @@ def _invalidate_widgets_on_new_build() -> None:
def main():
db.init_dbs()
_invalidate_widgets_on_new_build()
analytics.start_flush_thread()
app.run(host="0.0.0.0", port=config.PORT)
def _boot_analytics_for_gunicorn():
"""Gunicorn imports the module without calling main(); fire the daemon
flush thread here so render timings actually get flushed in production.
Idempotent — start_flush_thread checks for a running thread."""
try:
analytics.start_flush_thread()
except Exception:
log.exception("analytics boot failed")
_boot_analytics_for_gunicorn()
if __name__ == "__main__":
main()
+40
View File
@@ -78,3 +78,43 @@ def require_same_origin(fn):
return jsonify({"error": "bad_origin"}), 403
return fn(*args, **kwargs)
return wrapper
import base64
import hmac as _hmac
from functools import wraps as _wraps
from flask import jsonify as _jsonify, request as _request
from . import config as _config
def require_basic_auth(fn):
"""HTTP Basic Auth gate for the /dev dashboard. Returns 503 if either
credential env var is unset so a missing-secret deploy fails closed.
Constant-time comparison on the decoded user+pass concatenation keeps
the timing channel narrow without leaking length."""
@_wraps(fn)
def wrapper(*args, **kwargs):
u = _config.DEV_DASHBOARD_USER
p = _config.DEV_DASHBOARD_PASSWORD
if not u or not p:
return _jsonify({"error": "dashboard_disabled"}), 503
hdr = _request.headers.get("Authorization", "")
if not hdr.startswith("Basic "):
return _unauth()
try:
decoded = base64.b64decode(hdr[6:].encode("ascii"), validate=True).decode("utf-8")
except Exception:
return _unauth()
expected = f"{u}:{p}"
if not _hmac.compare_digest(decoded, expected):
return _unauth()
return fn(*args, **kwargs)
return wrapper
def _unauth():
resp = _jsonify({"error": "unauthorized"})
resp.status_code = 401
resp.headers["WWW-Authenticate"] = 'Basic realm="dev"'
return resp
+6
View File
@@ -118,6 +118,12 @@ TAG_TOPIC_MAP = {
PORT = int(os.getenv("GENERATOR_PORT", "5002"))
SETTINGS_DB_PATH = os.getenv("GENERATOR_SETTINGS_DB_PATH", "./data/settings.db")
WIDGETS_DB_PATH = os.getenv("GENERATOR_WIDGETS_DB_PATH", "./data/widgets.db")
ANALYTICS_DB_PATH = os.getenv("GENERATOR_ANALYTICS_DB_PATH", "./data/analytics.db")
ANALYTICS_RETENTION_DAYS = int(os.getenv("ANALYTICS_RETENTION_DAYS", "14"))
ANALYTICS_FLUSH_SECONDS = int(os.getenv("ANALYTICS_FLUSH_SECONDS", "5"))
ANALYTICS_QUEUE_MAX = int(os.getenv("ANALYTICS_QUEUE_MAX", "2000"))
DEV_DASHBOARD_USER = os.getenv("DEV_DASHBOARD_USER", "")
DEV_DASHBOARD_PASSWORD = os.getenv("DEV_DASHBOARD_PASSWORD", "")
FETCHER_URL = os.getenv("FETCHER_URL", "http://localhost:5001")
FETCHER_INTERNAL_TOKEN = os.getenv("FETCHER_INTERNAL_TOKEN", "")
REDIS_URL = os.getenv("REDIS_URL", "")
+5 -1
View File
@@ -6,7 +6,7 @@ import logging
import os
import time
from . import config, db, fetcher_client
from . import analytics, config, db, fetcher_client
log = logging.getLogger("generator.cron")
@@ -47,6 +47,10 @@ def tick() -> dict:
failed += 1
if _TICK_INTER_USER_SLEEP_S > 0:
time.sleep(_TICK_INTER_USER_SLEEP_S)
try:
analytics.prune_old()
except Exception:
log.exception("analytics prune failed")
return {"enqueued": enqueued, "failed": failed, "skipped_queue_full": skipped_queue_full}
+35
View File
@@ -15,6 +15,7 @@ from . import config
SETTINGS_DB_PATH = config.SETTINGS_DB_PATH
WIDGETS_DB_PATH = config.WIDGETS_DB_PATH
ANALYTICS_DB_PATH = config.ANALYTICS_DB_PATH
_SETTINGS_SCHEMA = """
CREATE TABLE IF NOT EXISTS users (
@@ -85,6 +86,24 @@ CREATE INDEX IF NOT EXISTS idx_widgets_username ON widgets(username);
CREATE INDEX IF NOT EXISTS idx_widget_data_username ON widget_data(username);
"""
_ANALYTICS_SCHEMA = """
CREATE TABLE IF NOT EXISTS events (
id INTEGER PRIMARY KEY AUTOINCREMENT,
ts INTEGER NOT NULL,
service TEXT NOT NULL,
kind TEXT NOT NULL,
username TEXT,
endpoint TEXT,
widget TEXT,
status INTEGER,
latency_ms INTEGER NOT NULL,
cache_hit INTEGER
);
CREATE INDEX IF NOT EXISTS idx_events_ts ON events(ts);
CREATE INDEX IF NOT EXISTS idx_events_user_ts ON events(username, ts);
CREATE INDEX IF NOT EXISTS idx_events_endpoint_ts ON events(endpoint, ts);
"""
def _now() -> str:
return datetime.utcnow().isoformat(timespec="seconds") + "Z"
@@ -123,6 +142,21 @@ def _widgets_conn():
conn.close()
@contextmanager
def analytics_conn():
conn = _open(ANALYTICS_DB_PATH)
try:
yield conn
finally:
conn.close()
def init_analytics_db() -> None:
with analytics_conn() as c:
c.executescript(_ANALYTICS_SCHEMA)
c.commit()
def init_dbs() -> None:
with _settings_conn() as c:
c.executescript(_SETTINGS_SCHEMA)
@@ -138,6 +172,7 @@ def init_dbs() -> None:
with _widgets_conn() as c:
c.executescript(_WIDGETS_SCHEMA)
c.commit()
init_analytics_db()
def settings_hash(settings: dict) -> str:
+10 -1
View File
@@ -13,7 +13,7 @@ import logging
import time
from dataclasses import asdict
from . import cache, config, db, fetcher_client, placeholder, processor
from . import analytics, cache, config, db, fetcher_client, placeholder, processor
from .widgets import compose_widget
log = logging.getLogger("generator.worker")
@@ -53,12 +53,15 @@ def _render_and_persist(username: str, payload: dict, settings: dict, settings_h
cron-driven worker so embedded widgets keep ticking forward (streak
counter, etc.) as the fetcher refreshes the underlying data — without
waiting for the user to manually click Generate."""
t0 = time.monotonic()
widgets = _render_widgets(username, payload, settings)
db.put_widgets(username, settings_hash, widgets)
cache.Cache().delete(
f"widget:composite:{username}",
*[f"widget:{n}:{username}" for n in widgets],
)
analytics.record_render(username, "composite",
int((time.monotonic() - t0) * 1000))
def _render_widgets(username: str, payload: dict, settings: dict) -> dict[str, str]:
@@ -155,7 +158,10 @@ def render_composite_adhoc(username: str, override_settings: dict) -> str | None
if not payload or payload.get("error") == "not_found":
return None
effective = {**settings_row["settings"], **(override_settings or {})}
t0 = time.monotonic()
widgets = _render_widgets(username, payload, effective)
analytics.record_render(username, "composite",
int((time.monotonic() - t0) * 1000))
return widgets.get("composite")
@@ -178,11 +184,14 @@ def render_widgets_now(username: str) -> dict[str, str]:
cache.Cache().delete(f"widget:composite:{username}")
return {"composite": svg}
t0 = time.monotonic()
widgets = _render_widgets(username, payload, settings_row["settings"])
db.put_widgets(username, settings_row["settings_hash"], widgets)
db.point_current_widget(username, settings_row["settings_hash"])
c = cache.Cache()
c.delete(f"widget:composite:{username}", *[f"widget:{n}:{username}" for n in widgets])
analytics.record_render(username, "composite",
int((time.monotonic() - t0) * 1000))
log.info("rendered widgets on-demand for %s", username)
return widgets
+88
View File
@@ -15,6 +15,7 @@ def client(monkeypatch):
with tempfile.TemporaryDirectory() as d:
monkeypatch.setattr(dbmod, "SETTINGS_DB_PATH", os.path.join(d, "s.db"))
monkeypatch.setattr(dbmod, "WIDGETS_DB_PATH", os.path.join(d, "w.db"))
monkeypatch.setattr(dbmod, "ANALYTICS_DB_PATH", os.path.join(d, "a.db"))
dbmod.init_dbs()
# Configure OAuth fixture with allowed origins and insecure cookies for testing.
monkeypatch.setattr(cfg, "ALLOWED_ORIGINS", ("https://gh-stats.com",))
@@ -536,3 +537,90 @@ def test_per_login_mutate_rate_limit(client, monkeypatch):
# Third request should be rate-limited.
r3 = client.patch("/api/alice/settings", json={}, headers=h)
assert r3.status_code == 429
def test_internal_analytics_events_requires_token(client, monkeypatch):
monkeypatch.setattr(cfg, "FETCHER_INTERNAL_TOKEN", "secret")
r = client.post("/internal/analytics/events", json={"events": []})
assert r.status_code == 401
def test_internal_analytics_events_ingests(client, monkeypatch):
from src import analytics
monkeypatch.setattr(cfg, "FETCHER_INTERNAL_TOKEN", "secret")
analytics._reset_for_tests()
body = {
"events": [
{"ts": 1700000000, "service": "edge", "kind": "request",
"username": "alice", "endpoint": "/<u>", "widget": "composite",
"status": 200, "latency_ms": 12, "cache_hit": 1}
]
}
r = client.post("/internal/analytics/events",
headers={"X-Internal-Token": "secret"},
json=body)
assert r.status_code == 200
assert r.get_json()["ingested"] == 1
def _basic(user="admin", pw="pw"):
import base64
return {"Authorization": "Basic " + base64.b64encode(f"{user}:{pw}".encode()).decode()}
def test_dev_summary_requires_auth(client, monkeypatch):
monkeypatch.setattr(cfg, "DEV_DASHBOARD_USER", "admin")
monkeypatch.setattr(cfg, "DEV_DASHBOARD_PASSWORD", "pw")
r = client.get("/api/dev/summary")
assert r.status_code == 401
def test_dev_summary_returns_shape(client, monkeypatch):
from src import analytics
monkeypatch.setattr(cfg, "DEV_DASHBOARD_USER", "admin")
monkeypatch.setattr(cfg, "DEV_DASHBOARD_PASSWORD", "pw")
analytics._reset_for_tests()
import time as _time
analytics.ingest_batch([
{"ts": int(_time.time()) - 60, "service": "edge", "kind": "request",
"username": "alice", "endpoint": "/<u>", "widget": "composite",
"status": 200, "latency_ms": 11, "cache_hit": 1},
])
r = client.get("/api/dev/summary", headers=_basic())
assert r.status_code == 200
body = r.get_json()
for key in ("requests_7d", "active_users_7d", "p50_ms", "p95_ms",
"renders_7d", "avg_render_ms", "daily_requests"):
assert key in body
assert len(body["daily_requests"]) == 7
def test_dev_users_endpoint(client, monkeypatch):
from src import analytics
monkeypatch.setattr(cfg, "DEV_DASHBOARD_USER", "admin")
monkeypatch.setattr(cfg, "DEV_DASHBOARD_PASSWORD", "pw")
analytics._reset_for_tests()
import time as _time
analytics.ingest_batch([
{"ts": int(_time.time()) - 60, "service": "edge", "kind": "request",
"username": "alice", "endpoint": "/<u>", "widget": "composite",
"status": 200, "latency_ms": 11, "cache_hit": 1},
])
r = client.get("/api/dev/users", headers=_basic())
assert r.status_code == 200
rows = r.get_json()
assert any(u["username"] == "alice" for u in rows)
def test_dev_latency_and_health(client, monkeypatch):
monkeypatch.setattr(cfg, "DEV_DASHBOARD_USER", "admin")
monkeypatch.setattr(cfg, "DEV_DASHBOARD_PASSWORD", "pw")
r = client.get("/api/dev/latency", headers=_basic())
assert r.status_code == 200
assert isinstance(r.get_json(), list)
r2 = client.get("/api/dev/health", headers=_basic())
assert r2.status_code == 200
body = r2.get_json()
for key in ("edge_cache_hit_rate", "fetcher_error_rate",
"events_dropped_24h"):
assert key in body
+64
View File
@@ -181,3 +181,67 @@ def test_callback_happy_path_sets_session(api_client, monkeypatch):
assert s["gh_avatar_url"] == "https://x/a.png"
# Row should now exist with github profile populated.
assert dbmod.get_settings("alice") is not None
def test_require_basic_auth_503_when_unset(monkeypatch):
from flask import Flask, jsonify
from src import auth as authmod
from src import config as cfg
monkeypatch.setattr(cfg, "DEV_DASHBOARD_USER", "")
monkeypatch.setattr(cfg, "DEV_DASHBOARD_PASSWORD", "")
app = Flask(__name__)
@app.route("/x")
@authmod.require_basic_auth
def x():
return jsonify({"ok": True})
with app.test_client() as c:
r = c.get("/x")
assert r.status_code == 503
def test_require_basic_auth_401_on_bad(monkeypatch):
import base64
from flask import Flask, jsonify
from src import auth as authmod
from src import config as cfg
monkeypatch.setattr(cfg, "DEV_DASHBOARD_USER", "admin")
monkeypatch.setattr(cfg, "DEV_DASHBOARD_PASSWORD", "pw")
app = Flask(__name__)
@app.route("/x")
@authmod.require_basic_auth
def x():
return jsonify({"ok": True})
with app.test_client() as c:
r = c.get("/x")
assert r.status_code == 401
assert r.headers.get("WWW-Authenticate", "").startswith("Basic")
bad = base64.b64encode(b"admin:wrong").decode()
r2 = c.get("/x", headers={"Authorization": f"Basic {bad}"})
assert r2.status_code == 401
def test_require_basic_auth_200_on_good(monkeypatch):
import base64
from flask import Flask, jsonify
from src import auth as authmod
from src import config as cfg
monkeypatch.setattr(cfg, "DEV_DASHBOARD_USER", "admin")
monkeypatch.setattr(cfg, "DEV_DASHBOARD_PASSWORD", "pw")
app = Flask(__name__)
@app.route("/x")
@authmod.require_basic_auth
def x():
return jsonify({"ok": True})
with app.test_client() as c:
good = base64.b64encode(b"admin:pw").decode()
r = c.get("/x", headers={"Authorization": f"Basic {good}"})
assert r.status_code == 200
+21
View File
@@ -35,3 +35,24 @@ def test_tick_skips_when_hash_unchanged(tmp_dbs):
return_value={"data": {}, "payload_hash": "same"}):
stats = cronmod.tick()
assert stats["enqueued"] == 0
def test_cron_tick_prunes_old_analytics(tmp_path, monkeypatch):
import os, time
from src import db as dbmod, analytics, cron
monkeypatch.setattr(dbmod, "SETTINGS_DB_PATH", os.path.join(tmp_path, "s.db"))
monkeypatch.setattr(dbmod, "WIDGETS_DB_PATH", os.path.join(tmp_path, "w.db"))
monkeypatch.setattr(dbmod, "ANALYTICS_DB_PATH", os.path.join(tmp_path, "a.db"))
dbmod.init_dbs()
analytics.ingest_batch([
{"ts": int(time.time()) - 30 * 86400, "service": "edge", "kind": "request",
"username": "u", "endpoint": "/<u>", "widget": "composite",
"status": 200, "latency_ms": 1, "cache_hit": 1},
])
# tick() iterates enrolled users but there are none, so it returns
# immediately — we only care that the prune call ran.
cron.tick()
with dbmod.analytics_conn() as c:
n = c.execute("SELECT COUNT(*) AS n FROM events").fetchone()["n"]
assert n == 0
+13
View File
@@ -9,6 +9,7 @@ def tmp_dbs(monkeypatch):
with tempfile.TemporaryDirectory() as d:
monkeypatch.setattr(dbmod, "SETTINGS_DB_PATH", os.path.join(d, "s.db"))
monkeypatch.setattr(dbmod, "WIDGETS_DB_PATH", os.path.join(d, "w.db"))
monkeypatch.setattr(dbmod, "ANALYTICS_DB_PATH", os.path.join(d, "a.db"))
dbmod.init_dbs()
yield d
@@ -172,3 +173,15 @@ def test_put_user_streak_upserts(tmp_dbs):
assert row["current_streak"] == 2
assert row["max_streak"] == 5
assert row["max_start"] == "2024-01-01"
def test_init_dbs_creates_analytics_schema(tmp_path, monkeypatch):
from src import db as dbmod
monkeypatch.setattr(dbmod, "SETTINGS_DB_PATH", str(tmp_path / "s.db"))
monkeypatch.setattr(dbmod, "WIDGETS_DB_PATH", str(tmp_path / "w.db"))
monkeypatch.setattr(dbmod, "ANALYTICS_DB_PATH", str(tmp_path / "a.db"))
dbmod.init_dbs()
with dbmod.analytics_conn() as c:
cols = {r["name"] for r in c.execute("PRAGMA table_info(events)").fetchall()}
assert cols == {"id", "ts", "service", "kind", "username",
"endpoint", "widget", "status", "latency_ms", "cache_hit"}
+24
View File
@@ -178,3 +178,27 @@ def test_process_one_merges_stored_max(tmp_dbs):
assert row["max_streak"] == 50
assert row["max_start"] == "2023-01-01"
assert row["current_streak"] == 2
def test_process_one_records_render_event(monkeypatch, tmp_path):
import os
from src import db as dbmod, worker, analytics, fetcher_client
monkeypatch.setattr(dbmod, "SETTINGS_DB_PATH", os.path.join(tmp_path, "s.db"))
monkeypatch.setattr(dbmod, "WIDGETS_DB_PATH", os.path.join(tmp_path, "w.db"))
monkeypatch.setattr(dbmod, "ANALYTICS_DB_PATH", os.path.join(tmp_path, "a.db"))
dbmod.init_dbs()
analytics._reset_for_tests()
dbmod.enroll("alice", {"theme": "dark",
"enabled": ["grade"], "widget_order": ["grade"]})
monkeypatch.setattr(fetcher_client, "get_data",
lambda u: {"data": {"user": {"login": "alice"}, "repos": [], "events": []},
"payload_hash": "h"})
monkeypatch.setattr(worker, "_render_widgets",
lambda *a, **kw: {"composite": "<svg/>", "grade": "<svg/>"})
assert worker.process_one() is True
analytics.ingest_batch(analytics._drain_queue())
with dbmod.analytics_conn() as c:
rows = c.execute("SELECT username, widget, kind FROM events").fetchall()
assert ("alice", "composite", "render") in [(r["username"], r["widget"], r["kind"]) for r in rows]