feat(fetcher): add Flask API with auth, auto-fetch, avatar

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
shay
2026-04-17 16:32:59 -04:00
co-authored by Claude Sonnet 4.6
parent 1a3caff269
commit d77dea20bc
2 changed files with 162 additions and 0 deletions
+89
View File
@@ -0,0 +1,89 @@
"""Flask app for the fetcher service. All endpoints require X-Internal-Token."""
import hmac
import requests
from flask import Flask, jsonify, request, Response
from functools import wraps
from . import config, db, github
app = Flask(__name__)
def require_internal_token(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
token = request.headers.get("X-Internal-Token", "")
if not config.INTERNAL_TOKEN or not hmac.compare_digest(token, config.INTERNAL_TOKEN):
return jsonify({"error": "unauthorized"}), 401
return fn(*args, **kwargs)
return wrapper
@app.route("/health", methods=["GET"])
def health():
return jsonify({"status": "ok", "service": "fetcher", "users": len(db.list_usernames())})
@app.route("/data/<username>", methods=["GET"])
@require_internal_token
def get_data(username: str):
row = db.get_user(username)
if row is None:
# Auto-fetch path
data = github.fetch_github_data(username, token=config.GITHUB_PAT)
if _is_github_not_found(data):
data = {"error": "not_found"}
h = db.upsert_user(username, data)
return jsonify({"data": data, "payload_hash": h, "fetched": True})
return jsonify({
"data": row["data"],
"payload_hash": row["payload_hash"],
"fetched_at": row["fetched_at"],
"fetched": False,
})
@app.route("/fetch", methods=["POST"])
@require_internal_token
def force_fetch():
body = request.get_json(silent=True) or {}
username = body.get("username")
if not username:
return jsonify({"error": "username required"}), 400
try:
data = github.fetch_github_data(username, token=config.GITHUB_PAT)
except Exception as e:
return jsonify({"error": f"fetch failed: {e}"}), 502
if _is_github_not_found(data):
data = {"error": "not_found"}
old = db.get_user(username)
old_hash = old["payload_hash"] if old else None
new_hash = db.upsert_user(username, data)
return jsonify({"stored": True, "payload_hash": new_hash, "changed": old_hash != new_hash})
@app.route("/avatar/<username>", methods=["GET"])
@require_internal_token
def avatar(username: str):
r = requests.get(f"https://github.com/{username}.png", timeout=config.API_TIMEOUT, allow_redirects=True)
if r.status_code != 200:
return jsonify({"error": "avatar unavailable"}), 404
return Response(r.content, mimetype=r.headers.get("Content-Type", "image/png"))
def _is_github_not_found(data: dict) -> bool:
user = data.get("user")
if user is None:
return True
if isinstance(user, dict) and user.get("message") == "Not Found":
return True
return False
def main():
db.init_db()
app.run(host="0.0.0.0", port=config.PORT)
if __name__ == "__main__":
main()
+73
View File
@@ -0,0 +1,73 @@
import os
import tempfile
import pytest
import responses as resp_lib
from src import db as dbmod
from src import api as apimod
@pytest.fixture
def client(monkeypatch):
with tempfile.TemporaryDirectory() as d:
monkeypatch.setattr(dbmod, "DB_PATH", os.path.join(d, "t.db"))
monkeypatch.setattr(apimod.config, "INTERNAL_TOKEN", "secret")
monkeypatch.setattr(apimod.config, "GITHUB_PAT", "ghp_test")
dbmod.init_db()
app = apimod.app
app.config["TESTING"] = True
with app.test_client() as c:
yield c
def test_health_no_auth_required(client):
r = client.get("/health")
assert r.status_code == 200
assert r.get_json()["service"] == "fetcher"
def test_endpoints_require_internal_token(client):
r = client.get("/data/alice")
assert r.status_code == 401
@resp_lib.activate
def test_data_auto_fetches_on_miss(client, monkeypatch):
# fetch_commits: contributionCalendar/weeks
resp_lib.add(resp_lib.POST, "https://api.github.com/graphql",
json={"data": {"user": {"contributionsCollection": {"contributionCalendar": {"weeks": []}}}}}, status=200)
# fetch_commit_count (alltime) — first call: get createdAt
resp_lib.add(resp_lib.POST, "https://api.github.com/graphql",
json={"data": {"user": {"createdAt": "2020-01-01T00:00:00Z"}}}, status=200)
# fetch_commit_count (alltime) — per-year contribution totals (2020–2026, 7 years)
for _ in range(7):
resp_lib.add(resp_lib.POST, "https://api.github.com/graphql",
json={"data": {"user": {"contributionsCollection": {"contributionCalendar": {"totalContributions": 10}}}}},
status=200)
# fetch_commit_count (recent, last 6 months)
resp_lib.add(resp_lib.POST, "https://api.github.com/graphql",
json={"data": {"user": {"contributionsCollection": {"contributionCalendar": {"totalContributions": 5}}}}},
status=200)
# fetch_user_commit_repos (for collaborators)
resp_lib.add(resp_lib.POST, "https://api.github.com/graphql",
json={"data": {"user": {"contributionsCollection": {"commitContributionsByRepository": []}}}},
status=200)
# PR count search
resp_lib.add(resp_lib.GET, "https://api.github.com/search/issues",
json={"total_count": 0, "items": []}, status=200)
resp_lib.add(resp_lib.GET, "https://api.github.com/users/alice",
json={"login": "alice", "public_repos": 1, "followers": 0, "avatar_url": "https://avatars.example/a"}, status=200)
# fetch_repos: two calls (owner + all)
resp_lib.add(resp_lib.GET, "https://api.github.com/users/alice/repos", json=[], status=200)
resp_lib.add(resp_lib.GET, "https://api.github.com/users/alice/repos", json=[], status=200)
resp_lib.add(resp_lib.GET, "https://api.github.com/users/alice/events", json=[], status=200)
r = client.get("/data/alice", headers={"X-Internal-Token": "secret"})
assert r.status_code == 200
body = r.get_json()
assert body["payload_hash"]
assert body["data"]["user"]["login"] == "alice"
def test_force_fetch_requires_auth(client):
r = client.post("/fetch", json={"username": "alice"})
assert r.status_code == 401