Lago 57c89e247c
Docker image / build-and-push (push) Successful in 37s
auto-pace: the sync interval computes itself from GitHub's API budget
Anonymous upstream fetches share GitHub's 60 req/h window with the
operator's browser. Instead of waiting for the 403, the scheduler plans
against 80% of it (48/h):

  effective = max(INTERVAL, cost_per_pass * 3600 / 48)

cost_per_pass is measured from the registry's own numbers — the parity
walk (1 page per ≤100 releases) plus one probe per tag lacking a
release. A settled 5-mirror fleet costs ~8 calls/pass and the plan stays
invisible at INTERVAL=600; a churning 12-mirror fleet widens itself to
2700s. Rules: floor never accelerator, INTERVAL=0 stays paused, pinned
(sync_interval) and tokened mirrors never enter the plan.

pacer.py holds the math; status/settings expose the plan (effective
interval, cost, est calls/h, reason); Worker shows it under Scheduler
(API budget row + auto badge), Settings explains when INTERVAL was
raised. 10 new unit tests + full e2e green.
2026-10-20 09:44:55 +02:00

Repo Forker

📖 Arquitectura interactiva: docs/index.html

Turn any git repo (GitHub, Gitea, Codeberg, …) into a live mirror on your Gitea — all branches, all tags, full commit history — plus releases built or mirrored per tag.

One container does everything. There is no CI pipeline, no runner and no local proxy: the worker and the UI run inside the same container, and the UI is the port you publish. It is a self-contained docker compose deploy — clone the repo, drop two variables in .env, docker compose up -d, done. Two variables drive it:

Variable Meaning
REMOTE the Gitea base URL mirrors are pushed to — https://git.lago.dev
TOKEN a Gitea admin token — it creates the mirror repos, fixes their default branch and publishes releases
docker login git.lago.dev                # once (token with read:package works)
docker compose up -d                     # pulls git.lago.dev/lago/repo-forker:latest
open http://127.0.0.1:8731               # the UI *is* the published port

What changed (and why)

This project used to be a template + Gitea Actions pipelines: fork the template per upstream, set UPSTREAM_URL in Actions variables, register an act_runner, and let a */10 * * * * cron run forker/sync.sh inside a per-job container. A local Node server proxied the Gitea API for the UI.

That worked, but the runner was the whole fragility budget: repo-scoped runners that don't serve other repos, an act_runner CLI that cannot register on this Gitea build, per-job containers whose DNS intermittently fails mid-push, an Actions token that is not an owner (so a wrong default branch could only be logged, never fixed), a wiped workspace that made every fetch cold, and upstream CI riding in on the mirrored branches and burning runner slots.

Now the same logic runs as a Python worker in a stateful container:

Before (pipelines) Now (container)
sync.yml cron → runner → forker/sync.sh in-container scheduler → forker/engine.py
runner registration + shared-runner PATCH dance nothing — no runner exists
Actions Variables/Secrets per repo REMOTE + TOKEN env, mirrors added in the UI
ephemeral workspace + actions/cache /data volume: every sync after the first is incremental
fork state read by paginating the REST API one git ls-remote per side
default branch mismatch could only be logged PATCHed for real (admin token)
upstream workflows disabled on a 5-min UI loop no runner to burn; still disabled defensively
node ui/bin/repo-forker-ui.js + paste URL/token UI served by the worker; env-driven, no login
concurrency: group on the workflow one queue with N slots

Quick start

1. Give it two variables

cp .env.example .env

A complete .env (only the first three lines are ever required):

REMOTE=https://git.lago.dev     # the Gitea the mirrors are pushed to
TOKEN=                          # Gitea admin token (Settings → Applications)
OWNER=Lago                      # user or org the mirror repos live under

IMAGE=git.lago.dev/lago/repo-forker:latest   # the published image; --build overwrites this tag
TEMPLATE=repo-forker            # repo holding each mirror's forker branch
INTERVAL=600                    # seconds between sync passes
PARALLELISM=1                   # concurrent syncs (1 = serial)
BIND_ADDR=127.0.0.1             # 0.0.0.0 only on a trusted LAN — the UI has no login
HOST_PORT=8731                  # where the UI is published on the host

The token needs to create repos, write files, PATCH repo settings and publish releases — an admin token is the honest answer on a stock Gitea. It is read once at boot, held in the process, and never written to the repo or a log line.

2. Run the published image

docker login git.lago.dev     # your Gitea user + a token (read:package is enough)
docker compose up -d          # pulls git.lago.dev/lago/repo-forker:latest

The image has two stages: the React app is built with Node, then dropped into a slim Python runtime that is stdlib-only (no pip install at start, no dependency supply chain). git is the only other thing it needs.

Hacking on the worker? Build from source instead — same tag, same compose file:

