feat(api): implement async fetch with callback to enqueue build job

This commit is contained in:
shay
2026-05-04 12:35:41 -04:00
parent 50dd73a0de
commit 4a1d31ffdd
9 changed files with 399 additions and 32 deletions
+89
View File
@@ -2,7 +2,9 @@
import hmac
import logging
import re
import threading
import requests
from concurrent.futures import ThreadPoolExecutor
from flask import Flask, jsonify, request, Response
from functools import wraps
@@ -11,6 +13,22 @@ from . import config, db, github
app = Flask(__name__)
log = logging.getLogger("fetcher.api")
# Background pool for /fetch-async. The fetch routinely takes 10-20s of
# wall clock even after parallelization, which is too long to hold an HTTP
# request open from the generator (it would block the worker on its hot
# path). Submitting to this pool lets us return 202 immediately and call
# the generator back when the fetch finishes.
_BG_POOL = ThreadPoolExecutor(
max_workers=max(1, config.ASYNC_FETCH_WORKERS),
thread_name_prefix="fetch-bg",
)
# Per-process in-flight set. If two callers ask us to fetch the same user
# while the first fetch is still running, we ack the second one without
# starting a duplicate GitHub call. Per-process only — fine for v1's single
# fetcher container; a multi-replica deploy would need a distributed lock.
_INFLIGHT: set[str] = set()
_INFLIGHT_LOCK = threading.Lock()
# Must stay in sync with github.py's _USERNAME_RE. Trust boundary: the
# fetcher is called only by the generator over the internal network, but
# a compromised/bugged generator must not be able to turn us into an
@@ -84,6 +102,77 @@ def force_fetch():
return jsonify({"stored": True, "payload_hash": new_hash, "changed": old_hash != new_hash})
def _bg_fetch(username: str) -> None:
"""Background fetch + generator callback. Runs on _BG_POOL.
Always notifies the generator on completion (including not_found and
failure cases) so the generator can decide whether to enqueue a build,
persist a not_found marker, or do nothing. Without the callback the
generator would have to poll, which is exactly the design we're
removing — the worker used to block on the synchronous /data call and
time out on long fetches.
"""
try:
try:
data = github.fetch_github_data(username, token=config.GITHUB_PAT)
if _is_github_not_found(data):
data = {"error": "not_found"}
payload_hash = db.upsert_user(username, data)
ok = True
except Exception:
log.exception("background fetch failed for %s", username)
payload_hash = ""
ok = False
_notify_generator_data_ready(username, payload_hash, ok)
finally:
with _INFLIGHT_LOCK:
_INFLIGHT.discard(username)
def _notify_generator_data_ready(username: str, payload_hash: str, ok: bool) -> None:
if not config.GENERATOR_URL or not config.INTERNAL_TOKEN:
return
try:
requests.post(
f"{config.GENERATOR_URL}/internal/data-ready",
headers={"X-Internal-Token": config.INTERNAL_TOKEN},
json={"username": username, "payload_hash": payload_hash, "ok": ok},
timeout=5,
)
except Exception:
log.warning("data-ready callback to generator failed for %s", username, exc_info=True)
@app.route("/fetch-async", methods=["POST"])
@require_internal_token
def fetch_async():
"""Kick off a background GitHub fetch and return immediately.
The generator calls this on enrollment so the user-perceived latency
isn't bounded by GitHub's response time + the generator's HTTP
timeout. When the fetch completes the fetcher posts back to
/internal/data-ready on the generator, which is what enqueues the
build job.
"""
body = request.get_json(silent=True) or {}
username = body.get("username")
if not _valid_username(username):
return jsonify({"error": "invalid_username"}), 400
with _INFLIGHT_LOCK:
if username in _INFLIGHT:
return jsonify({"queued": True, "already_inflight": True}), 202
_INFLIGHT.add(username)
try:
_BG_POOL.submit(_bg_fetch, username)
except RuntimeError:
# Pool was shut down (process exiting). Drop the in-flight marker
# so a retry after restart isn't blocked by a stale entry.
with _INFLIGHT_LOCK:
_INFLIGHT.discard(username)
return jsonify({"error": "shutting_down"}), 503
return jsonify({"queued": True}), 202
@app.route("/avatar/<username>", methods=["GET"])
@require_internal_token
def avatar(username: str):
+7
View File
@@ -9,6 +9,13 @@ REFRESH_INTERVAL_HOURS = int(os.getenv("FETCHER_REFRESH_INTERVAL_HOURS", "24"))
TRIAL_GC_DAYS = int(os.getenv("FETCHER_TRIAL_GC_DAYS", "7"))
API_TIMEOUT = int(os.getenv("API_TIMEOUT", "15"))
# Generator URL is used as a callback target when a /fetch-async background
# task completes. Token-protected via the same FETCHER_INTERNAL_TOKEN that
# secures generator -> fetcher calls. Empty string disables the callback,
# which is fine for tests and one-shot scripts.
GENERATOR_URL = os.getenv("GENERATOR_URL", "http://localhost:5002")
ASYNC_FETCH_WORKERS = int(os.getenv("FETCHER_ASYNC_WORKERS", "2"))
# Collaborator-detection tuning
COLLABORATOR_MAX_REPO_SIZE = int(os.getenv("COLLABORATOR_MAX_REPO_SIZE", "150"))
COLLABORATOR_TOP_REPOS = int(os.getenv("COLLABORATOR_TOP_REPOS", "30"))
+41 -15
View File
@@ -338,8 +338,9 @@ class DirectAPISource:
created_year = int(created_at[:4])
current_year = datetime.now().year
# Fetch year by year
total_contributions = 0
# Fetch year by year, in parallel. Sequentially this was 1 request
# per year of account age (~7-10 calls for typical accounts), each
# ~1s — easily a 10s wall-clock contributor on its own.
print(f" Fetching contributions from {created_year} to {current_year}...")
year_query = """
query($login: String!, $from: DateTime!, $to: DateTime!) {
@@ -350,7 +351,8 @@ class DirectAPISource:
}
}
"""
for year in range(created_year, current_year + 1):
def _fetch_year(year: int) -> tuple[int, int]:
year_resp = requests.post(
'https://api.github.com/graphql',
json={
@@ -364,17 +366,22 @@ class DirectAPISource:
headers=headers,
timeout=config.API_TIMEOUT,
)
if year_resp.ok:
year_data = year_resp.json()
if 'data' in year_data and year_data['data'].get('user'):
year_contributions = year_data['data']['user']['contributionsCollection']['contributionCalendar']['totalContributions']
total_contributions += year_contributions
print(f" {year}: {year_contributions:,} contributions")
else:
print(f" {year}: Error - {year_data}")
else:
if not year_resp.ok:
print(f" {year}: HTTP {year_resp.status_code}")
return year, 0
year_data = year_resp.json()
if 'data' in year_data and year_data['data'].get('user'):
n = year_data['data']['user']['contributionsCollection']['contributionCalendar']['totalContributions']
return year, n
print(f" {year}: Error - {year_data}")
return year, 0
years = list(range(created_year, current_year + 1))
total_contributions = 0
with ThreadPoolExecutor(max_workers=min(10, len(years) or 1)) as pool:
for year, n in sorted(pool.map(_fetch_year, years)):
total_contributions += n
print(f" {year}: {n:,} contributions")
print(f" GraphQL API found {total_contributions:,} contributions (all-time)")
return total_contributions
@@ -729,14 +736,33 @@ def _fetch_collaborators_data(
qualifying = qualifying[:config.COLLABORATOR_TOP_REPOS]
print(f" Scoring collaborators across {len(qualifying)} qualifying repos")
# Step 3+4: fetch contributors and score
# Step 3: fetch contributors for all qualifying repos in parallel.
# The per-repo REST call is ~300-500ms; sequentially this dominated the
# whole fetch (30 repos × ~0.5s ≈ 15s). Fan out with the same pool size
# used for languages — GitHub's secondary rate limit tolerates this fine.
contributors_by_repo: dict[str, list] = {}
with ThreadPoolExecutor(max_workers=10) as pool:
futures = {
pool.submit(source.fetch_repo_contributors, r["full_name"], 1): r["full_name"]
for r in qualifying
}
for fut in as_completed(futures):
full_name = futures[fut]
try:
contributors_by_repo[full_name] = fut.result() or []
except Exception as e:
print(f" failed to fetch contributors for {full_name}: {e}")
contributors_by_repo[full_name] = []
# Step 4: score sequentially (cheap, in-memory) preserving the original
# `qualifying` order so deterministic-output tests still pass.
collab_stats: dict = {}
for r in qualifying:
full_name = r["full_name"]
user_commits = r["user_commits"]
boost = config.OWNER_BOOST if r["is_owner"] else 1.0
contributors = source.fetch_repo_contributors(full_name, min_commits=1)
contributors = contributors_by_repo.get(full_name, [])
# Drop huge OSS projects
if len(contributors) >= config.COLLABORATOR_MAX_REPO_SIZE:
print(f" skipping {full_name}: too many contributors ({len(contributors)})")