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

+76 -10
View File
@@ -6,19 +6,11 @@ No network: httpx.MockTransport answers all requests deterministically.
import httpx
import pytest
from codeberg_to_gitea_migrator.clients import ApiClient, ApiError
from codeberg_to_gitea_migrator.clients import ApiClient, ApiError, CircuitOpenError, parallel
def _client(handler) -> ApiClient:
transport = httpx.MockTransport(handler)
real = ApiClient("https://example.com", "tok")
# Swap in the mock transport but keep the auth header.
real._client = httpx.Client(
base_url=real.api_root,
headers={"Authorization": "token tok"},
transport=transport,
)
return real
return ApiClient("https://example.com", "tok", transport=httpx.MockTransport(handler))
def test_paged_follows_pages_until_short_batch() -> None:
@@ -71,3 +63,77 @@ def test_post_sends_json_body() -> None:
result = c.post("/repos/o/r/issues", body={"title": "x"})
assert result == {"id": 7}
assert '"title":"x"' in seen["body"]
def test_raw_get_stream_returns_downloaded_bytes() -> None:
payload = b"binary-asset-bytes"
def handler(request: httpx.Request) -> httpx.Response:
return httpx.Response(200, content=payload)
with _client(handler) as c:
with c.raw_get_stream("/repos/o/r/releases/1/assets/9") as f:
assert f.read() == payload
def test_raw_get_stream_4xx_raises_apierror_not_attributeerror() -> None:
# Regression: the streamed 4xx path used resp.read().text on bytes, raising
# AttributeError instead of the intended ApiError on a missing/inaccessible
# asset.
def handler(request: httpx.Request) -> httpx.Response:
return httpx.Response(404, content=b"no such asset")
with _client(handler) as c:
with pytest.raises(ApiError) as exc_info:
with c.raw_get_stream("/repos/o/r/releases/1/assets/9"):
pass
assert exc_info.value.status == 404
def test_circuit_breaker_opens_then_aborts(monkeypatch) -> None:
monkeypatch.setattr("time.sleep", lambda _s: None) # no real backoff in the test
def handler(request: httpx.Request) -> httpx.Response:
return httpx.Response(503, text="down")
c = ApiClient(
"https://example.com",
"tok",
transport=httpx.MockTransport(handler),
max_retries=0,
fail_fast=3,
)
with c:
# First two 503s exhaust and return ApiError (counter < 3)...
for _ in range(2):
with pytest.raises(ApiError):
c.get("/x")
# ...the third consecutive failure trips the breaker.
with pytest.raises(CircuitOpenError):
c.get("/x")
# Now open → aborts immediately, without issuing a request.
with pytest.raises(CircuitOpenError):
c.get("/x")
def test_parallel_preserves_input_order() -> None:
def handler(request: httpx.Request) -> httpx.Response:
return httpx.Response(200, json={"id": int(request.url.params["x"])})
with _client(handler) as c:
items = list(range(12))
out = parallel(items, lambda i: c.get("/x", x=i)["id"], workers=4)
assert out == items
def test_parallel_serial_when_workers_one() -> None:
calls: list[int] = []
def handler(request: httpx.Request) -> httpx.Response:
calls.append(int(request.url.params["x"]))
return httpx.Response(200, json={"ok": True})
with _client(handler) as c:
parallel([3, 2, 1], lambda i: c.get("/x", x=i), workers=1)
# Serial path runs in input order; a thread pool would not guarantee it.
assert calls == [3, 2, 1]