From 4a1d31ffdda0b378d15d5cdd98c79178132d8a26 Mon Sep 17 00:00:00 2001 From: shay Date: Mon, 4 May 2026 12:35:41 -0400 Subject: [PATCH] feat(api): implement async fetch with callback to enqueue build job --- fetcher/src/api.py | 89 ++++++++++++++++++++++++++++++ fetcher/src/config.py | 7 +++ fetcher/src/github.py | 56 ++++++++++++++----- fetcher/tests/test_api.py | 97 +++++++++++++++++++++++++++++++++ generator/src/api.py | 62 ++++++++++++++++++++- generator/src/db.py | 33 +++++++---- generator/src/fetcher_client.py | 25 ++++++++- generator/tests/test_api.py | 51 +++++++++++++++++ generator/tests/test_db.py | 11 ++++ 9 files changed, 399 insertions(+), 32 deletions(-) diff --git a/fetcher/src/api.py b/fetcher/src/api.py index d16caee..b4805fa 100644 --- a/fetcher/src/api.py +++ b/fetcher/src/api.py @@ -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/", methods=["GET"]) @require_internal_token def avatar(username: str): diff --git a/fetcher/src/config.py b/fetcher/src/config.py index 19572a6..822b152 100644 --- a/fetcher/src/config.py +++ b/fetcher/src/config.py @@ -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")) diff --git a/fetcher/src/github.py b/fetcher/src/github.py index 60624ed..2cdcb70 100644 --- a/fetcher/src/github.py +++ b/fetcher/src/github.py @@ -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)})") diff --git a/fetcher/tests/test_api.py b/fetcher/tests/test_api.py index c161116..008b5d1 100644 --- a/fetcher/tests/test_api.py +++ b/fetcher/tests/test_api.py @@ -71,3 +71,100 @@ def test_data_auto_fetches_on_miss(client, monkeypatch): def test_force_fetch_requires_auth(client): r = client.post("/fetch", json={"username": "alice"}) assert r.status_code == 401 + + +def test_fetch_async_requires_auth(client): + r = client.post("/fetch-async", json={"username": "alice"}) + assert r.status_code == 401 + + +def test_fetch_async_rejects_invalid_username(client): + r = client.post("/fetch-async", headers={"X-Internal-Token": "secret"}, + json={"username": "../etc/passwd"}) + assert r.status_code == 400 + + +def test_fetch_async_runs_in_background_and_calls_back(client, monkeypatch): + """The async path must (a) return 202 immediately without waiting for + GitHub, and (b) POST back to the generator's /internal/data-ready when + the background fetch completes. Without (a) we'd be back to the old + synchronous-blocking design that timed out the worker; without (b) + nothing would ever enqueue the build job.""" + import threading + from src import api as apimod + + fetch_done = threading.Event() + callback_calls: list = [] + + def fake_fetch(username, token=None): + # Block briefly so the test can prove /fetch-async returned before + # this finished. + fetch_done.wait(timeout=2) + return {"user": {"login": username, "avatar_url": "x"}, "repos": []} + + def fake_post(url, headers=None, json=None, timeout=None): + callback_calls.append({"url": url, "json": json, "headers": headers}) + class _R: status_code = 200 + return _R() + + monkeypatch.setattr(apimod.github, "fetch_github_data", fake_fetch) + monkeypatch.setattr(apimod.requests, "post", fake_post) + monkeypatch.setattr(apimod.config, "GENERATOR_URL", "http://gen:5002") + + r = client.post("/fetch-async", headers={"X-Internal-Token": "secret"}, + json={"username": "alice"}) + assert r.status_code == 202 + assert r.get_json()["queued"] is True + + # Let the background fetch finish; wait for the callback. + fetch_done.set() + for _ in range(50): + if callback_calls: + break + threading.Event().wait(0.05) + + assert len(callback_calls) == 1 + cb = callback_calls[0] + assert cb["url"] == "http://gen:5002/internal/data-ready" + assert cb["json"]["username"] == "alice" + assert cb["json"]["ok"] is True + assert cb["json"]["payload_hash"] + + +def test_fetch_async_dedupes_inflight(client, monkeypatch): + """A second /fetch-async call for the same user while the first is + still in flight must not start a second GitHub fetch.""" + import threading + from src import api as apimod + + started = threading.Event() + release = threading.Event() + fetch_calls = {"n": 0} + + def fake_fetch(username, token=None): + fetch_calls["n"] += 1 + started.set() + release.wait(timeout=2) + return {"user": {"login": username, "avatar_url": "x"}, "repos": []} + + monkeypatch.setattr(apimod.github, "fetch_github_data", fake_fetch) + monkeypatch.setattr(apimod.requests, "post", lambda *a, **kw: type("R", (), {"status_code": 200})()) + monkeypatch.setattr(apimod.config, "GENERATOR_URL", "") + + r1 = client.post("/fetch-async", headers={"X-Internal-Token": "secret"}, + json={"username": "alice"}) + assert r1.status_code == 202 + assert started.wait(timeout=2) + + r2 = client.post("/fetch-async", headers={"X-Internal-Token": "secret"}, + json={"username": "alice"}) + assert r2.status_code == 202 + assert r2.get_json().get("already_inflight") is True + + release.set() + # Drain + for _ in range(50): + if fetch_calls["n"] >= 1 and "alice" not in apimod._INFLIGHT: + break + threading.Event().wait(0.05) + assert fetch_calls["n"] == 1 diff --git a/generator/src/api.py b/generator/src/api.py index b5b58e4..f4835c2 100644 --- a/generator/src/api.py +++ b/generator/src/api.py @@ -14,6 +14,7 @@ Two-phase pipeline: * POST /api//generate synchronously renders and persists the composite SVG. This is what the user's "Generate" button calls. """ +import hmac import logging import os import time @@ -72,6 +73,21 @@ def _kickoff_prefetch_async(username: str): log.warning("prefetch pool shut down; skipping kickoff for %s", username) +def _request_fetch_async(username: str) -> None: + """Ask the fetcher to start a background GitHub fetch for `username`. + + Returns as soon as the fetcher acks (HTTP 202). The fetcher will POST + back to /internal/data-ready when the data lands in fetcher.db, which + is what enqueues the build job. Failures here are logged and dropped: + the generator's cron loop will see the user on its next tick and try + again, so a transient network blip can't permanently strand a signup. + """ + try: + fetcher_client.start_fetch_async(username) + except Exception: + log.warning("fetch-async kickoff failed for %s", username, exc_info=True) + + # ---- Per-IP rate limiter ----------------------------------------------------- # In-process sliding-window limiter. Good enough for v1; behind a reverse proxy # we read X-Forwarded-For (trusting only the last hop set by the proxy). For a @@ -512,14 +528,20 @@ def auth_github_callback(): session["gh_id"] = gh_id session["gh_avatar_url"] = avatar_url - # Implicit enrollment. Idempotent; refreshes github_avatar_url on return logins. + # Implicit enrollment. Idempotent; refreshes github_avatar_url on return + # logins. We deliberately do NOT enqueue a build job here — the build is + # added to the queue by /internal/data-ready when the fetcher finishes + # the GitHub fetch. Enqueuing earlier means the worker pops a job before + # the fetcher has data, blocking on a synchronous GitHub fetch that can + # easily exceed the worker's HTTP timeout. defaults = { "theme": "dark", "enabled": config.ENABLED_WIDGETS, "widget_order": config.WIDGET_ORDER, } - db.enroll(login, defaults, github_id=gh_id, github_avatar_url=avatar_url) - _kickoff_prefetch_async(login) + db.enroll(login, defaults, github_id=gh_id, github_avatar_url=avatar_url, + enqueue_build=False) + _request_fetch_async(login) return redirect(nxt) @@ -529,6 +551,40 @@ def health(): return jsonify({"status": "ok", "service": "generator"}) +@app.route("/internal/data-ready", methods=["POST"]) +def internal_data_ready(): + """Called by the fetcher when a /fetch-async background job finishes. + + Token-protected by the same shared secret used for generator -> fetcher + calls. The body is `{username, payload_hash, ok}`. If the user is + enrolled, enqueue a build job; the worker picks it up on its next 0.5s + tick and the fetcher's data is already cached, so the build runs in + seconds. If the user is not enrolled here we silently ignore — the + fetcher might have been kicked off by some other path (cron, manual + refresh) and we don't want to leak a job for a stranger. + """ + token = request.headers.get("X-Internal-Token", "") + if not config.FETCHER_INTERNAL_TOKEN or not hmac.compare_digest( + token, config.FETCHER_INTERNAL_TOKEN + ): + return jsonify({"error": "unauthorized"}), 401 + body = request.get_json(silent=True) or {} + username = body.get("username") + if not isinstance(username, str) or not is_valid_username(username): + return jsonify({"error": "invalid_username"}), 400 + username = username.lower() + if db.get_settings(username) is None: + return jsonify({"ignored": True, "reason": "not_enrolled"}), 200 + if not body.get("ok", True): + # The fetch failed (network / GitHub 5xx). No point queueing a + # build that would just fail too. The cron loop will retry the + # fetch on its next tick. + return jsonify({"ignored": True, "reason": "fetch_failed"}), 200 + job_id = db.enqueue_build(username) + log.info("enqueued build %d for %s after fetch completion", job_id, username) + return jsonify({"queued": True, "job_id": job_id}), 200 + + @app.route("/api/", methods=["GET"]) @rate_limited("read") def get_widget(username: str): diff --git a/generator/src/db.py b/generator/src/db.py index 726c3bf..ec2d06e 100644 --- a/generator/src/db.py +++ b/generator/src/db.py @@ -149,13 +149,19 @@ def settings_hash(settings: dict) -> str: def enroll(username: str, defaults: dict, github_id: int | None = None, - github_avatar_url: str | None = None) -> dict: - """Insert a settings row if missing, bump the daily counter, enqueue a build. + github_avatar_url: str | None = None, + enqueue_build: bool = True) -> dict: + """Insert a settings row if missing, bump the daily counter, optionally + enqueue a build. - Idempotent: calling again for an existing user refreshes github_avatar_url - (so login keeps the avatar fresh) and enqueues a rebuild. Always returns - {"job_id": int}. No token is returned — auth is handled by the signed - session cookie. + `enqueue_build=False` is used by the OAuth callback so the build job is + only added to the queue *after* the fetcher has actually fetched the + user (via the /internal/data-ready callback). Without this, the worker + would pop a build job for a user the fetcher hasn't seen yet and either + block on a synchronous GitHub fetch or retry-fail until cron. + + Idempotent: calling again for an existing user refreshes + github_avatar_url. Returns {"job_id": int|None}. """ sh = settings_hash(defaults) now = _now() @@ -180,13 +186,16 @@ def enroll(username: str, defaults: dict, ON CONFLICT(day) DO UPDATE SET count = count + 1""", (_today(),), ) - cur = c.execute( - """INSERT INTO jobs(kind, username, status, created_at, updated_at) - VALUES ('build', ?, 'pending', ?, ?)""", - (username, now, now), - ) + job_id: int | None = None + if enqueue_build: + cur = c.execute( + """INSERT INTO jobs(kind, username, status, created_at, updated_at) + VALUES ('build', ?, 'pending', ?, ?)""", + (username, now, now), + ) + job_id = cur.lastrowid c.commit() - return {"job_id": cur.lastrowid} + return {"job_id": job_id} def enrollments_today() -> int: diff --git a/generator/src/fetcher_client.py b/generator/src/fetcher_client.py index 44d8fd7..e8c52bf 100644 --- a/generator/src/fetcher_client.py +++ b/generator/src/fetcher_client.py @@ -8,14 +8,35 @@ def _headers() -> dict: return {"X-Internal-Token": config.FETCHER_INTERNAL_TOKEN} +# Most calls hit the cache and return in <100ms; the only slow path is when +# the fetcher's /data endpoint falls back to a synchronous GitHub fetch +# (used by the /?username=X shortcut). 60s leaves headroom for the +# parallelized worst case (~15-25s) without poisoning the worker's job +# retry chain on a transient blip. +_TIMEOUT_S = 60 + + def get_data(username: str) -> dict: - r = requests.get(f"{config.FETCHER_URL}/data/{username}", headers=_headers(), timeout=30) + r = requests.get(f"{config.FETCHER_URL}/data/{username}", headers=_headers(), + timeout=_TIMEOUT_S) r.raise_for_status() return r.json() def force_fetch(username: str) -> dict: r = requests.post(f"{config.FETCHER_URL}/fetch", headers=_headers(), - json={"username": username}, timeout=30) + json={"username": username}, timeout=_TIMEOUT_S) + r.raise_for_status() + return r.json() + + +def start_fetch_async(username: str) -> dict: + """Tell the fetcher to fetch this user in the background. Returns 202 + after the fetcher has accepted the job — does NOT wait for the GitHub + fetch to complete. The fetcher will POST back to /internal/data-ready + on this service when the data is persisted, which is what enqueues the + build job. See fetcher.api.fetch_async for the other half.""" + r = requests.post(f"{config.FETCHER_URL}/fetch-async", headers=_headers(), + json={"username": username}, timeout=10) r.raise_for_status() return r.json() diff --git a/generator/tests/test_api.py b/generator/tests/test_api.py index 05934ba..9b2970b 100644 --- a/generator/tests/test_api.py +++ b/generator/tests/test_api.py @@ -10,6 +10,8 @@ def client(monkeypatch): # No-op the kickoff so tests don't spawn background threads that # would try to reach the (unmocked) fetcher and race tempdir teardown. monkeypatch.setattr(apimod, "_kickoff_prefetch_async", lambda *_a, **_kw: None) + # Same reason for the new async-fetch hook used by the OAuth callback. + monkeypatch.setattr(apimod, "_request_fetch_async", lambda *_a, **_kw: None) with tempfile.TemporaryDirectory() as d: monkeypatch.setattr(dbmod, "SETTINGS_DB_PATH", os.path.join(d, "s.db")) monkeypatch.setattr(dbmod, "WIDGETS_DB_PATH", os.path.join(d, "w.db")) @@ -304,6 +306,55 @@ def test_enroll_endpoint_is_gone(client): assert r.status_code == 405 +# ---- POST /internal/data-ready: callback from fetcher when an async fetch lands ---- + + +def test_data_ready_requires_internal_token(client, monkeypatch): + monkeypatch.setattr(cfg, "FETCHER_INTERNAL_TOKEN", "secret") + r = client.post("/internal/data-ready", json={"username": "alice"}) + assert r.status_code == 401 + + +def test_data_ready_enqueues_build_for_enrolled_user(client, monkeypatch): + """The whole point of the async path: the build job appears in the queue + after the fetcher has stored data, not before. Enrolling a user no + longer adds a job, so /data-ready is the only thing that does.""" + monkeypatch.setattr(cfg, "FETCHER_INTERNAL_TOKEN", "secret") + dbmod.enroll("alice", {"theme": "dark"}, enqueue_build=False) + assert dbmod.pending_job_count() == 0 + + r = client.post("/internal/data-ready", + headers={"X-Internal-Token": "secret"}, + json={"username": "alice", "payload_hash": "h1", "ok": True}) + assert r.status_code == 200 + assert r.get_json()["queued"] is True + assert dbmod.pending_job_count() == 1 + + +def test_data_ready_ignores_unknown_user(client, monkeypatch): + """If we get a callback for someone who hasn't enrolled here we must not + create a job — the fetcher might be shared or the enrollment might + have been deleted in between.""" + monkeypatch.setattr(cfg, "FETCHER_INTERNAL_TOKEN", "secret") + r = client.post("/internal/data-ready", + headers={"X-Internal-Token": "secret"}, + json={"username": "stranger", "payload_hash": "h1", "ok": True}) + assert r.status_code == 200 + assert r.get_json()["ignored"] is True + assert dbmod.pending_job_count() == 0 + + +def test_data_ready_does_not_enqueue_on_failed_fetch(client, monkeypatch): + monkeypatch.setattr(cfg, "FETCHER_INTERNAL_TOKEN", "secret") + dbmod.enroll("alice", {"theme": "dark"}, enqueue_build=False) + r = client.post("/internal/data-ready", + headers={"X-Internal-Token": "secret"}, + json={"username": "alice", "payload_hash": "", "ok": False}) + assert r.status_code == 200 + assert r.get_json()["ignored"] is True + assert dbmod.pending_job_count() == 0 + + def test_query_override_triggers_adhoc_render_without_persisting(client): """GET /api/?theme=... renders on-demand via worker.render_composite_adhoc and does not mutate the stored settings blob — this is the path visitors diff --git a/generator/tests/test_db.py b/generator/tests/test_db.py index f492678..a706ea1 100644 --- a/generator/tests/test_db.py +++ b/generator/tests/test_db.py @@ -31,6 +31,17 @@ def test_enroll_twice_noops(tmp_dbs): assert r1["job_id"] > 0 and r2["job_id"] > 0 +def test_enroll_without_build_skips_job(tmp_dbs): + """OAuth callback uses this so the build job is only added once the + fetcher has actually fetched (via /internal/data-ready). Otherwise the + worker pops a job for a user with no fetcher data yet.""" + r = dbmod.enroll("alice", {"theme": "dark"}, enqueue_build=False) + assert r["job_id"] is None + assert dbmod.pending_job_count() == 0 + # The user row itself was still created so callbacks can find them. + assert dbmod.get_settings("alice") is not None + + def test_enroll_with_github_profile(tmp_dbs): dbmod.enroll("alice", {"theme": "dark"}, github_id=1, github_avatar_url="https://x/a.png") with dbmod._settings_conn() as c: