mirror of
https://github.com/ShayManor/github-readme-stats.git
synced 2026-12-02 11:53:48 +05:30
feat(admin dashboard): add admin dashboard
This commit is contained in:
@@ -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
|
||||||
@@ -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("/<u>", "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("/<u>", "alice", "composite", 200, 12, cache_hit=1)
|
||||||
|
a.record_request("/<u>", "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"<svg/>"
|
||||||
|
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"] == "/<u>"
|
||||||
@@ -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/<u>",
|
||||||
|
"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
|
||||||
@@ -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/<u>"
|
||||||
|
|
||||||
|
|
||||||
|
@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)
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
import { useEffect, useState } from 'react'
|
||||||
|
import { fetchHealth, type Health } from '../lib/dev'
|
||||||
|
|
||||||
|
export function HealthStrip() {
|
||||||
|
const [h, setH] = useState<Health | null>(null)
|
||||||
|
useEffect(() => { fetchHealth().then(setH).catch(() => {}) }, [])
|
||||||
|
if (!h) return null
|
||||||
|
const pct = (n: number) => `${(n * 100).toFixed(1)}%`
|
||||||
|
return (
|
||||||
|
<div className="rounded-lg border border-white/10 bg-white/[0.02] p-4">
|
||||||
|
<div className="mb-3 text-sm text-white/70">Health</div>
|
||||||
|
<div className="grid grid-cols-3 gap-3 text-center">
|
||||||
|
<Pill label="Edge cache hit" value={pct(h.edge_cache_hit_rate)} />
|
||||||
|
<Pill label="Fetch error" value={pct(h.fetcher_error_rate)} tone={h.fetcher_error_rate > 0.05 ? 'warn' : 'ok'} />
|
||||||
|
<Pill label="Events dropped 24h" value={h.events_dropped_24h.toLocaleString()}
|
||||||
|
tone={h.events_dropped_24h > 0 ? 'warn' : 'ok'} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function Pill({ label, value, tone = 'ok' }: { label: string; value: string; tone?: 'ok' | 'warn' }) {
|
||||||
|
const color = tone === 'warn' ? 'text-amber-400' : 'text-emerald-400'
|
||||||
|
return (
|
||||||
|
<div className="rounded bg-white/[0.03] px-2 py-2">
|
||||||
|
<div className="text-xs text-white/40">{label}</div>
|
||||||
|
<div className={`mt-1 font-mono text-lg ${color}`}>{value}</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import { useEffect, useState } from 'react'
|
||||||
|
import { fetchLatency, type LatencyRow } from '../lib/dev'
|
||||||
|
|
||||||
|
export function LatencyChart() {
|
||||||
|
const [rows, setRows] = useState<LatencyRow[]>([])
|
||||||
|
useEffect(() => { fetchLatency().then(setRows).catch(() => {}) }, [])
|
||||||
|
|
||||||
|
const max = Math.max(1, ...rows.map(r => r.p95))
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="rounded-lg border border-white/10 bg-white/[0.02] p-4">
|
||||||
|
<div className="mb-3 text-sm text-white/70">Latency by endpoint</div>
|
||||||
|
{rows.length === 0 && <div className="text-xs text-white/40">no traffic yet</div>}
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
{rows.map(r => (
|
||||||
|
<div key={r.endpoint} className="grid grid-cols-[1fr_auto] items-center gap-3 font-mono text-xs">
|
||||||
|
<div>
|
||||||
|
<div className="text-white/70">{r.endpoint}</div>
|
||||||
|
<div className="mt-1 h-1.5 w-full overflow-hidden rounded bg-white/[0.04]">
|
||||||
|
<div className="h-full bg-sky-400/60" style={{ width: `${(r.p50 / max) * 100}%` }} />
|
||||||
|
<div className="-mt-1.5 h-1.5 bg-sky-300/30" style={{ width: `${(r.p95 / max) * 100}%` }} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="text-right text-white/80 tabular-nums">
|
||||||
|
<span>{r.p50}</span><span className="text-white/30"> · </span>
|
||||||
|
<span>{r.p95}</span><span className="text-white/30"> · </span>
|
||||||
|
<span>{r.p99}ms</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -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 <svg width={width} height={height} />
|
||||||
|
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 (
|
||||||
|
<svg width={width} height={height} viewBox={`0 0 ${width} ${height}`}>
|
||||||
|
<polyline points={pts} fill="none" stroke={stroke} strokeWidth={1.5} strokeLinecap="round" strokeLinejoin="round" />
|
||||||
|
</svg>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -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 (
|
||||||
|
<div className="rounded-lg border border-white/10 bg-white/[0.02] px-4 py-3">
|
||||||
|
<div className="text-xs uppercase tracking-wide text-white/50">{label}</div>
|
||||||
|
<div className="mt-1 text-2xl font-mono text-white">{value}</div>
|
||||||
|
{sub && <div className="mt-1 text-xs text-white/40">{sub}</div>}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function StatCards({ s }: { s: Summary }) {
|
||||||
|
const fmt = (n: number) => n.toLocaleString()
|
||||||
|
return (
|
||||||
|
<div className="grid grid-cols-1 gap-3 md:grid-cols-4">
|
||||||
|
<Card label="Requests 7d" value={fmt(s.requests_7d)}
|
||||||
|
sub={<Sparkline values={s.daily_requests.map(d => d.count)} />} />
|
||||||
|
<Card label="Active users 7d" value={fmt(s.active_users_7d)} />
|
||||||
|
<Card label="p50 / p95 latency" value={`${s.p50_ms}/${s.p95_ms}ms`} />
|
||||||
|
<Card label="Renders 7d" value={fmt(s.renders_7d)} sub={`avg ${s.avg_render_ms}ms`} />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -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<UserRow[]>([])
|
||||||
|
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 (
|
||||||
|
<div className="rounded-lg border border-white/10 bg-white/[0.02]">
|
||||||
|
<div className="flex items-center justify-between border-b border-white/10 px-4 py-2">
|
||||||
|
<div className="text-sm text-white/70">Users</div>
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<select value={sort} onChange={e => setSort(e.target.value as 'requests' | 'latency' | 'last_seen')}
|
||||||
|
className="rounded bg-white/[0.04] px-2 py-1 text-xs text-white/80">
|
||||||
|
<option value="requests">requests</option>
|
||||||
|
<option value="latency">latency</option>
|
||||||
|
<option value="last_seen">last seen</option>
|
||||||
|
</select>
|
||||||
|
<input value={q} onChange={e => 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" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<table className="w-full text-left text-sm">
|
||||||
|
<thead className="text-xs uppercase text-white/40">
|
||||||
|
<tr>
|
||||||
|
<th className="px-4 py-2 font-normal">User</th>
|
||||||
|
<th className="px-4 py-2 font-normal">Req 7d</th>
|
||||||
|
<th className="px-4 py-2 font-normal">Last seen</th>
|
||||||
|
<th className="px-4 py-2 font-normal">Top endpoint</th>
|
||||||
|
<th className="px-4 py-2 text-right font-normal">Avg ms</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{loading && <tr><td colSpan={5} className="px-4 py-6 text-center text-white/40">loading…</td></tr>}
|
||||||
|
{!loading && sorted.length === 0 && (
|
||||||
|
<tr><td colSpan={5} className="px-4 py-6 text-center text-white/40">no users yet</td></tr>
|
||||||
|
)}
|
||||||
|
{sorted.map(u => (
|
||||||
|
<tr key={u.username} className="border-t border-white/5">
|
||||||
|
<td className="px-4 py-2 text-white/90">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
{u.github_avatar_url
|
||||||
|
? <img src={u.github_avatar_url} alt="" className="h-5 w-5 rounded-full" />
|
||||||
|
: <span className="inline-block h-5 w-5 rounded-full bg-white/10" />}
|
||||||
|
<span className="font-mono">{u.username}</span>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
<td className="px-4 py-2 font-mono text-white/80">{u.requests_7d.toLocaleString()}</td>
|
||||||
|
<td className="px-4 py-2 text-white/60">{timeAgo(u.last_seen)}</td>
|
||||||
|
<td className="px-4 py-2 font-mono text-white/60">{u.top_endpoint || '—'}</td>
|
||||||
|
<td className="px-4 py-2 text-right font-mono text-white/80">{u.avg_latency_ms}</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -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<T>(path: string): Promise<T> {
|
||||||
|
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<Summary>('/api/dev/summary')
|
||||||
|
export const fetchUsers = (q = '', sort = 'requests') =>
|
||||||
|
getJSON<UserRow[]>(`/api/dev/users?q=${encodeURIComponent(q)}&sort=${sort}`)
|
||||||
|
export const fetchLatency = () => getJSON<LatencyRow[]>('/api/dev/latency')
|
||||||
|
export const fetchHealth = () => getJSON<Health>('/api/dev/health')
|
||||||
@@ -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<Summary | null>(null)
|
||||||
|
const [error, setError] = useState<string | null>(null)
|
||||||
|
const [lastRefresh, setLastRefresh] = useState<Date>(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 (
|
||||||
|
<Shell>
|
||||||
|
<div className="rounded-lg border border-amber-500/30 bg-amber-500/[0.06] p-6 text-amber-200">
|
||||||
|
The /dev dashboard is not configured on this deploy
|
||||||
|
(set DEV_DASHBOARD_USER and DEV_DASHBOARD_PASSWORD).
|
||||||
|
</div>
|
||||||
|
</Shell>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if (error === 'unauthorized') {
|
||||||
|
return (
|
||||||
|
<Shell>
|
||||||
|
<div className="text-white/60">Sign in to view the dashboard. Reload to retry.</div>
|
||||||
|
</Shell>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Shell lastRefresh={lastRefresh}>
|
||||||
|
{s ? <StatCards s={s} /> : <div className="text-white/40">loading…</div>}
|
||||||
|
<div className="mt-6">
|
||||||
|
<UsersTable />
|
||||||
|
</div>
|
||||||
|
<div className="mt-6 grid grid-cols-1 gap-4 md:grid-cols-2">
|
||||||
|
<LatencyChart />
|
||||||
|
<HealthStrip />
|
||||||
|
</div>
|
||||||
|
</Shell>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function Shell({ children, lastRefresh }: { children: ReactNode; lastRefresh?: Date }) {
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen bg-[#0b0d10] px-6 py-6 text-white">
|
||||||
|
<div className="mx-auto max-w-6xl">
|
||||||
|
<header className="mb-6 flex items-baseline justify-between">
|
||||||
|
<h1 className="font-mono text-lg text-white/90">/dev · gh-stats analytics</h1>
|
||||||
|
{lastRefresh && (
|
||||||
|
<div className="text-xs text-white/40">
|
||||||
|
last refresh {lastRefresh.toLocaleTimeString()}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</header>
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -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
|
||||||
@@ -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": "/<u>", "widget": "composite",
|
||||||
|
"status": 200, "latency_ms": 12, "cache_hit": 1},
|
||||||
|
{"ts": 1001, "service": "edge", "kind": "request",
|
||||||
|
"username": "bob", "endpoint": "/<u>", "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": "/<u>", "widget": "composite",
|
||||||
|
"status": 200, "latency_ms": 10, "cache_hit": 1},
|
||||||
|
{"ts": now - 120, "service": "edge", "kind": "request",
|
||||||
|
"username": "bob", "endpoint": "/<u>", "widget": "composite",
|
||||||
|
"status": 200, "latency_ms": 50, "cache_hit": 0},
|
||||||
|
{"ts": now - 10 * 86400, "service": "edge", "kind": "request",
|
||||||
|
"username": "old", "endpoint": "/<u>", "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": "/<u>", "widget": "composite",
|
||||||
|
"status": 200, "latency_ms": 10, "cache_hit": 1},
|
||||||
|
{"ts": now - 30, "service": "edge", "kind": "request",
|
||||||
|
"username": "alice", "endpoint": "/<u>/grade.svg", "widget": "grade",
|
||||||
|
"status": 200, "latency_ms": 20, "cache_hit": 1},
|
||||||
|
{"ts": now - 10, "service": "edge", "kind": "request",
|
||||||
|
"username": "alice", "endpoint": "/<u>", "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"] == "/<u>"
|
||||||
|
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": "/<u>", "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["/<u>"]["count"] == 100
|
||||||
|
assert by_ep["/<u>"]["p50"] == 50
|
||||||
|
assert by_ep["/<u>"]["p95"] == 95
|
||||||
|
assert by_ep["/<u>"]["p99"] == 99
|
||||||
|
|
||||||
|
|
||||||
|
def test_query_health(fresh):
|
||||||
|
now = int(time.time())
|
||||||
|
a.ingest_batch([
|
||||||
|
{"ts": now - 1, "service": "edge", "kind": "request",
|
||||||
|
"username": "u", "endpoint": "/<u>", "widget": "composite",
|
||||||
|
"status": 200, "latency_ms": 1, "cache_hit": 1},
|
||||||
|
{"ts": now - 2, "service": "edge", "kind": "request",
|
||||||
|
"username": "u", "endpoint": "/<u>", "widget": "composite",
|
||||||
|
"status": 200, "latency_ms": 1, "cache_hit": 0},
|
||||||
|
{"ts": now - 3, "service": "fetcher", "kind": "fetch",
|
||||||
|
"username": "u", "endpoint": "github/users/<u>",
|
||||||
|
"status": 500, "latency_ms": 100},
|
||||||
|
{"ts": now - 4, "service": "fetcher", "kind": "fetch",
|
||||||
|
"username": "u", "endpoint": "github/users/<u>",
|
||||||
|
"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": "/<u>", "widget": "composite",
|
||||||
|
"status": 200, "latency_ms": 1, "cache_hit": 1},
|
||||||
|
{"ts": now, "service": "edge", "kind": "request",
|
||||||
|
"username": "u", "endpoint": "/<u>", "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
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
"""Per-widget attribution behaves correctly in both contexts.
|
||||||
|
|
||||||
|
Standalone widget SVGs (served at /api/<u>/<widget>.svg) must show the
|
||||||
|
"Generated with gh-stats" footer; the composite (served at /api/<u>)
|
||||||
|
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
|
||||||
Reference in New Issue
Block a user