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
+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:
db.touch_last_requested(username)
return jsonify({"status": "building"}), 202
try:
result = fetcher_client.get_data(username)
except Exception as e:
return jsonify({"error": f"fetcher unavailable: {e}"}), 502
db.touch_last_requested(username)
payload = result.get("data") or {}
if payload.get("error") == "not_found" or "user" not in payload:
return jsonify({"error": "not_found"}), 404
row = db.get_current_widget_data(username)
if row is None:
return jsonify({"status": "building"}), 202
custom_tags = request.args.getlist("custom_tags") or None
hidden_languages = request.args.getlist("hidden_languages") or None
# 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
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()