feat(fetcher): add cron refresh + GC and service README

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
shay
2026-04-17 16:34:52 -04:00
co-authored by Claude Sonnet 4.6
parent d77dea20bc
commit cb3ace8dcd
3 changed files with 120 additions and 0 deletions
+37
View File
@@ -0,0 +1,37 @@
# Fetcher Service
Owns every GitHub API interaction. Holds the PAT. Exposes cached payloads
over an internal-only HTTP API protected by a shared secret.
## Run locally
cd fetcher
pip install -r requirements.txt
FETCHER_INTERNAL_TOKEN=dev GITHUB_PAT=ghp_xxx python -m src.api
Cron (separate process):
FETCHER_INTERNAL_TOKEN=dev GITHUB_PAT=ghp_xxx python -m src.cron
## Test
cd fetcher && pytest
## Docker
docker build -t ghstats-fetcher .
docker run -e GITHUB_PAT=ghp_xxx -e FETCHER_INTERNAL_TOKEN=dev -p 5001:5001 -v $(pwd)/data:/app/data ghstats-fetcher
# cron: override CMD to ["python","-m","src.cron"]
## Endpoints
| Method | Path | Auth | Description |
|---|---|---|---|
| GET | /health | none | health check |
| GET | /data/<u> | X-Internal-Token | return stored payload; auto-fetches on miss |
| POST | /fetch | X-Internal-Token | force re-fetch (body: {username}) |
| GET | /avatar/<u> | X-Internal-Token | proxied avatar bytes |
## Env
See `src/config.py`.
+48
View File
@@ -0,0 +1,48 @@
"""Scheduled refresh + GC loop. Run as its own container (CMD override)."""
import logging
import time
from . import config, db, github
log = logging.getLogger("fetcher.cron")
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:
try:
data = github.fetch_github_data(username, token=config.GITHUB_PAT)
user = data.get("user")
if user is None or (isinstance(user, dict) and user.get("message") == "Not Found"):
data = {"error": "not_found"}
db.upsert_user(username, data)
refreshed += 1
except Exception as e:
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}
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()
+35
View File
@@ -0,0 +1,35 @@
import os
import tempfile
import pytest
from unittest.mock import patch
from src import db as dbmod
from src import cron as cronmod
@pytest.fixture
def tmp_db(monkeypatch):
with tempfile.TemporaryDirectory() as d:
monkeypatch.setattr(dbmod, "DB_PATH", os.path.join(d, "t.db"))
dbmod.init_db()
yield
def test_refresh_tick_calls_github_for_due_users(tmp_db):
dbmod.upsert_user("alice", {"user": {"login": "alice"}})
# Backdate
with dbmod._connect() as c:
c.execute("UPDATE users SET fetched_at='2020-01-01T00:00:00Z', last_requested_at=? WHERE username='alice'",
(dbmod._now(),))
with patch("src.cron.github.fetch_github_data", return_value={"user": {"login": "alice", "updated": True}}) as gh:
stats = cronmod.tick(hours=24, active_within_days=7, gc_days=7)
assert gh.called
assert stats["refreshed"] == 1
def test_tick_runs_gc_for_abandoned_trial_users(tmp_db):
dbmod.upsert_user("ghost", {"user": {"login": "ghost"}})
with dbmod._connect() as c:
c.execute("UPDATE users SET last_requested_at='2020-01-01T00:00:00Z' WHERE username='ghost'")
stats = cronmod.tick(hours=24, active_within_days=7, gc_days=7)
assert stats["gc_removed"] == 1
assert dbmod.get_user("ghost") is None