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:
shay
2026-11-30 09:15:57 -08:00
co-authored by Claude Opus 5.5
parent d4b4a8bc52
commit 01afeeda4e
4 changed files with 65 additions and 3 deletions
+6
View File
@@ -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
View File
@@ -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
View File
@@ -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]