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
+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