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

+159 -16
View File
@@ -4,17 +4,33 @@ The two forges share one REST API lineage, so one client serves both: a source
instance (read) and a target instance (write). Handles bearer-token auth,
transparent pagination (``page``/``limit`` query params), and a small retry on
transient errors / rate limiting.
A single :class:`ApiClient` is safe to drive from multiple threads: each thread
transparently gets its own underlying ``httpx.Client`` (and thus its own
connection pool) via a thread-local. This lets the migration overlap independent
requests through :func:`parallel` without per-worker client plumbing.
"""
from __future__ import annotations
import random
import tempfile
import threading
import time
from collections.abc import Iterator
from collections.abc import Callable, Iterator
from concurrent.futures import ThreadPoolExecutor
from typing import Any
import httpx
PAGE_SIZE = 50
#: Per-op ceiling for bulk binary transfers (release assets). Metadata calls
#: stay on the snappier default ``timeout``; this only gates ``raw_get_stream`` /
#: ``post_multipart`` so large assets don't trip a read/write timeout mid-stream.
DEFAULT_BULK_TIMEOUT = 600.0
#: Aborts once this many requests exhaust their retries in a row with no success
#: in between (a sustained 5xx/429 storm → the target looks down). 0 disables.
DEFAULT_FAIL_FAST = 5
class ApiError(RuntimeError):
@@ -27,6 +43,20 @@ class ApiError(RuntimeError):
self.body = body
class CircuitOpenError(RuntimeError):
"""Raised once consecutive exhausted-retry failures exceed the fail-fast cap.
A degraded target forge otherwise turns the run into hours of per-item retry
churn; tripping aborts early so the operator learns the target (not the data)
is the problem.
"""
def _path(owner: str, repo: str, suffix: str = "") -> str:
"""Shared repo-scoped API path (used by every migration module)."""
return f"/repos/{owner}/{repo}{suffix}"
class ApiClient:
"""Bearer-auth client over the Forgejo/Gitea REST API (``/api/v1``)."""
@@ -37,21 +67,66 @@ class ApiClient:
*,
timeout: float = 30.0,
max_retries: int = 4,
bulk_timeout: float = DEFAULT_BULK_TIMEOUT,
fail_fast: int = DEFAULT_FAIL_FAST,
transport: httpx.BaseTransport | None = None,
) -> None:
# api/v1 path normalised onto the host root.
root = base_url.rstrip("/").removesuffix("/api/v1")
self.api_root = root + "/api/v1"
self.web_root = root
self._client = httpx.Client(
base_url=self.api_root,
headers={"Authorization": f"token {token}"},
timeout=timeout,
follow_redirects=True,
)
self._token = token
self._timeout = timeout
self.max_retries = max_retries
self._bulk_timeout = httpx.Timeout(timeout, read=bulk_timeout, write=bulk_timeout)
self._fail_fast = fail_fast
self._transport = transport
# One underlying httpx.Client per thread (httpx.Client is not itself
# concurrency-safe); a single ApiClient is then safe across threads.
self._tls = threading.local()
self._all_clients: list[httpx.Client] = []
self._clients_lock = threading.Lock()
self._fail_lock = threading.Lock()
self._consecutive_failures = 0
self._circuit_open = False
@property
def _client(self) -> httpx.Client:
c = getattr(self._tls, "client", None)
if c is None:
c = httpx.Client(
base_url=self.api_root,
headers={"Authorization": f"token {self._token}"},
timeout=self._timeout,
follow_redirects=True,
transport=self._transport,
)
self._tls.client = c
with self._clients_lock:
self._all_clients.append(c)
return c
# -- low level ---------------------------------------------------------
def _on_success(self) -> None:
if self._consecutive_failures:
with self._fail_lock:
self._consecutive_failures = 0
def _on_failure(self) -> None:
if self._fail_fast <= 0:
return
with self._fail_lock:
self._consecutive_failures += 1
if self._consecutive_failures >= self._fail_fast:
self._circuit_open = True
raise CircuitOpenError(
f"target {self.web_root} appears down: {self._consecutive_failures} "
f"consecutive requests exhausted retries — aborting"
)
def _request(self, method: str, path: str, **kwargs: Any) -> httpx.Response:
if self._circuit_open:
raise CircuitOpenError(f"target {self.web_root} circuit open — aborting")
path = path.lstrip("/")
url = f"{self.api_root}/{path}"
last_err: Exception | None = None
@@ -64,9 +139,11 @@ class ApiClient:
if resp.status_code in (429, 502, 503, 504):
last_err = ApiError(resp.status_code, url, resp.text)
else:
self._on_success()
return resp # caller decides on 4xx/5xx
# backoff: 0.5, 1, 2, 4, 8 …
time.sleep(0.5 * (2**attempt))
# backoff with full jitter: 0.5, 1, 2, 4, 8 … × [0.5, 1.0)
time.sleep((0.5 * (2**attempt)) * (0.5 + random.random()))
self._on_failure()
raise last_err if last_err else ApiError(0, url, "exhausted retries")
def request(self, method: str, path: str, **kwargs: Any) -> httpx.Response:
@@ -91,14 +168,48 @@ class ApiClient:
def delete(self, path: str, **kwargs: Any) -> None:
self.request("DELETE", path, **kwargs)
def post_multipart(self, path: str, files: dict[str, tuple[str, bytes]], **params: Any) -> Any:
resp = self.request("POST", path, files=files, params=_clean(params))
def post_multipart(self, path: str, files: dict[str, Any], **params: Any) -> Any:
# Bulk path: large asset uploads need a generous read/write window so a
# multi-hundred-MB file over a slow link doesn't time out mid-upload and
# trigger a wasteful full re-send.
resp = self.request(
"POST", path, files=files, params=_clean(params), timeout=self._bulk_timeout
)
return resp.json() if resp.content else None
def raw_get(self, path: str, **params: Any) -> bytes:
"""Fetch a path as raw bytes (binary downloads like release assets)."""
resp = self.request("GET", path, params=_clean(params))
return resp.content
def raw_get_stream(self, path: str, **params: Any) -> Any:
"""Stream a raw download into a spooled temp file; caller closes it.
The *download* is streamed to a spooled ~1 MiB temp file (vs. buffering
the whole body), so download peak memory is bounded regardless of asset
size. The subsequent *upload* (:meth:`post_multipart`) still buffers the
full asset — httpx materializes the multipart body — so overall peak
memory is ~one asset, not two. Honors the circuit breaker (aborts if
already open; counts transient 429/5xx + transport errors toward it) but
does NOT per-attempt retry a streamed download — a transient error on an
asset aborts the release phase; re-run the migration. Returns an open
``SpooledTemporaryFile`` positioned at 0.
"""
if self._circuit_open:
raise CircuitOpenError(f"target {self.web_root} circuit open — aborting")
tmp: Any = tempfile.SpooledTemporaryFile(max_size=1 << 20) # 1 MiB in-RAM threshold
try:
with self._client.stream(
"GET", path.lstrip("/"), params=_clean(params), timeout=self._bulk_timeout
) as resp:
if resp.status_code >= 400:
body = resp.read().decode(errors="replace")
if resp.status_code in (429, 502, 503, 504):
self._on_failure()
raise ApiError(resp.status_code, str(resp.url), body)
for chunk in resp.iter_bytes():
tmp.write(chunk)
self._on_success()
except httpx.TransportError as exc:
self._on_failure()
raise ApiError(0, f"{self.api_root}/{path.lstrip('/')}", str(exc)) from exc
tmp.seek(0)
return tmp
# -- pagination --------------------------------------------------------
def paged(self, path: str, **params: Any) -> Iterator[Any]:
@@ -118,7 +229,10 @@ class ApiClient:
return list(self.paged(path, **params))
def close(self) -> None:
self._client.close()
with self._clients_lock:
for c in self._all_clients:
c.close()
self._all_clients.clear()
def __enter__(self) -> ApiClient:
return self
@@ -127,6 +241,35 @@ class ApiClient:
self.close()
def parallel(
items: list[Any],
fn: Callable[[Any], Any],
*,
workers: int = 1,
executor: ThreadPoolExecutor | None = None,
) -> list[Any]:
"""Run ``fn(item)`` over ``items`` via a thread pool sized to ``workers``.
A single :class:`ApiClient` is thread-safe (each worker transparently gets
its own underlying ``httpx.Client``), so ``fn`` can close over the shared
source/target clients. Results are returned in input order. ``workers <= 1``
(or a single item) runs serially.
Pass a shared ``executor`` when calling in a loop (e.g. once per release) so
the same worker threads — and their thread-local clients — are reused
instead of accumulating a fresh pool per call. The first task failure
propagates via ``map`` but does NOT cancel already-running or queued
siblings (they drain on exit); the open-circuit fast-abort in ``_request``
makes the rest fail cheaply when the target is down.
"""
if workers <= 1 or len(items) <= 1:
return [fn(it) for it in items]
if executor is not None:
return list(executor.map(fn, items))
with ThreadPoolExecutor(max_workers=workers) as ex:
return list(ex.map(fn, items))
def _clean(params: dict[str, Any]) -> dict[str, Any]:
"""Drop ``None`` values and stringify booleans the Forgejo way."""
out: dict[str, Any] = {}