mirror of
https://github.com/ShayManor/github-readme-stats.git
synced 2026-12-02 11:53:48 +05:30
feat(api): implement async fetch with callback to enqueue build job
This commit is contained in:
+59
-3
@@ -14,6 +14,7 @@ Two-phase pipeline:
|
||||
* POST /api/<u>/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/<username>", methods=["GET"])
|
||||
@rate_limited("read")
|
||||
def get_widget(username: str):
|
||||
|
||||
+21
-12
@@ -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:
|
||||
|
||||
@@ -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()
|
||||
|
||||
Reference in New Issue
Block a user