mirror of
https://github.com/ShayManor/github-readme-stats.git
synced 2026-12-02 11:53:48 +05:30
feat(generator): raise enrollment ceiling, add burst guard, stop enqueue loop
ENROLLMENT_DAILY_CAP was 50, so any traffic spike past 50 new users in a day was turned away with a rate_limited card. Raise the default to 500 and add ENROLLMENT_HOURLY_CAP=60. The hourly guard is the one that actually protects the shared PAT: a new user costs ~37 REST calls (p90 ~104) against a 5000/hr budget, and a spike arrives inside an hour rather than spread over a day. Counted off users.enrolled_at, so no schema change. Also stop an unbounded enqueue loop. `name` is drawn inside the composite and never persisted standalone, and `achievements` renders nothing until the user authors one, so their SVG is permanently absent and every request re-enqueued a build that could never produce it. Only self-heal when no build has actually landed, keyed off widget_data for the current hash. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01BwMoSbmK77Ph7XaV5YnAdS
This commit is contained in:
+21
-5
@@ -535,6 +535,13 @@ def auth_logout():
|
||||
return ("", 204)
|
||||
|
||||
|
||||
def _enrollment_capped() -> bool:
|
||||
"""True when a new enrollment would exceed the daily budget or the hourly
|
||||
burst guard. Both protect the shared GitHub PAT."""
|
||||
return (db.enrollments_today() >= config.ENROLLMENT_DAILY_CAP
|
||||
or db.enrollments_last_hour() >= config.ENROLLMENT_HOURLY_CAP)
|
||||
|
||||
|
||||
@app.route("/api/auth/github/login", methods=["GET"])
|
||||
def auth_github_login():
|
||||
import secrets as _secrets
|
||||
@@ -769,7 +776,7 @@ def compat_top_langs():
|
||||
# backstop; without it a botnet hitting random ?username= values
|
||||
# could exhaust the GitHub PAT budget.
|
||||
if db.get_settings(username) is None:
|
||||
if db.enrollments_today() >= config.ENROLLMENT_DAILY_CAP:
|
||||
if _enrollment_capped():
|
||||
return _placeholder_response("rate_limited", username)
|
||||
defaults = {
|
||||
"theme": "dark",
|
||||
@@ -802,7 +809,7 @@ def get_user_data(username: str):
|
||||
if settings_row is None:
|
||||
# Daily cap is the abuse backstop: a botnet typing random names
|
||||
# can't burn through the GitHub PAT budget past this number.
|
||||
if db.enrollments_today() >= config.ENROLLMENT_DAILY_CAP:
|
||||
if _enrollment_capped():
|
||||
return jsonify({"status": "rate_limited"}), 429
|
||||
defaults = {
|
||||
"theme": "dark",
|
||||
@@ -856,7 +863,7 @@ def _serve(username: str, widget_name: str) -> Response:
|
||||
# actually trigger a build, instead of returning a "building"
|
||||
# placeholder that nothing ever resolves. Same daily-cap +
|
||||
# triple-kickoff pattern as /api/<u>/data and /api/top-langs.
|
||||
if db.enrollments_today() >= config.ENROLLMENT_DAILY_CAP:
|
||||
if _enrollment_capped():
|
||||
return _placeholder_response("rate_limited", username)
|
||||
defaults = {
|
||||
"theme": "dark",
|
||||
@@ -923,7 +930,16 @@ def _serve(username: str, widget_name: str) -> Response:
|
||||
# re-enqueues on payload-hash changes, so the user would otherwise
|
||||
# sit on "building" until GitHub data changed. Self-heal by
|
||||
# enqueuing a fresh build if nothing's in flight.
|
||||
if not db.has_open_build(username):
|
||||
#
|
||||
# But only when the build genuinely hasn't landed. A completed build
|
||||
# persists widget_data for the hash current_widget points at, so if
|
||||
# that row exists this widget simply renders nothing for this user
|
||||
# (`name` is drawn inside the composite and never stands alone;
|
||||
# `achievements` is skipped when the user has authored none). Without
|
||||
# this check every request re-enqueues a build that can never produce
|
||||
# the SVG, pinning the worker and growing the prefetch queue.
|
||||
built = db.get_current_widget_data(username) is not None
|
||||
if not built and not db.has_open_build(username):
|
||||
db.enqueue_build(username)
|
||||
_kickoff_prefetch_async(username)
|
||||
return _placeholder_response("building", username, theme=theme)
|
||||
@@ -960,7 +976,7 @@ def _serve_profile_widget(username: str) -> Response:
|
||||
settings_row = db.get_settings(username)
|
||||
just_enrolled = False
|
||||
if settings_row is None:
|
||||
if db.enrollments_today() >= config.ENROLLMENT_DAILY_CAP:
|
||||
if _enrollment_capped():
|
||||
return _placeholder_response("rate_limited", username)
|
||||
defaults = {
|
||||
"theme": "dark",
|
||||
|
||||
@@ -127,7 +127,11 @@ DEV_DASHBOARD_PASSWORD = os.getenv("DEV_DASHBOARD_PASSWORD", "")
|
||||
FETCHER_URL = os.getenv("FETCHER_URL", "http://localhost:5001")
|
||||
FETCHER_INTERNAL_TOKEN = os.getenv("FETCHER_INTERNAL_TOKEN", "")
|
||||
REDIS_URL = os.getenv("REDIS_URL", "")
|
||||
ENROLLMENT_DAILY_CAP = int(os.getenv("ENROLLMENT_DAILY_CAP", "50"))
|
||||
ENROLLMENT_DAILY_CAP = int(os.getenv("ENROLLMENT_DAILY_CAP", "500"))
|
||||
# Burst guard. A new user costs ~37 GitHub REST calls (p90 ~104) against a
|
||||
# 5000/hr budget, and a launch spike arrives in one hour rather than spread
|
||||
# over a day, so the hourly ceiling is what actually protects the PAT.
|
||||
ENROLLMENT_HOURLY_CAP = int(os.getenv("ENROLLMENT_HOURLY_CAP", "60"))
|
||||
WIDGET_LRU_PER_USER = int(os.getenv("WIDGET_LRU_PER_USER", "10"))
|
||||
POLL_INTERVAL_MINUTES = int(os.getenv("GENERATOR_POLL_INTERVAL_MINUTES", "15"))
|
||||
|
||||
|
||||
@@ -251,6 +251,18 @@ def enrollments_today() -> int:
|
||||
return row["count"] if row else 0
|
||||
|
||||
|
||||
def enrollments_last_hour() -> int:
|
||||
"""Enrollments in the trailing 60 minutes. Reads `users.enrolled_at`
|
||||
directly (ISO-8601 Zulu, so lexicographic order is chronological) rather
|
||||
than keeping a second counter table."""
|
||||
cutoff = (datetime.utcnow() - timedelta(hours=1)).isoformat(timespec="seconds") + "Z"
|
||||
with _settings_conn() as c:
|
||||
row = c.execute(
|
||||
"SELECT COUNT(*) AS n FROM users WHERE enrolled_at >= ?", (cutoff,)
|
||||
).fetchone()
|
||||
return row["n"] if row else 0
|
||||
|
||||
|
||||
def enrollment_rank(username: str) -> Optional[int]:
|
||||
"""1-based position in overall enrollment order by enrolled_at. Used by
|
||||
tag rules that reward early users (e.g. the 'founder' tag).
|
||||
|
||||
@@ -407,6 +407,57 @@ def test_data_unknown_user_when_cap_reached_returns_429(client, monkeypatch):
|
||||
assert dbmod.get_settings("testuser") is None
|
||||
|
||||
|
||||
def test_widget_with_no_output_does_not_reenqueue_forever(client):
|
||||
"""`name` is drawn inside the composite and never persisted standalone, so
|
||||
its SVG is permanently absent. Once a build has landed, requesting it must
|
||||
NOT enqueue another build: every request doing so pins the worker and grows
|
||||
the prefetch queue without bound under load."""
|
||||
dbmod.enroll("alice", {"theme": "dark"})
|
||||
dbmod.put_widget_data("alice", "h1", {"some": "data"})
|
||||
dbmod.put_widgets("alice", "h1", {"composite": "<svg>ready</svg>"})
|
||||
dbmod.point_current_widget("alice", "h1")
|
||||
|
||||
before = dbmod.pending_job_count()
|
||||
for _ in range(5):
|
||||
r = client.get("/api/alice/name.svg")
|
||||
assert r.headers["X-Widget-Status"] == "building"
|
||||
assert dbmod.pending_job_count() == before
|
||||
|
||||
|
||||
def test_missing_widget_still_self_heals_when_no_build_landed(client):
|
||||
"""The self-heal must survive: no widget_data means the build never
|
||||
completed, so one rebuild should still be queued."""
|
||||
dbmod.enroll("bob", {"theme": "dark"})
|
||||
# Drain the enrollment build without it ever persisting widget_data,
|
||||
# i.e. the permanently-failed build the self-heal exists for.
|
||||
job = dbmod.claim_next_job()
|
||||
dbmod.fail_job(job["id"], "boom", retry=False)
|
||||
assert dbmod.pending_job_count() == 0
|
||||
|
||||
r = client.get("/api/bob/grade.svg")
|
||||
assert r.headers["X-Widget-Status"] == "building"
|
||||
assert dbmod.pending_job_count() == 1
|
||||
|
||||
|
||||
def test_data_unknown_user_when_hourly_cap_reached_returns_429(client, monkeypatch):
|
||||
"""The hourly burst guard is what protects the PAT during a launch spike:
|
||||
a day's budget arriving inside one hour would exhaust it."""
|
||||
monkeypatch.setattr(cfg, "ENROLLMENT_DAILY_CAP", 10_000)
|
||||
monkeypatch.setattr(cfg, "ENROLLMENT_HOURLY_CAP", 0)
|
||||
r = client.get("/api/testuser/data")
|
||||
assert r.status_code == 429
|
||||
assert r.get_json()["status"] == "rate_limited"
|
||||
assert dbmod.get_settings("testuser") is None
|
||||
|
||||
|
||||
def test_data_unknown_user_enrolls_when_under_both_caps(client, monkeypatch):
|
||||
monkeypatch.setattr(cfg, "ENROLLMENT_DAILY_CAP", 10_000)
|
||||
monkeypatch.setattr(cfg, "ENROLLMENT_HOURLY_CAP", 10_000)
|
||||
r = client.get("/api/testuser/data")
|
||||
assert r.status_code == 202
|
||||
assert dbmod.get_settings("testuser") is not None
|
||||
|
||||
|
||||
# ---- /api/top-langs compat shim for upstream github-readme-stats URLs ----
|
||||
|
||||
|
||||
|
||||
@@ -57,6 +57,18 @@ def test_enrollments_daily_counter(tmp_dbs):
|
||||
assert dbmod.enrollments_today() == 2
|
||||
|
||||
|
||||
def test_enrollments_last_hour_counts_only_recent(tmp_dbs):
|
||||
dbmod.enroll("alice", {"theme": "dark"})
|
||||
dbmod.enroll("bob", {"theme": "dark"})
|
||||
assert dbmod.enrollments_last_hour() == 2
|
||||
# Age one of them past the window; it must drop out of the burst count
|
||||
# while still counting toward the daily total.
|
||||
with dbmod._settings_conn() as c:
|
||||
c.execute("UPDATE users SET enrolled_at='2020-01-01T00:00:00Z' WHERE username='alice'")
|
||||
c.commit()
|
||||
assert dbmod.enrollments_last_hour() == 1
|
||||
|
||||
|
||||
def test_enrollment_rank_is_case_insensitive(tmp_dbs):
|
||||
"""GitHub returns logins with original casing ("ShayManor") but the users
|
||||
table stores them lowercased. Without normalization the founder-tag rule
|
||||
|
||||
Reference in New Issue
Block a user