From ef48d2581b55ccbd9507b2c264aeeb95cf29dd58 Mon Sep 17 00:00:00 2001 From: shay Date: Mon, 11 May 2026 18:26:43 -0400 Subject: [PATCH] feat(admin dashboard): add admin dashboard --- edge/src/analytics.py | 93 +++++ edge/tests/test_analytics.py | 46 +++ fetcher/src/analytics.py | 91 +++++ fetcher/tests/test_analytics.py | 57 +++ .../frontend/src/components/HealthStrip.tsx | 30 ++ .../frontend/src/components/LatencyChart.tsx | 34 ++ .../frontend/src/components/Sparkline.tsx | 17 + .../frontend/src/components/StatCards.tsx | 26 ++ .../frontend/src/components/UsersTable.tsx | 81 ++++ generator/frontend/src/lib/dev.ts | 51 +++ generator/frontend/src/screens/DevScreen.tsx | 75 ++++ generator/src/analytics.py | 348 ++++++++++++++++++ generator/tests/test_analytics.py | 168 +++++++++ generator/tests/test_attribution.py | 108 ++++++ 14 files changed, 1225 insertions(+) create mode 100644 edge/src/analytics.py create mode 100644 edge/tests/test_analytics.py create mode 100644 fetcher/src/analytics.py create mode 100644 fetcher/tests/test_analytics.py create mode 100644 generator/frontend/src/components/HealthStrip.tsx create mode 100644 generator/frontend/src/components/LatencyChart.tsx create mode 100644 generator/frontend/src/components/Sparkline.tsx create mode 100644 generator/frontend/src/components/StatCards.tsx create mode 100644 generator/frontend/src/components/UsersTable.tsx create mode 100644 generator/frontend/src/lib/dev.ts create mode 100644 generator/frontend/src/screens/DevScreen.tsx create mode 100644 generator/src/analytics.py create mode 100644 generator/tests/test_analytics.py create mode 100644 generator/tests/test_attribution.py diff --git a/edge/src/analytics.py b/edge/src/analytics.py new file mode 100644 index 0000000..e62baf8 --- /dev/null +++ b/edge/src/analytics.py @@ -0,0 +1,93 @@ +"""Edge analytics — record + flush + push to generator. + +The hot path enqueues; the background thread does the network I/O. If the +generator is unreachable we drop the batch (logging a warning) and let the +queue catch the next tick. +""" +import logging +import threading +import time +from collections import deque +import requests + +from . import config + +log = logging.getLogger("edge.analytics") + +_QUEUE: deque = deque(maxlen=config.ANALYTICS_QUEUE_MAX) +_QUEUE_LOCK = threading.Lock() +_THREAD_LOCK = threading.Lock() +_FLUSH_THREAD: threading.Thread | None = None +_events_dropped: int = 0 +_drop_lock = threading.Lock() + + +def _reset_for_tests() -> None: + global _events_dropped, _FLUSH_THREAD, _QUEUE + with _QUEUE_LOCK: + _QUEUE = deque(maxlen=config.ANALYTICS_QUEUE_MAX) + with _drop_lock: + _events_dropped = 0 + _FLUSH_THREAD = None + + +def record_request(endpoint: str, username: str | None, widget: str | None, + status: int, latency_ms: int, cache_hit: int | None = None) -> None: + ev = { + "ts": int(time.time()), + "service": "edge", + "kind": "request", + "username": username, + "endpoint": endpoint, + "widget": widget, + "status": int(status), + "latency_ms": int(latency_ms), + "cache_hit": cache_hit, + } + global _events_dropped + with _QUEUE_LOCK: + if len(_QUEUE) >= _QUEUE.maxlen: + with _drop_lock: + _events_dropped += 1 + return + _QUEUE.append(ev) + + +def flush_now() -> int: + with _QUEUE_LOCK: + batch = list(_QUEUE) + _QUEUE.clear() + if not batch: + return 0 + if not config.ANALYTICS_GENERATOR_URL or not config.ANALYTICS_INTERNAL_TOKEN: + return 0 + try: + requests.post( + f"{config.ANALYTICS_GENERATOR_URL}/internal/analytics/events", + headers={"X-Internal-Token": config.ANALYTICS_INTERNAL_TOKEN}, + json={"events": batch}, + timeout=2, + ) + except Exception: + log.warning("analytics flush failed (events lost)", exc_info=True) + return 0 + return len(batch) + + +def _flush_loop(): + while True: + time.sleep(config.ANALYTICS_FLUSH_SECONDS) + try: + flush_now() + except Exception: + log.exception("flush loop error") + + +def start_flush_thread(): + global _FLUSH_THREAD + with _THREAD_LOCK: + if _FLUSH_THREAD is not None and _FLUSH_THREAD.is_alive(): + return + t = threading.Thread(target=_flush_loop, name="edge-analytics-flush", daemon=True) + t.start() + _FLUSH_THREAD = t diff --git a/edge/tests/test_analytics.py b/edge/tests/test_analytics.py new file mode 100644 index 0000000..d509930 --- /dev/null +++ b/edge/tests/test_analytics.py @@ -0,0 +1,46 @@ +import responses +from src import analytics as a +from src import config as cfg + + +def test_record_request_enqueues(): + a._reset_for_tests() + a.record_request("/", "alice", "composite", 200, 12, cache_hit=1) + assert len(a._QUEUE) == 1 + e = a._QUEUE[0] + assert e["service"] == "edge" + assert e["username"] == "alice" + assert e["latency_ms"] == 12 + + +@responses.activate +def test_flush_posts_batch(monkeypatch): + monkeypatch.setattr(cfg, "ANALYTICS_GENERATOR_URL", "http://gen:5002") + monkeypatch.setattr(cfg, "ANALYTICS_INTERNAL_TOKEN", "secret") + a._reset_for_tests() + responses.add(responses.POST, "http://gen:5002/internal/analytics/events", + json={"ingested": 2}, status=200) + a.record_request("/", "alice", "composite", 200, 12, cache_hit=1) + a.record_request("/", "bob", "composite", 200, 8, cache_hit=0) + a.flush_now() + assert len(responses.calls) == 1 + import json + body = json.loads(responses.calls[0].request.body) + assert len(body["events"]) == 2 + + +def test_instrument_wraps_serve_and_records(monkeypatch): + monkeypatch.setattr(cfg, "ANALYTICS_INTERNAL_TOKEN", "secret") + a._reset_for_tests() + from src import api as apimod + with apimod.app.test_client() as c: + class FakeResp: + status_code = 200 + content = b"" + headers = {"X-Widget-Status": "ready", "Content-Type": "image/svg+xml"} + monkeypatch.setattr(apimod, "_fetch_origin", lambda *a, **k: FakeResp()) + apimod.cache_ext.clear() + c.get("/alice") + assert len(a._QUEUE) == 1 + assert a._QUEUE[0]["username"] == "alice" + assert a._QUEUE[0]["endpoint"] == "/" diff --git a/fetcher/src/analytics.py b/fetcher/src/analytics.py new file mode 100644 index 0000000..80b354a --- /dev/null +++ b/fetcher/src/analytics.py @@ -0,0 +1,91 @@ +"""Fetcher analytics — record fetch latency + push batches to the generator. + +The hot path enqueues; a daemon thread flushes batches over the internal +Docker network. On push failure we drop the batch and keep going. +""" +import logging +import threading +import time +from collections import deque +import requests + +from . import config + +log = logging.getLogger("fetcher.analytics") + +_QUEUE: deque = deque(maxlen=config.ANALYTICS_QUEUE_MAX) +_QUEUE_LOCK = threading.Lock() +_THREAD_LOCK = threading.Lock() +_FLUSH_THREAD: threading.Thread | None = None +_events_dropped: int = 0 +_drop_lock = threading.Lock() + + +def _reset_for_tests() -> None: + global _events_dropped, _FLUSH_THREAD, _QUEUE + with _QUEUE_LOCK: + _QUEUE = deque(maxlen=config.ANALYTICS_QUEUE_MAX) + with _drop_lock: + _events_dropped = 0 + _FLUSH_THREAD = None + + +def record_fetch(username: str, status: int, latency_ms: int) -> None: + ev = { + "ts": int(time.time()), + "service": "fetcher", + "kind": "fetch", + "username": username, + "endpoint": "github/users/", + "widget": None, + "status": int(status), + "latency_ms": int(latency_ms), + "cache_hit": None, + } + global _events_dropped + with _QUEUE_LOCK: + if len(_QUEUE) >= _QUEUE.maxlen: + with _drop_lock: + _events_dropped += 1 + return + _QUEUE.append(ev) + + +def flush_now() -> int: + with _QUEUE_LOCK: + batch = list(_QUEUE) + _QUEUE.clear() + if not batch: + return 0 + if not config.GENERATOR_URL or not config.INTERNAL_TOKEN: + return 0 + try: + requests.post( + f"{config.GENERATOR_URL}/internal/analytics/events", + headers={"X-Internal-Token": config.INTERNAL_TOKEN}, + json={"events": batch}, + timeout=2, + ) + except Exception: + log.warning("analytics flush failed (events lost)", exc_info=True) + return 0 + return len(batch) + + +def _flush_loop(): + while True: + time.sleep(config.ANALYTICS_FLUSH_SECONDS) + try: + flush_now() + except Exception: + log.exception("flush loop error") + + +def start_flush_thread(): + global _FLUSH_THREAD + with _THREAD_LOCK: + if _FLUSH_THREAD is not None and _FLUSH_THREAD.is_alive(): + return + t = threading.Thread(target=_flush_loop, name="fetcher-analytics-flush", daemon=True) + t.start() + _FLUSH_THREAD = t diff --git a/fetcher/tests/test_analytics.py b/fetcher/tests/test_analytics.py new file mode 100644 index 0000000..7089d36 --- /dev/null +++ b/fetcher/tests/test_analytics.py @@ -0,0 +1,57 @@ +import os +import tempfile +import pytest +import responses +from src import analytics as a +from src import config as cfg +from src import db as dbmod +from src import api as apimod + + +@pytest.fixture +def client(monkeypatch): + with tempfile.TemporaryDirectory() as d: + monkeypatch.setattr(dbmod, "DB_PATH", os.path.join(d, "t.db")) + monkeypatch.setattr(apimod.config, "INTERNAL_TOKEN", "secret") + monkeypatch.setattr(apimod.config, "GITHUB_PAT", "ghp_test") + dbmod.init_db() + app = apimod.app + app.config["TESTING"] = True + with app.test_client() as c: + yield c + + +def test_record_fetch(): + a._reset_for_tests() + a.record_fetch("alice", 200, 312) + assert len(a._QUEUE) == 1 + e = a._QUEUE[0] + assert e["service"] == "fetcher" + assert e["kind"] == "fetch" + assert e["status"] == 200 + assert e["latency_ms"] == 312 + assert e["endpoint"] == "github/users/" + + +@responses.activate +def test_flush_posts(monkeypatch): + monkeypatch.setattr(cfg, "GENERATOR_URL", "http://gen:5002") + monkeypatch.setattr(cfg, "INTERNAL_TOKEN", "secret") + a._reset_for_tests() + responses.add(responses.POST, "http://gen:5002/internal/analytics/events", + json={"ingested": 1}, status=200) + a.record_fetch("alice", 200, 100) + a.flush_now() + assert len(responses.calls) == 1 + + +def test_force_fetch_records_event(monkeypatch, client): + a._reset_for_tests() + monkeypatch.setattr("src.api.github.fetch_github_data", + lambda u, token: {"user": {"login": u}}) + r = client.post("/fetch", + headers={"X-Internal-Token": "secret"}, + json={"username": "alice"}) + assert r.status_code == 200 + assert any(e["kind"] == "fetch" and e["username"] == "alice" + for e in a._QUEUE) diff --git a/generator/frontend/src/components/HealthStrip.tsx b/generator/frontend/src/components/HealthStrip.tsx new file mode 100644 index 0000000..a201cf0 --- /dev/null +++ b/generator/frontend/src/components/HealthStrip.tsx @@ -0,0 +1,30 @@ +import { useEffect, useState } from 'react' +import { fetchHealth, type Health } from '../lib/dev' + +export function HealthStrip() { + const [h, setH] = useState(null) + useEffect(() => { fetchHealth().then(setH).catch(() => {}) }, []) + if (!h) return null + const pct = (n: number) => `${(n * 100).toFixed(1)}%` + return ( +
+
Health
+
+ + 0.05 ? 'warn' : 'ok'} /> + 0 ? 'warn' : 'ok'} /> +
+
+ ) +} + +function Pill({ label, value, tone = 'ok' }: { label: string; value: string; tone?: 'ok' | 'warn' }) { + const color = tone === 'warn' ? 'text-amber-400' : 'text-emerald-400' + return ( +
+
{label}
+
{value}
+
+ ) +} diff --git a/generator/frontend/src/components/LatencyChart.tsx b/generator/frontend/src/components/LatencyChart.tsx new file mode 100644 index 0000000..25cd8e7 --- /dev/null +++ b/generator/frontend/src/components/LatencyChart.tsx @@ -0,0 +1,34 @@ +import { useEffect, useState } from 'react' +import { fetchLatency, type LatencyRow } from '../lib/dev' + +export function LatencyChart() { + const [rows, setRows] = useState([]) + useEffect(() => { fetchLatency().then(setRows).catch(() => {}) }, []) + + const max = Math.max(1, ...rows.map(r => r.p95)) + + return ( +
+
Latency by endpoint
+ {rows.length === 0 &&
no traffic yet
} +
+ {rows.map(r => ( +
+
+
{r.endpoint}
+
+
+
+
+
+
+ {r.p50} · + {r.p95} · + {r.p99}ms +
+
+ ))} +
+
+ ) +} diff --git a/generator/frontend/src/components/Sparkline.tsx b/generator/frontend/src/components/Sparkline.tsx new file mode 100644 index 0000000..f26a913 --- /dev/null +++ b/generator/frontend/src/components/Sparkline.tsx @@ -0,0 +1,17 @@ +type Props = { values: number[]; width?: number; height?: number; stroke?: string } + +export function Sparkline({ values, width = 140, height = 32, stroke = '#60a5fa' }: Props) { + if (values.length === 0) return + const max = Math.max(1, ...values) + const stepX = width / Math.max(1, values.length - 1) + const pts = values.map((v, i) => { + const x = i * stepX + const y = height - (v / max) * (height - 2) - 1 + return `${x.toFixed(1)},${y.toFixed(1)}` + }).join(' ') + return ( + + + + ) +} diff --git a/generator/frontend/src/components/StatCards.tsx b/generator/frontend/src/components/StatCards.tsx new file mode 100644 index 0000000..270f768 --- /dev/null +++ b/generator/frontend/src/components/StatCards.tsx @@ -0,0 +1,26 @@ +import type { ReactNode } from 'react' +import { Sparkline } from './Sparkline' +import type { Summary } from '../lib/dev' + +function Card({ label, value, sub }: { label: string; value: string; sub?: ReactNode }) { + return ( +
+
{label}
+
{value}
+ {sub &&
{sub}
} +
+ ) +} + +export function StatCards({ s }: { s: Summary }) { + const fmt = (n: number) => n.toLocaleString() + return ( +
+ d.count)} />} /> + + + +
+ ) +} diff --git a/generator/frontend/src/components/UsersTable.tsx b/generator/frontend/src/components/UsersTable.tsx new file mode 100644 index 0000000..64f560b --- /dev/null +++ b/generator/frontend/src/components/UsersTable.tsx @@ -0,0 +1,81 @@ +import { useEffect, useMemo, useState } from 'react' +import { fetchUsers, type UserRow } from '../lib/dev' + +function timeAgo(ts: number | null): string { + if (!ts) return '—' + const s = Math.max(0, Math.floor(Date.now() / 1000 - ts)) + if (s < 60) return `${s}s ago` + if (s < 3600) return `${Math.floor(s / 60)}m ago` + if (s < 86400) return `${Math.floor(s / 3600)}h ago` + return `${Math.floor(s / 86400)}d ago` +} + +export function UsersTable() { + const [q, setQ] = useState('') + const [sort, setSort] = useState<'requests' | 'latency' | 'last_seen'>('requests') + const [rows, setRows] = useState([]) + const [loading, setLoading] = useState(true) + + useEffect(() => { + let alive = true + const h = window.setTimeout(() => { + setLoading(true) + fetchUsers(q, sort).then(r => { if (alive) { setRows(r); setLoading(false) } }) + .catch(() => { if (alive) setLoading(false) }) + }, 200) + return () => { alive = false; window.clearTimeout(h) } + }, [q, sort]) + + const sorted = useMemo(() => rows, [rows]) + + return ( +
+
+
Users
+
+ + setQ(e.target.value)} placeholder="search…" + className="rounded bg-white/[0.04] px-2 py-1 text-xs text-white/80 placeholder:text-white/30" /> +
+
+ + + + + + + + + + + + {loading && } + {!loading && sorted.length === 0 && ( + + )} + {sorted.map(u => ( + + + + + + + + ))} + +
UserReq 7dLast seenTop endpointAvg ms
loading…
no users yet
+
+ {u.github_avatar_url + ? + : } + {u.username} +
+
{u.requests_7d.toLocaleString()}{timeAgo(u.last_seen)}{u.top_endpoint || '—'}{u.avg_latency_ms}
+
+ ) +} diff --git a/generator/frontend/src/lib/dev.ts b/generator/frontend/src/lib/dev.ts new file mode 100644 index 0000000..57b5b84 --- /dev/null +++ b/generator/frontend/src/lib/dev.ts @@ -0,0 +1,51 @@ +// Read helpers for the /dev dashboard. All four endpoints require a +// Basic-auth session that the browser establishes via the WWW-Authenticate +// challenge the first time the SPA hits /api/dev/summary. + +export type Summary = { + requests_7d: number + active_users_7d: number + p50_ms: number + p95_ms: number + renders_7d: number + avg_render_ms: number + daily_requests: { day: string; count: number }[] +} + +export type UserRow = { + username: string + requests_7d: number + last_seen: number | null + avg_latency_ms: number + top_endpoint: string + github_avatar_url: string | null +} + +export type LatencyRow = { + endpoint: string + count: number + p50: number + p95: number + p99: number +} + +export type Health = { + edge_cache_hit_rate: number + fetcher_error_rate: number + events_dropped_24h: number + oldest_event_ts: number | null +} + +async function getJSON(path: string): Promise { + const r = await fetch(path, { credentials: 'include' }) + if (r.status === 401) throw new Error('unauthorized') + if (r.status === 503) throw new Error('dashboard_disabled') + if (!r.ok) throw new Error(`HTTP ${r.status}`) + return (await r.json()) as T +} + +export const fetchSummary = () => getJSON('/api/dev/summary') +export const fetchUsers = (q = '', sort = 'requests') => + getJSON(`/api/dev/users?q=${encodeURIComponent(q)}&sort=${sort}`) +export const fetchLatency = () => getJSON('/api/dev/latency') +export const fetchHealth = () => getJSON('/api/dev/health') diff --git a/generator/frontend/src/screens/DevScreen.tsx b/generator/frontend/src/screens/DevScreen.tsx new file mode 100644 index 0000000..d30660a --- /dev/null +++ b/generator/frontend/src/screens/DevScreen.tsx @@ -0,0 +1,75 @@ +import { useEffect, useState } from 'react' +import type { ReactNode } from 'react' +import { fetchSummary, type Summary } from '../lib/dev' +import { StatCards } from '../components/StatCards' +import { UsersTable } from '../components/UsersTable' +import { LatencyChart } from '../components/LatencyChart' +import { HealthStrip } from '../components/HealthStrip' + +const REFRESH_MS = 15_000 + +export function DevScreen() { + const [s, setS] = useState(null) + const [error, setError] = useState(null) + const [lastRefresh, setLastRefresh] = useState(new Date()) + + useEffect(() => { + let alive = true + const load = () => + fetchSummary() + .then(v => { if (!alive) return; setS(v); setError(null); setLastRefresh(new Date()) }) + .catch(e => { if (alive) setError(e.message || 'error') }) + load() + const h = window.setInterval(load, REFRESH_MS) + return () => { alive = false; window.clearInterval(h) } + }, []) + + if (error === 'dashboard_disabled') { + return ( + +
+ The /dev dashboard is not configured on this deploy + (set DEV_DASHBOARD_USER and DEV_DASHBOARD_PASSWORD). +
+
+ ) + } + if (error === 'unauthorized') { + return ( + +
Sign in to view the dashboard. Reload to retry.
+
+ ) + } + + return ( + + {s ? :
loading…
} +
+ +
+
+ + +
+
+ ) +} + +function Shell({ children, lastRefresh }: { children: ReactNode; lastRefresh?: Date }) { + return ( +
+
+
+

/dev · gh-stats analytics

+ {lastRefresh && ( +
+ last refresh {lastRefresh.toLocaleTimeString()} +
+ )} +
+ {children} +
+
+ ) +} diff --git a/generator/src/analytics.py b/generator/src/analytics.py new file mode 100644 index 0000000..77b5a54 --- /dev/null +++ b/generator/src/analytics.py @@ -0,0 +1,348 @@ +"""Analytics: bounded in-memory queue, daemon flush thread, query helpers. + +Three call sites write events: + * record_request — generator's own HTTP path (rarely used; edge handles most) + * record_render — worker / on-demand /generate + * ingest_batch — POST /internal/analytics/events from edge & fetcher + +All writes go through a shared bounded deque so the hot path never blocks on +SQLite I/O. A daemon thread flushes the queue every _FLUSH_SECONDS into +analytics.db in a single transaction. +""" +import logging +import math +import threading +import time +from collections import deque +from typing import Any + +from . import config, db + +log = logging.getLogger("generator.analytics") + +_FLUSH_SECONDS = config.ANALYTICS_FLUSH_SECONDS +_QUEUE_MAX = config.ANALYTICS_QUEUE_MAX +_RETENTION_DAYS = config.ANALYTICS_RETENTION_DAYS + +_QUEUE: deque = deque(maxlen=_QUEUE_MAX) +_QUEUE_LOCK = threading.Lock() +_FLUSH_THREAD: threading.Thread | None = None +_THREAD_LOCK = threading.Lock() +_events_dropped: int = 0 +_drop_lock = threading.Lock() + +_ALLOWED_KINDS = {"request", "render", "fetch"} +_ALLOWED_SERVICES = {"edge", "generator", "fetcher"} + + +def _reset_for_tests() -> None: + """Clear the queue + dropped counter; rebuild deque so a monkeypatched + _QUEUE_MAX takes effect for the next test.""" + global _FLUSH_THREAD, _events_dropped, _QUEUE + with _QUEUE_LOCK: + _QUEUE = deque(maxlen=_QUEUE_MAX) + with _drop_lock: + _events_dropped = 0 + _FLUSH_THREAD = None + + +def _enqueue(event: dict) -> None: + global _events_dropped + with _QUEUE_LOCK: + if len(_QUEUE) >= _QUEUE.maxlen: + with _drop_lock: + _events_dropped += 1 + return + _QUEUE.append(event) + + +def record_request(endpoint: str, username: str | None, widget: str | None, + status: int, latency_ms: int, cache_hit: int | None = None) -> None: + _enqueue({ + "ts": int(time.time()), + "service": "generator", + "kind": "request", + "username": username, + "endpoint": endpoint, + "widget": widget, + "status": int(status), + "latency_ms": int(latency_ms), + "cache_hit": cache_hit, + }) + + +def record_render(username: str, widget: str, latency_ms: int) -> None: + _enqueue({ + "ts": int(time.time()), + "service": "generator", + "kind": "render", + "username": username, + "endpoint": None, + "widget": widget, + "status": None, + "latency_ms": int(latency_ms), + "cache_hit": None, + }) + + +def _coerce_int_or_none(v: Any) -> int | None: + if isinstance(v, bool) or v is None: + return None + if isinstance(v, int): + return v + return None + + +def _validate(ev: Any) -> dict | None: + if not isinstance(ev, dict): + return None + try: + ts = int(ev.get("ts", 0)) + if ts <= 0: + ts = int(time.time()) + service = ev.get("service") + kind = ev.get("kind") + latency_ms = int(ev.get("latency_ms")) + except (TypeError, ValueError): + return None + if service not in _ALLOWED_SERVICES or kind not in _ALLOWED_KINDS: + return None + return { + "ts": ts, + "service": service, + "kind": kind, + "username": ev.get("username") if isinstance(ev.get("username"), str) else None, + "endpoint": ev.get("endpoint") if isinstance(ev.get("endpoint"), str) else None, + "widget": ev.get("widget") if isinstance(ev.get("widget"), str) else None, + "status": _coerce_int_or_none(ev.get("status")), + "latency_ms": max(0, latency_ms), + "cache_hit": _coerce_int_or_none(ev.get("cache_hit")), + } + + +def ingest_batch(events: list) -> int: + """Validate + persist a batch in one transaction. Returns rows inserted.""" + if not isinstance(events, list): + return 0 + cleaned = [] + for ev in events[:500]: + n = _validate(ev) + if n is not None: + cleaned.append(n) + if not cleaned: + return 0 + with db.analytics_conn() as c: + c.executemany( + """INSERT INTO events(ts, service, kind, username, endpoint, widget, + status, latency_ms, cache_hit) + VALUES (:ts, :service, :kind, :username, :endpoint, :widget, + :status, :latency_ms, :cache_hit)""", + cleaned, + ) + c.commit() + return len(cleaned) + + +def _drain_queue() -> list[dict]: + with _QUEUE_LOCK: + out = list(_QUEUE) + _QUEUE.clear() + return out + + +def _flush_loop() -> None: + while True: + time.sleep(_FLUSH_SECONDS) + try: + batch = _drain_queue() + if batch: + ingest_batch(batch) + except Exception: + log.exception("analytics flush failed") + + +def start_flush_thread() -> None: + global _FLUSH_THREAD + with _THREAD_LOCK: + if _FLUSH_THREAD is not None and _FLUSH_THREAD.is_alive(): + return + t = threading.Thread(target=_flush_loop, name="analytics-flush", daemon=True) + t.start() + _FLUSH_THREAD = t + + +def _percentile(sorted_vals: list[int], pct: float) -> int: + if not sorted_vals: + return 0 + n = len(sorted_vals) + k = max(0, min(n - 1, math.ceil(pct / 100.0 * n) - 1)) + return int(sorted_vals[k]) + + +def query_summary() -> dict: + now = int(time.time()) + week_ago = now - 7 * 86400 + with db.analytics_conn() as c: + req_rows = c.execute( + """SELECT username, latency_ms, ts FROM events + WHERE kind='request' AND ts >= ?""", (week_ago,) + ).fetchall() + render_rows = c.execute( + """SELECT username, latency_ms FROM events + WHERE kind='render' AND ts >= ?""", (week_ago,) + ).fetchall() + requests_7d = len(req_rows) + renders_7d = len(render_rows) + latencies = sorted(r["latency_ms"] for r in req_rows) + active = {r["username"] for r in req_rows if r["username"]} + active.update(r["username"] for r in render_rows if r["username"]) + avg_render_ms = (sum(r["latency_ms"] for r in render_rows) // renders_7d) if renders_7d else 0 + by_day: dict[str, int] = {} + for r in req_rows: + day = time.strftime("%Y-%m-%d", time.gmtime(r["ts"])) + by_day[day] = by_day.get(day, 0) + 1 + daily = [] + for i in range(6, -1, -1): + day = time.strftime("%Y-%m-%d", time.gmtime(now - i * 86400)) + daily.append({"day": day, "count": by_day.get(day, 0)}) + return { + "requests_7d": requests_7d, + "active_users_7d": len(active), + "p50_ms": _percentile(latencies, 50), + "p95_ms": _percentile(latencies, 95), + "renders_7d": renders_7d, + "avg_render_ms": avg_render_ms, + "daily_requests": daily, + } + + +def query_users(q: str = "", sort: str = "requests", limit: int = 200) -> list[dict]: + now = int(time.time()) + week_ago = now - 7 * 86400 + with db.analytics_conn() as c: + c.execute("ATTACH DATABASE ? AS settings", (db.SETTINGS_DB_PATH,)) + try: + rows = c.execute( + """SELECT e.username AS username, + COUNT(*) AS requests_7d, + MAX(e.ts) AS last_seen, + AVG(e.latency_ms) AS avg_latency_ms, + (SELECT u.github_avatar_url FROM settings.users u + WHERE u.username = e.username) AS github_avatar_url + FROM events e + WHERE e.kind='request' AND e.ts >= ? AND e.username IS NOT NULL + GROUP BY e.username""", + (week_ago,), + ).fetchall() + top_eps_rows = c.execute( + """SELECT username, endpoint, COUNT(*) AS n + FROM events + WHERE kind='request' AND ts >= ? AND username IS NOT NULL + GROUP BY username, endpoint""", + (week_ago,), + ).fetchall() + finally: + c.execute("DETACH DATABASE settings") + top_by_user: dict[str, tuple[str, int]] = {} + for r in top_eps_rows: + cur = top_by_user.get(r["username"]) + if cur is None or r["n"] > cur[1]: + top_by_user[r["username"]] = (r["endpoint"], r["n"]) + out = [] + needle = q.lower().strip() + for r in rows: + if needle and needle not in (r["username"] or "").lower(): + continue + out.append({ + "username": r["username"], + "requests_7d": r["requests_7d"], + "last_seen": r["last_seen"], + "avg_latency_ms": int(r["avg_latency_ms"] or 0), + "top_endpoint": top_by_user.get(r["username"], ("", 0))[0], + "github_avatar_url": r["github_avatar_url"], + }) + key = { + "requests": lambda u: -u["requests_7d"], + "latency": lambda u: -u["avg_latency_ms"], + "last_seen": lambda u: -(u["last_seen"] or 0), + }.get(sort, lambda u: -u["requests_7d"]) + out.sort(key=key) + return out[: max(1, min(int(limit), 500))] + + +def query_latency() -> list[dict]: + now = int(time.time()) + week_ago = now - 7 * 86400 + with db.analytics_conn() as c: + top = c.execute( + """SELECT endpoint, COUNT(*) AS n FROM events + WHERE kind='request' AND ts >= ? AND endpoint IS NOT NULL + GROUP BY endpoint ORDER BY n DESC LIMIT 12""", + (week_ago,), + ).fetchall() + out = [] + for r in top: + vals = [ + row["latency_ms"] + for row in c.execute( + """SELECT latency_ms FROM events + WHERE kind='request' AND ts >= ? AND endpoint = ?""", + (week_ago, r["endpoint"]), + ).fetchall() + ] + vals.sort() + out.append({ + "endpoint": r["endpoint"], + "count": r["n"], + "p50": _percentile(vals, 50), + "p95": _percentile(vals, 95), + "p99": _percentile(vals, 99), + }) + return out + + +def query_health() -> dict: + now = int(time.time()) + week_ago = now - 7 * 86400 + with db.analytics_conn() as c: + edge = c.execute( + """SELECT SUM(CASE WHEN cache_hit=1 THEN 1 ELSE 0 END) AS hits, + COUNT(*) AS total + FROM events WHERE service='edge' AND kind='request' AND ts >= ?""", + (week_ago,), + ).fetchone() + fetcher = c.execute( + """SELECT SUM(CASE WHEN status >= 400 THEN 1 ELSE 0 END) AS errs, + COUNT(*) AS total + FROM events WHERE service='fetcher' AND kind='fetch' AND ts >= ?""", + (week_ago,), + ).fetchone() + oldest = c.execute( + "SELECT MIN(ts) AS oldest FROM events" + ).fetchone() + edge_total = (edge["total"] or 0) + fetch_total = (fetcher["total"] or 0) + return { + "edge_cache_hit_rate": (edge["hits"] / edge_total) if edge_total else 0.0, + "fetcher_error_rate": (fetcher["errs"] / fetch_total) if fetch_total else 0.0, + "events_dropped_24h": _events_dropped, + "oldest_event_ts": oldest["oldest"] if oldest and oldest["oldest"] else None, + } + + +def prune_old(retention_days: int = _RETENTION_DAYS) -> int: + cutoff = int(time.time()) - retention_days * 86400 + deleted = 0 + with db.analytics_conn() as c: + while True: + cur = c.execute( + "DELETE FROM events WHERE id IN (" + " SELECT id FROM events WHERE ts < ? LIMIT 5000)", + (cutoff,), + ) + c.commit() + n = cur.rowcount or 0 + deleted += n + if n < 5000: + break + return deleted diff --git a/generator/tests/test_analytics.py b/generator/tests/test_analytics.py new file mode 100644 index 0000000..27e0406 --- /dev/null +++ b/generator/tests/test_analytics.py @@ -0,0 +1,168 @@ +import os, tempfile, time +import pytest +from src import db as dbmod +from src import analytics as a + + +@pytest.fixture +def fresh(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() + a._reset_for_tests() + yield + + +def test_ingest_batch_writes_rows(fresh): + n = a.ingest_batch([ + {"ts": 1000, "service": "edge", "kind": "request", + "username": "alice", "endpoint": "/", "widget": "composite", + "status": 200, "latency_ms": 12, "cache_hit": 1}, + {"ts": 1001, "service": "edge", "kind": "request", + "username": "bob", "endpoint": "/", "widget": "composite", + "status": 200, "latency_ms": 8, "cache_hit": 0}, + ]) + assert n == 2 + with dbmod.analytics_conn() as c: + rows = c.execute("SELECT username, latency_ms FROM events ORDER BY ts").fetchall() + assert [(r["username"], r["latency_ms"]) for r in rows] == [("alice", 12), ("bob", 8)] + + +def test_ingest_drops_bad_rows(fresh): + n = a.ingest_batch([ + {"ts": 1, "service": "edge", "kind": "request", "latency_ms": 1}, + {"missing": "everything"}, + {"ts": 2, "service": "edge", "kind": "request", "latency_ms": "not-int"}, + ]) + assert n == 1 + + +def test_record_render_flushes_to_db(fresh, monkeypatch): + monkeypatch.setattr(a, "_FLUSH_SECONDS", 0.05) + a.start_flush_thread() + a.record_render("alice", "composite", 142) + deadline = time.time() + 3 + row = None + while time.time() < deadline: + with dbmod.analytics_conn() as c: + row = c.execute("SELECT * FROM events WHERE kind='render'").fetchone() + if row: + break + time.sleep(0.05) + assert row is not None + assert row["username"] == "alice" + assert row["widget"] == "composite" + assert row["latency_ms"] == 142 + + +def test_summary_aggregates_last_7d(fresh): + now = int(time.time()) + rows = [ + {"ts": now - 60, "service": "edge", "kind": "request", + "username": "alice", "endpoint": "/", "widget": "composite", + "status": 200, "latency_ms": 10, "cache_hit": 1}, + {"ts": now - 120, "service": "edge", "kind": "request", + "username": "bob", "endpoint": "/", "widget": "composite", + "status": 200, "latency_ms": 50, "cache_hit": 0}, + {"ts": now - 10 * 86400, "service": "edge", "kind": "request", + "username": "old", "endpoint": "/", "widget": "composite", + "status": 200, "latency_ms": 999, "cache_hit": 0}, + {"ts": now - 30, "service": "generator", "kind": "render", + "username": "alice", "widget": "composite", "latency_ms": 200}, + ] + a.ingest_batch(rows) + s = a.query_summary() + assert s["requests_7d"] == 2 # 'old' falls outside the 7d window + assert s["active_users_7d"] == 2 # alice (edge+render dedup) + bob + assert s["renders_7d"] == 1 + assert s["avg_render_ms"] == 200 + assert s["p50_ms"] in (10, 50) + assert s["p95_ms"] == 50 + assert len(s["daily_requests"]) == 7 + + +def test_query_users_returns_per_user_rows(fresh): + now = int(time.time()) + a.ingest_batch([ + {"ts": now - 60, "service": "edge", "kind": "request", + "username": "alice", "endpoint": "/", "widget": "composite", + "status": 200, "latency_ms": 10, "cache_hit": 1}, + {"ts": now - 30, "service": "edge", "kind": "request", + "username": "alice", "endpoint": "//grade.svg", "widget": "grade", + "status": 200, "latency_ms": 20, "cache_hit": 1}, + {"ts": now - 10, "service": "edge", "kind": "request", + "username": "alice", "endpoint": "/", "widget": "composite", + "status": 200, "latency_ms": 30, "cache_hit": 1}, + ]) + users = a.query_users() + assert len(users) == 1 + u = users[0] + assert u["username"] == "alice" + assert u["requests_7d"] == 3 + assert u["top_endpoint"] == "/" + assert u["avg_latency_ms"] == 20 + + +def test_query_latency_returns_percentiles(fresh): + now = int(time.time()) + a.ingest_batch([ + {"ts": now - 1, "service": "edge", "kind": "request", + "username": "u", "endpoint": "/", "widget": "composite", + "status": 200, "latency_ms": v, "cache_hit": 1} + for v in range(1, 101) + ]) + rows = a.query_latency() + by_ep = {r["endpoint"]: r for r in rows} + assert by_ep["/"]["count"] == 100 + assert by_ep["/"]["p50"] == 50 + assert by_ep["/"]["p95"] == 95 + assert by_ep["/"]["p99"] == 99 + + +def test_query_health(fresh): + now = int(time.time()) + a.ingest_batch([ + {"ts": now - 1, "service": "edge", "kind": "request", + "username": "u", "endpoint": "/", "widget": "composite", + "status": 200, "latency_ms": 1, "cache_hit": 1}, + {"ts": now - 2, "service": "edge", "kind": "request", + "username": "u", "endpoint": "/", "widget": "composite", + "status": 200, "latency_ms": 1, "cache_hit": 0}, + {"ts": now - 3, "service": "fetcher", "kind": "fetch", + "username": "u", "endpoint": "github/users/", + "status": 500, "latency_ms": 100}, + {"ts": now - 4, "service": "fetcher", "kind": "fetch", + "username": "u", "endpoint": "github/users/", + "status": 200, "latency_ms": 100}, + ]) + h = a.query_health() + assert abs(h["edge_cache_hit_rate"] - 0.5) < 1e-6 + assert abs(h["fetcher_error_rate"] - 0.5) < 1e-6 + assert h["events_dropped_24h"] == 0 + + +def test_prune_drops_old_events(fresh): + now = int(time.time()) + a.ingest_batch([ + {"ts": now - 20 * 86400, "service": "edge", "kind": "request", + "username": "u", "endpoint": "/", "widget": "composite", + "status": 200, "latency_ms": 1, "cache_hit": 1}, + {"ts": now, "service": "edge", "kind": "request", + "username": "u", "endpoint": "/", "widget": "composite", + "status": 200, "latency_ms": 1, "cache_hit": 1}, + ]) + deleted = a.prune_old(retention_days=14) + assert deleted == 1 + with dbmod.analytics_conn() as c: + n = c.execute("SELECT COUNT(*) AS n FROM events").fetchone()["n"] + assert n == 1 + + +def test_queue_drops_when_full_and_counts(fresh, monkeypatch): + monkeypatch.setattr(a, "_QUEUE_MAX", 3) + a._reset_for_tests() + for i in range(10): + a.record_render("u", "composite", i) + assert a._events_dropped == 7 diff --git a/generator/tests/test_attribution.py b/generator/tests/test_attribution.py new file mode 100644 index 0000000..a783767 --- /dev/null +++ b/generator/tests/test_attribution.py @@ -0,0 +1,108 @@ +"""Per-widget attribution behaves correctly in both contexts. + +Standalone widget SVGs (served at /api//.svg) must show the +"Generated with gh-stats" footer; the composite (served at /api/) +must strip the per-widget footer and only show its own bottom one. +""" +from src.models import GradeData, LanguageData, TagData +from src.widgets import ( + render_grade_widget, + render_languages_widget, + compose_widget, +) + + +def _grade_fixture() -> GradeData: + return GradeData( + grade="A", score=80, + stats={"commits": 100, "prs": 10, "stars": 5, "repos": 3, "followers": 1}, + tags=[TagData(tag="builder", source="earned")], + breakdown={"commits": 0.8, "consistency": 0.6, "stars": 0.4}, + ) + + +def _languages_fixture() -> list[LanguageData]: + return [ + LanguageData(language="Python", percentage=60.0, loc=0), + LanguageData(language="TypeScript", percentage=40.0, loc=0), + ] + + +def test_standalone_grade_widget_has_attribution(): + svg = render_grade_widget(_grade_fixture(), theme_name="dark") + assert "Generated with gh-stats" in svg + assert 'data-gh-attribution="1"' in svg + + +def test_standalone_languages_widget_has_attribution(): + svg = render_languages_widget(_languages_fixture(), theme_name="dark") + assert "Generated with gh-stats" in svg + assert 'data-gh-attribution="1"' in svg + + +def test_composite_strips_per_widget_attribution_from_grade(): + """Embedded inside the composite, the grade widget's per-widget + attribution must be removed — the composite has its own footer at + the bottom, showing both would be visually redundant.""" + grade_svg = render_grade_widget(_grade_fixture(), theme_name="dark") + composite = compose_widget( + widgets={"grade": grade_svg}, + enabled=["grade"], + theme_name="dark", + username="alice", + avatar_b64="", + show_name=False, + ) + # The composite has exactly ONE attribution (its own). The widget's + # footer attribution should be gone. + assert composite.count("Generated with gh-stats") == 1 + # No leftover attribution markers leaked through. + assert "data-gh-attribution" not in composite + + +def test_composite_strips_per_widget_attribution_from_languages(): + langs_svg = render_languages_widget(_languages_fixture(), theme_name="dark") + composite = compose_widget( + widgets={"languages": langs_svg}, + enabled=["languages"], + theme_name="dark", + username="alice", + avatar_b64="", + show_name=False, + ) + assert composite.count("Generated with gh-stats") == 1 + assert "data-gh-attribution" not in composite + + +def test_composite_strips_attribution_from_multiple_widgets(): + """When several attribution-bearing widgets are inlined together, + the composite still shows only its own single footer line.""" + grade_svg = render_grade_widget(_grade_fixture(), theme_name="dark") + langs_svg = render_languages_widget(_languages_fixture(), theme_name="dark") + composite = compose_widget( + widgets={"grade": grade_svg, "languages": langs_svg}, + enabled=["grade", "languages"], + theme_name="dark", + username="alice", + avatar_b64="", + show_name=False, + ) + # Each widget contributed an attribution; the composite contributes + # one of its own — total visible attributions must be exactly 1. + assert composite.count("Generated with gh-stats") == 1 + + +def test_composite_reclaims_attribution_height(): + """Stripping the attribution from a per-widget SVG must also reduce + the slot height the composite reserves — otherwise we'd leave 16px + of empty space at the bottom of every embedded widget.""" + from src.widgets import composite as composite_mod + + grade_svg = render_grade_widget(_grade_fixture(), theme_name="dark") + inner_with_attr, h_with_attr = composite_mod._extract_inner(grade_svg, "grade") + # The standalone grade SVG declares its full height including the + # 16px footer; the embed height should be 16 less. + import re + full_h = int(re.search(r'height="(\d+)"', grade_svg).group(1)) + assert h_with_attr == full_h - 16 + assert "data-gh-attribution" not in inner_with_attr