Files
github-readme-stats/generator/src/worker.py
T

225 lines
9.6 KiB
Python

"""Prefetch worker. Pulls pending jobs, populates widget data, renders SVGs.
Each job (from enroll/settings-change/cron-detected payload change) goes
through two steps in one pass: compute the widget_data dict for the client-
side Workshop preview, then render and persist the composite + per-widget
SVGs so embedded README widgets stay fresh as the underlying GitHub data
rotates. The /generate endpoint reuses the same render path for on-demand
re-renders triggered by the Generate button.
Run as its own container: CMD python -m src.worker
"""
import logging
import time
from dataclasses import asdict
from . import analytics, cache, config, db, fetcher_client, placeholder, processor
from .widgets import compose_widget
log = logging.getLogger("generator.worker")
MAX_ATTEMPTS = 3
def _compute_widget_data(payload: dict, settings: dict, username: str) -> dict:
"""Compute raw widget data dict for client-side rendering.
Also persists the user's streak state as a side effect — the longest streak
must survive settings-hash rotations, so it lives outside widget_data.
"""
custom_tags = settings.get("custom_tags")
hidden_languages = settings.get("hidden_languages")
stored_streak = db.get_user_streak(username)
streak = processor.compute_streaks(payload, stored_streak)
db.put_user_streak(username, {
"current_streak": streak.current,
"current_start": streak.current_start,
"last_active_date": streak.last_active_date,
"max_streak": streak.max,
"max_start": streak.max_start,
"max_end": streak.max_end,
})
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)],
"streaks": asdict(streak),
}
def _render_and_persist(username: str, payload: dict, settings: dict, settings_hash: str) -> None:
"""Render SVGs from the payload and persist to widgets.db. Used by the
cron-driven worker so embedded widgets keep ticking forward (streak
counter, etc.) as the fetcher refreshes the underlying data — without
waiting for the user to manually click Generate."""
t0 = time.monotonic()
widgets = _render_widgets(username, payload, settings)
db.put_widgets(username, settings_hash, widgets)
cache.Cache().delete(
f"widget:composite:{username}",
*[f"widget:{n}:{username}" for n in widgets],
)
analytics.record_render(username, "composite",
int((time.monotonic() - t0) * 1000))
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
theme = settings.get("theme", "dark")
stored_streak = db.get_user_streak(username)
widgets = processor.generate_widgets_from_github(
payload,
theme=theme,
custom_tags=settings.get("custom_tags"),
hidden_languages=settings.get("hidden_languages"),
enabled=enabled,
widget_settings=settings.get("widget_settings") or {},
achievements=settings.get("achievements") or [],
stored_streak=stored_streak,
)
enabled_set = set(enabled)
show_name = "name" in enabled_set
# Preserve "name" in the ordered list so the composite honors its
# user-ordered position (always 0 today, but future-proof).
ordered = [
w for w in order
if w in enabled_set and (w == "name" or (w in widgets and widgets[w]))
]
composite = compose_widget(
widgets=widgets, enabled=ordered, theme_name=theme,
username=username, avatar_b64=payload.get("avatar_b64", ""),
show_name=show_name,
)
out = {name: svg for name, svg in widgets.items() if svg}
out["composite"] = composite
return out
def process_one() -> bool:
"""Claim a pending job: populate widget_data AND render SVGs. The render
step is what keeps embedded README widgets fresh as the fetcher rotates
payloads — without it, SVGs would only ever update when the user clicks
Generate, which is why the streak counter previously appeared frozen."""
job = db.claim_next_job()
if job is None:
return False
username = job["username"]
try:
result = fetcher_client.get_data(username)
payload = result.get("data") or {}
if payload.get("error") == "not_found":
db.put_widget_data(username, "not_found", {"not_found": True})
db.point_current_widget(username, "not_found")
db.complete_job(job["id"])
log.info("not_found marker persisted for %s", username)
return True
settings_row = db.get_settings(username)
if settings_row is None:
db.fail_job(job["id"], "settings missing", retry=False)
return True
settings = settings_row["settings"]
settings_hash = settings_row["settings_hash"]
widget_data = _compute_widget_data(payload, settings, username)
db.put_widget_data(username, settings_hash, widget_data)
_render_and_persist(username, payload, settings, settings_hash)
db.point_current_widget(username, settings_hash)
db.set_last_fetcher_hash(username, result.get("payload_hash", ""))
db.lru_trim(username, config.WIDGET_LRU_PER_USER)
db.complete_job(job["id"])
log.info("prefetched + rendered widgets 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("prefetch failed for %s (retry=%s): %s", username, retry, e)
return True
def render_composite_adhoc(username: str, override_settings: dict,
widget_name: str = "composite") -> str | None:
"""Render `widget_name` for `username` using stored settings merged
with the per-request `override_settings`. Does NOT persist anything.
Used by the public `GET /api/<u>?...` endpoint so unauthenticated visitors
can preview/embed a widget configured purely via query string, without
touching the owner's stored settings.
Returns the SVG string, or None if the user isn't enrolled / the fetcher
has no data for them (caller should fall through to the cached path).
"""
settings_row = db.get_settings(username)
if settings_row is None:
return None
result = fetcher_client.get_data(username)
payload = result.get("data") or {}
if not payload or payload.get("error") == "not_found":
return None
effective = {**settings_row["settings"], **(override_settings or {})}
if widget_name != "composite":
# Only the requested widget is returned, so don't pay to render the
# rest: generate_widgets_from_github skips anything not enabled.
effective["enabled"] = [widget_name]
t0 = time.monotonic()
widgets = _render_widgets(username, payload, effective)
analytics.record_render(username, "composite",
int((time.monotonic() - t0) * 1000))
return widgets.get(widget_name)
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}
t0 = time.monotonic()
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])
analytics.record_render(username, "composite",
int((time.monotonic() - t0) * 1000))
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()
# If this boot is the first container to see a new BUILD_VERSION,
# enqueue a rebuild for every enrolled user. claim_build_version is
# atomic so racing with the api/cron containers is safe.
if config.BUILD_VERSION:
try:
if db.claim_build_version(config.BUILD_VERSION):
n = db.enqueue_build_all()
log.info("build %s: queued %d rebuild(s)", config.BUILD_VERSION, n)
except Exception:
log.exception("build-version invalidation failed")
while True:
db.reclaim_stuck_jobs(older_than_minutes=10)
if not process_one():
time.sleep(0.5)
if __name__ == "__main__":
main()