perf(migrator): parallelize and harden migration
CI / test (push) Canceled after 0s

The migrator was fully synchronous — every HTTP round-trip and git
op serialized over one blocking client, and a stalled git push could
hang it forever. Overlap the independent phases and bound the slow /
memory-heavy paths.

- clients: ApiClient is now thread-safe (per-thread httpx.Client) so
  labels, milestones, Pass-B comments, and release assets overlap via
  parallel(); --concurrency sizes it (default 8). Pass A issue/PR
  creation stays serial — entities are created in source-number order
  so the number map resolves forward cross-references.
- releases: stream assets through a spooled temp file instead of
  buffering each whole into memory; upload them concurrently.
- reliability: per-op --git-timeout (was unbounded hangs), a circuit
  breaker that aborts on a degraded target, jittered retry backoff,
  and a bulk timeout for large asset transfers.
- round-trips: set an issue's milestone in the create body; batch the
  deleted-branch PR-head git push and refs/pull/* pruning.
- fix: raw_get_stream 4xx/5xx raised AttributeError (resp.read().text
  on bytes) instead of ApiError — now decodes. Wrap mirror git ops in
  try/finally so tokenized remote URLs are scrubbed even on timeout.
- refactor: drop the typer dependency — the CLI is now stdlib argparse
  (same subcommands, flags, and env vars); remove dead code surfaced by
  a whole-repo audit (has_lfs, name_map, unused owner_repo param,
  stored-but-unread _base_url).
- ci: enable the uv download cache.

Tests cover parallel ordering, the circuit breaker, and the streamed
4xx path. CHANGELOG updated; the runtime dependency is now just httpx.
This commit is contained in:
AlexKucera committed 2026-08-11 13:36:11 +02:00
1 parent 867d982786
commit 137734673d
14 files changed
+1372 -299

No files matched your search

+100 -68
View File
@@ -5,17 +5,25 @@ Mirrors the source repository's git data to the target with
fetched and pushed separately — mirror push does not carry them. Both steps are
no-ops when there's nothing LFS in the source, so this is safe to run on any
repo.
Every network-bound git op runs under a timeout (``DEFAULT_GIT_TIMEOUT``,
overridable via ``--git-timeout``) so a stalled TCP connection aborts with a
clear :class:`GitError` instead of hanging the migration forever.
"""
from __future__ import annotations
import logging
import re
import shutil
import subprocess
from pathlib import Path
from urllib.parse import quote, urlsplit, urlunsplit
LFS_MARKERS = (".gitattributes",) # presence hints at possible LFS rules
log = logging.getLogger(__name__)
#: Per-op ceiling for network git ops (clone/fetch/push). Generous so a legit
#: large clone completes; small enough that a stalled connection is caught.
DEFAULT_GIT_TIMEOUT = 1800.0
class GitError(RuntimeError):
@@ -67,22 +75,24 @@ def _scrub_remote_tokens(bare: Path) -> None:
)
def _run(cmd: list[str], cwd: Path | None = None) -> None:
proc = subprocess.run( # noqa: S603 - argv list, no shell
cmd, cwd=cwd, capture_output=True, text=True
)
if proc.returncode != 0:
raise GitError(
f"git failed ({proc.returncode}): {' '.join(_redact(a) for a in cmd)}"
f"\n{_redact(proc.stderr.strip())}"
def _run_capture(
cmd: list[str],
cwd: Path | None = None,
*,
timeout: float = DEFAULT_GIT_TIMEOUT,
input: str | None = None,
) -> str:
"""Run git, return stdout; raise on non-zero or timeout (errors carry stderr).
The error message redacts any ``oauth2:<token>`` embedded in the command or
stderr so forge secrets never reach logs or tracebacks.
"""
try:
proc = subprocess.run( # noqa: S603 - argv list, no shell
cmd, cwd=cwd, capture_output=True, text=True, timeout=timeout, input=input
)
def _run_capture(cmd: list[str], cwd: Path | None = None) -> str:
"""Run git, return stdout; raise on non-zero (errors carry stderr)."""
proc = subprocess.run( # noqa: S603 - argv list, no shell
cmd, cwd=cwd, capture_output=True, text=True
)
except subprocess.TimeoutExpired as exc:
raise GitError(f"git timed out after {timeout}s: {_redact(' '.join(cmd))}") from exc
if proc.returncode != 0:
raise GitError(
f"git failed ({proc.returncode}): {' '.join(_redact(a) for a in cmd)}"
@@ -91,13 +101,31 @@ def _run_capture(cmd: list[str], cwd: Path | None = None) -> str:
return proc.stdout
def _run(
cmd: list[str],
cwd: Path | None = None,
*,
timeout: float = DEFAULT_GIT_TIMEOUT,
input: str | None = None,
) -> None:
"""Run git, raising on non-zero/timeout. Thin wrapper over :func:`_run_capture`."""
_run_capture(cmd, cwd, timeout=timeout, input=input)
def _prune_internal_refs(bare: Path) -> None:
"""Delete forge-managed refs (refs/pull/*) that the target won't accept."""
"""Delete forge-managed refs (refs/pull/*) that the target won't accept.
Batched into a single ``update-ref --stdin`` so one process prunes them all,
instead of spawning a git process per ref.
"""
listing = _run_capture(
["git", "--git-dir", str(bare), "for-each-ref", "--format=%(refname)", "refs/pull/"]
)
for ref in listing.split():
_run(["git", "--git-dir", str(bare), "update-ref", "-d", ref])
refs = listing.split()
if not refs:
return
stdin = "".join(f"delete {r}\n" for r in refs)
_run(["git", "--git-dir", str(bare), "update-ref", "--stdin"], input=stdin)
def _capture_pull_heads(bare: Path) -> dict[int, str]:
@@ -124,19 +152,12 @@ def _capture_pull_heads(bare: Path) -> dict[int, str]:
try:
number = int(ref.split("/")[2])
except (IndexError, ValueError):
log.warning("ignoring unparseable pull ref: %s", ref)
continue
heads[number] = sha
return heads
def has_lfs(source_url: str, token: str, workdir: Path) -> bool:
"""Quick check for LFS rules via the contents API is unreliable cross-forge,
so we treat LFS as present whenever ``git lfs`` is installed and the clone
yields LFS objects. Cheap heuristic: this always returns True when
``git lfs`` is available (fetch/push become no-ops without objects)."""
return shutil.which("git") is not None and _lfs_installed()
def _lfs_installed() -> bool:
proc = subprocess.run( # noqa: S603
["git", "lfs", "version"], capture_output=True, text=True
@@ -161,6 +182,8 @@ def mirror_repo(
source_token: str,
target_token: str,
workdir: Path,
*,
git_timeout: float = DEFAULT_GIT_TIMEOUT,
) -> dict[str, object]:
"""Mirror a repo's git data (and LFS) from source to target.
@@ -177,50 +200,59 @@ def mirror_repo(
src = _authed(source_url, source_token)
tgt = _authed(target_url, target_token)
if bare.exists():
# Re-fetch source refs into an existing mirror (idempotent re-run).
_run(["git", "--git-dir", str(bare), "remote", "set-url", "origin", src])
_run(["git", "--git-dir", str(bare), "fetch", "--prune", "origin", "*:*"])
else:
_run(["git", "clone", "--mirror", src, str(bare)])
# All git ops run under try/finally so the tokenized remote URLs git writes
# into .git/config are always scrubbed — even on a timeout/failure (the
# timeout this diff added makes early abort more frequent, so this matters).
try:
if bare.exists():
# Re-fetch source refs into an existing mirror (idempotent re-run).
_run(
["git", "--git-dir", str(bare), "remote", "set-url", "origin", src],
timeout=git_timeout,
)
_run(
["git", "--git-dir", str(bare), "fetch", "--prune", "origin", "*:*"],
timeout=git_timeout,
)
else:
_run(["git", "clone", "--mirror", src, str(bare)], timeout=git_timeout)
# Forgejo/Gitea expose refs/pull/<n>/head (and /merge) as fetchable refs;
# `clone --mirror` grabs them, but the target declines pushes to refs/pull/*
# (it manages those itself). First capture each PR's head SHA so we can
# recreate the PR on the target (a deleted-branch PR has no other branch),
# then drop the namespace so the mirror push doesn't trip on it.
pull_heads = _capture_pull_heads(bare)
_prune_internal_refs(bare)
# Forgejo/Gitea expose refs/pull/<n>/head (and /merge) as fetchable refs;
# `clone --mirror` grabs them, but the target declines pushes to refs/pull/*
# (it manages those itself). First capture each PR's head SHA so we can
# recreate the PR on the target (a deleted-branch PR has no other branch),
# then drop the namespace so the mirror push doesn't trip on it.
pull_heads = _capture_pull_heads(bare)
_prune_internal_refs(bare)
# push --mirror replaces all target refs with source refs.
_run(["git", "--git-dir", str(bare), "push", "--mirror", tgt])
# push --mirror replaces all target refs with source refs.
_run(["git", "--git-dir", str(bare), "push", "--mirror", tgt], timeout=git_timeout)
# Recreate each PR head on the target as a real branch refs/heads/_pr/<n>,
# used as the PR's head when the original branch is gone. (Pushed after the
# mirror so --mirror doesn't wipe them.)
for pr_number, sha in pull_heads.items():
_run(
[
"git",
"--git-dir",
str(bare),
"push",
tgt,
f"{sha}:refs/heads/_pr/{pr_number}",
]
)
# Recreate each PR head on the target as a real branch refs/heads/_pr/<n>,
# used as the PR's head when the original branch is gone. (Pushed after the
# mirror so --mirror doesn't wipe them.) Batched into one push so one
# process + one connection handles all deleted-branch PRs.
if pull_heads:
refspecs = [f"{sha}:refs/heads/_pr/{n}" for n, sha in pull_heads.items()]
_run(["git", "--git-dir", str(bare), "push", tgt, *refspecs], timeout=git_timeout)
lfs_pushed = False
if _lfs_installed():
# Fetch every LFS object the source history references.
_run(["git", "--git-dir", str(bare), "lfs", "fetch", "--all", "origin"])
# Push LFS objects to the target via a named remote (a bare mirror has
# `origin` → source; LFS needs the target URL reachable as a remote).
_ensure_remote(bare, "target", tgt)
_run(["git", "--git-dir", str(bare), "lfs", "push", "--all", "target"])
lfs_pushed = True
_scrub_remote_tokens(bare)
lfs_pushed = False
if _lfs_installed():
# Fetch every LFS object the source history references.
_run(
["git", "--git-dir", str(bare), "lfs", "fetch", "--all", "origin"],
timeout=git_timeout,
)
# Push LFS objects to the target via a named remote (a bare mirror has
# `origin` → source; LFS needs the target URL reachable as a remote).
_ensure_remote(bare, "target", tgt)
_run(
["git", "--git-dir", str(bare), "lfs", "push", "--all", "target"],
timeout=git_timeout,
)
lfs_pushed = True
finally:
_scrub_remote_tokens(bare)
return {"bare": str(bare), "lfs_pushed": lfs_pushed, "pr_head_branches": len(pull_heads)}