docker compose up -d --build          # or: make build && make push

make push publishes your build to the registry, and IMAGE=… overrides the registry location entirely if you mirror the image elsewhere.

3. Add mirrors in the UI

Open http://127.0.0.1:8731 → New mirror → paste the upstream git URL. The container creates the destination repo on REMOTE, writes the forker branch with that mirror's .forker.yaml, points the default branch at the upstream's, and runs the first sync immediately. Then it re-syncs every INTERVAL seconds.

Already have mirrors from the pipeline era? Dashboard → Adopt existing: repos carrying a forker branch + a UPSTREAM_URL variable (or the Mirror of <url> description) are registered here, and anything whose sync.yml is still enabled on a runner is skipped rather than double-driven.

Migrating from the pipeline setup

Nothing to convert, one thing to turn off:

  1. Bring the container up (cp .env.example .env, fill REMOTE/TOKEN, docker compose up -d). It starts with an empty registry — no repo is touched until you adopt it.
  2. Adopt your existing mirrors (Dashboard → Adopt existing mirrors). They keep their history and their forker branch; from the next pass on they are driven by the container instead of cron.
  3. Turn the old machinery off, so nothing is driven twice: disable sync.yml/release.yml on each mirrored repo (the container does this defensively on its passes, but do it explicitly), then stop and unregister the act_runner. After a week of green passes in the UI, delete the runner container for good.
  4. Per-repo Actions Variables/Secrets are dead — configuration now lives in each mirror's .forker.yaml, edited from the UI or in the repo.

Deploying on Unraid (Compose stack)

Verified working on Unraid: put both files below in the stack's appdata folder (e.g. /mnt/user/appdata/repo-forker/), docker login git.lago.dev once as root, and bring the stack up. If the stack editor offers a "build" option, leave it off — this compose pulls the published image and carries no build: block on purpose (the repo's own compose file does have one; using it without the Dockerfile next to it fails with failed to read dockerfile: no such file or directory).

docker-compose.yml:

services:
  repo-forker:
    image: ${IMAGE:-git.lago.dev/lago/repo-forker:latest}
    container_name: repo-forker
    restart: unless-stopped
    labels:
      # Presentation in Unraid's Docker tab (net.unraid.stack.*); ignored elsewhere.
      - net.unraid.stack.icon=https://git.lago.dev/Lago/repo-forker/raw/branch/main/brand/repo-forker.svg
      - net.unraid.stack.description=Live git mirrors on your Gitea — worker + UI in one container
      - net.unraid.stack.webui=http://192.168.178.3:8731/
      - net.unraid.stack.shell=bash
    environment:
      REMOTE: ${REMOTE:?set REMOTE to your Gitea base URL, e.g. https://git.lago.dev}
      TOKEN: ${TOKEN:?set TOKEN to a Gitea admin token (creates repos + publishes releases)}
      OWNER: ${OWNER:-}
      TEMPLATE: ${TEMPLATE:-repo-forker}
      INTERVAL: ${INTERVAL:-600}
      PARALLELISM: ${PARALLELISM:-1}
      PORT: "8731"          # container-internal port — do not change
      DATA_DIR: /data
    ports:
      - "${BIND_ADDR:-127.0.0.1}:${HOST_PORT:-8731}:8731"
    volumes:
      - forker-data:/data
    stop_grace_period: 90s

volumes:
  forker-data:

.env next to it (compose reads it automatically; not the sibling of a compose run from elsewhere — that is the usual cause of required variable REMOTE is missing a value):

REMOTE=https://git.lago.dev
TOKEN=***        # Gitea admin token (Settings → Applications)
OWNER=Lago
IMAGE=git.lago.dev/lago/repo-forker:latest
TEMPLATE=repo-forker
INTERVAL=600
PARALLELISM=1
BIND_ADDR=0.0.0.0        # reachable from the LAN; the UI has no login — keep this inside your network
HOST_PORT=8731

Then the UI answers on http://<unraid-ip>:8731, and the stack shows with its icon, Web UI link and console button in Unraid's Docker tab.

Configuration

Container (docker-compose.yml / environment)

Variable Default Meaning
REMOTE — Gitea base URL the mirrors are pushed to
TOKEN — Gitea token (admin recommended)
OWNER token's user user or org the mirrors live under
TEMPLATE repo-forker repo holding the forker branch machinery; created if missing
INTERVAL 600 seconds between sync passes — a floor; auto-pace raises it when the GitHub API budget asks (below)
PARALLELISM 1 concurrent mirror syncs (1 = serial)
PORT 8731 port the UI/API listens on inside the container
DATA_DIR /data volume: bare mirrors, registry, logs
SYNC_TIMEOUT 1800 hard cap per sync (then the pass fails, loudly)
PUSH_RETRIES 3 retries for transient network errors
UI_DIST /app/ui/dist built app; empty = API only
WORKER_LOG /data/logs/worker.log tailed by the UI's Worker page

Auto-pace: the interval computes itself

Upstream releases are fetched anonymously (golden rule #1), so every mirror shares GitHub's ~60 requests/hour anonymous window — with your browser, on the same IP. The worker plans its own pace instead of waiting for a 403:

effective_interval = max(INTERVAL, cost_per_pass × 3600 / 48)

48/h is 80% of the window; the rest stays free for the Re-sync button. cost_per_pass is measured from the registry's own numbers, not guesses: the parity walk (1 page per ≤100 upstream releases) plus one probe per tag that still lacks a release — so a settled mirror costs ~2 calls/pass and the plan stays invisible, while ten churning mirrors widen the interval by themselves. (forker/pacer.py owns the math; /api/status → scheduler.auto_pace shows cost, the resulting interval and why.)

Rules that keep it predictable:

  • a floor, never an accelerator — your INTERVAL is honored whenever it already fits the budget; the plan only pushes it up;
  • INTERVAL=0 stays paused — auto never resurrects a stopped scheduler;
  • a mirror with its own sync_interval schedules itself — pinned mirrors are listed in the plan but never paced (spending over budget becomes your explicit choice);
  • mirrors carrying their own upstream token cost zero budget — their calls are authenticated and live in a separate 5.000/h window.

Per mirror (.forker.yaml, on that mirror's forker branch)

Flat key: value — the parser is deliberately trivial so the file stays editable in Gitea's web editor. Edit it in the UI (Mirror → Config) or in the repo; the file wins: it is re-read at the start of every pass, so a hand edit is never clobbered.

Key Default Meaning
enabled true false pauses this mirror without unregistering it
sync_interval 0 per-mirror interval (seconds); 0 = container INTERVAL
mirror_branches * * = all, or a comma list (main,develop), or globs (release/*)
mirror_tags true mirror all tags
mirror_prune true delete refs the upstream removed
on_new_tag true publish a release for tags that lack one
mirror_upstream_releases false copy the upstream release (metadata + assets)
build_cmd — command(s) run in the tag's tree to produce assets
build_script — path (in the tag's tree) to a build script; overrides build_cmd
artifacts — space-separated globs attached to the release (dist/*)

With the build fields empty and mirror_upstream_releases: false a mirror is refs-only: tags land but no release is published. That is the safe default.

Releases

Two modes, both opt-in per mirror, both run inside the container:

  • MIRROR (mirror_upstream_releases: true) — copies the upstream's release for the tag: name, body and every asset, through the provider API (GitHub / Gitea / Codeberg, auto-detected in forker/provider.py).
  • BUILD (build_cmd / build_script + artifacts) — exports the tag's tree from the mirror it already holds (git archive, no extra network), runs your build, and uploads the artifacts.

Both publish only when there is real content, are idempotent (a tag that already has a release is skipped), and a missing release is retried on the next pass — so a failed release heals itself instead of staying invisible. A failing build never publishes an empty release: the pass is marked failed, the build's own output is streamed into the run log, and the tag is retried.

The image ships git, curl, tar, gzip — no compilers. Your mirrors build different things, so pass what you need at build time: docker compose build --build-arg EXTRA_APT_PACKAGES="nodejs npm make golang".

Repository layout

Dockerfile              two stages: ui/dist, then a slim python runtime
docker-compose.yml      the deployment (REMOTE + TOKEN + the published port)
docker/entrypoint.sh    volume ownership + drop privileges, then exec the worker
forker/                 the worker — stdlib Python, one module per concern
├── config.py           env settings + the flat .forker.yaml parser/renderer
├── gitea.py            minimal Gitea REST client
├── provider.py         upstream releases API (github/gitea/codeberg)
├── pacer.py            GitHub-budget auto-pace: the interval computes itself
├── gitops.py           bare-mirror fetch / multi-ref push / prune
├── engine.py           one pass: fetch → push → prune → heal → releases
├── registry.py         the mirrors this container owns (create/adopt/delete)
├── state.py            state.json + per-run logs
├── service.py          boot, scheduler, queue, graceful stop
├── logtee.py           stdout/stderr → WORKER_LOG (no pipe in the entrypoint)
└── api.py              /api/* for the UI + static serving of ui/dist
ui/                     React app (served by the container; dev server optional)
tests/test_worker.py    unit tests for the logic whose bugs are silent
tests/e2e.sh            full cycle against a throwaway Gitea in Docker
docs/index.html         architecture page

Security

Read this before exposing the port — the UI holds the admin token and has no login of its own. The compose file publishes to 127.0.0.1 by default for exactly that reason.

  • BIND_ADDR=0.0.0.0 makes anyone who can reach the port your Gitea admin. Front it with a reverse proxy that authenticates (oauth-proxy, Authelia, Caddy basic_auth, Tailscale) instead of publishing it raw.
  • The token never leaves the process. No endpoint echoes it; mirror records serialize as hasToken: true. Upstream tokens live in /data/state.json (chmod 600) — treat that volume as a secret.
  • Upstreams are fetched anonymously by default. Every upstream git call cuts GIT_CONFIG_GLOBAL/GIT_CONFIG_SYSTEM and GIT_CONFIG_NOSYSTEM, so a credential.helper=store entry can never be offered to git fetch. A Bearer header is added only when a mirror has a token, and an empty token means no header — never Bearer (GitHub 401s on that).
  • build_cmd / build_script are trusted code with credentials in scope. They run inside this container, which holds an admin token. Anyone who can edit a mirror's .forker.yaml on Gitea can run arbitrary commands here. Restrict who can push to forker branches, or only use mirror_upstream_releases.
  • Mirrored refs stay byte-identical to upstream — same commit and tag hashes, by design. The container's own files live on the forker branch, which is never overwritten by a mirrored ref and never pruned.
  • Git pushes are authenticated with a per-URL http.<url>.extraHeader Bearer, so the token never appears in a URL and never leaks into git's output/logs.

The one pipeline (ours, not the mirrors')

.gitea/workflows/docker-image.yml is a Gitea Actions workflow on this repo: any push to main rebuilds the image and publishes it to git.lago.dev/lago/repo-forker as latest + sha-<short>. Mirrors have their Actions unit switched off (the worker also disables foreign workflows every pass), so this is the only pipeline that ever runs. Deployments then just docker compose pull && up -d — that's how updates ship.

Requirements on the Gitea side: an Actions runner that answers ubuntu-latest, and two repo secrets — REGISTRY_USER (a Gitea username) and REGISTRY_TOKEN (an access token with write scope on the lago container registry). Same scheme the image's own build used before; nothing else reads them.

make pull && make up   # deploy whatever main just published

Operations

make up          # start from the published image (fails early, naming missing vars)
make pull        # refresh the image without redeploying
make logs        # scheduler + sync chatter (also on the UI's Worker page)
make status      # curl /api/status, pretty
make test        # python unit tests + UI typecheck/build
make test-e2e    # whole cycle against a throwaway Gitea
make clean-data  # drop the volume: every mirror + the registry
  • Backup /data. It holds state.json (the registry, including upstream tokens) and the bare mirrors. Losing it is not fatal — the mirrors can be re-adopted and a cold fetch is correct — but every mirror then pays a full-history fetch again.
  • docker stop is graceful: SIGTERM stops taking new work and waits for the pass in flight (stop_grace_period: 90s), because a half-pushed mirror is worse than a mirror a few minutes stale.
  • A sync cannot corrupt the previous state: refs are pushed in one pack per kind, transient network errors are retried with backoff, and a non-network failure aborts the pass loudly.

Gitea build quirks (still true, still handled)

Verified on git.lago.dev (Gitea 28.1.0) and re-verified here against 1.22.4:

  • Repos created as forks ship without the Releases unit (DefaultForkRepoUnits = [Code, PullRequests]). Release assets are then listed by the API but 404 on the web download route (the source tarball too), because the download path runs RequireUnitReader. Most builds expose no units API, so the worker tries PATCH /repos/{repo} with has_releases, verifies, and if nothing worked reports unitFix: "manual" — the one-time fix is repo Settings → Repository → Releases. Prefer creating mirrors from this container (not forking): non-fork repos get the full unit set, and Gitea only allows one fork of a repo per user anyway.
  • GET on a file in a repo with no commits answers 500 "no open git repo", not 404, and the contents endpoint answers []. Both mean "not there" here — the first write of a fresh mirror depends on it. POST contents creates the missing branch only on an empty repo; on a repo that already has commits it 404s, so the worker cuts the branch from the default branch and writes again — which is what lets a pre-existing repo become a mirror.
  • PATCH default_branch is a silent no-op until the branch exists, so the default branch is re-checked on every pass and heals itself once the upstream branch has been mirrored.
  • This build ignores ?workflow= on the Actions runs API and reports a disabled workflow as disabled_manually; workflow id is the filename. Moot for syncing now (no runner), still honored by the defensive disable loop.
  • Per-job DNS flapping (the old push_once retry wrapper) is gone with the per-job container — but the same retry-with-backoff remains, because transient network errors are not a runner-exclusive invention.
S
Description
Template: turn any git repo into a live Gitea mirror + local releases
Readme
150 MiB
0 Stars 1 Watchers 0 Forks
Languages
Python 46.6%
TypeScript 43.7%
Shell 6.4%
CSS 1.3%
Dockerfile 0.8%
Other 1.1%