chore(architecture): split into generator and fetcher

This commit is contained in:
shay
2026-04-15 19:49:49 -04:00
parent 87c802b20a
commit 2eee22024a
7 changed files with 462 additions and 4 deletions
+7 -3
View File
@@ -1,6 +1,11 @@
"""Data fetching and processing for GitHub profiles.""" """Data fetching and processing for GitHub profiles.
Note: ``fetch_github_data`` is intentionally NOT re-exported from this package
so that importing :mod:`src.data.processor` (used by the generator service)
does not transitively pull in the fetcher module and its ``requests`` dependency.
Import it directly from ``src.data.fetcher`` when you need it.
"""
from .fetcher import fetch_github_data
from .processor import ( from .processor import (
compute_grade, compute_grade,
compute_impact_timeline, compute_impact_timeline,
@@ -11,7 +16,6 @@ from .processor import (
) )
__all__ = [ __all__ = [
"fetch_github_data",
"compute_grade", "compute_grade",
"compute_impact_timeline", "compute_impact_timeline",
"compute_collaborators", "compute_collaborators",
+23
View File
@@ -0,0 +1,23 @@
from .repository import (
DB_PATH,
DUMMY_USERNAME,
init_db,
upsert_user,
get_user,
delete_user,
list_users,
seed_dummy_user,
REQUIRED_FIELDS,
)
__all__ = [
"DB_PATH",
"DUMMY_USERNAME",
"init_db",
"upsert_user",
"get_user",
"delete_user",
"list_users",
"seed_dummy_user",
"REQUIRED_FIELDS",
]
+115
View File
@@ -0,0 +1,115 @@
"""Hand-written dummy user payload.
Shape matches what ``fetch_github_data`` returns, so the generator's processor
code runs unchanged against it. Used as the fallback whenever a requested user
is missing from the DB or has incomplete data.
"""
from datetime import datetime, timedelta
def _recent_iso(days_ago: int) -> str:
return (datetime.utcnow() - timedelta(days=days_ago)).strftime("%Y-%m-%dT%H:%M:%SZ")
def _daily_commits() -> list[dict]:
out = []
for i in range(0, 180, 2):
date = (datetime.utcnow() - timedelta(days=i)).strftime("%Y-%m-%d")
out.append({"date": date, "count": 3 + (i % 5)})
return out
DUMMY_PAYLOAD: dict = {
"user": {
"login": "octocat",
"name": "Demo Developer",
"followers": 120,
"following": 40,
"public_repos": 24,
"avatar_url": "",
"created_at": "2018-01-15T00:00:00Z",
},
"repos": [
{
"id": 1, "name": "stellar-api", "full_name": "octocat/stellar-api",
"language": "Python", "stargazers_count": 310, "forks_count": 42,
"pushed_at": _recent_iso(3), "topics": ["backend", "api", "fastapi"],
"size": 2400,
},
{
"id": 2, "name": "pixel-ui", "full_name": "octocat/pixel-ui",
"language": "TypeScript", "stargazers_count": 180, "forks_count": 19,
"pushed_at": _recent_iso(6), "topics": ["frontend", "react", "design-system"],
"size": 1800,
},
{
"id": 3, "name": "nimbus-infra", "full_name": "octocat/nimbus-infra",
"language": "Go", "stargazers_count": 95, "forks_count": 12,
"pushed_at": _recent_iso(10), "topics": ["devops", "kubernetes", "terraform"],
"size": 1100,
},
{
"id": 4, "name": "ml-playground", "full_name": "octocat/ml-playground",
"language": "Jupyter Notebook", "stargazers_count": 64, "forks_count": 8,
"pushed_at": _recent_iso(14), "topics": ["ml", "pytorch"],
"size": 900,
},
{
"id": 5, "name": "dotfiles", "full_name": "octocat/dotfiles",
"language": "Shell", "stargazers_count": 22, "forks_count": 3,
"pushed_at": _recent_iso(20), "topics": [], "size": 120,
},
{
"id": 6, "name": "rustle", "full_name": "octocat/rustle",
"language": "Rust", "stargazers_count": 48, "forks_count": 5,
"pushed_at": _recent_iso(30), "topics": ["systems", "cli"], "size": 450,
},
{
"id": 7, "name": "web-playground", "full_name": "octocat/web-playground",
"language": "JavaScript", "stargazers_count": 30, "forks_count": 4,
"pushed_at": _recent_iso(40), "topics": ["frontend"], "size": 380,
},
{
"id": 8, "name": "notes-app", "full_name": "octocat/notes-app",
"language": "TypeScript", "stargazers_count": 15, "forks_count": 2,
"pushed_at": _recent_iso(55), "topics": ["frontend"], "size": 260,
},
],
"events": [
{"type": "PushEvent", "created_at": _recent_iso(1),
"actor": {"login": "octocat"}, "repo": {"name": "octocat/stellar-api"},
"payload": {"commits": [{"sha": "abc"}, {"sha": "def"}]}},
{"type": "PullRequestEvent", "created_at": _recent_iso(2),
"actor": {"login": "octocat"}, "repo": {"name": "octocat/pixel-ui"},
"payload": {}},
{"type": "PushEvent", "created_at": _recent_iso(4),
"actor": {"login": "octocat"}, "repo": {"name": "octocat/nimbus-infra"},
"payload": {"commits": [{"sha": "ghi"}]}},
],
"commits": _daily_commits(),
"total_commits": 2450,
"recent_commits": 680,
"total_prs": 180,
"collaborators_data": [
{
"login": "alice-dev", "avatar_url": "",
"raw_score": 220.0, "shared_repos": 3, "final_score": 660.0,
"repos": ["octocat/stellar-api", "octocat/pixel-ui", "octocat/nimbus-infra"],
"tight_owned_partner": True,
},
{
"login": "bob-builder", "avatar_url": "",
"raw_score": 140.0, "shared_repos": 2, "final_score": 280.0,
"repos": ["octocat/stellar-api", "octocat/ml-playground"],
"tight_owned_partner": False,
},
{
"login": "carol-codes", "avatar_url": "",
"raw_score": 95.0, "shared_repos": 2, "final_score": 190.0,
"repos": ["octocat/pixel-ui", "octocat/web-playground"],
"tight_owned_partner": False,
},
],
"avatar_b64": "",
}
+135
View File
@@ -0,0 +1,135 @@
"""SQLite repository: the only communication channel between fetcher and generator.
Stores each user's fetched GitHub payload as a JSON blob in a single table.
The generator reads from here; the fetcher writes to here. Neither imports the
other.
"""
import json
import os
import sqlite3
from datetime import datetime
from typing import Optional
_PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
DB_PATH = os.environ.get(
"GHSTATS_DB_PATH",
os.path.join(_PROJECT_ROOT, "data", "ghstats.db"),
)
DUMMY_USERNAME = "__dummy__"
# Fields the generator considers load-bearing. If any is missing from a row,
# the generator treats the row as unusable and falls back to the dummy user.
REQUIRED_FIELDS = (
"user",
"repos",
"events",
"commits",
"total_commits",
"recent_commits",
"total_prs",
"collaborators_data",
"avatar_b64",
)
SCHEMA_SQL = """
CREATE TABLE IF NOT EXISTS users (
username TEXT PRIMARY KEY,
data_json TEXT NOT NULL,
is_dummy INTEGER NOT NULL DEFAULT 0,
updated_at TEXT NOT NULL
);
"""
def _connect() -> sqlite3.Connection:
os.makedirs(os.path.dirname(DB_PATH), exist_ok=True)
conn = sqlite3.connect(DB_PATH)
conn.row_factory = sqlite3.Row
return conn
def init_db() -> None:
"""Create the schema and seed the dummy user if missing."""
with _connect() as conn:
conn.executescript(SCHEMA_SQL)
conn.commit()
seed_dummy_user(conn=conn)
def upsert_user(username: str, data: dict, conn: Optional[sqlite3.Connection] = None) -> None:
payload = json.dumps(data)
now = datetime.utcnow().isoformat(timespec="seconds") + "Z"
sql = """
INSERT INTO users (username, data_json, is_dummy, updated_at)
VALUES (?, ?, 0, ?)
ON CONFLICT(username) DO UPDATE SET
data_json = excluded.data_json,
is_dummy = 0,
updated_at = excluded.updated_at
"""
if conn is None:
with _connect() as c:
c.execute(sql, (username, payload, now))
c.commit()
else:
conn.execute(sql, (username, payload, now))
conn.commit()
def get_user(username: str) -> Optional[dict]:
"""Return the stored GitHub-data dict for a user, or None if not present."""
with _connect() as conn:
row = conn.execute(
"SELECT data_json FROM users WHERE username = ?",
(username,),
).fetchone()
if row is None:
return None
return json.loads(row["data_json"])
def delete_user(username: str) -> bool:
if username == DUMMY_USERNAME:
return False
with _connect() as conn:
cur = conn.execute("DELETE FROM users WHERE username = ?", (username,))
conn.commit()
return cur.rowcount > 0
def list_users() -> list[dict]:
with _connect() as conn:
rows = conn.execute(
"SELECT username, is_dummy, updated_at FROM users ORDER BY username"
).fetchall()
return [dict(r) for r in rows]
def seed_dummy_user(conn: Optional[sqlite3.Connection] = None) -> None:
"""Insert (or replace) the __dummy__ row using an explicit hand-written payload.
This is the fallback the generator uses whenever a requested user is missing
or has incomplete data. Kept deliberately plausible so every widget has
something to render.
"""
from .dummy_seed import DUMMY_PAYLOAD
payload = json.dumps(DUMMY_PAYLOAD)
now = datetime.utcnow().isoformat(timespec="seconds") + "Z"
sql = """
INSERT INTO users (username, data_json, is_dummy, updated_at)
VALUES (?, ?, 1, ?)
ON CONFLICT(username) DO UPDATE SET
data_json = excluded.data_json,
is_dummy = 1,
updated_at = excluded.updated_at
"""
if conn is None:
with _connect() as c:
c.execute(sql, (DUMMY_USERNAME, payload, now))
c.commit()
else:
conn.execute(sql, (DUMMY_USERNAME, payload, now))
conn.commit()
+78
View File
@@ -0,0 +1,78 @@
"""Flask API for the fetcher service.
Pulls data from the GitHub API and writes it to the shared SQLite database.
Does not render anything. Runs independently from the generator.
python -m src.fetcher_api # serves on :5001
Endpoints:
GET /health
POST /fetch {username, token?} -> fetches + upserts
GET /users -> list stored usernames
GET /users/<username> -> full stored payload
"""
import os
from flask import Flask, jsonify, request
from .data.fetcher import fetch_github_data
from .db import init_db, upsert_user, get_user, list_users, DUMMY_USERNAME
app = Flask(__name__)
@app.route("/health", methods=["GET"])
def health():
return jsonify({"status": "ok", "service": "fetcher"})
@app.route("/fetch", methods=["POST"])
def fetch():
body = request.get_json(silent=True) or {}
username = body.get("username")
if not username:
return jsonify({"error": "username is required"}), 400
if username == DUMMY_USERNAME:
return jsonify({"error": "cannot overwrite dummy user"}), 400
token = body.get("token") or os.environ.get("GITHUB_PAT")
try:
data = fetch_github_data(username, token)
except Exception as e:
return jsonify({"error": f"fetch failed: {e}"}), 502
if not data.get("user") or data["user"].get("message") == "Not Found":
return jsonify({"error": f"github user '{username}' not found"}), 404
upsert_user(username, data)
return jsonify({
"username": username,
"stored": True,
"total_commits": data.get("total_commits", 0),
"repos": len(data.get("repos", [])),
})
@app.route("/users", methods=["GET"])
def users_list():
return jsonify(list_users())
@app.route("/users/<username>", methods=["GET"])
def users_get(username: str):
data = get_user(username)
if data is None:
return jsonify({"error": "not found"}), 404
return jsonify(data)
def main():
init_db()
port = int(os.environ.get("FETCHER_PORT", "5001"))
app.run(host="0.0.0.0", port=port, debug=False)
if __name__ == "__main__":
main()
+2 -1
View File
@@ -9,7 +9,8 @@ import os
from typing import Optional from typing import Optional
from .models import AchievementData from .models import AchievementData
from .data import fetch_github_data, generate_widgets_from_github from .data.fetcher import fetch_github_data
from .data.processor import generate_widgets_from_github
from .widgets import render_achievements_widget, compose_widget from .widgets import render_achievements_widget, compose_widget
+102
View File
@@ -0,0 +1,102 @@
"""Flask API for the generator service.
Reads previously-fetched data from the shared SQLite database and renders
SVG widgets. Never calls the fetcher — if the requested user is missing or
has incomplete data, it falls back to the __dummy__ user seeded in the DB.
python -m src.generator_api # serves on :5002
Endpoints:
GET /health
POST /generate {username, theme?, widgets?, widget_order?,
custom_tags?, hidden_languages?, format?}
-> SVG string (format=svg, default) or
JSON {widgets: {...}, composite, used_dummy}
"""
import os
from flask import Flask, jsonify, request, Response
from .db import init_db, get_user, DUMMY_USERNAME, REQUIRED_FIELDS
from .data.processor import generate_widgets_from_github
from .widgets import compose_widget
from .config import ENABLED_WIDGETS, WIDGET_ORDER
app = Flask(__name__)
def _load_with_fallback(username: str) -> tuple[dict, bool]:
"""Return (github_data, used_dummy).
If the row is missing or is missing any REQUIRED_FIELDS, swap in the dummy
payload wholesale (no partial merging).
"""
data = get_user(username)
if data is None or any(f not in data for f in REQUIRED_FIELDS):
dummy = get_user(DUMMY_USERNAME)
if dummy is None:
raise RuntimeError("dummy user missing from database; run init_db")
return dummy, True
return data, False
@app.route("/health", methods=["GET"])
def health():
return jsonify({"status": "ok", "service": "generator"})
@app.route("/generate", methods=["POST"])
def generate():
body = request.get_json(silent=True) or {}
username = body.get("username")
if not username:
return jsonify({"error": "username is required"}), 400
theme = body.get("theme", "dark")
enabled = body.get("widgets") or ENABLED_WIDGETS
widget_order = body.get("widget_order") or WIDGET_ORDER
custom_tags = body.get("custom_tags")
hidden_languages = body.get("hidden_languages")
fmt = body.get("format", "svg")
github_data, used_dummy = _load_with_fallback(username)
widgets = generate_widgets_from_github(
github_data,
theme=theme,
custom_tags=custom_tags,
hidden_languages=hidden_languages,
enabled=enabled,
)
ordered = [w for w in widget_order if w in enabled and w in widgets and widgets[w]]
display_name = username if not used_dummy else username
composite = compose_widget(
widgets=widgets,
enabled=ordered,
theme_name=theme,
username=display_name,
avatar_b64=github_data.get("avatar_b64", ""),
)
if fmt == "json":
return jsonify({
"username": username,
"used_dummy": used_dummy,
"widgets": widgets,
"composite": composite,
})
headers = {"X-Used-Dummy": "1" if used_dummy else "0"}
return Response(composite, mimetype="image/svg+xml", headers=headers)
def main():
init_db()
port = int(os.environ.get("GENERATOR_PORT", "5002"))
app.run(host="0.0.0.0", port=port, debug=False)
if __name__ == "__main__":
main()