mirror of
https://github.com/ShayManor/github-readme-stats.git
synced 2026-12-02 11:53:48 +05:30
fix(fetcher): quota reserve and per-tick cap for refresh cron
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -7,6 +7,12 @@ GITHUB_PAT = os.getenv("GITHUB_PAT", "")
|
||||
INTERNAL_TOKEN = os.getenv("FETCHER_INTERNAL_TOKEN", "")
|
||||
REFRESH_INTERVAL_HOURS = int(os.getenv("FETCHER_REFRESH_INTERVAL_HOURS", "24"))
|
||||
TRIAL_GC_DAYS = int(os.getenv("FETCHER_TRIAL_GC_DAYS", "7"))
|
||||
# The hourly refresh tick stops once the PAT's core budget falls under this
|
||||
# reserve, so new sign-ups still get fetched, and refreshes at most this many
|
||||
# users per tick, so a day's worth of sign-ups going stale together is spread
|
||||
# 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_MAX_PER_TICK = int(os.getenv("FETCHER_REFRESH_MAX_PER_TICK", "60"))
|
||||
API_TIMEOUT = int(os.getenv("API_TIMEOUT", "15"))
|
||||
|
||||
# Generator URL is used as a callback target when a /fetch-async background
|
||||
|
||||
+26
-2
@@ -2,17 +2,41 @@
|
||||
import logging
|
||||
import time
|
||||
|
||||
import requests
|
||||
|
||||
from . import config, db, github
|
||||
|
||||
log = logging.getLogger("fetcher.cron")
|
||||
|
||||
|
||||
def _core_remaining() -> int | None:
|
||||
"""Core REST calls left on the PAT, or None if unknown. GitHub does not
|
||||
count /rate_limit calls against the quota."""
|
||||
if not config.GITHUB_PAT:
|
||||
return None
|
||||
try:
|
||||
r = requests.get("https://api.github.com/rate_limit",
|
||||
headers={"Authorization": f"Bearer {config.GITHUB_PAT}"},
|
||||
timeout=config.API_TIMEOUT)
|
||||
return int(r.json()["resources"]["core"]["remaining"])
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def tick(hours: int, active_within_days: int, gc_days: int) -> dict:
|
||||
"""Refresh due users, then GC abandoned ones. Returns counts."""
|
||||
refreshed = 0
|
||||
failed = 0
|
||||
due = db.users_due_for_refresh(hours=hours, active_within_days=active_within_days)
|
||||
for username in due:
|
||||
deferred = max(len(due) - config.REFRESH_MAX_PER_TICK, 0)
|
||||
due = due[:config.REFRESH_MAX_PER_TICK]
|
||||
for i, username in enumerate(due):
|
||||
left = _core_remaining()
|
||||
if left is not None and left < config.REFRESH_CORE_RESERVE:
|
||||
log.info("core budget %s under reserve %s; deferring %s refreshes",
|
||||
left, config.REFRESH_CORE_RESERVE, len(due) - i)
|
||||
deferred += len(due) - i
|
||||
break
|
||||
try:
|
||||
data = github.fetch_github_data(username, token=config.GITHUB_PAT)
|
||||
user = data.get("user")
|
||||
@@ -32,7 +56,7 @@ def tick(hours: int, active_within_days: int, gc_days: int) -> dict:
|
||||
log.warning("refresh failed for %s: %s", username, e)
|
||||
failed += 1
|
||||
gc_removed = db.delete_stale(days=gc_days)
|
||||
return {"refreshed": refreshed, "failed": failed, "gc_removed": gc_removed}
|
||||
return {"refreshed": refreshed, "failed": failed, "deferred": deferred, "gc_removed": gc_removed}
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
+1
-1
@@ -122,7 +122,7 @@ def users_due_for_refresh(hours: int, active_within_days: int) -> list[str]:
|
||||
active_after = (datetime.utcnow() - timedelta(days=active_within_days)).isoformat(timespec="seconds") + "Z"
|
||||
with _connect() as c:
|
||||
rows = c.execute(
|
||||
"SELECT username FROM users WHERE fetched_at < ? AND last_requested_at > ?",
|
||||
"SELECT username FROM users WHERE fetched_at < ? AND last_requested_at > ? ORDER BY fetched_at",
|
||||
(stale_before, active_after),
|
||||
).fetchall()
|
||||
return [r["username"] for r in rows]
|
||||
|
||||
@@ -50,3 +50,35 @@ def test_tick_runs_gc_for_abandoned_trial_users(tmp_db):
|
||||
stats = cronmod.tick(hours=24, active_within_days=7, gc_days=7)
|
||||
assert stats["gc_removed"] == 1
|
||||
assert dbmod.get_user("ghost") is None
|
||||
|
||||
|
||||
def _due(*names):
|
||||
# Backdate each user so they're due; later names are fetched more recently.
|
||||
for i, n in enumerate(names):
|
||||
dbmod.upsert_user(n, {"user": {"login": n}})
|
||||
with dbmod._connect() as c:
|
||||
c.execute("UPDATE users SET fetched_at=?, last_requested_at=? WHERE username=?",
|
||||
(f"2020-01-0{i + 1}T00:00:00Z", dbmod._now(), n))
|
||||
|
||||
|
||||
def test_tick_caps_refreshes_oldest_first(tmp_db, monkeypatch):
|
||||
_due("old", "mid", "new")
|
||||
monkeypatch.setattr(cronmod.config, "REFRESH_MAX_PER_TICK", 2)
|
||||
monkeypatch.setattr(cronmod, "_core_remaining", lambda: None)
|
||||
with patch("src.cron.github.fetch_github_data", side_effect=lambda u, **_k: {"user": {"login": u}}) 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] == ["old", "mid"]
|
||||
assert stats["refreshed"] == 2 and stats["deferred"] == 1
|
||||
|
||||
|
||||
def test_tick_stops_under_core_reserve(tmp_db, monkeypatch):
|
||||
# New sign-ups need the quota more than a day-old card does: once the
|
||||
# PAT's core budget drops under the reserve, the tick stops refreshing.
|
||||
_due("a", "b", "c")
|
||||
monkeypatch.setattr(cronmod.config, "REFRESH_CORE_RESERVE", 1500)
|
||||
left = iter([4000, 1400, 1400])
|
||||
monkeypatch.setattr(cronmod, "_core_remaining", lambda: next(left))
|
||||
with patch("src.cron.github.fetch_github_data", side_effect=lambda u, **_k: {"user": {"login": u}}) 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"]
|
||||
assert stats["refreshed"] == 1 and stats["deferred"] == 2
|
||||
|
||||
Reference in New Issue
Block a user