mirror of
https://github.com/ShayManor/github-readme-stats.git
synced 2026-12-02 11:53:48 +05:30
fix(fetcher): guard REST calls so a rate limit can't poison user records
The five REST calls parsed `.json()` with no status check, so a 403
{"message": "API rate limit exceeded..."} body was returned as user data.
`_is_github_not_found` only matched "Not Found", so it was recorded as a
successful fetch and upsert_user overwrote the user's last-good row. Every
user touched during the exhaustion window then served a blank card for up
to 24h while /metrics reported ok.
Reuse the existing `_raise_if_transient` on all five so exhaustion raises
GitHubTransientError before the upsert, preserving last-good and letting
the caller retry. `_raise_if_transient` was GraphQL-shaped and crashed on
the JSON arrays the list endpoints return, so it now ignores non-dict
bodies. A rate limit inside the per-repo fan-out aborts the fetch; a 404
on a single repo stays non-fatal.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BwMoSbmK77Ph7XaV5YnAdS
This commit is contained in:
@@ -242,6 +242,12 @@ def _is_github_not_found(data: dict) -> bool:
|
||||
return True
|
||||
if isinstance(user, dict) and user.get("message") == "Not Found":
|
||||
return True
|
||||
# An error body (rate limit, abuse detection, anything else GitHub answers
|
||||
# with a bare {"message": ...}) carries no login. It is not user data and
|
||||
# must never be recorded as a successful fetch. github.py raises
|
||||
# GitHubTransientError before we get here in practice; this is the backstop.
|
||||
if isinstance(user, dict) and "login" not in user:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
|
||||
+28
-6
@@ -58,12 +58,18 @@ def _raise_if_transient(resp) -> None:
|
||||
# budget at 0 (or a "secondary rate limit" message).
|
||||
if resp.status_code == 403 and resp.headers.get("X-RateLimit-Remaining") == "0":
|
||||
raise GitHubTransientError("REST rate limit exhausted")
|
||||
if resp.status_code == 403 and "rate limit" in (resp.text or "").lower():
|
||||
raise GitHubTransientError("REST rate limit exhausted")
|
||||
# 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.
|
||||
try:
|
||||
body = resp.json()
|
||||
except ValueError:
|
||||
return
|
||||
# REST list endpoints (events, repos, contributors) answer with a JSON
|
||||
# array — only a GraphQL-shaped object can carry an `errors` block.
|
||||
if not isinstance(body, dict):
|
||||
return
|
||||
for err in (body.get("errors") or []):
|
||||
if err.get("type") in ("RATE_LIMITED", "SERVICE_UNAVAILABLE"):
|
||||
raise GitHubTransientError(err.get("message") or err.get("type"))
|
||||
@@ -163,23 +169,27 @@ class DirectAPISource:
|
||||
def fetch_user_data(self, username: str) -> dict:
|
||||
"""Fetch user profile data."""
|
||||
_assert_username(username)
|
||||
return requests.get(
|
||||
resp = requests.get(
|
||||
f"{self.base}/users/{username}",
|
||||
headers=self.headers,
|
||||
timeout=config.API_TIMEOUT,
|
||||
).json()
|
||||
)
|
||||
_raise_if_transient(resp)
|
||||
return resp.json()
|
||||
|
||||
def fetch_repos(self, username: str) -> list:
|
||||
"""Fetch user repositories (owned + contributed to)."""
|
||||
_assert_username(username)
|
||||
|
||||
def _get(repo_type: str):
|
||||
return requests.get(
|
||||
resp = requests.get(
|
||||
f"{self.base}/users/{username}/repos",
|
||||
headers=self.headers,
|
||||
params={"per_page": 100, "sort": "pushed", "type": repo_type},
|
||||
timeout=config.API_TIMEOUT,
|
||||
).json()
|
||||
)
|
||||
_raise_if_transient(resp)
|
||||
return resp.json()
|
||||
|
||||
# The two REST calls are independent — fire them in parallel so the
|
||||
# second isn't waiting on the first to come back.
|
||||
@@ -209,8 +219,10 @@ class DirectAPISource:
|
||||
headers=self.headers,
|
||||
params={"per_page": 100},
|
||||
timeout=config.API_TIMEOUT,
|
||||
).json()
|
||||
return resp if isinstance(resp, list) else []
|
||||
)
|
||||
_raise_if_transient(resp)
|
||||
events = resp.json()
|
||||
return events if isinstance(events, list) else []
|
||||
|
||||
def fetch_commits(self, username: str, repos: list = None) -> list:
|
||||
"""
|
||||
@@ -529,6 +541,7 @@ class DirectAPISource:
|
||||
timeout=config.API_TIMEOUT
|
||||
)
|
||||
|
||||
_raise_if_transient(resp)
|
||||
if resp.ok:
|
||||
contributors = resp.json()
|
||||
# Filter by minimum commits
|
||||
@@ -536,6 +549,8 @@ class DirectAPISource:
|
||||
c for c in contributors
|
||||
if c.get("contributions", 0) >= min_commits
|
||||
]
|
||||
except GitHubTransientError:
|
||||
raise
|
||||
except Exception as e:
|
||||
print(f"Warning: Failed to fetch contributors from {repo_name}: {e}")
|
||||
|
||||
@@ -622,9 +637,12 @@ class DirectAPISource:
|
||||
headers=self.headers,
|
||||
timeout=config.API_TIMEOUT,
|
||||
)
|
||||
_raise_if_transient(resp)
|
||||
if resp.ok:
|
||||
data = resp.json()
|
||||
return data if isinstance(data, dict) else {}
|
||||
except GitHubTransientError:
|
||||
raise
|
||||
except Exception:
|
||||
pass
|
||||
return {}
|
||||
@@ -729,6 +747,8 @@ def _enrich_repo_languages(repos: list, source: GitHubDataSource) -> None:
|
||||
i = futures[fut]
|
||||
try:
|
||||
repos[i]["language_bytes"] = fut.result() or {}
|
||||
except GitHubTransientError:
|
||||
raise
|
||||
except Exception:
|
||||
repos[i]["language_bytes"] = {}
|
||||
|
||||
@@ -803,6 +823,8 @@ def _fetch_collaborators_data(
|
||||
full_name = futures[fut]
|
||||
try:
|
||||
contributors_by_repo[full_name] = fut.result() or []
|
||||
except GitHubTransientError:
|
||||
raise
|
||||
except Exception as e:
|
||||
print(f" failed to fetch contributors for {full_name}: {e}")
|
||||
contributors_by_repo[full_name] = []
|
||||
|
||||
Reference in New Issue
Block a user