From 13cc2b4eed3789254e7ca76df39c3cb6069d8413 Mon Sep 17 00:00:00 2001 From: shay Date: Mon, 20 Apr 2026 14:09:04 -0400 Subject: [PATCH] feat(build-system): introduce BUILD_VERSION for widget invalidation logic. --- deploy/compose.yml | 3 ++ generator/frontend/src/lib/renderWidgets.ts | 14 ++++- generator/src/api.py | 19 +++++++ generator/src/config.py | 8 +++ generator/src/db.py | 57 +++++++++++++++++++++ generator/src/widgets/grade.py | 33 ++++++++++-- generator/src/worker.py | 10 ++++ 7 files changed, 137 insertions(+), 7 deletions(-) diff --git a/deploy/compose.yml b/deploy/compose.yml index cf821d0..937e0c4 100644 --- a/deploy/compose.yml +++ b/deploy/compose.yml @@ -37,6 +37,7 @@ services: GH_OAUTH_CLIENT_SECRET: ${GH_OAUTH_CLIENT_SECRET:?missing GH_OAUTH_CLIENT_SECRET} GENERATOR_SECRET_KEY: ${GENERATOR_SECRET_KEY:?missing GENERATOR_SECRET_KEY} ALLOWED_ORIGINS: ${ALLOWED_ORIGINS:-https://gh-stats.com} + BUILD_VERSION: ${IMAGE_TAG:-} volumes: - ${HOME}/ghstats/data/generator:/app/data ports: @@ -52,6 +53,7 @@ services: environment: FETCHER_URL: http://fetcher:5001 FETCHER_INTERNAL_TOKEN: ${FETCHER_INTERNAL_TOKEN:?missing FETCHER_INTERNAL_TOKEN} + BUILD_VERSION: ${IMAGE_TAG:-} volumes: - ${HOME}/ghstats/data/generator:/app/data depends_on: @@ -65,6 +67,7 @@ services: environment: FETCHER_URL: http://fetcher:5001 FETCHER_INTERNAL_TOKEN: ${FETCHER_INTERNAL_TOKEN:?missing FETCHER_INTERNAL_TOKEN} + BUILD_VERSION: ${IMAGE_TAG:-} volumes: - ${HOME}/ghstats/data/generator:/app/data depends_on: diff --git a/generator/frontend/src/lib/renderWidgets.ts b/generator/frontend/src/lib/renderWidgets.ts index c48f3af..1576e99 100644 --- a/generator/frontend/src/lib/renderWidgets.ts +++ b/generator/frontend/src/lib/renderWidgets.ts @@ -111,9 +111,19 @@ function renderGrade(data: GradeData, t: Theme, s?: { max_tags?: number }): stri const tagPad = tagsH > 24 ? 18 : 14 const cardH = tags.length ? tagsY + tagsH + tagPad : statsY + 54 - let inner = `${esc(data.grade)}${data.score.toFixed(0)} / 100 + const breakdownLabels: Record = { + commits: 'Commits', consistency: 'Consistency', repos: 'Repos', + stars: 'Stars', forks: 'Forks', activity: 'Activity', followers: 'Followers', + } + const topStrengths = Object.entries(data.breakdown || {}) + .sort((a, b) => b[1] - a[1]) + .slice(0, 2) + .map(([k]) => breakdownLabels[k] ?? k.charAt(0).toUpperCase() + k.slice(1)) + const strengthsLine = topStrengths.length ? `Strong in ${topStrengths.join(' · ')}` : '' + + let inner = `${esc(data.grade)} - Developer ProfileGrade ${esc(data.grade)} · ${data.score.toFixed(0)}/100 + Developer Profile${esc(strengthsLine)}Score ${data.score.toFixed(0)} / 100 ${statsSvg}` diff --git a/generator/src/api.py b/generator/src/api.py index 842df0d..95d67c4 100644 --- a/generator/src/api.py +++ b/generator/src/api.py @@ -635,8 +635,27 @@ def _too_large(_e): return jsonify({"error": "payload_too_large"}), 413 +def _invalidate_widgets_on_new_build() -> None: + """On boot, if BUILD_VERSION differs from the last stamp, queue a + rebuild for every enrolled user so widgets re-render against the new + code. Races safely with the worker/cron containers: the first caller + to flip the meta row enqueues; the rest observe a no-op. + """ + if not config.BUILD_VERSION: + return + 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: + # Never let a failed invalidation prevent the API from booting — + # the next boot (or a manual refresh) will pick up the change. + log.exception("build-version invalidation failed") + + def main(): db.init_dbs() + _invalidate_widgets_on_new_build() app.run(host="0.0.0.0", port=config.PORT) diff --git a/generator/src/config.py b/generator/src/config.py index 70d2b6b..6548122 100644 --- a/generator/src/config.py +++ b/generator/src/config.py @@ -42,6 +42,14 @@ COMMIT_PER_REPO = int(os.getenv("COMMIT_PER_REPO", "30")) API_TIMEOUT = int(os.getenv("API_TIMEOUT", "5")) """Timeout in seconds for API requests.""" +# Deploy / invalidation. +# When set (populated from IMAGE_TAG in deploy/compose.yml), every generator +# container compares this to the persisted 'widgets_built_version' on boot; +# if it changed, all enrolled users get a fresh build job queued so widgets +# re-render against the new code. Empty string disables the check — useful +# in local dev where a restart shouldn't invalidate the cache. +BUILD_VERSION = os.getenv("BUILD_VERSION", "").strip() + # Data source DATA_SOURCE_TYPE = os.getenv("DATA_SOURCE", "direct") """Data source type: 'direct' for immediate API calls, 'queued' for batch processing.""" diff --git a/generator/src/db.py b/generator/src/db.py index a6bd627..d990309 100644 --- a/generator/src/db.py +++ b/generator/src/db.py @@ -44,6 +44,10 @@ CREATE TABLE IF NOT EXISTS jobs ( updated_at TEXT NOT NULL ); CREATE INDEX IF NOT EXISTS idx_jobs_pending ON jobs(status, created_at); +CREATE TABLE IF NOT EXISTS meta ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL +); CREATE TABLE IF NOT EXISTS user_streaks ( username TEXT PRIMARY KEY, current_streak INTEGER NOT NULL DEFAULT 0, @@ -336,6 +340,59 @@ def enqueue_build(username: str) -> int: return cur.lastrowid +def enqueue_build_all() -> int: + """Enqueue a 'build' job for every enrolled user that doesn't already + have one pending. Returns the number inserted. Idempotent — safe to + call from whichever generator container boots first after a deploy. + """ + now = _now() + with _settings_conn() as c: + c.execute("BEGIN IMMEDIATE") + cur = c.execute( + """INSERT INTO jobs(kind, username, status, created_at, updated_at) + SELECT 'build', u.username, 'pending', ?, ? + FROM users u + WHERE NOT EXISTS ( + SELECT 1 FROM jobs j + WHERE j.username = u.username + AND j.kind = 'build' + AND j.status IN ('pending', 'running') + )""", + (now, now), + ) + inserted = cur.rowcount or 0 + c.commit() + return inserted + + +def claim_build_version(version: str) -> bool: + """Atomically stamp the 'widgets_built_version' meta row. Returns True + iff this call changed it (the caller should then enqueue rebuilds); + False if it already matched — i.e. another container on this host + already claimed this deploy. + + Uses BEGIN IMMEDIATE so racing generator/worker/cron containers + serialize and only one observes the change. + """ + if not version: + return False + with _settings_conn() as c: + c.execute("BEGIN IMMEDIATE") + row = c.execute( + "SELECT value FROM meta WHERE key='widgets_built_version'" + ).fetchone() + if row and row["value"] == version: + c.commit() + return False + c.execute( + """INSERT INTO meta(key, value) VALUES('widgets_built_version', ?) + ON CONFLICT(key) DO UPDATE SET value=excluded.value""", + (version,), + ) + c.commit() + return True + + def pending_job_count() -> int: """Depth of the build queue. Used as backpressure so bursts of enroll/PATCH don't blow up SQLite when the worker is behind.""" diff --git a/generator/src/widgets/grade.py b/generator/src/widgets/grade.py index a59ee9f..61e75ec 100644 --- a/generator/src/widgets/grade.py +++ b/generator/src/widgets/grade.py @@ -9,6 +9,26 @@ from ..utils import escape, card_wrapper, icon_svg # → "ML Engineer", not "Ml Engineer"). _TAG_ACRONYMS = {"ml", "ai", "ui", "ux", "api", "cli", "sql", "css", "html", "js", "ios"} +# Human-readable names for the breakdown factors `compute_grade` emits. Used in +# the subtitle's "Strong in ..." callout to surface the two highest-scoring +# pillars of the grade — real info instead of repeating the letter + score. +_BREAKDOWN_LABELS = { + "commits": "Commits", + "consistency": "Consistency", + "repos": "Repos", + "stars": "Stars", + "forks": "Forks", + "activity": "Activity", + "followers": "Followers", +} + + +def _top_strengths(breakdown: dict | None, n: int = 2) -> list[str]: + if not breakdown: + return [] + ranked = sorted(breakdown.items(), key=lambda kv: kv[1], reverse=True) + return [_BREAKDOWN_LABELS.get(k, k.capitalize()) for k, _ in ranked[:n]] + def _format_tag_label(tag: str) -> str: # Custom tags may define an explicit label in src/tag_rules.py::TAG_DEFS. @@ -107,6 +127,9 @@ def render_grade_widget(data: GradeData, theme_name: str = "dark", settings: dic tag_padding = 18 if tags_h > 24 else 14 card_h = (tags_y + tags_h + tag_padding) if data.tags else (stats_y + 54) + strengths = _top_strengths(data.breakdown) + strengths_line = f"Strong in {' · '.join(strengths)}" if strengths else "" + inner = f''' @@ -115,18 +138,18 @@ def render_grade_widget(data: GradeData, theme_name: str = "dark", settings: dic stroke-linecap="round" transform="rotate(-90)"> - {escape(data.grade)} - {score:.0f} / 100 Developer Profile - Grade {escape(data.grade)} · {score:.0f}/100 + {strengths_line} + Score {score:.0f} / 100 diff --git a/generator/src/worker.py b/generator/src/worker.py index cac1109..d956c6e 100644 --- a/generator/src/worker.py +++ b/generator/src/worker.py @@ -144,6 +144,16 @@ def render_widgets_now(username: str) -> dict[str, str]: 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():