mirror of
https://github.com/ShayManor/github-readme-stats.git
synced 2026-12-02 11:53:48 +05:30
fix(fetcher): back off on GitHub secondary limits in refresh cron
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -13,6 +13,12 @@ TRIAL_GC_DAYS = int(os.getenv("FETCHER_TRIAL_GC_DAYS", "7"))
|
|||||||
# over several hours. Oldest-fetched users go first; the rest wait a tick.
|
# over several hours. Oldest-fetched users go first; the rest wait a tick.
|
||||||
REFRESH_CORE_RESERVE = int(os.getenv("FETCHER_REFRESH_CORE_RESERVE", "1500"))
|
REFRESH_CORE_RESERVE = int(os.getenv("FETCHER_REFRESH_CORE_RESERVE", "1500"))
|
||||||
REFRESH_MAX_PER_TICK = int(os.getenv("FETCHER_REFRESH_MAX_PER_TICK", "60"))
|
REFRESH_MAX_PER_TICK = int(os.getenv("FETCHER_REFRESH_MAX_PER_TICK", "60"))
|
||||||
|
# GitHub's secondary (burst) limits trip when refreshes run back to back. The
|
||||||
|
# tick pauses between users; on a rate limit it waits Retry-After (else the
|
||||||
|
# default, capped) and retries that user once, then stops and defers the rest.
|
||||||
|
REFRESH_USER_PAUSE = float(os.getenv("FETCHER_REFRESH_USER_PAUSE", "1.5"))
|
||||||
|
REFRESH_RETRY_SLEEP = int(os.getenv("FETCHER_REFRESH_RETRY_SLEEP", "60"))
|
||||||
|
REFRESH_RETRY_SLEEP_MAX = int(os.getenv("FETCHER_REFRESH_RETRY_SLEEP_MAX", "120"))
|
||||||
API_TIMEOUT = int(os.getenv("API_TIMEOUT", "15"))
|
API_TIMEOUT = int(os.getenv("API_TIMEOUT", "15"))
|
||||||
|
|
||||||
# Generator URL is used as a callback target when a /fetch-async background
|
# Generator URL is used as a callback target when a /fetch-async background
|
||||||
|
|||||||
+19
-2
@@ -23,6 +23,18 @@ def _core_remaining() -> int | None:
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _fetch_retrying_once(username: str) -> dict:
|
||||||
|
"""Fetch a user; on a transient GitHub error wait Retry-After (else the
|
||||||
|
default, capped) and try once more. A second failure propagates."""
|
||||||
|
try:
|
||||||
|
return github.fetch_github_data(username, token=config.GITHUB_PAT)
|
||||||
|
except github.GitHubTransientError as e:
|
||||||
|
wait = min(e.retry_after or config.REFRESH_RETRY_SLEEP, config.REFRESH_RETRY_SLEEP_MAX)
|
||||||
|
log.warning("refresh rate-limited for %s: %s; retrying once in %ss", username, e, wait)
|
||||||
|
time.sleep(wait)
|
||||||
|
return github.fetch_github_data(username, token=config.GITHUB_PAT)
|
||||||
|
|
||||||
|
|
||||||
def tick(hours: int, active_within_days: int, gc_days: int) -> dict:
|
def tick(hours: int, active_within_days: int, gc_days: int) -> dict:
|
||||||
"""Refresh due users, then GC abandoned ones. Returns counts."""
|
"""Refresh due users, then GC abandoned ones. Returns counts."""
|
||||||
refreshed = 0
|
refreshed = 0
|
||||||
@@ -31,6 +43,8 @@ def tick(hours: int, active_within_days: int, gc_days: int) -> dict:
|
|||||||
deferred = max(len(due) - config.REFRESH_MAX_PER_TICK, 0)
|
deferred = max(len(due) - config.REFRESH_MAX_PER_TICK, 0)
|
||||||
due = due[:config.REFRESH_MAX_PER_TICK]
|
due = due[:config.REFRESH_MAX_PER_TICK]
|
||||||
for i, username in enumerate(due):
|
for i, username in enumerate(due):
|
||||||
|
if i:
|
||||||
|
time.sleep(config.REFRESH_USER_PAUSE)
|
||||||
left = _core_remaining()
|
left = _core_remaining()
|
||||||
if left is not None and left < config.REFRESH_CORE_RESERVE:
|
if left is not None and left < config.REFRESH_CORE_RESERVE:
|
||||||
log.info("core budget %s under reserve %s; deferring %s refreshes",
|
log.info("core budget %s under reserve %s; deferring %s refreshes",
|
||||||
@@ -38,7 +52,7 @@ def tick(hours: int, active_within_days: int, gc_days: int) -> dict:
|
|||||||
deferred += len(due) - i
|
deferred += len(due) - i
|
||||||
break
|
break
|
||||||
try:
|
try:
|
||||||
data = github.fetch_github_data(username, token=config.GITHUB_PAT)
|
data = _fetch_retrying_once(username)
|
||||||
user = data.get("user")
|
user = data.get("user")
|
||||||
if user is None or (isinstance(user, dict) and user.get("message") == "Not Found"):
|
if user is None or (isinstance(user, dict) and user.get("message") == "Not Found"):
|
||||||
data = {"error": "not_found"}
|
data = {"error": "not_found"}
|
||||||
@@ -49,8 +63,11 @@ def tick(hours: int, active_within_days: int, gc_days: int) -> dict:
|
|||||||
refreshed += 1
|
refreshed += 1
|
||||||
except github.GitHubTransientError as e:
|
except github.GitHubTransientError as e:
|
||||||
db.bump_fetch_metric("rate_limited")
|
db.bump_fetch_metric("rate_limited")
|
||||||
log.warning("refresh rate-limited for %s (kept last-good): %s", username, e)
|
log.warning("refresh rate-limited for %s (kept last-good): %s; deferring %s refreshes",
|
||||||
|
username, e, len(due) - i - 1)
|
||||||
failed += 1
|
failed += 1
|
||||||
|
deferred += len(due) - i - 1
|
||||||
|
break
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
db.bump_fetch_metric("error")
|
db.bump_fetch_metric("error")
|
||||||
log.warning("refresh failed for %s: %s", username, e)
|
log.warning("refresh failed for %s: %s", username, e)
|
||||||
|
|||||||
+10
-3
@@ -47,19 +47,26 @@ class GitHubTransientError(Exception):
|
|||||||
next successful fetch. Propagate it instead so the caller aborts the fetch
|
next successful fetch. Propagate it instead so the caller aborts the fetch
|
||||||
and keeps the previously-cached record."""
|
and keeps the previously-cached record."""
|
||||||
|
|
||||||
|
def __init__(self, msg="", retry_after=None):
|
||||||
|
super().__init__(msg)
|
||||||
|
# Seconds from GitHub's Retry-After header, when it sent one.
|
||||||
|
self.retry_after = retry_after
|
||||||
|
|
||||||
|
|
||||||
def _raise_if_transient(resp) -> None:
|
def _raise_if_transient(resp) -> None:
|
||||||
"""Raise GitHubTransientError if `resp` looks like a rate limit or server
|
"""Raise GitHubTransientError if `resp` looks like a rate limit or server
|
||||||
error. A genuine NOT_FOUND (unknown user) is left alone — that is a real,
|
error. A genuine NOT_FOUND (unknown user) is left alone — that is a real,
|
||||||
persistable "this user has no data" answer, not a transient failure."""
|
persistable "this user has no data" answer, not a transient failure."""
|
||||||
|
retry_after = resp.headers.get("Retry-After")
|
||||||
|
retry_after = int(retry_after) if retry_after and retry_after.isdigit() else None
|
||||||
if resp.status_code in (429, 500, 502, 503, 504):
|
if resp.status_code in (429, 500, 502, 503, 504):
|
||||||
raise GitHubTransientError(f"HTTP {resp.status_code}")
|
raise GitHubTransientError(f"HTTP {resp.status_code}", retry_after)
|
||||||
# Primary/secondary REST rate limits come back as 403 with the remaining
|
# Primary/secondary REST rate limits come back as 403 with the remaining
|
||||||
# budget at 0 (or a "secondary rate limit" message).
|
# budget at 0 (or a "secondary rate limit" message).
|
||||||
if resp.status_code == 403 and resp.headers.get("X-RateLimit-Remaining") == "0":
|
if resp.status_code == 403 and resp.headers.get("X-RateLimit-Remaining") == "0":
|
||||||
raise GitHubTransientError("REST rate limit exhausted")
|
raise GitHubTransientError("REST rate limit exhausted", retry_after)
|
||||||
if resp.status_code == 403 and "rate limit" in (resp.text or "").lower():
|
if resp.status_code == 403 and "rate limit" in (resp.text or "").lower():
|
||||||
raise GitHubTransientError("REST rate limit exhausted")
|
raise GitHubTransientError("REST rate limit exhausted", retry_after)
|
||||||
# GraphQL reports rate limits as HTTP 200 with an `errors` array — the same
|
# GraphQL reports rate limits as HTTP 200 with an `errors` array — the same
|
||||||
# 200 that a valid response uses — so the body has to be inspected.
|
# 200 that a valid response uses — so the body has to be inspected.
|
||||||
try:
|
try:
|
||||||
|
|||||||
@@ -15,6 +15,14 @@ def tmp_db(monkeypatch):
|
|||||||
yield
|
yield
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def sleeps(monkeypatch):
|
||||||
|
# The tick pauses between users and before a retry; record, don't wait.
|
||||||
|
calls = []
|
||||||
|
monkeypatch.setattr(cronmod.time, "sleep", calls.append)
|
||||||
|
return calls
|
||||||
|
|
||||||
|
|
||||||
def test_refresh_tick_calls_github_for_due_users(tmp_db):
|
def test_refresh_tick_calls_github_for_due_users(tmp_db):
|
||||||
dbmod.upsert_user("alice", {"user": {"login": "alice"}})
|
dbmod.upsert_user("alice", {"user": {"login": "alice"}})
|
||||||
# Backdate
|
# Backdate
|
||||||
@@ -82,3 +90,36 @@ def test_tick_stops_under_core_reserve(tmp_db, monkeypatch):
|
|||||||
stats = cronmod.tick(hours=24, active_within_days=7, gc_days=7)
|
stats = cronmod.tick(hours=24, active_within_days=7, gc_days=7)
|
||||||
assert [c.args[0] for c in gh.call_args_list] == ["a"]
|
assert [c.args[0] for c in gh.call_args_list] == ["a"]
|
||||||
assert stats["refreshed"] == 1 and stats["deferred"] == 2
|
assert stats["refreshed"] == 1 and stats["deferred"] == 2
|
||||||
|
|
||||||
|
|
||||||
|
def test_tick_retries_once_after_capped_retry_after(tmp_db, monkeypatch, sleeps):
|
||||||
|
# A secondary rate limit clears after a wait: honour Retry-After (capped)
|
||||||
|
# and retry the same user once; pause between users.
|
||||||
|
_due("a", "b")
|
||||||
|
monkeypatch.setattr(cronmod, "_core_remaining", lambda: None)
|
||||||
|
results = iter([ghmod.GitHubTransientError("rate limited", retry_after=500),
|
||||||
|
{"user": {"login": "a"}}, {"user": {"login": "b"}}])
|
||||||
|
|
||||||
|
def fake(u, **_k):
|
||||||
|
r = next(results)
|
||||||
|
if isinstance(r, Exception):
|
||||||
|
raise r
|
||||||
|
return r
|
||||||
|
with patch("src.cron.github.fetch_github_data", side_effect=fake) as gh:
|
||||||
|
stats = cronmod.tick(hours=24, active_within_days=7, gc_days=7)
|
||||||
|
assert [c.args[0] for c in gh.call_args_list] == ["a", "a", "b"]
|
||||||
|
assert sleeps == [120, 1.5]
|
||||||
|
assert stats["refreshed"] == 2 and stats["failed"] == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_tick_stops_and_defers_after_second_rate_limit(tmp_db, monkeypatch, sleeps):
|
||||||
|
# Hammering on after a repeat rate limit only fails every remaining user;
|
||||||
|
# stop the tick and leave them due for the next one.
|
||||||
|
_due("a", "b", "c")
|
||||||
|
monkeypatch.setattr(cronmod, "_core_remaining", lambda: None)
|
||||||
|
with patch("src.cron.github.fetch_github_data",
|
||||||
|
side_effect=ghmod.GitHubTransientError("rate limited")) as gh:
|
||||||
|
stats = cronmod.tick(hours=24, active_within_days=7, gc_days=7)
|
||||||
|
assert [c.args[0] for c in gh.call_args_list] == ["a", "a"]
|
||||||
|
assert sleeps == [60]
|
||||||
|
assert stats["failed"] == 1 and stats["refreshed"] == 0 and stats["deferred"] == 2
|
||||||
|
|||||||
@@ -277,3 +277,16 @@ def test_repo_languages_capped_to_recent_owned_repos(monkeypatch):
|
|||||||
assert sorted(src.calls) == ["alice/mid", "alice/new"]
|
assert sorted(src.calls) == ["alice/mid", "alice/new"]
|
||||||
assert repos[1]["language_bytes"] == {"Python": 1}
|
assert repos[1]["language_bytes"] == {"Python": 1}
|
||||||
assert "language_bytes" not in repos[0]
|
assert "language_bytes" not in repos[0]
|
||||||
|
|
||||||
|
|
||||||
|
@responses.activate
|
||||||
|
def test_rate_limit_error_carries_retry_after():
|
||||||
|
responses.add(
|
||||||
|
responses.GET, "https://api.github.com/users/alice",
|
||||||
|
json={"message": "You have exceeded a secondary rate limit."}, status=403,
|
||||||
|
headers={"Retry-After": "42"},
|
||||||
|
)
|
||||||
|
src = github.DirectAPISource(token="t")
|
||||||
|
with pytest.raises(github.GitHubTransientError) as exc:
|
||||||
|
src.fetch_user_data("alice")
|
||||||
|
assert exc.value.retry_after == 42
|
||||||
|
|||||||
Reference in New Issue
Block a user