diff --git a/README.md b/README.md index bcc2424..79a5c55 100644 --- a/README.md +++ b/README.md @@ -152,7 +152,8 @@ authors' profile pictures. Nothing to configure: `GH_TOKEN` or a logged-in `gh` CLI is already there, it is used, which also covers private repositories). - GitLab: GitLab is asked who wrote each author's commit, so the commit email is matched - against all of the user's verified emails, like on GitLab's own pages. Public projects need + against all of the user's verified emails, like on GitLab's own pages. The commit asked about + is the author's newest *pushed* commit (GitLab can't know local-only commits). Public projects need nothing. **Private projects need a token** (an SSH key is not enough: it only works for git, not for GitLab's API): `GITLAB_TOKEN` with the `read_api` scope, or a `glab auth login` for that server, are used when already there (`GITLAB_TOKEN` only when `GITLAB_HOST` is unset or @@ -160,7 +161,8 @@ authors' profile pictures. Nothing to configure: finds authors whose *public email* in their GitLab profile is the one they commit with. Pictures that GitLab would take from Gravatar are ignored; only pictures uploaded to the GitLab instance are shown. -- Other hosts, no picture, offline, rate limits: the coloured initials. No other service is +- Other hosts, no picture, offline, rate limits: the coloured initials (when the host could not + be reached, the page asks again a couple of minutes later). No other service is ever contacted, and the page itself never talks to the internet (pictures go through the local server). - Pictures are cached for 7 days ("no picture" for 1 day, but asked again at once after you diff --git a/TESTING.md b/TESTING.md index 979d6ad..316b259 100644 --- a/TESTING.md +++ b/TESTING.md @@ -165,6 +165,16 @@ Originally reported by the user on Windows (fixed on macOS, verified above): before the login; those are now asked again (`avatars.LOOKUP_VERSION`, `auth` in the cache metadata). + **Still initials with 1.1.1 (2026/11/27, fixed in 1.1.2):** the page asks once per author, + with the author's *newest* commit in the graph. That is often a local-only commit or merge + GitLab does not know, so GitLab answered nothing and only the public-email lookup was left. + A slow GraphQL answer (> 6 s; a cold first lookup measured 5 s) or a 5xx/429 was treated as + "offline": nothing cached, and the page never asked again. Now: the commit asked about is the + author's newest pushed non-merge commit (`git log --remotes --no-merges --author=`, + ~70 ms), then the shown one; GraphQL gets 15 s and any failure falls back to the email + lookup; network trouble answers `503` + `Retry-After` and the page asks again (3 tries). + `LOOKUP_VERSION` 3 re-asks the misses cached by 1.1.1. + **Launch page (2026/11/27):** a cold Chromium start takes ~2-3 s on Windows, during which the private launch page is visible; it used to be a bare "Open gitgraph" link. It now shows the logo and "Opening …" in the app's colours and forwards with `location.replace` (meta diff --git a/src/gitgraph/__init__.py b/src/gitgraph/__init__.py index 90faa6b..17d955d 100644 --- a/src/gitgraph/__init__.py +++ b/src/gitgraph/__init__.py @@ -1,3 +1,3 @@ """gitgraph - interactive, GitLab-style commit graph for any git repository.""" -__version__ = "1.1.1" +__version__ = "1.1.2" diff --git a/src/gitgraph/avatars.py b/src/gitgraph/avatars.py index 90f8987..1076116 100644 --- a/src/gitgraph/avatars.py +++ b/src/gitgraph/avatars.py @@ -7,9 +7,10 @@ * GitLab (gitlab.com or self-hosted): GitLab is asked who wrote the commit (GraphQL), which matches the commit email against all of a user's verified emails, like GitLab's own pages. Private projects need a token the user - already has (``GITLAB_TOKEN`` or a ``glab auth login`` for that server). If - the project is not visible, the ``/api/v4/avatar`` lookup is used, which - only knows public profile emails. Gravatar answers are ignored: only + already has (``GITLAB_TOKEN`` or a ``glab auth login`` for that server). + The commit asked about is the author's newest pushed non-merge commit + (GitLab cannot know local-only commits). If GitLab cannot answer, the + ``/api/v4/avatar`` lookup is used, which only knows public profile emails. Gravatar answers are ignored: only pictures people uploaded to the host. Nothing else is ever contacted: other hosts and failures (offline, private @@ -42,11 +43,13 @@ MISS_TTL_S = 24 * 3600 # Bumped when lookups find more pictures than before: "no picture" answers of older # versions are then asked again instead of being trusted for MISS_TTL_S. -LOOKUP_VERSION = 2 +LOOKUP_VERSION = 3 MAX_BYTES = 512 * 1024 # one picture CACHE_MAX_BYTES = 20 * 1024 * 1024 # whole avatar cache on disk (least recently used go first) SESSION_MAX_LOOKUPS = 300 # network lookups per gitgraph run, however many authors a repo has TIMEOUT_S = 6.0 +GRAPHQL_TIMEOUT_S = 15.0 # GitLab resolves the commit through Gitaly: slower on big repositories +RETRY_S = 120.0 # after network trouble, ask again this much later (not remembered on disk) IMAGE_TYPES = {"image/png", "image/jpeg", "image/gif", "image/webp"} # no SVG _USER_AGENT = "gitgraph/%s (+https://github.com/edoardopanichi/gitgraph)" % __version__ _NOREPLY = re.compile(r"^(?:(\d+)\+)?([A-Za-z0-9-]+)@users\.noreply\.github\.com$", re.I) @@ -159,10 +162,12 @@ class AvatarService: """Looks up and caches author pictures. Thread-safe; ``get`` may block on the network.""" def __init__(self, host: Dict[str, str], cache_dir: str, token: Optional[str] = None, - opener=None) -> None: + opener=None, repo: Optional[str] = None) -> None: """``token``: None finds one the user already has (env, gh/glab login) on first use; - "" means no token.""" + "" means no token. ``repo``: the local repository, used to pick a pushed commit + of the author for GitLab.""" self.host = host + self.repo = repo self.cache_dir = os.path.join(cache_dir, "avatars") self._token = token self._token_checked = token is not None @@ -269,10 +274,10 @@ def prune(self) -> None: # ---- network ------------------------------------------------------- def _request(self, url: str, headers: Optional[Dict[str, str]] = None, max_bytes: int = MAX_BYTES, - body: Optional[bytes] = None): + body: Optional[bytes] = None, timeout_s: float = TIMEOUT_S): req = urllib.request.Request(url, data=body, headers=dict({"User-Agent": _USER_AGENT}, **(headers or {}))) with self._net: - with self._open(req, timeout=TIMEOUT_S) as res: + with self._open(req, timeout=timeout_s) as res: data = res.read(max_bytes + 1) if len(data) > max_bytes: raise ValueError("response too large") @@ -338,17 +343,20 @@ def _gitlab_commit_author(self, email: str, sha: str) -> Tuple[bool, Optional[st "variables": {"project": self.host["path"], "sha": sha}}).encode("utf-8") headers = dict({"Content-Type": "application/json", "Accept": "application/json"}, **self._auth(url)) try: - data, _, _ = self._request(url, headers, max_bytes=64 * 1024, body=body) + data, _, _ = self._request(url, headers, max_bytes=64 * 1024, body=body, timeout_s=GRAPHQL_TIMEOUT_S) + answer = json.loads(data.decode("utf-8")) or {} except urllib.error.HTTPError as exc: if exc.code == 401 and "Authorization" in headers: _debug("the GitLab token was rejected (expired?): continuing without it") self._token = "" - return False, None - if exc.code in (403, 404, 405): # GraphQL off or blocked: the email lookup may still work - _debug("GitLab GraphQL unavailable (HTTP %s)" % exc.code) - return False, None - raise - answer = json.loads(data.decode("utf-8")) or {} + else: # GraphQL off, blocked, overloaded...: the email lookup may still work + _debug("%s: GitLab GraphQL unavailable (HTTP %s)" % (email, exc.code)) + return False, None + except (urllib.error.URLError, OSError, ValueError) as exc: # e.g. a slow server timing out + _debug("%s: GitLab GraphQL failed (%s: %s)" % (email, type(exc).__name__, exc)) + return False, None + if not isinstance(answer, dict): + return False, None project = (answer.get("data") or {}).get("project") if not project: _debug("%s: project %s not visible%s" % ( @@ -356,16 +364,35 @@ def _gitlab_commit_author(self, email: str, sha: str) -> Tuple[bool, Optional[st return False, None commit = ((project.get("repository") or {}).get("tree") or {}).get("lastCommit") or {} same = commit.get("sha") == sha or (commit.get("authorEmail") or "").lower() == email.lower() - if not same: # e.g. an empty commit: GitLab names an earlier one + if not same: # unknown to GitLab (not pushed), or an empty commit: GitLab names another + _debug("%s: GitLab does not know commit %s" % (email, sha[:12])) return False, None avatar = (commit.get("author") or {}).get("avatarUrl") if not avatar: return True, None # GitLab knows no user with this email return True, urllib.parse.urljoin(self.host["base"] + "/", avatar) + def _pushed_commit(self, email: str) -> Optional[str]: + """The author's newest non-merge commit on a remote-tracking branch: one GitLab + knows (the commit shown may be local only) and that GitLab attributes to them.""" + if not self.repo: + return None + try: + out = gitdata.run_git(self.repo, ["log", "--remotes", "--no-merges", "-1", "--format=%H", + "--fixed-strings", "--regexp-ignore-case", + "--author=<%s>" % email], timeout_s=10) + except (gitdata.GitError, OSError, subprocess.SubprocessError): + return None + sha = out.decode("ascii", "ignore").strip() + return sha if gitdata.is_sha(sha) else None + def _gitlab_avatar_url(self, email: str, sha: Optional[str] = None) -> Optional[str]: - if sha: - answered, avatar = self._gitlab_commit_author(email, sha) + shas = [] + for candidate in (self._pushed_commit(email), sha): + if candidate and candidate not in shas: + shas.append(candidate) + for candidate in shas: + answered, avatar = self._gitlab_commit_author(email, candidate) if answered: return avatar # only matches a user's public profile email @@ -385,6 +412,12 @@ def _lookup(self, email: str, sha: Optional[str]) -> Optional[Tuple[bytes, str]] return self._download_image(url) if url else None # ---- public -------------------------------------------------------- + def retry_after(self, email: str) -> float: + """Seconds until ``email`` may be looked up again after network trouble (0: it was + a real answer, the picture or "no picture").""" + until = self._session_miss.get(self._key((email or "").strip()), 0.0) + return max(0.0, until - time.time()) + def get(self, email: str, sha: Optional[str] = None) -> Optional[Tuple[bytes, str]]: """``(image bytes, content type)`` for the author, or None (show initials).""" email = (email or "").strip() @@ -415,15 +448,15 @@ def get(self, email: str, sha: Optional[str] = None) -> Optional[Tuple[bytes, st _debug("%s: HTTP %s from %s" % (email, exc.code, exc.geturl() if hasattr(exc, "geturl") else "?")) if exc.code == 404 and self.host["kind"] == "gitlab": result = None # GitLab: no such user, a real answer - else: # rate limits, unpushed commits, private instance...: not an answer - self._session_miss[key] = time.time() + 600 + else: # rate limits, private instance...: not an answer + self._session_miss[key] = time.time() + RETRY_S return None except _NoAnswer: _debug("%s: not asked (no commit to look up, or rate limited)" % email) return None except (urllib.error.URLError, OSError, ValueError) as exc: _debug("%s: %s: %s" % (email, type(exc).__name__, exc)) - self._session_miss[key] = time.time() + 600 # offline or similar + self._session_miss[key] = time.time() + RETRY_S # offline or similar return None if not result: _debug("%s: the host has no picture for this author" % email) diff --git a/src/gitgraph/server.py b/src/gitgraph/server.py index 546d7fb..ce07ce7 100644 --- a/src/gitgraph/server.py +++ b/src/gitgraph/server.py @@ -230,7 +230,7 @@ def avatar_service(self): from . import avatars from .browser import cache_dir host = avatars.detect_host(self.repo) - self._avatar_service = avatars.AvatarService(host, cache_dir()) if host else None + self._avatar_service = avatars.AvatarService(host, cache_dir(), repo=self.repo) if host else None self._avatar_ready = True return self._avatar_service @@ -431,9 +431,12 @@ def log_message(self, fmt: str, *args: object) -> None: # noqa: D401 - stdlib s super().log_message(fmt, *args) # ---- helpers ------------------------------------------------------- - def _headers(self, status: int, ctype: str, length: Optional[int] = None) -> None: + def _headers(self, status: int, ctype: str, length: Optional[int] = None, + extra: Optional[Dict[str, str]] = None) -> None: self.send_response(status) self.send_header("Content-Type", ctype) + for name, value in (extra or {}).items(): + self.send_header(name, value) if length is not None: self.send_header("Content-Length", str(length)) self.send_header("Cache-Control", "no-store") @@ -442,8 +445,8 @@ def _headers(self, status: int, ctype: str, length: Optional[int] = None) -> Non self.send_header("Content-Security-Policy", CSP) self.end_headers() - def _send(self, status: int, body: bytes, ctype: str) -> None: - self._headers(status, ctype, len(body)) + def _send(self, status: int, body: bytes, ctype: str, extra: Optional[Dict[str, str]] = None) -> None: + self._headers(status, ctype, len(body), extra) try: self.wfile.write(body) except ConnectionError: # broken pipe / reset / aborted (Windows) @@ -591,8 +594,12 @@ def _avatar(self, q: Dict[str, List[str]]) -> None: if sha is not None and not gitdata.is_sha(sha): raise ValueError("bad commit id") found = service.get(email, sha) if service is not None else None - if not found: # "no picture" is a normal answer, not an error (keeps consoles clean) - self._send(204, b"", "text/plain") + if not found: + retry_s = service.retry_after(email) if service is not None else 0.0 + if retry_s > 0: # the host could not be asked right now: the page asks again later + self._send(503, b"", "text/plain", {"Retry-After": str(int(retry_s) + 1)}) + return + self._send(204, b"", "text/plain") # "no picture" is a normal answer, not an error return data, ctype = found self._send(200, data, ctype) diff --git a/src/gitgraph/web/app.js b/src/gitgraph/web/app.js index e3e22ff..667bc32 100644 --- a/src/gitgraph/web/app.js +++ b/src/gitgraph/web/app.js @@ -119,6 +119,7 @@ var avatarCache = new Map(); // lower-case email -> blob URL | null | 'pending' var avatarQueue = []; var avatarActive = 0; + var avatarTries = new Map(); // lower-case email -> lookups that the host could not answer function avatarFor(email, sha) { if (!S.meta || !S.meta.avatars || !email) return null; var key = email.toLowerCase(); @@ -141,6 +142,15 @@ function fetchAvatar(email, sha) { var key = email.toLowerCase(); fetch('api/avatar?email=' + encodeURIComponent(email) + (sha ? '&sha=' + sha : '')).then(function (res) { + if (res.status === 503) { // host not reachable right now: ask again later (a few times) + var tries = (avatarTries.get(key) || 0) + 1; + avatarTries.set(key, tries); + if (tries < 4) { + var wait_s = Math.min(600, Math.max(5, parseInt(res.headers.get('Retry-After'), 10) || 120)); + setTimeout(function () { avatarCache.delete(key); invalidateRows(); schedule(); }, wait_s * 1000); + } + return null; + } return res.status === 200 ? res.blob() : null; // 204: no picture }).then(function (blob) { avatarCache.set(key, blob ? URL.createObjectURL(blob) : null); diff --git a/tests/test_avatars.py b/tests/test_avatars.py index 3d94b44..73a7b4a 100644 --- a/tests/test_avatars.py +++ b/tests/test_avatars.py @@ -202,6 +202,61 @@ def test_gitlab_empty_commit_is_not_taken_for_another(tmp_path): assert not any("/uploads/" in u for u, _ in web.calls) + +def test_gitlab_asks_about_a_pushed_commit_of_the_author(tmp_path, repo): + # the newest commit shown (a local merge) is unknown to GitLab; origin/main has m2 + svc, web = service(tmp_path, GITLAB, { + GRAPHQL: lambda q: commit_answer(q["variables"]["sha"], "/uploads/a.png", email="alice@example.com"), + "https://gitlab.example.org/uploads/": (png(), "image/png"), + }, repo=str(repo.path)) + assert svc.get("Alice@Example.com", repo.shas["merge"])[1] == "image/png" + assert json.loads(web.bodies[0].decode("utf-8"))["variables"]["sha"] == repo.shas["m2"] + + +def test_gitlab_tries_the_shown_commit_when_gitlab_does_not_know_the_pushed_one(tmp_path, repo): + asked = [] + + def answer(q): + asked.append(q["variables"]["sha"]) + if q["variables"]["sha"] == repo.shas["m2"]: # e.g. the remote was force-pushed since + return json.dumps({"data": {"project": {"repository": {"tree": None}}}}).encode(), "application/json" + return commit_answer(q["variables"]["sha"], "/uploads/a.png") + svc, _ = service(tmp_path, GITLAB, {GRAPHQL: answer, "https://gitlab.example.org/uploads/": (png(), "image/png")}, + repo=str(repo.path)) + assert svc.get("alice@example.com", repo.shas["w1"]) + assert asked == [repo.shas["m2"], repo.shas["w1"]] + + +@pytest.mark.parametrize("failure", [ + urllib.error.URLError(TimeoutError("timed out")), + TimeoutError("timed out"), + urllib.error.HTTPError(GRAPHQL, 502, "bad gateway", {}, None), + urllib.error.HTTPError(GRAPHQL, 429, "too many", {}, None), +]) +def test_gitlab_graphql_trouble_falls_back_to_the_email_lookup(tmp_path, failure): + svc, web = service(tmp_path, GITLAB, { + GRAPHQL: failure, + "https://gitlab.example.org/api/v4/avatar": ( + json.dumps({"avatar_url": "/uploads/k.png"}).encode(), "application/json"), + "https://gitlab.example.org/uploads/": (png(), "image/png"), + }) + assert svc.get("kim@example.com", "5" * 40)[1] == "image/png" + assert svc.retry_after("kim@example.com") == 0 + + +def test_network_trouble_asks_again_later(tmp_path, monkeypatch): + svc, web = service(tmp_path, GITLAB, {"https://": urllib.error.URLError("offline")}) + now = [1000.0] + monkeypatch.setattr(avatars.time, "time", lambda: now[0]) + assert svc.get("lee@example.com") is None + assert svc.retry_after("lee@example.com") == avatars.RETRY_S + calls = len(web.calls) + assert svc.get("lee@example.com") is None and len(web.calls) == calls # not hammered + now[0] += avatars.RETRY_S + 1 + assert svc.retry_after("lee@example.com") == 0 + svc.get("lee@example.com") + assert len(web.calls) > calls + def test_gitlab_token_sources(tmp_path, monkeypatch): from conftest import make_program glab = make_program(tmp_path, "glab", ( @@ -266,6 +321,9 @@ def get(self, email, sha=None): self.asked.append((email, sha)) return (png(), "image/png") if email == "alice@example.com" else None + def retry_after(self, email): + return 42.0 if email == "offline@example.com" else 0.0 + def test_server_avatar_endpoint(repo): import http.client @@ -289,6 +347,7 @@ def get(path): status, ctype, body = get("api/avatar?email=alice%40example.com&sha=" + repo.shas["m1"]) assert status == 200 and ctype == "image/png" and body.startswith(b"\x89PNG") assert get("api/avatar?email=nobody%40example.com")[0] == 204 + assert get("api/avatar?email=offline%40example.com")[0] == 503 # the page asks again later assert get("api/avatar?email=alice%40example.com&sha=--evil")[0] == 400 assert stub.asked[0] == ("alice@example.com", repo.shas["m1"]) finally: