mirror of
https://github.com/ShayManor/github-readme-stats.git
synced 2026-12-02 11:53:48 +05:30
fix(launch): back off build retries on GitHub limits, dedupe fetcher misses, no ad hoc render before first build
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -9,5 +9,9 @@ cd "$(dirname "$0")"
|
|||||||
mkdir -p "$HOME/ghstats/data/fetcher" "$HOME/ghstats/data/generator"
|
mkdir -p "$HOME/ghstats/data/fetcher" "$HOME/ghstats/data/generator"
|
||||||
|
|
||||||
docker compose pull
|
docker compose pull
|
||||||
|
# Keep fetcher-cron stopped across a deploy if an operator stopped it (e.g.
|
||||||
|
# during a sign-up spike); otherwise the recreated container runs at once.
|
||||||
|
cron_was_stopped=$(docker inspect -f '{{.State.Status}}' ghstats-fetcher-cron 2>/dev/null | grep -qx exited && echo 1 || true)
|
||||||
docker compose up -d --remove-orphans
|
docker compose up -d --remove-orphans
|
||||||
|
if [ -n "$cron_was_stopped" ]; then docker stop ghstats-fetcher-cron; fi
|
||||||
docker compose ps
|
docker compose ps
|
||||||
|
|||||||
@@ -1,10 +1,13 @@
|
|||||||
"""Flask app for the fetcher service. All endpoints require X-Internal-Token."""
|
"""Flask app for the fetcher service. All endpoints require X-Internal-Token."""
|
||||||
|
import fcntl
|
||||||
import hmac
|
import hmac
|
||||||
import logging
|
import logging
|
||||||
|
import os
|
||||||
import re
|
import re
|
||||||
import threading
|
import threading
|
||||||
import time
|
import time
|
||||||
import requests
|
import requests
|
||||||
|
import tempfile
|
||||||
from concurrent.futures import ThreadPoolExecutor
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
from flask import Flask, jsonify, request, Response
|
from flask import Flask, jsonify, request, Response
|
||||||
from functools import wraps
|
from functools import wraps
|
||||||
@@ -31,6 +34,10 @@ _BG_POOL = ThreadPoolExecutor(
|
|||||||
# fetcher container; a multi-replica deploy would need a distributed lock.
|
# fetcher container; a multi-replica deploy would need a distributed lock.
|
||||||
_INFLIGHT: set[str] = set()
|
_INFLIGHT: set[str] = set()
|
||||||
_INFLIGHT_LOCK = threading.Lock()
|
_INFLIGHT_LOCK = threading.Lock()
|
||||||
|
# /data misses for the same user (worker build, ad hoc renders, cron) used to
|
||||||
|
# each run a full GitHub fetch. gunicorn runs sync worker processes, so the
|
||||||
|
# lock is a per-username file lock that all workers in the container share.
|
||||||
|
_MISS_LOCK_DIR = tempfile.gettempdir()
|
||||||
|
|
||||||
# Must stay in sync with github.py's _USERNAME_RE. Trust boundary: the
|
# Must stay in sync with github.py's _USERNAME_RE. Trust boundary: the
|
||||||
# fetcher is called only by the generator over the internal network, but
|
# fetcher is called only by the generator over the internal network, but
|
||||||
@@ -81,6 +88,15 @@ def metrics():
|
|||||||
def get_data(username: str):
|
def get_data(username: str):
|
||||||
if not _valid_username(username):
|
if not _valid_username(username):
|
||||||
return jsonify({"error": "invalid_username"}), 400
|
return jsonify({"error": "invalid_username"}), 400
|
||||||
|
if db.get_user(username) is None:
|
||||||
|
path = os.path.join(_MISS_LOCK_DIR, f"ghstats-miss-{username.lower()}.lock")
|
||||||
|
with open(path, "w") as lock:
|
||||||
|
fcntl.flock(lock, fcntl.LOCK_EX)
|
||||||
|
return _get_data(username)
|
||||||
|
return _get_data(username)
|
||||||
|
|
||||||
|
|
||||||
|
def _get_data(username: str):
|
||||||
row = db.get_user(username)
|
row = db.get_user(username)
|
||||||
if row is None:
|
if row is None:
|
||||||
# Auto-fetch path
|
# Auto-fetch path
|
||||||
|
|||||||
@@ -215,3 +215,30 @@ def test_data_miss_rate_limited_returns_503(client, monkeypatch):
|
|||||||
assert r.status_code == 503
|
assert r.status_code == 503
|
||||||
assert r.get_json() == {"error": "github_rate_limited"}
|
assert r.get_json() == {"error": "github_rate_limited"}
|
||||||
assert dbmod.get_user("alice") is None
|
assert dbmod.get_user("alice") is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_concurrent_data_misses_fetch_once(client, monkeypatch):
|
||||||
|
# Concurrent misses for one user used to each run a full GitHub fetch;
|
||||||
|
# the per-user lock makes later callers read what the first stored.
|
||||||
|
import threading, time as _time
|
||||||
|
calls = []
|
||||||
|
|
||||||
|
def fake_fetch(username, **_kw):
|
||||||
|
calls.append(username)
|
||||||
|
_time.sleep(0.3)
|
||||||
|
return {"user": {"login": username}, "repos": [], "events": []}
|
||||||
|
monkeypatch.setattr(apimod.github, "fetch_github_data", fake_fetch)
|
||||||
|
monkeypatch.setattr(apimod, "_is_github_not_found", lambda _d: False)
|
||||||
|
app = apimod.app
|
||||||
|
codes = []
|
||||||
|
|
||||||
|
def hit():
|
||||||
|
with app.test_client() as c:
|
||||||
|
codes.append(c.get("/data/alice", headers={"X-Internal-Token": "secret"}).status_code)
|
||||||
|
threads = [threading.Thread(target=hit) for _ in range(3)]
|
||||||
|
for t in threads:
|
||||||
|
t.start()
|
||||||
|
for t in threads:
|
||||||
|
t.join()
|
||||||
|
assert codes == [200, 200, 200]
|
||||||
|
assert calls == ["alice"]
|
||||||
|
|||||||
@@ -911,7 +911,10 @@ def _serve(username: str, widget_name: str) -> Response:
|
|||||||
overrides = sanitize_settings_query(request.args)
|
overrides = sanitize_settings_query(request.args)
|
||||||
if widget_name != "composite":
|
if widget_name != "composite":
|
||||||
overrides = {k: v for k, v in overrides.items() if k == "theme"}
|
overrides = {k: v for k, v in overrides.items() if k == "theme"}
|
||||||
if overrides and current_hash != "not_found":
|
# No current widget means no build has landed yet, so the fetcher likely
|
||||||
|
# has no data either; an ad hoc render would trigger a GitHub fetch per
|
||||||
|
# request. Fall through to the building placeholder instead.
|
||||||
|
if overrides and current_hash is not None and current_hash != "not_found":
|
||||||
# Honor the possibly-overridden theme for error placeholders.
|
# Honor the possibly-overridden theme for error placeholders.
|
||||||
override_theme = overrides.get("theme") if isinstance(overrides.get("theme"), str) else None
|
override_theme = overrides.get("theme") if isinstance(overrides.get("theme"), str) else None
|
||||||
effective_theme = override_theme or theme
|
effective_theme = override_theme or theme
|
||||||
|
|||||||
+9
-3
@@ -493,8 +493,11 @@ def pending_job_count() -> int:
|
|||||||
def claim_next_job() -> Optional[dict]:
|
def claim_next_job() -> Optional[dict]:
|
||||||
now = _now()
|
now = _now()
|
||||||
with _settings_conn() as c:
|
with _settings_conn() as c:
|
||||||
|
# A pending job whose updated_at is in the future is backing off
|
||||||
|
# (see fail_job's delay_s) and is not claimable yet.
|
||||||
row = c.execute(
|
row = c.execute(
|
||||||
"SELECT * FROM jobs WHERE status='pending' ORDER BY created_at LIMIT 1"
|
"SELECT * FROM jobs WHERE status='pending' AND updated_at <= ? ORDER BY created_at LIMIT 1",
|
||||||
|
(now,),
|
||||||
).fetchone()
|
).fetchone()
|
||||||
if row is None:
|
if row is None:
|
||||||
return None
|
return None
|
||||||
@@ -511,11 +514,14 @@ def complete_job(job_id: int) -> None:
|
|||||||
c.commit()
|
c.commit()
|
||||||
|
|
||||||
|
|
||||||
def fail_job(job_id: int, err: str, retry: bool) -> None:
|
def fail_job(job_id: int, err: str, retry: bool, delay_s: float = 0) -> None:
|
||||||
status = "pending" if retry else "failed"
|
status = "pending" if retry else "failed"
|
||||||
|
when = _now()
|
||||||
|
if retry and delay_s > 0:
|
||||||
|
when = (datetime.utcnow() + timedelta(seconds=delay_s)).isoformat(timespec="seconds") + "Z"
|
||||||
with _settings_conn() as c:
|
with _settings_conn() as c:
|
||||||
c.execute("UPDATE jobs SET status=?, last_error=?, updated_at=? WHERE id=?",
|
c.execute("UPDATE jobs SET status=?, last_error=?, updated_at=? WHERE id=?",
|
||||||
(status, err, _now(), job_id))
|
(status, err, when, job_id))
|
||||||
c.commit()
|
c.commit()
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ re-renders triggered by the Generate button.
|
|||||||
Run as its own container: CMD python -m src.worker
|
Run as its own container: CMD python -m src.worker
|
||||||
"""
|
"""
|
||||||
import logging
|
import logging
|
||||||
|
import random
|
||||||
import time
|
import time
|
||||||
from dataclasses import asdict
|
from dataclasses import asdict
|
||||||
|
|
||||||
@@ -18,6 +19,22 @@ from .widgets import compose_widget
|
|||||||
|
|
||||||
log = logging.getLogger("generator.worker")
|
log = logging.getLogger("generator.worker")
|
||||||
MAX_ATTEMPTS = 3
|
MAX_ATTEMPTS = 3
|
||||||
|
# A fetcher 503 means GitHub's quota is spent. Retrying in seconds burns all
|
||||||
|
# attempts before the hourly reset, so back off exponentially (1, 2, 4, ...
|
||||||
|
# minutes, jittered, capped at an hour) and allow enough attempts to span
|
||||||
|
# a full quota window.
|
||||||
|
RATE_LIMIT_MAX_ATTEMPTS = 8
|
||||||
|
RATE_LIMIT_BACKOFF_CAP_S = 3600
|
||||||
|
|
||||||
|
|
||||||
|
def _rate_limit_delay(e: Exception, attempts: int) -> float:
|
||||||
|
resp = getattr(e, "response", None)
|
||||||
|
try:
|
||||||
|
retry_after = float(resp.headers.get("Retry-After"))
|
||||||
|
except (AttributeError, TypeError, ValueError):
|
||||||
|
retry_after = 0
|
||||||
|
delay = max(retry_after, 60 * 2 ** (attempts - 1))
|
||||||
|
return min(delay * random.uniform(0.8, 1.2), RATE_LIMIT_BACKOFF_CAP_S)
|
||||||
|
|
||||||
|
|
||||||
def _compute_widget_data(payload: dict, settings: dict, username: str) -> dict:
|
def _compute_widget_data(payload: dict, settings: dict, username: str) -> dict:
|
||||||
@@ -133,6 +150,12 @@ def process_one() -> bool:
|
|||||||
log.info("prefetched + rendered widgets for %s", username)
|
log.info("prefetched + rendered widgets for %s", username)
|
||||||
return True
|
return True
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
if getattr(getattr(e, "response", None), "status_code", None) == 503:
|
||||||
|
retry = job["attempts"] < RATE_LIMIT_MAX_ATTEMPTS
|
||||||
|
db.fail_job(job["id"], str(e)[:500], retry=retry,
|
||||||
|
delay_s=_rate_limit_delay(e, job["attempts"]))
|
||||||
|
log.warning("prefetch rate-limited for %s (retry=%s): %s", username, retry, e)
|
||||||
|
return True
|
||||||
retry = job["attempts"] < MAX_ATTEMPTS
|
retry = job["attempts"] < MAX_ATTEMPTS
|
||||||
db.fail_job(job["id"], str(e)[:500], retry=retry)
|
db.fail_job(job["id"], str(e)[:500], retry=retry)
|
||||||
log.warning("prefetch failed for %s (retry=%s): %s", username, retry, e)
|
log.warning("prefetch failed for %s (retry=%s): %s", username, retry, e)
|
||||||
|
|||||||
@@ -719,6 +719,20 @@ def test_query_override_without_params_uses_cached_composite(client):
|
|||||||
assert b"<svg>cached</svg>" in r.data
|
assert b"<svg>cached</svg>" in r.data
|
||||||
|
|
||||||
|
|
||||||
|
def test_query_override_skips_adhoc_render_before_first_build(client):
|
||||||
|
"""With no build landed yet the fetcher likely has no data, so an ad hoc
|
||||||
|
render would start a GitHub fetch per request. Serve the building
|
||||||
|
placeholder instead."""
|
||||||
|
dbmod.enroll("alice", {"theme": "midnight"})
|
||||||
|
|
||||||
|
with patch("src.worker.render_composite_adhoc") as adhoc:
|
||||||
|
r = client.get("/api/alice?theme=onyx&widgets=name,grade")
|
||||||
|
assert adhoc.call_count == 0
|
||||||
|
|
||||||
|
assert r.status_code == 200
|
||||||
|
assert r.headers["X-Widget-Status"] == "building"
|
||||||
|
|
||||||
|
|
||||||
def test_query_override_ignores_unknown_params(client):
|
def test_query_override_ignores_unknown_params(client):
|
||||||
"""Keys not in the allow-list are dropped by sanitize_settings_query so
|
"""Keys not in the allow-list are dropped by sanitize_settings_query so
|
||||||
bogus query strings don't trigger the expensive ad-hoc path."""
|
bogus query strings don't trigger the expensive ad-hoc path."""
|
||||||
|
|||||||
@@ -83,6 +83,56 @@ def test_worker_marks_failed_after_max_attempts(tmp_dbs):
|
|||||||
assert row["attempts"] >= 3
|
assert row["attempts"] >= 3
|
||||||
|
|
||||||
|
|
||||||
|
def _http_503(retry_after=None):
|
||||||
|
import requests
|
||||||
|
resp = requests.Response()
|
||||||
|
resp.status_code = 503
|
||||||
|
if retry_after is not None:
|
||||||
|
resp.headers["Retry-After"] = str(retry_after)
|
||||||
|
return requests.HTTPError("503 Server Error", response=resp)
|
||||||
|
|
||||||
|
|
||||||
|
def test_worker_backs_off_on_rate_limit(tmp_dbs):
|
||||||
|
"""A fetcher 503 (GitHub quota spent) delays the retry instead of
|
||||||
|
burning all attempts in seconds; the job is not claimable until then."""
|
||||||
|
dbmod.enroll("alice", {"theme": "dark"})
|
||||||
|
with patch("src.worker.fetcher_client.get_data", side_effect=_http_503()):
|
||||||
|
worker.process_one()
|
||||||
|
assert worker.process_one() is False # backing off, nothing claimable
|
||||||
|
with dbmod._settings_conn() as c:
|
||||||
|
row = c.execute("SELECT status, attempts, updated_at FROM jobs WHERE username='alice'").fetchone()
|
||||||
|
assert row["status"] == "pending"
|
||||||
|
assert row["attempts"] == 1
|
||||||
|
assert row["updated_at"] > dbmod._now()
|
||||||
|
# Once the delay has passed the job is claimed again.
|
||||||
|
with dbmod._settings_conn() as c:
|
||||||
|
c.execute("UPDATE jobs SET updated_at='2020-01-01T00:00:00Z'")
|
||||||
|
c.commit()
|
||||||
|
assert dbmod.claim_next_job()["username"] == "alice"
|
||||||
|
|
||||||
|
|
||||||
|
def test_rate_limit_delay_grows_honors_retry_after_and_caps():
|
||||||
|
with patch("src.worker.random.uniform", return_value=1.0):
|
||||||
|
assert worker._rate_limit_delay(_http_503(), 1) == 60
|
||||||
|
assert worker._rate_limit_delay(_http_503(), 3) == 240
|
||||||
|
assert worker._rate_limit_delay(_http_503(retry_after=600), 1) == 600
|
||||||
|
assert worker._rate_limit_delay(_http_503(), 10) == worker.RATE_LIMIT_BACKOFF_CAP_S
|
||||||
|
|
||||||
|
|
||||||
|
def test_worker_rate_limit_allows_more_attempts(tmp_dbs):
|
||||||
|
dbmod.enroll("alice", {"theme": "dark"})
|
||||||
|
with patch("src.worker.fetcher_client.get_data", side_effect=_http_503()):
|
||||||
|
for _ in range(worker.RATE_LIMIT_MAX_ATTEMPTS):
|
||||||
|
with dbmod._settings_conn() as c:
|
||||||
|
c.execute("UPDATE jobs SET updated_at='2020-01-01T00:00:00Z' WHERE status='pending'")
|
||||||
|
c.commit()
|
||||||
|
worker.process_one()
|
||||||
|
with dbmod._settings_conn() as c:
|
||||||
|
row = c.execute("SELECT status, attempts FROM jobs WHERE username='alice'").fetchone()
|
||||||
|
assert row["status"] == "failed"
|
||||||
|
assert row["attempts"] == worker.RATE_LIMIT_MAX_ATTEMPTS
|
||||||
|
|
||||||
|
|
||||||
def test_process_one_persists_streak(tmp_dbs):
|
def test_process_one_persists_streak(tmp_dbs):
|
||||||
"""Phase 1 worker must compute and persist the user's streak so max survives
|
"""Phase 1 worker must compute and persist the user's streak so max survives
|
||||||
future settings changes."""
|
future settings changes."""
|
||||||
|
|||||||
Reference in New Issue
Block a user