CI / test (push) Canceled after 0s
Introduce a frozen Migration handle binding the identity quintet (src/tgt clients, owner, name, NumberMap) the four entity phases previously received as five loose params. The phases now take the handle; migrate_repo builds one and drives all phases with it. Retire RefCtx and the shared _path helper (absorbed into the handle's .path()/.rewrite() accessors), deleting code rather than leaving dead types. migrate_issues_and_prs mutates m.numbers in place (returns None). Add tests/test_phases.py: the previously-untested entity layer is now reachable through the Migration seam (two mock-transport clients + a number map, no network), covering the two-pass issue/PR flow, label/milestone mappings, state-setting, best-effort PR merge, the deleted-branch head fallback, and release+asset re-upload. Closes #2
279 lines
11 KiB
Python
279 lines
11 KiB
Python
"""Thin, shared REST client for Forgejo (Codeberg) and Gitea.
|
||
|
||
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 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):
|
||
"""A non-2xx response from the forge API."""
|
||
|
||
def __init__(self, status: int, url: str, body: str) -> None:
|
||
super().__init__(f"{status} {url}: {body[:300]}")
|
||
self.status = status
|
||
self.url = url
|
||
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.
|
||
"""
|
||
|
||
|
||
class ApiClient:
|
||
"""Bearer-auth client over the Forgejo/Gitea REST API (``/api/v1``)."""
|
||
|
||
def __init__(
|
||
self,
|
||
base_url: str,
|
||
token: str,
|
||
*,
|
||
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._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
|
||
for attempt in range(self.max_retries + 1):
|
||
try:
|
||
resp = self._client.request(method, path, **kwargs)
|
||
except httpx.TransportError as exc:
|
||
last_err = exc
|
||
else:
|
||
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 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:
|
||
resp = self._request(method, path, **kwargs)
|
||
if resp.status_code >= 400:
|
||
raise ApiError(resp.status_code, str(resp.url), resp.text)
|
||
return resp
|
||
|
||
# -- verbs -------------------------------------------------------------
|
||
def get(self, path: str, **params: Any) -> Any:
|
||
resp = self.request("GET", path, params=_clean(params))
|
||
return resp.json() if resp.content else None
|
||
|
||
def post(self, path: str, body: Any | None = None, **kwargs: Any) -> Any:
|
||
resp = self.request("POST", path, json=body, **kwargs)
|
||
return resp.json() if resp.content else None
|
||
|
||
def patch(self, path: str, body: Any | None = None, **kwargs: Any) -> Any:
|
||
resp = self.request("PATCH", path, json=body, **kwargs)
|
||
return resp.json() if resp.content else None
|
||
|
||
def delete(self, path: str, **kwargs: Any) -> None:
|
||
self.request("DELETE", path, **kwargs)
|
||
|
||
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_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]:
|
||
"""Yield every item across all pages of a list endpoint."""
|
||
page = int(params.pop("page", 1))
|
||
limit = int(params.pop("limit", PAGE_SIZE))
|
||
while True:
|
||
batch = self.get(path, page=page, limit=limit, **params) or []
|
||
if not isinstance(batch, list):
|
||
raise ApiError(200, path, f"expected list, got {type(batch).__name__}")
|
||
yield from batch
|
||
if len(batch) < limit:
|
||
return
|
||
page += 1
|
||
|
||
def get_all(self, path: str, **params: Any) -> list[Any]:
|
||
return list(self.paged(path, **params))
|
||
|
||
def close(self) -> None:
|
||
with self._clients_lock:
|
||
for c in self._all_clients:
|
||
c.close()
|
||
self._all_clients.clear()
|
||
|
||
def __enter__(self) -> ApiClient:
|
||
return self
|
||
|
||
def __exit__(self, *exc: object) -> None:
|
||
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] = {}
|
||
for key, value in params.items():
|
||
if value is None:
|
||
continue
|
||
if isinstance(value, bool):
|
||
out[key] = "true" if value else "false"
|
||
else:
|
||
out[key] = value
|
||
return out
|