mirror of
https://github.com/ShayManor/github-readme-stats.git
synced 2026-12-02 11:53:48 +05:30
98 lines
3.7 KiB
Python
98 lines
3.7 KiB
Python
"""Scheduled refresh + GC loop. Run as its own container (CMD override)."""
|
|
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 _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:
|
|
"""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)
|
|
deferred = max(len(due) - config.REFRESH_MAX_PER_TICK, 0)
|
|
due = due[:config.REFRESH_MAX_PER_TICK]
|
|
for i, username in enumerate(due):
|
|
if i:
|
|
time.sleep(config.REFRESH_USER_PAUSE)
|
|
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 = _fetch_retrying_once(username)
|
|
user = data.get("user")
|
|
if user is None or (isinstance(user, dict) and user.get("message") == "Not Found"):
|
|
data = {"error": "not_found"}
|
|
db.bump_fetch_metric("not_found")
|
|
else:
|
|
db.bump_fetch_metric("ok")
|
|
db.upsert_user(username, data)
|
|
refreshed += 1
|
|
except github.GitHubTransientError as e:
|
|
db.bump_fetch_metric("rate_limited")
|
|
log.warning("refresh rate-limited for %s (kept last-good): %s; deferring %s refreshes",
|
|
username, e, len(due) - i - 1)
|
|
failed += 1
|
|
deferred += len(due) - i - 1
|
|
break
|
|
except Exception as e:
|
|
db.bump_fetch_metric("error")
|
|
log.warning("refresh failed for %s: %s", username, e)
|
|
failed += 1
|
|
gc_removed = db.delete_stale(days=gc_days)
|
|
return {"refreshed": refreshed, "failed": failed, "deferred": deferred, "gc_removed": gc_removed}
|
|
|
|
|
|
def main():
|
|
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s")
|
|
db.init_db()
|
|
interval = 3600 # 1h between ticks
|
|
while True:
|
|
try:
|
|
stats = tick(
|
|
hours=config.REFRESH_INTERVAL_HOURS,
|
|
active_within_days=config.TRIAL_GC_DAYS,
|
|
gc_days=config.TRIAL_GC_DAYS,
|
|
)
|
|
log.info("tick complete: %s", stats)
|
|
except Exception:
|
|
log.exception("tick failed")
|
|
time.sleep(interval)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|