CI / test (push) Canceled after 0s
Pass-B writes (issue body rewrite + each comment) ran only at the caller's --concurrency, so a transient target 5xx either aborted the run or silently lost the write. A self-hosted Gitea throws bursts of 500s under concurrent writes, losing comments and leaving bodies with stale cross-refs. Failed writes are now deferred and replayed once serially (concurrency 1) after the concurrent wave -- serial load removes the backpressure causing the 500s, so nearly all recover. Writes still failing serially are logged and skipped; a genuinely-down target still aborts via CircuitOpenError. Adds two phase tests: persistent-fail (no abort) and transient (recover).
277 lines
11 KiB
Python
277 lines
11 KiB
Python
"""Migrate labels, milestones, issues, pull requests, and comments.
|
|
|
|
Two-pass design for issues + PRs:
|
|
|
|
* **Pass A** creates every issue/PR in ascending source-number order, sets its
|
|
state (and attempts to merge closed-and-merged PRs), and records the
|
|
source→target number mapping. Bodies are stored *unrewritten* here because
|
|
forward cross-references aren't resolvable yet.
|
|
* **Pass B** runs once the full number map is known: it rewrites
|
|
``#NNN`` refs / source URLs in each title+body (PATCH) and creates every
|
|
comment (rewritten), preserving comment order.
|
|
|
|
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.
|
|
|
|
Pass-B writes (the body rewrite and each comment) run at the caller's concurrency
|
|
first; any that hit a transient target ``ApiError`` are deferred and replayed
|
|
serially (concurrency 1) afterwards — serial load removes the concurrent-write
|
|
backpressure that causes bursts of 500s on a self-hosted target. Writes that
|
|
still fail serially are logged and skipped, so a flaky 5xx can't abort the repo
|
|
(a genuinely-down target still aborts via ``CircuitOpenError``).
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
from typing import Any
|
|
|
|
from .clients import ApiError, parallel
|
|
from .migration import Migration
|
|
from .refs import pr_head_branch
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
|
|
# -- labels ---------------------------------------------------------------
|
|
def migrate_labels(m: Migration, *, concurrency: int = 1) -> dict[int, int]:
|
|
"""Recreate labels on target. Returns old_id→new_id."""
|
|
labels = m.src.get_all(m.path("/labels"))
|
|
|
|
def make(label: dict) -> tuple[dict, dict]:
|
|
body = {
|
|
"name": label["name"],
|
|
"color": label.get("color", "ededed"),
|
|
"description": label.get("description") or "",
|
|
"exclusive": bool(label.get("exclusive", False)),
|
|
"is_archived": bool(label.get("is_archived", False)),
|
|
}
|
|
created = m.tgt.post(m.path("/labels"), body=body)
|
|
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(m: Migration, *, concurrency: int = 1) -> dict[int, int]:
|
|
"""Recreate milestones on target. Returns old_id→new_id."""
|
|
milestones = m.src.get_all(m.path("/milestones"), state="all")
|
|
|
|
def make(ms: dict) -> tuple[dict, dict]:
|
|
body: dict[str, Any] = {
|
|
"title": ms["title"],
|
|
"description": ms.get("description") or "",
|
|
"state": ms.get("state", "open"),
|
|
}
|
|
if ms.get("due_on"):
|
|
body["due_on"] = ms["due_on"]
|
|
created = m.tgt.post(m.path("/milestones"), body=body)
|
|
log.info("milestone %s → #%s", ms["title"], created["id"])
|
|
return ms, created
|
|
|
|
results = parallel(milestones, make, workers=concurrency)
|
|
return {ms["id"]: created["id"] for ms, created in results}
|
|
|
|
|
|
# -- issues + PRs ---------------------------------------------------------
|
|
def _collect(m: Migration) -> list[dict]:
|
|
"""All source issues and PRs, tagged with kind, sorted by number."""
|
|
items: list[dict] = []
|
|
for issue in m.src.get_all(m.path("/issues"), state="all", type="issues"):
|
|
issue["_kind"] = "issue"
|
|
items.append(issue)
|
|
for pull in m.src.get_all(m.path("/pulls"), state="all"):
|
|
pull["_kind"] = "pull"
|
|
items.append(pull)
|
|
items.sort(key=lambda it: it["number"])
|
|
return items
|
|
|
|
|
|
def _set_state(m: Migration, number: int, state: str) -> None:
|
|
if state != "closed":
|
|
return
|
|
m.tgt.patch(m.path(f"/issues/{number}"), body={"state": "closed"})
|
|
|
|
|
|
def _merge_pr(m: Migration, number: int, source_pull: dict) -> None:
|
|
"""Best-effort: recreate a merged PR's merged state. Gitea will only merge
|
|
if the head is cleanly mergeable into base at current history; for a
|
|
historical merge the commits are usually already in base, so this often
|
|
no-ops or 409s — either way the PR ends up closed, which is the fidelity
|
|
floor we can reach without time-travel."""
|
|
if not source_pull.get("merged"):
|
|
return
|
|
# The original merge style isn't exposed by the API; default to a merge commit.
|
|
try:
|
|
m.tgt.post(
|
|
m.path(f"/pulls/{number}/merge"),
|
|
body={"Do": "merge"},
|
|
)
|
|
except ApiError as exc: # already merged / not mergeable — expected
|
|
log.debug("merge attempt for #%s: %s (ignored)", number, exc.status)
|
|
|
|
|
|
def _create_entity(
|
|
m: Migration,
|
|
item: dict,
|
|
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.
|
|
|
|
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":
|
|
body: dict[str, Any] = {"title": item["title"], "body": item.get("body") or ""}
|
|
if ms_id is not None:
|
|
body["milestone"] = ms_id
|
|
created = m.tgt.post(m.path("/issues"), body=body)
|
|
else:
|
|
head = item.get("head", {}) or {}
|
|
base = (item.get("base", {}) or {}).get("ref", "main")
|
|
# Source reports a deleted-branch PR's head as "refs/pull/<n>/head";
|
|
# the mirror recreated its commits on the target as branch _pr/<n>
|
|
# (shared branch name — see refs.pr_head_branch, the single source of truth).
|
|
head_ref = head.get("ref", "")
|
|
if not head_ref or head_ref.startswith("refs/pull/"):
|
|
head_ref = pr_head_branch(item["number"])
|
|
created = m.tgt.post(
|
|
m.path("/pulls"),
|
|
body={
|
|
"title": item["title"],
|
|
"body": item.get("body") or "",
|
|
"head": head_ref,
|
|
"base": base,
|
|
},
|
|
)
|
|
if ms_id is not None:
|
|
m.tgt.patch(m.path(f"/issues/{created['number']}"), body={"milestone": ms_id})
|
|
return created["number"]
|
|
|
|
|
|
def migrate_issues_and_prs(
|
|
m: Migration,
|
|
label_id_map: dict[int, int],
|
|
milestone_map: dict[int, int],
|
|
*,
|
|
concurrency: int = 1,
|
|
) -> None:
|
|
"""Migrate issues + PRs + comments, recording the source→target number map
|
|
on ``m.numbers`` (mutated in place)."""
|
|
numbers = m.numbers
|
|
items = _collect(m)
|
|
|
|
created: list[tuple[dict, int]] = [] # (source_item, new_number)
|
|
for item in items:
|
|
kind = item["_kind"]
|
|
try:
|
|
new_number = _create_entity(m, item, milestone_map)
|
|
except ApiError as exc:
|
|
log.warning("skipped %s #%s (%s): %s", kind, item["number"], item["title"], exc.status)
|
|
continue
|
|
numbers.add(item["number"], new_number)
|
|
|
|
# Labels (works for both issues and PRs via the shared issue path).
|
|
label_ids = [
|
|
label_id_map[label["id"]]
|
|
for label in item.get("labels", [])
|
|
if label.get("id") in label_id_map
|
|
]
|
|
if label_ids:
|
|
m.tgt.post(
|
|
m.path(f"/issues/{new_number}/labels"),
|
|
body={"labels": label_ids},
|
|
)
|
|
|
|
_set_state(m, new_number, item.get("state", "open"))
|
|
if kind == "pull":
|
|
_merge_pr(m, new_number, item)
|
|
|
|
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. Items are
|
|
# independent of each other (the number map is already complete), so they
|
|
# overlap at the caller's concurrency; each item's comments stay sequential
|
|
# to preserve their order.
|
|
#
|
|
# Two-tier: a write that hits a transient target error is *deferred*, not
|
|
# raised, then replayed serially (concurrency 1) once the concurrent wave is
|
|
# done. Concurrent writes are what overstress a self-hosted target and
|
|
# surface as bursts of 500s; serial replay recovers nearly all of them.
|
|
def pass_b(pair: tuple[dict, int]) -> list[tuple]:
|
|
item, new_number = pair
|
|
new_title = m.rewrite(item.get("title"))
|
|
new_body = m.rewrite(item.get("body"))
|
|
deferred: list[tuple] = []
|
|
try:
|
|
m.tgt.patch(
|
|
m.path(f"/issues/{new_number}"),
|
|
body={"title": new_title, "body": new_body},
|
|
)
|
|
except ApiError as exc:
|
|
log.info("deferred body rewrite for #%s: %s", new_number, exc.status)
|
|
deferred.append(("rewrite", new_number, new_title, new_body))
|
|
for comment in m.src.get_all(m.path(f"/issues/{item['number']}/comments")):
|
|
body = m.rewrite(comment.get("body"))
|
|
try:
|
|
m.tgt.post(
|
|
m.path(f"/issues/{new_number}/comments"),
|
|
body={"body": body},
|
|
)
|
|
except ApiError as exc:
|
|
log.info(
|
|
"deferred comment %s on #%s: %s",
|
|
comment.get("id"),
|
|
new_number,
|
|
exc.status,
|
|
)
|
|
deferred.append(("comment", new_number, body))
|
|
return deferred
|
|
|
|
deferred = [d for sub in parallel(created, pass_b, workers=concurrency) for d in sub]
|
|
|
|
# Serial replay (concurrency 1) of the writes that failed under load. The
|
|
# backpressure that caused the 500s is gone; almost everything recovers.
|
|
for kind, new_number, *rest in deferred:
|
|
try:
|
|
if kind == "rewrite":
|
|
title, body = rest
|
|
m.tgt.patch(
|
|
m.path(f"/issues/{new_number}"),
|
|
body={"title": title, "body": body},
|
|
)
|
|
log.info("recovered body rewrite for #%s", new_number)
|
|
else: # "comment"
|
|
(body,) = rest
|
|
m.tgt.post(
|
|
m.path(f"/issues/{new_number}/comments"),
|
|
body={"body": body},
|
|
)
|
|
log.info("recovered comment on #%s", new_number)
|
|
except ApiError as exc:
|
|
log.warning(
|
|
"could not migrate %s for #%s after retry: %s",
|
|
kind,
|
|
new_number,
|
|
exc.status,
|
|
)
|