feat(api): implement precomputed widget data storage and retrieval.

This commit is contained in:
shay
2026-04-18 11:13:43 -04:00
parent f0c6edacf6
commit 79b9c31197
7 changed files with 207 additions and 94 deletions
+66 -22
View File
@@ -1,9 +1,10 @@
import { useState, useRef, useCallback } from 'react'
import { useState, useRef, useCallback, useEffect } from 'react'
import './index.css'
import { SearchScreen } from './screens/SearchScreen'
import { WorkshopScreen } from './screens/WorkshopScreen'
import { ResultScreen } from './screens/ResultScreen'
import type { WidgetData } from './lib/renderWidgets'
import { DEMO_WIDGET_DATA } from './lib/demoData'
export type Achievement = {
title: string
@@ -43,41 +44,81 @@ const DEFAULT_SETTINGS: WidgetSettings = {
type Step = 'search' | 'workshop' | 'result'
const POLL_INTERVAL_MS = 2000
const POLL_TIMEOUT_MS = 120_000
export default function App() {
const [step, setStep] = useState<Step>('search')
const [username, setUsername] = useState('')
const [settings, setSettings] = useState<WidgetSettings>({ ...DEFAULT_SETTINGS })
const [widgetData, setWidgetData] = useState<WidgetData | null>(null)
const [isDemo, setIsDemo] = useState(false)
const [fetchDone, setFetchDone] = useState(false)
const [fetchError, setFetchError] = useState<string | null>(null)
const fetchRef = useRef<AbortController | null>(null)
const pollTimer = useRef<number | null>(null)
const pollStart = useRef<number>(0)
const aborted = useRef(false)
const stopPolling = useCallback(() => {
if (pollTimer.current != null) {
window.clearTimeout(pollTimer.current)
pollTimer.current = null
}
}, [])
useEffect(() => stopPolling, [stopPolling])
const startFetch = useCallback((user: string) => {
if (fetchRef.current) fetchRef.current.abort()
const ctrl = new AbortController()
fetchRef.current = ctrl
stopPolling()
aborted.current = false
pollStart.current = Date.now()
setFetchDone(false)
setFetchError(null)
setWidgetData(null)
// Show demo data immediately so Workshop is interactive while the worker builds.
setWidgetData(DEMO_WIDGET_DATA)
setIsDemo(true)
fetch(`/api/${encodeURIComponent(user)}/data`, { signal: ctrl.signal })
.then(async r => {
if (r.status === 404) throw new Error('User not found')
if (!r.ok) throw new Error(`Fetch failed (${r.status})`)
return r.json()
})
.then(json => {
setWidgetData(json.data)
const poll = async () => {
if (aborted.current) return
try {
const r = await fetch(`/api/${encodeURIComponent(user)}/data`)
if (aborted.current) return
const body = await r.json().catch(() => ({} as { status?: string; data?: WidgetData }))
const status = body.status
if (r.status === 200 && status === 'ready' && body.data) {
setWidgetData(body.data)
setIsDemo(false)
setFetchDone(true)
})
.catch(e => {
if (e.name !== 'AbortError') {
console.warn('Fetch error:', e)
setFetchError(e.message)
return
}
if (r.status === 404 || status === 'not_found') {
setFetchError('User not found')
setFetchDone(true)
return
}
if (r.status === 429 || status === 'rate_limited') {
setFetchError('Enrollment limit reached — try again tomorrow')
setFetchDone(true)
return
}
// 202 building (or any non-terminal) — poll again until timeout.
if (Date.now() - pollStart.current > POLL_TIMEOUT_MS) {
setFetchError('Still building — refresh to keep waiting')
setFetchDone(true)
return
}
pollTimer.current = window.setTimeout(poll, POLL_INTERVAL_MS)
} catch (e) {
if (aborted.current) return
console.warn('Data poll failed:', e)
setFetchError('Network error')
setFetchDone(true)
}
})
}, [])
}
poll()
}, [stopPolling])
const handleSearch = (user: string) => {
setUsername(user)
@@ -92,7 +133,8 @@ export default function App() {
const handleBack = () => {
if (step === 'result') setStep('workshop')
else if (step === 'workshop') {
if (fetchRef.current) fetchRef.current.abort()
aborted.current = true
stopPolling()
setStep('search')
}
}
@@ -110,6 +152,8 @@ export default function App() {
onGenerate={handleGenerate}
onBack={handleBack}
fetchDone={fetchDone}
fetchError={fetchError}
isDemo={isDemo}
widgetData={widgetData}
/>
)}
@@ -85,6 +85,8 @@ type Props = {
onGenerate: () => void
onBack: () => void
fetchDone: boolean
fetchError: string | null
isDemo: boolean
widgetData: WidgetData | null
}
@@ -95,6 +97,8 @@ export function WorkshopScreen({
onGenerate,
onBack,
fetchDone,
fetchError,
isDemo,
widgetData,
}: Props) {
const [expandedWidget, setExpandedWidget] = useState<string | null>(null)
@@ -175,7 +179,17 @@ export function WorkshopScreen({
<div className="text-sm font-semibold text-gray-800 mb-1">{username}</div>
<div className="flex items-center gap-1.5 text-[10px] text-gray-400 mb-6">
{fetchDone ? (
{fetchError ? (
<>
<div className="w-1.5 h-1.5 rounded-full bg-red-400" />
{fetchError}
</>
) : isDemo ? (
<>
<div className="w-1.5 h-1.5 rounded-full bg-amber-400 animate-pulse" />
Building your widget — showing demo
</>
) : fetchDone ? (
<>
<div className="w-1.5 h-1.5 rounded-full bg-emerald-400" />
Data ready
+17 -31
View File
@@ -6,11 +6,10 @@ Serves:
/api/* -> JSON/SVG API
"""
import os
from dataclasses import asdict
from functools import wraps
from flask import Flask, jsonify, request, Response, send_from_directory
from . import config, db, fetcher_client, placeholder, processor
from . import config, db, fetcher_client, placeholder
_STATIC_DIR = os.path.join(os.path.dirname(__file__), "static")
@@ -57,50 +56,37 @@ def get_widget_named(username: str, widget: str):
@app.route("/api/<username>/data", methods=["GET"])
def get_user_data(username: str):
"""Computed widget data for client-side SVG rendering.
"""Precomputed widget data for client-side SVG rendering.
Auto-enrolls on first access (so the user appears in settings + the cron
keeps their data warm), then computes the data on-demand from fresh
fetcher output. Not cached at this layer — the fetcher already caches raw
GitHub payloads.
Pure DB lookup — never touches the fetcher or runs compute on the hot
path. On miss: auto-enroll (queues an async build) and return
`{status: "building"}` with HTTP 202 so the client can show demo data
and poll until ready.
"""
settings_row = db.get_settings(username)
if settings_row is None:
if db.enrollments_today() >= config.ENROLLMENT_DAILY_CAP:
return jsonify({"error": "rate_limited"}), 429
return jsonify({"status": "rate_limited"}), 429
defaults = {
"theme": "dark",
"enabled": config.ENABLED_WIDGETS,
"widget_order": config.WIDGET_ORDER,
}
db.enroll(username, defaults)
else:
return jsonify({"status": "building"}), 202
db.touch_last_requested(username)
try:
result = fetcher_client.get_data(username)
except Exception as e:
return jsonify({"error": f"fetcher unavailable: {e}"}), 502
row = db.get_current_widget_data(username)
if row is None:
return jsonify({"status": "building"}), 202
payload = result.get("data") or {}
if payload.get("error") == "not_found" or "user" not in payload:
return jsonify({"error": "not_found"}), 404
# Worker writes settings_hash="not_found" + data={"not_found": True}
# when GitHub returns 404 for this username.
if row["settings_hash"] == "not_found":
return jsonify({"status": "not_found"}), 404
custom_tags = request.args.getlist("custom_tags") or None
hidden_languages = request.args.getlist("hidden_languages") or None
try:
data = {
"grade": asdict(processor.compute_grade(payload, custom_tags=custom_tags)),
"impact": [asdict(w) for w in processor.compute_impact_timeline(payload)],
"collaborators": [asdict(c) for c in processor.compute_collaborators(payload)],
"focus": [asdict(f) for f in processor.compute_focus(payload, hidden_languages=hidden_languages)],
"languages": [asdict(l) for l in processor.compute_languages(payload, hidden_languages=hidden_languages)],
}
except Exception as e:
return jsonify({"error": f"processing failed: {e}"}), 500
return jsonify({"data": data})
return jsonify({"status": "ready", "data": row["data"]})
def _serve(username: str, widget_name: str) -> Response:
+43
View File
@@ -57,7 +57,15 @@ CREATE TABLE IF NOT EXISTS current_widget (
settings_hash TEXT NOT NULL,
updated_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS widget_data (
username TEXT NOT NULL,
settings_hash TEXT NOT NULL,
data_json TEXT NOT NULL,
built_at TEXT NOT NULL,
PRIMARY KEY (username, settings_hash)
);
CREATE INDEX IF NOT EXISTS idx_widgets_username ON widgets(username);
CREATE INDEX IF NOT EXISTS idx_widget_data_username ON widget_data(username);
"""
@@ -293,6 +301,37 @@ def get_current_widget(username: str, widget_name: str) -> Optional[str]:
return row["svg"] if row else None
def put_widget_data(username: str, hash_: str, data: dict) -> None:
"""Store computed widget data for client-side rendering. Keyed to the
same (username, settings_hash) that widgets are — the worker writes both
in the same build pass."""
now = _now()
with _widgets_conn() as c:
c.execute(
"""INSERT INTO widget_data(username, settings_hash, data_json, built_at)
VALUES (?, ?, ?, ?)
ON CONFLICT(username, settings_hash) DO UPDATE SET
data_json = excluded.data_json, built_at = excluded.built_at""",
(username, hash_, json.dumps(data, separators=(",", ":")), now),
)
c.commit()
def get_current_widget_data(username: str) -> Optional[dict]:
"""Returns {'data': <dict>, 'settings_hash': str} for the pointer in
current_widget, or None if nothing is built yet."""
with _widgets_conn() as c:
row = c.execute(
"""SELECT wd.data_json, wd.settings_hash FROM widget_data wd
JOIN current_widget cw ON cw.username=wd.username AND cw.settings_hash=wd.settings_hash
WHERE wd.username=?""",
(username,),
).fetchone()
if row is None:
return None
return {"data": json.loads(row["data_json"]), "settings_hash": row["settings_hash"]}
def lru_trim(username: str, keep: int) -> int:
"""Keep only the N newest settings_hashes per user; delete older rows."""
with _widgets_conn() as c:
@@ -309,5 +348,9 @@ def lru_trim(username: str, keep: int) -> int:
f"DELETE FROM widgets WHERE username=? AND settings_hash IN ({placeholders})",
(username, *to_delete),
)
c.execute(
f"DELETE FROM widget_data WHERE username=? AND settings_hash IN ({placeholders})",
(username, *to_delete),
)
c.commit()
return cur.rowcount
+18
View File
@@ -4,6 +4,7 @@ Run as its own container: CMD python -m src.worker
"""
import logging
import time
from dataclasses import asdict
from . import cache, config, db, fetcher_client, placeholder, processor
from .widgets import compose_widget
@@ -12,6 +13,20 @@ log = logging.getLogger("generator.worker")
MAX_ATTEMPTS = 3
def _compute_widget_data(payload: dict, settings: dict) -> dict:
"""Compute raw widget data dict for client-side rendering. Written
alongside SVGs so the /api/<u>/data endpoint is a precomputed lookup."""
custom_tags = settings.get("custom_tags")
hidden_languages = settings.get("hidden_languages")
return {
"grade": asdict(processor.compute_grade(payload, custom_tags=custom_tags)),
"impact": [asdict(w) for w in processor.compute_impact_timeline(payload)],
"collaborators": [asdict(c) for c in processor.compute_collaborators(payload)],
"focus": [asdict(f) for f in processor.compute_focus(payload, hidden_languages=hidden_languages)],
"languages": [asdict(l) for l in processor.compute_languages(payload, hidden_languages=hidden_languages)],
}
def _render_widgets(username: str, payload: dict, settings: dict) -> dict[str, str]:
enabled = settings.get("enabled") or config.ENABLED_WIDGETS
order = settings.get("widget_order") or config.WIDGET_ORDER
@@ -45,6 +60,7 @@ def process_one() -> bool:
if payload.get("error") == "not_found":
svg = placeholder.render("not_found", username, theme="dark")
db.put_widgets(username, "not_found", {"composite": svg})
db.put_widget_data(username, "not_found", {"not_found": True})
cache.Cache().delete(f"widget:composite:{username}")
db.complete_job(job["id"])
log.info("not_found marker persisted for %s", username)
@@ -56,7 +72,9 @@ def process_one() -> bool:
return True
widgets = _render_widgets(username, payload, settings_row["settings"])
widget_data = _compute_widget_data(payload, settings_row["settings"])
db.put_widgets(username, settings_row["settings_hash"], widgets)
db.put_widget_data(username, settings_row["settings_hash"], widget_data)
db.set_last_fetcher_hash(username, result.get("payload_hash", ""))
db.lru_trim(username, config.WIDGET_LRU_PER_USER)
c = cache.Cache()
+40 -37
View File
@@ -75,54 +75,57 @@ def test_not_found_status_header(client):
assert r.headers["X-Widget-Status"] == "not_found"
# ---- GET /api/<username>/data: computed widget data for client-side rendering ----
_FAKE_GITHUB_DATA = {
"user": {"login": "alice", "followers": 10},
"repos": [{"language": "Python", "stargazers_count": 5, "forks_count": 1, "topics": []}],
"events": [],
"commits": [],
"total_commits": 42,
"total_prs": 3,
"recent_commits": 20,
}
# ---- GET /api/<username>/data: precomputed widget data for client-side rendering ----
# Pure DB lookup — fetcher is never touched on the hot path.
def test_data_endpoint_auto_enrolls_and_returns_widget_data(client, monkeypatch):
monkeypatch.setattr(
apimod.fetcher_client, "get_data",
lambda u: {"data": _FAKE_GITHUB_DATA, "payload_hash": "h1", "fetched": True},
)
def test_data_endpoint_unknown_user_enrolls_and_returns_building(client):
r = client.get("/api/alice/data")
assert r.status_code == 200
body = r.get_json()
assert "data" in body
for key in ("grade", "impact", "collaborators", "focus", "languages"):
assert key in body["data"]
assert body["data"]["grade"]["grade"] # non-empty letter grade
assert r.status_code == 202
assert r.get_json() == {"status": "building"}
assert dbmod.get_settings("alice") is not None # auto-enrolled
def test_data_endpoint_returns_404_for_unknown_github_user(client, monkeypatch):
monkeypatch.setattr(
apimod.fetcher_client, "get_data",
lambda u: {"data": {"error": "not_found"}, "payload_hash": "nf"},
)
def test_data_endpoint_enrolled_but_unbuilt_returns_building(client):
dbmod.enroll("alice", {"theme": "dark"})
r = client.get("/api/alice/data")
assert r.status_code == 202
assert r.get_json() == {"status": "building"}
def test_data_endpoint_returns_ready_after_build(client):
dbmod.enroll("alice", {"theme": "dark"})
sample = {"grade": {"grade": "A", "score": 80, "stats": {}, "tags": [], "breakdown": {}}}
dbmod.put_widget_data("alice", "h1", sample)
with dbmod._widgets_conn() as c:
c.execute(
"""INSERT INTO current_widget(username, settings_hash, updated_at)
VALUES ('alice', 'h1', '2026-04-18T00:00:00Z')
ON CONFLICT(username) DO UPDATE SET settings_hash=excluded.settings_hash""")
c.commit()
r = client.get("/api/alice/data")
assert r.status_code == 200
body = r.get_json()
assert body["status"] == "ready"
assert body["data"] == sample
def test_data_endpoint_returns_not_found_for_unknown_github_user(client):
dbmod.enroll("ghost", {"theme": "dark"})
dbmod.put_widget_data("ghost", "not_found", {"not_found": True})
with dbmod._widgets_conn() as c:
c.execute(
"""INSERT INTO current_widget(username, settings_hash, updated_at)
VALUES ('ghost', 'not_found', '2026-04-18T00:00:00Z')
ON CONFLICT(username) DO UPDATE SET settings_hash=excluded.settings_hash""")
c.commit()
r = client.get("/api/ghost/data")
assert r.status_code == 404
assert r.get_json()["error"] == "not_found"
def test_data_endpoint_502_when_fetcher_fails(client, monkeypatch):
def boom(_u):
raise RuntimeError("connection refused")
monkeypatch.setattr(apimod.fetcher_client, "get_data", boom)
r = client.get("/api/alice/data")
assert r.status_code == 502
assert r.get_json()["status"] == "not_found"
def test_data_endpoint_rate_limited_before_enroll(client, monkeypatch):
monkeypatch.setattr(apimod.config, "ENROLLMENT_DAILY_CAP", 0)
r = client.get("/api/newbie/data")
assert r.status_code == 429
assert r.get_json()["error"] == "rate_limited"
assert r.get_json()["status"] == "rate_limited"
+7 -2
View File
@@ -16,15 +16,20 @@ def tmp_dbs(monkeypatch):
def test_process_one_renders_and_stores_widgets(tmp_dbs):
dbmod.enroll("alice", {"theme": "dark", "enabled": ["grade"]})
fake_payload = {"user": {"login": "alice"}, "repos": [], "events": [],
"commits": [], "total_commits": 0, "recent_commits": [],
"commits": [], "total_commits": 0, "recent_commits": 0,
"total_prs": 0, "collaborators_data": [], "avatar_b64": ""}
fake_data = {"grade": {"grade": "A", "score": 80, "stats": {}, "tags": [], "breakdown": {}}}
with patch("src.worker.fetcher_client.get_data",
return_value={"data": fake_payload, "payload_hash": "h1"}), \
patch("src.worker._render_widgets",
return_value={"composite": "<svg>c</svg>", "grade": "<svg>g</svg>"}):
return_value={"composite": "<svg>c</svg>", "grade": "<svg>g</svg>"}), \
patch("src.worker._compute_widget_data", return_value=fake_data):
worker.process_one()
svg = dbmod.get_current_widget("alice", "composite")
assert svg == "<svg>c</svg>"
# Data JSON is written alongside the SVGs so the /data endpoint is a lookup.
row = dbmod.get_current_widget_data("alice")
assert row is not None and row["data"] == fake_data
def test_not_found_payload_renders_not_found_placeholder(tmp_dbs):