From 243eea2aa397398c8615ba925da48ff79579c449 Mon Sep 17 00:00:00 2001 From: tienbh Date: Thu, 19 Nov 2026 11:59:20 +0700 Subject: [PATCH] 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/workflows/gitea-badges.yaml | 13 +- scripts/gitea-badges/README.md | 45 +++- scripts/gitea-badges/award_badges.py | 329 +++++++++++++++++++++++---- scripts/gitea-badges/badges.json | 2 +- scripts/gitea-badges/s3cache.py | 77 +++++++ 5 files changed, 419 insertions(+), 47 deletions(-) create mode 100644 scripts/gitea-badges/s3cache.py diff --git a/.gitea/workflows/gitea-badges.yaml b/.gitea/workflows/gitea-badges.yaml index 485a0cb..f3851da 100644 --- a/.gitea/workflows/gitea-badges.yaml +++ b/.gitea/workflows/gitea-badges.yaml @@ -9,11 +9,15 @@ on: description: "Chỉ in kế hoạch, không gán/gỡ badge" type: boolean default: false + rebuild_cache: + description: "Bỏ qua cache trên RustFS, quét lại toàn bộ rồi ghi cache mới" + type: boolean + default: false push: branches: [main] paths: - scripts/gitea-badges/** - - .github/workflows/gitea-badges.yaml + - .gitea/workflows/gitea-badges.yaml jobs: award: @@ -28,4 +32,11 @@ jobs: BADGE_TOKEN: ${{ secrets.BADGE_ADMIN_TOKEN }} # push -> dry-run để review thay đổi config; schedule -> chạy thật DRY_RUN: ${{ github.event_name == 'push' && 'true' || github.event.inputs.dry_run || 'false' }} + # Cache trên RustFS — thiếu bucket/key thì script tự chạy full scan + CACHE_S3_ENDPOINT: ${{ vars.CACHE_S3_ENDPOINT || 'https://rustfs.sothink.vn' }} + CACHE_S3_BUCKET: ${{ vars.CACHE_S3_BUCKET }} + CACHE_S3_KEY: gitea-badges/cache.json.gz + AWS_ACCESS_KEY_ID: ${{ secrets.CACHE_S3_ACCESS_KEY }} + AWS_SECRET_ACCESS_KEY: ${{ secrets.CACHE_S3_SECRET_KEY }} + CACHE_REBUILD: ${{ github.event.inputs.rebuild_cache || 'false' }} run: python3 scripts/gitea-badges/award_badges.py --config scripts/gitea-badges/badges.json diff --git a/scripts/gitea-badges/README.md b/scripts/gitea-badges/README.md index 85a1a8e..1b763be 100644 --- a/scripts/gitea-badges/README.md +++ b/scripts/gitea-badges/README.md @@ -1,7 +1,7 @@ # Gitea badges Gán badge cho user trên toàn instance `git.sothink.vn` dựa trên hoạt động ở **mọi repo**. -Workflow `.github/workflows/gitea-badges.yaml` chạy mỗi giờ, quét toàn bộ repo bằng token +Workflow `.gitea/workflows/gitea-badges.yaml` chạy mỗi giờ, quét toàn bộ repo bằng token site-admin, rồi đồng bộ badge qua `POST/DELETE /api/v1/admin/users/{user}/badges`. ## Điều kiện @@ -18,20 +18,61 @@ site-admin, rồi đồng bộ badge qua `POST/DELETE /api/v1/admin/users/{user} `tier_mode: highest` = mỗi nhóm chỉ giữ tier cao nhất (giống GitHub); `all` = giữ cả tier thấp. `revoke: true` = gỡ badge (managed) khi user không còn đủ điều kiện. `exclude_users` = bot (Renovate…) không bao giờ được tính. +`timeout` (mặc định 120s) / `retries` (mặc định 3) = timeout và số lần thử lại cho mỗi request GET +(thử lại khi timeout, lỗi mạng, HTTP 429/5xx). + +**An toàn khi thiếu dữ liệu:** nếu có repo quét lỗi, lần chạy đó **chỉ gán thêm, không gỡ badge** +(metric bị đếm thiếu sẽ làm gỡ oan); job vẫn exit 1 để báo lỗi. Repo tắt Issues/Pull Requests +(API trả 403/404) được bỏ qua, không tính là lỗi. + +Endpoint Gitea phải chạy git (`/pulls`, `/pulls/{n}`, `/pulls/{n}/commits`) có thể mất vài phút ở +repo lớn, nên: PR được liệt kê qua `/issues?type=pulls`, người merge/close lấy từ **timeline** +(chỉ đọc DB), chỉ có bước quét co-author gọi `/pulls/{n}/commits`. Lỗi ở một PR được ghi vào +`partial:` (không fail cả repo, không cache) và lần chạy sau chỉ thử lại đúng PR đó. +Read timeout không được thử lại trong cùng lần chạy (tránh treo worker 2×120s). ## Cài đặt 1. Badge phải có **slug** đúng với giá trị `slug` trong `badges.json` (đang dùng cột Name: `Pull-Shark-Gold`…). 2. Tạo PAT của một tài khoản **site admin** với scope: `read:repository`, `read:issue`, `read:user`, `write:admin`. 3. Thêm secret `BADGE_ADMIN_TOKEN` cho repo này (Settings → Actions → Secrets). -4. (Tuỳ chọn) variable `GITEA_URL` nếu runner phải gọi API qua URL khác `github.server_url`. +4. (Tuỳ chọn) variable `INSTANCE_URL` nếu runner phải gọi API qua URL khác `github.server_url`. 5. Chạy tay *Gitea badges* với `dry_run = true` để xem kế hoạch, rồi để schedule tự chạy. Push thay đổi vào `scripts/gitea-badges/**` sẽ tự chạy ở chế độ dry-run. +## Cache trên RustFS + +Mỗi giờ script phải xét lại toàn bộ PR/issue đã đóng. Để không gọi lại API cho những +PR đã xử lý, kết quả theo từng PR/issue (người close, có approve không, email co-author) +được lưu vào `s3:///gitea-badges/cache.json.gz`. Mỗi lần chạy, script vẫn liệt kê +PR/issue đã đóng (1 request / 50 mục) nhưng **chỉ gọi reviews/commits/timeline cho mục mới +hoặc vừa thay đổi** (mở lại, close lại → `closed_at` đổi → tính lại). + +- Metric luôn được tính lại từ cache + listing, nên đổi `exclude_users`, email, tier… có tác dụng ngay. +- Đổi `quickdraw_seconds` hoặc `CACHE_VERSION` trong script → cache tự bị bỏ, quét lại từ đầu. +- Lỗi đọc/ghi cache chỉ in `warn:`; script vẫn chạy full scan, không fail job. +- Muốn quét lại từ đầu: chạy tay workflow với `rebuild_cache = true`. +- Hạn chế: review bị dismiss **sau khi** PR đã merge sẽ không được phát hiện cho tới khi rebuild. + +Cài đặt: + +1. Tạo bucket (ví dụ `ci-cache`) trên RustFS và access key chỉ có quyền `GetObject`/`PutObject` trên bucket đó. +2. Variable `CACHE_S3_BUCKET` (và `CACHE_S3_ENDPOINT` nếu khác `https://rustfs.sothink.vn`). +3. Secret `CACHE_S3_ACCESS_KEY`, `CACHE_S3_SECRET_KEY`. + +Script dùng path-style URL (`https://rustfs.sothink.vn//`) và SigV4 region `us-east-1` +(đổi bằng `CACHE_S3_REGION`). Log có dòng `scan: …s, N API requests, cache hits … / misses …` để so sánh. + ## Test local ```bash +GITEA_URL=https://git.sothink.vn BADGE_TOKEN=xxx DRY_RUN=true \ + python3 scripts/gitea-badges/award_badges.py --config scripts/gitea-badges/badges.json + +# kèm cache +CACHE_S3_ENDPOINT=https://rustfs.sothink.vn CACHE_S3_BUCKET=ci-cache \ +AWS_ACCESS_KEY_ID=xxx AWS_SECRET_ACCESS_KEY=yyy \ GITEA_URL=https://git.sothink.vn BADGE_TOKEN=xxx DRY_RUN=true \ python3 scripts/gitea-badges/award_badges.py --config scripts/gitea-badges/badges.json ``` diff --git a/scripts/gitea-badges/award_badges.py b/scripts/gitea-badges/award_badges.py index 0f9bfef..7565db9 100644 --- a/scripts/gitea-badges/award_badges.py +++ b/scripts/gitea-badges/award_badges.py @@ -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) diff --git a/scripts/gitea-badges/badges.json b/scripts/gitea-badges/badges.json index a87cb4f..ba2e91d 100644 --- a/scripts/gitea-badges/badges.json +++ b/scripts/gitea-badges/badges.json @@ -3,7 +3,7 @@ "revoke": true, "quickdraw_seconds": 300, "scan_coauthors": true, - "workers": 6, + "workers": 2, "noreply_domain": "noreply.git.sothink.vn", "exclude_users": [ "giteabot", diff --git a/scripts/gitea-badges/s3cache.py b/scripts/gitea-badges/s3cache.py new file mode 100644 index 0000000..a9f22d0 --- /dev/null +++ b/scripts/gitea-badges/s3cache.py @@ -0,0 +1,77 @@ +""" +Tiny S3 client (AWS SigV4, path-style) for a single JSON cache object. +Stdlib only. Tested target: RustFS / MinIO-compatible endpoints. +""" +import datetime +import gzip +import hashlib +import hmac +import json +import urllib.error +import urllib.parse +import urllib.request + + +class S3Object: + def __init__(self, endpoint, bucket, key, access_key, secret_key, region="us-east-1"): + u = urllib.parse.urlsplit(endpoint.rstrip("/")) + self.scheme = u.scheme or "https" + self.host = u.netloc or u.path + parts = [bucket] + [p for p in key.split("/") if p] + self.path = "/" + "/".join(urllib.parse.quote(p, safe="-_.~") for p in parts) + self.access_key, self.secret_key, self.region = access_key, secret_key, region + self.label = f"s3://{bucket}/{key}" + + def _request(self, method, body=b""): + now = datetime.datetime.now(datetime.timezone.utc) + amz_date = now.strftime("%Y%m%dT%H%M%SZ") + day = amz_date[:8] + payload_hash = hashlib.sha256(body).hexdigest() + signed_headers = {"host": self.host, "x-amz-content-sha256": payload_hash, + "x-amz-date": amz_date} + names = sorted(signed_headers) + canonical = "\n".join([ + method, self.path, "", + "".join(f"{k}:{signed_headers[k]}\n" for k in names), + ";".join(names), payload_hash, + ]) + scope = f"{day}/{self.region}/s3/aws4_request" + to_sign = "\n".join(["AWS4-HMAC-SHA256", amz_date, scope, + hashlib.sha256(canonical.encode()).hexdigest()]) + k = ("AWS4" + self.secret_key).encode() + for part in (day, self.region, "s3", "aws4_request"): + k = hmac.new(k, part.encode(), hashlib.sha256).digest() + sig = hmac.new(k, to_sign.encode(), hashlib.sha256).hexdigest() + + req = urllib.request.Request(f"{self.scheme}://{self.host}{self.path}", + data=body if method == "PUT" else None, method=method) + req.add_header("Host", self.host) + req.add_header("x-amz-content-sha256", payload_hash) + req.add_header("x-amz-date", amz_date) + req.add_header("Authorization", + f"AWS4-HMAC-SHA256 Credential={self.access_key}/{scope}, " + f"SignedHeaders={';'.join(names)}, Signature={sig}") + if method == "PUT": + req.add_header("Content-Type", "application/gzip") + with urllib.request.urlopen(req, timeout=60) as r: + return r.read() + + def load_json(self): + """Return the decoded object, or None if it does not exist yet.""" + try: + raw = self._request("GET") + except urllib.error.HTTPError as e: + if e.code == 404: + return None + raise RuntimeError(f"GET {self.label} -> HTTP {e.code}: " + f"{e.read().decode(errors='replace')[:300]}") from None + return json.loads(gzip.decompress(raw)) + + def save_json(self, obj): + body = gzip.compress(json.dumps(obj, separators=(",", ":")).encode()) + try: + self._request("PUT", body) + except urllib.error.HTTPError as e: + raise RuntimeError(f"PUT {self.label} -> HTTP {e.code}: " + f"{e.read().decode(errors='replace')[:300]}") from None + return len(body)