mirror of
https://github.com/ShayManor/github-readme-stats.git
synced 2026-12-02 11:53:48 +05:30
feat(build-system): introduce BUILD_VERSION for widget invalidation logic.
This commit is contained in:
@@ -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:
|
||||
|
||||
@@ -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 = `<g transform="translate(52, 48)"><circle cx="0" cy="0" r="${radius}" fill="none" stroke="${t.grid}" stroke-width="5"/><circle cx="0" cy="0" r="${radius}" fill="none" stroke="${color}" stroke-width="5" stroke-dasharray="${circ.toFixed(1)}" stroke-dashoffset="${offset.toFixed(1)}" stroke-linecap="round" transform="rotate(-90)"/><text x="0" y="-4" text-anchor="middle" dominant-baseline="middle" font-family="${font}" font-size="${gf}" font-weight="800" fill="${color}">${esc(data.grade)}</text><text x="0" y="18" text-anchor="middle" font-family="${font}" font-size="11" fill="${t.text_secondary}">${data.score.toFixed(0)} / 100</text></g>
|
||||
const breakdownLabels: Record<string, string> = {
|
||||
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 = `<g transform="translate(52, 48)"><circle cx="0" cy="0" r="${radius}" fill="none" stroke="${t.grid}" stroke-width="5"/><circle cx="0" cy="0" r="${radius}" fill="none" stroke="${color}" stroke-width="5" stroke-dasharray="${circ.toFixed(1)}" stroke-dashoffset="${offset.toFixed(1)}" stroke-linecap="round" transform="rotate(-90)"/><text x="0" y="2" text-anchor="middle" dominant-baseline="middle" font-family="${font}" font-size="${gf}" font-weight="800" fill="${color}">${esc(data.grade)}</text></g>
|
||||
<line x1="100" y1="16" x2="100" y2="80" stroke="${t.grid}" stroke-width="1"/>
|
||||
<g transform="translate(114, 26)"><text x="0" y="10" font-family="${font}" font-size="16" font-weight="700" fill="${t.text}">Developer Profile</text><text x="0" y="28" font-family="${font}" font-size="11" fill="${t.text_secondary}">Grade <tspan fill="${color}" font-weight="700">${esc(data.grade)}</tspan> · ${data.score.toFixed(0)}/100</text></g>
|
||||
<g transform="translate(114, 26)"><text x="0" y="10" font-family="${font}" font-size="16" font-weight="700" fill="${t.text}">Developer Profile</text><text x="0" y="32" font-family="${font}" font-size="11" fill="${t.text_secondary}">${esc(strengthsLine)}</text><text x="0" y="50" font-family="${font}" font-size="10" letter-spacing="0.4" fill="${t.text_secondary}">Score <tspan fill="${t.text}" font-weight="600">${data.score.toFixed(0)}</tspan> / 100</text></g>
|
||||
<line x1="20" y1="${statsY-4}" x2="360" y2="${statsY-4}" stroke="${t.grid}" stroke-width="0.5"/>
|
||||
<g transform="translate(20, ${statsY})">${statsSvg}</g>`
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
|
||||
@@ -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."""
|
||||
|
||||
@@ -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."""
|
||||
|
||||
@@ -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'''
|
||||
<g transform="translate(52, 48)">
|
||||
<circle cx="0" cy="0" r="{radius}" fill="none" stroke="{t["grid"]}" stroke-width="5"/>
|
||||
@@ -115,18 +138,18 @@ def render_grade_widget(data: GradeData, theme_name: str = "dark", settings: dic
|
||||
stroke-linecap="round" transform="rotate(-90)">
|
||||
<animate attributeName="stroke-dashoffset" from="{circumference}" to="{offset}" dur="1s" fill="freeze"/>
|
||||
</circle>
|
||||
<text x="0" y="-4" text-anchor="middle" dominant-baseline="middle"
|
||||
<text x="0" y="2" text-anchor="middle" dominant-baseline="middle"
|
||||
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
|
||||
font-size="{grade_font}" font-weight="800" fill="{color}">{escape(data.grade)}</text>
|
||||
<text x="0" y="18" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
|
||||
font-size="11" fill="{t["text_secondary"]}">{score:.0f} / 100</text>
|
||||
</g>
|
||||
<line x1="100" y1="16" x2="100" y2="80" stroke="{t["grid"]}" stroke-width="1"/>
|
||||
<g transform="translate(114, 26)">
|
||||
<text x="0" y="10" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
|
||||
font-size="16" font-weight="700" fill="{t["text"]}">Developer Profile</text>
|
||||
<text x="0" y="28" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
|
||||
font-size="11" fill="{t["text_secondary"]}">Grade <tspan fill="{color}" font-weight="700">{escape(data.grade)}</tspan> · {score:.0f}/100</text>
|
||||
<text x="0" y="32" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
|
||||
font-size="11" fill="{t["text_secondary"]}">{strengths_line}</text>
|
||||
<text x="0" y="50" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
|
||||
font-size="10" fill="{t["text_secondary"]}" letter-spacing="0.4">Score <tspan fill="{t["text"]}" font-weight="600">{score:.0f}</tspan> / 100</text>
|
||||
</g>
|
||||
<line x1="20" y1="{stats_y - 4}" x2="360" y2="{stats_y - 4}" stroke="{t["grid"]}" stroke-width="0.5"/>
|
||||
<g transform="translate(20, {stats_y})">
|
||||
|
||||
@@ -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():
|
||||
|
||||
Reference in New Issue
Block a user