feat(fetcher): move GitHub client into fetcher service

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
shay
2026-04-17 16:30:52 -04:00
co-authored by Claude Sonnet 4.6
parent 15ad9c81aa
commit 1a3caff269
3 changed files with 121 additions and 31 deletions
+15
View File
@@ -8,3 +8,18 @@ INTERNAL_TOKEN = os.getenv("FETCHER_INTERNAL_TOKEN", "")
REFRESH_INTERVAL_HOURS = int(os.getenv("FETCHER_REFRESH_INTERVAL_HOURS", "24")) REFRESH_INTERVAL_HOURS = int(os.getenv("FETCHER_REFRESH_INTERVAL_HOURS", "24"))
TRIAL_GC_DAYS = int(os.getenv("FETCHER_TRIAL_GC_DAYS", "7")) TRIAL_GC_DAYS = int(os.getenv("FETCHER_TRIAL_GC_DAYS", "7"))
API_TIMEOUT = int(os.getenv("API_TIMEOUT", "15")) API_TIMEOUT = int(os.getenv("API_TIMEOUT", "15"))
# 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"))
SMALL_OWNED_REPO_SIZE = int(os.getenv("SMALL_OWNED_REPO_SIZE", "10"))
COLLABORATOR_LOOKBACK_DAYS = int(os.getenv("COLLABORATOR_LOOKBACK_DAYS", "365"))
MEANINGFUL_MIN_COMMITS = int(os.getenv("MEANINGFUL_MIN_COMMITS", "3"))
FORK_MIN_COMMITS = int(os.getenv("FORK_MIN_COMMITS", "10"))
OWNER_BOOST = float(os.getenv("OWNER_BOOST", "1.5"))
MIN_SHARED_REPOS = int(os.getenv("MIN_SHARED_REPOS", "2"))
DEEP_COLLAB_THRESHOLD = int(os.getenv("DEEP_COLLAB_THRESHOLD", "25"))
# Commit-fetching caps
COMMIT_MAX_REPOS = int(os.getenv("COMMIT_MAX_REPOS", "10"))
COMMIT_PER_REPO = int(os.getenv("COMMIT_PER_REPO", "30"))
+18 -31
View File
@@ -4,20 +4,7 @@ import requests
import base64 import base64
from typing import Optional, Protocol from typing import Optional, Protocol
from ..config import ( from . import config
COLLABORATOR_MAX_REPO_SIZE,
COLLABORATOR_TOP_REPOS,
COLLABORATOR_LOOKBACK_DAYS,
MEANINGFUL_MIN_COMMITS,
FORK_MIN_COMMITS,
OWNER_BOOST,
MIN_SHARED_REPOS,
DEEP_COLLAB_THRESHOLD,
SMALL_OWNED_REPO_SIZE,
COMMIT_MAX_REPOS,
COMMIT_PER_REPO,
API_TIMEOUT,
)
class GitHubDataSource(Protocol): class GitHubDataSource(Protocol):
@@ -91,7 +78,7 @@ class DirectAPISource:
"https://api.github.com/graphql", "https://api.github.com/graphql",
json=payload, json=payload,
headers=headers, headers=headers,
timeout=API_TIMEOUT, timeout=config.API_TIMEOUT,
) )
except Exception as e: except Exception as e:
print(f" GraphQL request failed: {e}") print(f" GraphQL request failed: {e}")
@@ -203,7 +190,7 @@ class DirectAPISource:
'https://api.github.com/graphql', 'https://api.github.com/graphql',
json={'query': query}, json={'query': query},
headers=headers, headers=headers,
timeout=API_TIMEOUT timeout=config.API_TIMEOUT
) )
if not resp.ok: if not resp.ok:
@@ -287,7 +274,7 @@ class DirectAPISource:
'https://api.github.com/graphql', 'https://api.github.com/graphql',
json={'query': query, 'variables': {'username': username}}, json={'query': query, 'variables': {'username': username}},
headers=headers, headers=headers,
timeout=API_TIMEOUT timeout=config.API_TIMEOUT
) )
if not resp.ok or 'data' not in resp.json(): if not resp.ok or 'data' not in resp.json():
@@ -322,7 +309,7 @@ class DirectAPISource:
'https://api.github.com/graphql', 'https://api.github.com/graphql',
json={'query': year_query}, json={'query': year_query},
headers=headers, headers=headers,
timeout=API_TIMEOUT timeout=config.API_TIMEOUT
) )
if year_resp.ok: if year_resp.ok:
@@ -371,7 +358,7 @@ class DirectAPISource:
'https://api.github.com/graphql', 'https://api.github.com/graphql',
json={'query': query}, json={'query': query},
headers=headers, headers=headers,
timeout=API_TIMEOUT timeout=config.API_TIMEOUT
) )
if resp.ok: if resp.ok:
@@ -401,7 +388,7 @@ class DirectAPISource:
f"{self.base}/search/issues", f"{self.base}/search/issues",
headers=self.headers, headers=self.headers,
params={"q": query, "per_page": 1}, params={"q": query, "per_page": 1},
timeout=API_TIMEOUT timeout=config.API_TIMEOUT
) )
if resp.ok: if resp.ok:
@@ -428,7 +415,7 @@ class DirectAPISource:
f"{self.base}/repos/{repo_name}/contributors", f"{self.base}/repos/{repo_name}/contributors",
headers=self.headers, headers=self.headers,
params={"per_page": 100}, params={"per_page": 100},
timeout=API_TIMEOUT timeout=config.API_TIMEOUT
) )
if resp.ok: if resp.ok:
@@ -508,7 +495,7 @@ class DirectAPISource:
def fetch_avatar(self, avatar_url: str) -> str: def fetch_avatar(self, avatar_url: str) -> str:
"""Fetch and encode avatar as base64.""" """Fetch and encode avatar as base64."""
try: try:
resp = requests.get(avatar_url + "&s=64", timeout=API_TIMEOUT) resp = requests.get(avatar_url + "&s=64", timeout=config.API_TIMEOUT)
if resp.ok: if resp.ok:
return base64.b64encode(resp.content).decode("ascii") return base64.b64encode(resp.content).decode("ascii")
except Exception: except Exception:
@@ -627,7 +614,7 @@ def _fetch_collaborators_data(
low = login.lower() low = login.lower()
return low in BOT_LOGINS or low.endswith("[bot]") or low.endswith("-bot") return low in BOT_LOGINS or low.endswith("[bot]") or low.endswith("-bot")
since = (datetime.now() - timedelta(days=COLLABORATOR_LOOKBACK_DAYS)).strftime("%Y-%m-%d") since = (datetime.now() - timedelta(days=config.COLLABORATOR_LOOKBACK_DAYS)).strftime("%Y-%m-%d")
commit_repos = source.fetch_user_commit_repos(username, since) commit_repos = source.fetch_user_commit_repos(username, since)
if not commit_repos: if not commit_repos:
return [] return []
@@ -636,15 +623,15 @@ def _fetch_collaborators_data(
qualifying = [] qualifying = []
for r in commit_repos: for r in commit_repos:
user_commits = r.get("user_commits", 0) user_commits = r.get("user_commits", 0)
if user_commits < MEANINGFUL_MIN_COMMITS: if user_commits < config.MEANINGFUL_MIN_COMMITS:
continue continue
if r.get("is_fork") and user_commits < FORK_MIN_COMMITS: if r.get("is_fork") and user_commits < config.FORK_MIN_COMMITS:
continue continue
qualifying.append(r) qualifying.append(r)
# Rank user's repos by their own commit count, scan top N # Rank user's repos by their own commit count, scan top N
qualifying.sort(key=lambda r: -r.get("user_commits", 0)) qualifying.sort(key=lambda r: -r.get("user_commits", 0))
qualifying = qualifying[:COLLABORATOR_TOP_REPOS] qualifying = qualifying[:config.COLLABORATOR_TOP_REPOS]
print(f" Scoring collaborators across {len(qualifying)} qualifying repos") print(f" Scoring collaborators across {len(qualifying)} qualifying repos")
# Step 3+4: fetch contributors and score # Step 3+4: fetch contributors and score
@@ -652,17 +639,17 @@ def _fetch_collaborators_data(
for r in qualifying: for r in qualifying:
full_name = r["full_name"] full_name = r["full_name"]
user_commits = r["user_commits"] user_commits = r["user_commits"]
boost = OWNER_BOOST if r["is_owner"] else 1.0 boost = config.OWNER_BOOST if r["is_owner"] else 1.0
contributors = source.fetch_repo_contributors(full_name, min_commits=1) contributors = source.fetch_repo_contributors(full_name, min_commits=1)
# Drop huge OSS projects # Drop huge OSS projects
if len(contributors) >= COLLABORATOR_MAX_REPO_SIZE: if len(contributors) >= config.COLLABORATOR_MAX_REPO_SIZE:
print(f" skipping {full_name}: too many contributors ({len(contributors)})") print(f" skipping {full_name}: too many contributors ({len(contributors)})")
continue continue
# A "tight" repo: one the user owns with few contributors — hackathon # A "tight" repo: one the user owns with few contributors — hackathon
# and side-project partners qualify from a single such repo. # and side-project partners qualify from a single such repo.
is_tight_owned = r["is_owner"] and len(contributors) <= SMALL_OWNED_REPO_SIZE is_tight_owned = r["is_owner"] and len(contributors) <= config.SMALL_OWNED_REPO_SIZE
for c in contributors: for c in contributors:
login = c.get("login", "") login = c.get("login", "")
@@ -705,8 +692,8 @@ def _fetch_collaborators_data(
# or a partner in a tight user-owned project (hackathon/side-project). # or a partner in a tight user-owned project (hackathon/side-project).
filtered = [ filtered = [
s for s in scored s for s in scored
if s["shared_repos"] >= MIN_SHARED_REPOS if s["shared_repos"] >= config.MIN_SHARED_REPOS
or s["raw_score"] >= DEEP_COLLAB_THRESHOLD or s["raw_score"] >= config.DEEP_COLLAB_THRESHOLD
or s["tight_owned_partner"] or s["tight_owned_partner"]
] ]
+88
View File
@@ -0,0 +1,88 @@
import responses
import pytest
from src import github
@responses.activate
def test_fetch_user_data_returns_user_payload():
# fetch_commits: contributionCalendar/weeks
responses.add(
responses.POST, "https://api.github.com/graphql",
json={"data": {"user": {"contributionsCollection": {"contributionCalendar": {"weeks": []}}}}},
status=200,
)
# fetch_commit_count (alltime) — first call: get createdAt
responses.add(
responses.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)
for _ in range(7):
responses.add(
responses.POST, "https://api.github.com/graphql",
json={"data": {"user": {"contributionsCollection": {"contributionCalendar": {"totalContributions": 10}}}}},
status=200,
)
# fetch_commit_count (recent, last 6 months)
responses.add(
responses.POST, "https://api.github.com/graphql",
json={"data": {"user": {"contributionsCollection": {"contributionCalendar": {"totalContributions": 5}}}}},
status=200,
)
# fetch_user_commit_repos (for collaborators)
responses.add(
responses.POST, "https://api.github.com/graphql",
json={"data": {"user": {"contributionsCollection": {"commitContributionsByRepository": []}}}},
status=200,
)
# PR count search
responses.add(
responses.GET, "https://api.github.com/search/issues",
json={"total_count": 0, "items": []},
status=200,
)
responses.add(
responses.GET, "https://api.github.com/users/alice",
json={"login": "alice", "public_repos": 3, "followers": 5, "avatar_url": "https://avatars.example/1"},
status=200,
)
# fetch_repos: two calls (owner + all)
responses.add(
responses.GET, "https://api.github.com/users/alice/repos",
json=[], status=200,
)
responses.add(
responses.GET, "https://api.github.com/users/alice/repos",
json=[], status=200,
)
responses.add(
responses.GET, "https://api.github.com/users/alice/events",
json=[], status=200,
)
data = github.fetch_github_data("alice", token="t")
assert data["user"]["login"] == "alice"
assert "repos" in data
assert "events" in data
@responses.activate
def test_fetch_handles_404():
responses.add(
responses.GET, "https://api.github.com/users/nope",
json={"message": "Not Found"}, status=404,
)
responses.add(
responses.POST, "https://api.github.com/graphql",
json={"data": {"user": None}}, status=200,
)
responses.add(
responses.GET, "https://api.github.com/users/nope/repos",
json={"message": "Not Found"}, status=404,
)
responses.add(
responses.GET, "https://api.github.com/users/nope/events",
json={"message": "Not Found"}, status=404,
)
data = github.fetch_github_data("nope", token="t")
assert data["user"].get("message") == "Not Found" or data["user"] is None