feat(admin dashboard): add admin dashboard

This commit is contained in:
shay
2026-05-11 18:26:43 -04:00
parent 00bf46968a
commit ef48d2581b
14 changed files with 1225 additions and 0 deletions
+91
View File
@@ -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
+57
View File
@@ -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)