chore(api): rename test function for clarity on enrollment behavior

This commit is contained in:
shay
2026-04-18 11:58:02 -04:00
parent f9c59d934d
commit 7b2301cec0
7 changed files with 239 additions and 71 deletions
+61 -27
View File
@@ -4,6 +4,15 @@ Serves:
/ -> React SPA (static/index.html)
/assets/<p> -> SPA bundles
/api/* -> JSON/SVG API
Two-phase pipeline:
* Enrollment / settings change enqueues a prefetch job and kicks it off
in a background thread so the fetcher starts pulling GitHub data the
instant the user submits a username. The thread only hydrates
widget_data for the client-side Workshop preview — it does not render
SVGs.
* POST /api/<u>/generate synchronously renders and persists the composite
SVG. This is what the user's "Generate" button calls.
"""
import logging
import os
@@ -16,21 +25,19 @@ from . import config, db, fetcher_client, placeholder
log = logging.getLogger("generator.api")
def _kickoff_build():
"""Run one build cycle in a background thread. Eliminates the worker's
poll latency for users who just enrolled or patched settings. The worker
container still drains the queue; this just gives interactive requests
a head start so the build runs concurrently with the user filling out
the workshop page."""
def _kickoff_prefetch():
"""Run one prefetch cycle in a background thread. Starts the fetcher
immediately on enrollment / settings-change so the raw GitHub payload
is hot by the time the user clicks Generate."""
try:
from . import worker
worker.process_one()
except Exception:
log.exception("background build kickoff failed")
log.exception("background prefetch kickoff failed")
def _kickoff_build_async():
Thread(target=_kickoff_build, daemon=True).start()
def _kickoff_prefetch_async():
Thread(target=_kickoff_prefetch, daemon=True).start()
_STATIC_DIR = os.path.join(os.path.dirname(__file__), "static")
@@ -94,7 +101,7 @@ def get_user_data(username: str):
"widget_order": config.WIDGET_ORDER,
}
db.enroll(username, defaults)
_kickoff_build_async()
_kickoff_prefetch_async()
return jsonify({"status": "building"}), 202
db.touch_last_requested(username)
@@ -112,29 +119,30 @@ def get_user_data(username: str):
def _serve(username: str, widget_name: str) -> Response:
settings_row = db.get_settings(username)
"""Serves a cached SVG for README embeds.
SVGs are only produced by POST /api/<u>/generate. Before that the
endpoint returns a "building" placeholder; enrollment is frontend-
driven (via /api/<u>/data or /api/enroll) so this path never auto-
enrolls on its own.
"""
settings_row = db.get_settings(username)
if settings_row is None:
if db.enrollments_today() >= config.ENROLLMENT_DAILY_CAP:
return _placeholder_response("rate_limited", username)
defaults = {
"theme": "dark",
"enabled": config.ENABLED_WIDGETS,
"widget_order": config.WIDGET_ORDER,
}
db.enroll(username, defaults)
_kickoff_build_async()
return _placeholder_response("building", username)
db.touch_last_requested(username)
svg = db.get_current_widget(username, widget_name)
if svg is None:
return _placeholder_response("building", username, theme=settings_row["settings"].get("theme", "dark"))
current_hash = db.get_current_widget_hash(username)
theme = settings_row["settings"].get("theme", "dark")
if settings_row.get("settings_hash") == "not_found":
if current_hash == "not_found":
svg = db.get_current_widget(username, widget_name) or placeholder.render("not_found", username, theme=theme)
return Response(svg, mimetype="image/svg+xml",
headers={"X-Widget-Status": "not_found", "Cache-Control": "no-store"})
svg = db.get_current_widget(username, widget_name)
if svg is None:
return _placeholder_response("building", username, theme=theme)
return Response(svg, mimetype="image/svg+xml",
headers={"X-Widget-Status": "ready",
"Cache-Control": "public, max-age=3600"})
@@ -158,7 +166,7 @@ def enroll_endpoint():
return jsonify({"error": "rate_limited"}), 429
defaults = {"theme": "dark", "enabled": config.ENABLED_WIDGETS, "widget_order": config.WIDGET_ORDER}
job_id = db.enroll(username, defaults)
_kickoff_build_async()
_kickoff_prefetch_async()
return jsonify({"enrolled": True, "job_id": job_id})
@@ -180,10 +188,36 @@ def patch_settings(username: str):
body = request.get_json(silent=True) or {}
merged = {**current["settings"], **body}
job_id = db.update_settings(username, merged)
_kickoff_build_async()
_kickoff_prefetch_async()
return jsonify({"updated": True, "job_id": job_id})
@app.route("/api/<username>/generate", methods=["POST"])
def generate(username: str):
"""Render the composite SVG from the cached fetcher payload + current
settings, persist it to widgets.db, and return status. Called by the
Generate button; safe to call repeatedly (each call re-renders with
the latest settings)."""
from . import worker
if db.get_settings(username) is None:
return jsonify({"error": "not_enrolled"}), 404
try:
widgets = worker.render_widgets_now(username)
except LookupError:
return jsonify({"error": "not_enrolled"}), 404
except Exception as e:
log.exception("generate failed for %s", username)
return jsonify({"error": f"render_failed: {e}"}), 502
current_hash = db.get_current_widget_hash(username)
if current_hash == "not_found":
return jsonify({"status": "not_found"}), 404
return jsonify({
"status": "ready",
"composite_url": f"/api/{username}",
"widgets": list(widgets.keys()),
})
@app.route("/api/<username>/refresh", methods=["POST"])
@require_auth
def refresh(username: str):
@@ -197,7 +231,7 @@ def refresh(username: str):
except Exception as e:
return jsonify({"error": f"fetch failed: {e}"}), 502
job_id = db.enqueue_build(username)
_kickoff_build_async()
_kickoff_prefetch_async()
return jsonify({"refreshed": True, "job_id": job_id})
+27
View File
@@ -290,6 +290,33 @@ def put_widgets(username: str, hash_: str, widgets: dict[str, str]) -> None:
c.commit()
def get_current_widget_hash(username: str) -> Optional[str]:
"""The settings_hash that current_widget points at (or None if nothing
has been prefetched/rendered yet). Distinct from users.settings_hash,
which is the hash of the *currently configured* settings."""
with _widgets_conn() as c:
row = c.execute(
"SELECT settings_hash FROM current_widget WHERE username=?",
(username,),
).fetchone()
return row["settings_hash"] if row else None
def point_current_widget(username: str, hash_: str) -> None:
"""Flip the current_widget pointer to a settings_hash. Used by the
prefetch worker (which writes only widget_data, not SVG rows) and by
the render path (which writes both, but calls this too for clarity)."""
now = _now()
with _widgets_conn() as c:
c.execute(
"""INSERT INTO current_widget(username, settings_hash, updated_at)
VALUES (?, ?, ?)
ON CONFLICT(username) DO UPDATE SET settings_hash=excluded.settings_hash, updated_at=excluded.updated_at""",
(username, hash_, now),
)
c.commit()
def get_current_widget(username: str, widget_name: str) -> Optional[str]:
with _widgets_conn() as c:
row = c.execute(
+46 -12
View File
@@ -1,4 +1,15 @@
"""Build worker. Pulls pending jobs and renders widgets.
"""Prefetch worker. Pulls pending jobs and populates widget data.
Two-phase pipeline:
* Phase 1 (this module): on enroll/settings-change, fetch the raw GitHub
payload from the fetcher and compute widget data for the client-side
Workshop preview. No SVG rendering.
* Phase 2 (render_widgets_now, called from the API's Generate endpoint):
synchronously render composite SVG from the cached raw + current
settings and persist to widgets.db.
This split keeps the fetcher hot while the user edits settings and defers
expensive SVG composition until the user clicks Generate.
Run as its own container: CMD python -m src.worker
"""
@@ -14,8 +25,7 @@ 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."""
"""Compute raw widget data dict for client-side rendering."""
custom_tags = settings.get("custom_tags")
hidden_languages = settings.get("hidden_languages")
return {
@@ -50,6 +60,7 @@ def _render_widgets(username: str, payload: dict, settings: dict) -> dict[str, s
def process_one() -> bool:
"""Phase 1: claim a pending job and populate widget data (no SVG)."""
job = db.claim_next_job()
if job is None:
return False
@@ -58,10 +69,8 @@ def process_one() -> bool:
result = fetcher_client.get_data(username)
payload = result.get("data") or {}
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.point_current_widget(username, "not_found")
db.complete_job(job["id"])
log.info("not_found marker persisted for %s", username)
return True
@@ -71,24 +80,49 @@ def process_one() -> bool:
db.fail_job(job["id"], "settings missing", retry=False)
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.point_current_widget(username, settings_row["settings_hash"])
db.set_last_fetcher_hash(username, result.get("payload_hash", ""))
db.lru_trim(username, config.WIDGET_LRU_PER_USER)
c = cache.Cache()
c.delete(f"widget:composite:{username}", *[f"widget:{n}:{username}" for n in widgets])
db.complete_job(job["id"])
log.info("built widgets for %s", username)
log.info("prefetched data for %s", username)
return True
except Exception as e:
retry = job["attempts"] < MAX_ATTEMPTS
db.fail_job(job["id"], str(e)[:500], retry=retry)
log.warning("build failed for %s (retry=%s): %s", username, retry, e)
log.warning("prefetch failed for %s (retry=%s): %s", username, retry, e)
return True
def render_widgets_now(username: str) -> dict[str, str]:
"""Phase 2: synchronously render composite SVG and persist it.
Called from POST /api/<u>/generate. Reuses the fetcher's cached payload
(a cheap internal HTTP lookup) so the user-facing render is fast even
if the prefetch job hasn't drained from the queue yet.
"""
settings_row = db.get_settings(username)
if settings_row is None:
raise LookupError("not_enrolled")
result = fetcher_client.get_data(username)
payload = result.get("data") or {}
if payload.get("error") == "not_found":
svg = placeholder.render("not_found", username, theme=settings_row["settings"].get("theme", "dark"))
db.put_widgets(username, "not_found", {"composite": svg})
db.point_current_widget(username, "not_found")
cache.Cache().delete(f"widget:composite:{username}")
return {"composite": svg}
widgets = _render_widgets(username, payload, settings_row["settings"])
db.put_widgets(username, settings_row["settings_hash"], widgets)
db.point_current_widget(username, settings_row["settings_hash"])
c = cache.Cache()
c.delete(f"widget:composite:{username}", *[f"widget:{n}:{username}" for n in widgets])
log.info("rendered widgets on-demand for %s", username)
return widgets
def main():
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s")
db.init_dbs()