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

+1
View File
@@ -14,6 +14,7 @@ jobs:
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
with:
python-version: "3.11"
cache: uv # persist the uv download cache across runs; --frozen stays hash-verified
# Install deps from the committed, hash-verified uv.lock (reproducible builds).
- run: python -m pip install uv
- run: uv sync --frozen --extra dev
+20
View File
@@ -9,6 +9,26 @@ All notable changes to this project will be documented in this file. The format
- **migrator:** keep forge API tokens out of error text and on-disk git config. Git failures now surface a redacted `oauth2:***@` URL instead of the live token, and the CLI catches `GitError` with a clean message instead of dumping a traceback. The mirror's remote URLs are scrubbed to bare form after each run (no token persisted in `.git/config`), and the default workdir is per-user `0700` (`/tmp/cb2gitea-<uid>`) so it isn't world-readable on shared hosts.
- **deps:** reproducible, hash-verified installs — commit `uv.lock` and install from it in CI (`uv sync --frozen`); pin Gitea Actions to commit SHAs instead of mutable `@vN` tags; pin the ruff rule set explicitly (`select = ["E4","E7","E9","F"]`) and exclude `audit/`.
### perf
- **migrator:** parallelize the independent migration phases. A single `ApiClient` is now thread-safe (each worker transparently gets its own underlying `httpx.Client` via a thread-local), so label/milestone creation, the Pass-B comment rewrite+upload, and per-release asset upload overlap through a bounded thread pool. New `--concurrency` (default 8) sizes it; Pass A issue/PR creation stays serial (entities must be created in source-number order so the number map resolves forward refs).
- **migrator:** stream release assets through a spooled temp file (`raw_get_stream`) instead of buffering each binary whole into memory, and upload them concurrently — peak memory is bounded (~1 MiB) regardless of asset size.
- **migrator:** set an issue's milestone in the create body instead of a follow-up PATCH (PRs still PATCH — the pull-create endpoint has no milestone field). One fewer round-trip per milestoned issue.
- **migrator:** batch git operations — one `git push` carries all deleted-branch PR-head refspecs, and `update-ref --stdin` prunes all `refs/pull/*` in one process (was one spawn per ref).
### fix
- **migrator:** every network git op (`clone --mirror`, `fetch`, `push --mirror`, PR-head push, LFS fetch/push) now runs under a per-op timeout (`--git-timeout`, default 1800s) so a stalled TCP connection aborts with a redacted `GitError` instead of hanging the migration forever.
- **client:** circuit breaker — once `--fail-fast` (default 5) consecutive requests exhaust their retries with no success in between, the run aborts (`CircuitOpenError`) instead of churning through every remaining item for hours on a degraded target.
- **client:** add full jitter to the retry backoff and a larger, write-aware timeout (`httpx.Timeout(read=600, write=600)`) for bulk asset transfers so large binaries stop timing out mid-transfer and re-uploading from scratch.
- **migrator:** log unparseable pull refs instead of dropping them silently.
- **ci:** enable the uv download cache (`setup-python` `cache: uv`) so warm runs skip re-fetching deps; installs stay `--frozen`/hash-verified.
### refactor
- **cli:** drop the `typer` dependency; the CLI now uses stdlib `argparse` (same `migrate`/`version` subcommands, flags, and `CODEBERG_TOKEN`/`GITEA_TOKEN` env vars). Removes `typer` and its transitive `rich`/`shellingham` from the install (3 fewer packages).
- **migrator:** remove dead code surfaced by a whole-repo over-engineering audit — `has_lfs`/`LFS_MARKERS` (uncalled), the `name_map` return of `migrate_labels` (sole caller discarded it), the unused `owner_repo` rewrite param, and a stored-but-unread `_base_url`.
### feat
- **migrator:** working Codeberg → Gitea migration via `codeberg-to-gitea migrate`. Mirrors git (code, history, tags, LFS) and replays labels, milestones, issues & PRs (with comments), and releases (with assets) entity-by-entity over the shared Forgejo/Gitea REST API. Two-pass issue/PR creation with `#NNN`/URL cross-reference rewriting to the target's number space; deleted-branch PR heads recreated as `refs/heads/_pr/<n>`. Tokens via `CODEBERG_TOKEN`/`GITEA_TOKEN`; `--repo owner/name` (or bare name). `--delete-existing` for clean re-runs.
+806
View File
@@ -0,0 +1,806 @@
# Code Optimization Audit Report
**Project:** codeberg-to-gitea-migrator
**Date:** 2026-08-11
**Auditor:** Claude — code-optimizer skill
**Framework:** 13-domain performance audit (parallel agents)
**Scope:** `src/codeberg_to_gitea_migrator/` (8 modules: `cli.py`, `clients.py`, `issues.py`, `migrate.py`, `mirror.py`, `refs.py`, `releases.py`, `__init__.py`), `pyproject.toml`, `.gitea/workflows/ci.yml`, `tests/`.
**Technology Stack:** Python 3.11+ CLI migrator — `httpx>=0.27` (sync `httpx.Client`), `typer>=0.12`. No database, no frontend UI, no Docker.
---
## Executive Summary
The migrator is a small, well-structured codebase that is correct and clean on the dimensions Python projects usually fail (dependencies, data structures, algorithmic complexity, logging, regex safety). The performance posture is dominated by **one architectural fact**: the entire HTTP layer is synchronous. A repository migration is overwhelmingly I/O-bound — labels, milestones, issues, PRs, comments, releases, and binary assets are each their own round-trip, and every one of them is serialized over a single blocking `httpx.Client` with zero `async`/`await`/`asyncio` anywhere in the codebase. On a tracker with hundreds of issues × dozens of comments plus binary releases, wall-time equals the raw sum of thousands of sequential network waits.
Three concrete amplifiers stack on top of that: release assets are **downloaded whole into memory then re-uploaded one at a time** (memory spike + serial transfer), the comment-upload loop is a **nested sequential POST** (the single hottest serialization), and every milestone is set via a **redundant follow-up PATCH** instead of in the create body. A separate reliability gap — **git subprocess calls have no timeout** — can hang an unattended cutover indefinitely.
None of this is a bug; the data structures, retry logic (exponential backoff), connection reuse (one pooled client), and logging (lazy `%s` everywhere) are all done right. The wins are architectural (async + streaming + bounded concurrency) and a handful of surgical fixes.
**Overall Risk Score:** 94 (Critical Risk)
| Severity | Count |
|----------|-------|
| Critical | 0 |
| High | 6 |
| Medium | 9 |
| Low | 8 |
| Info | 3 |
| **Total**| **26**|
### Top 3 highest-impact fixes
1. **Move the HTTP client to `httpx.AsyncClient` and overlap independent writes with bounded concurrency** — the dominant lever; migration wall-time moves from ≈ Σ(round-trips) toward ≈ max(batch) within each phase. Commonly **5–10× faster** on issue/comment-heavy repos. (`clients.py`, `issues.py`, `migrate.py`)
2. **Stream release assets and upload them concurrently** — `raw_get` buffers each binary into RAM; streaming bounds peak memory to a fixed buffer (~1 MiB vs. hundreds of MB) and bounded gather removes the serial download→upload wait. (`clients.py:98-101`, `releases.py:57-63`)
3. **Add a timeout to git subprocess calls** — `clone --mirror` / `fetch` / `push --mirror` currently block forever on a stalled TCP connection. Converts an indefinite production hang into a bounded, diagnosable `GitError`. (`mirror.py:70-73`)
---
## Findings
### Database & Queries
> The project has no DB/ORM layer — it is a pure REST-API migrator. The Database-domain analogs are the redundant-round-trip and N+1 patterns in the per-item migration loops.
#### Medium Milestone set via redundant follow-up PATCH instead of in the create body
- **File:** `src/codeberg_to_gitea_migrator/issues.py`
- **Line(s):** 150-178
- **Pattern:** Redundant round-trip (ORM `.create()` then `.update()` analog) — two requests per item where one suffices
- **Current code:**
```python
created = tgt.post(
_path(owner, repo, "/issues"),
body={"title": item["title"], "body": item.get("body") or ""},
)
...
new_number = created["number"]
ms = item.get("milestone")
if ms and ms.get("id") in milestone_map:
tgt.patch(
_path(owner, repo, f"/issues/{new_number}"),
body={"milestone": milestone_map[ms["id"]]},
)
```
- **Why it's slow:** Gitea/Forgejo `CreateIssueOption` accepts `milestone` directly in the create body. Setting it via a separate PATCH doubles the round-trips for every milestoned item, each a full WAN hop over the blocking client. Cost scales linearly with the count of milestoned items.
- **Optimal fix:**
```python
body = {"title": item["title"], "body": item.get("body") or ""}
ms = item.get("milestone")
if ms and ms.get("id") in milestone_map:
body["milestone"] = milestone_map[ms["id"]]
created = tgt.post(_path(owner, repo, "/issues"), body=body)
# drop the follow-up milestone PATCH entirely
```
(Labels and `state=closed` legitimately need separate endpoints — Gitea doesn't accept them on create — so those calls are inherent, not redundant.)
- **Estimated impact:** Eliminates one round-trip per milestoned item; roughly halves per-item wall time for those items over slow links.
#### Medium Per-issue paginated comment fetch inside the migration loop (N+1)
- **File:** `src/codeberg_to_gitea_migrator/issues.py`
- **Line(s):** 224-235
- **Pattern:** N+1 query — one (paginated) read per parent item inside a loop
- **Current code:**
```python
for item, new_number in created:
...
for comment in src.get_all(_path(owner, repo, f"/issues/{item['number']}/comments")):
tgt.post(_path(owner, repo, f"/issues/{new_number}/comments"), ...)
```
- **Why it's slow:** For M issues this is M fresh paginated GETs plus one POST per comment, all sequential through the blocking client. Latency of the comment pass scales O(M) and dominates runtime on large repos.
- **Optimal fix:** The per-issue fetch shape is largely inherent — Gitea exposes comments only per-issue (no bulk endpoint). The amplifier is the sequential blocking execution, so the real fix is in the Concurrency domain: stream comments for independent issues concurrently. Keep this as the query-shape note and apply the parallelization described under Concurrency & Async.
- **Estimated impact:** Concurrency change cuts comment-pass wall time by the concurrency factor; query count itself is bounded by the Gitea API.
*Notes (no separate findings):* pagination is correctly bounded (`clients.paged()` terminates on `len(batch) < limit`); `get_all()` materializes to a list, which matters only for large sets (see Memory & Resources).
---
### Memory & Resources
#### Medium Release assets fully buffered in memory (no streaming)
- **File:** `src/codeberg_to_gitea_migrator/releases.py` (root cause at `clients.py:98-101`)
- **Line(s):** releases.py:57-63; clients.py:98-101
- **Pattern:** Large allocations — whole-body `resp.content` read; binary download loaded entirely into memory instead of streamed
- **Current code:**
```python
# clients.py — raw_get returns the FULL response body as bytes
def raw_get(self, path: str, **params: Any) -> bytes:
resp = self.request("GET", path, params=_clean(params))
return resp.content # entire asset buffered in RAM
# releases.py — each asset downloaded whole, then re-uploaded
for asset in rel.get("assets", []) or []:
data = src.raw_get(_path(owner, repo, f"/releases/{rel['id']}/assets/{asset['id']}"))
tgt.post_multipart(..., files={"attachment": (asset["name"], data)}) # held in memory twice
```
- **Why it's slow:** `raw_get` reads the entire binary asset into a `bytes` object (httpx `.content` decodes eagerly); `post_multipart` keeps it alive while uploading. Peak memory ≈ the size of the largest single asset (briefly duplicated during multipart encoding). A release with a few hundred-MB binary caps the migrator's usable asset size at available RAM.
- **Optimal fix:**
```python
# clients.py — stream the download into a spooled temp file; return a handle
def raw_get_stream(self, path: str, **params: Any):
tmp = tempfile.SpooledTemporaryFile(max_size=1 << 20) # 1 MiB in-RAM threshold
with self._client.stream("GET", path, params=_clean(params), follow_redirects=True) as resp:
if resp.status_code >= 400:
raise ApiError(resp.status_code, str(resp.url), resp.read().text)
for chunk in resp.iter_bytes():
tmp.write(chunk)
tmp.seek(0)
return tmp
# releases.py — upload straight from the file handle (httpx streams file objs)
with src.raw_get_stream(...) as data:
tgt.post_multipart(..., files={"attachment": (asset["name"], data)}, name=asset["name"])
```
- **Estimated impact:** Bounds peak memory to ~1 MiB per asset regardless of size. A 500 MB asset drops peak RSS from ~500 MB+ to a few MB; large-binary repos stop risking OOM/swap.
#### Low Entire issues/PR collection materialized and held across a two-pass migration
- **File:** `src/codeberg_to_gitea_migrator/issues.py` (root cause at `clients.py:117-118`)
- **Line(s):** issues.py:95-105, 192-235; clients.py:117-118
- **Pattern:** Unbounded result set — `get_all` eagerly builds a full `list`; `_collect` keeps all issues *and* PRs in memory for sorting and a two-pass rewrite
- **Current code:**
```python
# clients.py
def get_all(self, path: str, **params: Any) -> list[Any]:
return list(self.paged(path, **params)) # entire dataset in RAM
```
- **Why it's slow:** Every issue/PR object (full body markdown + metadata) is loaded once and retained for the whole migration so the ref-rewrite pass can map `#old → #new`. The paged generator's memory benefit is discarded by `list(...)`. Bounded footprint, not a leak; matters mainly for repos with many thousands of issues.
- **Optimal fix:** Single-pass migration — create each entity and immediately write its rewritten title/body in the same loop, dropping the source dict after (requires migrating milestones/labels first, already done). Eliminates the held `created` list and lets each source item be GC'd.
- **Estimated impact:** Roughly halves peak memory for the issues/PRs phase on large repos.
---
### Algorithmic Complexity
No issues found. Checked: O(n²) nested loops / array-as-lookup (the only nested loop is the issue→comment fetch at `issues.py:224-235`, which is the N+1 network pattern reported under Database/Concurrency, not a data-structure issue); `sorted(...)[0]` sort-for-extremum (0 matches — the two `.sort()` calls produce fully ordered output and are load-bearing for correctness); redundant computation in loops (3 regexes all compiled once at module scope, callbacks do O(1) dict lookups); inefficient data structures (every keyed lookup is a dict).
---
### Concurrency & Async
#### High Foundational HTTP layer is fully synchronous — entire I/O-bound migration serialized
- **File:** `src/codeberg_to_gitea_migrator/clients.py`
- **Line(s):** 45, 60, 72, 80
- **Pattern:** Blocking synchronous I/O / missing parallelization
- **Current code:**
```python
self._client = httpx.Client(base_url=self.api_root, headers={"Authorization": f"token {token}"})
...
resp = self._client.request(method, path, **kwargs)
```
- **Why it's slow:** A migration is overwhelmingly I/O-bound. With a sync client and no `async`/`gather` anywhere (0 matches for `await`/`asyncio`/`AsyncClient`), total wall-time ≈ Σ of every round-trip, serialized. For hundreds of issues × dozens of comments plus binary assets, that is thousands of sequential network waits.
- **Optimal fix:** Move to `httpx.AsyncClient`, make the verb methods coroutines, and drive independent groups through a bounded gather that respects the forge's rate limit:
```python
SEM = asyncio.Semaphore(8) # ponytail: fixed cap, tune to source/target rate limit
async def get(self, path, **params):
async with SEM:
resp = await self._client.request("GET", path, params=_clean(params))
...
# independent, unordered group → gather (no shared mutation)
results = await asyncio.gather(*[tgt.post(...) for x in batch])
```
Keep ordering only where dependencies exist (labels/milestones before issues; release before its assets).
- **Estimated impact:** Migration wall-time divided roughly by the concurrency cap on parallelizable groups — commonly **5–10× faster** on issue/comment-heavy repos.
#### High Nested sequential comment-upload loop (the hottest serialization)
- **File:** `src/codeberg_to_gitea_migrator/issues.py`
- **Line(s):** 231-235
- **Pattern:** Sequential HTTP-in-loop
- **Current code:**
```python
for comment in src.get_all(_path(owner, repo, f"/issues/{item['number']}/comments")):
tgt.post(_path(owner, repo, f"/issues/{new_number}/comments"),
body={"body": ref(comment.get("body"))})
```
- **Why it's slow:** Nested loop — each issue is iterated, and within it every comment is POSTed one at a time. Comments are mutually independent (across and within issues), yet every POST blocks. On a busy tracker this is the single largest contributor to migration time.
- **Optimal fix:** Collect all `(new_number, comment)` pairs, then upload with a bounded gather:
```python
comments = [(nnum, ref(c.get("body")))
for item, nnum in created
for c in src.get_all(_path(owner, repo, f"/issues/{item['number']}/comments"))]
await asyncio.gather(*[
tgt.post(_path(owner, repo, f"/issues/{n}/comments"), body={"body": body})
for n, body in comments
])
```
- **Estimated impact:** Removes the dominant serialization; comments upload in `min(N, cap)` waves instead of one-by-one.
#### High Sequential release-asset download + upload
- **File:** `src/codeberg_to_gitea_migrator/releases.py`
- **Line(s):** 57-63
- **Pattern:** Sequential HTTP-in-loop (download then upload, per asset)
- **Current code:**
```python
for asset in rel.get("assets", []) or []:
data = src.raw_get(_path(owner, repo, f"/releases/{rel['id']}/assets/{asset['id']}"))
tgt.post_multipart(..., name=asset["name"])
```
- **Why it's slow:** Each asset is fetched in full, then uploaded in full, before the next starts. Assets within and across releases are independent; this pipeline is ideal for concurrency. Binary-heavy releases dominate runtime here.
- **Optimal fix:** Upload assets with a bounded gather (download can stream in parallel with other assets' uploads):
```python
async def _one(asset):
data = await src.raw_get_stream(_path(owner, repo, f"/releases/{rel['id']}/assets/{asset['id']}"))
await tgt.post_multipart(..., name=asset["name"])
await asyncio.gather(*[_one(a) for a in rel.get("assets", []) or []])
```
- **Estimated impact:** Large for binary release sets — throughput scales with the cap up to local bandwidth limits. (Pairs with the streaming fix in Memory & Resources.)
#### Medium Sequential label / milestone creation
- **File:** `src/codeberg_to_gitea_migrator/issues.py`
- **Line(s):** 60-73, 80-91
- **Pattern:** Sequential HTTP-in-loop
- **Why it's slow:** Labels/milestones are mutually independent (only issues depend on them), yet created one-by-one. `id_map`/`name_map` are built via shared mutation today, which is safe only because it's single-threaded.
- **Optimal fix:** Gather the POSTs and build the maps from returned results (no shared mutation):
```python
created = await asyncio.gather(*[tgt.post(.../labels, body=b) for label, b in jobs])
id_map = {lab["id"]: c["id"] for lab, c in zip(labels, created)}
```
- **Estimated impact:** Modest (counts are usually tens), but removes one serial stage.
#### Medium Sequential pagination could read total page count and fan out
- **File:** `src/codeberg_to_gitea_migrator/clients.py`
- **Line(s):** 108-115
- **Pattern:** Sequential `while True` paging
- **Current code:**
```python
while True:
batch = self.get(path, page=page, limit=limit, **params) or []
...
yield from batch
if len(batch) < limit:
return
page += 1
```
- **Why it's slow:** Every page waits on the previous. Forgejo/Gitea list endpoints return `X-Total-Count` / `X-Page-Count`, so after page 1 the remaining pages are known and independent.
- **Optimal fix:** Fetch page 1, read `X-Total-Count` to compute page count, then gather pages 2..N; yield in order. (Requires `get` to expose response headers — currently it returns parsed JSON only.)
- **Estimated impact:** Helps repos with thousands of items (many pages); negligible for small lists.
#### Low Sequential per-ref git subprocess spawns
- **File:** `src/codeberg_to_gitea_migrator/mirror.py`
- **Line(s):** 99-100 (also 201)
- **Pattern:** Subprocess-in-loop
- **Current code:**
```python
for ref in listing.split():
_run(["git", "--git-dir", str(bare), "update-ref", "-d", ref])
```
- **Why it's slow:** One `git` process per PR ref to delete. Local git is fast, so the cost is process-spawn overhead, fully serialized.
- **Optimal fix:** Delete all refs in a single process via `update-ref --stdin`:
```python
stdin = "".join(f"delete {r}\n" for r in listing.split()).encode()
_run(["git", "--git-dir", str(bare), "update-ref", "--stdin"], input=stdin)
```
- **Estimated impact:** Small (local ops), but turns N process spawns into one.
---
### Bundle & Dependencies
No issues found. Checked: wildcard imports (`import *`), declared-vs-used dependency cross-reference (`pyproject.toml` vs third-party imports in `src/`), duplicate/competing libraries, dev/test dependencies leaking into `src/`, large/inlined assets, dynamic-import opportunities. Runtime deps (`httpx`, `typer`) are both used and minimal; dev deps (`pytest`, `ruff`) correctly isolated to tests/CI. Every other import is stdlib. The bundle/dependency reference patterns are largely JS/TS-oriented (lodash/moment/tree-shaking) and don't apply to a stdlib-heavy Python CLI.
---
### Dead Code & Redundancy
#### Low Duplicate `_path()` helper defined byte-identically in two modules
- **File:** `src/codeberg_to_gitea_migrator/issues.py`, `src/codeberg_to_gitea_migrator/releases.py`
- **Line(s):** issues.py:49-50, releases.py:19-20
- **Pattern:** Duplicate logic — identical function copy-pasted across modules
- **Current code:**
```python
# issues.py:49 AND releases.py:19 — identical in both files
def _path(owner: str, repo: str, suffix: str = "") -> str:
return f"/repos/{owner}/{repo}{suffix}"
```
- **Why it's slow:** No runtime cost — pure maintainability redundancy. The two copies can drift; `releases.py` already imports from `.issues`, so the local copy is gratuitous.
- **Optimal fix:**
```python
# releases.py — import instead of redefine
from .issues import RefCtx, _path
```
(Or move `_path` to `clients.py` and import from there in both.)
- **Estimated impact:** Zero runtime effect; removes one DRY violation and drift risk.
#### Low Duplicated subprocess + error-raising block in `_run` / `_run_capture`
- **File:** `src/codeberg_to_gitea_migrator/mirror.py`
- **Line(s):** 70-91
- **Pattern:** Duplicate logic — identical 8-line `subprocess.run` + `GitError` construction in two near-identical helpers
- **Current code:**
```python
def _run(cmd, cwd=None) -> None:
proc = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True)
if proc.returncode != 0:
raise GitError(f"git failed ({proc.returncode}): ... \n{_redact(proc.stderr.strip())}")
def _run_capture(cmd, cwd=None) -> str:
proc = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True) # identical
if proc.returncode != 0:
raise GitError(...) # identical
return proc.stdout
```
- **Why it's slow:** No runtime cost — duplication is maintainability risk; an error-handling/redaction fix must be applied in two places. The only real difference is `_run_capture` returns `proc.stdout`.
- **Optimal fix:** Collapse `_run` into a thin wrapper over `_run_capture`:
```python
def _run_capture(cmd, cwd=None) -> str:
proc = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True)
if proc.returncode != 0:
raise GitError(...)
return proc.stdout
def _run(cmd, cwd=None) -> None:
_run_capture(cmd, cwd)
```
- **Estimated impact:** Zero runtime effect; removes ~8 lines of divergence-prone error handling.
*Checked and clean:* commented-out code (0), deprecated/legacy markers (0), dead branches (0), unreachable code (none), unused imports (every import used), unused functions (all 38 module-level defs/classes reachable — confirmed via the GitNexus call graph), no wildcard imports.
---
### I/O & Network
#### High Release assets downloaded + uploaded one-at-a-time, fully buffered
- **File:** `src/codeberg_to_gitea_migrator/releases.py`
- **Line(s):** 57-63
- **Pattern:** Missing batching / sequential requests in a loop; missing streaming for binary downloads
- **Current code:**
```python
for asset in rel.get("assets", []) or []:
data = src.raw_get(_path(owner, repo, f"/releases/{rel['id']}/assets/{asset['id']}"))
tgt.post_multipart(..., files={"attachment": (asset["name"], data)}, name=asset["name"])
```
- **Why it's slow:** Each asset is two blocking round trips (download then upload) strictly in series, and `raw_get` buffers the whole file into `bytes` before the upload can start. With N assets across M releases you pay 2·N·M sequential RTTs plus full in-memory copies of each file.
- **Optimal fix:** Stream the download into the upload so each asset never sits fully in memory, and run independent assets concurrently with bounded parallelism:
```python
# clients.py — streaming raw getter
def raw_get_stream(self, path, **params):
with self._client.stream("GET", path.lstrip("/"), params=_clean(params)) as r:
r.raise_for_status()
yield from r.iter_bytes() # hand chunks straight to the upload
# releases.py — pipeline download→upload, no full buffer, then bounded-gather across assets
```
- **Estimated impact:** Memory drops from O(max asset size) to a fixed buffer; transfer time goes from Σ(2·RTT per asset) toward max(batch) — multiple-fold faster for releases with many assets. (Same root cause as the Memory & Resources streaming finding.)
#### High Entire migration is synchronous; every independent API write serializes
- **File:** `src/codeberg_to_gitea_migrator/migrate.py`, `src/codeberg_to_gitea_migrator/issues.py`
- **Line(s):** migrate.py:160-169 (orchestration); issues.py:60-90, 195-235 (loops)
- **Pattern:** Sequential requests that should be parallel; blocking I/O where independent operations are issued one at a time
- **Current code:**
```python
for label in src.get_all(_path(owner, repo, "/labels")):
...
created = tgt.post(_path(owner, repo, "/labels"), body=body) # one at a time
```
Backed by a single blocking `httpx.Client` (`clients.py:45`) with `time.sleep` retries (`clients.py:69`).
- **Why it's slow:** Migration wall-time equals the sum of every HTTP round trip. Independent writes (all labels, all milestones, Pass-B comment batches across different issues) could overlap but don't.
- **Optimal fix:** Move to `httpx.AsyncClient` (already a declared dependency) and overlap independent writes with bounded concurrency, throttled to the target's rate limit (the existing 429 backoff already detects throttling). Ordering-sensitive work (issue number mapping) stays serial.
- **Estimated impact:** Large repos move from wall-time ≈ Σ(RTT) toward ≈ max(batch) within each phase — several-fold faster. (Canonical framing of the Concurrency & Async foundational finding.)
#### Medium Binary release assets fully buffered into memory instead of streamed
- **File:** `src/codeberg_to_gitea_migrator/clients.py`
- **Line(s):** 98-101
- **Pattern:** Missing streaming — entire response buffered
- **Current code:**
```python
def raw_get(self, path: str, **params: Any) -> bytes:
resp = self.request("GET", path, params=_clean(params))
return resp.content
```
- **Why it's slow:** `resp.content` loads the entire asset at once. This caps usable asset size at available RAM and prevents download/upload pipelining. Same root cause as the asset-loop finding, at the transport layer.
- **Optimal fix:** Streaming variant feeding chunks to the upload (see Memory & Resources / the High asset finding above).
- **Estimated impact:** Fixed low memory regardless of asset size; unblocks the pipeline fix. No speed change on its own but removes the size ceiling.
#### Medium One `git push` subprocess per PR-head branch instead of a single batched push
- **File:** `src/codeberg_to_gitea_migrator/mirror.py`
- **Line(s):** 201-211
- **Pattern:** Sequential I/O in a loop; N process spawns + N network connections where one suffices
- **Current code:**
```python
for pr_number, sha in pull_heads.items():
_run(["git", "--git-dir", str(bare), "push", tgt, f"{sha}:refs/heads/_pr/{pr_number}"])
```
- **Why it's slow:** Each iteration spawns a `git` process, opens a fresh network connection to the target, performs the auth handshake, and pushes a single ref. Repos with many deleted-branch PRs pay N launches and N connections serially.
- **Optimal fix:** `git push` accepts many refspecs in one invocation:
```python
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])
```
- **Estimated impact:** N process spawns + N connections → 1; meaningful for repos with many historical deleted-branch PRs.
*Positive (no action needed):* connection reuse is handled well — one `httpx.Client` per forge held open for the whole migration via a context manager (`migrate.py:135-138`), so HTTP keep-alive is reused. Retry logic uses exponential backoff (`clients.py:64-69`: `0.5 * 2**attempt` on 429/5xx), so the "retry without backoff" anti-pattern does not apply.
---
### Rendering & UI
No issues found. Not applicable — this is a CLI application with no rendering or UI layer. (Domain excluded from the dispatch: no frontend surface exists to scan.)
---
### Data Structures
No issues found. Checked: linear-search APIs (`.find`/`.index`/`.count`/list `in [` membership → 0 matches; all membership tests are dict-key O(1)), wrong container choices (`NumberMap` + every map is a dict → O(1) add/get/has/`in`), deep-copy/clone (`deepcopy`/`import copy`/`pickle`/JSON round-trip → 0), serialization in loops (no `json.*` in `src` → 0), array-as-queue (`.pop(0)`/`.insert(0)` → 0), regex-in-loop (3 compiles all module-scope, none in loops), object creation in loops (body dicts built once per item). The `any_mismatch` O(n) scan is confined to `__repr__`/test. Data-structure selection is appropriate throughout.
---
### Error & Resilience
#### High Git subprocess calls have no timeout — a stalled clone/push hangs the migration indefinitely
- **File:** `src/codeberg_to_gitea_migrator/mirror.py`
- **Line(s):** 70-73 (`_run`); callers `clone --mirror` (185), `fetch` (183), `push --mirror` (196)
- **Pattern:** Missing timeouts — network call without timeout
- **Current code:**
```python
def _run(cmd: list[str], cwd: Path | None = None) -> None:
proc = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True) # no timeout=
if proc.returncode != 0:
raise GitError(...)
```
- **Why it's slow/fails:** `subprocess.run` has no `timeout=`, so every network-bound git op can block **forever** on a stalled TCP connection. The API client carries a 30s timeout, but the git layer — which does the bulk of byte transfer — has none. A hung `git push` to a degraded target leaves the migration frozen with no progress, error, or recovery short of a manual Ctrl-C; for an unattended cutover that is a production hang.
- **Optimal fix:**
```python
def _run(cmd, cwd=None, timeout: float = 600):
try:
proc = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True, timeout=timeout)
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(...)
```
Generous per-op ceiling (e.g. 600s, overridable via `--git-timeout`).
- **Estimated impact:** Converts an indefinite hang into a bounded, diagnosable failure; the run reports which git op stalled.
#### Medium No fail-fast / circuit breaker — a degraded target forge turns the run into hours of retry churn
- **File:** `src/codeberg_to_gitea_migrator/clients.py` (retry loop) + `src/codeberg_to_gitea_migrator/issues.py:199-201`
- **Line(s):** clients.py:58-70; issues.py:199-201
- **Pattern:** No circuit breaker — retry loop without a global failure threshold
- **Current code:**
```python
# clients.py — every call retries independently
for attempt in range(self.max_retries + 1):
... time.sleep(0.5 * (2**attempt))
# issues.py — a failed item is logged and skipped, then the next starts fresh
except ApiError as exc:
log.warning("skipped %s #%s ...", ...)
continue
```
- **Why it's slow:** If the target degrades (persistent 5xx), the retry contract is *per call*: each of thousands of items waits ~7.5s across 4 attempts, fails, then the next item repeats the full budget. No shared consecutive-failure counter to abort early, so a sustained outage makes the migration crawl for hours producing only skipped items.
- **Optimal fix:** Add a consecutive-failure threshold in `ApiClient` that raises `MigrationError` once N calls exhaust their retries, resetting on a real write success.
- **Estimated impact:** A degraded-target run aborts in seconds (≈N×7.5s) instead of grinding through every remaining item.
#### Medium Single 30s timeout applied to large binary asset uploads/downloads
- **File:** `src/codeberg_to_gitea_migrator/clients.py`
- **Line(s):** 38 (default `timeout=30.0`), used by `raw_get` (98-101) and `post_multipart` (94-96)
- **Pattern:** Under-tuned timeout — `httpx.Client(timeout=30.0)` sets connect=read=write=pool all to 30s
- **Current code:**
```python
timeout: float = 30.0,
...
self._client = httpx.Client(base_url=self.api_root, ..., timeout=timeout, follow_redirects=True)
```
- **Why it's slow:** A single value applied to read *and* write. A multi-hundred-MB release asset over a slow link easily exceeds a 30s window → `ReadTimeout`/`WriteTimeout` → caught by the retry loop → the partially-uploaded asset is re-sent from scratch, repeatedly. The timeout that protects metadata calls is too tight for bulk transfers.
- **Optimal fix:** Give asset transfers a larger, write-aware timeout via `httpx.Timeout`, keeping metadata calls snappy:
```python
from httpx import Timeout
def raw_get(self, path, **params):
resp = self.request("GET", path, params=_clean(params),
timeout=Timeout(connect=10.0, read=600.0, write=600.0, pool=10.0))
return resp.content
```
- **Estimated impact:** Large-binary repos stop timing out mid-transfer and stop triggering wasteful full re-uploads.
#### Low Retry backoff has no jitter — deterministic against a shared rate limit
- **File:** `src/codeberg_to_gitea_migrator/clients.py`
- **Line(s):** 69
- **Pattern:** Missing jitter on retry
- **Current code:**
```python
time.sleep(0.5 * (2**attempt)) # 0.5, 1, 2, 4 … deterministic
```
- **Why it's slow:** Fully deterministic. Negligible for one instance, but several migrations (or the migrator + other clients) hitting the same forge retry on the exact same clock → synchronized retry storms that prolong the 429.
- **Optimal fix:** Add bounded (full) jitter: `time.sleep((0.5 * (2**attempt)) * (0.5 + random.random()))`.
- **Estimated impact:** Low for one run; meaningful when multiple clients share a forge's rate limit.
#### Low Malformed PR refs skipped silently — could lose a PR head with no trace
- **File:** `src/codeberg_to_gitea_migrator/mirror.py`
- **Line(s):** 124-127
- **Pattern:** Swallowed error — catch-and-continue with no logging
- **Current code:**
```python
try:
number = int(ref.split("/")[2])
except (IndexError, ValueError):
continue # no log
```
- **Why it's slow:** Unparseable refs are dropped with zero visibility. If a deleted-branch PR's head lives in such a ref, its reconstruction is silently lost with no log line to find it.
- **Optimal fix:** `log.warning("ignoring unparseable pull ref: %s", _redact(ref))` before `continue`.
- **Estimated impact:** No speed change; restores traceability of skipped refs.
#### Info Best-effort `chmod` silently ignored (intentional)
- **File:** `src/codeberg_to_gitea_migrator/mirror.py`
- **Line(s):** 171-174
- **Pattern:** Swallowed error — `except OSError: pass`
- **Current code:**
```python
try:
workdir.chmod(0o700)
except OSError:
pass
```
- **Why it's noted:** Best-effort hardening on a filesystem that may not support mode bits; swallowing is defensible. Flagged only so it is a conscious choice. No fix required.
*Checked and clean:* no swallowed `except` blocks (every handler is specific; no bare `except:` or `except Exception: pass`); `cli.py:80-87` echoes-and-exits on the typed error hierarchy; resource cleanup via context manager (`with` in `migrate.py:135-138`); graceful 404 degradation (`migrate.py:40-42`, `releases.py:33-36`); `max_retries=4` is sane.
---
### Caching & Memoization
#### Low Redundant per-call string normalization of constant web roots in `refs.rewrite`
- **File:** `src/codeberg_to_gitea_migrator/refs.py`
- **Line(s):** 70-71 (recomputed on every call; called via `RefCtx.__call__` at `issues.py:41`/`225-234`)
- **Pattern:** Constant derived value recomputed per call instead of memoized
- **Current code:**
```python
def rewrite(text, numbers, *, source_web_root, target_web_root, ...):
...
src_root = source_web_root.rstrip("/").removesuffix("/api/v1").rstrip("/")
tgt_root = target_web_root.rstrip("/").removesuffix("/api/v1").rstrip("/")
```
- **Why it's slow:** `source_web_root`/`target_web_root` are constant for the whole migration (already normalized once in `ApiClient.__init__`). The three-call normalization chain runs ~M·(2 + C) times on identical inputs. Small impact (microseconds), but a textbook "recompute a constant N times" pattern.
- **Optimal fix:** `RefCtx` already holds the two roots as immutable fields — precompute normalized forms in `__post_init__` and pass them through:
```python
@dataclass
class RefCtx:
numbers: NumberMap
source_web_root: str
target_web_root: str
def __post_init__(self) -> None:
self._src_root = self.source_web_root.rstrip("/").removesuffix("/api/v1").rstrip("/")
self._tgt_root = self.target_web_root.rstrip("/").removesuffix("/api/v1").rstrip("/")
def __call__(self, text):
return rewrite(text, self.numbers, src_root=self._src_root, tgt_root=self._tgt_root)
```
- **Estimated impact:** Marginal (microseconds); value is clarity and removing N redundant derivations. Listed for completeness.
*Checked and clean:* `@lru_cache`/`@cache` N/A (only one `@property`, used in `__repr__`/test — not hot); regex compilation clean (module-scope); no module/instance dict caches (no unbounded-cache risk); no redundant identical API fetches (each entity fetched once; the per-issue comment fetch is the N+1 shape, not a cache miss); HTTP response caching N/A (write-migration client, not a read-heavy server).
---
### Build & Compilation
#### Low CI dependency cache not enabled — deps reinstalled on every run
- **File:** `.gitea/workflows/ci.yml`
- **Line(s):** 14-19
- **Pattern:** Missing caching in CI/CD — `uv sync` without a persisted cache
- **Current code:**
```yaml
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
with:
python-version: "3.11"
- run: python -m pip install uv
- run: uv sync --frozen --extra dev
```
- **Why it's slow:** `setup-python@v5` is invoked without a `cache` input, and no `astral-sh/setup-uv`/`enable-cache` step exists, so uv's global download cache is not persisted across runs. Each CI run re-resolves and re-fetches deps cold.
- **Optimal fix:**
```yaml
- uses: astral-sh/setup-uv@v3 # pin to a SHA per project convention
with:
enable-cache: true
cache-dependency-glob: uv.lock
```
Or, keeping `setup-python`, set `cache: uv` (setup-python@v5 understands uv when `uv.lock` is present). Stays fully reproducible (`--frozen`/hash-verified).
- **Estimated impact:** Cuts `uv sync` from a fresh download/install to cache-restore on warm runs — roughly 10–30s saved per CI run; no production effect.
#### Info Guarded `print()` in `__main__` self-checks — non-actionable, intentional
- **File:** `src/codeberg_to_gitea_migrator/refs.py`, `src/codeberg_to_gitea_migrator/mirror.py`
- **Line(s):** 112, 233
- **Pattern:** Development-only code in production — `print(` matched the debug-logging pattern
- **Current code:**
```python
if __name__ == "__main__": # self-check — URL auth + redaction, no network
...
print("mirror self-check ok:", url)
```
- **Why it's noted:** Not slow — both `print` calls live behind `if __name__ == "__main__":` self-check guards and never run during CLI invocation or pytest. Flagged only because the literal pattern matched.
- **Optimal fix:** None required (intended self-check convention). Removable without behavior change if zero-noise is desired.
- **Estimated impact:** None.
*Checked and clean:* unoptimized build config (N/A — Python, no bundler), `__debug__`/`python -O` flags (no `__debug__` usage), heavy/wildcard imports (none), circular imports (none), real I/O in tests (tests use `httpx.MockTransport`, no network), disabled pytest parallelization (suite is 4 small files — xdist would be YAGNI).
---
### Security-Performance
No issues found. Checked: expensive-crypto-in-hot-paths (bcrypt/hashlib/jwt/hmac/sign/encrypt → 0 matches), ReDoS regex patterns (3 static module-level regexes in `refs.py`/`mirror.py` — all linear, no nested quantifiers like `(.*)+`/`(a+)+`, no user-input regex compilation), SQL string concatenation (no DB layer → 0), rate-limited web endpoints (no web server — CLI migrator; client-side pacing belongs to Concurrency/I/O), repeated authorization checks in loops (`.can`/`authorize`/`isAllowed`/`hasPermission` → 0).
---
### Logging & Observability
No issues found. Checked: `print()` in production paths (2, both in `__main__` self-checks — excluded as non-production), f-string/`.format()`/string-concat in log calls (0 matches — all 12 log sites use lazy `%s` formatting), logging inside loops (5 per-item INFO logs dominated by HTTP I/O — intended CLI progress, not hot-loop spam), synchronous file logging (none — stderr `StreamHandler` via `basicConfig` only), structured-logging gap (N/A for interactive CLI), request/trace IDs (N/A — no web framework). The logging layer follows best practice: module loggers via `logging.getLogger(__name__)`, level gated by `--verbose`, and consistently lazy `%s` argument formatting at every call site.
---
## Findings by File
### `src/codeberg_to_gitea_migrator/clients.py`
| # | Severity | Domain | Pattern | Fix summary | Impact |
|---|----------|--------|---------|-------------|--------|
| 1 | High | Concurrency | Sync HTTP layer | `httpx.AsyncClient` + bounded gather | 5–10× faster |
| 2 | High | I/O | All writes serialize | AsyncClient + overlap independent writes | Several-fold faster |
| 3 | Medium | I/O | `raw_get` buffers whole body | Streaming `iter_bytes` variant | Fixed low memory |
| 4 | Medium | Error | 30s timeout on bulk transfers | `httpx.Timeout(read=600, write=600)` for assets | No mid-transfer timeouts |
| 5 | Medium | Error | No circuit breaker | Consecutive-failure threshold → abort | Seconds vs. hours on outage |
| 6 | Medium | Concurrency | Sequential pagination | Read `X-Total-Count`, fan out pages | Helps many-page lists |
| 7 | Low | Error | No jitter on backoff | Full-jitter multiplier | Avoids retry storms |
| 8 | Low | Memory | `get_all` materializes to list | Streaming `paged()` where sets are large | Bounded memory |
### `src/codeberg_to_gitea_migrator/issues.py`
| # | Severity | Domain | Pattern | Fix summary | Impact |
|---|----------|--------|---------|-------------|--------|
| 1 | High | Concurrency | Nested sequential comment POSTs | Collect pairs, bounded gather | Removes dominant serialization |
| 2 | Medium | Database | Milestone via redundant PATCH | Set `milestone` in create body | −1 RTT per milestoned item |
| 3 | Medium | Database | N+1 per-issue comment fetch | Parallelize (no bulk endpoint) | Cuts comment-pass wall time |
| 4 | Medium | Concurrency | Sequential label/milestone create | Gather POSTs, build maps from results | Removes one serial stage |
| 5 | Low | Memory | Full issue/PR set held two-pass | Single-pass create+rewrite | ~halves peak memory |
| 6 | Low | Dead Code | Duplicate `_path` helper | Import shared `_path` | DRY, no drift |
### `src/codeberg_to_gitea_migrator/releases.py`
| # | Severity | Domain | Pattern | Fix summary | Impact |
|---|----------|--------|---------|-------------|--------|
| 1 | High | Concurrency / I/O | Sequential asset download+upload | Bounded gather over assets | Multiple-fold faster |
| 2 | Low | Dead Code | Duplicate `_path` helper | Import shared `_path` | DRY, no drift |
### `src/codeberg_to_gitea_migrator/mirror.py`
| # | Severity | Domain | Pattern | Fix summary | Impact |
|---|----------|--------|---------|-------------|--------|
| 1 | High | Error | No git subprocess timeout | `timeout=` + `TimeoutExpired` → `GitError` | Bounded hang, diagnosable |
| 2 | Medium | I/O | One `git push` per PR branch | Batch refspecs in one push | N connections → 1 |
| 3 | Low | Concurrency | Per-ref `update-ref` spawns | `update-ref --stdin` batch | N spawns → 1 |
| 4 | Low | Error | Malformed PR refs skipped silently | `log.warning` before `continue` | Traceability |
| 5 | Low | Dead Code | Duplicated `_run`/`_run_capture` block | `_run` wraps `_run_capture` | −8 lines, no drift |
| 6 | Info | Error | Best-effort `chmod` swallowed | Intentional — no change | None |
### `src/codeberg_to_gitea_migrator/migrate.py`
| # | Severity | Domain | Pattern | Fix summary | Impact |
|---|----------|--------|---------|-------------|--------|
| 1 | High | I/O | Entire migration synchronous | Async orchestration (see clients.py) | Several-fold faster |
### `src/codeberg_to_gitea_migrator/refs.py`
| # | Severity | Domain | Pattern | Fix summary | Impact |
|---|----------|--------|---------|-------------|--------|
| 1 | Low | Caching | Per-call root normalization | Precompute in `RefCtx.__post_init__` | Marginal (microseconds) |
| 2 | Info | Build | Guarded `print()` self-check | Intentional — no change | None |
### `.gitea/workflows/ci.yml`
| # | Severity | Domain | Pattern | Fix summary | Impact |
|---|----------|--------|---------|-------------|--------|
| 1 | Low | Build | No uv cache in CI | `setup-uv enable-cache` or `cache: uv` | 10–30s per CI run |
---
## Risk Score Breakdown
Scoring: Critical = 10, High = 7, Medium = 4, Low = 2, Info = 0.
| Domain | Critical | High | Medium | Low | Info | Points |
|--------|----------|------|--------|-----|------|--------|
| Database & Queries | 0 | 0 | 2 | 0 | 0 | 8 |
| Memory & Resources | 0 | 0 | 1 | 1 | 0 | 6 |
| Algorithmic Complexity | 0 | 0 | 0 | 0 | 0 | 0 |
| Concurrency & Async | 0 | 3 | 2 | 1 | 0 | 31 |
| Bundle & Dependencies | 0 | 0 | 0 | 0 | 0 | 0 |
| Dead Code & Redundancy | 0 | 0 | 0 | 2 | 0 | 4 |
| I/O & Network | 0 | 2 | 2 | 0 | 0 | 22 |
| Rendering & UI | 0 | 0 | 0 | 0 | 0 | 0 |
| Data Structures | 0 | 0 | 0 | 0 | 0 | 0 |
| Error & Resilience | 0 | 1 | 2 | 2 | 2 | 19 |
| Caching & Memoization | 0 | 0 | 0 | 1 | 0 | 2 |
| Build & Compilation | 0 | 0 | 0 | 1 | 1 | 2 |
| Security-Performance | 0 | 0 | 0 | 0 | 0 | 0 |
| Logging & Observability | 0 | 0 | 0 | 0 | 0 | 0 |
| **Total** | **0** | **6** | **9** | **8** | **3** | **94** |
**Risk Rating:** 0–10 = Low | 11–30 = Moderate | 31–60 = High | 61+ = Critical → **Critical (94)**
The Critical rating reflects the cumulative cost of fully-serialized I/O at migration scale. There are **zero Critical-severity findings** and the codebase is clean on 6 of 13 domains; the score is driven by High-severity serialization issues that are concentrated in one architectural change (async).
---
## Improvement Plan
Priority-ordered by impact in this codebase.
1. **[High] Asyncify the HTTP client and overlap independent writes** (`clients.py`, `issues.py`, `migrate.py`)
- Current: fully synchronous `httpx.Client`; every round-trip serialized.
- Fix: `httpx.AsyncClient` + bounded `asyncio.gather` (cap tuned to the forge rate limit) for labels, milestones, Pass-B comment batches, and release assets. Keep issue-number mapping serial.
- Impact: wall-time from ≈ Σ(RTT) toward ≈ max(batch) per phase — typically **5–10× faster** on issue/comment-heavy repos. *This is the single highest-leverage change and resolves the root cause behind four High findings.*
2. **[High] Stream release assets + upload concurrently** (`clients.py:98-101`, `releases.py:57-63`)
- Current: each asset downloaded whole into RAM, then uploaded one at a time.
- Fix: streaming `raw_get` (spooled temp file / `iter_bytes`) + bounded gather across assets.
- Impact: peak memory from O(max asset) to ~1 MiB; transfer time multiple-fold faster for binary releases.
3. **[High] Add a timeout to git subprocess calls** (`mirror.py:70-73`)
- Current: `subprocess.run` with no `timeout=` — `clone`/`fetch`/`push --mirror` can hang forever.
- Fix: `timeout=` + `TimeoutExpired` → `GitError`, overridable via `--git-timeout`.
- Impact: converts an indefinite unattended-cutover hang into a bounded, diagnosable failure.
4. **[Medium] Set milestone in the issue create body** (`issues.py:150-178`)
- Current: create issue, then a follow-up PATCH to set milestone.
- Fix: include `milestone` in the POST body; drop the PATCH.
- Impact: −1 round-trip per milestoned item.
5. **[Medium] Add a circuit breaker for a degraded target** (`clients.py`, `issues.py:199-201`)
- Current: per-call retries + per-item skip; a sustained outage grinds for hours.
- Fix: consecutive-failure threshold that raises `MigrationError` once N calls exhaust retries.
- Impact: aborts in seconds instead of churning through every remaining item.
6. **[Medium] Larger, write-aware timeout for bulk transfers** (`clients.py:38`)
- Current: single 30s timeout on read+write; large assets time out and re-upload repeatedly.
- Fix: `httpx.Timeout(read=600, write=600)` on `raw_get`/`post_multipart`.
- Impact: large-binary repos complete instead of fail-or-flail.
7. **[Medium] Batch git operations** (`mirror.py:99-100`, `201-211`)
- Current: one `git push` per PR-head branch; one `update-ref -d` per ref.
- Fix: batch refspecs in a single `git push`; `update-ref --stdin` for ref deletion.
- Impact: N process spawns + N connections → 1.
8. **[Low] Add jitter to retry backoff** (`clients.py:69`)
- Fix: full-jitter multiplier on the exponential backoff.
- Impact: avoids synchronized retry storms when multiple clients share a forge rate limit.
9. **[Low] Enable uv cache in CI** (`.gitea/workflows/ci.yml`)
- Fix: `astral-sh/setup-uv enable-cache` or `setup-python` `cache: uv`.
- Impact: 10–30s saved per CI run; no production effect.
10. **[Low] DRY helpers** (`issues.py`/`releases.py` `_path`; `mirror.py` `_run`/`_run_capture`)
- Fix: import shared `_path`; collapse `_run` into a `_run_capture` wrapper.
- Impact: removes ~10 lines of duplication and drift risk; zero runtime effect.
11. **[Low] Log skipped PR refs** (`mirror.py:124-127`) — restore traceability of unparseable refs.
12. **[Low] Precompute normalized web roots** (`refs.py:70-71`) — move constant normalization into `RefCtx.__post_init__`; marginal.
---
## Methodology
Pattern-based static analysis across 13 performance domains. Each domain was scanned by a specialist sub-agent using anti-anchoring methodology — the agent reads its reference file first, scans the codebase with Grep/Glob for known anti-patterns, and reads only 5–10 lines of context per match to confirm. This avoids accepting existing implementations as "reasonable" by default.
Domains with no applicable surface for this stack were still scanned and reported as "No issues found" (Algorithmic Complexity, Bundle & Dependencies, Data Structures, Rendering & UI, Security-Performance, Logging & Observability). Findings that the same code triggered across multiple domains were cross-referenced rather than duplicated (notably the release-asset loop, reported under Concurrency, I/O, and Memory; and the synchronous-client root cause, reported under Concurrency and I/O).
**Execution note:** The first parallel batch (13 agents) hit a provider rate-limit; 5 domains were re-run sequentially with `acceptance:false` so read-only analysis would not be mis-flagged. All 13 domains were ultimately covered.
**Limitations:** Static analysis only — no profiling, load testing, or runtime measurement. Estimated impacts are qualitative; actual gains depend on repo size, asset sizes, network conditions, and the forge's rate limit. The concurrency estimates in particular assume the chosen cap stays under the target's rate limit (the existing 429 backoff detects throttling). Some issues (e.g. unbounded hang on a stalled git push) are only discoverable under degraded-network conditions.
+1 -1
View File
@@ -12,7 +12,7 @@ license = "GPL-3.0-or-later"
license-files = ["LICENSE"]
authors = [{ name = "Alexander Kucera", email = "a.kucera@babylondreams.de" }]
keywords = ["migration", "codeberg", "gitea", "forgejo", "repository-migration"]
dependencies = ["httpx>=0.27", "typer>=0.12"]
dependencies = ["httpx>=0.27"]
[project.optional-dependencies]
dev = ["pytest", "ruff"]
+7 -6
View File
@@ -18,18 +18,18 @@ Console script: `codeberg-to-gitea`.
- `src/` layout; wheel `packages = ["src/codeberg_to_gitea_migrator"]` (root `pyproject.toml`).
- `__init__.py` holds the single `__version__` string — the version source of truth for the build.
- Distribution name `codeberg-to-gitea-migrator`; import name `codeberg_to_gitea_migrator` (dashes → underscores).
- Runtime deps (root `pyproject.toml`): `httpx` (HTTP), `typer` (CLI). Dev: `pytest`, `ruff`.
- Runtime deps (root `pyproject.toml`): `httpx` (HTTP). CLI is stdlib `argparse` (no CLI dep). Dev: `pytest`, `ruff`.
- Forgejo and Gitea share one REST API; `clients.ApiClient` is instantiated twice — once for source (read), once for target (write).
## Module map
- `clients.py` — `ApiClient`: bearer auth, transparent pagination (`page`/`limit`), retry on 429/5xx, `get/post/patch/delete`, `raw_get` (binary), `post_multipart` (asset upload).
- `mirror.py` — `git clone --mirror` + `push --mirror`; captures `refs/pull/<n>/head` SHAs and recreates them as target branches `refs/heads/_pr/<n>` (so deleted-branch PRs survive), prunes Forgejo-internal `refs/pull/*` before push, mirrors LFS objects. Tokens are masked in any `GitError` and scrubbed from the on-disk remote config after each run; the mirror workdir is per-user `0700`.
- `clients.py` — `ApiClient`: bearer auth, transparent pagination (`page`/`limit`), retry on 429/5xx with full jitter, `get/post/patch/delete`, `raw_get_stream` (binary download streamed to a spooled temp file), `post_multipart` (asset upload). Thread-safe (one underlying `httpx.Client` per thread via a thread-local), so a single client serves concurrent requests; circuit breaker (`CircuitOpenError`) trips after N consecutive exhausted-retry failures; `_path` helper + `parallel(items, fn, workers=, executor=)` live here.
- `mirror.py` — `git clone --mirror` + `push --mirror`; captures `refs/pull/<n>/head` SHAs and recreates them as target branches `refs/heads/_pr/<n>` (so deleted-branch PRs survive), prunes Forgejo-internal `refs/pull/*` before push, mirrors LFS objects. Tokens are masked in any `GitError` and scrubbed from the on-disk remote config after each run; the mirror workdir is per-user `0700`. Every network git op runs under a per-op timeout (`DEFAULT_GIT_TIMEOUT`, `--git-timeout`); PR-head pushes and `refs/pull/*` pruning are batched into a single `git push` / `update-ref --stdin`.
- `refs.py` — `NumberMap` + `rewrite`: rewrites `#NNN` refs and source issue/PR URLs to the target's fresh number space (source numbers are sparse after deletions).
- `issues.py` — labels, milestones, issues + PRs + comments. Two-pass: create in source-number order (build number map), then rewrite title/body refs + stream comments. PR head falls back to `_pr/<n>` when the source branch is gone.
- `releases.py` — non-draft releases + asset re-upload. Treats a 404 releases endpoint (feature disabled) as "none".
- `issues.py` — labels, milestones, issues + PRs + comments. Two-pass: create in source-number order (build number map), then rewrite title/body refs + stream comments. PR head falls back to `_pr/<n>` when the source branch is gone. Pass A (creation) is serial (ordered); labels/milestones and Pass B (ref rewrite + comments) overlap via `parallel`. Issues carry their milestone in the create body; PRs still PATCH it (pull-create has no milestone field).
- `releases.py` — non-draft releases + asset re-upload. Assets stream through `raw_get_stream` (bounded memory) and upload concurrently within a release. Treats a 404 releases endpoint (feature disabled) as "none".
- `migrate.py` — `migrate_repo` orchestrator: creates/validates the target repo, runs the pipeline, returns a report.
- `cli.py` — `codeberg-to-gitea migrate` Typer entrypoint. Tokens via `CODEBERG_TOKEN` / `GITEA_TOKEN` env or flags. `--repo owner/name` (or bare `name`).
- `cli.py` — `codeberg-to-gitea migrate` argparse entrypoint (`app()`). Tokens via `CODEBERG_TOKEN` / `GITEA_TOKEN` env or flags. `--repo owner/name` (or bare `name`). `--concurrency` (parallel independent writes, default 8), `--git-timeout` (per-op git timeout, default 1800s); catches `CircuitOpenError`.
## Work Guidance
@@ -40,6 +40,7 @@ Console script: `codeberg-to-gitea`.
- Repo creation needs the target token to have `write:user` scope; otherwise create the empty repo by hand first (the migrator then populates a fresh target).
- Migration is intentionally one-shot per repo (cutover model): populate a fresh target once, then freeze the source. There is no incremental/delta sync; re-running on a populated target refuses unless `--delete-existing`, which wipes and redoes everything with fresh numbers. Incremental `--update` was considered and deliberately not built.
- Forge API tokens are secrets: the mirror path never lets them reach logs, exceptions, or the persisted `/tmp/cb2gitea-<uid>/.git/config`. Don't reintroduce bare tokens into error messages or stored URLs.
- Execution model: a single `ApiClient` is thread-safe (per-thread underlying `httpx.Client`), so the migration overlaps independent writes via `parallel(..., workers=concurrency)`. Pass A issue/PR creation stays serial — entities are created in source-number order so the number map can rewrite forward cross-references. `--concurrency` sizes the pool (default 8); `--git-timeout` bounds network git ops (default 1800s). Tune `--concurrency` down if the target forge rate-limits hard — the jittered 429 backoff + circuit breaker handle it, but lower concurrency is gentler.
## Verification
+93 -61
View File
@@ -7,92 +7,124 @@ CODEBERG_TOKEN=*** GITEA_TOKEN=*** codeberg-to-gitea migrate AlexKucera/helm
Both tokens may be passed as flags or via the ``CODEBERG_TOKEN`` / ``GITEA_TOKEN``
env vars. ``--repo`` accepts ``owner/name`` or a bare ``name`` (owner defaults
to the source-forge authenticated user).
Uses stdlib ``argparse`` (no CLI dependency).
"""
from __future__ import annotations
import argparse
import logging
import typer
import os
import sys
from . import __version__
from .clients import ApiClient, ApiError
from .clients import ApiClient, ApiError, CircuitOpenError
from .migrate import DEFAULT_SOURCE, DEFAULT_TARGET, MigrationError, migrate_repo
from .mirror import GitError
from .mirror import DEFAULT_GIT_TIMEOUT, GitError
app = typer.Typer(
name="codeberg-to-gitea",
help="Migrate a Codeberg (Forgejo) repo to a self-hosted Gitea instance.",
no_args_is_help=True,
add_completion=False,
)
PROG = "codeberg-to-gitea"
@app.command()
def migrate(
repo: str = typer.Argument(
..., help="Source repo as 'owner/name', or just 'name' (owner defaults to your user)."
),
source_url: str = typer.Option(DEFAULT_SOURCE, "--source-url", help="Source forge base URL."),
target_url: str = typer.Option(DEFAULT_TARGET, "--target-url", help="Target Gitea base URL."),
source_token: str = typer.Option(
"", "--source-token", envvar="CODEBERG_TOKEN", help="Source forge API token."
),
target_token: str = typer.Option(
"", "--target-token", envvar="GITEA_TOKEN", help="Target Gitea API token."
),
delete_existing: bool = typer.Option(
False, "--delete-existing", help="Delete the target repo first (one-shot re-run)."
),
skip_git: bool = typer.Option(False, "--skip-git", help="Skip the git mirror."),
skip_issues: bool = typer.Option(
False, "--skip-issues", help="Skip issues/PRs/labels/milestones."
),
skip_releases: bool = typer.Option(False, "--skip-releases", help="Skip releases + assets."),
verbose: bool = typer.Option(False, "-v", "--verbose", help="Verbose logging."),
) -> None:
"""Migrate a single repository from source to target forge."""
def _die(msg: str, code: int = 1) -> None:
print(f"{PROG}: {msg}", file=sys.stderr)
raise SystemExit(code)
def app(argv: list[str] | None = None) -> None:
parser = argparse.ArgumentParser(
prog=PROG,
description="Migrate a Codeberg (Forgejo) repo to a self-hosted Gitea instance.",
)
sub = parser.add_subparsers(dest="command", metavar="<command>")
m = sub.add_parser("migrate", help="Migrate a single repository from source to target forge.")
m.add_argument(
"repo",
help="Source repo as 'owner/name', or just 'name' (owner defaults to your user).",
)
m.add_argument("--source-url", default=DEFAULT_SOURCE, help="Source forge base URL.")
m.add_argument("--target-url", default=DEFAULT_TARGET, help="Target Gitea base URL.")
m.add_argument(
"--source-token",
default=os.environ.get("CODEBERG_TOKEN", ""),
help="Source forge API token (or CODEBERG_TOKEN env).",
)
m.add_argument(
"--target-token",
default=os.environ.get("GITEA_TOKEN", ""),
help="Target Gitea API token (or GITEA_TOKEN env).",
)
m.add_argument(
"--delete-existing",
action="store_true",
help="Delete the target repo first (one-shot re-run).",
)
m.add_argument("--skip-git", action="store_true", help="Skip the git mirror.")
m.add_argument("--skip-issues", action="store_true", help="Skip issues/PRs/labels/milestones.")
m.add_argument("--skip-releases", action="store_true", help="Skip releases + assets.")
m.add_argument(
"--concurrency",
type=int,
default=8,
help="Parallel requests for independent writes (labels, comments, assets).",
)
m.add_argument(
"--git-timeout",
type=int,
default=int(DEFAULT_GIT_TIMEOUT),
help="Per-op timeout (seconds) for network git ops (clone/fetch/push).",
)
m.add_argument("-v", "--verbose", action="store_true", help="Verbose logging.")
sub.add_parser("version", help="Print the migrator version.")
args = parser.parse_args(argv)
if args.command is None:
parser.print_help()
return
if args.command == "version":
print(__version__)
return
_migrate(args)
def _migrate(args: argparse.Namespace) -> None:
logging.basicConfig(
level=logging.DEBUG if verbose else logging.INFO,
level=logging.DEBUG if args.verbose else logging.INFO,
format="%(levelname)s %(name)s: %(message)s",
)
if not source_token or not target_token:
raise typer.BadParameter(
"Both tokens are required (flags or CODEBERG_TOKEN/GITEA_TOKEN env)."
)
if not args.source_token or not args.target_token:
_die("both tokens are required (flags or CODEBERG_TOKEN/GITEA_TOKEN env).", code=2)
owner, name = _parse_repo(repo, source_url, source_token)
owner, name = _parse_repo(args.repo, args.source_url, args.source_token)
try:
report = migrate_repo(
source_url=source_url,
target_url=target_url,
source_url=args.source_url,
target_url=args.target_url,
owner=owner,
name=name,
source_token=source_token,
target_token=target_token,
delete_existing=delete_existing,
skip_git=skip_git,
skip_issues=skip_issues,
skip_releases=skip_releases,
source_token=args.source_token,
target_token=args.target_token,
delete_existing=args.delete_existing,
skip_git=args.skip_git,
skip_issues=args.skip_issues,
skip_releases=args.skip_releases,
concurrency=args.concurrency,
git_timeout=args.git_timeout,
)
except MigrationError as exc:
raise typer.BadParameter(str(exc)) from exc
_die(str(exc), code=2)
except CircuitOpenError as exc:
_die(f"aborting: {exc}")
except ApiError as exc:
typer.echo(f"API error: {exc}", err=True)
raise typer.Exit(1) from exc
_die(f"API error: {exc}")
except GitError as exc:
typer.echo(f"git error: {exc}", err=True)
raise typer.Exit(1) from exc
_die(f"git error: {exc}")
typer.echo(f"✓ migrated {owner}/{name}: {report}")
@app.command()
def version() -> None:
"""Print the migrator version."""
typer.echo(__version__)
print(f"✓ migrated {owner}/{name}: {report}")
def _parse_repo(repo: str, source_url: str, source_token: str) -> tuple[str, str]:
@@ -104,7 +136,7 @@ def _parse_repo(repo: str, source_url: str, source_token: str) -> tuple[str, str
me = src.get("/user")
login = me.get("login")
if not login:
raise typer.BadParameter("could not resolve source user to default the owner")
_die("could not resolve source user to default the owner.", code=2)
return login, repo
+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] = {}
+56 -36
View File
@@ -14,6 +14,11 @@ Issue/PR numbers share one sequence on both forges, and source numbers are
sparse (deleted issues leave gaps), so the rewrite pass is what keeps migrated
cross-references honest.
Pass A is inherently serial (entities must be created in source-number order so
the number map resolves forward references). Pass B, plus label/milestone
creation, are independent across items and overlap through
:func:`codeberg_to_gitea_migrator.clients.parallel`.
Known fidelity limits (the public Gitea API stamps these server-side): original
author (attributed to the migration token user), original timestamps, and
assignees/reactions.
@@ -25,7 +30,7 @@ import logging
from dataclasses import dataclass
from typing import Any
from .clients import ApiClient, ApiError
from .clients import ApiClient, ApiError, _path, parallel
from .refs import NumberMap, rewrite
log = logging.getLogger(__name__)
@@ -46,18 +51,19 @@ class RefCtx:
)
def _path(owner: str, repo: str, suffix: str = "") -> str:
return f"/repos/{owner}/{repo}{suffix}"
# -- labels ---------------------------------------------------------------
def migrate_labels(
src: ApiClient, tgt: ApiClient, owner: str, repo: str
) -> tuple[dict[int, int], dict[str, int]]:
"""Recreate labels on target. Returns (old_id→new_id, name→new_id)."""
id_map: dict[int, int] = {}
name_map: dict[str, int] = {}
for label in src.get_all(_path(owner, repo, "/labels")):
src: ApiClient,
tgt: ApiClient,
owner: str,
repo: str,
*,
concurrency: int = 1,
) -> dict[int, int]:
"""Recreate labels on target. Returns old_id→new_id."""
labels = src.get_all(_path(owner, repo, "/labels"))
def make(label: dict) -> tuple[dict, dict]:
body = {
"name": label["name"],
"color": label.get("color", "ededed"),
@@ -66,18 +72,21 @@ def migrate_labels(
"is_archived": bool(label.get("is_archived", False)),
}
created = tgt.post(_path(owner, repo, "/labels"), body=body)
new_id = created["id"]
id_map[label["id"]] = new_id
name_map[label["name"]] = new_id
log.info("label %s → #%s", label["name"], new_id)
return id_map, name_map
log.info("label %s → #%s", label["name"], created["id"])
return label, created
results = parallel(labels, make, workers=concurrency)
return {lab["id"]: created["id"] for lab, created in results}
# -- milestones -----------------------------------------------------------
def migrate_milestones(src: ApiClient, tgt: ApiClient, owner: str, repo: str) -> dict[int, int]:
def migrate_milestones(
src: ApiClient, tgt: ApiClient, owner: str, repo: str, *, concurrency: int = 1
) -> dict[int, int]:
"""Recreate milestones on target. Returns old_id→new_id."""
id_map: dict[int, int] = {}
for ms in src.get_all(_path(owner, repo, "/milestones"), state="all"):
milestones = src.get_all(_path(owner, repo, "/milestones"), state="all")
def make(ms: dict) -> tuple[dict, dict]:
body: dict[str, Any] = {
"title": ms["title"],
"description": ms.get("description") or "",
@@ -86,9 +95,11 @@ def migrate_milestones(src: ApiClient, tgt: ApiClient, owner: str, repo: str) ->
if ms.get("due_on"):
body["due_on"] = ms["due_on"]
created = tgt.post(_path(owner, repo, "/milestones"), body=body)
id_map[ms["id"]] = created["id"]
log.info("milestone %s → #%s", ms["title"], created["id"])
return id_map
return ms, created
results = parallel(milestones, make, workers=concurrency)
return {ms["id"]: created["id"] for ms, created in results}
# -- issues + PRs ---------------------------------------------------------
@@ -144,13 +155,21 @@ def _create_entity(
milestone_map: dict[int, int],
) -> int:
"""Create an issue or PR; return its new number. Raises on PR-create failure
(e.g. head branch gone) so the caller can skip cleanly."""
(e.g. head branch gone) so the caller can skip cleanly.
Issues carry their milestone in the create body (one request); PRs can't
(the pull-create endpoint has no milestone field), so they still take a
follow-up PATCH.
"""
kind = item["_kind"]
ms = item.get("milestone")
ms_id = milestone_map[ms["id"]] if ms and ms.get("id") in milestone_map else None
if kind == "issue":
created = tgt.post(
_path(owner, repo, "/issues"),
body={"title": item["title"], "body": item.get("body") or ""},
)
body: dict[str, Any] = {"title": item["title"], "body": item.get("body") or ""}
if ms_id is not None:
body["milestone"] = ms_id
created = tgt.post(_path(owner, repo, "/issues"), body=body)
else:
head = item.get("head", {}) or {}
base = (item.get("base", {}) or {}).get("ref", "main")
@@ -168,14 +187,9 @@ def _create_entity(
"base": base,
},
)
new_number = created["number"]
ms = item.get("milestone")
if ms and ms.get("id") in milestone_map:
tgt.patch(
_path(owner, repo, f"/issues/{new_number}"),
body={"milestone": milestone_map[ms["id"]]},
)
return new_number
if ms_id is not None:
tgt.patch(_path(owner, repo, f"/issues/{created['number']}"), body={"milestone": ms_id})
return created["number"]
def migrate_issues_and_prs(
@@ -186,6 +200,8 @@ def migrate_issues_and_prs(
label_id_map: dict[int, int],
milestone_map: dict[int, int],
ref: RefCtx,
*,
concurrency: int = 1,
) -> NumberMap:
"""Migrate issues + PRs + comments, returning the source→target number map."""
numbers = ref.numbers
@@ -220,8 +236,11 @@ def migrate_issues_and_prs(
created.append((item, new_number))
log.info("%s #%s → #%s (%s)", kind, item["number"], new_number, item["title"])
# Pass B: rewrite refs in title+body, then stream comments.
for item, new_number in created:
# Pass B: rewrite refs in title+body, then stream comments. Items are
# independent of each other (the number map is already complete), so they
# overlap; each item's comments stay sequential to preserve their order.
def pass_b(pair: tuple[dict, int]) -> None:
item, new_number = pair
new_title = ref(item.get("title"))
new_body = ref(item.get("body"))
tgt.patch(
@@ -234,4 +253,5 @@ def migrate_issues_and_prs(
body={"body": ref(comment.get("body"))},
)
parallel(created, pass_b, workers=concurrency)
return numbers
+12 -5
View File
@@ -15,7 +15,7 @@ from pathlib import Path
from .clients import ApiClient, ApiError
from .issues import RefCtx, migrate_issues_and_prs, migrate_labels, migrate_milestones
from .mirror import mirror_repo
from .mirror import DEFAULT_GIT_TIMEOUT, mirror_repo
from .refs import NumberMap
from .releases import migrate_releases
@@ -124,6 +124,8 @@ def migrate_repo(
skip_git: bool = False,
skip_issues: bool = False,
skip_releases: bool = False,
concurrency: int = 8,
git_timeout: float = DEFAULT_GIT_TIMEOUT,
) -> dict:
"""Migrate one repo from source forge to target forge. Returns a report."""
if not source_token or not target_token:
@@ -153,20 +155,25 @@ def migrate_repo(
source_token=source_token,
target_token=target_token,
workdir=workdir,
git_timeout=git_timeout,
)
report["git"] = git_report
log.info("git mirror done: %s", git_report)
if not skip_issues:
label_id_map, _name_map = migrate_labels(src, tgt, owner, name)
milestone_map = migrate_milestones(src, tgt, owner, name)
migrate_issues_and_prs(src, tgt, owner, name, label_id_map, milestone_map, ref)
label_id_map = migrate_labels(src, tgt, owner, name, concurrency=concurrency)
milestone_map = migrate_milestones(src, tgt, owner, name, concurrency=concurrency)
migrate_issues_and_prs(
src, tgt, owner, name, label_id_map, milestone_map, ref, concurrency=concurrency
)
report["labels"] = len(label_id_map)
report["milestones"] = len(milestone_map)
report["issues_prs"] = len(numbers)
if not skip_releases:
report["releases"] = migrate_releases(src, tgt, owner, name, ref)
report["releases"] = migrate_releases(
src, tgt, owner, name, ref, concurrency=concurrency
)
log.info("migration complete: %s", report)
return report
+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)}
-1
View File
@@ -56,7 +56,6 @@ def rewrite(
*,
source_web_root: str,
target_web_root: str,
owner_repo: str | None = None,
) -> str | None:
"""Rewrite ``#NNN`` refs and source URLs in ``text`` to target numbers.
+41 -26
View File
@@ -4,28 +4,33 @@ Git tags (which releases hang off) already arrived via the git mirror, so this
module only needs to (re)create each release record on the target and re-upload
its assets. Drafts are skipped — the target forge can't recreate a draft under
its true author, and a draft published under the token user would mislead.
Asset *downloads* stream through a spooled temp file (``raw_get_stream``) so
download memory is bounded regardless of asset size; the *upload* still
buffers the full asset (httpx materializes the multipart body), so overall peak
memory is ~one asset per in-flight worker, not two. A single executor spans all
releases so worker threads (and their thread-local clients) are reused.
"""
from __future__ import annotations
import logging
from concurrent.futures import ThreadPoolExecutor
from .clients import ApiClient, ApiError
from .clients import ApiClient, ApiError, _path, parallel
from .issues import RefCtx
log = logging.getLogger(__name__)
def _path(owner: str, repo: str, suffix: str = "") -> str:
return f"/repos/{owner}/{repo}{suffix}"
def migrate_releases(
src: ApiClient,
tgt: ApiClient,
owner: str,
repo: str,
ref: RefCtx,
*,
concurrency: int = 1,
) -> int:
"""Recreate non-draft releases + assets on target. Returns count migrated."""
try:
@@ -42,26 +47,36 @@ def migrate_releases(
releases.sort(key=lambda r: r.get("created_at", ""))
count = 0
for rel in releases:
body = {
"tag_name": rel["tag_name"],
"name": rel.get("name") or rel["tag_name"],
"body": ref(rel.get("body")),
"draft": False,
"prerelease": bool(rel.get("prerelease")),
"target_commitish": (rel.get("target_commitish") or "main"),
}
created = tgt.post(_path(owner, repo, "/releases"), body=body)
new_id = created["id"]
# One executor spans all releases so worker threads (and their thread-local
# clients) are reused, not re-created per release.
with ThreadPoolExecutor(max_workers=max(concurrency, 1)) as ex:
for rel in releases:
body = {
"tag_name": rel["tag_name"],
"name": rel.get("name") or rel["tag_name"],
"body": ref(rel.get("body")),
"draft": False,
"prerelease": bool(rel.get("prerelease")),
"target_commitish": (rel.get("target_commitish") or "main"),
}
created = tgt.post(_path(owner, repo, "/releases"), body=body)
new_id = created["id"]
for asset in rel.get("assets", []) or []:
data = src.raw_get(_path(owner, repo, f"/releases/{rel['id']}/assets/{asset['id']}"))
tgt.post_multipart(
_path(owner, repo, f"/releases/{new_id}/assets"),
files={"attachment": (asset["name"], data)},
name=asset["name"],
)
n_assets = len(rel.get("assets", []) or [])
log.info("release %s → #%s (%d assets)", rel["tag_name"], new_id, n_assets)
count += 1
assets = rel.get("assets", []) or []
def upload_asset(asset: dict) -> None:
# Stream the download to a spooled temp file (bounded download
# memory); the upload still buffers the full asset.
with src.raw_get_stream(
_path(owner, repo, f"/releases/{rel['id']}/assets/{asset['id']}")
) as data:
tgt.post_multipart(
_path(owner, repo, f"/releases/{new_id}/assets"),
files={"attachment": (asset["name"], data)},
name=asset["name"],
)
parallel(assets, upload_asset, workers=concurrency, executor=ex)
log.info("release %s → #%s (%d assets)", rel["tag_name"], new_id, len(assets))
count += 1
return count
+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]
Generated
-69
View File
@@ -2,15 +2,6 @@ version = 1
revision = 1
requires-python = ">=3.11"
[[package]]
name = "annotated-doc"
version = "0.0.5"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/5a/8e/38aa427ed5402449e226975b649c5dc73ccadfefeb95e6aecb8f8ea4b6b6/annotated_doc-0.0.5.tar.gz", hash = "sha256:c7e58ce09192557605d8bbd92836d7e1d520ac9580096042c0bfd197efacf1bb", size = 10758 }
wheels = [
{ url = "https://files.pythonhosted.org/packages/3e/30/e900b21425a860e195f32e37657aa1f7c7f2b1bfb26f03ca209b90933c06/annotated_doc-0.0.5-py3-none-any.whl", hash = "sha256:117bac03a25ede5df5440e855b32d556049ca169ead221505badf432fed4b101", size = 5302 },
]
[[package]]
name = "anyio"
version = "4.14.2"
@@ -39,7 +30,6 @@ version = "0.1.0"
source = { editable = "." }
dependencies = [
{ name = "httpx" },
{ name = "typer" },
]
[package.optional-dependencies]
@@ -53,7 +43,6 @@ requires-dist = [
{ name = "httpx", specifier = ">=0.27" },
{ name = "pytest", marker = "extra == 'dev'" },
{ name = "ruff", marker = "extra == 'dev'" },
{ name = "typer", specifier = ">=0.12" },
]
provides-extras = ["dev"]
@@ -121,27 +110,6 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/cb/b1/3846dd7f199d53cb17f49cba7e651e9ce294d8497c8c150530ed11865bb8/iniconfig-2.3.0-py3-none-any.whl", hash = "sha256:f631c04d2c48c52b84d0d0549c99ff3859c98df65b3101406327ecc7d53fbf12", size = 7484 },
]
[[package]]
name = "markdown-it-py"
version = "4.2.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "mdurl" },
]
sdist = { url = "https://files.pythonhosted.org/packages/06/ff/7841249c247aa650a76b9ee4bbaeae59370dc8bfd2f6c01f3630c35eb134/markdown_it_py-4.2.0.tar.gz", hash = "sha256:04a21681d6fbb623de53f6f364d352309d4094dd4194040a10fd51833e418d49", size = 82454 }
wheels = [
{ url = "https://files.pythonhosted.org/packages/b3/81/4da04ced5a082363ecfa159c010d200ecbd959ae410c10c0264a38cac0f5/markdown_it_py-4.2.0-py3-none-any.whl", hash = "sha256:9f7ebbcd14fe59494226453aed97c1070d83f8d24b6fc3a3bcf9a38092641c4a", size = 91687 },
]
[[package]]
name = "mdurl"
version = "0.1.2"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/d6/54/cfe61301667036ec958cb99bd3efefba235e65cdeb9c84d24a8293ba1d90/mdurl-0.1.2.tar.gz", hash = "sha256:bb413d29f5eea38f31dd4754dd7377d4465116fb207585f97bf925588687c1ba", size = 8729 }
wheels = [
{ url = "https://files.pythonhosted.org/packages/b3/38/89ba8ad64ae25be8de66a6d463314cf1eb366222074cfda9ee839c56a4b4/mdurl-0.1.2-py3-none-any.whl", hash = "sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8", size = 9979 },
]
[[package]]
name = "packaging"
version = "26.3"
@@ -185,19 +153,6 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/24/25/1de2678b631f5a49215c6c96fff41ba892b0a34df68d6d80292b1b48aa7f/pytest-9.1.1-py3-none-any.whl", hash = "sha256:37a86b45efb9a47a61a36449063e8e18d0cab3161329fc099eb21783169c4f0c", size = 386536 },
]
[[package]]
name = "rich"
version = "15.0.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "markdown-it-py" },
{ name = "pygments" },
]
sdist = { url = "https://files.pythonhosted.org/packages/c0/8f/0722ca900cc807c13a6a0c696dacf35430f72e0ec571c4275d2371fca3e9/rich-15.0.0.tar.gz", hash = "sha256:edd07a4824c6b40189fb7ac9bc4c52536e9780fbbfbddf6f1e2502c31b068c36", size = 230680 }
wheels = [
{ url = "https://files.pythonhosted.org/packages/82/3b/64d4899d73f91ba49a8c18a8ff3f0ea8f1c1d75481760df8c68ef5235bf5/rich-15.0.0-py3-none-any.whl", hash = "sha256:33bd4ef74232fb73fe9279a257718407f169c09b78a87ad3d296f548e27de0bb", size = 310654 },
]
[[package]]
name = "ruff"
version = "0.16.2"
@@ -223,30 +178,6 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/5b/6c/93e26c22c5f78ff87363e07da49c84955affbeb1098bd1936bf3b3f293bf/ruff-0.16.2-py3-none-win_arm64.whl", hash = "sha256:d614e95cedf38a2053fd351c55b103ba30d017d61688fdbfd40ee0412852a99f", size = 11374065 },
]
[[package]]
name = "shellingham"
version = "1.5.4"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/58/15/8b3609fd3830ef7b27b655beb4b4e9c62313a4e8da8c676e142cc210d58e/shellingham-1.5.4.tar.gz", hash = "sha256:8dbca0739d487e5bd35ab3ca4b36e11c4078f3a234bfce294b0a0291363404de", size = 10310 }
wheels = [
{ url = "https://files.pythonhosted.org/packages/e0/f9/0595336914c5619e5f28a1fb793285925a8cd4b432c9da0a987836c7f822/shellingham-1.5.4-py2.py3-none-any.whl", hash = "sha256:7ecfff8f2fd72616f7481040475a65b2bf8af90a56c89140852d1120324e8686", size = 9755 },
]
[[package]]
name = "typer"
version = "0.27.1"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "annotated-doc" },
{ name = "colorama", marker = "sys_platform == 'win32'" },
{ name = "rich" },
{ name = "shellingham" },
]
sdist = { url = "https://files.pythonhosted.org/packages/ae/40/4a3db7990d1f62a53182aa96eaef57aeb2886a27f90a195bc66713565d31/typer-0.27.1.tar.gz", hash = "sha256:a79bef8469a79c45498e7b814ecf8d603cc7644e9acbd9e19cac0334240b18df", size = 203994 }
wheels = [
{ url = "https://files.pythonhosted.org/packages/43/89/9518bc0c3929bee36b3a4a8e3daddd6e03f92f9961c66d4983b837160543/typer-0.27.1-py3-none-any.whl", hash = "sha256:53150287edd11baeb4e4722c8e394fcdf8181c0ae89485cba8d25c778d5edd56", size = 122874 },
]
[[package]]
name = "typing-extensions"
version = "4.16.0"