diff --git a/generator/frontend/src/App.tsx b/generator/frontend/src/App.tsx
index 4504792..3f63104 100644
--- a/generator/frontend/src/App.tsx
+++ b/generator/frontend/src/App.tsx
@@ -126,8 +126,17 @@ export default function App() {
setStep('workshop')
}
- const handleGenerate = () => {
+ const handleGenerate = async () => {
setStep('result')
+ // Fire-and-forget: the backend renders the composite SVG from the
+ // fetcher's cached payload + current settings and persists it to
+ // widgets.db for README embeds. The Result screen itself still
+ // renders client-side from widgetData for immediate feedback.
+ try {
+ await fetch(`/api/${encodeURIComponent(username)}/generate`, { method: 'POST' })
+ } catch (e) {
+ console.warn('generate call failed:', e)
+ }
}
const handleBack = () => {
diff --git a/generator/src/api.py b/generator/src/api.py
index ec85881..ea4059e 100644
--- a/generator/src/api.py
+++ b/generator/src/api.py
@@ -4,6 +4,15 @@ Serves:
/ -> React SPA (static/index.html)
/assets/
-> 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//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//generate. Before that the
+ endpoint returns a "building" placeholder; enrollment is frontend-
+ driven (via /api//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//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//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})
diff --git a/generator/src/db.py b/generator/src/db.py
index 0b01a52..e13f9fa 100644
--- a/generator/src/db.py
+++ b/generator/src/db.py
@@ -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(
diff --git a/generator/src/worker.py b/generator/src/worker.py
index 0626200..8f06a45 100644
--- a/generator/src/worker.py
+++ b/generator/src/worker.py
@@ -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//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//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()
diff --git a/generator/tests/integration/test_end_to_end.py b/generator/tests/integration/test_end_to_end.py
index d138091..be4c8fc 100644
--- a/generator/tests/integration/test_end_to_end.py
+++ b/generator/tests/integration/test_end_to_end.py
@@ -17,7 +17,12 @@ def env(monkeypatch):
@responses.activate
-def test_first_request_builds_then_serves_ready(env):
+def test_full_flow_data_then_generate_then_serve(env):
+ """End-to-end of the new two-phase pipeline:
+ 1. /data enrolls + kicks off prefetch (worker populates widget_data)
+ 2. /generate renders SVG from the cached payload + settings
+ 3. /api/ serves the stored SVG to README consumers
+ """
responses.add(
responses.GET, "http://fetcher-mock/data/alice",
json={"data": {"user": {"login": "alice"}, "repos": [], "events": [],
@@ -27,20 +32,31 @@ def test_first_request_builds_then_serves_ready(env):
)
client = apimod.app.test_client()
- r1 = client.get("/api/alice")
- assert r1.headers["X-Widget-Status"] == "building"
+ # Phase 1: prefetch via /data (enrolls + kicks off background thread).
+ r_data = client.get("/api/alice/data")
+ assert r_data.status_code == 202
- # First request kicks off a background build thread; drain any residual
- # job in case of races, then poll the API for readiness.
+ # Drain any residual job synchronously in case the kickoff thread lost
+ # the race (and to make the assertion deterministic).
for _ in range(5):
if not worker.process_one():
break
+ # Widget data should now be available for client-side preview.
deadline = time.time() + 2.0
while time.time() < deadline:
- r2 = client.get("/api/alice")
- if r2.headers["X-Widget-Status"] == "ready":
+ r = client.get("/api/alice/data")
+ if r.status_code == 200 and r.get_json().get("status") == "ready":
break
time.sleep(0.05)
- assert r2.headers["X-Widget-Status"] == "ready"
- assert r2.data.startswith(b"