Code Issues Pull Requests Actions Packages Projects Releases 15 Wiki Activity Security Code Quality

Enhance Gitea badges workflow with cache support and additional parameters; update badge awarding script for improved error handling and S3 integration; modify badges.json to adjust worker count and document cache usage in README
Gitea badges / award (push) Canceled after 43s

This commit is contained in:
tienbh committed 2026-11-19 11:59:20 +07:00
1 parent ec8522633b
commit 243eea2aa3
5 files changed
+419 -47

No files matched your search

+286 -43
View File
@@ -9,13 +9,26 @@ Env:
GITEA_URL e.g. https://git.sothink.vn
BADGE_TOKEN site-admin PAT (scopes: read:repository, read:issue, read:user, write:admin)
DRY_RUN "true" -> only print the plan, do not change badges
Optional cache on S3 (RustFS). Facts about closed PRs/issues are stored so each run
only calls the API for PRs/issues that are new or changed since the last run:
CACHE_S3_ENDPOINT e.g. https://rustfs.sothink.vn
CACHE_S3_BUCKET bucket name
CACHE_S3_KEY object key (default: gitea-badges/cache.json.gz)
CACHE_S3_REGION default: us-east-1
AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY
CACHE_REBUILD "true" -> ignore the stored cache, rescan everything, save fresh
Without CACHE_S3_ENDPOINT/BUCKET/keys the script runs a full scan (no cache).
"""
import argparse
import http.client
import json
import os
import re
import socket
import sys
import threading
import time
import urllib.error
import urllib.parse
import urllib.request
@@ -23,17 +36,36 @@ from collections import Counter, defaultdict
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime
from s3cache import S3Object
PAGE = 50
CACHE_VERSION = 3
COAUTHOR_RE = re.compile(r"^\s*co-authored-by:\s*.*?<([^>]+)>\s*$", re.I | re.M)
# --------------------------------------------------------------------------- API
class ApiError(RuntimeError):
def __init__(self, msg, code=None):
super().__init__(msg)
self.code = code
class Gitea:
def __init__(self, url, token):
RETRY_CODES = {429, 500, 502, 503, 504}
def __init__(self, url, token, timeout=120, retries=3, slow=15):
self.base = url.rstrip("/") + "/api/v1"
self.token = token
self.timeout = timeout
self.retries = retries
self.slow = slow # log requests slower than this (seconds)
self.timings = [] # (seconds, "GET /path?query", outcome)
self.requests = 0
self._lock = threading.Lock()
def call(self, method, path, params=None, body=None):
with self._lock:
self.requests += 1
url = self.base + path
if params:
url += "?" + urllib.parse.urlencode(params)
@@ -43,13 +75,39 @@ class Gitea:
req.add_header("Accept", "application/json")
if data is not None:
req.add_header("Content-Type", "application/json")
try:
with urllib.request.urlopen(req, timeout=60) as r:
raw = r.read()
return json.loads(raw) if raw else None
except urllib.error.HTTPError as e:
msg = e.read().decode(errors="replace")[:300]
raise RuntimeError(f"{method} {path} -> HTTP {e.code}: {msg}") from None
label = f"{method} {path}" + (f"?{urllib.parse.urlencode(params)}" if params else "")
for attempt in range(1, self.retries + 1):
t = time.monotonic()
outcome = "ok"
try:
with urllib.request.urlopen(req, timeout=self.timeout) as r:
raw = r.read()
return json.loads(raw) if raw else None
except urllib.error.HTTPError as e:
outcome = f"HTTP {e.code}"
msg = e.read().decode(errors="replace")[:300]
err = ApiError(f"{method} {path} -> HTTP {e.code}: {msg}", e.code)
if e.code not in self.RETRY_CODES or method != "GET":
raise err from None
except (OSError, http.client.HTTPException) as e: # timeouts, resets, URLError
outcome = f"{type(e).__name__}: {e}"
read_timeout = isinstance(e, socket.timeout) and getattr(e, "errno", None) is None
err = ApiError(f"{label} -> {type(e).__name__}: {e} "
f"(after {time.monotonic() - t:.0f}s, attempt {attempt}/{self.retries})",
"timeout" if read_timeout else None)
if method != "GET" or read_timeout:
raise err from None
finally:
dt = time.monotonic() - t
with self._lock:
self.timings.append((dt, label, outcome))
if dt >= self.slow:
print(f"slow: {dt:6.1f}s {outcome:<10.40} {label}", flush=True)
if attempt < self.retries:
time.sleep(2 * attempt)
with self._lock:
self.requests += 1
raise err
def get(self, path, **params):
return self.call("GET", path, params)
@@ -80,57 +138,154 @@ class Stats:
self.coauthored = Counter() # login -> co-authored commits on merged PRs
self.yolo = set() # merged a PR without an approving review
self.quickdraw = set() # closed an issue/PR within N seconds of opening
self.cache_hits = 0 # merged/quick PRs + quick issues served from cache
self.cache_misses = 0
self.skipped = set() # "owner/repo (pulls|issues: HTTP 404)"
self.partial = [] # per-PR fetch failures (data retried next run)
def closer_of(api, owner, repo, number, fallback):
"""Who closed/merged the issue/PR (from timeline); fallback to the poster."""
def timeline_of(api, owner, repo, number):
"""(closer, merger) from the issue/PR timeline — DB only, no git work.
"" when the event is absent, None on API error."""
try:
last = None
closer = merger = ""
for ev in api.paged(f"/repos/{owner}/{repo}/issues/{number}/timeline"):
if ev.get("type") in ("close", "merge_pull") and ev.get("user"):
last = ev["user"]["login"]
return last or fallback
login = (ev.get("user") or {}).get("login")
if not login:
continue
if ev.get("type") in ("close", "merge_pull"):
closer = login
if ev.get("type") == "merge_pull":
merger = login
return closer, merger
except RuntimeError:
return fallback
return None, None
def scan_repo(api, repo, cfg, users, email_map, stats):
def scan_repo(api, repo, cfg, users, email_map, stats, old):
"""Scan one repo. `old` is this repo's cache entry from the last run (or None).
Cache entry layout (keys kept short, the file is gzipped JSON):
prs[number] = {"f": [closed_at, merged], "mb": merger, "ok": approved?,
"co": [[emails]...], "q": closer}
issues[number] = {"f": closed_at, "q": closer}
"f" is the fingerprint: if closed_at/merged changed (reopened, re-closed) the entry is
discarded and refetched. Only PRs/issues that are merged or quickdraw-relevant are stored,
and only those still present in the current "closed" listing are written back.
Gitea endpoints that run git (/pulls, /pulls/{n}, /pulls/{n}/commits) can take minutes on
big repos, so: PRs are listed via /issues?type=pulls, merger/closer come from the timeline
(DB only), and only the co-author scan touches /pulls/{n}/commits. A failure on a single PR
is recorded in stats.partial and left out of the cache, so the next run retries just that PR.
A disabled issues/PR unit (HTTP 403/404 on the listing) is skipped, not an error.
"""
owner, name = repo["owner"]["login"], repo["name"]
quick = cfg["quickdraw_seconds"]
scan_co = cfg.get("scan_coauthors", True)
old = old or {}
old_prs, old_iss = old.get("prs", {}), old.get("issues", {})
new_prs, new_iss = {}, {}
local_merged, local_coauth = Counter(), Counter()
local_yolo, local_quick = set(), set()
hits = misses = 0
def is_quick(item):
c, d = ts(item.get("created_at")), ts(item.get("closed_at"))
return c and d and 0 <= (d - c).total_seconds() <= quick
def entry_for(cache, number, fp):
nonlocal hits, misses
e = cache.get(number)
if e is not None and e.get("f") == fp:
hits += 1
return e
misses += 1
return {"f": fp}
partial = []
def soft(number, what, err):
partial.append(f"{repo['full_name']}#{number} {what}: {err}")
def timeline(entry, number, need_merger):
"""Fill entry["q"] / entry["mb"] from the timeline if missing. False on error."""
if "q" in entry and ("mb" in entry or not need_merger):
return True
closer, merger = timeline_of(api, owner, name, number)
if closer is None:
soft(number, "timeline", "API error")
return False
entry["q"] = closer
if need_merger:
entry["mb"] = merger
return True
def listing(kind):
try:
yield from api.paged(f"/repos/{owner}/{name}/issues", state="closed", type=kind)
except ApiError as e:
if e.code in (403, 404): # unit disabled / external tracker
with stats.lock:
stats.skipped.add(f"{repo['full_name']} ({kind}: HTTP {e.code})")
return
raise
# Pull requests
if repo.get("has_pull_requests", True) and not repo.get("mirror"):
for pr in api.paged(f"/repos/{owner}/{name}/pulls", state="closed"):
for pr in listing("pulls"):
meta = pr.get("pull_request") or {}
merged, quickpr = bool(meta.get("merged") or meta.get("merged_at")), is_quick(pr)
if not merged and not quickpr:
continue
num = str(pr["number"])
poster = (pr.get("user") or {}).get("login")
if is_quick(pr):
who = closer_of(api, owner, name, pr["number"], poster)
e = entry_for(old_prs, num, [pr.get("closed_at"), merged])
new_prs[num] = e
n = pr["number"]
have_tl = timeline(e, n, need_merger=merged)
if quickpr:
who = (e.get("q") or poster) if have_tl else poster
if who:
local_quick.add(who)
if not pr.get("merged"):
if not merged:
continue
if poster:
local_merged[poster] += 1
merger = (pr.get("merged_by") or {}).get("login")
if merger and merger not in stats.yolo and merger not in local_yolo:
reviews = api.get(f"/repos/{owner}/{name}/pulls/{pr['number']}/reviews") or []
approved = any(r.get("state") == "APPROVED" and not r.get("dismissed")
for r in reviews)
if not approved:
merger = e.get("mb") or ""
if merger:
if "ok" not in e:
try:
reviews = api.get(f"/repos/{owner}/{name}/pulls/{n}/reviews") or []
e["ok"] = any(r.get("state") == "APPROVED" and not r.get("dismissed")
for r in reviews)
except ApiError as err:
if err.code == 404: # PR unit gone (archived repo)
e["ok"] = True
else:
soft(n, "reviews", err)
if e.get("ok") is False:
local_yolo.add(merger)
if cfg.get("scan_coauthors", True):
for c in api.paged(f"/repos/{owner}/{name}/pulls/{pr['number']}/commits",
stat="false", verification="false", files="false"):
msg = (c.get("commit") or {}).get("message", "")
if scan_co:
if "co" not in e:
try:
co = []
for c in api.paged(f"/repos/{owner}/{name}/pulls/{n}/commits",
stat="false", verification="false", files="false"):
found = COAUTHOR_RE.findall((c.get("commit") or {}).get("message", ""))
if found:
co.append(found)
e["co"] = co
except ApiError as err:
if err.code == 404: # head ref / PR unit gone
e["co"] = []
else:
soft(n, "commits", err)
for emails in e.get("co", []):
seen = set()
for email in COAUTHOR_RE.findall(msg):
for email in emails:
login = resolve_email(email, email_map, users, cfg)
if login and login not in seen:
seen.add(login)
@@ -138,18 +293,27 @@ def scan_repo(api, repo, cfg, users, email_map, stats):
# Issues (Quickdraw)
if repo.get("has_issues", True) and not repo.get("mirror"):
for iss in api.paged(f"/repos/{owner}/{name}/issues", state="closed", type="issues"):
if is_quick(iss):
poster = (iss.get("user") or {}).get("login")
who = closer_of(api, owner, name, iss["number"], poster)
if who:
local_quick.add(who)
for iss in listing("issues"):
if not is_quick(iss):
continue
num = str(iss["number"])
poster = (iss.get("user") or {}).get("login")
e = entry_for(old_iss, num, iss.get("closed_at"))
new_iss[num] = e
who = (e.get("q") or poster) if timeline(e, iss["number"], False) else poster
if who:
local_quick.add(who)
with stats.lock:
stats.merged_prs.update(local_merged)
stats.coauthored.update(local_coauth)
stats.yolo |= local_yolo
stats.quickdraw |= local_quick
stats.cache_hits += hits
stats.cache_misses += misses
stats.partial.extend(partial)
return {"name": repo["full_name"], "prs": new_prs, "issues": new_iss}
def resolve_email(email, email_map, users, cfg):
@@ -199,6 +363,42 @@ def desired_badges(values, families, tier_mode):
return want
def open_cache():
"""S3Object for the cache, or None if not configured."""
env = os.environ.get
endpoint, bucket = env("CACHE_S3_ENDPOINT"), env("CACHE_S3_BUCKET")
ak, sk = env("AWS_ACCESS_KEY_ID"), env("AWS_SECRET_ACCESS_KEY")
if not (endpoint and bucket and ak and sk):
print("cache: disabled (CACHE_S3_ENDPOINT/CACHE_S3_BUCKET/AWS_* not set)")
return None
return S3Object(endpoint, bucket, env("CACHE_S3_KEY") or "gitea-badges/cache.json.gz",
ak, sk, env("CACHE_S3_REGION") or "us-east-1")
def load_cache(store, cfg):
empty = {"version": CACHE_VERSION, "repos": {}}
if store is None:
return empty
if os.environ.get("CACHE_REBUILD", "false").lower() in ("1", "true", "yes"):
print("cache: rebuild requested, ignoring stored cache")
return empty
try:
data = store.load_json()
except Exception as e: # never fail the run because of the cache
print(f"warn: cache load failed ({e}); full scan")
return empty
if data is None:
print(f"cache: {store.label} not found; full scan")
return empty
# Facts depend on these settings; if they change, rebuild.
sig = {"quickdraw_seconds": cfg["quickdraw_seconds"]}
if data.get("version") != CACHE_VERSION or data.get("settings") != sig:
print("cache: version/settings changed; full scan")
return empty
print(f"cache: loaded {len(data.get('repos', {}))} repos from {store.label}")
return data
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--config", required=True)
@@ -206,10 +406,12 @@ def main():
cfg = json.load(open(args.config))
cfg.setdefault("quickdraw_seconds", 300)
t0 = time.monotonic()
url = os.environ.get("GITEA_URL") or sys.exit("GITEA_URL is required")
token = os.environ.get("BADGE_TOKEN") or sys.exit("BADGE_TOKEN is required")
dry = os.environ.get("DRY_RUN", "false").lower() in ("1", "true", "yes")
api = Gitea(url, token)
api = Gitea(url, token, timeout=cfg.get("timeout", 120), retries=cfg.get("retries", 3),
slow=cfg.get("slow_log_seconds", 15))
exclude = {u.lower() for u in cfg.get("exclude_users", [])}
families = cfg["families"]
@@ -240,15 +442,50 @@ def main():
if owner in users and not r.get("fork"):
stats.max_stars[owner] = max(stats.max_stars.get(owner, -1), r.get("stars_count", 0))
store = open_cache()
cache = load_cache(store, cfg)
old_repos = cache.get("repos", {})
new_repos = {}
errors = []
with ThreadPoolExecutor(max_workers=cfg.get("workers", 6)) as pool:
futs = {pool.submit(scan_repo, api, r, cfg, users, email_map, stats): r["full_name"]
futs = {pool.submit(scan_repo, api, r, cfg, users, email_map, stats,
old_repos.get(str(r["id"]))): r
for r in repos}
for f, name in futs.items():
for f, r in futs.items():
rid = str(r["id"])
try:
f.result()
new_repos[rid] = f.result()
except Exception as e: # keep going; report at the end
errors.append(f"{name}: {e}")
errors.append(f"{r['full_name']}: {e}")
if rid in old_repos: # keep last good data for this repo
new_repos[rid] = old_repos[rid]
t_scan = time.monotonic() - t0
print(f"scan: {t_scan:.1f}s, {api.requests} API requests, "
f"cache hits {stats.cache_hits} / misses {stats.cache_misses}")
if stats.partial:
print(f"partial: {len(stats.partial)} PR/issue fetch(es) failed (retried next run):")
for line in stats.partial[:30]:
print(f" {line}")
if len(stats.partial) > 30:
print(f" ... {len(stats.partial) - 30} more")
if stats.skipped:
print("skipped (issues/PR unit disabled or unavailable): " + ", ".join(sorted(stats.skipped)))
top = sorted(api.timings, reverse=True)[:10]
if top and top[0][0] >= 1:
print("slowest requests:")
for dt, label, outcome in top:
print(f" {dt:6.1f}s {outcome:<10.40} {label}")
if store is not None:
try:
size = store.save_json({"version": CACHE_VERSION,
"settings": {"quickdraw_seconds": cfg["quickdraw_seconds"]},
"updated_at": datetime.utcnow().isoformat() + "Z",
"repos": new_repos})
print(f"cache: saved {len(new_repos)} repos ({size} bytes) to {store.label}")
except Exception as e:
print(f"warn: cache save failed ({e})")
# Drop excluded bots from awarded sets (e.g. renovate as merger)
stats.yolo -= exclude
@@ -256,6 +493,11 @@ def main():
# Reconcile
revoke = cfg.get("revoke", True)
if (errors or stats.partial) and revoke:
# Missing data => metrics are undercounted => revoking would remove badges wrongly.
print(f"warn: {len(errors)} repo(s) failed, {len(stats.partial)} partial; "
"skipping revocations this run (adds only)")
revoke = False
tier_mode = cfg.get("tier_mode", "highest")
changes = 0
for login in sorted(users):
@@ -274,7 +516,8 @@ def main():
if rm:
api.call("DELETE", f"/admin/users/{login}/badges", body={"badge_slugs": rm})
print(f"{'[dry-run] ' if dry else ''}users changed: {changes}")
print(f"{'[dry-run] ' if dry else ''}users changed: {changes} "
f"(total {time.monotonic() - t0:.1f}s, {api.requests} API requests)")
if errors:
print("errors:\n " + "\n ".join(errors))
sys.exit(1)