Compare commits

...
10 Commits
Author SHA1 Message Date
Lago 57c89e247c auto-pace: the sync interval computes itself from GitHub's API budget
Docker image / build-and-push (push) Successful in 37s
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
Lago 75483188f9 docs: the one pipeline — push to main publishes the image
Docker image / build-and-push (push) Successful in 23s
Mirrors never run workflows; this repo's docker-image.yml is the only
pipeline and it is the update mechanism: commit main → new :latest →
'compose pull && up -d' everywhere.
2026-10-19 23:26:15 +02:00
Lago 85e8c3a814 CI: build + publish the image to the Gitea registry on push to main
Docker image / build-and-push (push) Successful in 3m37s
The one pipeline we keep — and it is ours, not the mirrors'. Mirrors have
their Actions unit off; only commits to Lago/repo-forker@main republish
git.lago.dev/lago/repo-forker:latest (+ :sha), which is exactly what the
deployments 'docker compose pull' from.

Pattern copied from Lago/Tide's verified-working pipeline (same Gitea
instance, same shared runner, same secrets scheme: REGISTRY_USER +
REGISTRY_TOKEN). GHA cache for the two-stage UI build.
2026-10-19 23:14:14 +02:00
Lago fd6223188c README: verified Unraid compose-stack deployment (no-build compose + .env examples)
Deployed and confirmed working on Unraid. The stack compose deliberately has
no build: block — the repo compose does, and using it without the Dockerfile
next to it fails with 'failed to read dockerfile'. Documented both failure
modes seen in practice (that build error, and 'REMOTE is missing a value'
from a .env that is not beside the compose file), plus the full .env example
in the Quick start. The Unraid compose snippet was extracted from the README
and validated with 'docker compose config'.

Also documents the net.unraid.stack.* labels (icon/webui/shell) that render
the stack in Unraid's Docker tab.
2026-10-19 22:57:21 +02:00
Lago fc54377f26 compose: Unraid stack labels (icon/webui/shell/description)
Unraid's Docker tab reads net.unraid.stack.* to render a compose stack with
an icon, a Web UI link and a console button; other hosts ignore them. The
icon is the repo's own brand/repo-forker.svg, served raw by git.lago.dev
(200 anonymous). Web UI defaults to this LAN's UI URL.
2026-10-19 22:51:22 +02:00
Lago 513389acfe brand: repo-forker logo (SVG) for dashboards and stack labels 2026-10-19 22:50:15 +02:00
Lago 6fd0c3daf1 Ship the image through the Gitea container registry
The published image now lives at git.lago.dev/lago/repo-forker:latest
(docker push to Gitea's built-in registry). The compose file references it
directly, so a deploy is: docker login git.lago.dev && docker compose up -d
— no source checkout required to run, though --build still works and lands
on the same tag.

- docker-compose.yml: image: ${IMAGE:-git.lago.dev/lago/repo-forker:latest}
- Makefile: up pulls by default; new pull/push targets; IMAGE override
- README + .env.example: login step, registry URL, build-from-source note

Verified: compose pull from the registry (digest match), container boots
from the pulled image with the existing /data volume (3 mirrors restored).
2026-10-19 22:43:28 +02:00
Lago de72dfb1d9 Drop TODO.md — pipeline-era planning, superseded by the container
Everything it asked for (a guided UI, no curl/DB, create/adopt/sync from a
web page) is now built, as an in-container UI driven by REMOTE+TOKEN rather
than an npx proxy with pasted tokens and Actions variables.
2026-10-19 22:39:39 +02:00
Lago c0d2353c7d README: foreground the self-contained compose deploy + migration steps 2026-10-19 22:39:18 +02:00
Lago ddff8a4c31 Migrate to a self-contained Docker worker (no pipelines, no runner)
Rip out the Gitea Actions model and rebuild the whole thing as one Docker
container that runs the scheduler, the git mirroring and the UI together.
The UI is the published port; two variables (REMOTE + a Gitea admin TOKEN)
drive everything.

Removed: .gitea/workflows/*, runner/, the forker/*.sh scripts, forker/lib/*,
and the Node API proxy (ui/server, ui/bin). Each behavior is reimplemented
in stdlib Python under forker/ and is now better because the container is
stateful (incremental fetches via /data) and holds an admin token (real
default-branch healing, releases for any repo).

Added:
- forker/       worker package: config, gitea, provider, gitops, engine,
                registry, state, service (scheduler + graceful stop), api
- Dockerfile    2-stage build (node → python:3.12-slim, stdlib-only)
- docker-compose.yml + docker/entrypoint.sh  the deployment
- ui/           React app reworked to the live contract (WorkerView etc.)
- tests/        43 unit tests + e2e.sh (throwaway Gitea, 47 asserts)
- README/AGENTS/docs rewritten for the container model

Verified end-to-end against the built image: boot, self-register, UI+API,
create/adopt/sync/prune/releases, SIGTERM drain, restart persistence.
2026-10-19 22:37:22 +02:00
68 changed files with 8378 additions and 4201 deletions

No files matched your search

+23
View File
@@ -0,0 +1,23 @@
# The image only needs the Python package + ui/. Everything else would bust
# the build cache or leak local state into it.
.git/
.gitignore
.design-audit/
.dev-test/
.superdesign/
.mirror/
docs/
runner/
*.md
.env
.env.*
!.env.example
# UI: sources are needed, build junk is not
ui/node_modules/
ui/dist/
ui/*.log
# Python
**/__pycache__/
**/*.pyc
+26
View File
@@ -0,0 +1,26 @@
# Copy to .env and fill in — docker compose reads it automatically.
# Never commit the filled-in file: TOKEN is an admin credential.
# Required: the Gitea this container pushes mirrors to.
REMOTE=https://git.lago.dev
# Required: Gitea admin token (creates repos, sets default branches, publishes releases).
TOKEN=
# Optional -------------------------------------------------------------
# Image to run. The default is published in the Gitea container registry;
# `docker compose up -d --build` (or make build) overwrites this tag locally.
#IMAGE=git.lago.dev/lago/repo-forker:latest
# Namespace for the mirrors (user or org). Default: the token's own user.
#OWNER=Lago
# Repo that carries each mirror's `forker` branch config. Auto-created if missing.
#TEMPLATE=repo-forker
# Seconds between sync passes.
# Floor between sync passes; auto-pace raises it when anonymous GitHub
# API use would exceed 48 req/h (80% of the unauthenticated window).
#INTERVAL=600
# Concurrent mirror syncs (1 = strictly serial).
#PARALLELISM=1
# Where the UI port is published. Keep it on loopback: the UI holds the admin
# token and has no login of its own.
#BIND_ADDR=127.0.0.1
#HOST_PORT=8731
-49
View File
@@ -1,49 +0,0 @@
# .forker.yaml — per-fork configuration for Repo Forker.
#
# The upstream URL and its token are NOT set here. They are set in the Gitea UI:
# Settings -> Actions -> Variables & Secrets
# UPSTREAM_URL = https://github.com/owner/repo.git (any provider)
# UPSTREAM_TOKEN = <token that can read the upstream>
# This keeps secrets out of the repo. Everything below is non-secret.
#
# All values are optional; sensible defaults apply when a key is absent.
# (unused — Bearer auth needs no username; retained for compatibility)
token_user: oauth2
# Mirror all tags (true/false). Default: true
mirror_tags: true
# Prune branches that were deleted upstream (true/false). Default: true
mirror_prune: true
# Which upstream branches to mirror. "*" = all (default).
# Comma-separated list to restrict, e.g. "main,develop" (stray spaces
# tolerated). NOTE: pruning is always checked against the FULL upstream
# branch set, so a branch outside this filter but still upstream is never
# deleted.
mirror_branches: "*"
# When a new upstream tag is mirrored, automatically build + publish a release
# on this Gitea (true/false). Default: true
on_new_tag: true
# Also mirror the upstream's existing releases (metadata + assets) via the
# provider API (true/false). Default: false
mirror_upstream_releases: false
# Build commands run inside the tag's working tree to produce release assets.
# Multiple commands are ';'-separated. Leave empty to skip the local build and
# only mirror upstream release assets.
# build_cmd: "make && go build -o dist/app ."
build_cmd: ""
# Optional: point to a custom build script (path relative to the forker branch)
# instead of build_cmd. If set, build_cmd is ignored.
# build_script: "forker/build-custom.sh"
build_script: ""
# Artifacts to attach to the locally-built release. Space-separated globs,
# relative to the tag's working tree.
# artifacts: "dist/*"
artifacts: ""
+49
View File
@@ -0,0 +1,49 @@
# On every push to main: build the container image and publish it to the
# Gitea container registry (git.lago.dev/lago/repo-forker). Deploys refresh
# with `docker compose pull && docker compose up -d`.
#
# Requires: an Actions runner reachable by this repo (Settings → Actions) and
# two repo secrets (Settings → Actions → Secrets):
# REGISTRY_USER registry username (Lago)
# REGISTRY_TOKEN a token with write:packages (the admin token works too)
name: Docker image
on:
push:
branches: [main]
jobs:
build-and-push:
runs-on: [ubuntu-latest]
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Log in to the Gitea registry
uses: docker/login-action@v3
with:
registry: git.lago.dev
username: ${{ secrets.REGISTRY_USER }}
password: ${{ secrets.REGISTRY_TOKEN }}
- name: Extract image metadata
id: meta
uses: docker/metadata-action@v5
with:
images: git.lago.dev/lago/repo-forker
tags: |
type=raw,value=latest
type=sha
- name: Build and push
uses: docker/build-push-action@v6
with:
context: .
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha
cache-to: type=gha,mode=max
-38
View File
@@ -1,38 +0,0 @@
name: Repo Forker — Release (build + publish)
# Produces a release on this Gitea fork. Two modes (see .forker.yaml):
# BUILD — checkout the tag's working tree, run the configured build command,
# publish the release (tag + assets) on this Gitea.
# MIRROR — mirror the upstream's existing release (metadata + assets).
#
# NOTE: this workflow is triggered MANUALLY from the UI (workflow_dispatch).
# Automatic releases on new tags are handled INLINE by sync.sh, because a
# mirrored tag points at an upstream commit whose tree has no .gitea/workflows,
# so a "push: tags" trigger would never find this file. See sync.sh.
on:
workflow_dispatch:
inputs:
tag:
description: 'Tag to release'
required: true
jobs:
release:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Run release
run: |
export GITEA_REPO="${GITEA_OWNER_REPO##*/}"
bash forker/release.sh "$TAG"
env:
GITEA_SERVER_URL: ${{ gitea.server_url }}
GITEA_OWNER: ${{ gitea.repository_owner }}
GITEA_OWNER_REPO: ${{ gitea.repository }}
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
UPSTREAM_URL: ${{ vars.UPSTREAM_URL }}
UPSTREAM_TOKEN: ${{ secrets.UPSTREAM_TOKEN }}
TAG: ${{ inputs.tag }}
-35
View File
@@ -1,35 +0,0 @@
name: Repo Forker — Runner check
# Verifies a runner is available for this repo before relying on the cron sync
# and local builds. Run it once after forking (or when a sync run is "pending"
# for a long time — that usually means no runner is registered for this repo).
#
# In this Gitea build, runners are repo-scoped: a runner registered on one repo
# does NOT serve another. Register a runner for this repo (see README, "Runner").
on:
workflow_dispatch: {}
jobs:
check:
runs-on: ubuntu-latest
steps:
- name: Confirm a runner picked this job up
run: |
echo "A runner is online and serving this job."
echo "OS=$RUNNER_OS Arch=$RUNNER_ARCH"
- name: Which runner(s) serve this repo
env:
GITEA_SERVER_URL: ${{ gitea.server_url }}
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
run: |
# The repo-level API does NOT list shared runners, so check the
# shared (instance) list too and report which serves the repo.
# (The Gitea Actions token has admin scope in this setup; with a
# plain repo token the admin call 403s and we say so, not hide it.)
curl -sS --max-time 20 -H "Authorization: Bearer $GITEA_TOKEN" \
"$GITEA_SERVER_URL/api/v1/repos/${GITEA_OWNER}/${GITEA_REPO}/actions/runners" > /tmp/repo_runners.json
curl -sS --max-time 20 -H "Authorization: Bearer $GITEA_TOKEN" \
"$GITEA_SERVER_URL/api/v1/admin/actions/runners?limit=50" > /tmp/shared_runners.json
python3 -c 'import json; R=json.load(open("/tmp/repo_runners.json")).get("runners",[]); S=[r for r in json.load(open("/tmp/shared_runners.json")).get("runners",[]) if r.get("shared")]; print("Repo-scoped runners: "+(", ".join("%s (%s)"%(r["name"],r["status"]) for r in R) or "(none)")); print("Shared runners: "+(", ".join("%s (%s)"%(r["name"],r["status"]) for r in S) or "(none)")); print("OK: a runner serves this repo." if (R or S) else "WARNING: no runner (repo-scoped or shared) registered - cron runs will stay queued.")'
-82
View File
@@ -1,82 +0,0 @@
name: Repo Forker — Sync (mirror upstream)
# Periodically mirrors the upstream repo (all branches, tags, full history) into
# this Gitea fork. This is the "worker" job.
#
# One-time setup (Gitea UI):
# Settings -> Actions -> Variables & Secrets
# UPSTREAM_URL = https://github.com/owner/repo.git (any provider)
# UPSTREAM_TOKEN = <secret: token that can read the upstream>
# GITEA_* values below are injected automatically by Gitea Actions.
on:
schedule:
# "very periodically" — every 10 minutes. Tune to taste (5-field cron).
- cron: '*/10 * * * *'
workflow_dispatch: {} # manual trigger from the UI
push:
branches: [forker] # re-sync when the forker config changes
jobs:
sync:
runs-on: ubuntu-latest
# A cold full-history fetch can exceed the 10-min cron interval (or a
# push/dispatch can land mid-run); without this, two overlapping runs
# both see the same tag as "missing release" and both build/publish —
# duplicate releases + double builds. Serialize per repo (do NOT
# cancel-in-progress: an in-flight sync must finish).
concurrency:
group: sync-${{ gitea.repository }}
steps:
# A repo without UPSTREAM_URL (e.g. the template itself) is not a mirror:
# skip the whole job with a notice instead of failing.
- name: Upstream configured?
id: check
env:
UPSTREAM_URL: ${{ vars.UPSTREAM_URL }}
run: |
if [ -z "$UPSTREAM_URL" ]; then
echo "::notice::UPSTREAM_URL is not set — this repo is not configured as a mirror (e.g. the template). No-op."
echo "configured=false" >> "$GITHUB_OUTPUT"
else
echo "configured=true" >> "$GITHUB_OUTPUT"
fi
- name: Checkout
if: steps.check.outputs.configured == 'true'
uses: actions/checkout@v4
- name: Restore mirror cache
if: steps.check.outputs.configured == 'true'
uses: actions/cache@v4
continue-on-error: true # no cache service configured? continue cold — still correct
with:
path: .mirror
# Unique per run so saves never conflict; restore-keys pulls the most
# recent saved mirror (incremental fetch). No cache → full fetch, still
# correct.
key: forker-mirror-${{ github.run_id }}
restore-keys: |
forker-mirror-
- name: Show config
if: steps.check.outputs.configured == 'true'
run: |
echo "UPSTREAM_URL=${UPSTREAM_URL:?set in Gitea UI (Variables & Secrets)}"
echo "Gitea repo: ${{ gitea.repository }}"
env:
UPSTREAM_URL: ${{ vars.UPSTREAM_URL }}
- name: Run sync
if: steps.check.outputs.configured == 'true'
run: |
# gitea.repository is "owner/repo"; extract just the repo name.
export GITEA_REPO="${GITEA_OWNER_REPO##*/}"
bash forker/sync.sh
env:
GITEA_SERVER_URL: ${{ gitea.server_url }}
GITEA_OWNER: ${{ gitea.repository_owner }}
GITEA_OWNER_REPO: ${{ gitea.repository }}
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
UPSTREAM_URL: ${{ vars.UPSTREAM_URL }}
UPSTREAM_TOKEN: ${{ secrets.UPSTREAM_TOKEN }}
+13 -7
View File
@@ -1,13 +1,6 @@
# The bare mirror holds upstream objects; never commit it.
.mirror/
# Local runner config (contains tokens) — but KEEP runner/docker-compose.yml
# tracked, otherwise a fresh fork has no documented runner setup at all.
# (The runner/_svc_*.go files are untracked Gitea-source scratch snippets.)
runner/config/
runner/_svc_*.go
*.runner.conf
# OS / editor noise
.DS_Store
*.swp
@@ -22,3 +15,16 @@ ui/node_modules/
ui/dist/
ui/*.log
.design-audit/
# python bytecode (the worker is stdlib-only python; no build step, so nothing
# should ever commit a .pyc)
__pycache__/
*.pyc
# compose reads REMOTE/TOKEN from here; it holds the admin token, so it must
# never reach a commit (.dockerignore keeps it out of the image too)
.env
# local test/dev harness (Gitea + upstream fixtures + scratch state) — never
# committed
.dev-test/
+151 -140
View File
@@ -4,159 +4,170 @@ Instructions for AI agents (and humans) working on or with this repository.
## What this is
A **template**. Each fork/generation of it is a *live mirror* of one upstream
git repo on this Gitea: all branches, all tags, full history, plus releases
produced on the runner. The working tree (the `forker` branch) holds only the
machinery — the upstream's content never enters it.
A **Dockerized mirror worker**. One container turns any git repo (GitHub,
Gitea, Codeberg, …) into a **live mirror on your Gitea**: all branches, all
tags, full history, plus releases built or mirrored per tag. The worker
(scheduler + git) and the UI (React app + JSON API) run **inside the same
container**; the UI is the port you publish. There are **no CI pipelines and no
runner** — that model was removed.
```
This repo (template) → fork/generate per upstream (Lago/<upstream>)
├── forker branch ← scripts, config, workflows
├── .mirror/ ← bare mirror (gitignored)
└── refs ← upstream branches + tags
REMOTE + TOKEN → container → scheduler (each mirror every INTERVAL)
├── fetch upstream → /data/mirrors/<name> (bare mirror)
├── push refs → REMOTE/<owner>/<repo> (the mirror)
├── prune → refs the upstream deleted
└── releases → build in a worktree / mirror upstream
```
Each mirror is a normal repo on `REMOTE`, created by the container. Upstream
objects arrive as refs; the container's own files live on a reserved `forker`
branch (never overwritten by a mirrored ref, never pruned).
## Golden rules (non-negotiable)
1. **Never authenticate to upstreams with the operator's personal accounts or
stored credentials.** Public upstreams are fetched **anonymously**:
`sync.sh`/`release.sh` cut `GIT_CONFIG_GLOBAL`/`GIT_CONFIG_SYSTEM` and the
credential helper before any upstream git call, and add a Bearer header
**only** when `UPSTREAM_TOKEN` is explicitly set. Do not "simplify" this
away — a `credential.helper=store` entry must never be offered to
`git fetch`. Do not pass tokens from `~/.git-credentials` into the tool.
2. **An empty token must mean "no auth header", not "Bearer <empty>".**
GitHub rejects empty Bearer headers (401). All code paths (git
`extraHeader`, `provider.sh` curl calls) must branch on token presence.
3. **Secrets live in Gitea Actions Variables/Secrets, never in the repo.**
`UPSTREAM_URL` (variable) and `UPSTREAM_TOKEN` (secret, optional). The
`GITEA_*` values are injected by Gitea Actions automatically.
4. **Keep `.forker.yaml` flat** (`key: value`, no nesting) — `config.sh` is a
simple grep parser.
1. **Never authenticate to upstreams with the operator's credentials.** Public
upstreams are fetched **anonymously**. Every upstream git call cuts
`GIT_CONFIG_GLOBAL`/`GIT_CONFIG_SYSTEM` + `GIT_CONFIG_NOSYSTEM`
(`forker/gitops.py:_clean_git_env`), so a stored `credential.helper=store`
entry can never be offered to `git fetch`. Do not "simplify" this away.
2. **An empty token must mean "no auth header", not "Bearer <empty>".** GitHub
rejects empty Bearer headers (401). Branch on token presence in
`provider.py`, `gitops.py:_set_header`, `gitea.py`.
3. **Secrets live in the environment, never in the repo.** `REMOTE` + `TOKEN`
(plus per-mirror upstream tokens in `/data/state.json`, chmod 600). Nothing
secret is committed, logged in full, or echoed by an API response — a mirror
serializes as `hasToken: true`, never the value.
4. **Keep `.forker.yaml` flat** (`key: value`, no nesting) — `config.py` is a
simple parser and it *raises* on nesting instead of dropping lines.
5. **The remote `.forker.yaml` is the source of truth.** It is re-read at the
start of every pass so a hand edit in the Gitea UI is never clobbered. When
the UI writes config, it writes the **file** (`Registry.update` →
`write_remote_config`), not just `state.json` — config that only lived in
state would be overwritten by the file on the next pass. (This was a real
bug; `KeyAgreementTest` guards the key lists from drifting again.)
6. **`config.py`'s key lists must agree**: `KNOWN_KEYS`, `BOOL_KEYS`,
`CONFIG_DEFAULTS` and `engine.default_config_text()`. A key in the defaults
but missing from `KNOWN_KEYS` cannot be written through the API. Add a config
key → add it everywhere and let the test pass.
7. **A partial mirror must never look like success.** Refs are pushed in one
pack per kind; transient network errors retry with backoff
(`gitops.py:_with_retry`); a non-network failure aborts the pass loudly. A
failing build does not publish; an empty release does not publish. Prune is
always checked against the FULL upstream set, never the `mirror_branches`
filter, so a filtered branch that still exists upstream is not deleted.
## How it runs
- **Cron** (`sync.yml`, every 10 min) → `forker/sync.sh`:
1. fetch all branches + tags + history into the bare `.mirror/` (incremental
when `actions/cache` restores it),
2. push refs onto this repo + prune what upstream deleted (fork state is
read via the Gitea **API**, not git state — works on cold mirrors),
3. for each **tag that has no release yet**, run `forker/release.sh <tag>`
inline (a tag-push can't trigger a workflow: the tag points at an upstream
commit whose tree has no `.gitea/workflows`). The "missing release" check
(not "new tag") makes a failed release retry on the next cron tick.
`release.sh` publishes only when there is actual content (build assets or
an existing upstream release) and fails loudly on a bad asset
download/upload — a partial release never masquerades as success.
4. `forker/check-unit.sh` — verifies the **Releases unit** is enabled
(self-heals via the units API when the build exposes it; otherwise
detects the 404 and prints the one-time UI fix).
- `release.sh` = local build (if `build_cmd`/`build_script` set) + optional
upstream-release mirror (metadata + assets via `forker/lib/provider.sh`).
Idempotent: an existing release is skipped, not duplicated.
- `runner-check.yml` — run once per repo to confirm a runner serves it.
**Runners are repo-scoped on this Gitea build**: a runner registered on one
repo does not serve another. Use a **shared** runner (or PATCH the runner
to `"shared":true` — the units/runners APIs are missing here, so UI/DB).
- `docker/entrypoint.sh` validates `REMOTE`/`TOKEN`, prepares `/data` (a mounted
volume may arrive root-owned → it chowns and drops to uid 10001), then
`exec python3 -m forker`. It stays a thin `exec` so SIGTERM from `docker stop`
reaches the worker's graceful shutdown — **do not reintroduce a `cmd | tee`
pipe**; the worker tees its own stdout via `logtee.py`.
- `forker/__main__.py` starts the scheduler + sync threads, then serves the UI.
- `service.py:_scheduler_thread` is a **15s heartbeat**: it decides when work is
*taken*; each mirror's own interval (`INTERVAL`, or `sync_interval` per mirror)
gates the enqueue. `pacer.py` recomputes per tick an **auto-pace floor** from
the anonymous-GitHub-API budget (48/h = 80% of 60): the effective interval is
`max(INTERVAL, required)` — auto only ever slows down, never resurrects
`INTERVAL=0`, and never paces a pinned or tokened mirror. `PARALLELISM`
(default 1) bounds concurrency so two passes never push the same repo at once.
- `engine.py:SyncWorker.sync` is the whole pass: fetch → push branches → push
tags → prune → heal default branch → disable foreign workflows → releases →
Releases-unit check.
- The UI (`ui/`) is a React SPA served by `api.py` from `ui/dist`; the browser
talks to `/api/*` on the same origin. `ui/vite.config.ts` proxies `/api` to the
container for `npm run dev` (override with `BACKEND=…`).
## Known Gitea-build quirks (verified on git.lago.dev, Gitea 28.1.0)
- **Forks are created without the Releases unit**
(`DefaultForkRepoUnits = [Code, PullRequests]`) → release assets 404 on the
web download route (`context.RequireUnitReader`), the source tarball 404s
too, while the API by-id works. Fix: enable the Releases unit
(Settings → Repository, or DB `INSERT INTO repo_unit (repo_id, type) ... 4` —
there is no units API on this build). `check-unit.sh` detects/fixes.
**Prefer generating from this template over forking**: generated repos are
not forks and get the full unit set (and Gitea only allows 1 fork of a
repo per user).
- **GitHub asset gotcha**: for a release addressed by *tag*, the asset
`download_url` is **null** — the API `url` returns JSON metadata unless
`Accept: application/octet-stream` is sent. `provider.sh` instead resolves
to the **web download URL** (`github.com/.../releases/download/<tag>/<file>`),
which is also unthrottled (the REST asset endpoint is 60 req/h
unauthenticated — not enough to mirror ~200 assets).
- Runner registration: the `gitea/act_runner` CLI (old and new) fails on this
build ("instance address is empty"); runner creation via API is 405.
Existing runners can be made shared via `PATCH /api/v1/admin/actions/runners/<id>`.
- `actions/cache` timeouts on this build are handled with
`continue-on-error: true` (cold fetch is still correct). The artifact cache
service itself is NOT configured on this Gitea — every sync is a cold fetch
(correct, slower; the cache steps are kept in case a backend is added).
- **Upstream CI rides the mirror**: mirrored branches carry the upstream's
`.github/workflows/*` (cron/push triggers). Gitea runs them on this runner
and they fail on missing GitHub infra (`gh: command not found`, labeler
actions), burning the serial runner's slots. Mirrored refs must stay
byte-identical, and the Actions token cannot disable workflows (403) — so
the **UI server** (`ui/server/server.js`, admin token) auto-disables every
workflow except `sync.yml`/`release.yml`/`runner-check.yml` on a 5-min
loop (`ensureUpstreamWorkflowsDisabled`; PUT `/workflows/{file}/disable` —
this build 405s on POST and reports state `disabled_manually`). Caveat:
workflow list is keyed by FILENAME, so an upstream `release.yml` cannot be
disabled without killing the mirror's own release workflow — it stays on.
- **Per-job DNS flapping:** the ephemeral per-job container intermittently
fails to resolve `git.lago.dev` on the fork push (the runner daemon's own
network resolves fine). `sync.sh` therefore wraps every fork push in
`push_once` — retry with backoff on transient network errors (resolve /
connect / timeout), abort immediately on non-network failures.
## Editing the template vs. a mirror repo
- **Template** (this repo): edit on `forker` and `git push`. Mirror repos do
**not** auto-track the template — sync them manually after a template
change:
- **Forked repos** (e.g. `Lago/photocraft`): the `forker` branch *is* a
descendant of the template's, so a normal merge works:
```
git remote add template <template-url>
git fetch template forker
git checkout forker && git merge template/forker
git push origin forker
```
- **Generated repos** (e.g. `Lago/pdfcraft`): the `forker` branch is an
**unrelated snapshot** (no common ancestor — `git merge` fails with
add/add conflicts). Reset it to the template and re-apply the single
per-repo setting, then force-push:
```
git checkout forker
git fetch template forker
git reset --hard template/forker
# re-apply this repo's .forker.yaml setting(s), e.g.:
sed -i 's/^mirror_upstream_releases: false/mirror_upstream_releases: true/' .forker.yaml
git commit -am "Adopt template; enable mirror_upstream_releases"
git push --force origin forker
```
This is safe: `forker` holds only the machinery + config (the upstream
content lives on the mirrored branches), so the snapshot's extra content
is discarded by design.
- **Per-repo config**: edit `.forker.yaml` in the UI on the `forker` branch.
Pushing to `forker` triggers a re-sync.
## Local testing (without the runner)
## Verifying a change
```bash
make test # unit tests (config parser, provider URL math, api shaping)
# + `cd ui && npx tsc --noEmit && npm run build`
make test-e2e # throwaway Gitea in Docker: create → sync → release (mirror and
# build) → prune → scheduler → adopt → delete → SIGTERM
```
export UPSTREAM_URL=... UPSTREAM_TOKEN= # empty for public upstreams
export GITEA_TOKEN=... GITEA_SERVER_URL=... GITEA_OWNER=... GITEA_REPO=...
bash forker/sync.sh # full mirror (use a scratch repo!)
bash forker/release.sh <tag>
make check-unit
`tests/e2e.sh` is the authority on "does it actually work": it asserts real
git/Gitea state (commit hashes identical to upstream, an asset returning 200 over
the **web download** route, the `forker` branch surviving every pass), not canned
data. Never call work done on `make test-py` alone if you touched the
sync/release path.
To poke it by hand:
```bash
REMOTE=http://127.0.0.1:3099 TOKEN=… OWNER=forge DATA_DIR=$PWD/.dev-test/data \
PORT=8741 UI_DIST=$PWD/ui/dist python3 -m forker
curl -s localhost:8741/api/status | python3 -m json.tool
```
Test against a **scratch repo** you delete afterwards; never point the scripts
at a real mirror while experimenting. `GITEA_TOKEN` from Actions is an API
token (Bearer works for API + git); a *password* only works for basic auth —
expect the Bearer API calls to fail when testing with a password.
Use a scratch Gitea (`make test-e2e` spins one in Docker under `.dev-test/`,
gitignored); never point the worker at a real mirror while experimenting.
## Local dev (no Docker)
`REMOTE=… TOKEN=… OWNER=… DATA_DIR=$PWD/.dev-test/data PORT=8741 python3 -m forker`
+ `cd ui && npm run dev` (Vite proxies `/api` to the container; `BACKEND=…`
overrides). The container is only needed for the packaged end state.
## Known Gitea-build quirks (re-verified on 1.22.4, seen on git.lago.dev 28.1.0)
- **Repos created as forks lack the Releases unit** (`DefaultForkRepoUnits`) →
asset web downloads 404 on `RequireUnitReader` while the by-id API works. No
units API on these builds. `engine._unit` tries
`PATCH /repos/{repo} {"has_releases":true}`, re-checks, and reports
`unitFix: "manual"` (fix once: Settings → Repository → Releases) when it
cannot. Prefer creating mirrors from the container: non-fork repos get the
full unit set, and Gitea only allows one fork of a repo per user anyway.
- **Reading a file in a repo with no commits returns `500 "no open git repo"`**,
not 404, and `GET contents` returns `[]`. Both mean "absent" here
(`gitea.py:get_file`) — the first `.forker.yaml` write of a fresh mirror
depends on it.
- **`POST /repos/{repo}/contents/{path}` births the branch only on an EMPTY
repo**; on a repo with commits it answers 404 "branch does not exist", and
`PUT` before that 500s. `write_file` chooses the verb by file state, falls
back on a 409/422 race, and on that 404 cuts the branch from the default
branch (`POST /branches`, which works even with content) and writes again —
this is what lets a repo that already has history (the pipeline era, or a
push before registration) become a mirror. Verified against the built image.
- **`PATCH default_branch` is a silent 200 no-op** until the target branch
exists, so the default branch is re-checked every pass and self-heals.
- Actions quirks that survive only in the defensive workflow-disable path: the
runs API ignores `?workflow=` (it honors `?branch=`), a disabled workflow
reports `disabled_manually`, a workflow `id` is the *filename*, and the
disable verb is `POST` in the docs but this build answers `PUT` — so both are
tried.
- **`build_cmd`/`build_script` run with the container's credentials in scope.**
Anyone who can push to a mirror's `forker` branch can run commands here — same
trust the runner had, but say so in the README. Build output is streamed to
the run log so a failure is diagnosable instead of a bare "exit 127".
## Per-mirror config
Edit a mirror's `.forker.yaml` in the UI (**Mirror → Config**) or on that
mirror's `forker` branch in Gitea; either way it is re-read next pass. To run it
now: `POST /api/mirrors/<name>/sync`, or the Re-sync button.
## File map
- `forker/sync.sh` — mirror worker (fetch/push/prune + inline releases + unit check)
- `forker/release.sh` — local build + upstream-release mirror, idempotent
- `forker/check-unit.sh` — Releases unit detection/self-heal (exit 10 = missing)
- `forker/lib/config.sh` — flat `.forker.yaml` parser
- `forker/lib/provider.sh` — provider-agnostic releases API (github/gitea/codeberg)
- `forker/runner-register.sh` — runner registration (see quirks above)
- `.gitea/workflows/` — sync.yml (cron), release.yml (manual), runner-check.yml
- `runner/docker-compose.yml` — gitea-act-runner in Docker (tracked; the local
`runner/config/` token dir is gitignored)
- `Makefile` — local targets (sync / release / mirror-releases / runner-check /
runner-register / check-unit); `runner-check` queries the Gitea runner APIs
- `docs/index.html` — architecture webpage (static)
- `Dockerfile`, `docker-compose.yml`, `docker/entrypoint.sh` — the deliverable
- `forker/config.py` — env `Settings` + flat `.forker.yaml` parse/render
- `forker/engine.py` — the sync pass + releases (the heart)
- `forker/gitops.py` — bare-mirror fetch/push/prune, `ls-remote`, error hints
- `forker/gitea.py` — Gitea REST client (repos, contents, releases, units)
- `forker/provider.py` — upstream releases (github/gitea/codeberg), anonymous
- `forker/pacer.py` — GitHub anonymous-API budget → the effective interval
- `forker/registry.py` — mirror records: create/adopt/update/delete, parity
- `forker/service.py` — boot/self-register, scheduler, queue, graceful stop
- `forker/api.py` — `/api/*` + static UI serving (stdlib `http.server`)
- `forker/state.py` — `state.json` + per-run logs · `logtee.py` — stdout tee
- `ui/` — React control plane (served by the container, `npm run dev` locally)
- `tests/test_worker.py`, `tests/e2e.sh` — the two verification tiers
- `docs/index.html` — architecture page
## Removing the pipeline era (done here, don't resurrect it)
Deleted: `.gitea/workflows/*`, `runner/`, `forker/{sync,release,check-unit,runner-register}.sh`,
`forker/lib/*`, `ui/server/` + `ui/bin/` (the Node proxy). The port of each
behavior into Python, and what got *better* because the container is stateful
and holds an admin token, is documented in `README.md` ("What changed").
+79
View File
@@ -0,0 +1,79 @@
# syntax=docker.io/docker/dockerfile:1
#
# Repo Forker — one container, everything inside it.
#
# stage 1 builds the React app (ui/dist)
# stage 2 a slim Python runtime that holds the worker AND serves that app
#
# The worker no longer needs a Gitea Actions runner: the scheduler, the git
# mirrors and the UI are all in here. Only two things are required at run time:
# REMOTE (the Gitea base URL to push mirrors to) and TOKEN (a Gitea admin token).
# ---------------------------------------------------------------- stage 1: UI
FROM docker.io/node:22-alpine AS ui-build
WORKDIR /build/ui
# Install first so a source-only change does not re-resolve the dependency tree.
COPY ui/package.json ui/package-lock.json ./
RUN --mount=type=cache,target=/root/.npm npm ci --no-audit --no-fund
COPY ui/ ./
RUN npm run build
# ------------------------------------------------------------- stage 2: worker
FROM docker.io/python:3.12-slim-bookworm
# git : the whole mirror mechanism is git fetch/push/ls-remote/archive
# curl : the image healthcheck
# ca-certificates: HTTPS to the remote + to upstreams
# build tooling is deliberately NOT baked in — every mirror builds something
# different, so pass what you need with EXTRA_APT_PACKAGES (see README).
ARG EXTRA_APT_PACKAGES=""
RUN apt-get update \
&& apt-get install -y --no-install-recommends \
git curl ca-certificates tar gzip ${EXTRA_APT_PACKAGES} \
&& rm -rf /var/lib/apt/lists/* \
&& git config --system --add safe.directory '*'
# Non-root: /data is a mounted volume and must stay chown-able for uid 10001.
RUN useradd --uid 10001 --create-home --shell /usr/sbin/nologin forker
WORKDIR /app
# The worker is stdlib-only on purpose: nothing to `pip install`, so the image
# has no dependency supply chain and starts instantly.
# chmod a+rX, because COPY preserves the SOURCE file mode: a working tree whose
# .py files are 0600 baked an image the runtime user could not read
# (PermissionError on __main__.py). a+rX adds read to everything and the
# traverse bit to directories only — unlike COPY --chmod, which would strip the
# x from the directories it flattens. The image must not inherit host modes.
COPY forker/ /app/forker/
COPY --from=ui-build /build/ui/dist/ /app/ui/dist/
RUN chmod -R a+rX /app/forker /app/ui/dist
ENV PYTHONUNBUFFERED=1 \
PYTHONDONTWRITEBYTECODE=1 \
DATA_DIR=/data \
HOST=0.0.0.0 \
PORT=8731 \
UI_DIST=/app/ui/dist \
WORKER_LOG=/data/logs/worker.log \
INTERVAL=600 \
PARALLELISM=1
VOLUME ["/data"]
# The UI is the published port — it is the container's only front door.
EXPOSE 8731
COPY docker/entrypoint.sh /usr/local/bin/repo-forker
RUN chmod +x /usr/local/bin/repo-forker
HEALTHCHECK --interval=30s --timeout=10s --start-period=20s --retries=3 \
CMD curl -fsS "http://127.0.0.1:${PORT}/api/health" || exit 1
# Deliberately NOT `USER forker`: a bind-mounted /data usually arrives owned by
# a human uid, and a non-root entrypoint could not fix that. The script starts
# as root, chowns the volume and drops to uid 10001 itself — and if you start
# the container with your own `user:`, it skips the drop and just runs.
ENTRYPOINT ["/usr/local/bin/repo-forker"]
+75 -33
View File
@@ -1,43 +1,85 @@
# Repo Forker — convenience targets.
# Most work happens in the Gitea Actions workflows; these targets are for local
# use (dry-runs, runner setup) and for debugging on the runner.
# Repo Forker — Docker-first targets.
#
# The pipeline model needed a runner, workflows and a local Node proxy. Now
# there is one container: `make up` starts it, serves the UI on localhost:8731
# and runs the mirror scheduler inside it. The image ships in the Gitea
# container registry (git.lago.dev/lago/repo-forker); building from source
# still works with `make build`.
CONFIG_FILE ?= .forker.yaml
UI_PORT ?= 8731
IMAGE ?= git.lago.dev/lago/repo-forker:latest
.PHONY: help sync release mirror-releases runner-check runner-register check-unit
.PHONY: help build pull push up down restart logs status ui ui-dev test test-py \
test-e2e clean clean-data secret-check
help:
@echo "Repo Forker targets:"
@echo " sync Run a manual sync (needs UPSTREAM_* + GITEA_* env)"
@echo " release TAG=x Run a release for tag x"
@echo " mirror-releases Mirror upstream releases for a tag (release.sh MIRROR)"
@echo " runner-check Run the runner-check workflow logic locally"
@echo " runner-register Register a shared gitea-act-runner (see README)"
@echo " check-unit Verify the Releases unit is enabled (fork quirk)"
@echo "Repo Forker (Docker) targets:"
@echo " up Start the container from the published image"
@echo " (needs REMOTE + TOKEN; docker login git.lago.dev once)"
@echo " pull Refresh the local copy of the published image"
@echo " build / push Build the Dockerfile locally / publish it to the registry"
@echo " down / restart Stop / restart it"
@echo " logs Follow container logs (scheduler + syncs)"
@echo " status Query /api/status from the running container"
@echo " ui Build the UI (npm) — the image builds it too"
@echo " ui-dev Vite dev server against the running container"
@echo " test Python unit tests + UI typecheck/build"
@echo " test-e2e Full cycle against a throwaway Gitea in Docker"
@echo " clean-data Delete the data volume (all mirrors + state)"
sync:
bash forker/sync.sh
# ------------------------------------------------------------------ container
build:
IMAGE=$(IMAGE) docker compose build
release:
@test -n "$(TAG)" || (echo "make release TAG=<tag>"; exit 1)
bash forker/release.sh "$(TAG)"
pull:
docker compose pull
mirror-releases:
@test -n "$(TAG)" || (echo "make mirror-releases TAG=<tag>"; exit 1)
bash forker/release.sh "$(TAG)"
# Publish the local build. Requires: docker login git.lago.dev
push: build
docker push $(IMAGE)
runner-check:
@test -n "$(GITEA_SERVER_URL)" -a -n "$(GITEA_TOKEN)" -a -n "$(GITEA_OWNER)" -a -n "$(GITEA_REPO)" \
|| { echo "needs GITEA_SERVER_URL/GITEA_TOKEN/GITEA_OWNER/GITEA_REPO (or run the workflow instead)"; exit 1; }
@curl -sS --max-time 20 -H "Authorization: Bearer $(GITEA_TOKEN)" \
"$(GITEA_SERVER_URL)/api/v1/repos/$(GITEA_OWNER)/$(GITEA_REPO)/actions/runners" > /tmp/rc_repo.json
@curl -sS --max-time 20 -H "Authorization: Bearer $(GITEA_TOKEN)" \
"$(GITEA_SERVER_URL)/api/v1/admin/actions/runners?limit=50" > /tmp/rc_shared.json || true
@python3 -c 'import json; R=json.load(open("/tmp/rc_repo.json")).get("runners",[]); S=[r for r in json.load(open("/tmp/rc_shared.json")).get("runners",[]) if r.get("shared")]; print("Repo-scoped runners: "+(", ".join("%s (%s)"%(r["name"],r["status"]) for r in R) or "(none)")); print("Shared runners: "+(", ".join("%s (%s)"%(r["name"],r["status"]) for r in S) or "(none)")); print("OK: a runner serves this repo." if (R or S) else "WARNING: no runner (repo-scoped or shared) registered - cron runs will stay queued.")'
@rm -f /tmp/rc_repo.json /tmp/rc_shared.json
up: secret-check
docker compose up -d
@echo "UI -> http://127.0.0.1:$(UI_PORT) (the published container port)"
runner-register:
bash forker/runner-register.sh
down:
docker compose down
check-unit:
bash forker/check-unit.sh
restart:
docker compose restart
logs:
docker compose logs -f
status:
@curl -s http://127.0.0.1:$(UI_PORT)/api/status | python3 -m json.tool
# Fails before docker does, naming the variable instead of printing a compose error.
secret-check:
@sh -c 'if [ -z "$${REMOTE:-}" ]; then grep -qs "^REMOTE=..*" .env || { echo "set REMOTE (env var or .env — see .env.example)"; exit 1; }; fi; \
if [ -z "$${TOKEN:-}" ]; then grep -qs "^TOKEN=..*" .env || { echo "set TOKEN (env var or .env — see .env.example)"; exit 1; }; fi'
# ------------------------------------------------------------------------ ui
ui:
cd ui && npm ci && npm run build
@echo "then: make push -> the published image, or make up for the local build"
ui-dev:
cd ui && BACKEND=http://127.0.0.1:$(UI_PORT) npm run dev
# ---------------------------------------------------------------------- test
test: test-py
cd ui && npx tsc --noEmit && npm run build
test-py:
python3 -m unittest discover -s tests -v
# End-to-end: throwaway Gitea + upstream fixture; real create/sync/prune/release.
test-e2e:
./tests/e2e.sh
clean:
rm -rf ui/dist .dev-test forker/__pycache__ tests/__pycache__
clean-data:
docker compose down -v
+367 -183
View File
@@ -1,221 +1,405 @@
# Repo Forker
> 📖 **Documentación y arquitectura interactiva:** [docs/index.html](docs/index.html) — qué es, cómo funciona, cómo crear un fork paso a paso, runner, config y limitaciones.
> 🖥️ **UI de gestión local (mirrors):** [ui/README.md](ui/README.md) — `cd ui && npm install && npm run build && node bin/repo-forker-ui.js` → http://127.0.0.1:8731. Crea/elimina/monitorea mirrors, paridad vs upstream, logs en vivo, cola del runner.
> 📖 **Arquitectura interactiva:** [docs/index.html](docs/index.html)
Turn **any** git repo (GitHub, Gitea, Codeberg, …) into a **live mirror on your
Gitea** — all branches, all tags, full commit history — synced very
periodically by a Gitea Actions runner (your "gitea worker"), with releases
produced **locally on the runner** (and optionally mirrored from the upstream).
Gitea** — all branches, all tags, full commit history — plus releases built or
mirrored per tag.
This repo is a **template**. You **fork** it once per upstream; the fork *is*
the mirror. The upstream's content never touches the working tree: upstream
objects live in a bare mirror (`.mirror/`, gitignored) and are pushed as refs
so they show up in the Gitea UI.
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 |
```
Fork of this template (Lago/<upstream>)
├── working tree (forker branch) ← the machinery: scripts, config, workflows
├── .mirror/ ← bare mirror of the upstream (gitignored)
└── refs: <upstream branches> + <tags> ← visible in the Gitea UI
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
```
## How it works
## What changed (and why)
1. **Sync (the worker).** A cron workflow runs every N minutes. `sync.sh` fetches
all branches + tags + full history from the upstream into a true bare mirror
(`.mirror/`), then pushes them onto this fork and **prunes** what the upstream
deleted. The fork's current state is read via the Gitea API (not git state),
so prune + change-detection work even when the workspace is wiped between
runs. `actions/cache` restores `.mirror/` when possible → incremental fetches.
2. **Release (local build).** When sync detects a **new tag**, it invokes
`release.sh` inline: checkout the tag's tree, run your build command **on the
runner**, publish the release (tag + assets) on this Gitea. (A tag-push can't
trigger a workflow on its own — the tag points at an upstream commit whose
tree has no `.gitea/workflows` — so sync does it.) Re-running is idempotent:
an existing release is skipped, not duplicated.
3. **Release (mirror, optional).** If enabled, the upstream's existing release
(metadata + assets) is copied over via the provider API
(GitHub / Gitea / Codeberg — auto-detected in `forker/lib/provider.sh`).
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.
## Quick start (3 steps)
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.
### 1. Fork this template
In the Gitea UI: **this repo → Fork** → name it after the upstream
(e.g. `Lago/some-upstream`).
Now the same logic runs as a Python worker in a stateful container:
### 2. Point it at the upstream (the "remote")
In the fork: **Settings → Actions → Variables & Secrets**
- **Variable** `UPSTREAM_URL` = `https://github.com/owner/repo.git` (any provider)
- **Secret** `UPSTREAM_TOKEN` = *(optional — only for private upstreams.)*
Public upstreams are mirrored **anonymously** and the tool never
authenticates against them: the global/system git config and the
credential helper are cut for all upstream git calls, so a stored
`~/.git-credentials` entry is never used. Only set a token when the
upstream is private (or you need a higher API rate for mirrored
releases).
| 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 | `PATCH`ed 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 |
Everything non-secret (which branches, how often, build command, artifacts) lives
in **`.forker.yaml`** — edit it in the UI on the `forker` branch.
## Quick start
> The `GITEA_*` values (server URL, owner, repo, token) are injected
> automatically by Gitea Actions — you don't set them. (`GITEA_TOKEN` in the
> workflow env block is Gitea's **built-in** Actions secret, not a
> user-created secret — don't create one.)
### 1. Give it two variables
### 3. Make sure a runner serves this repo
In this Gitea build, **runners are repo-scoped**: a runner registered on one
repo does **not** serve another. So either:
```bash
cp .env.example .env
```
- **Shared runner (recommended, one-time):** register a single runner that serves
**all** repos. See [Runner](#runner).
- **Per-repo runner:** register a runner for this specific repo.
A complete `.env` (only the first three lines are ever required):
Then trigger **Settings → Actions → "Repo Forker — Runner check"** and confirm it
completes. If sync runs stay *pending* for a long time, no runner is serving
this repo.
```bash
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
That's it. The cron sync starts pulling the upstream in, and releases are
produced locally when tags appear. Note: with the template defaults
(`build_cmd` empty, `mirror_upstream_releases: false`) there is nothing to
build, so new tags are mirrored as **refs only** — set a `build_cmd` /
`build_script` (or `mirror_upstream_releases: true`) for releases to appear.
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
```
## Configuration (`.forker.yaml`)
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
```bash
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:
```bash
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`:
```yaml
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`):
```bash
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 |
|---|---|---|
| `token_user` | `oauth2` | *(unused — Bearer auth needs no username; retained for compatibility)* |
| `mirror_tags` | `true` | Mirror all tags |
| `mirror_prune` | `true` | Prune branches deleted upstream |
| `mirror_branches` | `*` | `*` = all, or a comma list (`main,develop`) |
| `on_new_tag` | `true` | Build+publish a release when a new tag is mirrored |
| `mirror_upstream_releases` | `false` | Also copy the upstream's release (metadata + assets) |
| `build_cmd` | — | Build command(s), `;`-separated, run in the tag's tree |
| `build_script` | — | Path to a custom build script (overrides `build_cmd`) |
| `artifacts` | — | Space-separated globs of files to attach to the release |
| `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/*`) |
## Manual triggers
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.
- **Sync now:** Settings → Actions → *Repo Forker — Sync* → Run workflow.
- **Release a tag:** Settings → Actions → *Repo Forker — Release* → Run workflow
→ enter the tag.
- **Check the runner:** Settings → Actions → *Repo Forker — Runner check*.
## Releases
Or from a machine that has the repo + env vars: `make sync`,
`make release TAG=v1.2.3`.
Two modes, both opt-in per mirror, both run inside the container:
## Runner
- **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.
The sync (cron) and the local release build both need a **Gitea Actions runner**
serving the repo. In this build, runners are **repo-scoped**, so the clean path
is a **shared runner** registered once:
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.
```bash
# install gitea-act-runner (see the Gitea runner docs), then:
GITEA_SERVER_URL=https://git.lago.dev \
GITEA_TOKEN=<admin-token> \
GITEA_OWNER=Lago GITEA_REPO=any \
bash forker/runner-register.sh shared
# then start it (e.g. via docker, see runner/docker-compose.yml)
gitea-act-runner run
```
`forker/runner-register.sh` auto-generates a registration token via
`POST /api/v1/admin/actions/runners/registration-token` (verified working on this
instance) and registers either a **shared** runner or a **per-repo** one.
> The existing online runner on this instance (id 3, `496cfb9f4583`,
> `ubuntu-latest/24.04/22.04`) is registered to `Lago/Tide` only — it will not
> serve your forks. Register a shared runner (or one per repo) as above.
> **This Gitea build quirk (verified):** the `act_runner` CLI fails to
> register ("instance address is empty") on both `gitea/act_runner:0.6.1`
> and `0.2.13`, and the runner-creation API returns 405. The path that
> **does** work: take an existing registered runner and PATCH it to shared:
> ```bash
> curl -X PATCH "$GITEA_SERVER_URL/api/v1/admin/actions/runners/<id>" \
> -H "Authorization: Bearer $GITEA_TOKEN" \
> -d '{"name":"gitea-runner-forker","labels":["ubuntu-latest"],"shared":true,"disabled":false}'
> ```
> then point a `gitea/act_runner:0.6.1` container at its config
> (`runner/docker-compose.yml`).
> 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
```
repo-forker/
├── .gitea/workflows/
│ ├── sync.yml # cron: mirror upstream (the "worker"); restores .mirror cache
│ ├── release.yml # MANUAL only (a tag push can't trigger it); see sync.sh
│ └── runner-check.yml # verify a runner serves this repo
├── forker/
│ ├── sync.sh # true-mirror fetch + push + prune + inline new-tag release + unit check
│ ├── release.sh # local build + publish release (± mirror upstream), idempotent
│ ├── runner-register.sh # register a shared / per-repo runner
│ ├── check-unit.sh # verify/fix the Releases unit (Gitea fork quirk)
│ └── lib/
│ ├── config.sh # load .forker.yaml
│ └── provider.sh # detect provider + releases API (Gitea/GitHub/Codeberg)
├── .mirror/ # bare mirror (gitignored, cached by the workflow)
├── .forker.yaml # per-fork config (non-secret)
├── Makefile
├── runner/docker-compose.yml
└── README.md
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
```
## Notes & limitations
## Security
- **Releases are not git objects.** Git only carries the *tag*; release *assets*
live on the Gitea. "Local release" = build on the runner + upload via the
Gitea API. Mirroring upstream assets works anonymously for public upstreams
(a token is only needed for private ones).
- **Ephemeral workspace.** The Gitea runner wipes the workspace between runs.
`sync.sh` is written to not depend on leftover git state: it re-reads the fork's
current refs via the API every run. `actions/cache` on `.mirror/` makes the
fetch incremental when it hits; a cold cache just means a full-history fetch
(correct, slower).
- **Tags point at upstream commits.** That's intentional — it keeps commit
hashes identical to the upstream. It also means the workflow can't be
triggered *by the tag* (the tag's tree has no workflows), so sync triggers
releases inline.
- **Provider differences** (releases API, token username) are isolated in
`forker/lib/provider.sh`; the rest is provider-agnostic.
- **Secrets stay out of the repo.** Upstream URL/token are Gitea Actions
Variables/Secrets; the Gitea token is the built-in `GITEA_TOKEN`.
- **Runner is the hard dependency.** Without a runner serving the repo, the cron
sync and local builds won't run — run the *Runner check* first.
- **Gitea forks ship without the Releases unit → asset downloads 404.**
Root cause found on this instance (verified in the Gitea source + DB): a fork
is created with `DefaultForkRepoUnits = [Code, PullRequests]` — **no
Releases unit** — while normal repos get it. So release *assets* uploaded to
a fork repo are listed in the API (by-id works) but the web
`browser_download_url` returns 404 at the unit-permission check, and the
release *source tarball* 404s too.
**Detected + fixed:** `sync.sh` runs `check-unit.sh` at the end of every
sync — it self-heals via the units API on builds that expose it, and on
this build (no units API) it detects the 404 (confirming the API by-id
path still works) and prints the exact one-time fix: UI → Settings →
Repository → enable the **Releases** unit. `make check-unit` runs it
standalone.
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.
## Security notes
- **`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.
- **Upstreams are fetched anonymously by default.** `sync.sh` / `release.sh`
cut `GIT_CONFIG_GLOBAL`/`GIT_CONFIG_SYSTEM` and the credential helper before
any upstream git call, and add a Bearer header **only** when `UPSTREAM_TOKEN`
is set. A stored `~/.git-credentials` entry is therefore *never* offered to
`git fetch` — a public upstream is a pure anonymous fetch.
- **`build_cmd` / `build_script` run with the tokens in the environment.**
`release.sh` keeps `GITEA_TOKEN` and `UPSTREAM_TOKEN` set so it can fetch the
tag's tree and publish assets. Any repo member can edit `.forker.yaml`, so a
malicious `build_cmd` could exfiltrate both tokens. Treat `build_cmd` /
`build_script` as **trusted code with credential access** — only put commands
you (or the repo owners) trust there.
- **Tokens briefly persist in the cached `.mirror/` git config.** The per-URL
`http.<url>.extraHeader` Bearer header is written into `.mirror/config`, and
`.mirror/` is the `actions/cache` path. The cache is repo-scoped (not
committed), but a cache-service reader can read it until the next save
overwrites it. The tokens are never written into the repo itself.
## 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.
```bash
make pull && make up # deploy whatever main just published
```
## Operations
```bash
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.
-102
View File
@@ -1,102 +0,0 @@
# TODO — a futuro
## [UI] Gestión local de mirrors (npx)
Una web local (arrancable con `npx`) para gestionar todo el ecosistema de
Repo Forker desde un solo lugar, sin tocar API/curl/DB.
### Idea
```
npx repo-forker-ui # -> http://localhost:8731 (o el puerto libre)
```
El UI habla con la API de Gitea (con un token que el usuario pega una vez,
guardado localmente — nunca en el repo) y ejecuta las mismas operaciones que
los scripts, pero de forma guiada.
### Features (por prioridad)
**P0 — Gestión de mirrors (el corazón):**
- **Crear un mirror**: pega la URL del upstream (GitHub/Gitea/Codeberg/otro)
+ nombre → el UI hace lo que se hace hoy por API/curl:
1. `POST /repos/{owner}/repo-forker/generate` con `git_content: true`
2. crea la variable `UPSTREAM_URL` (`POST .../actions/variables/UPSTREAM_URL`)
3. `PATCH` default branch → la del upstream (o `main`)
4. activa `mirror_upstream_releases` en la rama `forker` (reset + re-apply,
el procedimiento de AGENTS.md para repos generados)
5. dispara el primer `sync.yml` (dispatch) y muestra el progreso
- **Lista de mirrors**: todos los repos generados desde `repo-forker`
(detectables por la rama `forker` + la variable `UPSTREAM_URL`), con:
- estado del último `sync.yml` (green/red, timestamp, duración)
- branches / tags / releases / assets (vs upstream — paridad)
- unidades activas (Code/Issues/PR/Releases/...)
- **Stats y gráficas** (por mirror y agregado):
- timeline de runs (success/failure/queued) — sparkline de los últimos 7 días
- tiempo de sync por run (cold vs incremental — la caché, cuando exista)
- assets por release (barras), crecimiento de branches/tags
- latencia de mirror: commits upstream sin replicar todavía
- **Eliminar un mirror**: delete del repo (con confirmación + advertencia de
lo que se pierde; el template queda intacto)
- **Re-sincronizar / forzar**: dispatch manual de `sync.yml` / `release.yml` /
`runner-check.yml` desde la UI
- **Config per-repo**: editar `.forker.yaml` (los campos conocidos:
`mirror_branches`, `mirror_tags`, `mirror_prune`, `mirror_upstream_releases`,
`build_cmd`, `build_script`, `artifacts`, `on_new_tag`) con validación de
esquema plano (el parser es grep — el UI debe mantenerlo plano)
- **Variables & secrets**: listar/crear/borrar las Variables de Actions
(`UPSTREAM_URL`, `UPSTREAM_TOKEN` opcional) — los secrets solo se crean,
no se leen (la API no los devuelve)
**P1 — Observabilidad:**
- **Cola del runner**: runs `queued`/`in_progress` en vivo (polling), con
tiempo de espera — el runner es serial (maxParallel=1), así que una vista
de "fila" es muy útil
- **Logs en vivo** de un run (stream del log del job, con el
`::group::`/`::notice::` de Gitea Actions renderizado)
- **Diagnóstico de un run fallido**: extraer la línea de error del log y
sugerir la causa (DNS flap, cache timeout, token, unidad Releases)
- **Unidades**: ver/quitar/habilitar la unidad Releases (con fallback a DB
cuando la API no existe — este build)
- **Alerta** de mirror "desactualizado" (última sync > N min con runner idle)
**P2 — Extras:**
- **Generar desde otros templates**: que el UI permita usar cualquier repo
marcado `template: true` (no solo repo-forker)
- **Import de config**: pegar un `.forker.yaml` y aplicarlo
- **Export del estado**: snapshot JSON de todos los mirrors (para backups /
re-crear después de una catástrofe)
- **Comparador de paridad**: side-by-side upstream vs fork (branches/tags/
releases) con diff visual (lo que falta se marca)
### Notas de diseño
- **Stack sugerido**: Vite + React (o SvelteKit) + Tailwind; el backend
"npx" puede ser un thin server Node que solo hace proxy + auth al Gitea
(el UI puede ser 100% client-side si el token se guarda en `localStorage`;
el proxy solo evita CORS y esconde el token de los logs del navegador).
- **Auth**: el usuario pega su token Gitea (o basic) una vez; se guarda en
`~/.repo-forker/credentials` (chmod 600) o `localStorage` según el modo.
NUNCA se sube al repo.
- **Idempotencia**: todas las acciones de creación deben ser idempotentes
(re-crear el mirror con el mismo nombre → "ya existe" + enlazar).
- **No duplicar lógica**: las operaciones (generate, variable, default branch,
forker reset+re-apply, dispatch) ya están probadas en esta sesión — el UI
las reproduce tal cual, no inventa variantes.
- **Modo offline**: la UI debe funcionar aunque el Gitea esté caído (los
últimos datos cacheados + estado "offline").
### Criterio de "hecho" (P0)
1. `npx repo-forker-ui` arranca y se conecta a un Gitea (URL + token).
2. Desde la UI: crear un mirror de un repo GitHub público → aparece en la
lista con su primer sync en verde y paridad correcta.
3. Eliminar un mirror desde la UI (con confirmación).
4. Ver en la UI: últimos 20 runs de cada mirror, paridad de
branches/tags/releases, y el log del último run.
5. Re-sincronizar (dispatch) desde la UI.
### Estado: **A FUTURO — no empezar sin revisar esta spec**
La infraestructura ya soporta todo lo que el UI necesita (APIs de generate,
variables, dispatch, runners, releases; scripts de sync con retry; `check-unit`;
cron de limpieza en tizona). Faltan decisiones: stack, nombre del paquete,
y si el modo "solo client-side con token en localStorage" es suficiente.
+13
View File
@@ -0,0 +1,13 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512">
<rect width="512" height="512" rx="96" fill="#0b1220"/>
<rect x="8" y="8" width="496" height="496" rx="88" fill="none" stroke="#4de1ff" stroke-opacity="0.35" stroke-width="10"/>
<g fill="none" stroke="#4de1ff" stroke-width="34" stroke-linecap="round">
<line x1="166" y1="132" x2="166" y2="380"/>
<path d="M166 254h112a72 72 0 0 0 72-72v-50"/>
</g>
<g fill="#0b1220" stroke="#4de1ff" stroke-width="30">
<circle cx="166" cy="118" r="52"/>
<circle cx="166" cy="394" r="52"/>
<circle cx="350" cy="118" r="52"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 639 B

+64
View File
@@ -0,0 +1,64 @@
# Repo Forker — the whole thing in one container.
#
# The image is published in the Gitea container registry:
# docker login git.lago.dev # your Gitea user + a token with read:package
# REMOTE=https://git.lago.dev TOKEN=<admin token> docker compose up -d
#
# Building from source instead (hacking, or extra build toolchains) keeps
# working — it just lands on the same tag:
# docker compose up -d --build
#
# The UI is the published port. The worker (scheduler + mirrors) runs inside
# this same container: no runner, no pipelines, nothing else to deploy.
#
# Secrets are read from the environment (or a sibling .env file) and never
# baked into the image or committed.
services:
repo-forker:
# The published image by default; `--build` builds the local Dockerfile
# onto this same tag. Override the repo with IMAGE= if you mirror it
# somewhere else.
image: ${IMAGE:-git.lago.dev/lago/repo-forker:latest}
build:
context: .
dockerfile: Dockerfile
# Toolchains your mirrors' `build_cmd` needs are NOT in the base image —
# add them here and rebuild (nodejs, golang, rustc, make, …).
args:
EXTRA_APT_PACKAGES: ""
container_name: repo-forker
labels:
# UI hints for the Unraid Docker tab (net.unraid.stack.*); any other
# host simply ignores them. The icon is served raw by the repo itself.
- 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
restart: unless-stopped
environment:
# ---- required -----------------------------------------------------
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)}
# ---- optional -----------------------------------------------------
OWNER: ${OWNER:-} # namespace for mirrors (user or org); default: token's user
TEMPLATE: ${TEMPLATE:-repo-forker} # repo holding each mirror's forker branch
INTERVAL: ${INTERVAL:-600} # seconds between sync passes
PARALLELISM: ${PARALLELISM:-1} # concurrent mirror syncs (1 = serial)
PORT: ${PORT:-8731}
DATA_DIR: /data
ports:
# The UI is the only front door. It holds the admin token in-process and
# has no login of its own, so keep it loopback-bound unless you front it
# with a reverse proxy + auth (see README "Security").
- "${BIND_ADDR:-127.0.0.1}:${HOST_PORT:-8731}:8731"
volumes:
# Bare mirrors, the registry (state.json) and the logs. Back this up: it
# is what makes every sync after the first one incremental.
- forker-data:/data
stop_grace_period: 90s # let an in-flight push finish on `docker stop`
# Run as your own uid instead of root→10001 if you prefer the volume to be
# owned by you: user: "${UID:-1000}:${GID:-1000}"
volumes:
forker-data:
+36
View File
@@ -0,0 +1,36 @@
#!/usr/bin/env bash
# repo-forker — container entrypoint.
#
# Kept deliberately thin: the worker owns its own concerns (log tee, graceful
# SIGTERM shutdown, config validation) so that this stays the direct exec and
# `docker stop` sends SIGTERM straight to the Python process — a shell holding
# a `cmd | tee` pipeline would swallow it and kill a sync mid-push.
#
# It only does the two things Python cannot do for itself:
# 1. prepare a mounted /data that may arrive root-owned;
# 2. print the boot summary (masked) so `docker logs` explains the run.
set -uo pipefail
fail() { printf 'FATAL: %s\n' "$1" >&2; exit 2; }
[ -n "${REMOTE:-}" ] || fail "REMOTE is required — the Gitea base URL mirrors are pushed to (e.g. https://git.lago.dev)"
[ -n "${TOKEN:-}" ] || fail "TOKEN is required — a Gitea token that can create repos and publish releases (admin recommended)"
DATA_DIR="${DATA_DIR:-/data}"
mkdir -p "$DATA_DIR/mirrors" "$DATA_DIR/logs" 2>/dev/null \
|| fail "$DATA_DIR is not writable for uid $(id -u) — chown the volume, or set 'user: \"\$(id -u):\$(id -g)'"
# When started as root (the usual case for a bind-mounted volume owned by a
# human), hand /data to the app user and drop privileges.
if [ "$(id -u)" = "0" ]; then
chown -R forker:forker "$DATA_DIR" 2>/dev/null || true
if command -v setpriv >/dev/null 2>&1 && [ "$(id -u forker 2>/dev/null || echo 0)" = "10001" ]; then
exec setpriv --reuid forker --regid forker --clear-groups python3 -m forker
fi
fi
printf 'repo-forker REMOTE=%s OWNER=%s DATA=%s UI=:%s every %ss\n' \
"${REMOTE%/}" "${OWNER:-<token owner>}" "$DATA_DIR" "${PORT:-8731}" "${INTERVAL:-600}" >&2
cd /app
exec python3 -m forker
+757 -262
View File
File diff suppressed because it is too large. Load diff
+20
View File
@@ -0,0 +1,20 @@
"""Repo Forker worker — mirror upstreams into a Gitea, from inside one container.
Package layout (the whole machinery, no CI pipelines involved):
``config`` environment (REMOTE/TOKEN/…) + the flat ``.forker.yaml`` parser
``gitea`` minimal Gitea REST client (stdlib only)
``provider`` upstream *releases* API (GitHub / Gitea / Codeberg), anonymous by default
``gitops`` bare-mirror fetch / multi-ref push / prune
``engine`` one sync pass: fetch → push → prune → heal → releases
``registry`` the mirrors this container owns (create / adopt / update / delete)
``state`` ``state.json`` + per-run log files under ``DATA_DIR``
``service`` boot, scheduler, serialized sync queue, graceful stop
``api`` the ``/api/*`` the React UI speaks + static serving of ``dist/``
"""
__all__ = [
"config", "gitea", "provider", "gitops", "engine",
"registry", "state", "service", "api",
]
__version__ = "2.0.0"
+65
View File
@@ -0,0 +1,65 @@
"""``python -m forker`` — the container's single process.
One container, both halves inside it (the point of this rework):
* the **worker** — boot, scheduler and mirror syncs — as background threads,
* the **UI** — the built React app plus the JSON API it talks to — on the
published port.
``REMOTE`` and ``TOKEN`` are the only required inputs, validated in
``Settings.from_env``: a missing one is a hard exit naming the variable,
because otherwise the mistake looks like a healthy container that syncs
nothing.
Signal handling matters here: ``docker stop`` sends SIGTERM, and killing the
process mid-push leaves a half-mirrored repo. So SIGTERM stops the scheduler,
waits for the pass in flight (bounded), then shuts the HTTP server down.
"""
from __future__ import annotations
import sys
import threading
from . import logtee
from .api import make_server, serve_ready_message
from .config import Settings
from .service import Worker
def main() -> int:
logtee.install_worker_log()
settings = Settings.from_env()
worker = Worker(settings)
httpd = make_server(worker)
def on_signal(signum: int, _: object) -> None:
print(f"\nreceived signal {signum}, shutting down", flush=True)
# The HTTP socket stays up while the in-flight sync lands, so the UI
# keeps answering until the very end.
threading.Thread(target=_drain, args=(worker, httpd), daemon=True).start()
import signal
signal.signal(signal.SIGTERM, on_signal)
signal.signal(signal.SIGINT, on_signal)
worker.start()
serve_ready_message(httpd, settings)
try:
httpd.serve_forever(poll_interval=0.3)
except KeyboardInterrupt:
pass
finally:
httpd.server_close()
worker.graceful_stop(grace=1)
return 0
def _drain(worker: Worker, httpd: object) -> None:
worker.graceful_stop()
httpd.shutdown() # type: ignore[attr-defined]
if __name__ == "__main__":
sys.exit(main())
+599
View File
@@ -0,0 +1,599 @@
"""HTTP layer: the ``/api/*`` contract the React app speaks, plus static UI.
Zero dependencies (``http.server`` + ``ThreadingHTTPServer``) so the runtime
image stays slim and there is nothing to ``npm install`` or ``pip install`` at
start. The Node proxy it replaces existed only because a local process had to
hold a token the browser should not see; here the token is already inside this
container, so the browser talks to this API directly and the container's
published port *is* the UI.
Security posture: the token never leaves the process — no endpoint echoes it,
and mirror records serialize with the upstream token masked (``hasToken``).
That also means **the published port is the trust boundary**: bind it to
localhost unless you front it with auth (see README + docker-compose).
"""
from __future__ import annotations
import datetime
import json
import time
import mimetypes
import os
import posixpath
import threading
import traceback
import urllib.parse
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from typing import Any, Callable
from .config import KNOWN_KEYS, Settings, merge_config
from .engine import default_config_text
from .gitea import GiteaError
from .gitops import MACHINERY_BRANCH
from .service import Worker
MAX_BODY = 1 << 20 # 1 MiB — these payloads are configs, not artifacts
class HttpError(Exception):
def __init__(self, status: int, message: str):
super().__init__(message)
self.status = status
self.message = message
def parse_interval(value: Any) -> int:
"""Seconds for ``POST /api/settings {interval}`` — rejects, never clamps.
A 200 whose body quietly disagrees with what was sent is worse than a 400
the UI can show; the bound mirrors the app's own validation.
"""
try:
val = int(value)
except (TypeError, ValueError):
raise HttpError(400, "interval must be a number of seconds") from None
if not 30 <= val <= 86400:
raise HttpError(400, "interval must be between 30 and 86400 seconds")
return val
def _iso(ts: Any) -> str | None:
if not ts:
return None
return datetime.datetime.fromtimestamp(int(ts), datetime.timezone.utc).strftime(
"%Y-%m-%dT%H:%M:%SZ"
)
def to_ui_mirror(summary: dict[str, Any]) -> dict[str, Any]:
"""Worker summary → the Mirror shape the React app renders.
The app was built around Gitea *Actions* runs; a container pass is not a
workflow run, so the last pass is mapped onto that vocabulary
(``in_progress`` / ``completed`` + ``conclusion``) and the log/worker pages
get the worker's own data instead of run logs.
``event`` is *why the pass ran*, in one vocabulary everywhere — ``manual``
(Re-sync), ``tick`` (scheduler), ``boot``, ``created``, ``adopt``. A pass's
identity is its log **file** (unique: timestamp + pid); ``id`` is epoch
seconds, a display affordance only.
"""
last = summary.get("last") or {}
at = last.get("at")
running = bool(summary.get("running"))
last_sync = None
if running or at:
last_sync = {
"id": int(at or 0),
"event": summary.get("runningReason") or last.get("reason") or "worker",
"status": "in_progress" if running else "completed",
"conclusion": None if running else ("success" if last.get("ok") else "failure"),
"durationSec": last.get("durationSec") or 0,
}
# Emitted only when known: a mirror's very first pass has no completion
# timestamp yet, and a field typed as a string that arrives null is a
# trap for the renderer.
if at:
last_sync["createdAt"] = _iso(at)
last_sync["updatedAt"] = _iso(at)
if last.get("file"):
last_sync["file"] = last["file"]
counts = summary.get("counts") or {}
parity = summary.get("parity") or {}
return {
"name": summary["name"],
"full": summary["full"],
"upstream": summary["upstream"],
"forkUrl": summary["forkUrl"],
"defaultBranch": summary["defaultBranch"],
"owner": summary.get("owner"),
"running": running,
"enabled": summary.get("enabled", True),
"intervalSec": summary.get("intervalSec"),
"hasToken": summary.get("hasToken", False),
"config": summary.get("config") or {},
"lastSync": last_sync,
"lastError": last.get("error"),
"parity": {
"branches": counts.get("branches"),
"tags": counts.get("tags"),
"releases": counts.get("releases"),
"assets": counts.get("assets"),
"upstream": {
"branches": parity.get("branches"),
"tags": parity.get("tags"),
"releases": parity.get("releases"),
"assets": parity.get("assets"),
},
},
"units": summary.get("units") or [],
"spark": summary.get("spark") or [],
# A mirror can be green while its releases fail (a broken build_cmd) or
# while its assets would 404 (Releases unit off). Those are the two
# silent-failure modes the operator must see on the dashboard.
"releaseFailures": summary.get("releaseFailures") or [],
"disabledWorkflows": summary.get("disabledWorkflows") or [],
"unitFix": summary.get("unitFix"),
# Set when the UI saved a config the remote .forker.yaml refused; such a
# config is overwritten by the file on the next pass.
"configSync": summary.get("configSync"),
"lastCounts": {
"branches": last.get("branchesPushed"),
"tags": last.get("tagsPushed"),
"pruned": (last.get("branchesPruned") or 0) + (last.get("tagsPruned") or 0),
"releases": last.get("releasesPublished") or [],
"cold": last.get("cold"),
},
}
class Handler(BaseHTTPRequestHandler):
server_version = "RepoForkerWorker/2.0"
protocol_version = "HTTP/1.1"
worker: Worker # injected on the server instance
settings: Settings
ui_dist: str
# ------------------------------------------------------------- plumbing
def log_message(self, fmt: str, *args: Any) -> None: # quieter access log
pass
@property
def w(self) -> Worker:
return type(self).worker # type: ignore[attr-defined]
def _send(self, status: int, payload: Any, *, ctype: str = "application/json",
cache: str = "no-store") -> None:
body = payload if isinstance(payload, bytes) else (
payload if isinstance(payload, str) else json.dumps(payload, default=str)
).encode()
self.send_response(status)
self.send_header("Content-Type", f"{ctype}; charset=utf-8" if ctype.startswith("text") or ctype.endswith("json") else ctype)
self.send_header("Content-Length", str(len(body)))
self.send_header("Cache-Control", cache)
self.send_header("Access-Control-Allow-Origin", "*")
self.send_header("Access-Control-Allow-Headers", "Content-Type")
self.send_header("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS")
self.end_headers()
if self.command != "HEAD":
self.wfile.write(body)
def send_json(self, status: int, payload: Any) -> None:
self._send(status, payload)
def _body(self) -> dict[str, Any]:
length = int(self.headers.get("Content-Length") or 0)
if length <= 0:
return {}
if length > MAX_BODY:
raise HttpError(413, "body too large")
raw = self.rfile.read(length)
if not raw:
return {}
try:
data = json.loads(raw.decode("utf-8"))
except (UnicodeDecodeError, json.JSONDecodeError) as e:
raise HttpError(400, f"invalid JSON body: {e}") from None
if not isinstance(data, dict):
raise HttpError(400, "body must be a JSON object")
return data
# -------------------------------------------------------------- methods
def do_OPTIONS(self) -> None: # noqa: N802
self.send_response(204)
self.send_header("Access-Control-Allow-Origin", "*")
self.send_header("Access-Control-Allow-Headers", "Content-Type")
self.send_header("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS")
self.send_header("Content-Length", "0")
self.end_headers()
def do_GET(self) -> None: # noqa: N802
self._dispatch("GET")
def do_POST(self) -> None: # noqa: N802
self._dispatch("POST")
def do_PUT(self) -> None: # noqa: N802
self._dispatch("PUT")
def do_DELETE(self) -> None: # noqa: N802
self._dispatch("DELETE")
def do_HEAD(self) -> None: # noqa: N802
self._dispatch("GET")
def _dispatch(self, method: str) -> None:
path = urllib.parse.urlsplit(self.path).path
try:
if path.startswith("/api/"):
self._api(method, path, urllib.parse.parse_qs(urllib.parse.urlsplit(self.path).query))
return
if method == "GET":
self._static(path)
return
self.send_json(405, {"ok": False, "error": "method not allowed"})
except HttpError as e:
self.send_json(e.status, {"ok": False, "error": e.message})
except GiteaError as e:
status = e.status if 400 <= e.status < 600 else 502
self.send_json(status, {"ok": False, "error": str(e)[:400]})
except ValueError as e:
self.send_json(400, {"ok": False, "error": str(e)})
except KeyError as e:
self.send_json(404, {"ok": False, "error": f"not found: {e}"})
except Exception as e: # noqa: BLE001 — the UI must get a JSON error, not a stack
traceback.print_exc()
self.send_json(500, {"ok": False, "error": f"{type(e).__name__}: {e}"})
# ------------------------------------------------------------------- api
def _api(self, method: str, path: str, q: dict[str, list[str]]) -> None:
w = self.w
seg = [urllib.parse.unquote(s) for s in path.split("/") if s][1:] # drop "api"
def want(m: str) -> None:
if method != m:
raise HttpError(405, f"{path} only supports {m}")
# ---- /api/health
if path == "/api/health" and method == "GET":
try:
version = w.gitea.version()
return self.send_json(200, {
"ok": True, "gitea": {"url": w.s.remote, "version": version},
"worker": {"mirrors": len(w.registry.records()), "queued": w.queue_depth()},
})
except GiteaError as e:
return self.send_json(200, {"ok": False, "gitea": None, "error": str(e)[:200]})
if path == "/api/status" and method == "GET":
return self.send_json(200, w.status())
# ---- /api/settings (GET contract-compatible; POST edits the runtime)
if path == "/api/settings":
if method == "GET":
st = w.status()
return self.send_json(200, {
"configured": True,
"url": w.s.remote,
"user": st["settings"]["owner"],
"template": st["settings"]["template"],
"managedBy": "environment",
"tokenSource": "REMOTE/TOKEN environment variables",
"version": w.boot.get("gitea_version", "unknown"),
"tokenIsAdmin": st["settings"]["token_is_admin"],
"dataDir": st["settings"]["data_dir"],
"intervalSec": w.s.interval_sec,
"effectiveIntervalSec": st["scheduler"].get("effective_interval_sec")
or w.s.interval_sec,
"autoPace": st["scheduler"].get("auto_pace"),
"parallelism": w.s.parallelism,
})
want("POST")
body = self._body()
changed: dict[str, Any] = {}
if "interval" in body:
w.s.interval_sec = parse_interval(body["interval"])
changed["interval_sec"] = w.s.interval_sec
w.pace() # re-plan now, not on the next heartbeat
if "parallelism" in body:
raise HttpError(400, "parallelism is fixed at boot (restart the container)")
return self.send_json(200, {"ok": True, "changed": changed})
if path == "/api/connect":
raise HttpError(400, (
"the connection comes from REMOTE + TOKEN — this container is "
"already connected; set the variables and restart to change it"
))
# ---- mirrors collection
if path == "/api/mirrors" and method == "GET":
# Counts are refreshed after every sync and on demand via
# /api/mirrors/:name/refresh; ?fresh=1 forces a recount now (it hits
# the network, so the dashboard does not do it on every 3s poll).
fresh = (q.get("fresh") or ["0"])[0] == "1"
recs = []
for name, rec in sorted(w.registry.records().items()):
if fresh:
try:
rec = w.registry.refresh(name, force=True)
except Exception: # noqa: BLE001 — a bad probe must not blank the list
pass
recs.append(w.registry.summary(name, rec))
return self.send_json(200, [to_ui_mirror(s) for s in recs])
if path == "/api/mirrors" and method == "POST":
body = self._body()
upstream = str(body.get("upstream") or "").strip()
if not upstream:
raise HttpError(400, "upstream required")
steps: list[dict[str, str]] = []
def step(name: str, status: str, detail: str = "") -> None:
steps.append({"name": name, "status": status, "detail": detail})
def note(line: str) -> None:
print(f"[create] {line}", flush=True)
res = w.registry.create(
upstream=upstream,
name=body.get("name") or None,
upstream_token=str(body.get("token") or ""),
config=body.get("config") or {},
private=bool(body.get("private")),
step=step, log=note,
)
name = res["repo"]
# The first pass runs in the background: the wizard gets its answer
# immediately and watches the mirror's status like any other.
w.enqueue(name, why="created")
steps.append({"name": "first-sync", "status": "ok", "detail": "queued"})
return self.send_json(200, {"ok": True, "repo": res["full"], "steps": steps})
if path == "/api/adopt" and method == "POST":
return self.send_json(200, w.registry.adopt_all())
if path.startswith("/api/adopt"):
raise HttpError(404, f"unknown api: {method} {path}")
# ---- worker log (the runner page's replacement)
if path == "/api/worker/log" and method == "GET":
tail = int((q.get("tail") or ["400"])[0])
return self.send_json(200, {"lines": _lines(w.logs.worker_tail(tail=tail)),
"running": True})
# ---- queue: everything waiting or working, ordered by wait time
if path == "/api/queue" and method == "GET":
out = []
now = time.time()
for name, rec in w.registry.records().items():
reason = w.registry.running_reason(name)
if reason is not None:
out.append({
"repo": name, "event": reason, "status": "in_progress",
"waitedSec": int(now - (rec.get("last_started") or 0)),
})
elif name in w.queued_names():
out.append({
"repo": name, "event": w.queued_reason(name) or "worker",
"status": "queued",
"waitedSec": int(time.time() - (w.queued_since(name) or now)),
})
out.sort(key=lambda r: (r["status"] != "in_progress", -r["waitedSec"]))
return self.send_json(200, out)
# ---- single mirror routes
if seg and seg[0] == "mirrors" and len(seg) >= 2:
name = seg[1]
sub = seg[2] if len(seg) > 2 else ""
rec = w.registry.record(name)
if not rec:
raise HttpError(404, f"no mirror named {name}")
full = rec.get("full") or w.registry.full_name(name)
if not sub and method == "GET":
return self.send_json(200, to_ui_mirror(w.registry.summary(name)))
if not sub and method == "DELETE":
remove_repo = (q.get("repo") or ["false"])[0] == "true"
w.registry.delete(name, remove_repo=remove_repo)
return self.send_json(200, {"ok": True, "deletedRepo": remove_repo})
if not sub and method == "PUT":
body = self._body()
w.registry.update(
name,
upstream=body.get("upstream"),
upstream_token=body.get("token") if "token" in body else None,
config=body.get("config"),
)
return self.send_json(200, to_ui_mirror(w.registry.summary(name)))
if sub == "sync" and method == "POST":
queued = w.enqueue(name, why="manual")
return self.send_json(200, {"ok": True, "queued": queued,
"running": w.registry.is_running(name)})
if sub == "runs" and method == "GET":
return self.send_json(200, _history(name, w, full))
if sub == "log" and method == "GET":
tail = int((q.get("tail") or ["800"])[0])
run = (q.get("file") or [None])[0] # a specific run from /runs
serving = run or w.logs.current_file(name) or "latest.log"
return self.send_json(200, {
"lines": _lines(w.logs.read(name, tail=tail, run=serving)),
"cursor": -1,
"running": w.registry.is_running(name),
# The file actually tailed: while a pass runs this is THAT
# pass's own log (latest.log only lands when it closes), so
# "pass in flight" never shows the previous run.
"file": os.path.basename(serving),
})
if sub == "releases" and method == "GET":
rels = w.gitea.list_releases(full)
return self.send_json(200, [{
"id": r.get("id"), "tag": r.get("tag_name"),
"name": r.get("name") or r.get("tag_name"),
"assets": len(r.get("assets") or []),
"url": r.get("html_url"),
} for r in rels])
if sub == "config" and method == "GET":
raw = w.gitea.get_file(full, ".forker.yaml", MACHINERY_BRANCH) or default_config_text()
from .config import parse_flat
try:
parsed = merge_config(parse_flat(raw))
except ValueError as e:
raise HttpError(422, str(e)) from None
return self.send_json(200, {"raw": raw, "parsed": parsed})
if sub == "config" and method == "PUT":
body = self._body()
incoming = body.get("parsed") or {}
unknown = [k for k in incoming if k not in KNOWN_KEYS]
if unknown:
raise HttpError(400, f"unknown key(s): {', '.join(sorted(unknown))}")
for k, v in incoming.items():
if isinstance(v, dict) or isinstance(v, list):
raise HttpError(400, f"nested value not allowed: {k} — the parser is flat")
from .engine import write_remote_config
changed = write_remote_config(w.gitea, full, incoming)
w.registry.touch(name, {"config": {**(rec.get("config") or {}), **incoming},
"config_sync": "ok"})
raw = w.gitea.get_file(full, ".forker.yaml", MACHINERY_BRANCH) or ""
from .config import parse_flat
return self.send_json(200, {"raw": raw, "parsed": merge_config(parse_flat(raw)),
"changed": changed})
if sub == "refresh" and method == "POST":
rec2 = w.registry.refresh(name, force=True)
return self.send_json(200, to_ui_mirror(w.registry.summary(name, rec2)))
if sub == "unit" and method in ("GET", "POST"):
# A read; POST is kept for the UI that already calls it that way.
return self.send_json(200, w.gitea.releases_unit_state(full))
if sub in ("variables", "dispatch", "jobs"):
raise HttpError(410, (
f"{sub} belonged to Gitea Actions; this mirror is synced by the "
"container — use /api/mirrors/:name/sync and /api/mirrors/:name/config"
))
raise HttpError(404, f"unknown api: {method} {path}")
# ---------------------------------------------------------------- static
def _static(self, path: str) -> None:
dist = type(self).ui_dist
if not dist or not os.path.isdir(dist):
return self._send(200, _NOT_BUILT_HTML, ctype="text/html")
clean = posixpath.normpath(urllib.parse.urlsplit(path).path)
if clean in ("/", "", "."):
clean = "/index.html"
full = os.path.realpath(os.path.join(dist, clean.lstrip("/")))
root = os.path.realpath(dist)
if not full.startswith(root + os.sep) and full != root:
full = os.path.join(root, "index.html") # traversal → app shell
if not os.path.isfile(full):
full = os.path.join(root, "index.html") # SPA fallback
if not os.path.isfile(full):
return self._send(404, "not found", ctype="text/plain")
ctype = mimetypes.guess_type(full)[0] or "application/octet-stream"
with open(full, "rb") as fh:
data = fh.read()
cache = "no-cache" if full.endswith("index.html") else "public, max-age=31536000, immutable"
self._send(200, data, ctype=ctype, cache=cache)
_NOT_BUILT_HTML = """<!doctype html><meta charset=utf-8>
<title>Repo Forker — worker</title>
<body style="font:14px/1.6 ui-monospace,monospace;background:#0d1117;color:#e6edf3;padding:40px">
<h1 style="font-size:18px">Repo Forker worker is running</h1>
<p>The React app has not been built into this image (<code>UI_DIST</code> is empty or <code>dist/</code> is missing).</p>
<p>Build it locally and rebuild the image: <code>cd ui &amp;&amp; npm ci &amp;&amp; npm run build</code>,
then <code>docker compose build</code>.</p>
<p>The JSON API is live: <a style="color:#58a6ff" href="/api/status">/api/status</a> ·
<a style="color:#58a6ff" href="/api/mirrors">/api/mirrors</a> ·
<a style="color:#58a6ff" href="/api/health">/api/health</a></p>
</body>"""
def _history(name: str, w: Worker, full: str) -> list[dict[str, Any]]:
"""Run history for the detail page, from the on-disk logs.
Gitea's Actions runs are gone from this model, so a run is a sync pass:
the log files are the record, newest first. ``file`` is the run's identity
(unique per second + pid) and is what ``/log?file=`` takes back.
"""
out: list[dict[str, Any]] = []
rec = w.registry.record(name) or {}
reasons: dict[str, str] = rec.get("run_reasons") or {}
last = rec.get("last") or {}
for i, item in enumerate(w.logs.history(name)):
ok = not item["failed"]
row = {
"id": item["at"],
# Per-run truth when recorded (run_reasons), with the last pass's
# reason as fallback for the newest; history predating this key
# says "worker" — better than lying about which button ran it.
"event": reasons.get(item["file"]) or ((last.get("reason") or "worker") if i == 0 else "worker"),
"status": "completed",
"conclusion": "success" if ok else "failure",
"createdAt": _iso(item["at"]),
"updatedAt": _iso(item["at"]),
"durationSec": (last.get("durationSec") or 0) if i == 0 else 0,
"file": item["file"],
"headline": item["headline"],
}
out.append(row)
return out
def _lines(text: str) -> list[dict[str, Any]]:
return [{"t": i, "text": line} for i, line in enumerate(str(text or "").split("\n"))]
def make_server(worker: Worker, *, host: str | None = None,
port: int | None = None) -> ThreadingHTTPServer:
"""Bind the UI/API socket without serving yet.
Split from ``serve`` so ``__main__`` can start the worker first (a request
arriving before the registry loads would answer empty) and still see a port
conflict at boot time.
"""
settings = worker.s
handler = type("BoundHandler", (Handler,), {
"worker": worker,
"settings": settings,
"ui_dist": settings.ui_dist,
})
httpd = ThreadingHTTPServer((host or settings.host, port or settings.port), handler)
httpd.daemon_threads = True
return httpd
def serve_ready_message(httpd: ThreadingHTTPServer, settings: Settings) -> None:
port = httpd.server_address[1]
shown = "localhost" if settings.host in ("0.0.0.0", "") else settings.host
print(f"UI → http://{shown}:{port} (publish this container port)", flush=True)
print(f"API → http://{shown}:{port}/api/status", flush=True)
def serve(worker: Worker, *, host: str | None = None, port: int | None = None,
ready: Callable[[], None] | None = None) -> None:
"""Bind and serve forever (convenience wrapper; ``__main__`` drives it stepwise)."""
httpd = make_server(worker, host=host, port=port)
serve_ready_message(httpd, worker.s)
if ready:
ready()
try:
httpd.serve_forever(poll_interval=0.3)
except KeyboardInterrupt:
pass
finally:
httpd.server_close()
-198
View File
@@ -1,198 +0,0 @@
#!/usr/bin/env bash
# check-unit.sh — verify the Releases unit is enabled on this repo (the fork).
#
# WHY: Gitea creates FORKS with DefaultForkRepoUnits = [Code, PullRequests] —
# NO Releases unit. Without it, release ASSETS on the fork 404 on the web
# download route (browser_download_url) even though the API lists them
# correctly (by-id works). The release source tarball 404s too. So a fork
# silently produces un-downloadable releases.
#
# This script:
# 1. If the units API exists (newer Gitea builds): checks the Releases unit
# and, if it is disabled, ENABLES IT via the API (self-healing).
# 2. If the units API is absent (this build): probes the web download URL of
# the latest release's asset — 200 = OK, 404 = unit missing.
# 3. Prints a loud one-time-style warning with the exact UI fix when the
# unit is missing (there is no API to fix it on this build).
#
# Exit codes: 0 = ok / not-verifiable, 10 = Releases unit missing (or
# auto-fix failed), 1 = environment error.
#
# Inputs: GITEA_SERVER_URL, GITEA_OWNER, GITEA_REPO, GITEA_TOKEN (optional).
set -euo pipefail
GITEA_SERVER_URL="${GITEA_SERVER_URL:?GITEA_SERVER_URL is required}"
GITEA_OWNER="${GITEA_OWNER:?GITEA_OWNER is required}"
GITEA_REPO="${GITEA_REPO:?GITEA_REPO is required}"
GITEA_TOKEN="${GITEA_TOKEN:-}"
auth=()
if [ -n "$GITEA_TOKEN" ]; then
# API token (Bearer) or password (Basic) — use whichever Gitea accepts.
# GITEA_TOKEN from Actions is an API token -> Bearer.
auth=(-H "Authorization: Bearer $GITEA_TOKEN")
fi
api() { # api <path> — GET with auth, prints body (or empty)
curl -sS --max-time 30 ${auth[@]+"${auth[@]}"} \
"$GITEA_SERVER_URL/api/v1$1" 2>/dev/null || true
}
http_code() { # http_code <path> — GET status code
curl -sS --max-time 30 -o /dev/null -w "%{http_code}" \
${auth[@]+"${auth[@]}"} "$GITEA_SERVER_URL/api/v1$1" 2>/dev/null || echo 000
}
WARN() {
echo "!! ==============================================================="
echo "!! Releases unit is DISABLED on $GITEA_OWNER/$GITEA_REPO."
echo "!! This is a known Gitea fork quirk: forks are created WITHOUT the"
echo "!! Releases unit, so release assets 404 on the web download route"
echo "!! (the API lists them fine, but you can't download them)."
echo "!!"
echo "!! Fix (one-time): UI -> Settings -> Repository -> enable the"
echo "!! 'Releases' unit. (The units API is unavailable on this Gitea"
echo "!! build, so it can't be fixed automatically.)"
echo "!! Until then: releases exist but their assets are not downloadable."
echo "!! ==============================================================="
}
# --- 1) units API path (self-healing on builds that have it) -------------
# NOTE on the API shape (Gitea Unit JSON): `enabled` is a TOP-LEVEL field,
# and the PATCH body (UnitOption) expects `enabled` top-level too — NOT
# nested under "config". (Gitea's Go struct: Unit{..., Enabled bool,
# Config UnitConfig}; the config object only holds per-unit options like
# auto_merge.) Reading/PATCHing the wrong field made the old code
# "fix" a unit that was already enabled and report a false success.
CODE_UNITS="$(http_code "/repos/$GITEA_OWNER/$GITEA_REPO/units")"
if [ "$CODE_UNITS" = "200" ]; then
# Prints: <enabled:True/False> or <missing> if there is no Releases unit row.
state="$(api "/repos/$GITEA_OWNER/$GITEA_REPO/units" | python3 -c '
import sys, json
try:
d = json.load(sys.stdin)
except Exception:
sys.exit(1)
units = d if isinstance(d, list) else d.get("units", [])
for u in units:
if u.get("unit_type") == 4 or "releases" in str(u.get("name","")).lower():
print(u.get("enabled", False))
break
else:
print("missing")
' 2>/dev/null || echo unknown)"
if [ "$state" = "missing" ]; then
# no unit row at all -> add it via POST (some builds support this)
resp="$(curl -sS --max-time 30 -o /dev/null -w "%{http_code}" \
${auth[@]+"${auth[@]}"} -X POST \
"$GITEA_SERVER_URL/api/v1/repos/$GITEA_OWNER/$GITEA_REPO/units" \
-H "Content-Type: application/json" \
-d '{"unit_type":4,"config":{"enabled":true}}' 2>/dev/null || echo 000)"
if [ "$resp" != "201" ] && [ "$resp" != "200" ]; then
echo ">> Units API: Releases unit row missing and POST failed (HTTP $resp) — manual fix needed."
WARN
exit 10
fi
elif [ "$state" = "False" ] || [ "$state" = "false" ] || [ -z "$state" ] || [ "$state" = "unknown" ]; then
# disabled (or unknown) -> try to enable via PATCH (top-level `enabled`)
resp="$(curl -sS --max-time 30 -o /dev/null -w "%{http_code}" \
${auth[@]+"${auth[@]}"} -X PATCH \
"$GITEA_SERVER_URL/api/v1/repos/$GITEA_OWNER/$GITEA_REPO/units/4" \
-H "Content-Type: application/json" \
-d '{"enabled":true}' 2>/dev/null || echo 000)"
if [ "$resp" != "200" ]; then
echo ">> Units API present but PATCH failed (HTTP $resp) — manual fix needed."
WARN
exit 10
fi
fi
# RE-VERIFY after any mutation (a 200 alone is not proof of change).
after="$(api "/repos/$GITEA_OWNER/$GITEA_REPO/units" | python3 -c '
import sys, json
try:
d = json.load(sys.stdin)
except Exception:
sys.exit(1)
units = d if isinstance(d, list) else d.get("units", [])
for u in units:
if u.get("unit_type") == 4 or "releases" in str(u.get("name","")).lower():
print("True" if u.get("enabled") else "False")
break
else:
print("missing")
' 2>/dev/null || echo unknown)"
if [ "$after" = "True" ]; then
if [ "$state" = "$after" ]; then
echo ">> Releases unit enabled (verified via units API)."
else
echo ">> Fixed: enabled the Releases unit via the units API (verified)."
fi
exit 0
fi
echo ">> Units API: still not enabled after the attempt (state: $after) — manual fix needed."
WARN
exit 10
fi
# --- 2) fallback: web download probe (units API absent) --------------------
# Find the latest release that has at least one asset.
probe_url="$(api "/repos/$GITEA_OWNER/$GITEA_REPO/releases?limit=10" | python3 -c '
import sys, json
try:
d = json.load(sys.stdin)
except Exception:
sys.exit(0)
for r in (d if isinstance(d, list) else []):
assets = r.get("assets") or []
if assets:
print(assets[0].get("browser_download_url",""))
break
' 2>/dev/null || true)"
if [ -z "$probe_url" ]; then
echo ">> Cannot verify the Releases unit (no release with assets yet)."
echo ">> NOTE: if this is a fork, remember to enable the 'Releases' unit"
echo ">> (Settings -> Repository) once releases appear, or asset downloads 404."
exit 0
fi
code="$(curl -sS --max-time 60 -o /dev/null -w "%{http_code}" \
${auth[@]+"${auth[@]}"} "$probe_url" 2>/dev/null || echo 000)"
case "$code" in
200|301|302|303)
echo ">> Releases unit OK (web asset download works: HTTP $code)."
exit 0
;;
404)
# Confirm it is the unit (not a deleted asset): the API by-id path
# bypasses the unit-permission check. If it 200s while the web route
# 404s, the Releases unit is the culprit.
api_by_id="$(api "/repos/$GITEA_OWNER/$GITEA_REPO/releases?limit=10" | python3 -c '
import sys, json
try:
d = json.load(sys.stdin)
except Exception:
sys.exit(0)
for r in (d if isinstance(d, list) else []):
a = r.get("assets") or []
if a:
print(r.get("id", 0), a[0].get("id", 0))
break
' 2>/dev/null || true)"
if [ -n "$api_by_id" ]; then
set -- $api_by_id
rid="$1" aid="$2"
api_code="$(curl -sS --max-time 30 -o /dev/null -w "%{http_code}" \
${auth[@]+"${auth[@]}"} \
"$GITEA_SERVER_URL/api/v1/repos/$GITEA_OWNER/$GITEA_REPO/releases/$rid/assets/$aid" 2>/dev/null || echo 000)"
[ "$api_code" = "200" ] && echo ">> Confirmed: API by-id works (HTTP 200) but web route 404s -> Releases unit missing."
fi
WARN
exit 10
;;
*)
echo ">> Releases unit check inconclusive (HTTP $code on asset probe)."
exit 0
;;
esac
+276
View File
@@ -0,0 +1,276 @@
"""Environment settings + the flat `.forker.yaml` per-mirror config.
Two different config layers, deliberately kept apart:
* :class:`Settings` — the container's wiring, read from the environment on
boot. Everything the operator declares once at ``docker run`` time:
``REMOTE`` (the Gitea base URL the mirrors are pushed to), ``TOKEN`` (an
admin token so the worker can create repos and publish releases), owner,
interval, ports, data dir.
* The per-mirror config — the flat ``.forker.yaml`` that lives on the
``forker`` branch of each mirror repo. It is *remote* state (editable in the
Gitea UI, exactly like before), and this module owns the parser/renderer for
it. It stays flat ``key: value`` on purpose: no YAML library, and a human can
edit it in a web text box without breaking the indent.
"""
from __future__ import annotations
import os
import re
from dataclasses import dataclass, field
from typing import Any
# ---------------------------------------------------------------------------
# container settings (environment)
# ---------------------------------------------------------------------------
def _env(name: str, default: str = "") -> str:
val = os.environ.get(name)
return default if val is None else val.strip()
def _env_int(name: str, default: int) -> int:
raw = _env(name)
if not raw:
return default
try:
return int(raw)
except ValueError:
raise SystemExit(f"{name}={raw!r} is not a number") from None
def _env_bool(name: str, default: bool) -> bool:
raw = _env(name).lower()
if not raw:
return default
return raw in ("1", "true", "yes", "on")
@dataclass
class Settings:
"""Everything the container needs, from the environment."""
#: Gitea base URL that mirrors are pushed to, e.g. https://git.lago.dev
remote: str = ""
#: Gitea token. Admin scope: the worker creates repos, sets default
#: branches and publishes releases.
token: str = ""
#: Owner the mirrors are created under. Empty = the token's own user.
owner: str = ""
#: Repo name holding the `forker` branch machinery (auto-created if absent).
template_name: str = "repo-forker"
#: Where the bare mirrors, state and logs live. Mount a volume here.
data_dir: str = "/data"
#: Seconds between scheduler passes.
interval_sec: int = 600
#: Max concurrent mirror syncs. 1 = strictly serial (one noisy upstream
#: cannot starve the others, and the Gitea API is not hammered).
parallelism: int = 1
host: str = "0.0.0.0"
port: int = 8731
#: Directory holding the built React app (dist/). Empty = no UI, API only.
ui_dist: str = ""
#: Seconds a sync is allowed to run before it is killed and marked failed.
sync_timeout_sec: int = 1800
#: HTTP retries for transient network errors against REMOTE.
push_retries: int = 3
#: Serve the UI on plain HTTP with no auth — it holds the admin token.
allow_unauthenticated_ui: bool = True
@property
def mirrors_dir(self) -> str:
return os.path.join(self.data_dir, "mirrors")
@property
def logs_dir(self) -> str:
return os.path.join(self.data_dir, "logs")
@property
def state_file(self) -> str:
return os.path.join(self.data_dir, "state.json")
@classmethod
def from_env(cls) -> "Settings":
remote = _env("REMOTE") or _env("GITEA_SERVER_URL")
token = _env("TOKEN") or _env("GITEA_TOKEN")
if not remote:
raise SystemExit(
"REMOTE is required — the Gitea base URL the mirrors are "
"pushed to (e.g. REMOTE=https://git.lago.dev)"
)
if not token:
raise SystemExit(
"TOKEN is required — a Gitea token with permission to create "
"repos and publish releases (admin recommended)"
)
return cls(
remote=remote.rstrip("/"),
token=token,
owner=_env("OWNER") or _env("GITEA_OWNER"),
template_name=_env("TEMPLATE") or _env("TEMPLATE_REPO") or "repo-forker",
data_dir=_env("DATA_DIR") or "/data",
interval_sec=_env_int("INTERVAL", 600),
parallelism=max(1, _env_int("PARALLELISM", 1)),
host=_env("HOST") or "0.0.0.0",
port=_env_int("PORT", 8731),
ui_dist=_env("UI_DIST"),
sync_timeout_sec=_env_int("SYNC_TIMEOUT", 1800),
push_retries=_env_int("PUSH_RETRIES", 3),
allow_unauthenticated_ui=_env_bool("ALLOW_UNAUTHENTICATED_UI", True),
)
# ---------------------------------------------------------------------------
# .forker.yaml — flat key: value parser/renderer
# ---------------------------------------------------------------------------
#: Keys the UI and the worker understand. Anything else in the file is kept
#: verbatim on write (a hand-added key survives an edit from the UI) but is
#: ignored by the worker.
KNOWN_KEYS: tuple[str, ...] = (
"enabled",
"mirror_branches",
"mirror_tags",
"mirror_prune",
"mirror_upstream_releases",
"on_new_tag",
"sync_interval",
"build_cmd",
"build_script",
"artifacts",
)
BOOL_KEYS: tuple[str, ...] = (
"mirror_tags",
"mirror_prune",
"mirror_upstream_releases",
"on_new_tag",
"enabled",
)
#: Config keys that accept a shell command / path. Treated as TRUSTED CODE:
#: they run with the container's token in the environment.
EXEC_KEYS: tuple[str, ...] = ("build_cmd", "build_script")
_LINE_RE = re.compile(r"^([A-Za-z0-9_]+)[ \t]*:[ \t]*(.*)$")
_TRUE = ("true", "1", "yes", "on")
def _parse_value(key: str, raw: str) -> Any:
val = raw.strip()
# A trailing comment is stripped first, then the quotes: `artifacts: "dist/*" # globs`
# ends in the comment, so a quote check alone would keep the quotes (and the
# renderer would then treat it as a different value and rewrite the line).
quoted = re.match(r"^([\"'])(.*)\1[ \t]*(?:#.*)?$", val)
if quoted:
val = quoted.group(2)
else:
val = re.sub(r"[ \t]+#.*$", "", val).strip()
if key in BOOL_KEYS:
return val.lower() in _TRUE
return val
def parse_flat(text: str) -> dict[str, Any]:
"""Parse flat ``key: value`` text. Comments and blanks are skipped.
Raises ValueError on a line that is not flat, instead of silently
dropping it — a nested YAML block means the file no longer matches the
contract and the operator should hear about it.
"""
out: dict[str, Any] = {}
for line in str(text or "").splitlines():
stripped = line.strip()
if not stripped or stripped.startswith("#"):
continue
if line[:1] in (" ", "\t"):
raise ValueError(f"nested value not supported (flat parser): {stripped}")
m = _LINE_RE.match(line)
if not m:
raise ValueError(f"not a flat key: value line — {stripped}")
out[m.group(1)] = _parse_value(m.group(1), m.group(2))
return out
def _serialize_value(key: str, val: Any) -> str:
if key in BOOL_KEYS:
return "true" if val else "false"
s = "" if val is None else str(val)
if s == "":
return ""
needs_quote = bool(re.search(r"""[!*|&>%@"\[\] ]""", s)) or re.fullmatch(
r"(?i)true|false|null|~", s
)
return '"%s"' % s.replace("\\", "\\\\").replace('"', '\\"') if needs_quote else s
def render_flat(parsed: dict[str, Any], original_text: str = "") -> str:
"""Render flat config back to text, preserving comments and line order.
A value equal to what the file already says keeps its verbatim line, so a
no-op write is byte-identical to the source (callers diff on the text to
decide whether a write is needed at all). Unknown keys are preserved;
known-but-missing keys are appended in KNOWN_KEYS order.
"""
raw = str(original_text or "")
had_trailing_nl = raw.endswith("\n")
lines = raw.split("\n")
if had_trailing_nl and lines and lines[-1] == "":
lines = lines[:-1]
out: list[str] = []
used: set[str] = set()
for line in lines:
m = _LINE_RE.match(line)
key = m.group(1) if m else None
if key is not None and key in parsed:
val = parsed[key]
out.append(line if _parse_value(key, m.group(2)) == val else f"{key}: {_serialize_value(key, val)}")
used.add(key)
else:
out.append(line)
for key in KNOWN_KEYS:
if key in parsed and key not in used:
out.append(f"{key}: {_serialize_value(key, parsed[key])}")
result = "\n".join(out)
if had_trailing_nl or not result:
result += "\n"
return result
#: Defaults applied to a freshly created mirror (and to any key absent from a
#: mirror's .forker.yaml). Empty build fields = refs-only mirror: tags land but
#: nothing is published, which is the safe default.
CONFIG_DEFAULTS: dict[str, Any] = {
"enabled": True,
"mirror_branches": "*",
"mirror_tags": True,
"mirror_prune": True,
"mirror_upstream_releases": False,
"on_new_tag": True,
"sync_interval": 0, # 0 = use the container's INTERVAL
"build_cmd": "",
"build_script": "",
"artifacts": "",
}
def merge_config(raw: dict[str, Any]) -> dict[str, Any]:
"""Overlay parsed file values on the defaults, coercing types."""
merged = dict(CONFIG_DEFAULTS)
for key, val in (raw or {}).items():
if key in BOOL_KEYS:
merged[key] = val if isinstance(val, bool) else str(val).lower() in _TRUE
elif key == "sync_interval":
try:
merged[key] = int(str(val).strip() or 0)
except ValueError:
merged[key] = 0
else:
merged[key] = "" if val is None else str(val)
return merged
+547
View File
@@ -0,0 +1,547 @@
"""The worker: sync one mirror (fetch → push → prune → heal → releases).
This is the job that used to be ``forker/sync.sh`` fired by a Gitea Actions
cron. Inside the container it is a function the scheduler calls, so the pieces
the pipeline could not do properly now do it directly:
* the mirror's real state is read with **one ``git ls-remote``**, not by
paginating the Gitea REST API (cheaper and it cannot disagree with git);
* the default branch is **actually corrected** with a PATCH (the Actions token
was 403 "should be an owner", so ``sync.sh`` could only log the mismatch and
the UI server had to heal it);
* anything that is not one of our ``forker*`` workflows is **disabled** the
same instant it is discovered. Mirrored branches carry the upstream's own
``.gitea/workflows/*``; Gitea would fire them on its runner and they would
die on missing GitHub infra. There is no runner in this model, so a leak is
cheap — but it stays loud in the UI;
* releases are published for tags that **lack** one (not merely "new" tags), so
a failed release is retried on the next pass.
Releases support two modes, exactly as before, and both are opt-in per mirror
in ``.forker.yaml``: BUILD (run ``build_cmd`` / ``build_script`` on the tag's
tree, attach ``artifacts``) and MIRROR (copy the upstream release metadata +
assets through the provider API).
"""
from __future__ import annotations
import fnmatch
import os
import subprocess
import time
from dataclasses import dataclass, field
import urllib.parse
from typing import Any, Callable
from . import provider
from .config import Settings, merge_config, parse_flat, render_flat
from .gitea import Gitea, GiteaError
from .gitops import MACHINERY_BRANCH, GitError, Mirror, Refs, discard, fresh_workdir
#: Config keys that run shell commands. Trusted-code warning lives in the README.
CONFIG_FILENAME = ".forker.yaml"
#: Workflow filenames the mirror's own machinery may need. On the pipeline
#: model these were sync.yml / release.yml / runner-check.yml; with no runner
#: there is nothing to run, so the allow-list is whatever lives on the forker
#: branch itself.
#: Workflow filenames that belong to the mirror itself (anything else on the
#: repo is the upstream's CI riding in on a mirrored branch).
_OWN_WORKFLOWS = frozenset({"forker-sync.yml", "forker-release.yml"})
@dataclass
class SyncReport:
ok: bool = True
branches_pushed: int = 0
tags_pushed: int = 0
branches_pruned: int = 0
tags_pruned: int = 0
new_tags: list[str] = field(default_factory=list)
releases_published: list[str] = field(default_factory=list)
release_failures: list[str] = field(default_factory=list)
disabled_workflows: list[str] = field(default_factory=list)
unit_fix: str = "n/a"
default_branch: str | None = None
default_branch_fixed: bool = False
cold: bool = False
error: str | None = None
duration_sec: int = 0
def to_dict(self) -> dict[str, Any]:
return {
"ok": self.ok,
"branchesPushed": self.branches_pushed,
"tagsPushed": self.tags_pushed,
"branchesPruned": self.branches_pruned,
"tagsPruned": self.tags_pruned,
"newTags": self.new_tags[-20:],
"releasesPublished": self.releases_published,
"releaseFailures": self.release_failures,
"disabledWorkflows": self.disabled_workflows,
"unitFix": self.unit_fix,
"defaultBranch": self.default_branch,
"defaultBranchFixed": self.default_branch_fixed,
"cold": self.cold,
"error": self.error,
"durationSec": self.duration_sec,
}
class SyncWorker:
def __init__(self, settings: Settings, gitea: Gitea, log: Callable[[str], None] | None = None):
self.s = settings
self.g = gitea
self._log = log or (lambda m: print(m, flush=True))
def log(self, msg: str) -> None:
self._log(msg)
# ------------------------------------------------------------- plumbing
def mirror_dir(self, name: str) -> str:
return os.path.join(self.s.mirrors_dir, name.replace("/", "_"))
def fork_url(self, full: str) -> str:
return f"{self.s.remote}/{full}.git"
# ---------------------------------------------------------------- sync
def sync(self, *, name: str, full: str, upstream: str, upstream_token: str = "",
config: dict[str, Any] | None = None) -> SyncReport:
"""One full mirror pass. Raises nothing: the report carries the error."""
started = time.time()
rep = SyncReport()
cfg = merge_config(config or {})
self.log(f">> sync {full} (upstream {upstream})")
if not cfg.get("enabled", True):
self.log(" disabled by config (enabled: false) — skipping")
rep.duration_sec = int(time.time() - started)
return rep
path = self.mirror_dir(name)
# Cold = no mirror on disk yet, so this pass pays a full-history fetch.
rep.cold = not os.path.isfile(os.path.join(path, "HEAD"))
mirror = Mirror(path, upstream, upstream_token, retries=self.s.push_retries, log=self.log)
try:
mirror.ensure_init()
self.log(f">> Fetching all branches + tags ({'cold' if rep.cold else 'incremental'})")
mirror.fetch()
refs = mirror.upstream_refs()
self.log(f" upstream: {len(refs.heads)} branches, {len(refs.tags)} tags")
# What the mirror already has — one ls-remote, not 3 paginated APIs.
target = self.fork_url(full)
try:
have = mirror.remote_refs(target, self.s.token)
except GitError as e:
# An empty repo answers 0 refs; a genuine failure must abort,
# because pruning against a bogus empty "have" deletes nothing
# but a bogus full "have" could delete real refs.
self.log(f" ls-remote on mirror failed: {e.output or e}")
raise
self._push_branches(mirror, refs, have, cfg, rep, target)
self._push_tags(mirror, refs, have, cfg, rep, target)
self._heal_default_branch(mirror, full, rep)
self._disable_foreign_workflows(full, rep)
self._releases(mirror, full=full, upstream=upstream, upstream_token=upstream_token,
cfg=cfg, rep=rep)
self._unit(full, rep)
mirror.gc()
if rep.release_failures:
# The refs are correct, but a release the operator asked for did
# not happen. Reporting that pass as green is how a broken
# build_cmd stays invisible for weeks.
rep.ok = False
rep.error = f"{len(rep.release_failures)} release(s) failed: " \
f"{rep.release_failures[0].splitlines()[0][:200]}"
self.log(f"!! {len(rep.release_failures)} release(s) failed this pass")
self.log(
f">> Sync complete. branches:{rep.branches_pushed} tags:{rep.tags_pushed} "
f"pruned:{rep.branches_pruned + rep.tags_pruned} "
f"new tags:{len(rep.new_tags)} releases:{len(rep.releases_published)}"
)
self.log("=== sync failed" if not rep.ok else "=== sync finished")
except (GitError, GiteaError, RuntimeError, OSError) as e:
rep.ok = False
rep.error = str(e).splitlines()[0][:300] if str(e) else e.__class__.__name__
self.log(f"ERROR: {e}")
self.log("=== sync failed")
rep.duration_sec = int(time.time() - started)
return rep
# -------------------------------------------------------------- branches
def _push_branches(self, mirror: Mirror, refs: Refs, have: Refs, cfg: dict,
rep: SyncReport, target: str) -> None:
wanted = _filter_branches(refs.heads, str(cfg.get("mirror_branches") or "*"))
specs = [f"refs/heads/{b}:refs/heads/{b}" for b in wanted if b != MACHINERY_BRANCH]
if specs:
self.log(f" pushing {len(specs)} branches (1 pack)")
mirror.push(target, self.s.token, specs, timeout=self.s.sync_timeout_sec)
rep.branches_pushed = len(specs)
if cfg.get("mirror_prune", True):
# Prune is checked against the FULL upstream branch set: a branch
# outside the mirror_branches filter but still upstream is kept.
keep = set(refs.heads)
doomed = [
f":refs/heads/{b}" for b in have.heads
if b != MACHINERY_BRANCH and b not in keep
]
if doomed:
self.log(f" prune {len(doomed)} branch(es) deleted upstream")
mirror.push(target, self.s.token, doomed, timeout=self.s.sync_timeout_sec)
rep.branches_pruned = len(doomed)
# ------------------------------------------------------------------ tags
def _push_tags(self, mirror: Mirror, refs: Refs, have: Refs, cfg: dict,
rep: SyncReport, target: str) -> None:
if not cfg.get("mirror_tags", True):
return
specs = [f"refs/tags/{t}:refs/tags/{t}" for t in refs.tags]
if specs:
self.log(f" pushing {len(specs)} tags (1 pack)")
mirror.push(target, self.s.token, specs, timeout=self.s.sync_timeout_sec)
rep.tags_pushed = len(specs)
have_tags = set(have.tags)
rep.new_tags = [t for t in refs.tags if t not in have_tags]
if rep.new_tags:
self.log(f" new tags: {', '.join(rep.new_tags[:10])}")
if cfg.get("mirror_prune", True):
keep = set(refs.tags)
doomed = [f":refs/tags/{t}" for t in have.tags if t not in keep]
if doomed:
self.log(f" prune {len(doomed)} tag(s) deleted upstream")
mirror.push(target, self.s.token, doomed, timeout=self.s.sync_timeout_sec)
rep.tags_pruned = len(doomed)
# ------------------------------------------------------ default branch
def _heal_default_branch(self, mirror: Mirror, full: str, rep: SyncReport) -> None:
"""Make the mirror's default branch follow the upstream's.
A generated repo is born with ``forker`` as default and Gitea does not
switch it when a matching branch later appears. The pipeline could only
log this (Actions token is not an owner); the admin token can fix it,
and it is re-checked every pass so the fork follows an upstream rename.
"""
try:
repo = self.g.repo(full)
except GiteaError as e:
self.log(f" default branch: repo unreadable ({e})")
return
current = repo.get("default_branch") or ""
rep.default_branch = current or None
if current and current != MACHINERY_BRANCH:
return
upstream_default = mirror.default_branch()
if not upstream_default or upstream_default == MACHINERY_BRANCH:
return
# Only point at a branch the mirror actually has (a mirror_branches
# filter can exclude the upstream default).
try:
present = self.g.has_branch(full, upstream_default)
except GiteaError:
present = False
if not present:
self.log(f" default branch: upstream default '{upstream_default}' not mirrored yet — left as-is")
return
try:
self.g.set_default_branch(full, upstream_default)
rep.default_branch = upstream_default
rep.default_branch_fixed = True
self.log(f" default branch: {current or '(none)'} -> {upstream_default}")
except GiteaError as e:
self.log(f"WARN: set default branch -> {upstream_default} failed: {e}")
# ------------------------------------------------- foreign workflows
def _disable_foreign_workflows(self, full: str, rep: SyncReport) -> None:
"""Disable anything on the mirror that is not our machinery.
Mirrored branches carry the upstream's own ``.gitea/workflows/*``. With
the Actions runner gone they cannot fire, but if the instance still has
a shared runner they would; the check is cheap and it keeps the run
history clean. Failures are swallowed and retried next pass.
"""
try:
data = self.g.get(f"/repos/{full}/actions/workflows")
except GiteaError as e:
if e.status in (404, 403):
return # no Actions unit on this mirror — nothing to disable
return
for w in (data or {}).get("workflows") or []:
state = str(w.get("state") or "")
if state.startswith("disabled"):
continue
file = str(w.get("id") or "")
if not file.endswith((".yml", ".yaml")):
file = str(w.get("path") or "").split("/")[-1]
if not file or file in _OWN_WORKFLOWS:
continue
path = f"/repos/{full}/actions/workflows/{urllib.parse.quote(file, safe='')}/disable"
# Gitea's documented verb is POST; the build on git.lago.dev 405s on
# it and answers PUT instead. Try both, swallow both failures, and
# the check repeats on the next pass.
done = False
for verb in ("POST", "PUT"):
try:
self.g.request(verb, path)
done = True
break
except GiteaError:
continue
if done:
rep.disabled_workflows.append(file)
self.log(f" disabled upstream workflow: {file}")
# -------------------------------------------------------------- releases
def _releases(self, mirror: Mirror, *, full: str, upstream: str,
upstream_token: str, cfg: dict, rep: SyncReport) -> None:
wants_build = bool(str(cfg.get("build_cmd") or "").strip() or str(cfg.get("build_script") or "").strip())
wants_mirror = bool(cfg.get("mirror_upstream_releases"))
if not cfg.get("on_new_tag", True) or not (wants_build or wants_mirror):
return # refs-only mirror: tags land, nothing is published
# "No release yet" (not "new tag"): a release that failed last pass is
# retried here, and release.sh's idempotency guard prevents duplicates.
for tag in mirror.upstream_refs().tags:
try:
if self.g.release_for_tag(full, tag) is not None:
continue
except GiteaError as e:
self.log(f" release check for {tag} failed: {e}")
continue
self.log(f">> No release for {tag} — building + publishing")
try:
published = self.build_and_publish(
mirror, full=full, upstream=upstream,
upstream_token=upstream_token, cfg=cfg, tag=tag,
wants_build=wants_build, wants_mirror=wants_mirror)
# Only count what actually landed: "asked for a release" and
# "published a release" are different facts for the UI.
if published:
rep.releases_published.append(tag)
except Exception as e: # noqa: BLE001 — one bad tag must not fail the mirror
rep.release_failures.append(f"{tag}: {str(e)[:160]}")
self.log(f"!! release for {tag} failed: {e}")
def build_and_publish(self, mirror: Mirror, *, full: str, upstream: str,
upstream_token: str, cfg: dict, tag: str,
wants_build: bool = True, wants_mirror: bool = True) -> bool:
work = fresh_workdir()
try:
assets: list[str] = []
name: str | None = None
body: str | None = None
upstream_has_release = False
if wants_build:
self.log(f" exporting {tag} and building in a worktree")
mirror.worktree_export(tag, work)
script = str(cfg.get("build_script") or "").strip()
cmd = str(cfg.get("build_cmd") or "").strip()
env = {
**os.environ,
"FORK_TAG": tag,
"FORK_REPO": full,
"FORK_UPSTREAM": upstream,
"FORK_WORK": work,
}
if script:
script_path = os.path.join(work, script)
if not os.path.isfile(script_path):
raise RuntimeError(f"build_script not found in the tag tree: {script}")
self._run_build(["bash", script_path], work, env, script)
elif cmd:
self._run_build(["bash", "-lc", cmd], work, env, cmd)
assets.extend(_collect_artifacts(work, str(cfg.get("artifacts") or "")))
if wants_mirror:
self.log(f" mirroring upstream release for {tag}")
rel = provider.get_release(upstream, upstream_token, tag)
if rel:
upstream_has_release = True
name = rel.get("name") or None
body = rel.get("body") or None
asset_dir = os.path.join(work, "upstream_assets")
os.makedirs(asset_dir, exist_ok=True)
for a in rel.get("assets") or []:
url = a.get("url")
if not url:
continue
fname = a.get("name") or os.path.basename(url)
dest = os.path.join(asset_dir, fname)
self.log(f" asset: {fname}")
provider.download_asset(upstream, upstream_token, url, dest)
assets.append(dest)
# Publish only with real content: an empty "Release <tag>" would be
# skipped forever by the idempotency guard, so nothing is retried.
if not assets and not upstream_has_release:
self.log(f" no content for {tag} (no build assets, no upstream release) — not publishing")
return False
self.g.publish_release(
full, tag,
name or f"Release {tag}",
body or "Auto-released by Repo Forker",
assets,
)
self.log(f" published {tag} ({len(assets)} asset(s))")
return True
finally:
discard(work)
def _run_build(self, argv: list[str], cwd: str, env: dict, label: str) -> None:
"""Run the configured build, streaming its output into the run log.
The command is trusted code from .forker.yaml (see README: it runs with
this container's credentials available), so it is executed verbatim —
but a failed build used to surface as a bare "exit status 127" with no
clue. Its stdout/stderr now land in the log the UI shows.
"""
self.log(f" build: {label}")
try:
proc = subprocess.Popen( # noqa: S603 — trusted build command by design
argv, cwd=cwd, env=env,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True,
)
except OSError as e:
raise RuntimeError(f"build could not start ({label}): {e}") from None
tail: list[str] = []
assert proc.stdout is not None
for line in proc.stdout:
line = line.rstrip("\n")
tail.append(line)
del tail[:-200]
if line.strip():
self.log(f" | {line}")
rc = proc.wait(timeout=self.s.sync_timeout_sec)
if rc != 0:
detail = "\n".join(tail[-15:]) or "(no output)"
raise RuntimeError(f"build failed (exit {rc}):\n{detail}")
# ------------------------------------------------------------- unit heal
def _unit(self, full: str, rep: SyncReport) -> None:
"""Gitea creates forks WITHOUT the Releases unit → assets 404.
The web download route runs ``RequireUnitReader``, so with the unit off
an uploaded asset is listed by the API but 404s for a browser (the old
``check-unit.sh`` detected this and printed the manual fix). Most builds
expose no units API, but ``PATCH /repos/{repo}`` carries
``has_releases`` — so try that first, then verify, then report.
"""
try:
state = self.g.releases_unit_state(full)
except GiteaError:
rep.unit_fix = "n/a"
return
rep.unit_fix = state.get("fix", "n/a")
rep.units = state.get("units") or []
if rep.unit_fix == "off":
try:
self.g.patch(f"/repos/{full}", body={"has_releases": True})
after = self.g.releases_unit_state(full)
rep.units = after.get("units") or rep.units
rep.unit_fix = "fixed" if after.get("has_releases") else "manual"
except GiteaError:
rep.unit_fix = "manual"
if rep.unit_fix == "manual":
self.log(
"WARN: Releases unit is OFF and no API flipped it — release assets "
"will 404 on the web download route. One-time fix: repo Settings -> "
"Repository -> check Releases."
)
elif rep.unit_fix == "fixed":
self.log(" Releases unit was OFF — enabled via repo PATCH")
def _filter_branches(heads: list[str], spec: str) -> list[str]:
"""``*`` = all; otherwise a comma list, with optional ``*`` globs.
Pruning is always checked against the *full* upstream set by the caller, so
a branch excluded here but still present upstream is never deleted.
"""
spec = (spec or "*").strip()
if not spec or spec in ('"*"', "'*'"):
return list(heads)
patterns = [p.strip().strip("\"'") for p in spec.split(",") if p.strip()]
out: list[str] = []
for b in heads:
for pat in patterns:
if pat == "*" or fnmatch.fnmatch(b, pat) or b == pat:
out.append(b)
break
return out
def _collect_artifacts(work: str, artifacts: str) -> list[str]:
"""Resolve space-separated globs relative to the tag's tree."""
if not artifacts.strip():
return []
found: list[str] = []
for pattern in artifacts.split():
pattern = pattern.strip().strip('"')
if not pattern:
continue
base = os.path.dirname(pattern) or "."
glob_root = os.path.join(work, base)
if not os.path.isdir(glob_root):
continue
for entry in sorted(os.listdir(glob_root)):
if fnmatch.fnmatch(entry, os.path.basename(pattern)):
full = os.path.join(glob_root, entry)
if os.path.isfile(full):
found.append(full)
return found
def read_remote_config(gitea: Gitea, full: str) -> dict[str, Any]:
"""Read a mirror's ``.forker.yaml`` from its forker branch (empty when absent)."""
raw = gitea.get_file(full, CONFIG_FILENAME, MACHINERY_BRANCH)
if raw is None:
return {}
try:
return parse_flat(raw)
except ValueError as e:
raise GiteaError(0, f"{full}: invalid .forker.yaml — {e}", full) from None
def write_remote_config(gitea: Gitea, full: str, parsed: dict[str, Any]) -> bool:
"""Write ``.forker.yaml`` preserving comments; returns True if it changed."""
raw = gitea.get_file(full, CONFIG_FILENAME, MACHINERY_BRANCH) or ""
merged = parse_flat(raw) if raw else {}
merged.update(parsed)
next_text = render_flat(merged, raw or default_config_text())
return gitea.write_file(full, CONFIG_FILENAME, next_text, "Update .forker.yaml", MACHINERY_BRANCH)
def default_config_text() -> str:
"""The per-mirror ``.forker.yaml`` the worker writes on creation."""
return (
"# .forker.yaml — per-mirror configuration for Repo Forker.\n"
"#\n"
"# The upstream URL, its token, and the Gitea REMOTE/TOKEN are NOT set\n"
"# here: they live in the container (environment or the UI's mirror\n"
"# registry). Everything below is non-secret per-mirror behavior.\n"
"#\n"
"# Flat `key: value` only (the parser is a grep) — no nesting.\n"
"\n"
"enabled: true\n"
"mirror_tags: true\n"
"mirror_prune: true\n"
'mirror_branches: "*"\n'
"on_new_tag: true\n"
"mirror_upstream_releases: false\n"
"sync_interval: 0\n"
'build_cmd: ""\n'
'build_script: ""\n'
'artifacts: ""\n'
)
__all__ = [
"SyncWorker", "SyncReport", "read_remote_config", "write_remote_config",
"default_config_text", "CONFIG_FILENAME", "MACHINERY_BRANCH",
]
+434
View File
@@ -0,0 +1,434 @@
"""Minimal Gitea REST client on the standard library.
One base URL (``REMOTE``) + one token (``TOKEN``) — the container's whole
identity. Everything the worker used to get "for free" from Gitea Actions
(repo scoping, the Actions token, workflow dispatch) is now an explicit call
here, and the token is admin-scoped so it can also create repos and flip
settings the Actions token could not (the old ``sync.sh`` could only *log* a
default-branch mismatch because the Actions token was not an owner; here it is
a real PATCH).
"""
from __future__ import annotations
import base64
import json
import os
import time
import urllib.error
import urllib.parse
import urllib.request
from typing import Any, Iterable
DEFAULT_TIMEOUT = 30
class GiteaError(RuntimeError):
"""A Gitea API failure, with the HTTP status attached."""
def __init__(self, status: int, message: str, url: str = ""):
super().__init__(message or f"HTTP {status} on {url}")
self.status = status
self.message = message or f"HTTP {status} on {url}"
self.url = url
def __str__(self) -> str: # pragma: no cover - display helper
return f"HTTP {self.status}: {super().__str__()}"
class Gitea:
def __init__(self, base_url: str, token: str, timeout: int = DEFAULT_TIMEOUT):
self.base_url = base_url.rstrip("/")
self.token = token
self.timeout = timeout
# ---------------------------------------------------------------- core
def request(
self,
method: str,
path: str,
*,
params: dict[str, Any] | None = None,
body: Any = None,
raw: bool = False,
timeout: int | None = None,
ok: Iterable[int] = (),
) -> Any:
"""Call the API. ``path`` may carry or omit the /api/v1 prefix.
``raw=True`` returns the response body as text (used for reading repo
files verbatim — a JSON round-trip would reformat them).
"""
api = path if path.startswith("/api/") else "/api/v1" + (
path if path.startswith("/") else "/" + path
)
url = self.base_url + api
if params:
clean = {k: v for k, v in params.items() if v is not None}
if clean:
url += ("&" if "?" in url else "?") + urllib.parse.urlencode(clean)
data = None
headers = {"Authorization": f"Bearer {self.token}", "User-Agent": "repo-forker-worker"}
if body is not None:
data = json.dumps(body).encode()
headers["Content-Type"] = "application/json"
req = urllib.request.Request(url, data=data, headers=headers, method=method)
try:
with urllib.request.urlopen(req, timeout=timeout or self.timeout) as res:
payload = res.read()
status = res.status
except urllib.error.HTTPError as e:
payload = e.read() or b""
status = e.code
text = payload.decode("utf-8", "replace")
message = text
try:
message = json.loads(text).get("message", text) or text
except Exception:
pass
if status not in tuple(ok):
raise GiteaError(status, message.strip()[:400], url) from None
except urllib.error.URLError as e:
raise GiteaError(0, f"{getattr(e, 'reason', e)} while calling {url}", url) from None
if status == 204 or not payload:
return None
if raw:
return payload.decode("utf-8", "replace")
try:
return json.loads(payload)
except json.JSONDecodeError:
return payload.decode("utf-8", "replace")
def get(self, path: str, **kw: Any) -> Any:
return self.request("GET", path, **kw)
def post(self, path: str, **kw: Any) -> Any:
return self.request("POST", path, **kw)
def put(self, path: str, **kw: Any) -> Any:
return self.request("PUT", path, **kw)
def patch(self, path: str, **kw: Any) -> Any:
return self.request("PATCH", path, **kw)
def delete(self, path: str, **kw: Any) -> Any:
return self.request("DELETE", path, **kw)
def paged(self, path: str, *, limit: int = 50, max_pages: int = 60,
params: dict[str, Any] | None = None) -> list[Any]:
"""Walk a list endpoint to the end. Gitea's default page size is 30."""
out: list[Any] = []
base = dict(params or {})
for page in range(1, max_pages + 1):
chunk = self.get(path, params={**base, "limit": limit, "page": page})
if not isinstance(chunk, list) or not chunk:
break
out.extend(chunk)
if len(chunk) < limit:
break
return out
def search_repos(self, *, owner: str | None = None, forked_only: bool = False,
limit: int = 500) -> list[dict[str, Any]]:
"""Repo discovery for ``adopt_all``.
``/user/repos`` does not list org repos the token can see, so search is
the reliable way in. Gitea's ``q=`` is a *name* search, not a substring
search — an empty q plus a generous ``limit`` (one page, no pagination)
is what actually works on this API.
"""
params: dict[str, Any] = {"limit": limit}
if owner:
params["owner"] = owner
if forked_only:
params["forked"] = "true"
out = self.get("/repos/search", params=params) or {}
repos = out.get("data") if isinstance(out, dict) else None
return repos if isinstance(repos, list) else []
# ------------------------------------------------------------ identity
def whoami(self) -> dict[str, Any]:
return self.request("GET", "/user", timeout=15) or {}
def version(self) -> str:
try:
return str((self.request("GET", "/version", timeout=15) or {}).get("version", "unknown"))
except GiteaError:
return "unknown"
# ---------------------------------------------------------- repositories
def repo(self, full: str) -> dict[str, Any]:
return self.get(f"/repos/{full}")
def list_repos(self, owner: str | None = None) -> list[dict[str, Any]]:
if owner:
return self.paged(f"/orgs/{owner}/repos")
return self.paged("/user/repos", params={"affiliation": "owner,organization_member"})
def create_repo(self, owner: str, name: str, *, description: str = "",
private: bool = False) -> dict[str, Any]:
"""Create a repo under a user or an org.
OWNER may be either. ``/orgs/<user>/repos`` answers 404 "GetOrgByName"
for a user, and ``/user/repos`` creates under the TOKEN's owner, which
is the wrong namespace when OWNER is an org — so try the right one for
the identity we know and fall back to the other.
"""
body = {"name": name, "description": description, "private": private, "auto_init": False}
me = ""
try:
me = str(self.whoami().get("login") or "")
except GiteaError:
me = ""
prefer_org = bool(owner) and owner.lower() != me.lower()
paths = ([f"/orgs/{owner}/repos", "/user/repos"] if prefer_org
else ["/user/repos", f"/orgs/{owner}/repos"])
last: GiteaError | None = None
for path in paths:
try:
return self.post(path, body=body)
except GiteaError as e:
# 404 (not an org / no such user) is worth the fallback; a 409
# or 403 is the real answer and must reach the caller.
if e.status not in (404, 422):
raise
last = e
assert last is not None
raise last
def set_default_branch(self, full: str, branch: str) -> None:
self.patch(f"/repos/{full}", body={"default_branch": branch})
def delete_repo(self, full: str) -> None:
self.delete(f"/repos/{full}")
def has_branch(self, full: str, branch: str) -> bool:
try:
self.get(f"/repos/{full}/branches/{urllib.parse.quote(branch, safe='')}")
return True
except GiteaError as e:
if e.status in (404, 409):
return False
raise
def branch_names(self, full: str) -> list[str]:
return [b.get("name", "") for b in self.paged(f"/repos/{full}/branches") if b.get("name")]
def tag_names(self, full: str) -> list[str]:
return [t.get("name", "") for t in self.paged(f"/repos/{full}/tags") if t.get("name")]
# ------------------------------------------------------------- contents
def get_file(self, full: str, path: str, ref: str) -> str | None:
"""Read a repo file verbatim, or None when it is not there.
"Not there" has three shapes on this API, all of them real:
404 (no such file), 409 (no such branch) and — on a repo that has no
commits at all — **500 "no open git repo"**. Treating that 500 as an
error makes the very first write of a fresh mirror look like an API
failure, so absence is absence here.
"""
try:
data = self.get(
f"/repos/{full}/raw/{path.lstrip('/')}",
params={"ref": ref},
raw=True,
)
except GiteaError as e:
if e.status in (404, 409) or (e.status >= 500 and "no open git repo" in e.message):
return None
raise
return data if isinstance(data, str) else None
def create_file(self, full: str, path: str, content: str, message: str, branch: str) -> None:
"""POST creates (and, on an empty repo, BIRTHS the branch).
PUT against a branch that does not exist yet answers 500 "no open git
repo", so the create verb matters: a mirror's `forker` branch is
created here the first time, not by a workflow checkout as before.
"""
self.post(f"/repos/{full}/contents/{path.lstrip('/')}", body={
"content": base64.b64encode(content.encode()).decode(),
"message": message,
"branch": branch,
})
def create_branch(self, full: str, branch: str, from_branch: str) -> None:
self.post(f"/repos/{full}/branches", body={
"new_branch_name": branch,
"old_branch_name": from_branch,
})
def ensure_machinery_branch(self, full: str, branch: str) -> None:
"""Create a missing branch on a repo that already has commits.
``POST contents`` births a branch **only on an empty repo**; on a repo
with content it answers 404 "branch does not exist". That is the shape
of a real migration: the destination repo already exists with history
(the pipeline era, or a push before the mirror was registered), so the
machinery branch is cut from the default branch and the config file
lands on top of it.
"""
default = (self.repo(full).get("default_branch") or "").strip()
if not default:
return
self.create_branch(full, branch, default)
def update_file(self, full: str, path: str, content: str, message: str, branch: str,
sha: str | None = None) -> None:
if sha is None:
# An empty repo answers this with `[]` (a list), not a 404.
meta = self.get(f"/repos/{full}/contents/{path.lstrip('/')}", params={"ref": branch})
sha = meta.get("sha") if isinstance(meta, dict) else None
self.put(f"/repos/{full}/contents/{path.lstrip('/')}", body={
"content": base64.b64encode(content.encode()).decode(),
"message": message,
"branch": branch,
"sha": sha,
})
def write_file(self, full: str, path: str, content: str, message: str, branch: str) -> bool:
"""Create-or-update a file. Returns True when something was written.
PUT needs the current blob sha (422 "file already exists" without it)
and POST fails once the file exists, so the verb is chosen per state —
and a lost race falls back to the other one. A 404 on create means the
*branch* is missing on a repo that already has commits (POST contents
only births branches on an empty repo): cut it from the default branch
and write again. This is what lets a pre-existing repo become a mirror.
"""
existing = self.get_file(full, path, branch)
if existing is not None and existing != content:
self.update_file(full, path, content, message, branch)
return True
if existing is None:
try:
self.create_file(full, path, content, message, branch)
except GiteaError as e:
if e.status == 404 and "does not exist" in str(e.message).lower():
self.ensure_machinery_branch(full, branch)
self.create_file(full, path, content, message, branch)
elif e.status in (409, 422):
self.update_file(full, path, content, message, branch, sha=None)
else:
raise
return True
return False
# ------------------------------------------------------------- releases
def release_for_tag(self, full: str, tag: str) -> dict[str, Any] | None:
try:
return self.get(f"/repos/{full}/releases/tags/{urllib.parse.quote(tag, safe='')}")
except GiteaError as e:
if e.status == 404:
return None
raise
def list_releases(self, full: str) -> list[dict[str, Any]]:
return self.paged(f"/repos/{full}/releases")
def create_release(self, full: str, tag: str, name: str, body: str) -> dict[str, Any]:
return self.post(f"/repos/{full}/releases", body={
"tag_name": tag, "name": name, "body": body,
})
def upload_asset(self, full: str, release_id: int, file_path: str,
timeout: int = 300) -> None:
"""Upload one release asset (multipart, field name `attachment`)."""
api = f"/api/v1/repos/{full}/releases/{release_id}/assets"
url = self.base_url + api
name = urllib.parse.quote(os.path.basename(file_path))
url += f"?name={name}"
with open(file_path, "rb") as fh:
payload = fh.read()
content_type = "application/octet-stream"
boundary = "----repo-forker-boundary"
body = (
f"--{boundary}\r\n"
f'Content-Disposition: form-data; name="attachment"; filename="{name}"\r\n'
f"Content-Type: {content_type}\r\n\r\n"
).encode() + payload + f"\r\n--{boundary}--\r\n".encode()
req = urllib.request.Request(url, data=body, method="POST", headers={
"Authorization": f"Bearer {self.token}",
"Content-Type": f"multipart/form-data; boundary={boundary}",
})
try:
with urllib.request.urlopen(req, timeout=timeout) as res:
if res.status >= 300:
raise GiteaError(res.status, f"asset upload returned {res.status}", url)
except urllib.error.HTTPError as e:
raise GiteaError(e.code, f"asset upload failed: {(e.read() or b'').decode('utf-8','replace')[:200]}", url) from None
def publish_release(self, full: str, tag: str, name: str, body: str,
assets: list[str]) -> dict[str, Any]:
"""Create the release and attach every asset, loudly.
A failed upload raises: the caller's idempotency guard skips tags that
already have a release, so a silently-partial release would stay
partial forever while every later run looked green.
"""
rel = self.create_release(full, tag, name, body)
rid = (rel or {}).get("id")
if not rid:
raise GiteaError(0, f"release create returned no id for {tag}", full)
for asset in assets:
if os.path.isfile(asset):
self.upload_asset(full, int(rid), asset)
return rel or {}
# ---------------------------------------------------------------- units
def releases_unit_state(self, full: str) -> dict[str, Any]:
"""Reports the Releases unit honestly, without pretending an API exists.
Gitea creates *forks* with DefaultForkRepoUnits = [Code, PullRequests]:
no Releases unit. The web download route then 404s on
``RequireUnitReader`` while the by-id API keeps working, so a mirror
silently produces un-downloadable releases. Most builds expose no units
API, so the honest answer is read from the flags Gitea does return:
fix = "ok" unit enabled
= "off" unit disabled, something may be able to flip it
= "manual" no units API and the repo PATCH cannot be trusted
= "n/a" repo unreadable
"""
info: dict[str, Any] = {"has_releases": None, "fix": "n/a", "units": []}
try:
repo = self.repo(full)
except GiteaError:
return info
info["units"] = [
label for key, label in (
("has_code", "Code"), ("has_issues", "Issues"),
("has_pull_requests", "Pull Requests"), ("has_releases", "Releases"),
("has_packages", "Packages"), ("has_projects", "Projects"),
("has_wiki", "Wiki"), ("has_actions", "Actions"),
) if repo.get(key)
]
if repo.get("has_releases"):
info["has_releases"] = True
info["fix"] = "ok"
return info
info["has_releases"] = False
try:
units = self.get(f"/repos/{full}/units")
except GiteaError as e:
# 404/405 = no units API on this build: the caller may still try the
# repo PATCH; anything else is a transient we report as manual.
info["fix"] = "off" if e.status in (404, 405, 403) else "manual"
return info
for u in units if isinstance(units, list) else []:
if u.get("type_key") == "releases":
try:
self.patch(f"/repos/{full}/units/{u.get('id')}", body={"enabled": True})
info["has_releases"] = True
info["fix"] = "fixed"
if "Releases" not in info["units"]:
info["units"].append("Releases")
except GiteaError:
info["fix"] = "manual"
return info
info["fix"] = "off"
return info
+290
View File
@@ -0,0 +1,290 @@
"""Git mirror mechanics: fetch upstream → push refs to REMOTE → prune.
Port of the heart of ``forker/sync.sh``. The invariants that survived the move
from Gitea Actions into a container:
* **True bare mirror.** Upstream branches land in ``refs/heads/*`` and tags in
``refs/tags/*``, byte-identical objects (tags keep pointing at upstream
commits, so hashes match).
* **The upstream is fetched anonymously by default.** Every upstream git call
runs with ``GIT_CONFIG_GLOBAL`` / ``GIT_CONFIG_SYSTEM`` cut and
``GIT_CONFIG_NOSYSTEM`` set, so a ``credential.helper=store`` entry on the
host can never be offered to ``git fetch``. A Bearer header is added **only**
when an upstream token is configured.
* **Bearer, not user:password in the URL.** Scoped per URL through
``http.<url>.extraHeader``, so the token never appears in a remote URL and
therefore never leaks into git's own output or logs.
* **One multi-ref pack.** Pushing ~300 branches one by one opened ~300 TLS
connections and the remote dropped the ~20th; a single pack is robust and a
retry re-pushes idempotently.
* **Transient network errors are retried with backoff; anything else aborts
at once.** A partial mirror reported as success is the one outcome we must
never produce.
The one thing that got *better*: the container is stateful (``/data``), so
``.mirror`` persists between passes and every fetch after the first is
incremental — the old runner wiped the workspace every run.
"""
from __future__ import annotations
import os
import shutil
import subprocess
import tempfile
import time
from dataclasses import dataclass
from typing import Iterable
#: Branch name the worker reserves on every mirror for its own files
#: (.forker.yaml). Upstream refs are never pushed under it, and it is never
#: pruned — exactly like the old machinery branch.
MACHINERY_BRANCH = "forker"
TRANSIENT_MARKERS = (
"Could not resolve host",
"Failed to connect",
"Connection timed out",
"RPC failed",
"early EOF",
"remote end hung up",
"The requested URL returned error: 5",
"timed out",
"Temporary failure in name resolution",
)
class GitError(RuntimeError):
def __init__(self, message: str, output: str = ""):
super().__init__(message)
self.output = output
def _clean_git_env() -> dict[str, str]:
"""Env that makes git ignore every credential source on the host."""
env = dict(os.environ)
env["GIT_TERMINAL_PROMPT"] = "0"
env["GIT_CONFIG_GLOBAL"] = os.devnull
env["GIT_CONFIG_SYSTEM"] = os.devnull
env["GIT_CONFIG_NOSYSTEM"] = "1"
env.pop("GCM_PROVIDER", None)
return env
def run_git(args: list[str], *, cwd: str | None = None, timeout: int = 1800,
stdin: bytes | None = None) -> str:
try:
proc = subprocess.run(
["git", *args], cwd=cwd, env=_clean_git_env(), input=stdin,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=timeout,
)
except subprocess.TimeoutExpired:
raise GitError(f"git {' '.join(args)} timed out after {timeout}s") from None
except FileNotFoundError:
raise GitError("git executable not found in this container") from None
out = (proc.stdout or b"").decode("utf-8", "replace")
if proc.returncode != 0:
raise GitError(f"git {' '.join(args)} exited {proc.returncode}", out)
return out
def is_transient(output: str) -> bool:
return any(marker in output for marker in TRANSIENT_MARKERS)
@dataclass
class Refs:
heads: list[str]
tags: list[str]
@staticmethod
def parse(ls_remote_output: str) -> "Refs":
heads: list[str] = []
tags: list[str] = []
for line in ls_remote_output.splitlines():
parts = line.split("\t")
if len(parts) != 2:
continue
ref = parts[1].strip()
if ref.endswith("^{}"): # peeled annotated tag — not a ref of its own
continue
if ref.startswith("refs/heads/"):
heads.append(ref[len("refs/heads/"):])
elif ref.startswith("refs/tags/"):
tags.append(ref[len("refs/tags/"):])
return Refs(sorted(heads), sorted(tags))
class Mirror:
"""A bare mirror of one upstream, plus the push target on REMOTE."""
def __init__(self, path: str, upstream: str, upstream_token: str = "",
retries: int = 3, log=print):
self.path = path
self.upstream = upstream
self.upstream_token = upstream_token
self.retries = max(1, retries)
self._log = log
# ---------------------------------------------------------------- setup
def ensure_init(self) -> None:
if os.path.isfile(os.path.join(self.path, "HEAD")):
return
os.makedirs(self.path, exist_ok=True)
run_git(["init", "--bare", self.path])
def _set_header(self, url: str, token: str) -> None:
key = f'http.{url}.extraHeader'
if token:
run_git(["--git-dir", self.path, "config", key, f"Authorization: Bearer {token}"])
else:
# An empty token must mean "no header", never "Bearer <empty>".
try:
run_git(["--git-dir", self.path, "config", "--unset", key])
except GitError:
pass
def remote_url(self, url: str, token: str = "") -> str:
"""Register (or refresh) an extraHeader for a remote URL."""
self._set_header(url, token)
# ---------------------------------------------------------------- fetch
def fetch(self) -> None:
self._set_header(self.upstream, self.upstream_token)
args = ["--git-dir", self.path, "fetch", "--force", "--prune", self.upstream,
"+refs/heads/*:refs/heads/*", "+refs/tags/*:refs/tags/*"]
self._with_retry(args, "fetch")
def upstream_refs(self) -> Refs:
out = run_git(["--git-dir", self.path, "for-each-ref",
"--format=%(refname)%09%(refname:short)",
"refs/heads/", "refs/tags/"])
heads: list[str] = []
tags: list[str] = []
for line in out.splitlines():
full, _, short = line.partition("\t")
short = short.strip()
if not short:
continue
if full.startswith("refs/heads/"):
heads.append(short)
elif full.startswith("refs/tags/"):
tags.append(short)
return Refs(sorted(heads), sorted(tags))
def default_branch(self) -> str | None:
"""Upstream HEAD's target, read over the wire (honors the header config)."""
try:
out = run_git(["--git-dir", self.path, "ls-remote", "--symref",
self.upstream, "HEAD"], timeout=60)
except GitError:
return None
for line in out.splitlines():
if line.startswith("ref: refs/heads/") and line.rstrip().endswith("HEAD"):
name = line.split()[1][len("refs/heads/"):]
return name.strip() or None
return None
def remote_refs(self, url: str, token: str = "") -> Refs:
"""What a remote currently has — one connection, no API pagination."""
self._set_header(url, token)
try:
out = run_git(["--git-dir", self.path, "ls-remote", url], timeout=120)
except GitError as e:
# A brand-new empty repo answers with an empty body (rc 0); a real
# failure must not be read as "no refs" or the prune step would
# delete everything.
raise e
return Refs.parse(out)
# ----------------------------------------------------------------- push
def push(self, url: str, token: str, refspecs: Iterable[str], *,
timeout: int = 1800) -> None:
specs = [s for s in refspecs if s]
if not specs:
return
self._set_header(url, token)
args = ["--git-dir", self.path, "push", "--force", url, *specs]
self._with_retry(args, "push", timeout=timeout)
def _with_retry(self, args: list[str], what: str, timeout: int = 1800) -> None:
last = ""
for attempt in range(1, self.retries + 1):
try:
run_git(args, timeout=timeout)
return
except GitError as e:
last = e.output or str(e)
if not is_transient(last):
tail = "\n".join(last.strip().splitlines()[-10:])
raise GitError(_explain(what, last, tail), last) from None
self._log(f" {what} retry {attempt}/{self.retries} (transient network)")
time.sleep(min(60, attempt * 5))
tail = "\n".join(last.strip().splitlines()[-10:])
raise GitError(_explain(what, last, tail), last)
# ---------------------------------------------------------------- misc
def head_commit(self, ref: str) -> str | None:
try:
return run_git(["--git-dir", self.path, "rev-parse", "--verify", "-q",
f"refs/tags/{ref}^{{commit}}"]).strip() or None
except GitError:
try:
return run_git(["--git-dir", self.path, "rev-parse", "--verify", "-q",
f"refs/tags/{ref}"]).strip() or None
except GitError:
return None
def worktree_export(self, tag: str, dest: str) -> None:
"""Export a tag's tree into ``dest`` for a local build.
Uses the mirror we already hold — no extra network round-trip, and the
objects are guaranteed identical to upstream.
"""
os.makedirs(dest, exist_ok=True)
run_git(["--git-dir", self.path, "worktree", "prune"], timeout=60)
archive = subprocess.run(
["git", "--git-dir", self.path, "archive", "--format=tar", f"refs/tags/{tag}"],
env=_clean_git_env(), stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=600,
)
if archive.returncode != 0:
raise GitError(
f"git archive {tag} failed: {archive.stderr.decode('utf-8','replace')[:400]}"
)
extract = subprocess.run(
["tar", "-x", "-C", dest], input=archive.stdout,
stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=600,
)
if extract.returncode != 0:
raise GitError(f"extracting {tag} failed: {extract.stderr.decode('utf-8','replace')[:400]}")
def gc(self) -> None:
try:
run_git(["--git-dir", self.path, "gc", "--auto", "--quiet"], timeout=900)
except GitError:
pass
def _explain(what: str, raw: str, tail: str) -> str:
"""Turn a raw git failure into something an operator can act on.
The two shapes people actually hit are an auth prompt (the upstream is
private, or the instance requires sign-in, so the anonymous fetch was
refused) and a dead URL. Both say so in the log instead of a git stack.
"""
hint = ""
if "could not read Username" in raw or "terminal prompts disabled" in raw or \
"Authentication failed" in raw or "403" in raw:
hint = ("\n the upstream refused an anonymous fetch — set its token "
"on the mirror (private repo, or the host requires sign-in)")
elif "repository not found" in raw or "404" in raw:
hint = "\n the upstream URL is not reachable as a git repo"
return f"{what} failed (not retrying):\n{tail}{hint}"
def fresh_workdir(prefix: str = "forker-build-") -> str:
return tempfile.mkdtemp(prefix=prefix)
def discard(path: str) -> None:
shutil.rmtree(path, ignore_errors=True)
-34
View File
@@ -1,34 +0,0 @@
#!/usr/bin/env bash
# config.sh — load .forker.yaml (flat key: value) into shell variables.
# Sourced by other scripts. Keeps the YAML trivial (no nesting) so a simple
# parser is robust and the file stays human-editable in the Gitea UI.
# cfg_get <key> <default>
cfg_get() {
local key="$1" default="$2"
local file="${CONFIG_FILE:-.forker.yaml}"
[ -f "$file" ] || { echo "$default"; return; }
local val
val="$(grep -E "^[[:space:]]*${key}[[:space:]]*:" "$file" | head -n1 \
| sed -E "s/^[[:space:]]*${key}[[:space:]]*:[[:space:]]*//" \
| sed -E 's/[[:space:]]+#.*$//' \
| sed -E 's/^"(.*)"$/\1/; s/^'"'"'(.*)'"'"'$/\1/' \
| sed -E 's/[[:space:]]+$//')"
[ -z "$val" ] && val="$default"
echo "$val"
}
# load_config sets: TOKEN_USER, MIRROR_TAGS, MIRROR_PRUNE, MIRROR_BRANCHES,
# ON_NEW_TAG, MIRROR_UPSTREAM_RELEASES, BUILD_CMD, BUILD_SCRIPT, ARTIFACTS
load_config() {
TOKEN_USER="$(cfg_get token_user "oauth2")"
MIRROR_TAGS="$(cfg_get mirror_tags "true")"
MIRROR_PRUNE="$(cfg_get mirror_prune "true")"
MIRROR_BRANCHES="$(cfg_get mirror_branches "*")"
ON_NEW_TAG="$(cfg_get on_new_tag "true")"
MIRROR_UPSTREAM_RELEASES="$(cfg_get mirror_upstream_releases "false")"
BUILD_CMD="$(cfg_get build_cmd "")"
BUILD_SCRIPT="$(cfg_get build_script "")"
ARTIFACTS="$(cfg_get artifacts "")"
}
-320
View File
@@ -1,320 +0,0 @@
#!/usr/bin/env bash
# provider.sh — detect the upstream provider and expose a uniform releases API.
#
# Sourced by other scripts. Provides:
# detect_provider <url> -> prints gitea|github|codeberg|unknown
# releases_api_base <url> -> prints the REST base for the repo
# releases_auth_header <url> -> prints "Authorization: ..." line
# list_releases <url> <token> -> prints JSON array of releases (normalized)
# get_release <url> <token> <tag> -> prints one release JSON
# download_asset <url> <token> <asset_url> <dest>
#
# The token is passed in (from the Gitea Actions secret), never read from the
# repo. Provider differences are isolated here so the rest of the code is
# provider-agnostic.
set -o pipefail
# --- detection ---------------------------------------------------------------
# Bare hostname from a URL: "https://host", "https://host/", or "https://host/path".
host_of() { local u="${1#*://}"; echo "${u%%/*}"; }
# Base URL with scheme, no path: "https://host" (for building absolute API URLs).
base_url_of() {
local u="$1" scheme rest host
scheme="${u%%://*}"; rest="${u#*://}" # split off scheme
host="${rest%%/*}" # host (stop at first /)
echo "${scheme}://${host}"
}
detect_provider() {
local url="${1:-}"
local host
host="$(host_of "$url")"
case "$host" in
github.com|api.github.com|githubusercontent.com) echo "github" ;;
codeberg.org|*.codeberg.org) echo "codeberg" ;;
gitea.com|*.gitea.com) echo "gitea" ;;
*)
# Fallback: unknown hosts are treated as Gitea-compatible (the most common
# self-hosted shape). The releases API is Gitea's; if a host speaks a
# different dialect the mirror step will simply find no matching release.
echo "gitea"
;;
esac
}
# owner/repo from a clone URL (https://host/owner/repo.git or .../owner/repo)
owner_repo() {
local url="${1:-}"
# strip protocol, host, .git, trailing slash
local path
path="${url#*://}"
path="${path#*/}" # drop host
path="${path%.git}"
path="${path%/}"
echo "$path" # owner/repo
}
# --- releases API -----------------------------------------------------------
# Each provider returns a slightly different shape. We normalize to:
# [{"tag": "...", "name": "...", "body": "...", "assets": [{"name": "...", "url": "...", "size": N}]}]
# auth_args <token> — sets the global AUTH_ARGS array to -H "Authorization:
# Bearer <token>", or empty. An empty Bearer header makes GitHub reject the
# request (401 "Bad credentials"); public repos need no auth at all.
auth_args() {
local token="${1:-}"
AUTH_ARGS=()
if [ -n "$token" ]; then
AUTH_ARGS=(-H "Authorization: Bearer $token")
fi
}
list_releases() {
local url="${1:-}"
local token="${2:-}"
local provider
provider="$(detect_provider "$url")"
local base owner_repo_ api
base="$(base_url_of "$url")"
owner_repo_="$(owner_repo "$url")"
# GitHub's REST API lives on api.github.com (no /api/v1 prefix), while
# Gitea/Codeberg use <host>/api/v1.
if [ "$provider" = "github" ]; then
api="https://api.github.com/repos/$owner_repo_/releases"
else
api="$base/api/v1/repos/$owner_repo_/releases"
fi
auth_args "$token"
local clone_base
clone_base="$(github_clone_base "$url")"
case "$provider" in
github)
# GitHub: token via header (only when set), per_page for pagination
# shellcheck disable=SC2068 # AUTH_ARGS is a safe -H pair
curl -sS --max-time 60 \
${AUTH_ARGS[@]+"${AUTH_ARGS[@]}"} \
-H "Accept: application/vnd.github+json" \
"$api?per_page=100" | _norm_releases github "$clone_base"
;;
gitea|codeberg)
# Gitea and Codeberg both use the Gitea API shape; Bearer works for both.
# shellcheck disable=SC2068 # AUTH_ARGS is a safe -H pair
curl -sS --max-time 60 \
${AUTH_ARGS[@]+"${AUTH_ARGS[@]}"} \
"$api?limit=100" | _norm_releases gitea "$clone_base"
;;
*)
echo "[]"
;;
esac
}
get_release() {
local url="${1:-}" token="${2:-}" tag="${3:-}"
local provider base owner_repo_ api
provider="$(detect_provider "$url")"
base="$(base_url_of "$url")"
owner_repo_="$(owner_repo "$url")"
# GitHub's REST API lives on api.github.com (no /api/v1 prefix), while
# Gitea/Codeberg use <host>/api/v1.
if [ "$provider" = "github" ]; then
api="https://api.github.com/repos/$owner_repo_/releases/tags/$tag"
else
api="$base/api/v1/repos/$owner_repo_/releases/tags/$tag"
fi
# Bearer only when a token is set (public repos: no auth header at all).
# The clone URL + tag are passed so GitHub assets resolve to the web
# download URL (unthrottled) instead of the REST asset endpoint.
local clone_base code body rc
clone_base="$(github_clone_base "$url")"
# Capture the HTTP code: a 404 (no release for this tag upstream) must be
# distinguishable from a valid-but-empty release, so it is NOT normalized
# into a pseudo-release with zero assets.
body="$(mktemp)"
if [ -n "$token" ]; then
code="$(curl -sS --max-time 60 -o "$body" -w '%{http_code}' \
-H "Authorization: Bearer $token" "$api" 2>/dev/null || echo 000)"
else
code="$(curl -sS --max-time 60 -o "$body" -w '%{http_code}' \
"$api" 2>/dev/null || echo 000)"
fi
case "$code" in
200) _norm_release "$provider" "$clone_base" "$tag" < "$body"; rc=0 ;;
404) echo '{}'; rc=0 ;;
*) echo "ERROR: get_release $tag returned HTTP $code" >&2; rc=1 ;;
esac
rm -f "$body"
return "$rc"
}
# github_clone_base <url> -> "https://github.com/owner/repo" (or "" for
# non-GitHub). Used to build the unthrottled web asset download URL.
github_clone_base() {
local url="${1:-}" host path
host="$(host_of "$url")"
case "$host" in
github.com)
path="${url#*://}"; path="${path#*/}" # owner/repo[.git]
path="${path%.git}"
echo "https://github.com/$path"
;;
*) echo "" ;;
esac
}
# Normalize a single release object.
# _norm_release <provider> <clone_base> <tag>
# For GitHub, when the asset's download_url is null (true for releases
# addressed by tag), resolve the asset to the WEB download URL
# (<clone_base>/releases/download/<tag>/<name>) — this is unthrottled,
# unlike the REST asset endpoint (60 req/h unauthenticated). Falls back to
# the API url (which download_asset handles via Accept: octet-stream).
_norm_release() {
local provider="$1" clone_base="${2:-}" tag="${3:-}"
# NOTE: use `python3 -c` (script as a string) so STDIN remains the curl pipe.
# A heredoc (`python3 - <<'PY'`) would consume stdin and the JSON would be lost.
CB="$clone_base" TAG="$tag" PROVIDER="$provider" python3 -c '
import sys, json, os
cb = os.environ.get("CB","")
tag = os.environ.get("TAG","")
prov = os.environ.get("PROVIDER","")
try:
d = json.load(sys.stdin)
except Exception:
print("{}"); sys.exit(0)
if not isinstance(d, dict):
print("{}"); sys.exit(0)
assets = []
for a in (d.get("assets") or []):
name = a.get("name")
u = a.get("download_url") or a.get("url") or a.get("browser_download_url")
if prov == "github" and not a.get("download_url") and cb and tag and name:
# REST asset url -> unthrottled web url
u = cb + "/releases/download/" + tag + "/" + name
assets.append({"name": name, "url": u, "size": a.get("size")})
print(json.dumps({
"tag": d.get("tag_name"),
"name": d.get("name"),
"body": d.get("body") or d.get("description") or "",
"assets": assets,
}))'
}
# Normalize a list of release objects.
# _norm_releases <provider> <clone_base>
# GitHub assets resolve to the unthrottled web download URL when possible
# (see _norm_release); non-GitHub providers ignore clone_base.
_norm_releases() {
local provider="$1" clone_base="${2:-}"
# stdin must stay the curl pipe -> use `python3 -c`, not a heredoc.
CB="$clone_base" PROVIDER="$provider" python3 -c '
import sys, json, os
cb = os.environ.get("CB","")
prov = os.environ.get("PROVIDER","")
try:
d = json.load(sys.stdin)
except Exception:
print("[]"); sys.exit(0)
if not isinstance(d, list):
print("[]"); sys.exit(0)
out = []
for r in d:
tag = r.get("tag_name") or ""
assets = []
for a in (r.get("assets") or []):
name = a.get("name")
u = a.get("download_url") or a.get("url") or a.get("browser_download_url")
if prov == "github" and not a.get("download_url") and cb and tag and name:
u = cb + "/releases/download/" + tag + "/" + name
assets.append({"name": name, "url": u, "size": a.get("size")})
out.append({
"tag": tag,
"name": r.get("name"),
"body": r.get("body") or r.get("description") or "",
"assets": assets,
})
print(json.dumps(out))'
}
download_asset() {
local url="${1:-}" token="${2:-}" asset_url="${3:-}" dest="${4:-}"
# Accept: application/octet-stream is REQUIRED for GitHub: for a release
# addressed by tag, the asset's `download_url` is null, so the API `url`
# is used — without this header it returns the asset's JSON metadata
# (HTTP 200, ~1.8 KB) instead of the binary file. Harmless for direct
# file URLs (Gitea/Codeberg browser_download_url).
#
# Fail LOUDLY: a 404 / rate-limit body must not be written to $dest and
# then attached as a (corrupt/JSON) asset. --fail makes curl exit non-zero
# on HTTP >= 400; we also delete a partial file on failure so the caller's
# set -e aborts the release instead of shipping a bad asset.
local rc=0
if [ -n "$token" ]; then
curl -sSL --fail --max-time 300 -H "Authorization: Bearer $token" \
-H "Accept: application/octet-stream" -o "$dest" "$asset_url" || rc=$?
else
curl -sSL --fail --max-time 300 -H "Accept: application/octet-stream" \
-o "$dest" "$asset_url" || rc=$?
fi
if [ "$rc" -ne 0 ]; then
rm -f "$dest"
echo "ERROR: asset download failed (curl exit $rc): $asset_url" >&2
return 1
fi
[ -s "$dest" ] || { rm -f "$dest"; echo "ERROR: asset download empty: $asset_url" >&2; return 1; }
}
# Does a release for this tag already exist on THIS gitea? Prints yes/no.
# release_exists <gitea_url> <owner/repo> <token> <tag>
release_exists() {
local gitea_url="${1:-}" owner_repo_="${2:-}" token="${3:-}" tag="${4:-}"
local code
code="$(curl -sS --max-time 30 -o /dev/null -w "%{http_code}" \
-H "Authorization: Bearer $token" \
"$gitea_url/api/v1/repos/$owner_repo_/releases/tags/$tag")"
[ "$code" = "200" ] && echo "yes" || echo "no"
}
# Publish a release on THIS gitea (the fork). Token is the Gitea token.
# publish_local_release <gitea_url> <owner/repo> <token> <tag> <name> <body> [asset_file ...]
publish_local_release() {
local gitea_url="${1:-}" owner_repo_="${2:-}" token="${3:-}" tag="${4:-}"
local name="${5:-}" body="${6:-}"
shift 6
local assets=(${@+"$@"})
# Create the release (tag must already exist in the repo).
local resp
resp="$(curl -sS --max-time 60 -X POST \
-H "Authorization: Bearer $token" \
-H "Content-Type: application/json" \
-d "$(python3 -c 'import sys,json;print(json.dumps({"tag_name":sys.argv[1],"name":sys.argv[2],"body":sys.argv[3]}))' "$tag" "$name" "$body")" \
"$gitea_url/api/v1/repos/$owner_repo_/releases")"
local release_id
release_id="$(echo "$resp" | python3 -c 'import sys,json;print(json.load(sys.stdin).get("id",""))' 2>/dev/null)"
[ -z "$release_id" ] && { echo "ERROR: could not create release: $resp" >&2; return 1; }
# Attach assets (if any). Gitea's upload field is "attachment".
# Fail LOUDLY: a failed upload (413 too large, 404, transient) must abort
# the release, not be swallowed — release.sh's idempotency guard would
# otherwise skip this tag forever and the release would be permanently
# partial while every subsequent run reports green.
local f rc
for f in "${assets[@]}"; do
[ -f "$f" ] || continue
rc=0
curl -sS --fail --max-time 300 -X POST \
-H "Authorization: Bearer $token" \
-F "attachment=@$f" \
"$gitea_url/api/v1/repos/$owner_repo_/releases/$release_id/assets" \
>/dev/null || rc=$?
if [ "$rc" -ne 0 ]; then
echo "ERROR: asset upload failed (curl exit $rc): $f -> release $release_id" >&2
return 1
fi
done
echo "$release_id"
}
+70
View File
@@ -0,0 +1,70 @@
"""Mirror stdout/stderr into a log file without losing ``docker logs``.
The UI's Worker page tails ``WORKER_LOG`` to show scheduler and queue chatter.
Doing it here (instead of ``cmd | tee`` in the entrypoint) keeps the worker as
the direct child of PID 1, so SIGTERM from ``docker stop`` reaches its graceful
shutdown instead of a shell holding a pipe.
"""
from __future__ import annotations
import os
import sys
import threading
from typing import TextIO
class _Tee:
def __init__(self, stream: TextIO, sink: TextIO | None):
self._stream = stream
self._sink = sink
self._lock = threading.Lock()
def write(self, data: str) -> int:
n = self._stream.write(data)
if self._sink is not None:
with self._lock:
try:
self._sink.write(data)
self._sink.flush()
except (OSError, ValueError):
pass # a full/log-rotated volume must never break the worker
return n
def flush(self) -> None:
self._stream.flush()
if self._sink is not None:
try:
self._sink.flush()
except (OSError, ValueError):
pass
def isatty(self) -> bool:
return self._stream.isatty()
def fileno(self) -> int:
return self._stream.fileno()
@property
def encoding(self) -> str:
return getattr(self._stream, "encoding", "utf-8")
def install_worker_log(path: str | None = None) -> str:
"""Tee stdout/stderr into ``path`` (default: $WORKER_LOG). Returns the path used.
A path outside a writable directory is not fatal — the container still
works, ``docker logs`` still shows everything.
"""
path = path or os.environ.get("WORKER_LOG") or ""
if not path:
return ""
try:
os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
sink = open(path, "a", encoding="utf-8", errors="replace") # noqa: SIM115 - process lifetime
except OSError as e:
print(f"WARN: worker log disabled ({path}: {e})", file=sys.stderr, flush=True)
return ""
sys.stdout = _Tee(sys.stdout, sink) # type: ignore[assignment]
sys.stderr = _Tee(sys.stderr, sink) # type: ignore[assignment]
return path
+152
View File
@@ -0,0 +1,152 @@
"""Auto-paced interval: never schedule passes faster than our share of
GitHub's unauthenticated API window.
GitHub answers anonymous REST calls with a rolling budget of ~60 requests per
hour per IP. That IP is usually also the operator's browser, so the worker
plans against **80% of the window (48/h)** and leaves the rest for manual
triggers. The rule is a floor, never an accelerator:
effective_interval = max(INTERVAL, what_the_budget_requires)
* an explicit ``INTERVAL`` larger than the required minimum is honored
untouched (auto never syncs *more* than you asked for);
* an ``INTERVAL`` that would overshoot the window is pushed up to the safe
value — this is the "don't think about it" part;
* ``INTERVAL=0`` stays paused — auto never un-pauses a stopped scheduler;
* a mirror pinned with its own ``sync_interval`` schedules itself regardless
(documented trade-off: a pinned fast mirror may spend over budget).
Cost model — exactly what one pass makes against api.github.com, anonymous,
for one GitHub mirror:
* parity recount, once per pass: ``1 + walk`` pages, where ``walk`` is the
release-pagination walk of :func:`forker.provider.list_release_counts`
(bounded at 10), plus one releases-tag probe for refs-only mirrors;
* ``mirror_upstream_releases``: one ``releases/tags/<tag>`` call per upstream
tag the fork has no release for — including tags upstream simply has no
release for (their 404 spends budget too), so a tag list full of
release-less tags honestly keeps the pace slow.
So a settled mirror costs 2–3 calls/pass; a cold mirror catching up on N
tags costs N+2 that pass, and the plan spreads it by widening the interval.
Estimates read each record's own counts (tags/releases/parity), not guesses.
"""
from __future__ import annotations
import math
from typing import Any
from . import provider
from .config import merge_config
#: Our share of GitHub's anonymous window (60/h leaves 12/h for the browser).
GITHUB_BUDGET_PER_HOUR = 48
#: When the plan itself picks the interval it will not go below this —
#: sub-10-minute mirror churn buys nothing. It does NOT clamp an explicit
#: INTERVAL that the budget already tolerates.
FLOOR_SEC = 600
#: Never slower than daily — beyond that a mirror is effectively "on demand".
CEIL_SEC = 86400
#: Fallback tag count for a brand-new mirror whose counts are not known yet:
#: assume a small catch-up storm so the very first passes are conservative.
UNKNOWN_TAGS_ASSUMED = 10
def release_walk_pages(release_count: Any) -> int:
"""Pages `list_release_counts` fetches: 1 when empty/unknown, ≤ 10."""
try:
n = max(int(release_count), 0)
except (TypeError, ValueError):
n = 0
return min(10, max(1, math.ceil(n / 100)))
def pass_cost(rec: dict[str, Any]) -> int:
"""Calls one pass makes against the *anonymous GitHub* budget for this
mirror. 0 = this mirror cannot spend it: disabled, non-GitHub upstream,
or carrying its own token (authenticated calls live in a separate
5.000/h window and never touch the anonymous one)."""
cfg = merge_config(rec.get("config") or {})
if not cfg.get("enabled", True):
return 0
if provider.detect_provider(rec.get("upstream") or "") != "github":
return 0
if str(rec.get("upstream_token") or "").strip():
return 0
parity = rec.get("parity") or {}
counts = rec.get("counts") or {}
known_releases = parity.get("releases")
if not isinstance(known_releases, int):
known_releases = counts.get("releases")
# Parity walk: list_release_counts walks 1..10 pages, one call each.
cost = release_walk_pages(known_releases)
# Only mirroring upstream releases hits api.github.com per tag; a
# build-only mirror never calls the GitHub API (git traffic is separate).
if bool(cfg.get("mirror_upstream_releases")):
tags = parity.get("tags")
if not isinstance(tags, int) or tags < 0:
known_tags = counts.get("tags")
tags = known_tags if isinstance(known_tags, int) and known_tags >= 0 \
else UNKNOWN_TAGS_ASSUMED
have = counts.get("releases")
have = have if isinstance(have, int) and have > 0 else 0
cost += max(0, tags - have)
return cost
def plan(records: dict[str, dict[str, Any]], explicit_interval: int,
budget: int = GITHUB_BUDGET_PER_HOUR) -> dict[str, Any]:
"""Decide this tick's interval from the registry's current shape."""
github_cost = 0
github_repos = 0
pinned: list[tuple[str, int]] = []
for name, rec in (records or {}).items():
cfg = merge_config(rec.get("config") or {})
try:
pin = int(cfg.get("sync_interval") or 0)
except (TypeError, ValueError):
pin = 0
if pin > 0:
pinned.append((name, pin))
continue
cost = pass_cost(rec)
if cost:
github_repos += 1
github_cost += cost
required = 0
if github_cost:
required = -(-github_cost * 3600 // budget) # ceil: seconds to fit the window
if explicit_interval <= 0:
# Paused is a user's call — the plan must not resurrect the scheduler.
effective = int(explicit_interval)
reason = "scheduler en pausa (INTERVAL≤0): el plan solo observa"
elif required == 0:
effective = int(explicit_interval)
reason = "sin mirrors github anónimos: el presupuesto no aplica"
elif explicit_interval >= required:
# The explicit INTERVAL already respects the window — auto defers to
# it, even below FLOOR_SEC. Auto never slows a safe user choice down.
effective = int(explicit_interval)
reason = (f"INTERVAL={explicit_interval}s respeta el presupuesto "
f"({github_cost} llamadas/pasada ≤ {budget}/h)")
else:
effective = max(FLOOR_SEC, min(CEIL_SEC, required))
reason = (f"auto: {github_cost} llamadas/pasada en {github_repos} mirror(s) "
f"github anónimo(s) exigen ≥{required}s con {budget}/h; "
f"INTERVAL={explicit_interval}s se subió a {effective}s")
return {
"effective_sec": int(effective),
"explicit_sec": int(explicit_interval),
"required_sec": int(required),
"github_repos": github_repos,
"cost_per_pass": github_cost,
"est_calls_per_hour": (round(github_cost * 3600 / effective, 1)
if github_cost and effective > 0 else 0.0),
"budget_per_hour": budget,
"pinned": [{"name": n, "interval_sec": p} for n, p in pinned],
"reason": reason,
}
+183
View File
@@ -0,0 +1,183 @@
"""Provider-agnostic upstream *releases* API (GitHub / Gitea / Codeberg).
Port of ``forker/lib/provider.sh``. Two invariants inherited from the shell
version, both non-negotiable:
1. **Anonymous by default.** A public upstream is fetched with *no* auth
header at all. An empty token must mean "no header", never
``Authorization: Bearer `` — GitHub answers that with a 401, so an empty
Bearer is worse than none.
2. **GitHub asset URLs.** On a release addressed by tag the REST asset
``download_url`` is null and the API ``url`` returns JSON metadata unless
``Accept: application/octet-stream`` is sent; the REST endpoint is also
throttled to 60 req/h unauthenticated (nowhere near enough to mirror ~200
assets). So GitHub assets resolve to the *web* download URL
``https://github.com/<owner>/<repo>/releases/download/<tag>/<name>``, which
is unthrottled.
"""
from __future__ import annotations
import json
import urllib.error
import urllib.parse
import urllib.request
from typing import Any
UA = "repo-forker-worker (anonymous)"
def host_of(url: str) -> str:
rest = url.split("://", 1)[-1]
rest = rest.split("/", 1)[0]
return rest.split("@")[-1].split(":")[0].lower()
def base_url_of(url: str) -> str:
if "://" not in url:
return url
scheme, rest = url.split("://", 1)
return f"{scheme}://{rest.split('/', 1)[0]}"
def owner_repo(url: str) -> str:
path = url.split("://", 1)[-1]
path = path.split("/", 1)[-1] if "/" in path else ""
return path.removesuffix("/").removesuffix(".git")
def detect_provider(url: str) -> str:
host = host_of(url)
if host in ("github.com", "api.github.com", "githubusercontent.com"):
return "github"
if host == "codeberg.org" or host.endswith(".codeberg.org"):
return "codeberg"
if host == "gitea.com" or host.endswith(".gitea.com"):
return "gitea"
# Unknown hosts are treated as Gitea-compatible (the common self-hosted
# shape). A host speaking a different dialect simply yields no release.
return "gitea"
def _api_base(url: str) -> str:
provider = detect_provider(url)
repo = owner_repo(url)
if provider == "github":
return f"https://api.github.com/repos/{repo}"
return f"{base_url_of(url)}/api/v1/repos/{repo}"
def _request(url: str, token: str = "", *, timeout: int = 60,
accept: str | None = None) -> tuple[int, bytes]:
headers = {"User-Agent": UA}
if accept:
headers["Accept"] = accept
if token: # never send an empty Bearer (see module docstring)
headers["Authorization"] = f"Bearer {token}"
req = urllib.request.Request(url, headers=headers)
try:
with urllib.request.urlopen(req, timeout=timeout) as res:
return res.status, res.read()
except urllib.error.HTTPError as e:
return e.code, (e.read() or b"")
except urllib.error.URLError as e:
return 0, str(getattr(e, "reason", e)).encode()
def _norm_release(raw: dict[str, Any], provider: str, clone_base: str, tag: str) -> dict[str, Any]:
assets = []
for a in raw.get("assets") or []:
name = a.get("name")
url = a.get("download_url") or a.get("url") or a.get("browser_download_url")
if provider == "github" and not a.get("download_url") and clone_base and tag and name:
url = f"{clone_base}/releases/download/{tag}/{name}"
assets.append({"name": name, "url": url, "size": a.get("size")})
return {
"tag": raw.get("tag_name"),
"name": raw.get("name"),
"body": raw.get("body") or raw.get("description") or "",
"assets": assets,
}
def github_clone_base(url: str) -> str:
if host_of(url) != "github.com":
return ""
return f"https://github.com/{owner_repo(url)}"
def get_release(url: str, token: str, tag: str) -> dict[str, Any] | None:
"""Upstream release for a tag. None = the upstream has none (HTTP 404).
Raises on any other failure: a 500 or a rate-limit body must not be
normalized into "no release", or the mirror would quietly publish an
empty release and then skip the tag forever.
"""
provider = detect_provider(url)
api = f"{_api_base(url)}/releases/tags/{urllib.parse.quote(tag, safe='')}"
accept = "application/vnd.github+json" if provider == "github" else None
status, payload = _request(api, token, accept=accept)
if status == 200:
try:
data = json.loads(payload)
except json.JSONDecodeError as e:
raise RuntimeError(f"upstream release JSON unreadable ({url}): {e}") from None
return _norm_release(data, provider, github_clone_base(url), tag)
if status == 404:
return None
raise RuntimeError(f"upstream release {tag} returned HTTP {status} ({url})")
def list_release_counts(url: str, token: str = "") -> tuple[int | None, int | None]:
"""(release_count, asset_count) upstream, for the parity panel.
GitHub gets a paginated REST walk; everything else is counted with
``git ls-remote`` by the caller, so releases stay unknown (None) here.
"""
provider = detect_provider(url)
if provider != "github":
return (None, None)
api = f"{_api_base(url)}/releases"
releases = 0
assets = 0
for page in range(1, 11):
status, payload = _request(
f"{api}?per_page=100&page={page}", token,
accept="application/vnd.github+json",
)
if status != 200:
return (None, None) if page == 1 else (releases, assets)
try:
chunk = json.loads(payload)
except json.JSONDecodeError:
return (None, None) if page == 1 else (releases, assets)
if not isinstance(chunk, list):
break
releases += len(chunk)
assets += sum(len(r.get("assets") or []) for r in chunk)
if len(chunk) < 100:
break
return (releases, assets)
def download_asset(url: str, token: str, asset_url: str, dest: str,
timeout: int = 300) -> None:
"""Download one upstream asset to ``dest``, loudly.
A 404 or a rate-limit HTML body must never end up attached as a corrupt
asset, so failures raise and remove the partial file.
"""
status, payload = _request(asset_url, token, timeout=timeout,
accept="application/octet-stream")
if status >= 400 or not payload:
try:
import os
os.path.exists(dest) and os.remove(dest)
except OSError:
pass
raise RuntimeError(
f"asset download failed (HTTP {status}): {asset_url}"
)
with open(dest, "wb") as fh:
fh.write(payload)
+523
View File
@@ -0,0 +1,523 @@
"""Mirror registry: create / list / update / delete the mirrors this container owns.
This replaces the UI server's ``createMirror`` pipeline choreography. The old
sequence was "fork the template, set an Actions variable, dispatch sync.yml";
with the runner gone there is nothing to dispatch, so the equivalent is:
1. create (or adopt) the destination repo on ``REMOTE``,
2. write the machinery branch (``forker``) holding ``.forker.yaml``,
3. point the default branch at the upstream's,
4. register the mirror in ``state.json`` and sync it immediately.
Upstream tokens are stored in ``state.json`` (chmod 600, inside ``DATA_DIR`` —
mount it on a volume you control), never in the mirrored repo.
"""
from __future__ import annotations
import hashlib
import os
import re
import shutil
import threading
import time
import urllib.request
from typing import Any, Callable
from . import provider
from .config import CONFIG_DEFAULTS, Settings, merge_config, parse_flat, render_flat
from .gitea import Gitea, GiteaError
from .gitops import MACHINERY_BRANCH, GitError, Mirror, Refs
from .state import LogStore, StateStore
# A repo name Gitea will accept (and which must not end in .git).
_NAME_RE = re.compile(r"[^A-Za-z0-9._-]+")
def derive_repo_name(url: str) -> str:
"""Name a mirror from its upstream URL (lowercased, no trailing .git)."""
path = url.split("://", 1)[-1]
path = path.split("/", 1)[-1] if "/" in path else ""
path = path.strip("/") # a trailing slash would yield an empty name
last = path.split("/")[-1] if path else ""
last = _NAME_RE.sub("-", last.removesuffix(".git")).strip("-._") or "mirror"
return last.lower()
class Registry:
"""Owns the mirror records and the operations that mutate them."""
def __init__(self, settings: Settings, gitea: Gitea, state: StateStore, logs: LogStore,
owner: str | None = None):
self.s = settings
self.g = gitea
self.state = state
self.logs = logs
self._owner = owner
self._lock = threading.RLock()
# name -> why the pass is running ("manual", "tick", "boot", …). The UI
# labels a pass by *why it ran*, and a set could not carry that.
self._running: dict[str, str] = {}
@property
def owner(self) -> str:
if self._owner is None:
try:
self._owner = (self.g.whoami().get("login") or "").strip()
except GiteaError as e:
raise GiteaError(e.status, f"cannot resolve the token owner: {e}") from None
return self._owner or ""
def full_name(self, name: str) -> str:
return f"{self.owner}/{name}" if "/" not in name else name
# ------------------------------------------------------------------ list
def records(self) -> dict[str, dict[str, Any]]:
return self.state.mirrors()
def record(self, name: str) -> dict[str, Any] | None:
return self.state.mirror(name)
def is_running(self, name: str) -> bool:
with self._lock:
return name in self._running
def running_reason(self, name: str) -> str | None:
with self._lock:
return self._running.get(name)
def mark_running(self, name: str, running: bool, reason: str = "worker") -> None:
with self._lock:
if running:
self._running[name] = reason
else:
self._running.pop(name, None)
def summary(self, name: str, rec: dict[str, Any] | None = None) -> dict[str, Any]:
"""API view of one mirror: config + last result + live status."""
rec = rec or self.state.mirror(name) or {}
cfg = merge_config(rec.get("config") or {})
last = dict(rec.get("last") or {})
return {
"name": name,
"full": rec.get("full") or self.full_name(name),
"upstream": rec.get("upstream", ""),
"forkUrl": f"{self.s.remote}/{rec.get('full') or self.full_name(name)}",
"defaultBranch": rec.get("default_branch") or MACHINERY_BRANCH,
"owner": (rec.get("full") or self.full_name(name)).split("/")[0],
"hasToken": bool(rec.get("upstream_token")),
"enabled": bool(cfg.get("enabled", True)),
"intervalSec": int(cfg.get("sync_interval") or self.s.interval_sec),
"running": self.is_running(name),
"runningReason": self.running_reason(name),
"config": cfg,
# The last pass, flat: the API layer reads these keys directly and a
# nested "summary" sub-dict was a silent bug (lastCounts came back
# all-null because the two sides disagreed on where the counts live).
"last": {
"at": rec.get("last_at"),
"ok": last.get("ok"),
"reason": rec.get("last_reason"),
"file": last.get("file"),
"durationSec": last.get("durationSec"),
"error": last.get("error"),
"cold": last.get("cold"),
"branchesPushed": last.get("branchesPushed"),
"tagsPushed": last.get("tagsPushed"),
"branchesPruned": last.get("branchesPruned"),
"tagsPruned": last.get("tagsPruned"),
"releasesPublished": last.get("releasesPublished") or [],
} if rec.get("last") else None,
"spark": (rec.get("spark") or [])[-20:],
"releaseFailures": last.get("releaseFailures") or [],
"disabledWorkflows": last.get("disabledWorkflows") or [],
"unitFix": last.get("unitFix"),
"counts": rec.get("counts") or {},
"parity": rec.get("parity") or {},
"units": rec.get("units") or [],
# "ok" | "remote write failed: …" — a config the UI saved but the
# remote file refused survives exactly one pass, so the UI must be
# able to say so instead of showing a green save.
"configSync": rec.get("config_sync"),
"createdAt": rec.get("created_at"),
}
def list_summaries(self) -> list[dict[str, Any]]:
recs = self.state.mirrors()
return [self.summary(name, rec) for name, rec in sorted(recs.items())]
# ---------------------------------------------------------------- create
def create(self, *, upstream: str, name: str | None = None,
upstream_token: str = "", config: dict[str, Any] | None = None,
private: bool = False,
step: Callable[[str, str, str], None] | None = None,
log: Callable[[str], None] | None = None) -> dict[str, Any]:
"""Create a mirror. ``step(name, status, detail)`` drives the wizard.
Idempotent by design: a retry after a half-finished creation adopts the
repo that is already there and re-applies the remaining steps, instead
of 409ing on "the repository with the same name already exists".
"""
say = step or (lambda n, s, d: None)
note = log or (lambda m: None)
upstream = (upstream or "").strip()
if not upstream.startswith(("http://", "https://")):
raise ValueError("upstream must be an http(s) git URL")
repo_name = (name or "").strip().removesuffix(".git") or derive_repo_name(upstream)
if not _NAME_RE.sub("", repo_name) or repo_name in (".", ".."):
raise ValueError(f"invalid mirror name: {repo_name!r}")
full = f"{self.owner}/{repo_name}"
parsed = dict(config or {})
unknown = [k for k in parsed if k not in CONFIG_DEFAULTS]
if unknown:
raise ValueError(f"unknown config key(s): {', '.join(sorted(unknown))}")
if self.state.mirror(repo_name):
raise ValueError(f"{repo_name} is already managed by this container")
# 1) destination repo
try:
try:
self.g.create_repo(self.owner, repo_name,
description=f"Mirror of {upstream} (Repo Forker)",
private=private)
note(f"created {full}")
except GiteaError as e:
if e.status in (409,) or "already exists" in str(e.message).lower():
note(f"{full} already exists — adopting it")
self.g.repo(full) # blows up loudly if it is something else
else:
raise
say("create-repo", "ok", full)
except (GiteaError, ValueError) as e:
say("create-repo", "error", str(e))
raise
# 2) machinery branch + 3) per-mirror config
try:
from .engine import default_config_text
text = render_flat({**CONFIG_DEFAULTS, **parsed}, default_config_text())
wrote = self.g.write_file(full, ".forker.yaml", text,
"Add Repo Forker mirror config", MACHINERY_BRANCH)
note(f"forker branch config {'written' if wrote else 'already current'}")
say("forker-branch", "ok", ".forker.yaml")
say("config", "ok", f"{len(parsed)} override(s)" if parsed else "defaults")
except GiteaError as e:
say("forker-branch", "error", str(e))
raise
rec = {
"full": full,
"upstream": upstream,
"upstream_token": upstream_token or "",
"config": {**CONFIG_DEFAULTS, **parsed},
"created_at": int(time.time()),
"default_branch": MACHINERY_BRANCH,
"spark": [],
}
self.state.put(repo_name, rec)
# 4) default branch: try now (a 200 no-op on Gitea until the branch
# exists, so the first sync re-applies it for real).
try:
upstream_default = _probe_upstream_default(upstream, upstream_token)
if upstream_default and upstream_default != MACHINERY_BRANCH:
try:
self.g.set_default_branch(full, upstream_default)
rec["default_branch"] = upstream_default
self.state.put(repo_name, rec)
say("default-branch", "ok", upstream_default)
except GiteaError as e:
say("default-branch", "ok", f"deferred to first sync ({e})")
else:
say("default-branch", "ok", "after first sync")
except Exception as e: # noqa: BLE001 — probing the upstream is optional
say("default-branch", "ok", f"unknown ({e})")
return {"ok": True, "repo": repo_name, "full": full}
# ---------------------------------------------------------------- update
def update(self, name: str, *, upstream: str | None = None,
upstream_token: str | None = None, config: dict[str, Any] | None = None) -> dict[str, Any]:
rec = self.state.mirror(name)
if not rec:
raise KeyError(name)
if upstream is not None:
upstream = upstream.strip()
if not upstream.startswith(("http://", "https://")):
raise ValueError("upstream must be an http(s) git URL")
rec["upstream"] = upstream
# The mirror cache belongs to the old upstream — drop it so the next
# pass does not push a blend of two remotes.
shutil.rmtree(self.mirror_dir(name), ignore_errors=True)
if upstream_token is not None:
rec["upstream_token"] = upstream_token.strip()
if config:
unknown = [k for k in config if k not in CONFIG_DEFAULTS]
if unknown:
raise ValueError(f"unknown config key(s): {', '.join(sorted(unknown))}")
rec["config"] = {**merge_config(rec.get("config") or {}), **config}
# The remote .forker.yaml is what the sync pass actually honors (it
# re-reads it every pass, so an edit in the Gitea UI is never
# clobbered). A config change that only lands in state.json would
# therefore survive exactly one pass — so mirror it to the file too,
# and say so in the record if the repo refused it.
from .engine import write_remote_config
try:
write_remote_config(self.g, rec.get("full") or self.full_name(name), config)
rec["config_sync"] = "ok"
except GiteaError as e:
rec["config_sync"] = f"remote write failed: {str(e)[:160]}"
self.state.put(name, rec)
return rec
def set_config(self, name: str, parsed: dict[str, Any]) -> dict[str, Any]:
return self.update(name, config=parsed)
def touch(self, name: str, patch: dict[str, Any],
mutate: Callable[[dict], None] | None = None) -> dict[str, Any]:
"""Shallow-merge a patch into a record (the worker's run data).
A mirror deleted while a sync is in flight must stay deleted: without
this, the finishing pass would write its result back and resurrect it.
"""
if self.state.mirror(name) is None:
return {}
return self.state.update(name, patch, mutate)
def delete(self, name: str, *, remove_repo: bool = False) -> None:
rec = self.state.mirror(name)
if not rec:
raise KeyError(name)
if remove_repo:
self.g.delete_repo(rec.get("full") or self.full_name(name))
shutil.rmtree(self.mirror_dir(name), ignore_errors=True)
shutil.rmtree(self.probe_dir(name), ignore_errors=True)
shutil.rmtree(self.logs.dir_for(name), ignore_errors=True)
self.state.remove(name)
def mirror_dir(self, name: str) -> str:
return os.path.join(self.s.mirrors_dir, name.replace("/", "_"))
def probe_dir(self, name: str) -> str:
"""Throwaway bare repo used only as a config carrier for ls-remote."""
return os.path.join(self.s.data_dir, "probes",
hashlib.sha1(name.encode()).hexdigest()[:12]) # noqa: S324 - cache key
# ----------------------------------------------------------------- adopt
def adopt_all(self, *, include_repo_deletion_risk: bool = False) -> dict[str, Any]:
"""Register mirrors that already exist on REMOTE but are unknown here.
The pipeline world left a trail of forked/generated repos (a `forker`
branch + an `UPSTREAM_URL` Actions variable). Nothing forces a container
to own them, but re-creating 36 mirrors by hand is not an upgrade, so
this scans and takes them over:
* the upstream URL comes from the repo's `UPSTREAM_URL` Actions
variable when it still exists, else from the ``Mirror of <url>``
description the wizard writes;
* a repo whose `sync.yml` workflow is still enabled and *not* disabled
is left alone — its cron pipeline is still driving it, and running
both against one repo means two writers pushing the same refs;
* nothing on Gitea is deleted, ever. ``remove_repo`` only exists on the
explicit delete endpoint.
"""
adopted: list[dict[str, Any]] = []
skipped: list[dict[str, str]] = []
for repo in self._candidates():
full = repo.get("full_name") or ""
if not full:
continue
name = full.split("/", 1)[1]
if self.state.mirror(name):
continue
if not self.g.has_branch(full, MACHINERY_BRANCH):
continue
upstream = self._upstream_of(repo, full)
if not upstream:
skipped.append({"repo": full, "reason": "no UPSTREAM_URL variable and no 'Mirror of <url>' description"})
continue
still_pipelined = self._pipeline_still_drives(full)
if still_pipelined:
skipped.append({"repo": full, "reason": f"sync.yml still active on the runner ({still_pipelined})"})
continue
config = {}
try:
from .engine import read_remote_config
config = read_remote_config(self.g, full) or {}
except GiteaError:
pass
self.state.put(name, {
"full": full,
"upstream": upstream,
# Secrets are write-only in the Gitea API: an Actions secret that
# still exists cannot be read back, so the operator re-supplies it
# in the UI if the upstream is private.
"upstream_token": "",
"config": {**CONFIG_DEFAULTS, **config},
"created_at": int(time.time()),
"adopted_at": int(time.time()),
"default_branch": repo.get("default_branch") or MACHINERY_BRANCH,
"spark": [],
})
adopted.append({"repo": full, "upstream": upstream})
return {"adopted": adopted, "skipped": skipped,
"would_delete": None if not include_repo_deletion_risk else "nothing"}
def _candidates(self) -> list[dict[str, Any]]:
"""Repos that look like mirrors: forks of the template, plus any repo
under OWNER carrying a `forker` branch (generated repos are not forks)."""
out: dict[str, dict[str, Any]] = {}
owner = self.owner
try:
template = f"{owner}/{self.s.template_name}"
for repo in self.g.search_repos(owner=owner):
out[repo.get("full_name") or ""] = repo
for repo in self.g.search_repos(forked_only=True):
out.setdefault(repo.get("full_name") or "", repo)
try:
for repo in self.g.paged(f"/repos/{template}/forks"):
out.setdefault(repo.get("full_name") or "", repo)
except GiteaError:
pass # no forks / endpoint missing
except GiteaError:
pass
out.pop(f"{owner}/{self.s.template_name}", None)
return [r for full, r in out.items() if full and (
"/" in full and (full.split("/")[0] == owner or True)
)]
def _upstream_of(self, repo: dict[str, Any], full: str) -> str | None:
try:
data = self.g.get(f"/repos/{full}/actions/variables/UPSTREAM_URL")
value = (data or {}).get("data")
if isinstance(value, str) and value.startswith("http"):
return value
except GiteaError:
pass
desc = str(repo.get("description") or "")
if desc.startswith("Mirror of "):
head = desc[len("Mirror of "):].split(" ")[0].strip()
if head.startswith("http"):
return head
return None
def _pipeline_still_drives(self, full: str) -> str | None:
"""Return a reason when a Gitea Actions pipeline is still syncing this repo."""
try:
data = self.g.get(f"/repos/{full}/actions/workflows")
except GiteaError as e:
return None if e.status in (404, 403) else None
for w in (data or {}).get("workflows") or []:
path = str(w.get("path") or "")
name = str(w.get("name") or "")
if path.endswith("sync.yml") and not str(w.get("state", "")).startswith("disabled"):
if "Repo Forker" in name:
return path
return None
# ------------------------------------------------------ refresh (parity)
def refresh(self, name: str, *, force: bool = False) -> dict[str, Any]:
"""Recount branches/tags/releases on both sides for the parity panel.
Cheap by construction: counts come from ``git ls-remote`` (one
connection each) instead of paginating the REST API, and results are
cached 5 minutes so a UI polling every few seconds does not hammer
GitHub (anonymous REST is 60 req/h).
"""
rec = self.state.mirror(name)
if not rec:
raise KeyError(name)
last = rec.get("refreshed_at") or 0
if not force and time.time() - last < 300:
return rec
full = rec.get("full") or self.full_name(name)
upstream = rec.get("upstream", "")
token = rec.get("upstream_token", "")
counts: dict[str, Any]
units: list[str] = []
probe = Mirror(self.probe_dir(name), upstream, token)
try:
probe.ensure_init()
fork_refs = probe.remote_refs(f"{self.s.remote}/{full}.git", self.s.token)
# The machinery branch is ours, not a mirrored ref — counting it made
# every mirror look "ahead" of its upstream by one.
counts = {
"branches": len([b for b in fork_refs.heads if b != MACHINERY_BRANCH]),
"tags": len(fork_refs.tags),
}
except (GitError, GiteaError) as e:
counts = {"branches": None, "tags": None, "error": str(e)[:200]}
try:
releases = self.g.list_releases(full)
counts["releases"] = len(releases)
counts["assets"] = sum(len(r.get("assets") or []) for r in releases)
repo_obj = self.g.repo(full)
units = _units_of(repo_obj)
rec["default_branch"] = repo_obj.get("default_branch") or rec.get("default_branch")
except GiteaError as e:
counts.setdefault("releases", None)
counts["releases_error"] = str(e)[:200]
# ls-remote is one connection and needs no history download, so the
# probe mirror above stays empty forever — it is only a config carrier
# for the per-URL Bearer header.
parity: dict[str, Any]
try:
up_refs = probe.remote_refs(upstream, token)
parity = {"branches": len(up_refs.heads), "tags": len(up_refs.tags)}
except (GitError, GiteaError):
parity = {"branches": None, "tags": None}
rel_count, asset_count = provider.list_release_counts(upstream, token)
parity["releases"] = rel_count
parity["assets"] = asset_count
rec["counts"] = counts
rec["parity"] = parity
rec["units"] = units
rec["refreshed_at"] = int(time.time())
self.state.put(name, rec)
return rec
def _units_of(repo_obj: dict[str, Any]) -> list[str]:
flags = {
"has_code": "Code", "has_issues": "Issues", "has_pull_requests": "Pull Requests",
"has_releases": "Releases", "has_packages": "Packages", "has_projects": "Projects",
"has_wiki": "Wiki", "has_actions": "Actions",
}
return [label for key, label in flags.items() if repo_obj and repo_obj.get(key)]
def _probe_upstream_default(upstream: str, token: str) -> str | None:
"""Upstream's default branch over the wire (anonymous unless a token is set)."""
host = provider.host_of(upstream)
if host == "github.com":
repo = provider.owner_repo(upstream)
try:
import json
headers = {"User-Agent": "repo-forker-worker"}
if token:
headers["Authorization"] = f"Bearer {token}"
req = urllib.request.Request(f"https://api.github.com/repos/{repo}", headers=headers)
with urllib.request.urlopen(req, timeout=15) as res: # noqa: S310 - https URL
return str(json.loads(res.read()).get("default_branch") or "") or None
except Exception: # noqa: BLE001 — probing is best-effort
return None
try:
m = Mirror(os.path.join(os.environ.get("DATA_DIR", "/data"), "probes",
hashlib.sha1(upstream.encode()).hexdigest()[:12]), # noqa: S324
upstream, token)
m.ensure_init()
return m.default_branch()
except Exception: # noqa: BLE001
return None
__all__ = ["Registry", "derive_repo_name"]
-146
View File
@@ -1,146 +0,0 @@
#!/usr/bin/env bash
# release.sh — produce a release on this Gitea fork.
#
# Two modes (both on by default; controlled by .forker.yaml):
# 1. BUILD: checkout the tag's working tree, run the configured build
# command, and publish a release (tag + assets) on this Gitea.
# 2. MIRROR: mirror the upstream's existing releases (metadata + assets) via
# the provider API (see lib/provider.sh).
#
# Inputs (from Gitea Actions Variables/Secrets):
# GITEA_TOKEN, GITEA_SERVER_URL, GITEA_OWNER, GITEA_REPO
# UPSTREAM_URL, UPSTREAM_TOKEN (only needed for MIRROR mode)
#
# Args:
# $1 = tag to release (required)
set -euo pipefail
cd "$(dirname "$0")/.."
source forker/lib/config.sh
source forker/lib/provider.sh
load_config
TAG="${1:?usage: release.sh <tag>}"
GITEA_TOKEN="${GITEA_TOKEN:?GITEA_TOKEN is required}"
GITEA_SERVER_URL="${GITEA_SERVER_URL:?GITEA_SERVER_URL is required}"
GITEA_OWNER="${GITEA_OWNER:?GITEA_OWNER is required}"
GITEA_REPO="${GITEA_REPO:?GITEA_REPO is required}"
UPSTREAM_URL="${UPSTREAM_URL:-}"
UPSTREAM_TOKEN="${UPSTREAM_TOKEN:-}"
# --- never touch stored git credentials (same hardening as sync.sh) ---------
# All git calls here use explicit Bearer headers (fork build) or are
# anonymous (upstream mirror via provider.sh). Cut global/system config and
# the credential helper so a stored github.com entry can't be used silently.
export GIT_CONFIG_GLOBAL=/dev/null
export GIT_CONFIG_NOSYSTEM=1
export GIT_CONFIG_SYSTEM=/dev/null
# REPO_ROOT = the forker-branch checkout (where the machinery lives). The build
# runs inside $WORK (the tag's tree), but the build SCRIPT is resolved from here.
REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
WORK="$(mktemp -d)"
trap 'rm -rf "$WORK"' EXIT
# --- idempotency: skip if this tag already has a release ---------------------
if [ "$(release_exists "$GITEA_SERVER_URL" "$GITEA_OWNER/$GITEA_REPO" "$GITEA_TOKEN" "$TAG")" = "yes" ]; then
echo ">> Release for $TAG already exists — skipping (idempotent)."
exit 0
fi
cd "$WORK"
# --- 1) local build --------------------------------------------------------
ASSETS=()
BUILD_ENABLED=false
[ -n "$BUILD_CMD" ] && BUILD_ENABLED=true
[ -n "$BUILD_SCRIPT" ] && BUILD_ENABLED=true
if [ "$BUILD_ENABLED" = "true" ]; then
echo ">> Building release for tag $TAG (local build)"
# checkout the tag into a working tree. Bearer auth scoped to the fork URL
# (this repo is fresh; it doesn't inherit sync.sh's http.<url> config).
FORK_URL="$GITEA_SERVER_URL/$GITEA_OWNER/$GITEA_REPO.git"
git init . >/dev/null
git remote add fork "$FORK_URL"
git config http."$FORK_URL".extraHeader "Authorization: Bearer $GITEA_TOKEN"
git fetch --depth=1 fork "refs/tags/$TAG"
git checkout -q FETCH_HEAD
if [ -n "$BUILD_SCRIPT" ]; then
# Build script lives in the forker-branch tree (the machinery), run it with
# cwd = the tag's tree so its artifacts land where we expect.
[ -f "$REPO_ROOT/$BUILD_SCRIPT" ] || { echo "!! build script not found: $REPO_ROOT/$BUILD_SCRIPT" >&2; exit 1; }
bash "$REPO_ROOT/$BUILD_SCRIPT"
else
eval "$BUILD_CMD"
fi
# collect artifacts (globs are relative to the tag's tree = cwd)
if [ -n "$ARTIFACTS" ]; then
for g in $ARTIFACTS; do
for f in $g; do
[ -f "$f" ] && ASSETS+=("$f")
done
done
fi
fi
# --- 2) mirror upstream releases (metadata + assets) ------------------------
# $WORK from mktemp -d is already absolute, so the globbed dir below resolves
# correctly even though the cwd is now $WORK itself.
UPSTREAM_ASSET_DIR="$WORK/upstream_assets"
mkdir -p "$UPSTREAM_ASSET_DIR"
# UPSTREAM_TOKEN is optional: public upstreams need no auth (get_release /
# download_asset skip the header when the token is empty).
MIRROR_FOUND=false
if [ "$MIRROR_UPSTREAM_RELEASES" = "true" ] && [ -n "$UPSTREAM_URL" ]; then
echo ">> Mirroring upstream releases for tag $TAG"
# get_release returns '{}' (rc 0) when the upstream has no release for the
# tag (HTTP 404); it fails loudly (rc 1) on a hard error, aborting the run.
rel="$(get_release "$UPSTREAM_URL" "$UPSTREAM_TOKEN" "$TAG")"
# pull the body/name from upstream if present
BODY="$(echo "$rel" | python3 -c 'import sys,json;print(json.load(sys.stdin).get("body",""))' 2>/dev/null)"
NAME="$(echo "$rel" | python3 -c 'import sys,json;print(json.load(sys.stdin).get("name",""))' 2>/dev/null)"
[ -n "$NAME" ] && MIRROR_FOUND=true
[ -n "$BODY" ] && MIRROR_FOUND=true
# download upstream assets (avoid the subshell-loses-ASSETS trap by writing to
# disk). Use the asset's NAME, not basename(url): a GitHub download_url ends
# in the numeric asset id (e.g. .../assets/626817787), not the file name.
echo "$rel" | python3 -c 'import sys,json
for a in json.load(sys.stdin).get("assets",[]):
if a.get("url"):
print((a.get("name") or "asset") + "\t" + a["url"])
' | while IFS=$'\t' read -r fn u; do
[ -n "$fn" ] && [ -n "$u" ] || continue
echo " asset: $fn"
download_asset "$UPSTREAM_URL" "$UPSTREAM_TOKEN" "$u" "$UPSTREAM_ASSET_DIR/$fn"
done
for f in "$UPSTREAM_ASSET_DIR"/*; do
[ -f "$f" ] && ASSETS+=("$f")
done
[ "${#ASSETS[@]}" -gt 0 ] && MIRROR_FOUND=true
fi
# --- 3) publish on this Gitea ----------------------------------------------
# Only publish when there is actual content: the local build produced assets,
# or the upstream release exists (name/body/assets). This avoids publishing an
# empty "Release $TAG" when the upstream has no release for the tag (and no
# build produced assets) — the idempotency guard would otherwise skip the tag
# forever, so nothing would ever be retried.
HAS_CONTENT=false
[ "${#ASSETS[@]}" -gt 0 ] && HAS_CONTENT=true
[ "$MIRROR_FOUND" = "true" ] && HAS_CONTENT=true
if [ "$HAS_CONTENT" != "true" ]; then
echo ">> No content for $TAG (no build assets, no upstream release) — not publishing."
exit 0
fi
NAME="${NAME:-Release $TAG}"
BODY="${BODY:-Auto-released by Repo Forker}"
echo ">> Publishing release $TAG on $GITEA_SERVER_URL/$GITEA_OWNER/$GITEA_REPO"
# shellcheck disable=SC2068 # assets are individual file paths (safe)
publish_local_release "$GITEA_SERVER_URL" "$GITEA_OWNER/$GITEA_REPO" "$GITEA_TOKEN" \
"$TAG" "$NAME" "$BODY" ${ASSETS[@]+"${ASSETS[@]}"}
echo ">> Release $TAG published."
-60
View File
@@ -1,60 +0,0 @@
#!/usr/bin/env bash
# runner-register.sh — register a gitea-act-runner for this repo (or shared).
#
# In this Gitea build, runners are repo-scoped. Two options:
# 1. Per-repo: register a runner for THIS repo only.
# 2. Shared: register ONE runner that serves ALL repos (recommended).
#
# Requires: gitea-act-runner installed, GITEA_SERVER_URL, GITEA_TOKEN (admin or
# repo-scoped token), GITEA_OWNER, GITEA_REPO.
#
# Usage:
# GITEA_SERVER_URL=https://git.lago.dev GITEA_TOKEN=... GITEA_OWNER=Lago \
# GITEA_REPO=some-upstream bash forker/runner-register.sh [shared]
set -euo pipefail
GITEA_SERVER_URL="${GITEA_SERVER_URL:?GITEA_SERVER_URL is required}"
GITEA_TOKEN="${GITEA_TOKEN:?GITEA_TOKEN is required}"
GITEA_OWNER="${GITEA_OWNER:?GITEA_OWNER is required}"
GITEA_REPO="${GITEA_REPO:?GITEA_REPO is required}"
SHARED="${1:-}"
command -v gitea-act-runner >/dev/null 2>&1 || {
echo "gitea-act-runner not found. Install it first (see README 'Runner')." >&2
exit 1
}
# Generate a registration token via the Gitea API.
REG_TOKEN="$(curl -sS -X POST \
-H "Authorization: Bearer $GITEA_TOKEN" \
"$GITEA_SERVER_URL/api/v1/admin/actions/runners/registration-token" \
| python3 -c 'import sys,json;print(json.load(sys.stdin).get("token",""))' 2>/dev/null)"
if [ -z "$REG_TOKEN" ]; then
echo "WARN: could not auto-generate a registration token." >&2
echo " Create one manually in the Gitea UI (Settings -> Actions -> Runners" >&2
echo " -> 'Generate runner token') and set RUNNER_REG_TOKEN." >&2
REG_TOKEN="${RUNNER_REG_TOKEN:?RUNNER_REG_TOKEN is required}"
fi
if [ "$SHARED" = "shared" ]; then
echo ">> Registering a SHARED runner (serves all repos)"
gitea-act-runner register \
--server "$GITEA_SERVER_URL" \
--token "$REG_TOKEN" \
--name "shared-runner-$(date +%s)" \
--labels "linux,amd64,ubuntu-latest" \
--shared
else
echo ">> Registering a runner for $GITEA_OWNER/$GITEA_REPO"
gitea-act-runner register \
--server "$GITEA_SERVER_URL" \
--token "$REG_TOKEN" \
--owner "$GITEA_OWNER" \
--repo "$GITEA_REPO" \
--name "runner-$GITEA_REPO" \
--labels "linux,amd64,ubuntu-latest"
fi
echo ">> Registered. Now start the runner: gitea-act-runner run"
+423
View File
@@ -0,0 +1,423 @@
"""The worker process: boot, scheduler, serialized sync queue, graceful stop.
Everything the pipeline model spread across YAML lives here:
* **boot / self-register** — the container knows ``REMOTE`` + ``TOKEN`` and
nothing else; on first boot it resolves its owner, verifies the ``forker``
machinery branch is present on the template, and reports the result in the
UI's status panel instead of requiring a runner registration dance.
* **scheduler** — a tick every ``INTERVAL`` seconds (per-mirror override:
``sync_interval``) replaces the ``*/10 * * * *`` cron. It is in-container, so
no runner, no queue, and no per-job container with flapping DNS.
* **the sync queue** — one worker thread (``PARALLELISM`` slots) so two passes
never push the same repo at once. The pipeline needed ``concurrency:`` on the
workflow to get this; here it is a lock.
* **SIGTERM** finishes the pass in flight and exits — a mirror is never left
half-pushed by a ``docker stop``.
"""
from __future__ import annotations
import os
import queue
import sys
import threading
import time
import traceback
from typing import Any
from .config import Settings, merge_config
from .engine import SyncWorker, default_config_text, read_remote_config
from .gitea import Gitea, GiteaError
from .gitops import MACHINERY_BRANCH
from .pacer import plan as pace_plan
from .registry import Registry
from .state import LogStore, StateStore
class Worker:
def __init__(self, settings: Settings):
self.s = settings
os.makedirs(settings.data_dir, exist_ok=True)
os.makedirs(settings.mirrors_dir, exist_ok=True)
os.makedirs(settings.logs_dir, exist_ok=True)
self.gitea = Gitea(settings.remote, settings.token)
self.state = StateStore(settings.state_file)
self.logs = LogStore(settings.logs_dir)
self.registry = Registry(settings, self.gitea, self.state, self.logs)
self.boot: dict[str, Any] = {
"started_at": int(time.time()),
"remote": settings.remote,
"owner": "",
"gitea_version": "unknown",
"self_registered": False,
"template": f"{settings.owner}/{settings.template_name}",
"errors": [],
}
self._queue: "queue.Queue[str]" = queue.Queue()
self._queued: dict[str, tuple[int, str]] = {} # name -> (enqueued at, why)
self._qlock = threading.Lock()
self._stop = threading.Event()
self._threads: list[threading.Thread] = []
self._last_tick = 0
# GitHub-budget auto-pace: INTERVAL is a floor, the plan raises it when
# the anonymous-API budget demands it (see forker/pacer.py).
self._pace: dict[str, Any] = {}
self._pace_lock = threading.Lock()
# ---------------------------------------------------------------- boot
def bootstrap(self) -> None:
"""Resolve identity and make sure the machinery branch exists.
Non-fatal on purpose: a Gitea blip at boot must not kill the container
(the scheduler retries every tick); only a bad REMOTE/TOKEN is fatal,
and that is caught in ``Settings.from_env``.
"""
try:
me = self.gitea.whoami()
self.gitea.login = me.get("login") or ""
owner = self.s.owner or (me.get("login") or "")
self.boot["owner"] = owner
self.boot["user"] = me.get("login") or ""
self.boot["is_admin"] = bool(me.get("is_admin"))
self.registry._owner = owner # noqa: SLF001 — resolved identity
except GiteaError as e:
msg = f"cannot reach {self.s.remote} with this token: {e}"
print(f"FATAL: {msg}", flush=True)
raise SystemExit(2) from None
self.boot["gitea_version"] = self.gitea.version()
print(f"repo-forker worker → {self.s.remote} as {self.boot['owner']} "
f"(Gitea {self.boot['gitea_version']}, admin={self.boot['is_admin']})", flush=True)
self._ensure_template()
self.state.set_boot(**{k: v for k, v in self.boot.items() if k != "errors"})
for name in self.registry.records():
self.enqueue(name, why="boot")
def _ensure_template(self) -> None:
"""Create the machinery repo if the operator wants it but it is absent.
With no runner there is nothing to *execute* from a template repo — its
only remaining job is to carry the ``.forker.yaml`` that
``adopt_all``/``create`` seed new mirrors with, so it is optional and we
never fight the operator over it.
"""
if not self.s.owner or not self.s.template_name:
return
full = f"{self.s.owner}/{self.s.template_name}"
self.boot["template"] = full
try:
if self.gitea.has_branch(full, MACHINERY_BRANCH):
print(f" template ok: {full}@{MACHINERY_BRANCH}", flush=True)
self.boot["self_registered"] = True
return
except GiteaError:
pass
try:
self.gitea.create_repo(self.s.owner, self.s.template_name,
description="Repo Forker machinery (mirror configs)",
private=False)
print(f" created {full}", flush=True)
except GiteaError as e:
if e.status not in (409,) and "already exists" not in str(e.message).lower():
self.boot["errors"].append(f"template: {e}")
print(f"WARN: template {full} unavailable: {e}", flush=True)
return
try:
self.gitea.write_file(full, ".forker.yaml", default_config_text(),
"Add Repo Forker mirror config", MACHINERY_BRANCH)
self.boot["self_registered"] = True
print(f" wrote {full}@{MACHINERY_BRANCH}/.forker.yaml", flush=True)
except GiteaError as e:
self.boot["errors"].append(f"template config: {e}")
print(f"WARN: could not write the template config: {e}", flush=True)
# ----------------------------------------------------------------- queue
def enqueue(self, name: str, *, why: str = "manual") -> bool:
rec = self.registry.record(name)
if not rec:
return False
with self._qlock:
if name in self._queued or self.registry.is_running(name):
return False
self._queued[name] = (int(time.time()), why)
self._queue.put(name)
print(f"[{name}] queued ({why})", flush=True)
return True
def enqueue_all(self, *, why: str = "tick") -> int:
interval = self.pace()
n = 0
for name, rec in self.registry.records().items():
cfg = merge_config(rec.get("config") or {})
if not cfg.get("enabled", True):
continue
if not self._due(rec, cfg, interval):
continue
if self.enqueue(name, why=why):
n += 1
return n
def _due(self, rec: dict[str, Any], cfg: dict[str, Any], interval: int | None = None) -> bool:
interval = int(cfg.get("sync_interval") or (interval if interval is not None
else self.s.interval_sec))
if interval <= 0:
return False
# Measured from the END of the last pass, not its start: a cold fetch
# of a big repo takes minutes, and with start-based math the mirror is
# "due" the second it finishes — the scheduler then chains passes back
# to back forever (observed: syncs 19s apart at INTERVAL=60).
last = rec.get("last_at") or rec.get("last_started") or 0
return time.time() - last >= interval
# ------------------------------------------------------------- auto-pace
def pace(self) -> int:
"""Recompute the GitHub-budget plan and return this tick's interval.
``self.s.interval_sec`` keeps the operator's explicit value (the API
and the UI show it as such); the plan only raises the *effective*
value when the anonymous-API budget demands it. Auto never syncs more
than asked, and never un-pauses INTERVAL=0.
"""
p = pace_plan(self.registry.records(), self.s.interval_sec)
with self._pace_lock:
first = not self._pace
prev = self._pace.get("effective_sec")
self._pace = p
if not first and p.get("effective_sec") != prev and p.get("explicit_sec", 0) > 0:
print(f"auto-pace: {p['reason']}", flush=True)
return int(p["effective_sec"])
def pace_plan(self) -> dict[str, Any]:
with self._pace_lock:
return dict(self._pace)
def queue_depth(self) -> int:
with self._qlock:
return len(self._queued)
def queued_names(self) -> set[str]:
with self._qlock:
return set(self._queued)
def queued_since(self, name: str) -> int | None:
with self._qlock:
entry = self._queued.get(name)
return entry[0] if entry else None
def queued_reason(self, name: str) -> str | None:
with self._qlock:
entry = self._queued.get(name)
return entry[1] if entry else None
# ------------------------------------------------------------- execution
def run_sync(self, name: str, *, reason: str = "worker") -> dict[str, Any]:
"""One mirror pass, with its own log file and a state update.
``reason`` is why the pass ran (``manual``/``tick``/``boot``/…): it is
recorded on the pass so the UI can label it with the same word the queue
used, instead of inventing a second vocabulary.
"""
rec = self.registry.record(name)
if not rec:
raise KeyError(name)
full = rec.get("full") or self.registry.full_name(name)
path, write, close = self.logs.new_run(name)
log_file = os.path.basename(path)
started = time.time()
self.registry.mark_running(name, True, reason)
def remember(mutate_rec: dict[str, Any]) -> None:
# Reason per run FILE, not just on `last`: /runs lists older passes
# too, and their event must not silently degrade to "worker".
reasons = dict(mutate_rec.get("run_reasons") or {})
reasons[log_file] = reason
mutate_rec["run_reasons"] = dict(list(reasons.items())[-40:])
self.registry.touch(name, {"last_started": int(started), "last_reason": reason},
mutate=remember)
worker = SyncWorker(self.s, self.gitea, log=write)
try:
# Config is remote state: it may have been edited in the Gitea UI
# since the last pass, so re-read it before honoring it.
remote_cfg: dict[str, Any] = {}
try:
remote_cfg = read_remote_config(self.gitea, full) or {}
except GiteaError as e:
write(f"WARN: remote .forker.yaml unreadable ({e}); using the registry copy")
config = {**(rec.get("config") or {}), **remote_cfg}
if remote_cfg:
self.registry.touch(name, {"config": config})
if not self.registry.record(name):
write("mirror was deleted while the sync was queued — skipping")
return {"ok": False, "skipped": "deleted"}
rep = worker.sync(
name=name, full=full,
upstream=rec.get("upstream", ""),
upstream_token=rec.get("upstream_token", ""),
config=config,
)
return self._record(name, rep, started, log_file=log_file, reason=reason)
except Exception as e: # noqa: BLE001 — a crash must still land in state
write(f"ERROR: {e}")
traceback.print_exc(file=sys.stdout)
for line in traceback.format_exc().splitlines()[-12:]:
write(f" {line}")
write("=== sync failed")
self.registry.touch(name, {
"last_at": int(time.time()),
"last": {"ok": False, "error": str(e)[:300], "file": log_file,
"durationSec": int(time.time() - started)},
})
self._spark(name, False)
return {"ok": False, "error": str(e)}
finally:
self.registry.mark_running(name, False)
close()
def _record(self, name: str, rep, started: float, *, log_file: str = "",
reason: str = "worker") -> dict[str, Any]:
data = rep.to_dict()
data["at"] = int(time.time())
data["file"] = log_file
data["reason"] = reason
self.registry.touch(name, {"last_at": int(time.time()), "last": data,
"last_reason": reason})
self._spark(name, rep.ok)
try:
self.registry.refresh(name, force=True)
except Exception: # noqa: BLE001 — parity counts are cosmetic
pass
return data
def _spark(self, name: str, ok: bool) -> None:
def mutate(rec: dict[str, Any]) -> None:
spark = list(rec.get("spark") or [])
spark.append("success" if ok else "failure")
rec["spark"] = spark[-20:]
self.registry.touch(name, {}, mutate=mutate)
# --------------------------------------------------------------- threads
def _sync_worker_thread(self, idx: int) -> None:
while not self._stop.is_set():
try:
name = self._queue.get(timeout=1.0)
except queue.Empty:
continue
with self._qlock:
entry = self._queued.pop(name, None)
reason = entry[1] if entry else "worker"
try:
self.run_sync(name, reason=reason)
except Exception as e: # noqa: BLE001
print(f"[{name}] sync crashed: {e}", flush=True)
finally:
self._queue.task_done()
def _scheduler_thread(self) -> None:
# A 15s heartbeat decides *when work is taken*, not how often a mirror
# syncs: each mirror's own interval (INTERVAL, or sync_interval per
# mirror) gates the enqueue. The heartbeat stays short so a mirror whose
# interval just elapsed starts within seconds instead of waiting on a
# coarse tick; `last_tick` reports the heartbeat, so the UI never shows
# a stale clock at INTERVAL=3600.
while not self._stop.wait(15):
self._last_tick = int(time.time())
try:
n = self.enqueue_all(why="tick")
if n:
print(f"scheduler: {n} mirror(s) due", flush=True)
except Exception as e: # noqa: BLE001 — the scheduler must survive
print(f"scheduler error: {e}", flush=True)
def start(self) -> None:
self.bootstrap()
eff = self.pace() # prime the plan so the UI has it from second one
for i in range(self.s.parallelism):
t = threading.Thread(target=self._sync_worker_thread, args=(i,),
name=f"sync-{i}", daemon=True)
t.start()
self._threads.append(t)
t = threading.Thread(target=self._scheduler_thread, name="scheduler", daemon=True)
t.start()
self._threads.append(t)
extra = "" if eff == self.s.interval_sec else f" (auto-pace: {eff}s)"
print(f"worker ready: {len(self.registry.records())} mirror(s), "
f"interval={self.s.interval_sec}s{extra}, parallelism={self.s.parallelism}", flush=True)
def graceful_stop(self, grace: int = 30) -> None:
"""Stop taking work, and let a push already in flight land.
A mirror half-pushed is worse than a mirror a few minutes stale, so
``docker stop`` waits for the running pass instead of killing it (up to
``grace`` seconds; Docker's own default is 10s, so compose sets a longer
stop_grace_period).
"""
if self._stop.is_set():
return
self._stop.set()
running = [n for n in self.registry.records() if self.registry.is_running(n)]
if not running:
print("stopped (nothing in flight)", flush=True)
return
print(f"stopping: waiting up to {grace}s for {', '.join(running)}", flush=True)
deadline = time.time() + grace
while time.time() < deadline:
if not any(self.registry.is_running(n) for n in self.registry.records()):
break
time.sleep(1)
print("stopped", flush=True)
# ---------------------------------------------------------------- status
def status(self, *, pace: bool = False) -> dict[str, Any]:
now = time.time()
recs = self.registry.records()
running = [n for n in recs if self.registry.is_running(n)]
with self._pace_lock:
p = dict(self._pace)
# Healthy uses the EFFECTIVE interval: when auto-pace widens it, a
# mirror on the widened schedule is still healthy, not "stale".
eff = int(p.get("effective_sec") or self.s.interval_sec or 0)
horizon = max(3 * eff, 900)
healthy = sum(
1 for r in recs.values()
if (r.get("last") or {}).get("ok")
and eff > 0 and now - (r.get("last_at") or 0) < horizon
)
if pace:
p = pace_plan(recs, self.s.interval_sec)
return {
"ok": True,
"boot": {
**self.boot,
"uptime_sec": int(now - self.boot["started_at"]),
},
"scheduler": {
"interval_sec": self.s.interval_sec,
"effective_interval_sec": int(p.get("effective_sec") or eff),
"auto_pace": p or None,
"parallelism": self.s.parallelism,
"last_tick": self._last_tick,
"queued": self.queue_depth(),
"running": running,
},
"settings": {
"remote": self.s.remote,
"owner": self.boot.get("owner", ""),
"template": self.boot.get("template", ""),
"data_dir": self.s.data_dir,
"token_is_admin": bool(self.boot.get("is_admin")),
},
"totals": {
"mirrors": len(recs),
"healthy": healthy,
"assets": sum((r.get("counts") or {}).get("assets") or 0 for r in recs.values()),
"releases": sum((r.get("counts") or {}).get("releases") or 0 for r in recs.values()),
},
}
__all__ = ["Worker", "MACHINERY_BRANCH"]
+267
View File
@@ -0,0 +1,267 @@
"""Persistent state (``/data/state.json``) and per-run log files.
The container is deliberately stateful: the bare mirrors, the mirror registry
and the run history all live under ``DATA_DIR`` (mount a volume there). This is
what replaced Gitea's ``actions/cache`` — the runner wiped its workspace every
run and had to re-read the fork's state from the API; here the previous sync is
simply still on disk.
Writes are atomic (tmp + ``os.replace``) and serialized under a lock: the
scheduler thread and the HTTP thread both touch the same file, and a torn
``state.json`` would forget the whole registry.
"""
from __future__ import annotations
import json
import os
import shutil
import threading
import time
from typing import Any, Callable
MAX_LOG_FILES = 30 # per mirror
class StateStore:
def __init__(self, path: str):
self.path = path
self._lock = threading.RLock()
self._data: dict[str, Any] = {"mirrors": {}, "boot": {}}
self.load()
# ---------------------------------------------------------------- io
def load(self) -> None:
os.makedirs(os.path.dirname(self.path) or ".", exist_ok=True)
try:
with open(self.path, "r", encoding="utf-8") as fh:
raw = json.load(fh)
if isinstance(raw, dict):
raw.setdefault("mirrors", {})
raw.setdefault("boot", {})
self._data = raw
except FileNotFoundError:
pass
except (json.JSONDecodeError, OSError) as e:
# Never clobber a file we failed to read: keep it for forensics and
# start empty, loudly.
backup = f"{self.path}.corrupt-{int(time.time())}"
try:
os.replace(self.path, backup)
print(f"WARN: state.json unreadable ({e}); moved to {backup}, starting empty", flush=True)
except OSError:
print(f"WARN: state.json unreadable ({e}); starting empty", flush=True)
def save(self) -> None:
with self._lock:
tmp = f"{self.path}.tmp"
payload = json.dumps(self._data, indent=1, sort_keys=True)
with open(tmp, "w", encoding="utf-8") as fh:
fh.write(payload)
os.replace(tmp, self.path)
try:
os.chmod(self.path, 0o600) # may hold upstream tokens
except OSError:
pass
# ------------------------------------------------------------- mirrors
def mirrors(self) -> dict[str, Any]:
with self._lock:
return dict(self._data["mirrors"])
def mirror(self, name: str) -> dict[str, Any] | None:
with self._lock:
return self._data["mirrors"].get(name)
def update(self, name: str, patch: dict[str, Any], mutate: Callable[[dict], None] | None = None) -> dict[str, Any]:
with self._lock:
rec = self._data["mirrors"].setdefault(name, {})
rec.update(patch)
if mutate:
mutate(rec)
self.save()
return dict(rec)
def put(self, name: str, record: dict[str, Any]) -> None:
with self._lock:
self._data["mirrors"][name] = record
self.save()
def remove(self, name: str) -> None:
with self._lock:
self._data["mirrors"].pop(name, None)
self.save()
def set_boot(self, **kw: Any) -> None:
with self._lock:
self._data["boot"].update(kw)
self.save()
def boot(self) -> dict[str, Any]:
with self._lock:
return dict(self._data.get("boot", {}))
class LogStore:
"""Per-mirror run logs: ``<dir>/<mirror>/<ts>-<pid>.log`` + ``latest.log``.
The UI's log viewer tails these files. ``latest.log`` is rewritten (not
symlinked) so a bind-mounted volume on any host filesystem behaves the same.
"""
def __init__(self, root: str):
self.root = root
os.makedirs(root, exist_ok=True)
# mirror -> the log file of its in-flight pass. `latest.log` is only
# written when a pass closes, so without this the UI's "pass in flight"
# panel tails the PREVIOUS run and shows a finished log while a sync is
# running (seen live: "latest · success · sync finished" under
# "Sync in flight").
self._current: dict[str, str] = {}
self._clock = threading.Lock()
def current_file(self, mirror: str) -> str | None:
with self._clock:
return self._current.get(mirror)
def dir_for(self, mirror: str) -> str:
path = os.path.join(self.root, mirror.replace("/", "_"))
os.makedirs(path, exist_ok=True)
return path
def _dir(self, mirror: str) -> str:
return self.dir_for(mirror)
def new_run(self, mirror: str) -> tuple[str, Callable[[str], None], Callable[[], None]]:
"""Returns (path, write_line, close). Lines land on disk as they are
produced so the UI can tail a sync that is still running."""
path = os.path.join(self._dir(mirror), f"{time.strftime('%Y%m%d-%H%M%S')}-{os.getpid()}.log")
fh = open(path, "w", encoding="utf-8", errors="replace") # noqa: SIM115 (closed by close())
with self._clock:
self._current[mirror] = path
def write(line: str) -> None:
try:
fh.write(f"{time.strftime('%H:%M:%S')} {line}\n")
fh.flush()
except (OSError, ValueError):
pass
def close() -> None:
try:
fh.close()
except OSError:
pass
# Copy (not move) into latest.log: the timestamped file is the run
# history the detail page lists, latest.log is what the log viewer
# tails. Losing the history would make a mirror look never-run.
try:
shutil.copyfile(path, os.path.join(self._dir(mirror), "latest.log"))
except OSError:
pass
with self._clock:
if self._current.get(mirror) == path:
self._current.pop(mirror, None)
self._rotate(mirror)
return path, write, close
def _rotate(self, mirror: str) -> None:
d = self._dir(mirror)
try:
files = sorted(
(f for f in os.listdir(d) if f != "latest.log" and f.endswith(".log")),
key=lambda f: os.path.getmtime(os.path.join(d, f)),
reverse=True,
)
for stale in files[MAX_LOG_FILES:]:
os.remove(os.path.join(d, stale))
except OSError:
pass
def read(self, mirror: str, *, tail: int | None = None,
run: str | None = None) -> str:
"""Return a run's log (``latest.log`` unless ``run`` names a file).
``run`` is validated to a bare ``*.log`` name inside the mirror's own
directory: it comes from the client, so a path like ``../../etc/passwd``
must not reach open().
"""
d = self._dir(mirror)
name = "latest.log"
if run:
name = os.path.basename(run)
if not name.endswith(".log"):
raise ValueError("run must be a .log file name")
path = os.path.join(d, name)
if not os.path.isfile(path):
return ""
try:
with open(path, "r", encoding="utf-8", errors="replace") as fh:
text = fh.read()
except OSError as e:
return f"<unreadable: {e}>"
lines = text.splitlines()
if tail:
lines = lines[-tail:]
return "\n".join(lines)
def history(self, mirror: str, limit: int = 20) -> list[dict[str, Any]]:
"""Run history, newest first — timestamped files only.
``latest.log`` is a copy of the newest run for the log viewer, not a
run of its own: listing it duplicated every latest pass (two rows, same
content, colliding React keys). A run's identity is its file name, which
is unique per second *and* pid — a mtime in seconds was not.
"""
d = self._dir(mirror)
out: list[dict[str, Any]] = []
try:
names = sorted(
(f for f in os.listdir(d) if f.endswith(".log") and f != "latest.log"),
key=lambda f: os.path.getmtime(os.path.join(d, f)),
reverse=True,
)
except OSError:
return out
for name in names[:limit]:
full = os.path.join(d, name)
try:
st = os.stat(full)
with open(full, "r", encoding="utf-8", errors="replace") as fh:
text = fh.read()
except OSError:
continue
first = text.split("\n", 1)[0] if text else ""
out.append({
"file": name,
"at": int(st.st_mtime),
"size": st.st_size,
"headline": first.replace(">> ", "").strip()[:160],
"failed": "ERROR" in text or "Traceback" in text,
})
return out
def worker_tail(self, tail: int = 400) -> str:
"""The worker's own stdout/stderr, captured by the entrypoint.
The runner page used to show Gitea job logs; now the interesting
process is this container, so the scheduler/queue chatter is read from
the log file the entrypoint tees stdout into.
"""
path = os.environ.get("WORKER_LOG") or os.path.join(self.root, "worker.log")
if not os.path.isfile(path):
return ""
try:
with open(path, "r", encoding="utf-8", errors="replace") as fh:
lines = fh.readlines()
except OSError as e:
return f"<unreadable: {e}>"
return "".join(lines[-max(1, tail):])
def _looks_running(text: str) -> bool:
# Heuristic for the log panel: no completion marker means a run may still
# be appending. The UI only uses it to decide whether to auto-refresh.
return "=== sync finished" not in text and "=== sync failed" not in text
-341
View File
@@ -1,341 +0,0 @@
#!/usr/bin/env bash
# sync.sh — mirror the upstream into this fork (the "worker" job).
#
# Brings in ALL branches, ALL tags, and full commit history from the upstream,
# then pushes them as refs on this Gitea fork. Upstream objects live in a true
# bare mirror (.mirror/); the working tree (forker branch) is never touched.
#
# Design notes:
# * .mirror is a TRUE bare mirror: upstream branches live in refs/heads/*,
# upstream tags in refs/tags/*. If a previous run's .mirror is restored from
# cache (see .gitea/workflows/sync.yml), the fetch is INCREMENTAL; otherwise
# it downloads the full history (still correct).
# * The fork's current state (which branches/tags it already has) is read via
# the Gitea API, not from git state — so prune + "new tag" detection work even
# on a cold mirror, and never touch "forker".
# * Releases are triggered INLINE (a tag-push cannot trigger a workflow, because
# a mirrored tag points at an upstream commit whose tree has no .gitea/workflows).
#
# Inputs (from Gitea Actions Variables/Secrets):
# UPSTREAM_URL, UPSTREAM_TOKEN, GITEA_TOKEN, GITEA_SERVER_URL, GITEA_OWNER,
# GITEA_REPO
#
# Config (from .forker.yaml via load_config):
# TOKEN_USER, MIRROR_TAGS, MIRROR_PRUNE, MIRROR_BRANCHES, ON_NEW_TAG,
# MIRROR_UPSTREAM_RELEASES, BUILD_CMD, BUILD_SCRIPT
set -euo pipefail
cd "$(dirname "$0")/.."
source forker/lib/config.sh
source forker/lib/provider.sh
load_config
UPSTREAM_URL="${UPSTREAM_URL:?UPSTREAM_URL is required}"
UPSTREAM_TOKEN="${UPSTREAM_TOKEN:-}"
GITEA_TOKEN="${GITEA_TOKEN:?GITEA_TOKEN is required}"
GITEA_SERVER_URL="${GITEA_SERVER_URL:?GITEA_SERVER_URL is required}"
GITEA_OWNER="${GITEA_OWNER:?GITEA_OWNER is required}"
GITEA_REPO="${GITEA_REPO:?GITEA_REPO is required}"
MIRROR_DIR=".mirror"
mkdir -p "$MIRROR_DIR"
# --- auth: Bearer per-URL (works on Gitea / GitHub / Codeberg) --------------
# We authenticate git over HTTPS with an `Authorization: Bearer <token>`
# header, scoped to a URL via git config's http.<url>.extraHeader. This is the
# most robust cross-provider option:
# * no username needed -> Gitea's "username must match the token owner"
# rule can't bite us (it would, e.g. on cron where actor=gitea-actions, or
# for a private upstream on the same instance with an OAuth2 token).
# * Bearer is accepted by Gitea, Codeberg and GitHub for git-over-HTTPS.
# * scoping to the exact repo URL means a same-host upstream and fork each
# get their own token (no header collision).
# The token never appears in a URL, so it doesn't leak into `git` output/logs.
# Fail fast instead of hanging on an interactive credential prompt.
export GIT_TERMINAL_PROMPT=0
# --- upstream is ANONYMOUS by default (never touch stored credentials) ------
# Public upstreams must be fetched without authenticating. Without this, a
# `credential.helper=store` + a stored github.com entry would SILENTLY
# authenticate the fetch with the operator's GitHub account. We cut the
# global/system git config and the credential helper for ALL upstream git
# calls (env-scoped, does not affect the fork push below, which uses its own
# explicit Bearer header). Private upstreams opt in via UPSTREAM_TOKEN.
export GIT_CONFIG_GLOBAL=/dev/null
export GIT_CONFIG_NOSYSTEM=1
export GIT_CONFIG_SYSTEM=/dev/null
# --- ensure the bare mirror exists -------------------------------------------
if [ ! -f "$MIRROR_DIR/HEAD" ]; then
echo ">> Initializing bare mirror for $UPSTREAM_URL"
git init --bare "$MIRROR_DIR" >/dev/null
fi
# --- fetch everything from upstream (true-mirror layout) --------------------
# Bearer auth scoped to the upstream URL (works even when the upstream is a
# private repo on the same Gitea instance as the fork).
# Only add the Bearer header when a token is actually set (an empty Bearer
# header makes GitHub reject the request; public repos need no auth at all).
if [ -n "$UPSTREAM_TOKEN" ]; then
git --git-dir="$MIRROR_DIR" config http."$UPSTREAM_URL".extraHeader "Authorization: Bearer $UPSTREAM_TOKEN"
else
git --git-dir="$MIRROR_DIR" config --unset http."$UPSTREAM_URL".extraHeader 2>/dev/null || true
fi
# With a cached .mirror this is incremental; cold it pulls full history.
PRUNE_FLAG=""
[ "$MIRROR_PRUNE" = "true" ] && PRUNE_FLAG="--prune"
# Retry budget shared by the upstream fetch and the fork push (overridable).
# Defined here (before the fetch) so both fetch_once and push_once can use it.
PUSH_RETRIES="${PUSH_RETRIES:-3}"
# fetch_once — the per-job container intermittently can't resolve the upstream
# host (same per-job DNS flap that hits the fork push), so retry transient
# network errors with backoff, mirroring push_once. An incremental fetch of an
# up-to-date mirror is cheap; a failed fetch must fail the run loudly (a
# stale mirror pushed as "success" is the exact thing we never want).
fetch_once() {
local out rc
for (( fa = 1; fa <= PUSH_RETRIES; fa++ )); do
rc=0
out="$(git --git-dir="$MIRROR_DIR" fetch --force $PRUNE_FLAG \
"$UPSTREAM_URL" \
'+refs/heads/*:refs/heads/*' \
'+refs/tags/*:refs/tags/*' 2>&1)" || rc=$?
[ "$rc" -eq 0 ] && return 0
case "$out" in
*"Could not resolve host"*|*"Failed to connect"*|*"Connection timed out"*|\
*"RPC failed"*|*"early EOF"*|*"remote end hung up"*)
echo " fetch retry $fa/$PUSH_RETRIES (transient network: ${out##* })"
sleep $(( fa * 5 )) ;;
*)
echo " fetch failed (non-network, not retrying):" >&2
printf '%s\n' "$out" | tail -10 >&2
return "$rc" ;;
esac
done
echo " giving up after $PUSH_RETRIES fetch attempts; last error:" >&2
printf '%s\n' "$out" | tail -10 >&2
return 1
}
echo ">> Fetching all branches + tags from upstream ($UPSTREAM_URL)"
fetch_once
# upstream branches (true-mirror layout: refs/heads/*)
all_upstream_branches="$(git --git-dir="$MIRROR_DIR" for-each-ref --format='%(refname:short)' refs/heads/ || true)"
# Branches to PUSH, restricted by MIRROR_BRANCHES if configured. Pruning below
# must be checked against the FULL upstream list (not the filtered one), so a
# fork branch that still exists upstream but is outside the filter is never
# deleted.
mirror_branches="$all_upstream_branches"
if [ "$MIRROR_BRANCHES" != "*" ]; then
# split on commas (also tolerate stray spaces)
IFS=', ' read -ra want <<< "$MIRROR_BRANCHES"
filtered=""
for b in "${want[@]}"; do
b="$(echo "$b" | sed -E 's/^[[:space:]]+//; s/[[:space:]]+$//')"
[ -n "$b" ] || continue
printf '%s\n' "$all_upstream_branches" | grep -qxF "$b" && filtered="$filtered $b"
done
mirror_branches="$filtered"
fi
# --- current state of the fork (via Gitea API) ------------------------------
# All pages, so repos with >100 branches/tags are handled correctly.
fork_names() {
local endpoint="$1" page=1 items
while :; do
items="$(curl -sS --max-time 60 -H "Authorization: Bearer $GITEA_TOKEN" \
"$GITEA_SERVER_URL/api/v1/repos/$GITEA_OWNER/$GITEA_REPO/$endpoint?page=$page&limit=50" 2>/dev/null || true)"
[ -z "$items" ] && break
printf '%s' "$items" | python3 -c 'import sys,json;print(" ".join(x.get("name","") for x in json.load(sys.stdin)))' 2>/dev/null || true
# stop when this page is short (Gitea returns fewer than limit at the end)
printf '%s' "$items" | python3 -c 'import sys,json;sys.exit(0 if len(json.load(sys.stdin))<50 else 1)' && break
page=$((page+1))
[ "$page" -gt 100 ] && break # hard cap
done
}
fork_branches="$(fork_names "branches")"
fork_tags="$(fork_names "tags")"
# register the fork as a push target inside the mirror, with its own Bearer
# token scoped to the fork URL (distinct from the upstream header above, so a
# same-instance upstream + fork each authenticate with the right token).
FORK_URL="$GITEA_SERVER_URL/$GITEA_OWNER/$GITEA_REPO.git"
git --git-dir="$MIRROR_DIR" remote remove fork 2>/dev/null || true
git --git-dir="$MIRROR_DIR" remote add fork "$FORK_URL"
git --git-dir="$MIRROR_DIR" config http."$FORK_URL".extraHeader "Authorization: Bearer $GITEA_TOKEN"
# --- 1) branches -----------------------------------------------------------
# A failed push must fail the run (loudly) — a partial mirror reported as
# success is worse than a red run. `&&` would mask the failure under set -e.
# Momentary network errors (DNS "Could not resolve host", connect timeouts)
# are retried a few times with backoff; a non-network failure aborts at once.
push_once() { # push_once <push-args...>
# set -e safe: a failing command-substitution assignment would otherwise
# abort the script, so catch it with `|| rc=$?` (left of || is exempt).
local out rc
for (( attempt = 1; attempt <= PUSH_RETRIES; attempt++ )); do
rc=0
# --force: this is a MIRROR. Upstream is authoritative, so a fork ref that
# has drifted (e.g. a leftover from an interrupted partial mirror, or an
# upstream rebase/re-tag) must be OVERWRITTEN, not fast-forward-checked —
# a single non-FF ref would otherwise reject the whole multi-ref pack. The
# machinery "forker" branch is excluded from the push loop above, so it is
# never clobbered. (Not --force-with-lease: the fork is not authoritative,
# and its refs are expected to be stale.)
out="$(git --git-dir="$MIRROR_DIR" push --force fork "$@" 2>&1)" || rc=$?
[ "$rc" -eq 0 ] && return 0
case "$out" in
*"Could not resolve host"*|*"Failed to connect"*|*"Connection timed out"*|\
*"RPC failed"*|*"early EOF"*|*"remote end hung up"*)
# also widen the backoff: a big multi-ref pack needs time to settle
echo " retry $attempt/$PUSH_RETRIES (transient network: ${out##* })"
sleep $(( attempt * 5 )) ;;
*)
echo " push failed (attempt $attempt/$PUSH_RETRIES, non-network — not retrying):" >&2
printf '%s\n' "$out" | tail -10 >&2
return "$rc" ;;
esac
done
echo " giving up after $PUSH_RETRIES attempts; last error:" >&2
printf '%s\n' "$out" | tail -10 >&2
return 1
}
pushed_b=""
# Push ALL branches in ONE multi-ref pack (a single connection), not one push
# per branch. The per-branch burst opened ~280 separate TLS connections and the
# remote dropped the ~20th; one pack is far more robust, and a network failure
# retries the whole batch cleanly (a re-push of an already-current ref is
# idempotent: "Everything up-to-date").
branch_refspecs=""
for b in $mirror_branches; do
# never let the upstream's content clobber the machinery branch (if the
# upstream ever has a branch named "forker")
[ "$b" = "forker" ] && continue
branch_refspecs="$branch_refspecs refs/heads/$b:refs/heads/$b"
done
if [ -n "$branch_refspecs" ]; then
echo " pushing $(printf '%s' "$branch_refspecs" | wc -w) branches (1 pack)"
push_once $branch_refspecs \
|| { echo "ERROR: branch push failed after $PUSH_RETRIES attempts — aborting (partial mirror)." >&2; exit 1; }
for b in $mirror_branches; do [ "$b" = "forker" ] && continue; pushed_b="$pushed_b $b"; done
fi
# prune fork branches that no longer exist upstream (never touch "forker");
# checked against the FULL upstream list (a branch outside the MIRROR_BRANCHES
# filter but still present upstream is NOT deleted). One pack for all prunes.
if [ "$MIRROR_PRUNE" = "true" ]; then
prune_refspecs=""
for f in $fork_branches; do
[ "$f" = "forker" ] && continue
if ! printf '%s\n' "$all_upstream_branches" | grep -qxF "$f"; then
echo " prune branch: $f (deleted upstream)"
prune_refspecs="$prune_refspecs :refs/heads/$f"
fi
done
if [ -n "$prune_refspecs" ]; then
push_once $prune_refspecs \
|| echo "WARN: branch prune failed (will retry next run)"
fi
fi
# --- 2) tags ----------------------------------------------------------------
new_tags=""
pushed_t=""
upstream_tags="$(git --git-dir="$MIRROR_DIR" for-each-ref --format='%(refname:short)' refs/tags/ || true)"
if [ "$MIRROR_TAGS" = "true" ]; then
tag_refspecs=""
for t in $upstream_tags; do
# is this tag NEW relative to the fork? (for inline release triggering)
printf '%s\n' $fork_tags | grep -qxF "$t" || new_tags="$new_tags $t"
tag_refspecs="$tag_refspecs refs/tags/$t:refs/tags/$t"
done
if [ -n "$tag_refspecs" ]; then
echo " pushing $(printf '%s' "$tag_refspecs" | wc -w) tags (1 pack)"
push_once $tag_refspecs \
|| { echo "ERROR: tag push failed after $PUSH_RETRIES attempts — aborting (partial mirror)." >&2; exit 1; }
for t in $upstream_tags; do pushed_t="$pushed_t $t"; done
fi
# prune fork tags that no longer exist upstream (one pack for all prunes)
if [ "$MIRROR_PRUNE" = "true" ]; then
tag_prune_refspecs=""
for t in $fork_tags; do
if ! printf '%s\n' "$upstream_tags" | grep -qxF "$t"; then
echo " prune tag: $t (deleted upstream)"
tag_prune_refspecs="$tag_prune_refspecs :refs/tags/$t"
fi
done
if [ -n "$tag_prune_refspecs" ]; then
push_once $tag_prune_refspecs \
|| echo "WARN: tag prune failed (will retry next run)"
fi
fi
fi
echo ">> Sync complete. Branches:${pushed_b:- (none)} | Tags:${pushed_t:- (none)} | New tags:${new_tags:- (none)}"
# --- 1b) fork default branch = upstream default branch --------------------
# Generated repos are born with default 'forker' (the only branch that exists
# at generate time), and Gitea does NOT switch it once a pre-set branch later
# appears (verified: pre-PATCH is a 200 no-op until re-applied). So we
# self-correct here on every run: read the upstream's default via ls-remote
# --symref (works on GitHub/Gitea/Codeberg; honors the upstream Bearer config,
# anonymous otherwise — golden rule kept), and if the fork's default differs,
# PATCH it — but only to a branch the fork actually has (a MIRROR_BRANCHES
# filter can exclude the upstream default; never point at 'forker').
# Self-healing: if the upstream later changes its default, the fork follows.
upstream_default="$(git --git-dir="$MIRROR_DIR" ls-remote --symref "$UPSTREAM_URL" HEAD 2>/dev/null \
| sed -n 's/^ref: refs\/heads\/\(.*\)[[:space:]]*HEAD$/\1/p' | head -1 \
| sed -E 's/[[:space:]]+$//; s/^[[:space:]]+//')"
if [ -n "$upstream_default" ] && [ "$upstream_default" != "forker" ]; then
# the branch must exist on the fork (just pushed, or already there).
# NOTE: grep -qxF would SIGPIPE the (large) printf under `set -o pipefail`
# once it matches an early line, giving a false negative — so use grep -xF
# (reads ALL input, no early exit) and test the captured output instead.
if [ -n "$(printf '%s\n' $mirror_branches $fork_branches | grep -xF "$upstream_default")" ]; then
fork_default="$(curl -sS --max-time 20 -H "Authorization: Bearer $GITEA_TOKEN" \
"$GITEA_SERVER_URL/api/v1/repos/$GITEA_OWNER/$GITEA_REPO" 2>/dev/null \
| python3 -c 'import sys,json;print(json.load(sys.stdin).get("default_branch",""))' 2>/dev/null || true)"
if [ -n "$fork_default" ] && [ "$fork_default" != "$upstream_default" ]; then
# capture the HTTP status (curl -o exit code is 0 even on 4xx, so we must
# check the code, not just the exit status) and log it for diagnosis.
db_code="$(curl -sS --max-time 20 -o /tmp/db_resp.$$ -w '%{http_code}' \
-X PATCH -H "Authorization: Bearer $GITEA_TOKEN" \
"$GITEA_SERVER_URL/api/v1/repos/$GITEA_OWNER/$GITEA_REPO" \
-H "Content-Type: application/json" \
-d "{\"default_branch\":\"$upstream_default\"}" 2>/dev/null)"
case "$db_code" in
2*) echo " default branch: $fork_default -> $upstream_default (matches upstream)" ;;
*) echo "WARN: set default branch -> $upstream_default returned HTTP $db_code (body: $(head -c 200 /tmp/db_resp.$$ 2>/dev/null))" ;;
esac
rm -f /tmp/db_resp.$$
fi
else
echo " default branch: upstream default '$upstream_default' not mirrored (filtered) — left as-is"
fi
fi
# --- 3) build + publish a release for each tag that LACKS one (inline) -----
# A tag-push CANNOT trigger release.yml (the tag points at an upstream commit
# whose tree has no .gitea/workflows), so we trigger the release here instead.
# We check for *missing* releases (not just new tags), so a release that
# failed on a previous run is retried by the next cron tick (self-healing);
# release.sh's own idempotency guard still prevents duplicates.
RELEASE_EXPECTED=false
[ -n "$BUILD_CMD" ] && RELEASE_EXPECTED=true
[ -n "$BUILD_SCRIPT" ] && RELEASE_EXPECTED=true
[ "$MIRROR_UPSTREAM_RELEASES" = "true" ] && RELEASE_EXPECTED=true
if [ "$ON_NEW_TAG" = "true" ] && [ "$RELEASE_EXPECTED" = "true" ]; then
for t in $upstream_tags; do
if [ "$(release_exists "$GITEA_SERVER_URL" "$GITEA_OWNER/$GITEA_REPO" "$GITEA_TOKEN" "$t")" = "no" ]; then
echo ">> No release for $t — building + publishing"
bash forker/release.sh "$t" || echo "!! release for $t failed (will retry next run)"
fi
done
fi
# --- 4) verify the Releases unit is enabled (fork quirk) -------------------
# Gitea creates forks WITHOUT the Releases unit, so release assets 404 on the
# web download route. check-unit.sh self-heals when the units API exists and
# warns (with the exact UI fix) otherwise. Never fails the sync on its own.
bash forker/check-unit.sh || echo "!! check-unit: see the warning above (sync continues)"
-18
View File
@@ -1,18 +0,0 @@
# Run a gitea-act-runner in Docker. After `gitea-act-runner register`, point
# this at the generated config (or use the official gitea/act-runner image).
#
# docker compose -f runner/docker-compose.yml up -d
#
# The runner must be registered (shared or per-repo) first — see README "Runner".
services:
runner:
image: gitea/act_runner:0.6.1
restart: unless-stopped
volumes:
- ./config:/config
- /var/run/docker.sock:/var/run/docker.sock
environment:
# If you registered with `gitea-act-runner register`, the config is in
# ./config (copied from the registration output). The container reads it.
GITEA_RUNNER_CONFIG: /config/config.yaml
Executable
+379
View File
@@ -0,0 +1,379 @@
#!/usr/bin/env bash
# End-to-end test of the whole container model against a throwaway Gitea.
#
# ./tests/e2e.sh
#
# Real git + real Gitea (Docker), no mocks: creates a mirror, syncs it, prunes
# refs the upstream deleted, mirrors an upstream release with an asset, builds a
# local release from build_cmd, edits the remote config, and deletes the mirror.
set -uo pipefail
here="$(cd "$(dirname "$0")" && pwd)"
root="$(dirname "$here")"
# A directory of its own — NOT the shared .dev-test/: the e2e owns its gitea
# data dir and its compose project, and pointing it at the same folder a dev
# harness uses means it starts from dirty state (old repos, extra refs) or,
# worse, tears down that harness on exit.
work="${E2E_WORK:-$root/.dev-test/e2e}"
port="${E2E_PORT:-8741}"
gitea_port="${E2E_GITEA_PORT:-3099}"
gitea_pass=forker12345
fails=0
ok() { printf ' \033[32mok\033[0m %s\n' "$1"; }
bad() { printf ' \033[31mFAIL\033[0m %s\n' "$1"; fails=$((fails + 1)); }
section() { printf '\n\033[1m%s\033[0m\n' "$1"; }
cleanup() {
section "cleanup"
[ -f "$work/worker.pid" ] && kill "$(cat "$work/worker.pid")" 2>/dev/null
(cd "$work" && docker compose -p rf-e2e down -v >/dev/null 2>&1)
# The Gitea container writes its volume as uid 1000 from inside the image,
# which is rootless Docker's *host* uid — the host user cannot rm that tree.
# A throwaway container owns the deletion, or the next run starts on a dirty
# directory with whatever refs the previous one left behind.
docker run --rm -v "$work:/x" alpine:latest rm -rf /x 2>/dev/null || rm -rf "$work"
ok "torn down"
}
trap cleanup EXIT
check() { # check <label> <expected> <actual>
if [ "$2" = "$3" ]; then ok "$1"; else bad "$1 (expected '$2', got '$3')"; fi
}
contains() { # contains <label> <needle> <haystack>
case "$3" in *"$2"*) ok "$1";; *) bad "$1 (missing '$2' in: $(printf '%s' "$3" | head -c 200))";; esac
}
wait_for() { # wait_for <url> [secs]
local url="$1" limit="${2:-60}" i=0
while [ "$i" -lt "$limit" ]; do
curl -fsS -o /dev/null "$url" 2>/dev/null && return 0
sleep 1; i=$((i + 1))
done
return 1
}
# A directory of its own, wiped before we start: the e2e asserts ref counts and
# release lists, so a leftover repo from an earlier run (or another harness on
# this checkout) turns every one of those checks into noise.
if [ -e "$work" ]; then
docker run --rm -v "$work:/x" alpine:latest rm -rf /x 2>/dev/null || rm -rf "$work" 2>/dev/null
[ -e "$work" ] && { bad "$work still exists — cannot start from a clean state"; exit 1; }
fi
mkdir -p "$work"
# ------------------------------------------------------------ 0. the port is ours
if curl -fsS -o /dev/null --max-time 2 "http://127.0.0.1:$gitea_port/" 2>/dev/null; then
bad "something already answers on :$gitea_port — the e2e would test THAT Gitea, not a clean one (stop it, or E2E_GITEA_PORT=3199 ./tests/e2e.sh)"
exit 1
fi
if curl -fsS -o /dev/null --max-time 2 "http://127.0.0.1:$port/api/health" 2>/dev/null; then
bad "a worker is already running on :$port (stop it, or E2E_PORT=8752 ./tests/e2e.sh)"
exit 1
fi
# ------------------------------------------------------------ 1. throwaway Gitea
# REQUIRE_SIGNIN_VIEW is on deliberately: it is git.lago.dev's setting, it
# forces every read to carry credentials, and it is what caught (once) the
# worker sending "Authorization: Bearer " for an empty token. So the fixture
# pushes/publishes with -u forge:pass and every read below authenticates too.
section "1. Gitea on :$gitea_port (sign-in required)"
cat > "$work/docker-compose.yml" <<EOF
# throwaway, generated by tests/e2e.sh
services:
gitea:
image: docker.gitea.com/gitea:1.22.4
container_name: rf-e2e-gitea
environment:
USER_UID: "1000"
USER_GID: "1000"
GITEA__database__DB_TYPE: sqlite3
GITEA__server__DOMAIN: localhost
GITEA__server__ROOT_URL: http://localhost:$gitea_port/
GITEA__server__HTTP_PORT: "$gitea_port"
GITEA__server__DISABLE_SSH: "true"
GITEA__security__INSTALL_LOCK: "true"
GITEA__service__REQUIRE_SIGNIN_VIEW: "true"
GITEA__repository__DEFAULT_BRANCH: main
GITEA__actions__ENABLED: "false"
ports: ["$gitea_port:$gitea_port"]
volumes: ["./gitea:/data"]
EOF
# Loudly, not >/dev/null: a bind failure here used to be swallowed, the wait
# then passed against whatever else held the port, and every later section
# failed with confusing ref-count diffs.
(cd "$work" && docker compose -p rf-e2e up -d) || { bad "gitea container failed to start"; exit 1; }
# Gitea binds its port before the ORM/indexer init finishes. The signal that
# it is serving is the log line it writes when it starts listening.
#
# What must NOT be used as a readiness probe is an HTTP request: this instance
# requires sign-in, so an anonymous probe is a permanent 403 and the loop would
# spin for its whole budget and then abort a run that was actually fine.
for _ in $(seq 1 120); do
docker logs rf-e2e-gitea 2>&1 | grep -q "Starting new Web server" && break
sleep 1
done
docker logs rf-e2e-gitea 2>&1 | grep -q "Starting new Web server" \
|| { bad "gitea never started listening"; docker logs --tail 15 rf-e2e-gitea 2>&1 | sed 's/^/ /'; exit 1; }
# A real error here used to be swallowed (>/dev/null 2>&1) and surfaced 40
# lines later as "could not mint a token".
docker exec rf-e2e-gitea su git -c "gitea admin user create --username forge --password '$gitea_pass' --email forge@example.com --admin" 2>&1 | tail -2 | sed 's/^/ /'
# 1.22.4 rejects scopes on this route ("all:admin"/"all:write" …); `--raw` is
# the token format, `--scopes all` is what this build accepts.
token="$(docker exec rf-e2e-gitea su git -c "gitea admin user generate-access-token --username forge --token-name e2e --raw --scopes all" 2>/dev/null | tail -1)"
[ -n "$token" ] || { bad "could not mint a token"; exit 1; }
ok "gitea up, admin token minted"
api() { curl -s -H "Authorization: token $token" "http://127.0.0.1:$gitea_port/api/v1$1"; }
# Every read in this script must authenticate: the instance refuses anonymous
# access on purpose, and that refusal is part of what is being tested.
gapi() { curl -s -u "forge:$gitea_pass" "http://127.0.0.1:$gitea_port/api/v1$1"; }
# ---------------------------------------------------------- 2. upstream fixture
section "2. upstream fixture (3 branches, 1 tag, 1 release + asset)"
up="$work/upstream"
rm -rf "$up" && mkdir -p "$up" && cd "$up"
export GIT_CONFIG_GLOBAL="$work/gitconfig" GIT_CONFIG_SYSTEM=/dev/null
printf '[user]\n\tname = Up\n\temail = up@example.com\n' > "$work/gitconfig"
git init -q -b main .
echo hello > README.md && mkdir -p dist && printf 'x=1\n' > app.py
# mkdir is part of the script on purpose: git does not track the empty dist/
# directory above, so the tree `git archive` exports has no dist/ to write into.
printf 'mkdir -p dist
echo "artifact for $FORK_TAG" | tee dist/app.bin
' > build.sh
git add -A && git commit -qm initial && git tag v1.0.0
git checkout -qb develop && echo more >> app.py && git commit -qam develop && git checkout -q main
git checkout -qb feature/x && echo f > f.txt && git add -A && git commit -qm feat && git checkout -q main
U="http://forge:$gitea_pass@127.0.0.1:$gitea_port/forge/upstream-demo.git"
curl -s -u "forge:$gitea_pass" -X POST "http://127.0.0.1:$gitea_port/api/v1/user/repos" \
-H 'Content-Type: application/json' -d '{"name":"upstream-demo","auto_init":false}' >/dev/null
gapi '/repos/forge/upstream-demo' | grep -q '"full_name"' || { bad "fixture: upstream repo missing"; exit 1; }
git -c credential.helper= push -q "$U" --all && git -c credential.helper= push -q "$U" --tags
# Gitea answers "repo is empty" until a ref is actually visible, and the push
# above is processed asynchronously on the server: poll before building on it.
have_refs=""
for _ in $(seq 1 45); do
gapi '/repos/forge/upstream-demo/tags' | grep -q '"v1.0.0"' && { have_refs=1; break; }
sleep 1
done
[ -n "$have_refs" ] || { bad "fixture: the pushed tags never became visible"; exit 1; }
# v1.0.0 exists on the remote by now (pushed above); Gitea 1.22 refuses to
# create a release for a tag it cannot see ("Release is has no Tag"), so the
# order here matters — and the id is asserted, not silently empty.
# "repo is empty" is answered until the push hook flips the flag, which is
# asynchronous even after the tag is already ls-remote-able: retry, do not race.
rel_json=""
for _ in $(seq 1 30); do
rel_json="$(curl -s -u "forge:$gitea_pass" -X POST "http://127.0.0.1:$gitea_port/api/v1/repos/forge/upstream-demo/releases" \
-H 'Content-Type: application/json' -d '{"tag_name":"v1.0.0","name":"Upstream v1.0.0","body":"from upstream"}')"
printf '%s' "$rel_json" | grep -q '"id"' && break
sleep 1
done
rid="$(printf '%s' "$rel_json" | python3 -c 'import sys,json;print(json.load(sys.stdin).get("id",""))' 2>/dev/null)"
[ -n "$rid" ] || { bad "fixture: upstream release not created (${rel_json:0:200})"; exit 1; }
printf 'upstream-asset-payload\n' > "$work/asset.bin"
asset_name="$(curl -s -u "forge:$gitea_pass" -X POST \
"http://127.0.0.1:$gitea_port/api/v1/repos/forge/upstream-demo/releases/$rid/assets" \
-F "attachment=@$work/asset.bin" | python3 -c 'import sys,json;print(json.load(sys.stdin).get("name",""))')"
check "upstream release has its asset" "asset.bin" "$asset_name"
refs="$(git -c credential.helper= ls-remote --heads --tags "$U" | grep -cv '\^{}')"
check "upstream has 4 refs (3 branches + 1 tag)" "4" "$refs"
cd "$root"
# ------------------------------------------------------------- 3. boot worker
section "3. worker boots and self-registers the machinery repo"
rm -rf "$work/data"
REMOTE="http://127.0.0.1:$gitea_port" TOKEN="$token" OWNER=forge \
DATA_DIR="$work/data" INTERVAL=999 PORT="$port" HOST=127.0.0.1 \
UI_DIST="$root/ui/dist" WORKER_LOG="$work/data/logs/worker.log" \
python3 -m forker > "$work/worker.out" 2>&1 &
echo $! > "$work/worker.pid"
wait_for "http://127.0.0.1:$port/api/health" 30 || { bad "worker never answered"; cat "$work/worker.out"; exit 1; }
contains "template repo created" "created forge/repo-forker" "$(cat "$work/worker.out")"
contains "machinery config written" "wrote forge/repo-forker@forker/.forker.yaml" "$(cat "$work/worker.out")"
health="$(curl -s "http://127.0.0.1:$port/api/health")"
contains "health reports gitea version" '"version"' "$health"
# ---------------------------------------------------------- 4. create + 1st sync
section "4. create a mirror through the API, first sync lands"
created="$(curl -s -X POST "http://127.0.0.1:$port/api/mirrors" -H 'Content-Type: application/json' \
-d "{\"upstream\":\"http://127.0.0.1:$gitea_port/forge/upstream-demo.git\",\"name\":\"demo\",\"token\":\"$token\"}")"
contains "create returned the steps" '"create-repo"' "$created"
contains "first sync queued" '"first-sync"' "$created"
synced=""
for _ in $(seq 1 60); do
s="$(curl -s "http://127.0.0.1:$port/api/mirrors/demo" | python3 -c 'import sys,json;d=json.load(sys.stdin);print(d["lastSync"] and d["lastSync"]["status"] or "")' 2>/dev/null)"
[ "$s" = "completed" ] && { synced=1; break; }
sleep 1
done
[ -n "$synced" ] || { bad "first sync did not finish"; curl -s "http://127.0.0.1:$port/api/mirrors/demo/log" | python3 -c 'import sys,json;print("\n".join(l["text"] for l in json.load(sys.stdin)["lines"]))'; exit 1; }
m="$(curl -s "http://127.0.0.1:$port/api/mirrors/demo")"
check "mirror branches mirrored" "3" "$(printf '%s' "$m" | python3 -c 'import sys,json;print(json.load(sys.stdin)["parity"]["branches"])')"
check "mirror tags mirrored" "1" "$(printf '%s' "$m" | python3 -c 'import sys,json;print(json.load(sys.stdin)["parity"]["tags"])')"
check "default branch healed" "main" "$(printf '%s' "$m" | python3 -c 'import sys,json;print(json.load(sys.stdin)["defaultBranch"])')"
check "upstream token stored masked" "True" "$(printf '%s' "$m" | python3 -c 'import sys,json;print(json.load(sys.stdin)["hasToken"])')"
check "token value never serialized" "False" "$(printf '%s' "$m" | python3 -c "import sys,json;print('$token' in json.dumps(json.load(sys.stdin)))")"
branches="$(api '/repos/forge/demo/branches' | python3 -c 'import sys,json;print(",".join(sorted(b["name"] for b in json.load(sys.stdin))))')"
check "gitea shows the mirrored refs" "develop,feature/x,forker,main" "$branches"
# byte-identical objects: the mirror's main must be the very same commit
up_sha="$(git -c credential.helper= ls-remote "$U" refs/heads/main | cut -f1)"
mir_sha="$(api '/repos/forge/demo/branches/main' | python3 -c 'import sys,json;print(json.load(sys.stdin)["commit"]["id"])')"
check "commit hashes are identical to upstream" "$up_sha" "$mir_sha"
log="$(curl -s "http://127.0.0.1:$port/api/mirrors/demo/log" | python3 -c 'import sys,json;print("\n".join(l["text"] for l in json.load(sys.stdin)["lines"]))')"
contains "cold fetch reported" "(cold)" "$log"
contains "one pack for branches" "pushing 3 branches (1 pack)" "$log"
contains "sync finished marker" "=== sync finished" "$log"
# A pass whose counts all read null is the silent-failure mode the detail page
# used to hide (lastCounts was read from a key the summary never wrote).
check "last pass counts are reported" "3" "$(printf '%s' "$m" | python3 -c 'import sys,json;print(json.load(sys.stdin)["lastCounts"]["branches"])')"
check "last pass tags are reported" "1" "$(printf '%s' "$m" | python3 -c 'import sys,json;print(json.load(sys.stdin)["lastCounts"]["tags"])')"
# ------------------------------------------------------------ 5. release mirror
section "5. upstream release mirrored (metadata + asset)"
curl -s -X PUT "http://127.0.0.1:$port/api/mirrors/demo/config" -H 'Content-Type: application/json' \
-d '{"parsed":{"mirror_upstream_releases":true}}' >/dev/null
curl -s -X POST "http://127.0.0.1:$port/api/mirrors/demo/sync" >/dev/null
sleep 8
rels="$(api '/repos/forge/demo/releases' | python3 -c 'import sys,json;[print(r["tag_name"],len(r["assets"])) for r in json.load(sys.stdin)]')"
contains "v1.0.0 release published" "v1.0.0 1" "$rels"
asset_url="$(gapi '/repos/forge/demo/releases/tags/v1.0.0' | python3 -c 'import sys,json;print(json.load(sys.stdin)["assets"][0]["browser_download_url"])')"
code="$(curl -s -o /dev/null -w '%{http_code}' -L -u "forge:$gitea_pass" "$asset_url")"
check "asset downloads over the web route" "200" "$code"
cfg="$(curl -s "http://127.0.0.1:$port/api/mirrors/demo/config")"
contains "config write preserved comments" "Flat " "$cfg"
contains "config edit landed on the forker branch" '"mirror_upstream_releases": true' "$cfg"
# --------------------------------------------------------------- 6. local build
section "6. local build (build_cmd) publishes its artifact"
# a tag whose tree carries build.sh, so the build has something to run
cd "$up" && git checkout -q main && git add -A && git commit -q --allow-empty -m "for v1.1.0" && git tag v1.1.0
git -c credential.helper= push -q "$U" main --tags && cd "$root"
curl -s -X PUT "http://127.0.0.1:$port/api/mirrors/demo/config" -H 'Content-Type: application/json' \
-d '{"parsed":{"build_cmd":"bash build.sh","artifacts":"dist/app.bin","mirror_upstream_releases":false}}' >/dev/null
curl -s -X POST "http://127.0.0.1:$port/api/mirrors/demo/sync" >/dev/null
# Wait for the release to exist — a fixed sleep made this a race: on a busy
# machine the pass had not published yet and the section "failed" for timing.
built=""
for _ in $(seq 1 40); do
sleep 1
rels="$(api '/repos/forge/demo/releases' | python3 -c 'import sys,json;[print(r["tag_name"],len(r["assets"])) for r in json.load(sys.stdin)]' 2>/dev/null)"
case "$rels" in *"v1.1.0 1"*) built=1; break;; esac
done
if [ -z "$built" ]; then
echo " ---- run log (why v1.1.0 did not publish):"
curl -s "http://127.0.0.1:$port/api/mirrors/demo/log" | python3 -c 'import sys,json;print("\n".join(l["text"] for l in json.load(sys.stdin)["lines"]))' | sed 's/^/ /'
echo " ---- config seen by the worker:"
curl -s "http://127.0.0.1:$port/api/mirrors/demo/config" | python3 -c 'import sys,json;print(json.dumps(json.load(sys.stdin)["parsed"], indent=1))' | sed 's/^/ /'
fi
contains "built release published with its artifact" "1" "${built:-0}"
build_log="$(curl -s "http://127.0.0.1:$port/api/mirrors/demo/log")"
case "$build_log" in *'artifact for v1.1.0'*) ok "build output streamed to the log";; *) bad "build output streamed to the log — the pass log never showed the build's stdout"; printf '%s' "$build_log" | python3 -c 'import sys,json;print("\n".join(l["text"] for l in json.load(sys.stdin)["lines"]))' | sed 's/^/ /';; esac
section "6b. a broken build is loud, and does not publish an empty release"
# A NEW tag, or there would be nothing to build and the pass would be green
# for the wrong reason.
cd "$up" && git commit -q --allow-empty -m "for v1.2.0" && git tag v1.2.0
git -c credential.helper= push -q "$U" main --tags && cd "$root"
curl -s -X PUT "http://127.0.0.1:$port/api/mirrors/demo/config" -H 'Content-Type: application/json' \
-d '{"parsed":{"build_cmd":"bash does-not-exist.sh","artifacts":""}}' >/dev/null
curl -s -X POST "http://127.0.0.1:$port/api/mirrors/demo/sync" >/dev/null
sleep 10
fail_log="$(curl -s "http://127.0.0.1:$port/api/mirrors/demo/log")"
contains "the failure names the tag" "v1.2.0" "$fail_log"
contains "the build error is visible" "does-not-exist.sh" "$fail_log"
mm="$(curl -s "http://127.0.0.1:$port/api/mirrors/demo")"
check "the pass is marked failed" "failure" "$(printf '%s' "$mm" | python3 -c 'import sys,json;print(json.load(sys.stdin)["lastSync"]["conclusion"])')"
contains "and says which tag broke" "release(s) failed" "$(printf '%s' "$mm" | python3 -c 'import sys,json;print(json.load(sys.stdin)["lastError"])')"
rel_fails="$(printf '%s' "$mm" | python3 -c 'import sys,json;print("\n".join(json.load(sys.stdin)["releaseFailures"]))')"
contains "every failed tag is listed" "v1.2.0" "$rel_fails"
bad_count="$(api '/repos/forge/demo/releases' | python3 -c 'import sys,json;print(len(json.load(sys.stdin)))')"
check "the broken build added no empty release" "2" "$bad_count"
# Retire the deliberate failures the way the engine does: a tag with a release
# is never retried. Publishing them by hand makes the next pass green for the
# right reason (nothing left to do), which is what the scheduler sections
# below depend on.
for t in $(printf '%s' "$rel_fails" | cut -d: -f1); do
curl -s -u "forge:$gitea_pass" -X POST "http://127.0.0.1:$gitea_port/api/v1/repos/forge/demo/releases" \
-H 'Content-Type: application/json' -d "{\"tag_name\":\"$t\",\"name\":\"$t (published out of band)\",\"body\":\"clears the deliberate failure\"}" >/dev/null
done
curl -s -X POST "http://127.0.0.1:$port/api/mirrors/demo/sync" >/dev/null
for _ in $(seq 1 30); do
sleep 1
c="$(curl -s "http://127.0.0.1:$port/api/mirrors/demo" | python3 -c 'import sys,json;print(json.load(sys.stdin)["lastSync"]["conclusion"])')"
[ "$c" = "success" ] && break
done
check "the pass goes green once the releases exist" "success" "$c"
check "and reports no release failures" "[]" "$(curl -s "http://127.0.0.1:$port/api/mirrors/demo" | python3 -c 'import sys,json;print(json.dumps(json.load(sys.stdin)["releaseFailures"]))')"
# ------------------------------------------------------------------ 7. prune
section "7. refs deleted upstream are pruned on the mirror"
cd "$up" && git -c credential.helper= push -q "$U" --delete refs/heads/feature/x refs/tags/v1.0.0 && cd "$root"
curl -s -X PUT "http://127.0.0.1:$port/api/mirrors/demo/config" -H 'Content-Type: application/json' \
-d '{"parsed":{"build_cmd":"","on_new_tag":false}}' >/dev/null
curl -s -X POST "http://127.0.0.1:$port/api/mirrors/demo/sync" >/dev/null
sleep 8
branches="$(api '/repos/forge/demo/branches' | python3 -c 'import sys,json;print(",".join(sorted(b["name"] for b in json.load(sys.stdin))))')"
check "deleted branch pruned (forker branch kept)" "develop,forker,main" "$branches"
tags="$(api '/repos/forge/demo/tags' | python3 -c 'import sys,json;print(",".join(sorted(t["name"] for t in json.load(sys.stdin))))')"
contains "surviving tags still there" "v1.1.0" "$tags"
case "$tags" in *v1.0.0*) bad "v1.0.0 still present";; *) ok "v1.0.0 pruned";; esac
# ------------------------------------------------------- 8. machinery protection
section "8. the machinery branch survives every pass"
fb="$(api '/repos/forge/demo/contents/.forker.yaml?ref=forker' | python3 -c 'import sys,json;d=json.load(sys.stdin);print(d.get("name",""))')"
check "forker branch config intact" ".forker.yaml" "$fb"
# --------------------------------------------------------------- 9. scheduler
section "9. scheduler picks a due mirror on its own"
curl -s -X POST "http://127.0.0.1:$port/api/settings" -H 'Content-Type: application/json' \
-d '{"interval":30}' >/dev/null
curl -s -X POST "http://127.0.0.1:$port/api/mirrors/demo/config" -H 'Content-Type: application/json' \
-d '{"parsed":{"sync_interval":1}}' >/dev/null
before="$(curl -s "http://127.0.0.1:$port/api/mirrors/demo" | python3 -c 'import sys,json;print(json.load(sys.stdin)["lastSync"]["id"])')"
tick=""
for _ in $(seq 1 40); do
sleep 1
now="$(curl -s "http://127.0.0.1:$port/api/mirrors/demo" | python3 -c 'import sys,json;print(json.load(sys.stdin)["lastSync"]["id"])')"
if [ "$now" != "$before" ]; then tick=1; break; fi
done
[ -n "$tick" ] && ok "scheduled pass ran without any API call" || bad "scheduler never ran the due mirror"
# ---------------------------------------------------------- 10. adopt + delete
section "10. adopt existing mirrors, then delete"
# a hand-made "legacy" mirror: forker branch + UPSTREAM_URL variable, no registry entry
curl -s -u "forge:$gitea_pass" -X POST "http://127.0.0.1:$gitea_port/api/v1/user/repos" \
-H 'Content-Type: application/json' -d '{"name":"legacy","auto_init":false,"description":"Mirror of http://127.0.0.1:'"$gitea_port"'/forge/upstream-demo.git (Repo Forker)"}' >/dev/null
b64="$(printf 'enabled: true\n' | base64 -w0)"
curl -s -X POST -H "Authorization: token $token" -H 'Content-Type: application/json' \
-d "{\"content\":\"$b64\",\"branch\":\"forker\",\"message\":\"seed\"}" \
"http://127.0.0.1:$gitea_port/api/v1/repos/forge/legacy/contents/.forker.yaml" >/dev/null
adopted="$(curl -s -X POST "http://127.0.0.1:$port/api/adopt")"
contains "legacy mirror adopted" '"forge/legacy"' "$adopted"
contains "its upstream was recovered from the description" 'upstream-demo.git' "$adopted"
deleted="$(curl -s -X DELETE "http://127.0.0.1:$port/api/mirrors/demo")"
contains "mirror unregistered" '"ok": true' "$deleted"
still="$(api '/repos/forge/demo' | python3 -c 'import sys,json;print(json.load(sys.stdin).get("full_name","gone"))')"
check "the Gitea repo was kept (opt-in deletion only)" "forge/demo" "$still"
gone="$(curl -s -o /dev/null -w '%{http_code}' "http://127.0.0.1:$port/api/mirrors/demo")"
check "the mirror is gone from the registry" "404" "$gone"
# -------------------------------------------------------------- 11. graceful stop
section "11. SIGTERM stops cleanly"
kill -TERM "$(cat "$work/worker.pid")" 2>/dev/null
st=1
for _ in $(seq 1 30); do
kill -0 "$(cat "$work/worker.pid")" 2>/dev/null || { st=0; break; }
sleep 0.5
done
[ "$st" = "0" ] && ok "worker exited on SIGTERM" || bad "worker ignored SIGTERM"
contains "shutdown was announced" "stopped" "$(cat "$work/worker.out")"
printf '\n'
if [ "$fails" = "0" ]; then printf '\033[32mE2E PASSED\033[0m\n'; else printf '\033[31m%d FAILURE(S)\033[0m\n' "$fails"; fi
exit "$fails"
+430
View File
@@ -0,0 +1,430 @@
"""Unit tests for the parts of the worker that are pure logic.
No network, no Gitea: the git/API paths are covered by tests/e2e.sh against a
real throwaway Gitea. What is tested here is the code whose bugs are silent —
the config parser/renderer (a mirror's whole behavior comes from it) and the
URL/provider derivation (a wrong host split means pushing to the wrong place).
"""
from __future__ import annotations
import os
import sys
import tempfile
import time
import unittest
from unittest import mock
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from forker.api import to_ui_mirror # noqa: E402
from forker.config import ( # noqa: E402
BOOL_KEYS, CONFIG_DEFAULTS, KNOWN_KEYS, Settings, merge_config, parse_flat, render_flat,
)
from forker.engine import ( # noqa: E402
_collect_artifacts, _filter_branches, default_config_text,
)
from forker.gitops import Refs, is_transient # noqa: E402
from forker.provider import ( # noqa: E402
base_url_of, detect_provider, github_clone_base, host_of, owner_repo,
)
from forker.registry import derive_repo_name # noqa: E402
from forker.state import LogStore # noqa: E402
class ConfigTest(unittest.TestCase):
def test_parses_flat_keys_and_quotes(self):
parsed = parse_flat('mirror_branches: "*"\nmirror_tags: true\nbuild_cmd: "make && go build"\n')
self.assertEqual(parsed["mirror_branches"], "*")
self.assertIs(parsed["mirror_tags"], True)
self.assertEqual(parsed["build_cmd"], "make && go build")
def test_comments_and_blanks_are_ignored(self):
parsed = parse_flat("# c\n\n # indented comment\nenabled: false\n")
self.assertEqual(parsed, {"enabled": False})
def test_trailing_comment_stripped_but_not_inside_quotes(self):
parsed = parse_flat('artifacts: "dist/*" # globs\nmirror_branches: "a # b"\n')
self.assertEqual(parsed["artifacts"], "dist/*")
self.assertEqual(parsed["mirror_branches"], "a # b")
def test_nesting_is_rejected_not_silently_dropped(self):
with self.assertRaises(ValueError):
parse_flat("root:\n child: 1\n")
def test_bool_coercion_only_for_bool_keys(self):
parsed = parse_flat("mirror_prune: TRUE\nbuild_cmd: true\n")
self.assertIs(parsed["mirror_prune"], True)
self.assertEqual(parsed["build_cmd"], "true") # a command is a string
def test_render_is_byte_identical_for_a_noop(self):
original = '# header\nmirror_tags: true\nmirror_branches: "*"\nartifacts: ""\n'
rendered = render_flat(parse_flat(original), original)
self.assertEqual(rendered, original)
def test_render_preserves_comments_and_appends_new_keys(self):
original = '# keep me\nmirror_tags: true\n'
parsed = parse_flat(original)
parsed["mirror_prune"] = False
out = render_flat(parsed, original)
self.assertIn("# keep me", out)
self.assertIn("mirror_prune: false", out)
def test_render_keeps_unknown_keys(self):
original = "token_user: oauth2\nmirror_tags: true\n"
out = render_flat(parse_flat(original), original)
self.assertIn("token_user: oauth2", out)
def test_special_chars_get_quoted(self):
out = render_flat({"build_cmd": "make && go build -o dist/app ."}, "")
self.assertIn('build_cmd: "make && go build -o dist/app ."', out)
def test_missing_trailing_newline_is_not_added(self):
out = render_flat(parse_flat("mirror_tags: true"), "mirror_tags: false")
self.assertFalse(out.endswith("\n"))
def test_merge_applies_defaults_and_coerces_interval(self):
merged = merge_config({"sync_interval": "90", "mirror_tags": "no"})
self.assertEqual(merged["sync_interval"], 90)
self.assertIs(merged["mirror_tags"], False)
self.assertEqual(merged["mirror_branches"], "*")
def test_merge_survives_garbage_interval(self):
self.assertEqual(merge_config({"sync_interval": "soon"})["sync_interval"], 0)
class KeyAgreementTest(unittest.TestCase):
"""The three places that name config keys must agree.
`enabled` was once in the defaults and in BOOL_KEYS but missing from
KNOWN_KEYS, so the file the worker itself shipped could not be written
through the API — a key list drift is exactly the silent bug worth a test.
"""
def test_every_default_key_is_writable(self):
for key in CONFIG_DEFAULTS:
self.assertIn(key, KNOWN_KEYS, f"{key} is a default but not writable")
def test_bool_keys_are_bools_in_the_defaults(self):
for key in BOOL_KEYS:
self.assertIsInstance(CONFIG_DEFAULTS.get(key, True), bool)
def test_the_shipped_template_round_trips(self):
text = default_config_text()
parsed = parse_flat(text)
self.assertEqual(render_flat(parsed, text), text)
self.assertIs(parsed["enabled"], True)
class SettingsTest(unittest.TestCase):
def test_requires_remote_and_token(self):
with mock.patch.dict(os.environ, {}, clear=True):
with self.assertRaises(SystemExit) as ctx:
Settings.from_env()
self.assertIn("REMOTE", str(ctx.exception))
with mock.patch.dict(os.environ, {"REMOTE": "https://g.example/"}, clear=True):
with self.assertRaises(SystemExit) as ctx:
Settings.from_env()
self.assertIn("TOKEN", str(ctx.exception))
def test_alias_names_for_the_pipeline_era_still_work(self):
env = {"GITEA_SERVER_URL": "https://g.example", "GITEA_TOKEN": "t"}
with mock.patch.dict(os.environ, env, clear=True):
s = Settings.from_env()
self.assertEqual(s.remote, "https://g.example")
def test_strips_trailing_slash_and_reads_aliases(self):
env = {"REMOTE": "https://git.example/base/", "TOKEN": "t",
"GITEA_OWNER": "Lago", "INTERVAL": "300"}
with mock.patch.dict(os.environ, env, clear=True):
s = Settings.from_env()
self.assertEqual(s.remote, "https://git.example/base")
self.assertEqual(s.owner, "Lago")
self.assertEqual(s.interval_sec, 300)
self.assertTrue(s.host.startswith("0.0.0.0"))
def test_bad_number_is_a_startup_error_not_a_silent_default(self):
with mock.patch.dict(os.environ, {"REMOTE": "https://g", "TOKEN": "t",
"INTERVAL": "ten"}, clear=True):
with self.assertRaises(SystemExit):
Settings.from_env()
class ProviderTest(unittest.TestCase):
def test_detection(self):
self.assertEqual(detect_provider("https://github.com/a/b.git"), "github")
self.assertEqual(detect_provider("https://codeberg.org/a/b"), "codeberg")
self.assertEqual(detect_provider("https://git.lago.dev/a/b"), "gitea")
def test_url_splitting(self):
self.assertEqual(host_of("https://git.lago.dev/o/r.git"), "git.lago.dev")
self.assertEqual(host_of("https://user:tok@host/x"), "host")
self.assertEqual(base_url_of("https://git.lago.dev/o/r.git"), "https://git.lago.dev")
self.assertEqual(owner_repo("https://github.com/o/r.git"), "o/r")
def test_github_clone_base_only_for_github(self):
self.assertEqual(github_clone_base("https://github.com/o/r.git"), "https://github.com/o/r")
self.assertEqual(github_clone_base("https://codeberg.org/o/r"), "")
class RefsTest(unittest.TestCase):
def test_peeled_annotated_tags_are_not_counted_twice(self):
out = "\t".join(["abc", "refs/heads/main"]) + "\n" + \
"\t".join(["def", "refs/tags/v1"]) + "\n" + \
"\t".join(["ghi", "refs/tags/v1^{}"]) + "\n"
refs = Refs.parse(out)
self.assertEqual(refs.heads, ["main"])
self.assertEqual(refs.tags, ["v1"])
def test_transient_detection(self):
self.assertTrue(is_transient("fatal: unable to access: Could not resolve host: x"))
self.assertFalse(is_transient("remote: error: denied to forker"))
class FilterTest(unittest.TestCase):
heads = ["main", "develop", "release/1.2", "release/1.3", "topic"]
def test_star_means_all(self):
self.assertEqual(_filter_branches(self.heads, "*"), self.heads)
self.assertEqual(_filter_branches(self.heads, '"*"'), self.heads)
self.assertEqual(_filter_branches(self.heads, ""), self.heads)
def test_comma_list_tolerates_spaces(self):
self.assertEqual(_filter_branches(self.heads, "main, develop "), ["main", "develop"])
def test_glob_patterns(self):
self.assertEqual(_filter_branches(self.heads, "release/*"), ["release/1.2", "release/1.3"])
def test_unknown_branch_is_simply_absent(self):
self.assertEqual(_filter_branches(self.heads, "main,ghost"), ["main"])
def test_artifact_globs_resolve_in_the_tag_tree(self):
with tempfile.TemporaryDirectory() as work:
os.makedirs(os.path.join(work, "dist"))
for name in ("dist/a.tar.gz", "dist/b.bin", "dist/skip.txt"):
with open(os.path.join(work, name), "w") as fh:
fh.write("x")
found = sorted(os.path.basename(p) for p in _collect_artifacts(work, "dist/*.tar.gz dist/*.bin"))
self.assertEqual(found, ["a.tar.gz", "b.bin"])
self.assertEqual(_collect_artifacts(work, "nope/*"), [])
self.assertEqual(_collect_artifacts(work, ""), [])
class NamingTest(unittest.TestCase):
def test_derives_a_gitea_legal_name(self):
self.assertEqual(derive_repo_name("https://github.com/owner/Some-Repo.git"), "some-repo")
self.assertEqual(derive_repo_name("https://github.com/owner/x/"), "x")
self.assertEqual(derive_repo_name("not a url"), "mirror")
def test_gitea_rejects_a_dotgit_suffix(self):
self.assertFalse(derive_repo_name("https://github.com/o/thing.git").endswith(".git"))
class ApiShapeTest(unittest.TestCase):
def test_running_sync_maps_to_in_progress(self):
summary = _summary(running=True, last=None)
ui = to_ui_mirror(summary)
self.assertEqual(ui["lastSync"]["status"], "in_progress")
self.assertIsNone(ui["lastSync"]["conclusion"])
def test_a_first_in_flight_pass_has_no_timestamps_at_all(self):
# `createdAt` typed as a string that arrives null is a renderer trap: the
# field is omitted when nothing finished yet.
ui = to_ui_mirror(_summary(running=True, last=None))
self.assertNotIn("createdAt", ui["lastSync"])
self.assertNotIn("updatedAt", ui["lastSync"])
def test_event_is_why_the_pass_ran(self):
ui = to_ui_mirror(_summary(running=False, last={"ok": True, "at": 1700000000,
"reason": "manual"}))
self.assertEqual(ui["lastSync"]["event"], "manual")
ui2 = to_ui_mirror(_summary(running=True, last=None, running_reason="tick"))
self.assertEqual(ui2["lastSync"]["event"], "tick")
def test_last_counts_are_read_from_the_flat_pass_record(self):
# The counts live flat on `last`. They used to be nested under
# last["summary"] on one side and read flat on the other, so the detail
# page's "last pass" row was silently always empty.
ui = to_ui_mirror(_summary(running=False, last={
"ok": True, "at": 1700000000, "branchesPushed": 2, "tagsPushed": 4,
"branchesPruned": 1, "tagsPruned": 0, "releasesPublished": ["v1.0.0"],
"cold": False, "file": "20261019-180750-9.log",
}))
self.assertEqual(ui["lastCounts"]["branches"], 2)
self.assertEqual(ui["lastCounts"]["tags"], 4)
self.assertEqual(ui["lastCounts"]["pruned"], 1)
self.assertEqual(ui["lastCounts"]["releases"], ["v1.0.0"])
self.assertEqual(ui["lastSync"]["file"], "20261019-180750-9.log")
def test_failed_sync_maps_to_failure_conclusion(self):
ui = to_ui_mirror(_summary(running=False, last={"ok": False, "at": 1700000000,
"durationSec": 3}))
self.assertEqual(ui["lastSync"]["conclusion"], "failure")
def test_no_sync_yet_has_no_last_sync(self):
self.assertIsNone(to_ui_mirror(_summary(running=False, last=None))["lastSync"])
def test_parity_is_nested_under_upstream(self):
ui = to_ui_mirror(_summary(running=False, last=None))
self.assertEqual(ui["parity"]["upstream"]["branches"], 3)
self.assertEqual(ui["parity"]["branches"], 2)
def test_settings_interval_is_validated_not_clamped(self):
# A 200 whose body quietly disagrees with the request is worse than a 400.
from forker.api import HttpError, parse_interval
self.assertEqual(parse_interval(3600), 3600)
self.assertEqual(parse_interval("600"), 600)
for bad in (5, 29, 86401, 100000, "fast", None, {}):
with self.assertRaises(HttpError) as cm:
parse_interval(bad)
self.assertEqual(cm.exception.status, 400)
class DueTimingTest(unittest.TestCase):
"""The scheduler must measure INTERVAL from the END of the last pass."""
def _worker(self):
from forker.service import Worker
w = Worker.__new__(Worker) # no network: _due only reads s + rec
w.s = Settings(remote="http://g", token="t", owner="o", data_dir="/tmp/x",
interval_sec=60)
return w
def test_long_pass_does_not_chain_the_next_one(self):
# A cold pass started 200s ago and ended 5s ago: at INTERVAL=60 the
# next pass is NOT due. (Start-based math enqueued instantly — syncs
# 19s apart at INTERVAL=60, seen live against GitHub.)
w = self._worker()
rec = {"last_started": time.time() - 200, "last_at": time.time() - 5}
self.assertFalse(w._due(rec, {"sync_interval": 0}))
def test_due_after_interval_from_last_finish(self):
w = self._worker()
rec = {"last_started": time.time() - 300, "last_at": time.time() - 61}
self.assertTrue(w._due(rec, {"sync_interval": 0}))
def test_never_run_is_due(self):
w = self._worker()
self.assertTrue(w._due({}, {"sync_interval": 0}))
class LiveLogTest(unittest.TestCase):
"""A pass in flight tails its OWN file, not the previous run's latest.log."""
def test_current_file_tracks_the_open_run(self):
with tempfile.TemporaryDirectory() as d:
store = LogStore(d)
path, write, close = store.new_run("forge/demo")
self.assertEqual(store.current_file("forge/demo"), path)
write("in flight")
# While open, latest.log must not exist yet — the UI must not tail
# the PREVIOUS run and call it "pass in flight".
self.assertFalse(os.path.exists(os.path.join(store.dir_for("forge/demo"), "latest.log")))
close()
self.assertIsNone(store.current_file("forge/demo"))
def _gh_rec(name, *, tags=3, releases=1, parity_rel=1, cfg=None, token=""):
"""Registry record shaped like a settled GitHub mirror."""
return {
"name": name, "upstream": f"https://github.com/o/{name}.git",
"upstream_token": token,
"config": cfg or {"mirror_upstream_releases": True},
"counts": {"branches": 1, "tags": tags, "releases": releases, "assets": 0},
"parity": {"branches": 1, "tags": tags, "releases": parity_rel, "assets": 0},
}
class AutoPaceTest(unittest.TestCase):
"""The GitHub anonymous-API budget drives the effective interval."""
def test_settled_github_mirrors_cost_walk_plus_missing_tags(self):
from forker.pacer import pass_cost
# 3 tags, 1 release landed, parity says upstream has 1 release:
# walk=1 page + (3-1) tag probes = 3.
self.assertEqual(pass_cost(_gh_rec("a")), 3)
def test_token_and_non_github_mirrors_spend_no_anonymous_budget(self):
from forker.pacer import pass_cost
self.assertEqual(pass_cost(_gh_rec("a", token="ghp_x")), 0)
rec = _gh_rec("c")
rec["upstream"] = "https://codeberg.org/o/c.git"
self.assertEqual(pass_cost(rec), 0)
rec = _gh_rec("d", cfg={"mirror_upstream_releases": False})
self.assertEqual(pass_cost(rec), 1) # parity walk only
def test_release_walk_pages_capped(self):
from forker.pacer import release_walk_pages
self.assertEqual(release_walk_pages(0), 1)
self.assertEqual(release_walk_pages(None), 1)
self.assertEqual(release_walk_pages(250), 3)
self.assertEqual(release_walk_pages(5000), 10)
def test_explicit_interval_already_within_budget_is_kept(self):
from forker.pacer import plan
recs = {f"m{i}": _gh_rec(f"m{i}") for i in range(5)} # 5 × 3 = 15/pass
p = plan(recs, 3600) # 15/h ≪ 48/h
self.assertEqual(p["effective_sec"], 3600)
self.assertLessEqual(p["cost_per_pass"] * 3600 / p["effective_sec"], 48)
def test_fast_interval_is_raised_to_respect_the_budget(self):
from forker.pacer import plan
# 40 settled mirrors: 40 × 3 = 120/pass → 120/h ≫ 48/h → ≥ 2700s.
recs = {f"m{i}": _gh_rec(f"m{i}") for i in range(40)}
p = plan(recs, 600)
self.assertGreaterEqual(p["effective_sec"], 2700)
self.assertLessEqual(p["cost_per_pass"] * 3600 / p["effective_sec"], 48)
self.assertEqual(p["github_repos"], 40)
def test_cold_mirror_with_many_tags_widens_the_interval(self):
from forker.pacer import plan
recs = {"big": _gh_rec("big", tags=60, releases=0, parity_rel=0)}
p = plan(recs, 600) # 61 calls/pass → 61*75 = 4575 → ≥ FLOOR; ceil(61*3600/48)=4575
self.assertGreaterEqual(p["effective_sec"], 4575)
self.assertLessEqual(p["cost_per_pass"] * 3600 / p["effective_sec"], 48)
def test_paused_stays_paused(self):
from forker.pacer import plan
p = plan({"a": _gh_rec("a")}, 0)
self.assertEqual(p["effective_sec"], 0)
def test_no_github_mirrors_defer_to_explicit(self):
from forker.pacer import plan
rec = _gh_rec("c"); rec["upstream"] = "https://codeberg.org/o/c.git"
p = plan({"c": rec}, 300)
self.assertEqual(p["effective_sec"], 300)
self.assertEqual(p["github_repos"], 0)
def test_pinned_mirror_is_reported_and_never_paced(self):
from forker.pacer import plan
rec = _gh_rec("fast", cfg={"sync_interval": 60, "mirror_upstream_releases": True})
p = plan({"fast": rec}, 600)
self.assertEqual(p["github_repos"], 0) # pinned: outside the plan
self.assertEqual(p["effective_sec"], 600)
self.assertEqual(p["pinned"][0]["name"], "fast")
def test_ceiling_caps_a_huge_catchup(self):
from forker.pacer import plan
recs = {f"m{i}": _gh_rec(f"m{i}", tags=300, releases=0, parity_rel=0)
for i in range(5)} # 1500 calls/pass → way over a day
p = plan(recs, 600)
self.assertEqual(p["effective_sec"], 86400)
def _summary(*, running: bool, last: dict | None, running_reason: str | None = None) -> dict:
return {
"name": "demo", "full": "forge/demo", "upstream": "http://u/x.git",
"forkUrl": "http://g/forge/demo", "defaultBranch": "main", "owner": "forge",
"hasToken": False, "enabled": True, "intervalSec": 60, "running": running,
"runningReason": running_reason,
"config": {}, "spark": [], "units": ["Code"],
"counts": {"branches": 2, "tags": 2, "releases": 0, "assets": 0},
"parity": {"branches": 3, "tags": 3},
"last": last,
"last_at": (last or {}).get("at"),
}
if __name__ == "__main__":
unittest.main()
-61
View File
@@ -1,61 +0,0 @@
# API CONTRACT NOTES — verified live on git.lago.dev (Gitea 28.1.0)
These override any assumption in DESIGN.md about Gitea response shapes.
Every item below was verified with a real request today.
## Endpoint corrections
1. **Repo list**: `GET /api/v1/user/repos?limit=50&page=N` (paginate until <50).
`GET /api/v1/repos/{owner}` and `GET /api/v1/repos?owner=...` → **404** on this build.
2. **Workflow-specific runs**: `GET /repos/{o}/{r}/actions/workflows/{file}/actions/runs` → **404**.
Use `GET /repos/{o}/{r}/actions/runs?limit=N` and filter client-side on
`path` (= `"sync.yml@refs/heads/forker"`). The `?workflow=sync.yml` query
param DOES work on this build (verified 200) — acceptable alternative.
3. **Run object** fields: `id, event, status, conclusion, created_at,
completed_at (ISO, both always present), updated_at, path, run_attempt`.
duration = (completed_at − created_at) seconds. No `duration_sec` field.
4. **Jobs/log**: `GET /repos/{o}/{r}/actions/runs/{runId}/jobs` → `{"jobs":[{id,...}]}`;
`GET /repos/{o}/{r}/actions/jobs/{jobId}/logs` → **plain text** (one line per
run entry; includes `::group::`/`::notice::`/`::warning::` lines).
5. **Variable**: `GET /repos/{o}/{r}/actions/variables/{name}` →
`{"name":"UPSTREAM_URL","data":"<value>","description":""}` — the value field
is **`data`**, not `value`.
6. **Raw file read**: `GET /repos/{o}/{r}/raw/.forker.yaml?ref=forker` → plain
text. Write-back: `PUT /repos/{o}/{r}/contents/.forker.yaml` with
`{"content": <base64>, "message": ..., "branch": "forker"}`.
7. **Dispatch**: `POST /repos/{o}/{r}/actions/workflows/sync.yml/dispatches`
`{"ref":"forker"}` → **204** (works; the workflow path form is fine here).
## Object corrections
8. **Repo object** has NO `units` array. Derive unit names from booleans:
`has_code`→Code, `has_issues`→Issues, `has_pull_requests`→Pull Requests,
`has_releases`→Releases, `has_packages`→Packages, `has_projects`→Projects,
`has_wiki`→Wiki.
9. **Runner object** (repo + admin lists): `id, name, status
("online"|"offline"), busy (bool), disabled, labels:[{name}]`. NO `shared`/
`type` fields. Infer type: present in repo-scoped list of ≥2 repos →
"shared"; exactly 1 → "repo: {name}"; only in admin list → "shared
(unattached)". (The known good runner is `gitea-runner-forker`, id 5,
shared.)
10. **Releases object**: `id, tag_name, name, assets:[{name,size,download_url,...}],
published_at, ...`. Asset count = `len(assets)`.
11. **Mirror detection** (server-side): `GET /user/repos` (paginated) → for each
repo: `GET .../branches/forker` (200?) AND `GET .../actions/variables/UPSTREAM_URL`
(200 → value in `data`). Exclude the template repo (settings).
12. **GitHub upstream parity** (anonymous, NO Authorization header — golden
rule): `https://api.github.com/repos/{o}/{r}/branches?per_page=100`
(paginate), `/tags?per_page=100`, `/releases?per_page=100` (assets inside).
Cache 300 s per upstream. Non-GitHub upstreams: `git ls-remote --heads
--tags <url>` for counts (spawn, 30 s timeout, no credentials configured);
releases via the provider API pattern in `forker/lib/provider.sh`.
+54 -33
View File
@@ -1,48 +1,69 @@
# Repo Forker UI
Local control-plane for managing the mirrors generated from `repo-forker`.
A single `npx` command starts a tiny zero-dependency Node server that serves
the React app and proxies the Gitea API — the token never leaves your machine
and never touches the repo.
The control plane for the mirrors this container manages. It is **served by the
worker itself** (`forker/api.py` serves `ui/dist` plus the `/api/*` it calls), so
there is nothing separate to start in production: publish the container port and
open it.
## Run
There is no sign-in: the connection is the container's `REMOTE` + `TOKEN`
environment variables, and the token never leaves the process.
```
cd ui
npm install && npm run build # first time
node bin/repo-forker-ui.js # → http://127.0.0.1:8731
# or, once published / linked: npx repo-forker-ui
## Production
```bash
docker compose up -d --build # stage 1 builds this app into ui/dist
open http://127.0.0.1:8731
```
Open the URL, paste your Gitea base URL + a token (any scope; it only talks
to the API), and the dashboard appears with every mirror (a repo with a
`forker` branch + `UPSTREAM_URL` variable; the template is excluded).
## Development
Credentials are stored in `~/.repo-forker/credentials` (chmod 600).
Run the worker and the Vite dev server side by side; Vite proxies `/api` to it:
## What it does
```bash
# terminal 1 — the backend (no Docker needed)
REMOTE=https://git.lago.dev TOKEN=<admin token> DATA_DIR=$PWD/../.dev-test/data \
PORT=8741 python3 -m forker
- **Mirrors**: create from any git URL (generate → `UPSTREAM_URL` → default
branch → `.forker.yaml` config → first sync), delete, re-sync, view parity
(branches/tags/releases/assets vs upstream — anonymous for public GitHub),
edit the flat `.forker.yaml`, manage action variables, 7-day run sparkline,
staleness badge (last success > 30 min with the runner online).
- **Detail**: run history (last 12, failed ones expandable with the failing
log line), live log viewer, units, variables, config.
- **Runner**: serial-queue view (the runner is `maxParallel=1`), runners
online/offline, busy state, wait times.
- **States**: offline banner + cached data, empty states, skeletons, exact
error lines.
# terminal 2 — the app, on http://127.0.0.1:8730
npm install
npm run dev # BACKEND=http://127.0.0.1:8741 by default
```
```bash
npm run typecheck # tsc --noEmit
npm run build # → dist/, what the container serves
```
## Pages
- **Dashboard `/`** — every mirror this container owns: status, fork + origin
URLs, last sync, parity vs upstream (branches/tags/releases/assets), a 20-run
sparkline, and warnings for release failures or a disabled Releases unit.
Also **Adopt existing mirrors** (pipeline-era repos, skipped if a runner is
still driving them).
- **Mirror `/:name`** — run history (the on-disk logs), live log viewer with
build output, parity, the flat `.forker.yaml` editor, upstream panel (URL,
masked token, `enabled`, `sync_interval`), releases, units.
- **New mirror `/new`** — 3 steps: upstream (+ optional token for a private
one) → per-mirror config → the creation sequence
(`create-repo → forker-branch → config → default-branch → first-sync`).
- **Worker `/worker`** — the container itself: scheduler heartbeat, interval,
parallelism, queued/in-flight work, totals, Gitea url/version/owner, whether
the token is admin, and the worker's own log tail. (This replaced the old
Runner page — there is no runner.)
- **Settings `/settings`** — read-only view of the environment (`REMOTE`,
`TOKEN` masked, owner, template, data dir, Gitea version) plus the one thing
that is editable at runtime: the sync interval.
## Design
See [DESIGN.md](DESIGN.md) — the locked token set and the direction (dense
operator console, GitHub-dark, one blue signal color, monospace data).
[DESIGN.md](DESIGN.md) — the locked token set and direction (dense operator
console, GitHub-dark, one blue signal color, monospace data). Every page
implements the empty / loading / error / offline states it requires.
## API
`server/server.js` implements the full contract in DESIGN.md ("API contract"
section). All requests go to the Gitea base URL with a Bearer token; upstream
parity checks for public GitHub repos are **anonymous** (no auth header — the
golden rule), and upstream git operations (non-GitHub providers) run
`git ls-remote` without any credential configuration.
`/api/*` on the same origin, implemented by `forker/api.py`; the browser never
sees the Gitea token. Upstream counts for non-GitHub providers come from
`git ls-remote` (anonymous unless the mirror has a token); GitHub parity uses
the anonymous REST API.
-82
View File
@@ -1,82 +0,0 @@
# REWORK-CONTRACT.md — Neon Ops Console (rework de UI)
Read this fully before touching any file. Work ONLY on the files assigned in
your prompt. Never edit files owned by other agents. Never run `git commit`.
## What this product is
**Repo Forker** — a local control plane for git mirrors on a Gitea instance.
Operators live here all day. The rework keeps 100% of the functionality:
same data hooks, same API calls, same behavior. **Presentation only.**
## Direction (committed — do not deviate)
> **Neon Ops Console**: dense operator console, cool near-black ramp (one hue),
> ONE cyan signal color (#35e2ff), neon glow reserved for three moments only:
> the primary action, live/"you are here" states, and the brand mark.
> JetBrains Mono for every datum (numbers, names, URLs, ids); Space Grotesk
> for structure. Uppercase micro-labels (11px, tracking-wide) frame every
> panel — the console reads like an instrument, not a marketing page.
## Tokens (already installed — use ONLY these)
Tailwind color names (from `tailwind.config.js`): `bg panel panel2 chip border
border2 dim muted text accent accdim ok warn danger`. Opacity modifiers work:
`border-accent/40`, `bg-accent/10`.
CSS helpers (from `src/index.css`): `.ops-canvas` (page bg + grid),
`.font-mono`, `.tabular`, `.focus-ring` (cyan focus), `.glow-acc .glow-ok
.glow-warn .glow-danger`, `.text-glow`, `.animate-breathe`, `.skeleton`
(sheen loading block). `prefers-reduced-motion` is handled globally.
**Never** hardcode hex colors except via `HEALTH_COLORS` / `RUN_COLORS` (from
`src/lib/health.ts`) or the `C` map (from `src/pages/shared.tsx`). Never
invent new sizes outside the scale: `11 12 13 14 16 20 28` px. Space comes
from the Tailwind scale (multiples of 4). Touch targets: icons ≥ 32px
(`IconBtn` is 32), buttons ≥ 34px, primary CTAs taller on mobile.
## Shared components (use them, don't reinvent)
From `src/components/primitives.tsx`:
`StatusDot Badge StatCard Sparkline Toggle Btn IconBtn SkeletonRow EmptyState
ErrorInline OfflineBanner Panel ConfirmDialog toast Toaster`
From `src/pages/shared.tsx`: `MonoInput Spinner Label C`
From `src/lib/health.ts`: `health HEALTH_COLORS RUN_COLORS runColor timeAgo duration`
From `src/lib/app-context.tsx`: `useApp usePoll` (untouched, working).
`IconBtn` is NEW: row icon actions (re-sync, open, delete) —
`<IconBtn label="Re-sync" onClick disabled><RotateCw size={16}/></IconBtn>`,
`danger` prop for the trash.
## Hard rules
1. **API of pages/props/exports must not change** — App.tsx imports stay valid.
2. No changes to `src/api/*`, `src/lib/*` (except what your prompt grants),
`server/*`.
3. lucide icons: one set, `strokeWidth={2}` for UI, `1.5` for inline rows is
fine — stay consistent within your page. No emoji.
4. States are first-class: loading (`.skeleton`), empty (`EmptyState` with
hint), error (`ErrorInline` + retry), long content (truncate + `title=`),
mobile (< lg).
5. Glow discipline: if a non-primary, non-live element needs attention,
use color + weight, never glow.
6. Contrast: `text-dim` (#5f7186) only on backgrounds `panel`/`bg` for 11px+
uppercase labels — never for reading text; body secondary text is
`text-muted` (#8b9cb3).
7. Responsive: every page must work at 390px AND 1440px with **zero horizontal
overflow** (the old dashboard table overflowed 815px at 390px — fixed by
card-list switch below; follow that pattern where relevant).
## Mobile table pattern (Dashboard proved it)
`<table className="hidden ... md:table">` for ≥768px, and a parallel
`<div className="flex flex-col gap-2 md:hidden">` of compact cards for
<768px, same data, same onClick.
## Definition of done (per page you own)
- `cd ui && npx tsc --noEmit` passes (fix anything YOUR files broke; ignore
errors clearly owned by other pages mid-rework — list them in your report).
- No behavior lost: every button/link/state from the original page exists.
- Report at the end: files touched, decisions taken, any contract friction.
-81
View File
@@ -1,81 +0,0 @@
# VERIFY + POLISH plan (final round)
## A. Functional verification against the REAL Gitea (git.lago.dev)
Setup: start the server WITHOUT mock: `node bin/repo-forker-ui.js`, then
`POST /api/connect` with `http://127.0.0.1:3000` is WRONG — the real base URL
is `https://git.lago.dev` and the token is a temporary one created for this:
`POST /api/v1/users/Lago/tokens {"name":"ui-verify","scopes":["all"]}` → capture
the `sha1` at creation (the only time it's visible). After verification:
`DELETE /api/v1/users/Lago/tokens/{id}`. (The user's stored `~/.git-credentials`
line is basic-auth and works too; prefer the temp token so nothing long-lived
touches the UI.)
Checklist (all must pass; report each with a ✓/✗ and the raw JSON snippet):
1. `GET /api/health` → ok + gitea version.
2. `GET /api/mirrors` → exactly 3 mirrors (photocraft, pdfcraft, AnyPS5), each
with: upstream correct, lastSync from the real run, parity matching the
known-good numbers (photocraft 273 br / 10 tags / 10 rel / 203 assets;
AnyPS5 13 br / 3 tags / 2 rel / 16 assets; pdfcraft its real counts),
spark array length ≤20, units include "Releases".
3. `GET /api/mirrors/photocraft/runs?limit=12` → real run ids (recent ones:
the 1200s range).
4. `GET .../runs/{latest}/log` (via jobs) → text contains "Sync complete" or
"Releases unit OK".
5. `GET /api/runners` → `gitea-runner-forker` present, status online.
6. `GET /api/queue` → 200 (possibly empty array — that's fine).
7. `GET /api/mirrors/AnyPS5/config` → flat parse with
`mirror_upstream_releases: "true"` (string ok) and the other known keys.
8. `PUT` config with an INVALID nested value → 400 with a clear message.
`PUT` config with a valid no-op value → 200 and no commit spam (or at most
one commit).
9. **DO NOT** `POST /api/mirrors` (create) or `DELETE` against the real Gitea —
creation/deletion are verified in MOCK mode instead (idempotency + delete
with the type-the-name confirm are client-side; the server routes just need
to 200 against mock).
10. `POST /api/mirrors/{name}/dispatch {workflow:"sync.yml"}` → 204/200 on the
real Gitea is ACCEPTABLE once (it just re-runs the 10-min cron; harmless).
Do it at most once, on AnyPS5.
## B. Visual verification (offline, MOCK mode)
1. `MOCK=1 node bin/repo-forker-ui.js` → serve.
2. `design_audit` the 5 routes at 1440×900 and 390×844 (mobile).
3. Fix EVERY blocker/high the audit names (contrast, target size, spacing off
grid, too many font sizes/colors). Deliberate exceptions (e.g. 11px table
metadata is below the 14px floor) must be LISTED in the final report, not
silently left.
4. Screenshots (headless Chrome) of: dashboard (mock 3 mirrors), detail
(photocraft, with the failed run expanded), wizard (step 1 + step 3),
runner (queue populated), settings (connected). Save under
`.design-audit/ui-<timestamp>/`.
5. Confirm: no violet/indigo gradient, no emoji, no card gradients, hairline
borders, mono for all data, status dots with rings, one accent color doing
all "act here" work.
## C. Code polish pass (before commit)
- No `console.log` left in src/ or server/ (structured errors only).
- No unused imports; TS strict passes; `vite build` clean.
- The server is dependency-free (only node built-ins).
- `~/.repo-forker/credentials` is written chmod 600; the token never appears
in any URL, in logs, or in the client bundle.
- Offline banner works: kill nothing — just confirm the UI renders cached data
when /api/health fails (test by pointing connect at a dead URL).
- Empty states: with the real Gitea, the template repo must NOT appear in
/api/mirrors.
## D. Commit (subagent 5 does it)
- Branch `forker`, single squashed commit: "Repo Forker UI: local mirror-management
control plane (npx repo-forker-ui)" with body: what it does, how to run,
design spec pointer, verification summary.
- `ui/**` is added to .gitignore? NO — ui/ is tracked (it's the deliverable).
Only `ui/node_modules/`, `ui/dist/` are ignored (add to root .gitignore).
- Push to origin forker.
- DO NOT touch `forker/`, `.gitea/`, `Makefile`, `AGENTS.md`, `docs/` in the
commit (only `ui/` + the .gitignore line + a README.md pointer line at most).
- Final: report to the user in Spanish, concise: what was built, how to run it
(`cd ui && npm install && npm run build && node bin/repo-forker-ui.js`), the
verification table, the design-audit findings + fixes, and the open questions
(publish as an npm package? P1/P2 scope?).
-26
View File
@@ -1,26 +0,0 @@
#!/usr/bin/env node
/* npx repo-forker-ui — start the local control plane.
* Builds on first run if dist/ is missing, then serves on 8731 (or next free).
*/
'use strict';
const path = require('path');
const fs = require('fs');
const { spawnSync } = require('child_process');
const here = __dirname;
const uiDir = path.join(here, '..');
const dist = path.join(uiDir, 'dist');
if (!fs.existsSync(path.join(dist, 'index.html'))) {
console.log('repo-forker-ui: first run — building (vite build)…');
const r = spawnSync('npm', ['run', 'build'], { cwd: uiDir, stdio: 'inherit' });
if (r.status !== 0) {
console.error('repo-forker-ui: build failed. Run `cd ui && npm install && npm run build` manually.');
process.exit(r.status || 1);
}
}
// Require the server and start it (its `require.main === module` guard would not
// fire when loaded from this bin, so call boot() explicitly).
const { boot } = require(path.join(uiDir, 'server', 'server.js'));
boot();
+1 -2
View File
@@ -2,8 +2,7 @@
"name": "repo-forker-ui",
"version": "0.1.0",
"private": true,
"description": "Local control plane for Repo Forker mirrors",
"bin": { "repo-forker-ui": "bin/repo-forker-ui.js" },
"description": "Repo Forker UI \u2014 served by the container's worker; dev server proxies /api to it",
"scripts": {
"dev": "vite",
"build": "vite build",
-202
View File
@@ -1,202 +0,0 @@
'use strict';
// Canned data for MOCK=1 mode. Shapes match the real /api/* contract exactly.
// Timestamps are relative to boot so "time ago" stays plausible.
const now = Date.now();
const iso = (minAgo) => new Date(now - minAgo * 60000).toISOString();
function run(id, event, status, conclusion, minAgo, durationSec) {
return {
id, event, status, conclusion,
createdAt: iso(minAgo + durationSec / 60), updatedAt: iso(minAgo),
durationSec, path: 'sync.yml@refs/heads/forker',
};
}
const MIRRORS = [
{
name: 'photocraft', full: 'Lago/photocraft',
upstream: 'https://github.com/storytold/photocraft.git', forkUrl: 'https://git.lago.dev/Lago/photocraft', defaultBranch: 'main',
lastSync: run(1203, 'schedule', 'completed', 'success', 3, 372),
parity: { branches: 274, tags: 10, releases: 10, assets: 203, upstream: { branches: 273, tags: 10, releases: 10, assets: 203 } },
units: ['Code', 'Issues', 'Pull Requests', 'Releases', 'Packages', 'Projects', 'Actions'],
spark: ['success','success','success','success','failure','success','success','success','success','success',
'success','success','success','success','success','success','success','success','success','success'],
},
{
name: 'pdfcraft', full: 'Lago/pdfcraft',
upstream: 'https://github.com/storytold/pdfcraft.git', forkUrl: 'https://git.lago.dev/Lago/pdfcraft', defaultBranch: 'main',
lastSync: run(1191, 'push', 'completed', 'success', 8, 160),
parity: { branches: 19, tags: 8, releases: 10, assets: 168, upstream: { branches: 18, tags: 8, releases: 10, assets: 168 } },
units: ['Code', 'Issues', 'Pull Requests', 'Releases', 'Packages', 'Projects', 'Actions'],
spark: Array(20).fill('success'),
},
{
name: 'AnyPS5', full: 'Lago/AnyPS5',
upstream: 'https://github.com/boykopovar/AnyPS5.git', forkUrl: 'https://git.lago.dev/Lago/AnyPS5', defaultBranch: 'main',
lastSync: run(1199, 'schedule', 'in_progress', null, 1, 45),
parity: { branches: 13, tags: 3, releases: 2, assets: 16, upstream: { branches: 13, tags: 3, releases: 2, assets: 16 } },
units: ['Code', 'Issues', 'Pull Requests', 'Releases', 'Packages', 'Projects', 'Actions'],
spark: ['in_progress', ...Array(19).fill('success')],
},
];
const RUNS = {
photocraft: [
run(1203, 'schedule', 'completed', 'success', 3, 372),
run(1199, 'schedule', 'in_progress', null, 1, 45),
run(1196, 'schedule', 'completed', 'failure', 13, 96),
run(1190, 'push', 'completed', 'success', 28, 402),
run(1188, 'schedule', 'completed', 'success', 43, 388),
run(1185, 'schedule', 'completed', 'success', 58, 361),
run(1181, 'schedule', 'completed', 'failure', 73, 44),
run(1178, 'schedule', 'completed', 'success', 88, 395),
run(1174, 'schedule', 'completed', 'success', 103, 370),
run(1170, 'schedule', 'completed', 'success', 118, 382),
run(1166, 'schedule', 'completed', 'success', 133, 377),
run(1162, 'schedule', 'completed', 'success', 148, 369),
],
pdfcraft: [
run(1191, 'push', 'completed', 'success', 8, 160),
run(1189, 'schedule', 'completed', 'success', 23, 155),
run(1186, 'schedule', 'completed', 'success', 38, 149),
run(1182, 'schedule', 'completed', 'success', 53, 162),
run(1178, 'schedule', 'completed', 'success', 68, 158),
run(1174, 'schedule', 'completed', 'success', 83, 151),
run(1170, 'schedule', 'completed', 'success', 98, 166),
run(1166, 'schedule', 'completed', 'success', 113, 159),
],
AnyPS5: [
run(1199, 'schedule', 'in_progress', null, 1, 45),
run(1198, 'push', 'completed', 'success', 16, 38),
run(1194, 'schedule', 'completed', 'success', 31, 41),
run(1190, 'schedule', 'completed', 'success', 46, 39),
run(1186, 'schedule', 'completed', 'success', 61, 44),
run(1182, 'schedule', 'completed', 'success', 76, 37),
],
};
const LOG_OK = [
">> Upstream configured: https://github.com/storytold/photocraft.git",
"::group::fetch upstream refs",
"remote: Enumerating objects: 18243, done.",
"From https://github.com/storytold/photocraft",
" 3f21c09..91c47aa main -> upstream/main",
"::endgroup::",
"::group::push to fork (274 refs)",
"To https://git.lago.dev/Lago/photocraft.git",
" 91c47aa..b8d2c10 main -> main",
"::endgroup::",
">> Sync complete. Branches: (274) Tags: (10) New tags: (none)",
">> v0.8.2 already released — skipping (idempotent)",
">> Releases unit OK (web asset download works: HTTP 200).",
].map((text, t) => ({ t, text }));
const LOG_FAIL = [
">> Upstream configured: https://github.com/storytold/photocraft.git",
"::group::push to fork (274 refs)",
"fatal: unable to access 'https://git.lago.dev/Lago/photocraft.git/': Could not resolve host: git.lago.dev",
">> push_once: transient network error, retry 1 in 10s",
"fatal: unable to access 'https://git.lago.dev/Lago/photocraft.git/': Could not resolve host: git.lago.dev",
">> push_once: transient network error, retry 2 in 20s",
"fatal: unable to access 'https://git.lago.dev/Lago/photocraft.git/': Could not resolve host: git.lago.dev",
"::error::push failed after 3 attempts — aborting",
].map((text, t) => ({ t, text }));
const RELEASES = {
photocraft: ['v0.8.2','v0.7.0','v0.6.0','v0.5.0','v0.3.0','v0.2.0','v0.1.1-rc.5','v0.1.1-rc.4','v0.1.1','v0.1.0']
.map((tag, i) => ({ id: 100 - i, tag, name: tag, assets: [40,22,18,12,16,15,14,14,22,30][i] })),
pdfcraft: ['v1.4.0','v1.3.2','v1.3.1','v1.3.0','v1.2.0','v1.1.0','v1.0.2','v1.0.1','v1.0.0','v0.9.0']
.map((tag, i) => ({ id: 90 - i, tag, name: tag, assets: [22,18,15,12,16,14,10,8,12,6][i] })),
AnyPS5: ['v0.1.2','v0.1.1','v0.1.0'].map((tag, i) => ({ id: 80 - i, tag, name: tag, assets: [0,8,8][i] })),
};
const RUNNERS = [
{ id: 5, name: 'gitea-runner-forker', status: 'online', busy: true, labels: ['ubuntu-latest','ubuntu-24.04','ubuntu-22.04'], type: 'shared' },
{ id: 3, name: '496cfb9f4583', status: 'offline', busy: false, labels: ['ubuntu-latest','ubuntu-24.04'], type: 'repo', repo: 'Lago/Tide' },
{ id: 2, name: 'd3847f78c484', status: 'offline', busy: false, labels: ['ubuntu-latest','ubuntu-24.04'], type: 'repo', repo: 'Lago/Tide' },
];
const QUEUE = [
{ repo: 'AnyPS5', runId: 1199, event: 'schedule', status: 'in_progress', waitedSec: 45 },
{ repo: 'photocraft', runId: 1204, event: 'schedule', status: 'queued', waitedSec: 12 },
];
const CONFIG_RAW = [
'# .forker.yaml — per-fork configuration for Repo Forker.',
'',
'mirror_branches: "*"',
'mirror_tags: true',
'mirror_prune: true',
'mirror_upstream_releases: true',
'on_new_tag: true',
'build_cmd: ',
'build_script: ',
'artifacts: ',
].join('\n');
function parseFlatLocal(text) {
const KNOWN = ['mirror_branches','mirror_tags','mirror_prune','mirror_upstream_releases','on_new_tag','build_cmd','build_script','artifacts'];
const BOOL = ['mirror_tags','mirror_prune','mirror_upstream_releases','on_new_tag'];
const parsed = {};
for (const line of String(text).split('\n')) {
const t = line.trim();
if (!t || t.startsWith('#')) continue;
const m = line.match(/^([A-Za-z0-9_]+)\s*:\s*(.*)$/);
if (!m) continue;
let val = m[2].trim();
if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) val = val.slice(1, -1);
parsed[m[1]] = BOOL.includes(m[1]) ? (val === 'true' || val === '1') : val;
}
return { raw: text, parsed };
}
const VARIABLES = {
photocraft: [{ name: 'UPSTREAM_URL', value: 'https://github.com/storytold/photocraft.git' }],
pdfcraft: [{ name: 'UPSTREAM_URL', value: 'https://github.com/storytold/pdfcraft.git' }],
AnyPS5: [{ name: 'UPSTREAM_URL', value: 'https://github.com/boykopovar/AnyPS5.git' }],
};
function find(name) {
return MIRRORS.find((m) => m.name === name) || MIRRORS[0];
}
module.exports = {
health: () => ({ ok: true, gitea: { url: 'http://127.0.0.1:3000', version: '28.1.0' } }),
settings: () => ({ configured: true, url: 'http://127.0.0.1:3000', user: 'lago', template: 'Lago/repo-forker' }),
mirrors: () => MIRRORS,
mirrorRuns: (name, limit) => (RUNS[find(name).name] || []).slice(0, limit || 12),
mirrorReleases: (name) => RELEASES[find(name).name] || [],
mirrorConfig: (name) => parseFlatLocal(CONFIG_RAW),
mirrorVariables: (name) => VARIABLES[find(name).name] || [],
log: (name, runId) => {
const isFail = String(runId) === '1196' || String(runId) === '1181';
const lines = isFail ? LOG_FAIL : LOG_OK;
return { lines, cursor: lines.length - 1 };
},
runners: () => RUNNERS,
queue: () => QUEUE,
connect: () => ({ ok: true, user: 'lago', version: '28.1.0' }),
createMirror: (body) => {
// mirror the server: strip a trailing .git from a provided name, else
// derive from the upstream URL (last path segment, .git stripped, lower).
const b = body || {};
const provided = String(b.name || '').trim().replace(/\.git$/i, '');
let repoName = provided;
if (!repoName) {
try { repoName = new URL(b.upstream).pathname.split('/').filter(Boolean).pop().replace(/\.git$/i, '').toLowerCase() || 'new-mirror'; }
catch { repoName = 'new-mirror'; }
}
return {
ok: true,
repo: `Lago/${repoName}`,
steps: [
{ name: 'generate', status: 'ok' },
{ name: 'variable', status: 'ok' },
{ name: 'default-branch', status: 'ok' },
{ name: 'config', status: 'ok' },
{ name: 'first-sync', status: 'ok' },
],
};
},
};
-810
View File
@@ -1,810 +0,0 @@
#!/usr/bin/env node
/* Repo Forker UI — zero-dependency local server.
* Serves the built app (dist/) and proxies the Gitea API.
* The token never leaves this process; it is stored in ~/.repo-forker/credentials (chmod 600).
* Usage: node bin/repo-forker-ui.js (or: MOCK=1 node server/server.js for canned data)
*/
'use strict';
const http = require('http');
const fs = require('fs');
const os = require('os');
const path = require('path');
const { spawn } = require('child_process');
const MOCK = !!process.env.MOCK;
const CRED_DIR = path.join(os.homedir(), '.repo-forker');
const CRED_FILE = path.join(CRED_DIR, 'credentials');
const TEMPLATE = 'Lago/repo-forker';
// ---------------------------------------------------------------- credentials
function loadCreds() {
try {
const c = JSON.parse(fs.readFileSync(CRED_FILE, 'utf8'));
if (c && c.url && c.token) return c;
} catch { /* absent */ }
return null;
}
function saveCreds(c) {
fs.mkdirSync(CRED_DIR, { recursive: true });
fs.writeFileSync(CRED_FILE, JSON.stringify(c, null, 2));
fs.chmodSync(CRED_FILE, 0o600);
}
let CREDS = MOCK ? { url: 'http://127.0.0.1:3000', token: 'mock', user: 'lago' } : loadCreds();
// ---------------------------------------------------------------- gitea helper
async function gitea(method, apiPath, { body, raw } = {}) {
if (MOCK) return mockCall(method, apiPath, body);
if (!CREDS) throw new Error('not connected — POST /api/connect first');
// Normalize: caller paths may or may not carry the /api/v1 prefix.
let ap = apiPath;
if (!ap.startsWith('/api/')) ap = '/api/v1' + ap;
const url = CREDS.url.replace(/\/+$/, '') + ap;
const res = await fetch(url, {
method,
headers: {
Authorization: `Bearer ${CREDS.token}`,
...(body ? { 'Content-Type': 'application/json' } : {}),
},
body: body ? JSON.stringify(body) : undefined,
signal: AbortSignal.timeout(30000),
});
if (res.status === 204) return { status: 204, data: null };
const text = await res.text();
let data = raw ? text : null;
if (!raw && text) { try { data = JSON.parse(text); } catch { data = text; } }
if (!res.ok) {
const msg = (data && data.message) || (typeof data === 'string' ? data : text) || `HTTP ${res.status}`;
const e = new Error(msg); e.status = res.status;
throw e;
}
return { status: res.status, data };
}
async function giteaList(apiPath) {
const all = [];
for (let page = 1; page <= 60; page++) {
const { data } = await gitea('GET', `${apiPath}?limit=50&page=${page}`);
if (!Array.isArray(data)) break;
all.push(...data);
if (data.length < 50) break;
}
return all;
}
// ---------------------------------------------------------------- flat .forker.yaml
const KNOWN_KEYS = ['mirror_branches', 'mirror_tags', 'mirror_prune',
'mirror_upstream_releases', 'on_new_tag', 'build_cmd', 'build_script', 'artifacts'];
const BOOL_KEYS = ['mirror_tags', 'mirror_prune', 'mirror_upstream_releases', 'on_new_tag'];
function parseVal(key, raw) {
let val = String(raw).trim();
if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) val = val.slice(1, -1);
return BOOL_KEYS.includes(key) ? (val === 'true' || val === '1') : val;
}
function parseFlat(text) {
const parsed = {};
for (const line of String(text).split('\n')) {
const t = line.trim();
if (!t || t.startsWith('#')) continue;
const m = line.match(/^([A-Za-z0-9_]+)\s*:\s*(.*)$/);
if (!m) throw new Error(`not a flat key: value line — ${t}`);
parsed[m[1]] = parseVal(m[1], m[2]);
}
return parsed;
}
// Validate only the client's incoming keys — the file may carry other inert keys
// (e.g. `token_user`) that the grep parser ignores. Reject unknown keys + nesting.
function validateIncoming(parsed) {
for (const k of Object.keys(parsed)) {
if (!KNOWN_KEYS.includes(k)) { const e = new Error(`unknown key: ${k} (allowed: ${KNOWN_KEYS.join(', ')})`); e.status = 400; throw e; }
if (typeof parsed[k] === 'object') { const e = new Error(`nested value not allowed: ${k} — the parser is flat`); e.status = 400; throw e; }
}
return true;
}
function ser(key, v) {
if (BOOL_KEYS.includes(key)) return v ? 'true' : 'false';
const s = String(v);
if (s === '') return '';
const needQuote = /[!*|&>%@[\]"\n ]/.test(s) || /^(true|false|null|~)$/i.test(s);
return needQuote ? `"${s.replace(/"/g, '\\"')}"` : s;
}
// Preserving render: a value equal to the original keeps its verbatim line, so
// `mirror_branches: "*"` stays quoted and a no-op yields byte-identical text
// (→ the caller's `next !== raw` guard skips the PUT). Trailing-newline state
// is preserved exactly so a no-op never differs from the source.
function renderFlat(parsed, originalText) {
const raw = String(originalText);
const hadTrailingNL = raw.endsWith('\n');
let lines = raw.split('\n');
if (hadTrailingNL && lines[lines.length - 1] === '') lines = lines.slice(0, -1);
const out = [];
const used = new Set();
for (const line of lines) {
const m = line.match(/^([A-Za-z0-9_]+)\s*:\s*(.*)$/);
if (m && m[1] in parsed) {
const k = m[1], v = parsed[k];
out.push(parseVal(k, m[2]) === v ? line : `${k}: ${ser(k, v)}`);
used.add(k);
} else out.push(line);
}
for (const k of KNOWN_KEYS) {
if (k in parsed && !used.has(k)) out.push(`${k}: ${ser(k, parsed[k])}`);
}
let result = out.join('\n');
if (hadTrailingNL) result += '\n';
return result;
}
// Update an existing repo file on a branch. Gitea's contents API 422s
// ("file already exists") if you omit the current blob `sha`, so fetch it first.
async function updateRepoFile(full, filePath, content, message, branch) {
const { data: meta } = await gitea('GET', `/repos/${full}/contents/${filePath}?ref=${branch}`);
const body = {
content: Buffer.from(content).toString('base64'),
message,
branch,
};
if (meta && meta.sha) body.sha = meta.sha; // present ⇒ update, not create
await gitea('PUT', `/repos/${full}/contents/${filePath}`, { body });
}
// ---------------------------------------------------------------- upstream parity (anonymous)
const parityCache = new Map();
async function upstreamCounts(upstream) {
const key = String(upstream).toLowerCase();
const hit = parityCache.get(key);
if (hit && Date.now() - hit.at < 300000) return hit.data;
let data;
try {
const u = new URL(upstream);
data = (u.hostname === 'github.com' || u.hostname === 'gist.github.com')
? await githubCounts(u)
: await gitLsRemoteCounts(upstream);
} catch (e) {
data = { branches: null, tags: null, releases: null, assets: null };
}
parityCache.set(key, { at: Date.now(), data });
return data;
}
async function githubCounts(u) {
const parts = u.pathname.split('/').filter(Boolean);
const owner = parts[0];
const repo = (parts[1] || '').replace(/\.git$/, '');
const base = `https://api.github.com/repos/${owner}/${repo}`;
const hdr = { 'User-Agent': 'repo-forker-ui (anonymous)' };
const listAll = async (p) => {
let all = [], page = 1;
while (page <= 10) {
const r = await fetch(`${base}${p}?per_page=100&page=${page}`, { headers: hdr, signal: AbortSignal.timeout(30000) });
if (!r.ok) throw new Error(`github ${p} → ${r.status}`);
const arr = await r.json();
all.push(...arr);
if (arr.length < 100) break;
page++;
}
return all;
};
const [branches, tags, releases] = await Promise.all([
listAll('/branches').catch(() => null),
listAll('/tags').catch(() => null),
listAll('/releases').catch(() => []),
]);
return {
branches: branches ? branches.length : null,
tags: tags ? tags.length : null,
releases: releases.length,
assets: releases.reduce((s, r) => s + (r.assets ? r.assets.length : 0), 0),
};
}
function gitLsRemoteCounts(url) {
return new Promise((resolve) => {
const child = spawn('git', ['ls-remote', '--heads', '--tags', url], {
timeout: 30000,
env: { ...process.env, GIT_TERMINAL_PROMPT: '0', GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1' },
});
let out = '';
child.stdout.on('data', (d) => (out += d));
child.on('error', () => resolve({ branches: null, tags: null, releases: null, assets: null }));
child.on('close', (code) => {
if (code !== 0) return resolve({ branches: null, tags: null, releases: null, assets: null });
const lines = out.split('\n').filter(Boolean);
// Exclude peeled refs ("refs/tags/X^{}") — every annotated tag has one.
// GitHub's API counts them once so it looked right, but raw ls-remote
// doubles them (radiance: 25 real tags → '25/50' parity phantom).
const clean = lines.filter((l) => !l.endsWith('^{}'));
resolve({
branches: clean.filter((l) => l.includes('refs/heads/')).length,
tags: clean.filter((l) => l.includes('refs/tags/')).length,
releases: null, assets: null,
});
});
});
}
// ---------------------------------------------------------------- fork side
function mapRun(r) {
const created = new Date(r.created_at || 0).getTime();
const completed = new Date(r.completed_at || 0).getTime();
return {
id: r.id, event: r.event, status: r.status, conclusion: r.conclusion || null,
createdAt: r.created_at, updatedAt: r.updated_at, path: r.path,
durationSec: completed > created ? Math.round((completed - created) / 1000) : 0,
};
}
async function runsFor(full, workflow, limit) {
// Mirrored branches carry the upstream's own .gitea workflows (AnyPS5 runs
// area-labels.yml / pr-overlap.yml every few minutes), which flood the
// global runs list — even a 100-row window misses the mirror's sync.yml.
// The mirror's own workflows (sync.yml, release.yml) live ONLY on the
// `forker` branch; this build ignores ?workflow= but honors ?branch=forker,
// so filter server-side and keep the path check as belt-and-braces.
const q = workflow ? '?limit=100&branch=forker' : `?limit=${Math.min(limit * 20, 100)}`;
const { data } = await gitea('GET', `/repos/${full}/actions/runs${q}`);
let runs = ((data && data.workflow_runs) || []).map(mapRun);
if (workflow) runs = runs.filter((r) => (r.path || '').startsWith(workflow));
return runs.slice(0, limit);
}
async function lastRun(full, workflow) {
const runs = await runsFor(full, workflow, 1);
return runs[0] || null;
}
async function sparkFor(full, workflow) {
const runs = await runsFor(full, workflow, 20);
return runs.map((r) => r.conclusion === 'failure' ? 'failure' : r.status === 'in_progress' ? 'in_progress' : r.status === 'queued' ? 'queued' : 'success');
}
async function forkCounts(full) {
const [branches, tags, releases] = await Promise.all([
giteaList(`/repos/${full}/branches`),
giteaList(`/repos/${full}/tags`),
giteaList(`/repos/${full}/releases`),
]);
return {
branches: branches.length,
tags: tags.length,
releases: releases.length,
assets: releases.reduce((s, r) => s + (r.assets ? r.assets.length : 0), 0),
};
}
function unitsOf(repoObj) {
const map = { has_code: 'Code', has_issues: 'Issues', has_pull_requests: 'Pull Requests',
has_releases: 'Releases', has_packages: 'Packages', has_projects: 'Projects', has_wiki: 'Wiki' };
return Object.entries(map).filter(([k]) => repoObj && repoObj[k]).map(([, v]) => v);
}
// ---------------------------------------------------------------- mirror detection
// Upstream default branch (anonymous ls-remote, cached). The runner's Actions
// token CANNOT PATCH the repo default branch (Gitea 403 "should be an owner"),
// so sync.sh's self-correct can only log — the UI server holds the admin token
// and is the one place that can actually fix it.
const upDefCache = new Map();
function upstreamDefault(url) {
const key = String(url).toLowerCase();
const hit = upDefCache.get(key);
if (hit && Date.now() - hit.at < 600000) return Promise.resolve(hit.data);
return new Promise((resolve) => {
const child = spawn('git', ['ls-remote', '--symref', url, 'HEAD'], {
timeout: 20000,
env: { ...process.env, GIT_TERMINAL_PROMPT: '0', GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1' },
});
let out = '';
child.stdout.on('data', (d) => (out += d));
const done = (v) => { upDefCache.set(key, { at: Date.now(), data: v }); resolve(v); };
child.on('error', () => done(null));
child.on('close', () => {
const m = out.match(/^ref:\s+refs\/heads\/(\S+)\s+HEAD/m);
done(m ? m[1] : null);
});
});
}
async function ensureUpstreamDefault(repo, upVar) {
// one-shot heal: only when the machinery branch is still the default
if (repo.default_branch !== 'forker') return repo.default_branch;
const d = await upstreamDefault(upVar).catch(() => null);
if (!d || d === 'forker') return repo.default_branch;
try { await gitea('GET', `/repos/${repo.full_name}/branches/${encodeURIComponent(d)}`); }
catch { return repo.default_branch; } // not mirrored (filtered) yet — retry next cycle
try {
await gitea('PATCH', `/repos/${repo.full_name}`, { body: { default_branch: d } });
repo.default_branch = d;
} catch { /* leave as-is */ }
return repo.default_branch;
}
// Upstream CI workflows ride in on the mirrored branches and Gitea runs them
// on THIS runner: their triggers (cron/push) fire, and they die on missing
// GitHub infra (`gh: command not found`, actions/labeler, GitHub cache). That
// burns the serial runner's slots and floods the run history with red. The
// mirrored refs must stay byte-identical to upstream (no rewriting files),
// and sync.sh CANNOT disable anything (Actions token 403) — so the UI server
// (admin token) disables every workflow that isn't the mirror's own machinery
// on the `forker` branch. This build uses PUT /workflows/{file}/disable
// (POST → 405). Runs per-repo at most every 5 min; catches workflows upstream
// adds later, on any new mirror, automatically.
const MIRROR_WORKFLOWS = new Set(['sync.yml', 'release.yml', 'runner-check.yml']);
const wfHeal = new Map();
async function ensureUpstreamWorkflowsDisabled(full) {
const hit = wfHeal.get(full);
if (hit && Date.now() - hit.at < 300000) return hit.list;
const list = [];
try {
const { data } = await gitea('GET', `/repos/${full}/actions/workflows`);
for (const w of (data && data.workflows) || []) {
// this build: `id` is the FILENAME, `name` is the display name, and a
// disabled workflow reports state "disabled_manually" (not "disabled").
if (String(w.state || '').startsWith('disabled')) continue;
let file = String(w.id || '');
if (!file.endsWith('.yml') && !file.endsWith('.yaml')) file = String(w.path || '').split('/').pop();
file = file.split('/').pop();
if (!file || MIRROR_WORKFLOWS.has(file)) continue;
try {
const r = await gitea('PUT', `/repos/${full}/actions/workflows/${encodeURIComponent(file)}/disable`);
if (r.status === 204) list.push(file);
} catch { /* per-file failure — retry next cycle */ }
}
} catch { /* no actions unit / transient — retry next cycle */ }
wfHeal.set(full, { at: Date.now(), list });
return list;
}
// Limited-concurrency pool (keeps Gitea's connection pool happy, no thundering herd).
async function pmap(items, limit, fn) {
const out = new Array(items.length);
let i = 0;
const workers = Array.from({ length: Math.min(limit, items.length) || 1 }, async () => {
while (i < items.length) { const idx = i++; out[idx] = await fn(items[idx], idx); }
});
await Promise.all(workers);
return out;
}
// Shared cache so the 3s queue poll and 15s runner poll don't re-probe 36 repos.
const mirrorsCache = { at: 0, data: null, refreshing: false, pending: null };
// Cold start = 36 repo probes + anonymous upstream ls-remotes (15-30s). Keep
// the first paint instant: persist the last snapshot and warm it at boot, so
// /api/mirrors answers immediately from disk while a background refresh lands
// through the existing SWR path.
const MIRRORS_CACHE_FILE = path.join(CRED_DIR, 'mirrors-cache.json');
function loadMirrorsCache() {
try {
const raw = JSON.parse(fs.readFileSync(MIRRORS_CACHE_FILE, 'utf8'));
if (Array.isArray(raw.data) && raw.data.length) {
mirrorsCache.data = raw.data;
// Age it deliberately into the SWR window (>15s, <10min) no matter how
// old the file is: the first request then answers INSTANTLY from disk
// and only the background refresh hits the network.
mirrorsCache.at = Date.now() - 20000;
return true;
}
} catch { /* no cache yet */ }
return false;
}
function saveMirrorsCache(data) {
try {
if (!Array.isArray(data) || !data.length) return;
fs.writeFileSync(MIRRORS_CACHE_FILE, JSON.stringify({ at: Date.now(), data }));
fs.chmodSync(MIRRORS_CACHE_FILE, 0o600); // repo names/URLs only — no tokens
} catch { /* best-effort */ }
}
async function detectMirrors(force) {
const now = Date.now();
const age = mirrorsCache.data ? now - mirrorsCache.at : Infinity;
if (!force && age < 15000) return mirrorsCache.data;
if (!force && age < 600000) {
// stale-while-revalidate: ALWAYS answer instantly from cache. Only start a
// background refresh if one isn't already running (never stack recomputes).
if (!mirrorsCache.refreshing) {
mirrorsCache.refreshing = true;
detectMirrors(true).catch(() => {}).finally(() => { mirrorsCache.refreshing = false; });
}
return mirrorsCache.data;
}
// Cold / forced: dedupe so N simultaneous first-time callers (mirrors+runners+
// queue on page load) share ONE probe round instead of firing 3x ~74 requests.
if (mirrorsCache.pending) return mirrorsCache.pending;
mirrorsCache.pending = (async () => {
try {
const repos = await giteaList('/user/repos');
const candidates = [];
await pmap(repos, 8, async (repo) => {
const full = repo.full_name;
if (full.toLowerCase() === TEMPLATE.toLowerCase()) return; // never the template
try { await gitea('GET', `/repos/${full}/branches/forker`); } catch { return; }
try {
const { data } = await gitea('GET', `/repos/${full}/actions/variables/UPSTREAM_URL`);
if (data && data.data) candidates.push({ repo, upVar: data.data });
} catch { /* not a mirror */ }
});
const out = [];
await pmap(candidates, 4, async ({ repo, upVar }) => {
const full = repo.full_name;
await ensureUpstreamDefault(repo, upVar).catch(() => {});
const [lastSync, fc, up, spark] = await Promise.all([
lastRun(full, 'sync.yml').catch(() => null),
forkCounts(full).catch(() => null),
upstreamCounts(upVar).catch(() => null), // 300s-cached; keeps anonymous GitHub calls at ~1/repo/5min
sparkFor(full, 'sync.yml').catch(() => []),
ensureUpstreamWorkflowsDisabled(full).catch(() => []), // 300s-cached per repo
]);
out.push({
name: repo.name, full, upstream: upVar,
forkUrl: `${(CREDS && CREDS.url ? CREDS.url : '').replace(/\/+$/, '')}/${full}`,
defaultBranch: repo.default_branch || 'main',
lastSync,
parity: fc ? {
branches: fc.branches, tags: fc.tags, releases: fc.releases, assets: fc.assets,
upstream: up || {},
} : null,
units: unitsOf(repo),
spark,
});
});
out.sort((a, b) => a.name.localeCompare(b.name));
mirrorsCache.at = now;
mirrorsCache.data = out;
saveMirrorsCache(out);
return out;
} finally {
mirrorsCache.pending = null;
}
})();
return mirrorsCache.pending;
}
// Cheap name list backed by the same cache (queue/runner polls don't re-probe).
async function listMirrorNames() {
const list = await detectMirrors();
return list.map((m) => m.full);
}
// ---------------------------------------------------------------- create mirror
// Derive a repo name from an upstream URL — MUST mirror the client's
// deriveName (format.ts) so the placeholder shown to the user is exactly the
// name that gets created. Gitea rejects repo names matching *.git, so strip a
// trailing .git (and lowercase) or the generate step 400s with
// "name pattern is not allowed [pattern: *.git]".
function deriveRepoName(url) {
try {
const u = new URL(url);
const last = u.pathname.split('/').filter(Boolean).pop() || 'mirror';
return last.replace(/\.git$/i, '').toLowerCase() || 'mirror';
} catch { return 'mirror'; }
}
async function createMirror(upstream, name, config) {
const owner = (CREDS && CREDS.user) || 'lago';
// A provided name keeps its case (only the derived one is lowercased, to
// match the placeholder) but a trailing .git is stripped; if that leaves it
// empty, fall back to deriving from the URL (which is always non-empty).
const repoName = String(name || '').trim().replace(/\.git$/i, '') || deriveRepoName(upstream);
const full = `${owner}/${repoName}`;
const steps = [];
const fail = (stepName, e) => { steps.push({ name: stepName, status: 'error' }); return { ok: false, repo: full, steps, error: String((e && e.message) || e) }; };
try {
try {
await gitea('POST', `/repos/${TEMPLATE}/generate`, {
body: { name: repoName, owner, description: `Mirror of ${upstream} (Repo Forker)`, git_content: true, private: false },
});
} catch (e) {
// idempotent: a retry after a partially completed creation hits 409
// ("The repository with the same name already exists") — the repo is
// there, so proceed to finish the remaining steps instead of failing.
if (!(e.status === 409 && /already exists/i.test(String(e.message)))) throw e;
}
steps.push({ name: 'generate', status: 'ok' });
} catch (e) { return fail('generate', e); }
try {
try {
await gitea('POST', `/repos/${full}/actions/variables/UPSTREAM_URL`, { body: { name: 'UPSTREAM_URL', value: upstream } });
} catch (e) {
// idempotent: on retry the variable already exists (409 "variable name
// already exists") — update it via PUT so a stale value is also fixed.
if (!(e.status === 409 && /already exists/i.test(String(e.message)))) throw e;
await gitea('PUT', `/repos/${full}/actions/variables/UPSTREAM_URL`, { body: { value: upstream } });
}
steps.push({ name: 'variable', status: 'ok' });
} catch (e) { return fail('variable', e); }
let def = 'main';
try {
const u = new URL(upstream);
if (u.hostname === 'github.com') {
const r = await fetch(`https://api.github.com/repos${u.pathname}`, {
headers: { 'User-Agent': 'repo-forker-ui (anonymous)' }, signal: AbortSignal.timeout(15000),
});
if (r.ok) def = ((await r.json()).default_branch) || 'main';
}
} catch { /* default main */ }
try {
// Retry: a freshly generated repo can 404 transiently on this Gitea build
// right after the variable POST (observed: "variable UPSTREAM_URL: not
// found" — the repo's actions state isn't ready yet). The PATCH is also a
// silent no-op on this build when the target branch doesn't exist yet, so
// a failure here is not fatal to the mirror: sync.sh self-corrects the
// default branch on the first cron tick.
let lastErr;
for (let attempt = 0; attempt < 3; attempt++) {
try {
await gitea('PATCH', `/repos/${full}`, { body: { default_branch: def } });
lastErr = null;
break;
} catch (e) {
lastErr = e;
await new Promise((r) => setTimeout(r, 1500 * (attempt + 1)));
}
}
if (lastErr) throw lastErr;
steps.push({ name: 'default-branch', status: 'ok' });
} catch (e) { return fail('default-branch', e); }
try {
const { data: raw } = await gitea('GET', `/repos/${full}/raw/.forker.yaml?ref=forker`, { raw: true });
const parsed = parseFlat(raw);
for (const [k, v] of Object.entries(config || {})) {
if (v === undefined || v === null || v === '') continue;
parsed[k] = v;
}
validateIncoming(config || {});
const next = renderFlat(parsed, raw);
if (next !== raw) await updateRepoFile(full, '.forker.yaml', next, 'Configure .forker.yaml', 'forker');
steps.push({ name: 'config', status: 'ok' });
} catch (e) { return fail('config', e); }
try {
await gitea('POST', `/repos/${full}/actions/workflows/sync.yml/dispatches`, { body: { ref: 'forker' } });
steps.push({ name: 'first-sync', status: 'ok' });
} catch (e) { return fail('first-sync', e); }
return { ok: true, repo: full, steps };
}
// ---------------------------------------------------------------- mock mode
const mock = require('./mock.js');
// In MOCK mode the /api handlers below short-circuit to these canned helpers
// (no network, no detectMirrors). The gitea() mockCall is only a fallback for
// any path the handlers don't special-case.
function mockCall(method, apiPath, body) {
// Not used by the main handlers in MOCK mode; kept as a safe no-op fallback.
return { status: 200, data: {} };
}
// ---------------------------------------------------------------- http server
const MIME = { '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css', '.svg': 'image/svg+xml', '.png': 'image/png', '.ico': 'image/x-icon', '.json': 'application/json', '.map': 'application/json' };
const server = http.createServer(async (req, res) => {
const url = new URL(req.url, 'http://127.0.0.1');
const p = url.pathname;
const send = (code, obj) => {
const data = typeof obj === 'string' ? obj : JSON.stringify(obj);
res.writeHead(code, {
'Content-Type': typeof obj === 'string' ? 'text/plain; charset=utf-8' : 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
'Access-Control-Allow-Methods': 'GET,POST,PUT,DELETE,OPTIONS',
});
res.end(data);
};
if (req.method === 'OPTIONS') return send(204, '');
const readBody = async () => {
const chunks = [];
for await (const c of req) chunks.push(c);
return chunks.length ? JSON.parse(Buffer.concat(chunks).toString('utf8')) : null;
};
try {
if (p.startsWith('/api/')) {
// ---- MOCK short-circuits (canned data, no network) ----
if (MOCK) {
let m;
if (p === '/api/health') return send(200, mock.health());
if (p === '/api/settings') return send(200, mock.settings());
if (p === '/api/connect' && req.method === 'POST') return send(200, mock.connect());
if (p === '/api/mirrors' && req.method === 'GET') return send(200, mock.mirrors());
if (p === '/api/mirrors' && req.method === 'POST') { const b = await readBody(); return send(200, mock.createMirror(b)); }
if ((m = p.match(/^\/api\/mirrors\/([^/]+)\/runs$/))) return send(200, mock.mirrorRuns(decodeURIComponent(m[1]), parseInt(url.searchParams.get('limit') || '12', 10)));
if ((m = p.match(/^\/api\/mirrors\/([^/]+)\/releases$/))) return send(200, mock.mirrorReleases(decodeURIComponent(m[1])));
if ((m = p.match(/^\/api\/mirrors\/([^/]+)\/config$/))) return send(200, mock.mirrorConfig(decodeURIComponent(m[1])));
if ((m = p.match(/^\/api\/mirrors\/([^/]+)\/variables$/)) && req.method === 'GET') return send(200, mock.mirrorVariables(decodeURIComponent(m[1])));
if ((m = p.match(/^\/api\/mirrors\/([^/]+)\/variables$/)) && req.method === 'POST') return send(200, { ok: true });
if ((m = p.match(/^\/api\/mirrors\/([^/]+)\/variables\/([^/]+)$/)) && req.method === 'DELETE') return send(200, { ok: true });
if ((m = p.match(/^\/api\/mirrors\/([^/]+)\/dispatch$/))) return send(200, { ok: true });
if ((m = p.match(/^\/api\/mirrors\/([^/]+)$/)) && req.method === 'DELETE') return send(200, { ok: true });
if ((m = p.match(/^\/api\/mirrors\/([^/]+)\/runs\/(\d+)\/log$/))) return send(200, mock.log(decodeURIComponent(m[1]), m[2]));
if (p === '/api/runners') return send(200, mock.runners());
if (p === '/api/queue') return send(200, mock.queue());
return send(404, { ok: false, error: `unknown mock api: ${req.method} ${p}` });
}
// ---- real Gitea proxy ----
if (p === '/api/health') {
if (!CREDS) return send(200, { ok: false, gitea: null });
try {
const { data } = await gitea('GET', '/api/v1/version');
return send(200, { ok: true, gitea: { url: CREDS.url, version: (data && data.version) || 'unknown' } });
} catch (e) {
return send(200, { ok: false, gitea: null, error: String(e.message) });
}
}
if (p === '/api/connect' && req.method === 'POST') {
const b = await readBody();
const base = String((b && b.url) || '').replace(/\/+$/, '');
const tok = String((b && b.token) || '');
if (!base || !tok) return send(400, { ok: false, error: 'url and token required' });
if (MOCK) { CREDS = { url: base, token: tok, user: 'lago' }; return send(200, { ok: true, user: 'lago', version: '28.1.0' }); }
try {
const r = await fetch(`${base}/api/v1/user`, { headers: { Authorization: `Bearer ${tok}` }, signal: AbortSignal.timeout(15000) });
if (!r.ok) throw new Error(`Gitea replied HTTP ${r.status}`);
const u = await r.json();
let version = 'unknown';
try { version = ((await (await fetch(`${base}/api/v1/version`, { headers: { Authorization: `Bearer ${tok}` } })).json()).version) || 'unknown'; } catch { /* ok */ }
CREDS = { url: base, token: tok, user: u.login };
saveCreds(CREDS);
return send(200, { ok: true, user: u.login, version });
} catch (e) {
return send(400, { ok: false, error: String(e.message) });
}
}
if (p === '/api/settings') {
return send(200, { configured: !!CREDS, url: CREDS ? CREDS.url : '', user: CREDS ? CREDS.user : '', template: TEMPLATE });
}
if (p === '/api/mirrors' && req.method === 'GET') {
const mirrors = await detectMirrors();
return send(200, mirrors);
}
if (p === '/api/mirrors' && req.method === 'POST') {
const b = await readBody();
if (!b || !b.upstream) return send(400, { ok: false, error: 'upstream required' });
const r = await createMirror(b.upstream, b.name, b.config || {});
return send(r.ok ? 200 : 400, r);
}
let m;
if ((m = p.match(/^\/api\/mirrors\/([^/]+)\/runs\/(\d+)\/log$/))) {
const full = `${CREDS.user}/${decodeURIComponent(m[1])}`;
const { data: jobs } = await gitea('GET', `/repos/${full}/actions/runs/${m[2]}/jobs`);
const job = (jobs && jobs.jobs && jobs.jobs[0]) || {};
if (!job.id) return send(200, { lines: [], cursor: -1 });
const { data: text } = await gitea('GET', `/repos/${full}/actions/jobs/${job.id}/logs`, { raw: true });
const lines = String(text || '').split('\n').map((text2, i) => ({ t: i, text: text2 }));
return send(200, { lines, cursor: lines.length - 1 });
}
if ((m = p.match(/^\/api\/mirrors\/([^/]+)\/runs$/))) {
const full = `${CREDS.user}/${decodeURIComponent(m[1])}`;
const limit = parseInt(url.searchParams.get('limit') || '12', 10);
const runs = await runsFor(full, null, limit);
return send(200, runs);
}
if ((m = p.match(/^\/api\/mirrors\/([^/]+)\/releases$/))) {
const full = `${CREDS.user}/${decodeURIComponent(m[1])}`;
const rels = await giteaList(`/repos/${full}/releases`);
return send(200, rels.map((r) => ({ id: r.id, tag: r.tag_name, name: r.name || r.tag_name, assets: r.assets ? r.assets.length : 0 })));
}
if ((m = p.match(/^\/api\/mirrors\/([^/]+)\/config$/))) {
const full = `${CREDS.user}/${decodeURIComponent(m[1])}`;
if (req.method === 'GET') {
const { data } = await gitea('GET', `/repos/${full}/raw/.forker.yaml?ref=forker`, { raw: true });
return send(200, { raw: data, parsed: parseFlat(data) });
}
const b = await readBody();
const incoming = (b && b.parsed) || {};
validateIncoming(incoming);
const { data: raw } = await gitea('GET', `/repos/${full}/raw/.forker.yaml?ref=forker`, { raw: true });
const merged = { ...parseFlat(raw), ...incoming };
const next = renderFlat(merged, raw);
if (next !== raw) await updateRepoFile(full, '.forker.yaml', next, 'Update .forker.yaml', 'forker');
return send(200, { raw: next, parsed: merged });
}
if ((m = p.match(/^\/api\/mirrors\/([^/]+)\/variables\/([^/]+)$/)) && req.method === 'DELETE') {
const full = `${CREDS.user}/${decodeURIComponent(m[1])}`;
await gitea('DELETE', `/repos/${full}/actions/variables/${decodeURIComponent(m[2])}`);
return send(200, { ok: true });
}
if ((m = p.match(/^\/api\/mirrors\/([^/]+)\/variables$/))) {
const full = `${CREDS.user}/${decodeURIComponent(m[1])}`;
if (req.method === 'GET') {
// this Gitea build has no list-variables endpoint — probe the known names
const out = [];
for (const n of ['UPSTREAM_URL', 'UPSTREAM_TOKEN']) {
try {
const { data } = await gitea('GET', `/repos/${full}/actions/variables/${n}`);
if (data && data.name) out.push({ name: data.name, value: data.data });
} catch { /* not set */ }
}
return send(200, out);
}
const b = await readBody();
if (!b || !b.name) return send(400, { ok: false, error: 'name required' });
await gitea('POST', `/repos/${full}/actions/variables/${encodeURIComponent(b.name)}`, { body: b });
return send(200, { ok: true });
}
if ((m = p.match(/^\/api\/mirrors\/([^/]+)\/dispatch$/)) && req.method === 'POST') {
const full = `${CREDS.user}/${decodeURIComponent(m[1])}`;
const b = await readBody();
const wf = (b && b.workflow) || 'sync.yml';
const ref = (b && b.ref) || 'forker';
await gitea('POST', `/repos/${full}/actions/workflows/${wf}/dispatches`, { body: { ref } });
return send(200, { ok: true });
}
if ((m = p.match(/^\/api\/mirrors\/([^/]+)$/)) && req.method === 'DELETE') {
const full = `${CREDS.user}/${decodeURIComponent(m[1])}`;
await gitea('DELETE', `/repos/${full}`);
return send(200, { ok: true });
}
if (p === '/api/runners') {
const out = new Map();
const add = (r, scopeRepo) => {
const prev = out.get(r.id);
const repos = prev ? new Set(prev.repoScope) : new Set();
if (scopeRepo) repos.add(scopeRepo);
out.set(r.id, {
id: r.id, name: r.name, status: r.status, busy: !!r.busy, disabled: !!r.disabled,
labels: ((r.labels) || []).map((l) => l.name), repoScope: [...repos],
});
};
// repo-scoped list — one representative mirror (or the template) is enough to
// discover which runners attach to this user's repos
const names = await listMirrorNames().catch(() => []);
const probe = names[0] || TEMPLATE;
try {
const { data } = await gitea('GET', `/repos/${probe}/actions/runners?limit=50`);
for (const r of (data && data.runners) || []) add(r, probe);
} catch { /* skip */ }
try {
const { data } = await gitea('GET', '/api/v1/admin/actions/runners?limit=50');
for (const r of (data && data.runners) || []) add(r, null);
} catch { /* 403 tolerated — not an admin */ }
const runners = [...out.values()].map((r) => ({
id: r.id, name: r.name, status: r.status, busy: r.busy, labels: r.labels,
// repo-scoped list is empty for instance-shared runners on this build,
// so admin-only ⇒ shared (serves all repos).
type: r.repoScope.length >= 2 ? 'shared' : r.repoScope.length === 1 ? 'repo' : 'shared',
repo: r.repoScope.length === 1 ? r.repoScope[0] : undefined,
}));
return send(200, runners);
}
if (p === '/api/queue') {
const names = await listMirrorNames().catch(() => []);
const out = [];
for (const full of names) {
const runs = await runsFor(full, null, 10).catch(() => []);
for (const r of runs) {
if (r.status !== 'queued' && r.status !== 'in_progress') continue;
out.push({
repo: full.split('/')[1], runId: r.id, event: r.event, status: r.status,
waitedSec: Math.max(0, Math.round((Date.now() - new Date(r.createdAt).getTime()) / 1000)),
});
}
}
out.sort((a, b) => b.waitedSec - a.waitedSec);
return send(200, out);
}
return send(404, { ok: false, error: `unknown api: ${req.method} ${p}` });
}
// ---------- static ----------
const base = path.join(__dirname, '..', 'dist');
let fp = path.normalize(path.join(base, p === '/' ? 'index.html' : p));
if (!fp.startsWith(base)) fp = path.join(base, 'index.html');
if (!fs.existsSync(fp) && !path.extname(fp)) fp = path.join(base, 'index.html'); // SPA fallback
if (fs.existsSync(fp)) {
res.writeHead(200, { 'Content-Type': MIME[path.extname(fp)] || 'application/octet-stream' });
return res.end(fs.readFileSync(fp));
}
return send(404, 'not found');
} catch (e) {
const status = e && e.status ? e.status : 500;
return send(status, { ok: false, error: String((e && e.message) || e).split('\n')[0] });
}
});
// ---------------------------------------------------------------- boot
function boot() {
const host = process.env.HOST || '127.0.0.1';
const start = (port) => {
server.listen(port, host, () => {
console.log(`repo-forker-ui → http://${host === '0.0.0.0' ? '0.0.0.0' : host}:${port}${MOCK ? ' (MOCK mode)' : ''}`);
// Instant first paint: serve the persisted snapshot while a full probe
// runs in the background (15-30s on 36 repos + upstream ls-remotes).
if (MOCK || !CREDS) return;
const warm = loadMirrorsCache();
if (warm) console.log(' warm: serving last snapshot while refreshing…');
detectMirrors(true).catch(() => {});
});
};
const tryPort = (port) => {
const probe = http.createServer();
probe.once('error', () => { probe.close(); tryPort(port + 1); });
probe.once('listening', () => probe.close(() => start(port)));
probe.listen(port, host);
};
tryPort(8731);
}
if (require.main === module) boot();
module.exports = { server, boot };
+69 -63
View File
@@ -1,94 +1,83 @@
import { useCallback, useState } from 'react';
import { Routes, Route, Navigate } from 'react-router-dom';
import { GitBranch, Loader2 } from 'lucide-react';
import { useApp, usePoll } from './lib/app-context';
import { api } from './api/client';
import { useApp } from './lib/app-context';
import { Shell } from './components/Shell';
import { Btn, ErrorInline } from './components/primitives';
import type { Runner } from './api/types';
import { Label, MonoInput } from './pages/shared';
import { Btn, StatusDot } from './components/primitives';
import { HEALTH_COLORS } from './lib/health';
import Dashboard from './pages/Dashboard';
import Detail from './pages/Detail';
import Wizard from './pages/Wizard';
import RunnerView from './pages/RunnerView';
import WorkerView from './pages/WorkerView';
import SettingsPage from './pages/Settings';
// ============================================================================
// ConnectionGate — the console's sign-in screen. Centered card on the ops
// canvas; the brand mark is the sanctioned glow. Logic is unchanged:
// connect(url, token) via the app context, error inline, disabled until both
// fields are filled.
// The container is configured by REMOTE + TOKEN and holds the token itself, so
// there is no sign-in screen any more: if /api/settings answers, the app runs.
// If it does not, the container is down — that is a real offline state, not a
// login prompt, and it is the only thing left to say.
// ============================================================================
function ConnectionGate() {
const { connect, settings } = useApp();
const [url, setUrl] = useState(settings?.url || '');
const [token, setToken] = useState('');
const [busy, setBusy] = useState(false);
const [err, setErr] = useState('');
const submit = async () => {
setBusy(true); setErr('');
const ok = await connect(url.trim(), token.trim());
setBusy(false);
if (!ok) setErr('Connection failed — check the URL and token.');
};
function ContainerDown({ error }: { error: string | null }) {
const { reload } = useApp();
return (
<div className="ops-canvas flex min-h-screen items-center justify-center p-4">
{/* Enter in either field submits; the disabled submit button blocks it until both are filled */}
<form onSubmit={(e) => { e.preventDefault(); if (url.trim() && token.trim() && !busy) void submit(); }}
className="w-full max-w-[440px] rounded-panel border border-border bg-panel p-6 shadow-lift sm:p-8">
{/* brand mark — accent-bordered square, glow legit for the brand */}
<div className="flex h-10 w-10 items-center justify-center rounded-ctl border border-accent/40 bg-accent/10 glow-acc">
<GitBranch size={20} strokeWidth={2} className="text-accent" />
<div className="w-full max-w-[440px] rounded-panel border border-border bg-panel p-6 shadow-lift sm:p-8">
{/* brand mark — the sanctioned glow, kept for identity */}
<div className="flex items-center gap-3">
<span className="flex h-10 w-10 shrink-0 items-center justify-center rounded-ctl border border-accent/40 bg-accent/10 glow-acc">
<GitBranch size={20} strokeWidth={2} className="text-accent" />
</span>
<span className="min-w-0">
<span className="block text-[20px] font-bold leading-tight tracking-tight text-text">Repo Forker</span>
<span className="block font-mono text-[12px] leading-tight text-danger">worker unreachable</span>
</span>
</div>
<h1 className="mt-4 text-[20px] font-bold leading-tight tracking-tight text-text">Repo Forker</h1>
<p className="mt-2 text-[13px] leading-relaxed text-muted">
Connect to your Gitea to manage the mirrors generated from{' '}
<span className="font-mono text-text">repo-forker</span>. The token stays on this machine
(<span className="font-mono">~/.repo-forker/credentials</span>) and never touches the repo.
<p className="mt-4 text-[13px] leading-relaxed text-muted">
<span className="font-mono text-text">GET /api/settings</span> did not answer, so nothing can be read
or written. The container owns the Gitea token (<span className="font-mono text-text">REMOTE</span> and{' '}
<span className="font-mono text-text">TOKEN</span>) and serves this page from its published port — if
you are looking at it, the process behind it has stopped or the port moved.
</p>
<div className="mt-6">
<Label className="mb-[6px]">Gitea base URL</Label>
<MonoInput value={url} onChange={(e) => setUrl(e.target.value)}
placeholder="https://git.lago.dev" spellCheck={false} autoComplete="off" />
</div>
<div className="mt-4">
<Label className="mb-[6px]">Token</Label>
<MonoInput value={token} onChange={(e) => setToken(e.target.value)}
type="password" placeholder="Gitea token" />
<div className="mt-4 flex items-center gap-2 rounded-panel border border-border bg-chip px-3 py-2 font-mono text-[12px] text-muted">
<StatusDot color={HEALTH_COLORS.failed} pulse />
<span className="min-w-0 truncate" title={error || undefined}>{error || 'no response'}</span>
</div>
{err && <div className="mt-3"><ErrorInline message={err} /></div>}
<div className="mt-4 text-[12px] leading-relaxed text-muted">
Start it again with{' '}
<span className="font-mono text-text">docker compose up -d</span> (or the worker’s{' '}
<span className="font-mono text-text">run.sh start</span> for a local run), then retry.
</div>
<Btn type="submit" variant="primary" className="mt-6 min-h-[40px] w-full"
disabled={!url.trim() || !token.trim() || busy}>
{busy && <Loader2 size={16} strokeWidth={2} className="animate-spin" />}
{busy ? 'Connecting…' : 'Connect'}
<Btn variant="primary" className="mt-6 min-h-[40px] w-full" onClick={() => void reload()}>
<Loader2 size={16} strokeWidth={2} className="animate-spin" />
Retry connection
</Btn>
</form>
</div>
</div>
);
}
function AppInner() {
const { configured, host } = useApp();
const [runner, setRunner] = useState<Runner | null>(null);
const pollRunner = useCallback(() => {
void api.runners().then((rs) => {
setRunner(rs.find((r) => r.name === 'gitea-runner-forker') || rs.find((r) => r.status === 'online') || null);
}).catch(() => setRunner(null));
}, []);
usePoll(pollRunner, 15000);
if (!configured) return <ConnectionGate />;
function Gate() {
const { settings, configured, offline, error, worker, host } = useApp();
// First /api/settings call still in flight. If it answered "no" but the
// status stream still works, the container is alive — keep rendering.
if (!settings) {
if (!offline || worker?.ok) return <ShellLoading />;
return <ContainerDown error={error} />;
}
if (!configured) return <ContainerDown error={error} />;
return (
<Shell runner={runner} host={host} mirrorName={undefined}>
<Shell worker={worker} host={host}>
<Routes>
<Route path="/" element={<Dashboard />} />
<Route path="/mirrors/:name" element={<Detail />} />
<Route path="/new" element={<Wizard />} />
<Route path="/runner" element={<RunnerView runner={runner} />} />
<Route path="/worker" element={<WorkerView />} />
{/* the pipeline-era link */}
<Route path="/runner" element={<Navigate to="/worker" replace />} />
<Route path="/settings" element={<SettingsPage />} />
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>
@@ -96,6 +85,23 @@ function AppInner() {
);
}
function ShellLoading() {
return (
<div className="ops-canvas min-h-screen text-text">
<div className="mx-auto max-w-[1180px] px-4 py-7">
<div className="skeleton h-[16px] w-[160px] rounded" />
<div className="mt-4 grid grid-cols-2 gap-4 lg:grid-cols-4">
<div className="skeleton h-[92px] rounded-panel" />
<div className="skeleton h-[92px] rounded-panel" />
<div className="skeleton h-[92px] rounded-panel" />
<div className="skeleton h-[92px] rounded-panel" />
</div>
<div className="skeleton mt-4 h-[220px] rounded-panel" />
</div>
</div>
);
}
export default function App() {
return <AppInner />;
return <Gate />;
}
+66 -39
View File
@@ -1,8 +1,10 @@
// Typed client for the local server's /api/* contract (same-origin).
// Typed client for the container worker's /api/* contract (same-origin: the
// worker serves this bundle and the API from the published port, and the token
// never leaves the container).
import type {
Health, Settings, ConnectResult, Mirror, RunInfo, ReleaseInfo,
RepoVariable, FlatConfig, Runner, QueueEntry, LogResult, ConfigFile,
CreateMirrorResult,
Health, Settings, Mirror, RunInfo, ReleaseInfo, FlatConfig, QueueEntry,
LogResult, ConfigFile, CreateMirrorResult, WorkerStatus, UnitState,
AdoptResult, SyncResult, DeleteResult,
} from './types';
async function req<T>(path: string, init?: RequestInit): Promise<T> {
@@ -15,46 +17,71 @@ async function req<T>(path: string, init?: RequestInit): Promise<T> {
return body;
}
const q = (name: string) => encodeURIComponent(name);
// The worker always fills these in, but a build that predates a field must not
// blank a page: the dashboard reads releaseFailures/unitFix directly.
function mirror(m: Mirror): Mirror {
return {
...m,
running: !!m.running,
enabled: m.enabled !== false,
intervalSec: Number(m.intervalSec) || 0,
hasToken: !!m.hasToken,
config: m.config || {},
lastError: m.lastError ?? null,
units: m.units || [],
spark: m.spark || [],
releaseFailures: m.releaseFailures || [],
disabledWorkflows: m.disabledWorkflows || [],
unitFix: m.unitFix ?? null,
lastCounts: m.lastCounts || { branches: null, tags: null, pruned: 0, releases: [], cold: null },
};
}
export const api = {
health: () => req<Health>('/health'),
settings: () => req<Settings>('/settings'),
connect: (url: string, token: string) =>
req<ConnectResult>('/connect', { method: 'POST', body: JSON.stringify({ url, token }) }),
/** the only mutable setting — everything else comes from REMOTE/TOKEN */
saveSettings: (interval: number) =>
req<{ ok: boolean; changed: Record<string, number> }>('/settings', {
method: 'POST', body: JSON.stringify({ interval }),
}),
mirrors: () => req<Mirror[]>('/mirrors'),
mirrorRuns: (name: string, limit = 12) =>
req<RunInfo[]>(`/mirrors/${encodeURIComponent(name)}/runs?limit=${limit}`),
mirrorReleases: (name: string) =>
req<ReleaseInfo[]>(`/mirrors/${encodeURIComponent(name)}/releases`),
mirrorConfig: (name: string) =>
req<ConfigFile>(`/mirrors/${encodeURIComponent(name)}/config`),
// ---- worker (the container's own state — replaces the runner view)
workerStatus: () => req<WorkerStatus>('/status'),
workerLog: (tail = 400) => req<LogResult>(`/worker/log?tail=${tail}`),
queue: () => req<QueueEntry[]>('/queue'),
adopt: () => req<AdoptResult>('/adopt', { method: 'POST' }),
// ---- mirrors
mirrors: async (fresh = false) => (await req<Mirror[]>(`/mirrors${fresh ? '?fresh=1' : ''}`)).map(mirror),
mirror: async (name: string) => mirror(await req<Mirror>(`/mirrors/${q(name)}`)),
createMirror: (body: {
upstream: string; name?: string; token?: string; config?: FlatConfig; private?: boolean;
}) => req<CreateMirrorResult>('/mirrors', { method: 'POST', body: JSON.stringify(body) }),
/** upstream url / token ("" clears) / per-mirror config — returns the mirror */
updateMirror: async (name: string, body: { upstream?: string; token?: string; config?: FlatConfig }) =>
mirror(await req<Mirror>(`/mirrors/${q(name)}`, { method: 'PUT', body: JSON.stringify(body) })),
deleteMirror: (name: string, removeRepo = false) =>
req<DeleteResult>(`/mirrors/${q(name)}${removeRepo ? '?repo=true' : ''}`, { method: 'DELETE' }),
/** queue a sync pass now (this is the old workflow dispatch) */
sync: (name: string) => req<SyncResult>(`/mirrors/${q(name)}/sync`, { method: 'POST' }),
/** recount parity on both sides (network-heavy) */
refresh: async (name: string) => mirror(await req<Mirror>(`/mirrors/${q(name)}/refresh`, { method: 'POST' })),
unit: (name: string) => req<UnitState>(`/mirrors/${q(name)}/unit`, { method: 'POST' }),
mirrorRuns: (name: string) => req<RunInfo[]>(`/mirrors/${q(name)}/runs`),
mirrorReleases: (name: string) => req<ReleaseInfo[]>(`/mirrors/${q(name)}/releases`),
/** `file` picks a specific pass from /runs; default is the mirror's latest log */
log: (name: string, opts?: { tail?: number; file?: string }) => {
const p = new URLSearchParams({ tail: String(opts?.tail ?? 800) });
if (opts?.file) p.set('file', opts.file);
return req<LogResult>(`/mirrors/${q(name)}/log?${p}`);
},
mirrorConfig: (name: string) => req<ConfigFile>(`/mirrors/${q(name)}/config`),
saveMirrorConfig: (name: string, parsed: FlatConfig) =>
req<ConfigFile>(`/mirrors/${encodeURIComponent(name)}/config`, {
req<ConfigFile & { changed?: boolean }>(`/mirrors/${q(name)}/config`, {
method: 'PUT', body: JSON.stringify({ parsed }),
}),
mirrorVariables: (name: string) =>
req<RepoVariable[]>(`/mirrors/${encodeURIComponent(name)}/variables`),
createVariable: (name: string, variable: string, value: string) =>
req<{ ok: boolean }>(`/mirrors/${encodeURIComponent(name)}/variables`, {
method: 'POST', body: JSON.stringify({ name: variable, value }),
}),
deleteVariable: (name: string, variable: string) =>
req<{ ok: boolean }>(`/mirrors/${encodeURIComponent(name)}/variables/${encodeURIComponent(variable)}`, {
method: 'DELETE',
}),
dispatch: (name: string, workflow: string, ref?: string) =>
req<{ ok: boolean; runId?: number }>(`/mirrors/${encodeURIComponent(name)}/dispatch`, {
method: 'POST', body: JSON.stringify({ workflow, ref }),
}),
deleteMirror: (name: string) =>
req<{ ok: boolean }>(`/mirrors/${encodeURIComponent(name)}`, { method: 'DELETE' }),
createMirror: (upstream: string, name: string | undefined, config: FlatConfig) =>
req<CreateMirrorResult>('/mirrors', {
method: 'POST', body: JSON.stringify({ upstream, name, config }),
}),
log: (name: string, runId: number) =>
req<LogResult>(`/mirrors/${encodeURIComponent(name)}/runs/${runId}/log`),
runners: () => req<Runner[]>('/runners'),
queue: () => req<QueueEntry[]>('/queue'),
};
+148 -25
View File
@@ -1,18 +1,46 @@
// API contract types — mirror DESIGN.md /api/* exactly.
// API contract types — the container worker's /api/* contract, verified live
// against the running worker (see the notes on each field).
export interface Health { ok: boolean; gitea: { url: string; version: string } | null; error?: string }
export interface Settings { configured: boolean; url: string; user: string; template: string }
export interface ConnectResult { ok: boolean; user?: string; version?: string; error?: string }
export interface Health {
ok: boolean;
gitea: { url: string; version: string } | null;
worker?: { mirrors: number; queued: number };
error?: string;
}
/** GET /api/settings — env-driven, so `configured` is always true when the
* container answers. Everything except the interval is read-only. */
export interface Settings {
configured: boolean;
url: string; // REMOTE
user: string; // resolved owner/user of TOKEN
template: string; // owner/repo-forker
managedBy?: string; // "environment"
tokenSource?: string; // "REMOTE/TOKEN environment variables"
version?: string; // Gitea version
tokenIsAdmin?: boolean;
dataDir?: string;
intervalSec?: number;
effectiveIntervalSec?: number;
autoPace?: WorkerStatus['scheduler']['auto_pace'];
parallelism?: number;
}
export interface RunInfo {
/** unix seconds the pass started — a display affordance, NOT an identity */
id: number;
/** why the pass ran: 'manual' | 'tick' | 'boot' | 'created' | 'adopt' | 'worker' */
event: string;
status: 'queued' | 'in_progress' | 'completed';
conclusion: 'success' | 'failure' | 'cancelled' | 'skipped' | string | null;
createdAt: string;
updatedAt: string;
/** absent while a mirror's very first pass is in flight (nothing finished yet) */
createdAt?: string | null;
updatedAt?: string | null;
durationSec: number;
path?: string;
/** log file for this pass — pass it back as ?file= to read THAT log */
file?: string;
/** first line of the log, as the worker recorded it */
headline?: string;
}
export interface Parity {
@@ -20,48 +48,143 @@ export interface Parity {
tags: number | null;
releases: number | null;
assets: number | null;
/** null on the upstream side = not countable for this provider: never read as "behind" */
upstream?: { branches?: number | null; tags?: number | null; releases?: number | null; assets?: number | null };
}
/** What the last pass did — the honest tail of the sync report. */
export interface LastCounts {
branches: number | null;
tags: number | null;
pruned: number;
releases: string[]; // tags a release was published for
cold: boolean | null; // full fetch (no cached mirror) — explains a slow pass
}
/** Releases-unit verdict from the last pass:
* ok = enabled · off = disabled · fixed = healed by the worker this pass ·
* manual = off and NO API can flip it (assets 404 on the web route; fix once
* in repo Settings → Repository) · n/a = repo unreadable. */
export type UnitFix = 'ok' | 'off' | 'fixed' | 'manual' | 'n/a' | null;
export interface Mirror {
name: string;
full: string;
upstream: string; // origin URL (github.com/… or gitea/codeberg/…)
forkUrl: string; // where the mirror lives (https://git.lago.dev/Lago/<name>)
upstream: string;
forkUrl: string;
defaultBranch: string;
owner: string;
running: boolean;
/** scheduler switch (config `enabled`) */
enabled: boolean;
/** effective interval: config `sync_interval` or the container's INTERVAL */
intervalSec: number;
/** the upstream token is stored in the container, never echoed — true = one is set */
hasToken: boolean;
config: FlatConfig;
lastSync: RunInfo | null;
lastError: string | null;
parity: Parity | null;
units: string[];
spark: (string)[]; // run statuses, oldest→newest, ≤20
spark: string[]; // run statuses, oldest→newest, ≤20
/** last pass's silent failures — a mirror can be green while these are not empty */
releaseFailures: string[];
/** upstream workflow files the worker had to disable on the mirror */
disabledWorkflows: string[];
unitFix: UnitFix;
lastCounts: LastCounts;
/** set when a saved config could not be written to the remote .forker.yaml */
configSync?: string | null;
}
export interface ReleaseInfo { id: number; tag: string; name: string; assets: number }
export interface ReleaseInfo { id: number; tag: string; name: string; assets: number; url?: string | null }
export interface RepoVariable { name: string; value: string }
export interface FlatConfig { [key: string]: string | boolean | number }
export interface FlatConfig { [key: string]: string | boolean }
export interface Runner {
id: number; name: string; status: 'online' | 'offline'; busy: boolean;
type: 'shared' | 'repo' | 'shared (unattached)'; labels: string[]; repo?: string;
}
export interface QueueEntry { repo: string; runId: number; event: string; status: 'queued' | 'in_progress'; waitedSec: number }
export interface QueueEntry { repo: string; event: string; status: 'queued' | 'in_progress'; waitedSec: number }
export interface LogLine { t: number; text: string }
export interface LogResult { lines: LogLine[]; cursor: number }
export interface LogResult { lines: LogLine[]; cursor?: number; running?: boolean; file?: string }
export interface ConfigFile { raw: string; parsed: FlatConfig }
export interface CreateMirrorStep { name: string; status: 'ok' | 'error' }
export interface SyncResult { ok: boolean; queued: boolean; running: boolean }
export interface DeleteResult { ok: boolean; deletedRepo?: boolean }
/** POST /api/status */
export interface WorkerStatus {
ok: boolean;
boot: {
started_at: number;
uptime_sec: number;
remote: string;
owner: string;
user?: string;
is_admin?: boolean;
gitea_version: string;
self_registered?: boolean;
template: string;
errors: string[];
};
scheduler: {
interval_sec: number;
parallelism: number;
last_tick: number;
queued: number;
running: string[];
effective_interval_sec?: number;
auto_pace?: {
effective_sec: number;
explicit_sec: number;
required_sec: number;
github_repos: number;
cost_per_pass: number;
est_calls_per_hour: number;
budget_per_hour: number;
pinned: { name: string; interval_sec: number }[];
reason: string;
} | null;
};
settings: { remote: string; owner: string; template: string; data_dir: string; token_is_admin: boolean };
totals: { mirrors: number; healthy: number; assets: number; releases: number };
}
/** POST /api/mirrors/:name/unit */
export interface UnitState {
has_releases: boolean | null;
/** ok = enabled · off = disabled, flippable · manual = no API, fix in the UI · n/a = repo unreadable */
fix: 'ok' | 'off' | 'manual' | 'n/a' | string;
units?: string[];
}
/** POST /api/adopt */
export interface AdoptResult {
adopted: { repo: string; upstream: string }[];
skipped: { repo: string; reason: string }[];
would_delete?: string | null;
}
export interface CreateMirrorStep {
name: string;
status: 'ok' | 'error' | string;
detail?: string;
}
export interface CreateMirrorResult { ok: boolean; repo?: string; steps: CreateMirrorStep[]; error?: string }
/** Keys the worker understands in .forker.yaml (its KNOWN_KEYS + `enabled`,
* which the file renders but PUT /config does not accept yet). */
export const KNOWN_CONFIG_KEYS = [
'mirror_branches', 'mirror_tags', 'mirror_prune',
'mirror_upstream_releases', 'on_new_tag',
'enabled', 'mirror_branches', 'mirror_tags', 'mirror_prune',
'mirror_upstream_releases', 'on_new_tag', 'sync_interval',
'build_cmd', 'build_script', 'artifacts',
] as const;
export const BOOLEAN_CONFIG_KEYS = [
'mirror_tags', 'mirror_prune', 'mirror_upstream_releases', 'on_new_tag',
'enabled', 'mirror_tags', 'mirror_prune',
'mirror_upstream_releases', 'on_new_tag',
] as const;
/** The worker's fixed creation sequence (registry.create step names). */
export const CREATE_STEPS = [
'create-repo', 'forker-branch', 'config', 'default-branch', 'first-sync',
] as const;
+24 -15
View File
@@ -1,18 +1,19 @@
import React, { useState } from 'react';
import { NavLink, useLocation } from 'react-router-dom';
import { LayoutGrid, Cpu, Plus, Settings, Menu, X, GitBranch } from 'lucide-react';
import type { Runner } from '../api/types';
import type { WorkerStatus } from '../api/types';
import { fmtSec } from '../pages/format';
// ============================================================================
// Neon Ops Console shell: fixed sidebar on desktop, top bar + slide-down nav
// on mobile. The brand mark is the only always-on glow. Runner status lives
// in a bottom rail (desktop) / top-bar dot (mobile).
// on mobile. The brand mark is the only always-on glow. The bottom rail now
// reports the worker — this container is the thing that used to be a runner.
// ============================================================================
const NAV = [
{ to: '/', label: 'Mirrors', icon: LayoutGrid, exact: true },
{ to: '/new', label: 'New mirror', icon: Plus },
{ to: '/runner', label: 'Runner', icon: Cpu },
{ to: '/worker', label: 'Worker', icon: Cpu },
{ to: '/settings', label: 'Settings', icon: Settings },
];
@@ -30,20 +31,28 @@ function Brand({ host }: { host: string }) {
);
}
function RunnerPill({ runner }: { runner: Runner | null }) {
const online = runner?.status === 'online';
// Worker = this container. Alive if /api/status answered; "busy" (breathing)
// while a sync pass is in flight.
function WorkerPill({ worker }: { worker: WorkerStatus | null }) {
const live = !!worker?.ok;
const running = (worker?.scheduler?.running?.length || 0) > 0;
const queued = worker?.scheduler?.queued || 0;
return (
<span className="inline-flex items-center gap-2 rounded-pill border border-border bg-chip px-2.5 py-1 font-mono text-[12px] text-muted"
title={runner ? `${runner.name}: ${runner.status}` : 'runner unknown'}>
<span className={`h-2 w-2 rounded-full ${online ? 'bg-ok glow-ok' : 'bg-danger'}`} />
{online ? 'runner online' : runner ? 'runner offline' : 'runner ?'}
<span className="inline-flex max-w-full items-center gap-2 rounded-pill border border-border bg-chip px-2.5 py-1 font-mono text-[12px] text-muted"
title={live
? `worker up ${fmtSec(worker.boot?.uptime_sec || 0)} · ${worker.scheduler?.running?.length || 0} running · ${queued} queued`
: 'worker status unknown'}>
<span className={`h-2 w-2 shrink-0 rounded-full ${live ? 'bg-ok glow-ok' : 'bg-danger'} ${
live && running ? 'animate-breathe' : ''}`} aria-hidden />
<span className="truncate">{live ? 'worker online' : 'worker ?'}</span>
{live && queued > 0 && <span className="shrink-0 text-accent">+{queued}</span>}
</span>
);
}
export function Shell({ children, runner, host, mirrorName }: {
export function Shell({ children, worker, host, mirrorName }: {
children: React.ReactNode;
runner: Runner | null;
worker: WorkerStatus | null;
host: string;
mirrorName?: string;
}) {
@@ -80,7 +89,7 @@ export function Shell({ children, runner, host, mirrorName }: {
)}
</nav>
<div className="mt-auto border-t border-border px-4 py-3">
<RunnerPill runner={runner} />
<WorkerPill worker={worker} />
</div>
</aside>
@@ -88,8 +97,8 @@ export function Shell({ children, runner, host, mirrorName }: {
<header className="sticky top-0 z-30 flex items-center justify-between border-b border-border bg-panel/90 px-4 py-3 backdrop-blur-md lg:hidden">
<Brand host={host} />
<div className="flex items-center gap-2">
<span className={`h-2.5 w-2.5 rounded-full ${runner?.status === 'online' ? 'bg-ok glow-ok' : 'bg-danger'}`}
title={runner ? `${runner.name}: ${runner.status}` : 'runner unknown'} aria-hidden />
<span className={`h-2.5 w-2.5 rounded-full ${worker?.ok ? 'bg-ok glow-ok' : 'bg-danger'}`}
title={worker?.ok ? 'worker online' : 'worker status unknown'} aria-hidden />
<button onClick={() => setOpen((o) => !o)} aria-expanded={open} aria-label="Menu"
className="focus-ring flex h-10 w-10 items-center justify-center rounded-ctl border border-border text-muted">
{open ? <X size={18} /> : <Menu size={18} />}
+4 -5
View File
@@ -175,8 +175,8 @@ export function Panel({ title, action, children, className = '' }: {
}
// ---- ConfirmDialog (type-the-name for destructive) ----
export function ConfirmDialog({ open, name, confirmText, onConfirm, onClose, busy }: {
open: boolean; name: string; confirmText?: string;
export function ConfirmDialog({ open, name, confirmText, message, action = 'Delete', onConfirm, onClose, busy }: {
open: boolean; name: string; confirmText?: string; message?: React.ReactNode; action?: string;
onConfirm: () => void; onClose: () => void; busy?: boolean;
}) {
const [text, setText] = React.useState('');
@@ -191,8 +191,7 @@ export function ConfirmDialog({ open, name, confirmText, onConfirm, onClose, bus
onClick={(e) => e.stopPropagation()}>
<h3 className="font-mono text-[16px] font-bold text-text">Delete <span className="text-danger">{name}</span>?</h3>
<p className="mt-2 text-[13px] leading-relaxed text-muted">
This permanently deletes the repository and all its branches, tags and releases.
The template is not affected.
{message ?? 'This stops the container from managing this mirror.'}
</p>
<input value={text} onChange={(e) => setText(e.target.value)}
placeholder={`Type ${required} to confirm`}
@@ -200,7 +199,7 @@ export function ConfirmDialog({ open, name, confirmText, onConfirm, onClose, bus
<div className="mt-5 flex justify-end gap-2">
<Btn variant="ghost" onClick={onClose}>Cancel</Btn>
<Btn variant="dangerSolid" disabled={!ready || busy} onClick={onConfirm}>
{busy ? 'Deleting…' : 'Delete'}
{busy ? `${action}…` : action}
</Btn>
</div>
</div>
+55 -15
View File
@@ -1,51 +1,82 @@
import React, { createContext, useContext, useEffect, useState } from 'react';
import React, { useCallback, createContext, useContext, useEffect, useState } from 'react';
import { api } from '../api/client';
import type { Settings } from '../api/types';
import type { Settings, WorkerStatus } from '../api/types';
interface AppCtx {
settings: Settings | null;
configured: boolean;
/** the container did not answer /api/settings — it is down or unreachable */
offline: boolean;
/** exact failing line, for the container-down screen */
error: string | null;
/** host of REMOTE — shown in the brand rail so you know which Gitea this container drives */
host: string;
/** the container's own state (GET /api/status) — the runner's replacement */
worker: WorkerStatus | null;
workerError: string | null;
reload: () => Promise<void>;
connect: (url: string, token: string) => Promise<boolean>;
refreshWorker: () => Promise<void>;
}
const Ctx = createContext<AppCtx>({
settings: null, configured: false, offline: false, host: '', reload: async () => {},
connect: async () => false,
settings: null, configured: false, offline: false, error: null, host: '',
worker: null, workerError: null,
reload: async () => {}, refreshWorker: async () => {},
});
export function useApp() { return useContext(Ctx); }
/**
* The connection is environment-driven (REMOTE + TOKEN inside the container),
* so there is nothing to sign in to: if /api/settings answers, the app is
* configured. If it does not answer, the container itself is down and App
* renders a real offline screen — the old ConnectionGate had nothing left to
* collect, because the token cannot leave the container.
*/
export function AppProvider({ children }: { children: React.ReactNode }) {
const [settings, setSettings] = useState<Settings | null>(null);
const [offline, setOffline] = useState(false);
const [error, setError] = useState<string | null>(null);
const [worker, setWorker] = useState<WorkerStatus | null>(null);
const [workerError, setWorkerError] = useState<string | null>(null);
const reload = React.useCallback(async () => {
const reload = useCallback(async () => {
try {
const s = await api.settings();
setSettings(s);
setOffline(false);
} catch {
setError(null);
} catch (e) {
setOffline(true);
setError(e instanceof Error ? e.message : String(e));
}
}, []);
useEffect(() => { void reload(); }, [reload]);
const connect = React.useCallback(async (url: string, token: string) => {
// The container IS the runner now, so /api/status is one shared stream: the
// sidebar pill, the dashboard's worker badge and the Worker page all read it.
// A failed status poll means the container went away mid-session.
const refreshWorker = useCallback(async () => {
try {
const r = await api.connect(url, token);
if (r.ok) { await reload(); return true; }
return false;
} catch { return false; }
}, [reload]);
setWorker(await api.workerStatus());
setWorkerError(null);
} catch (e) {
setWorkerError(e instanceof Error ? e.message : String(e));
}
}, []);
usePoll(refreshWorker, 5000);
let host = '';
const remote = settings?.url || worker?.boot?.remote || '';
if (remote) {
try { host = new URL(remote).host; } catch { host = remote; }
}
return (
<Ctx.Provider value={{
settings, configured: !!settings?.configured, offline,
host: settings?.url ? new URL(settings.url).host : '', reload, connect,
settings, configured: !!settings?.configured, offline, error, host,
worker, workerError, reload, refreshWorker,
}}>
{children}
</Ctx.Provider>
@@ -65,3 +96,12 @@ export function usePoll(fn: () => void | Promise<unknown>, ms: number) {
return () => { alive = false; window.clearInterval(timer); document.removeEventListener('visibilitychange', vis); };
}, [fn, ms]);
}
/** Page-local view of the container's own status (GET /api/status), polled at a
* page's own cadence. Same hook as the shared stream — pages that need it
* faster than the shell's 5s (the Worker page) call this. */
export function useWorker(ms: number) {
const { worker, workerError, refreshWorker } = useContext(Ctx);
usePoll(refreshWorker, ms);
return { worker, error: workerError, refresh: refreshWorker };
}
+34 -11
View File
@@ -8,6 +8,11 @@ export const HEALTH_COLORS: Record<HealthState, string> = {
running: '#35e2ff', never: '#74879c',
};
// One word for a state, used where a dot needs a label.
export const HEALTH_WORDS: Record<HealthState, string> = {
ok: 'healthy', stale: 'stale', failed: 'failed', running: 'in flight', never: 'never',
};
export const RUN_COLORS: Record<string, string> = {
success: '#3dfca4', failure: '#ff5f6d', cancelled: '#74879c',
skipped: '#74879c', in_progress: '#35e2ff', queued: '#74879c',
@@ -22,21 +27,39 @@ export function runColor(status: string, conclusion: string | null): string {
return '#3dfca4';
}
const STALE_MS = 48 * 60 * 60 * 1000; // 48h — the runner is serial (maxParallel=1),
// so a queued mirror can wait a long time; 30m made everything yellow on churn.
// The worker gives a mirror three passes before it calls it unhealthy (same
// rule as /api/status totals.healthy: last success within 3× interval). One
// blipped pass never turns the console yellow. A missing/zero interval falls
// back to the container default cadence rather than to "instantly stale".
export const STALE_FACTOR = 3;
export const FALLBACK_INTERVAL_SEC = 600;
export function health(m: Mirror, runnerOnline: boolean | null): HealthState {
const r = m.lastSync;
if (!r) return 'never';
if (r.status === 'in_progress' || r.status === 'queued') return 'running';
if (r.conclusion === 'failure') return 'failed';
const age = Date.now() - new Date(r.updatedAt).getTime();
if (age > STALE_MS && runnerOnline === true) return 'stale';
export function staleAfterMs(m: Mirror): number {
const sec = m.intervalSec && m.intervalSec > 0 ? m.intervalSec : FALLBACK_INTERVAL_SEC;
return STALE_FACTOR * sec * 1000;
}
/** Worker health of one mirror — the container itself is the runner now, so
* there is no runner-online input: in flight > failed > stale > ok > never.
* `running` is the container's own lock and wins over the last run's data.
* A paused mirror (config `enabled: false`) is NOT a failure: the table shows
* a "paused" chip; the dot keeps reporting the last pass honestly. */
export function health(m: Mirror): HealthState {
if (m.running || m.lastSync?.status === 'in_progress' || m.lastSync?.status === 'queued') return 'running';
if (m.lastError || m.lastSync?.conclusion === 'failure') return 'failed';
const at = m.lastSync?.updatedAt;
if (!at) return 'never';
if (Date.now() - new Date(at).getTime() > staleAfterMs(m)) return 'stale';
return 'ok';
}
export function timeAgo(iso: string): string {
const s = Math.max(0, (Date.now() - new Date(iso).getTime()) / 1000);
export function timeAgo(iso: string | null | undefined): string {
// A first pass in flight has no timestamp yet: to_ui_mirror maps a missing
// `at` to null, so guard instead of printing "1970d ago".
if (!iso) return '—';
const t = new Date(iso).getTime();
if (Number.isNaN(t)) return '—';
const s = Math.max(0, (Date.now() - t) / 1000);
if (s < 60) return `${Math.floor(s)}s ago`;
if (s < 3600) return `${Math.floor(s / 60)}m ago`;
if (s < 86400) return `${Math.floor(s / 3600)}h ago`;
+188 -44
View File
@@ -1,10 +1,9 @@
import { useCallback, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Plus } from 'lucide-react';
import { Plus, Wand2, Check, X, RefreshCw } from 'lucide-react';
import { api } from '../api/client';
import type { Mirror } from '../api/types';
import { health } from '../lib/health';
import { HEALTH_COLORS } from '../lib/health';
import type { Mirror, AdoptResult } from '../api/types';
import { health, HEALTH_COLORS } from '../lib/health';
import { useApp, usePoll } from '../lib/app-context';
import {
Badge, StatCard, Btn, SkeletonRow,
@@ -18,21 +17,24 @@ import type { RowHandlers } from './dashboard/MirrorRows';
// Dashboard — Neon Ops Console.
// md+ : instrument table inside a framed panel (mono names, fork/origin
// URL stack, sparkline column).
// <md : compact mirror cards — the old table overflowed 815px at 390px;
// this switch keeps zero horizontal overflow (REWORK-CONTRACT rule 7).
// Glow appears ONLY on the primary CTA (Btn primary) and the Healthy stat
// number when every mirror is green. The row-hover bar is accent, no glow.
// <md : compact mirror cards — zero horizontal overflow at 390px.
// The health signal is the WORKER's own view of each mirror (in flight /
// stale after 3× the mirror's interval / failed / never), not a runner's
// online flag — the container does the syncing now.
// ============================================================================
type AdoptState = { busy: boolean; result: AdoptResult | null; error: string | null };
export default function Dashboard() {
const nav = useNavigate();
const { host, offline } = useApp();
const { host, offline, worker } = useApp();
const [mirrors, setMirrors] = useState<Mirror[] | null>(null);
const [err, setErr] = useState<string | null>(null);
const [loading, setLoading] = useState(true);
const [runnerOnline, setRunnerOnline] = useState<boolean | null>(null);
const [queued, setQueued] = useState(0);
const [syncing, setSyncing] = useState<string | null>(null);
const [recounting, setRecounting] = useState(false);
const [adopt, setAdopt] = useState<AdoptState>({ busy: false, result: null, error: null });
const [del, setDel] = useState<{ open: boolean; name: string }>({ open: false, name: '' });
const [delBusy, setDelBusy] = useState(false);
@@ -49,16 +51,8 @@ export default function Dashboard() {
}, []);
usePoll(load, 10000);
// runners: 15s poll — online = any runner.status === 'online'
const loadRunners = useCallback(async () => {
try {
const rs = await api.runners();
setRunnerOnline(rs.some((r) => r.status === 'online'));
} catch { /* keep last known value */ }
}, []);
usePoll(loadRunners, 15000);
// queue: 10s poll, best-effort (a queue failure must not wipe the table)
// queue: 10s poll, best-effort (a queue failure must not wipe the table).
// /api/status carries the same number; the queue endpoint gives the detail.
const loadQueue = useCallback(async () => {
try {
setQueued((await api.queue()).length);
@@ -69,8 +63,9 @@ export default function Dashboard() {
const reSync = async (name: string) => {
setSyncing(name);
try {
await api.dispatch(name, 'sync.yml');
toast('sync dispatched');
const r = await api.sync(name);
toast(r.queued || r.running ? `sync queued — ${name}` : `already scheduled — ${name}`,
r.queued || r.running ? 'ok' : 'error');
await Promise.all([load(), loadQueue()]);
} catch (e) {
toast((e as Error).message, 'error');
@@ -79,13 +74,43 @@ export default function Dashboard() {
}
};
// Hand recount of parity — the worker only recounts after a pass, so this is
// the on-demand escape hatch (it hits the network on both sides).
const recountAll = async () => {
setRecounting(true);
try {
setMirrors(await api.mirrors(true));
setErr(null);
toast('parity recounted');
} catch (e) {
toast((e as Error).message, 'error');
} finally {
setRecounting(false);
}
};
// Adopt mirrors that already exist on the Gitea (created by an earlier
// install or by hand) without deleting anything.
const runAdopt = async () => {
setAdopt({ busy: true, result: null, error: null });
try {
const res = await api.adopt();
setAdopt({ busy: false, result: res, error: null });
const n = res.adopted.length;
toast(n ? `adopted ${n} mirror${n > 1 ? 's' : ''}` : 'nothing to adopt', 'ok');
if (n) await load();
} catch (e) {
setAdopt({ busy: false, result: null, error: (e as Error).message });
}
};
const doDelete = async () => {
const name = del.name;
setDelBusy(true);
try {
await api.deleteMirror(name);
setDel({ open: false, name: '' });
toast(`deleted ${name}`);
toast(`deleted ${name} — the repo stays on the Gitea`);
await Promise.all([load(), loadQueue()]);
} catch (e) {
toast((e as Error).message, 'error');
@@ -95,9 +120,13 @@ export default function Dashboard() {
};
const n = mirrors?.length ?? 0;
const healthy = mirrors?.filter((m) => health(m, runnerOnline) === 'ok').length ?? 0;
const healthy = mirrors?.filter((m) => health(m) === 'ok').length ?? 0;
const assets = mirrors?.reduce((s, m) => s + (m.parity?.assets ?? 0), 0) ?? 0;
const allHealthy = !!mirrors && n > 0 && healthy === n;
// The worker's own totals agree with these numbers; while the mirror list is
// still loading, the status stream is the honest source.
const totals = worker?.totals;
const queuedTotal = worker?.scheduler?.queued ?? queued;
const h: RowHandlers = {
syncing,
@@ -106,38 +135,59 @@ export default function Dashboard() {
onDelete: (m) => setDel({ open: true, name: m.name }),
};
const workerDown = worker === null || !worker.ok;
return (
<div>
{offline && <div className="mb-4"><OfflineBanner /></div>}
{offline && <div className="mb-4"><OfflineBanner message="Worker unreachable — showing last cached state" /></div>}
{/* ---------- header: title + connection badge + primary CTA (stacks < sm) ---------- */}
{/* ---------- header: title + worker badge + primary CTA (stacks < sm) ---------- */}
<div className="flex flex-col gap-4 sm:flex-row sm:items-end sm:justify-between">
<div className="min-w-0">
<Label>Mirror console</Label>
<div className="mt-2 flex flex-wrap items-center gap-3">
<h1 className="text-[20px] font-bold leading-none tracking-tight text-text">Mirrors</h1>
<Badge dot={runnerOnline ? HEALTH_COLORS.ok : HEALTH_COLORS.never}>
<Badge dot={workerDown ? HEALTH_COLORS.failed : HEALTH_COLORS.ok}>
<span className="font-mono">{host || 'not connected'}</span>
</Badge>
<Badge color={workerDown ? HEALTH_COLORS.failed : HEALTH_COLORS.ok}
dot={workerDown ? HEALTH_COLORS.failed : HEALTH_COLORS.ok}>
{workerDown ? 'worker down' : 'worker online'}
</Badge>
</div>
</div>
{/* the page's one primary glow — taller touch target on mobile */}
<Btn variant="primary" onClick={() => nav('/new')} className="h-11 w-full shrink-0 sm:h-auto sm:w-auto">
<Plus size={16} strokeWidth={2} /> New mirror
</Btn>
<div className="flex shrink-0 items-center gap-2">
{/* the worker only recounts parity after a pass — this is the on-demand version */}
<Btn variant="secondary" className="h-11 w-full sm:h-auto sm:w-auto"
disabled={recounting || n === 0} onClick={() => void recountAll()}>
<RefreshCw size={16} strokeWidth={2} className={recounting ? 'animate-spin' : ''} />
{recounting ? 'Recounting…' : 'Recount parity'}
</Btn>
{/* the page's one primary glow — taller touch target on mobile */}
<Btn variant="primary" onClick={() => nav('/new')} className="h-11 w-full shrink-0 sm:h-auto sm:w-auto">
<Plus size={16} strokeWidth={2} /> New mirror
</Btn>
</div>
</div>
{/* ---------- adopt existing mirrors ---------- */}
<AdoptPanel state={adopt} onAdopt={() => void runAdopt()}
onDismiss={() => setAdopt({ busy: false, result: null, error: null })}
onOpen={(repo) => nav(`/mirrors/${encodeURIComponent(repo.split('/').pop() || repo)}`)} />
{/* ---------- stats: 2-col mobile / 4-col desktop ---------- */}
<div className="mt-4 grid grid-cols-2 gap-4 lg:grid-cols-4">
<StatCard label="Mirrors" value={mirrors ? n : '…'} sub="generated from template" />
<StatCard label="Mirrors" value={mirrors ? n : (totals ? totals.mirrors : '…')} sub="managed by this container" />
<StatCard
label="Healthy"
accent={allHealthy}
value={mirrors ? <>{healthy}<span className="text-[13px] font-normal text-muted">/{n}</span></> : '…'}
sub="last sync green < 48h"
value={mirrors
? <>{healthy}<span className="text-[13px] font-normal text-muted">/{n}</span></>
: totals ? <>{totals.healthy}<span className="text-[13px] font-normal text-muted">/{totals.mirrors}</span></> : '…'}
sub="last success < 3× interval"
/>
<StatCard label="Queued runs" value={queued} sub="serial runner (maxParallel=1)" />
<StatCard label="Assets mirrored" value={assets} sub="across all mirrors" />
<StatCard label="Queued" value={queuedTotal} sub={worker ? `worker slots ${worker.scheduler?.parallelism}` : 'in-flight work'} />
<StatCard label="Assets mirrored" value={mirrors ? assets : (totals ? totals.assets : '…')} sub="across all mirrors" />
</div>
{/* ---------- mirrors: framed panel — table md+ / card list <md ---------- */}
@@ -158,15 +208,23 @@ export default function Dashboard() {
) : mirrors && mirrors.length === 0 ? (
<EmptyState
title="No mirrors yet"
hint="Generate a mirror from the repo-forker template to track an upstream's branches, tags, releases and assets."
action={<Btn variant="primary" onClick={() => nav('/new')} className="h-11 w-full sm:h-auto sm:w-auto"><Plus size={16} strokeWidth={2} /> New mirror</Btn>}
hint="Create a mirror of any upstream repo, or adopt the mirrors this Gitea already has — nothing is deleted either way."
action={
<div className="flex flex-wrap items-center justify-center gap-2">
<Btn variant="primary" onClick={() => nav('/new')} className="h-11 w-full sm:h-auto sm:w-auto">
<Plus size={16} strokeWidth={2} /> New mirror
</Btn>
<Btn variant="secondary" className="h-11 w-full sm:h-auto sm:w-auto" disabled={adopt.busy}
onClick={() => void runAdopt()}>
<Wand2 size={16} strokeWidth={2} /> {adopt.busy ? 'Scanning…' : 'Adopt existing'}
</Btn>
</div>
}
/>
) : mirrors ? (
<>
{/* md+ : fixed-layout table — columns own their widths so long mono
names/URLs truncate and the Actions column never clips (128px
reserved for 3× IconBtn). Its own scroll region keeps the page
free of horizontal overflow below ~960px of content. */}
names/URLs truncate and the Actions column never clips. */}
<div className="hidden overflow-x-auto md:block">
<table className="w-full min-w-[960px] table-fixed text-[13px]">
<thead>
@@ -176,13 +234,13 @@ export default function Dashboard() {
<th className={`${TH} w-[13%]`}>Last sync</th>
<th className={`${TH} w-[7%]`}>Duration</th>
<th className={`${TH} w-[13%]`}>Parity</th>
<th className={`${TH} w-[8%]`}>7-day runs</th>
<th className={`${TH} w-[8%]`}>Recent runs</th>
<th className={`${TH} w-[14%] text-right`}>Actions</th>
</tr>
</thead>
<tbody>
{mirrors.map((m) => (
<MirrorRow key={m.name} m={m} st={health(m, runnerOnline)} h={h} />
<MirrorRow key={m.name} m={m} st={health(m)} h={h} />
))}
</tbody>
</table>
@@ -191,7 +249,7 @@ export default function Dashboard() {
{/* <md : compact mirror cards — same data, same actions */}
<div className="flex flex-col gap-3 p-3 md:hidden">
{mirrors.map((m) => (
<MirrorCard key={m.name} m={m} st={health(m, runnerOnline)} h={h} />
<MirrorCard key={m.name} m={m} st={health(m)} h={h} />
))}
</div>
</>
@@ -204,3 +262,89 @@ export default function Dashboard() {
</div>
);
}
// ---------------------------------------------------------------- Adopt
// Inline result panel for POST /api/adopt: what landed, what was skipped and
// WHY (the reason is the operator's next action, so it is never dropped).
function AdoptPanel({ state, onAdopt, onDismiss, onOpen }: {
state: AdoptState; onAdopt: () => void; onDismiss: () => void; onOpen: (repo: string) => void;
}) {
const { busy, result, error } = state;
const empty = !result || (result.adopted.length === 0 && result.skipped.length === 0);
if (!busy && !result && !error) {
return (
<div className="mt-4 flex flex-col gap-2 rounded-panel border border-border bg-panel px-4 py-3 sm:flex-row sm:items-center sm:justify-between">
<div className="min-w-0 text-[12px] leading-relaxed text-muted">
Mirrors that already exist on this Gitea (an earlier install, or created by hand) are not
managed until they are adopted. Adopting never deletes or rewrites a repo.
</div>
<Btn variant="secondary" className="shrink-0" onClick={onAdopt}>
<Wand2 size={14} strokeWidth={2} /> Adopt existing mirrors
</Btn>
</div>
);
}
return (
<div className="mt-4 rounded-panel border border-border bg-panel">
<header className="flex items-center justify-between gap-3 border-b border-border px-4 py-3">
<Label>Adopt existing mirrors</Label>
<span className="flex items-center gap-2">
{busy && <span className="font-mono text-[12px] text-accent">scanning…</span>}
{!busy && <Btn variant="ghost" className="h-8 px-2 py-0 text-[12px]" onClick={onDismiss}>
<X size={14} strokeWidth={2} /> Close
</Btn>}
</span>
</header>
<div className="flex flex-col gap-3 p-4">
{error && <ErrorInline message={error} onRetry={onAdopt} />}
{result && (
<>
{result.adopted.length > 0 && (
<div className="flex flex-col gap-1">
<div className="flex items-center gap-2 text-[12px] text-ok">
<Check size={14} strokeWidth={2} />
<span className="font-mono tabular">{result.adopted.length} adopted</span>
</div>
<ul className="flex flex-col divide-y divide-border">
{result.adopted.map((a) => (
<li key={a.repo} className="flex min-w-0 items-center gap-3 py-1.5">
<button type="button" onClick={() => onOpen(a.repo)}
className="focus-ring min-w-0 truncate rounded-ctl px-1 font-mono text-[13px] text-accent hover:underline"
title={a.repo}>
{a.repo}
</button>
<span className="min-w-0 flex-1 truncate text-right font-mono text-[12px] text-muted" title={a.upstream}>
{a.upstream}
</span>
</li>
))}
</ul>
</div>
)}
{result.skipped.length > 0 && (
<div className="flex flex-col gap-1">
<div className="flex items-center gap-2 text-[12px] text-warn">
<X size={14} strokeWidth={2} />
<span className="font-mono tabular">{result.skipped.length} skipped</span>
</div>
<ul className="flex flex-col divide-y divide-border">
{result.skipped.map((s) => (
<li key={s.repo} className="flex min-w-0 flex-col gap-0.5 py-1.5 sm:flex-row sm:items-baseline sm:gap-3">
<span className="shrink-0 font-mono text-[13px] text-text" title={s.repo}>{s.repo}</span>
<span className="min-w-0 flex-1 text-[12px] leading-snug text-muted" title={s.reason}>{s.reason}</span>
</li>
))}
</ul>
</div>
)}
{empty && (
<div className="text-[12px] text-muted">
Nothing to adopt — no repo on this Gitea looks like an unmanaged mirror.
</div>
)}
</>
)}
</div>
</div>
);
}
+154 -44
View File
@@ -1,54 +1,98 @@
import { useCallback, useEffect, useState } from 'react';
import type { ReactNode } from 'react';
import { Link, useNavigate, useParams } from 'react-router-dom';
import { RotateCw } from 'lucide-react';
import { RotateCw, Pause, Play } from 'lucide-react';
import {
Btn, StatusDot, ConfirmDialog, OfflineBanner, toast,
Btn, StatusDot, ConfirmDialog, OfflineBanner, Badge, toast,
} from '../components/primitives';
import { api } from '../api/client';
import { useApp } from '../lib/app-context';
import { health, HEALTH_COLORS } from '../lib/health';
import { fmtInterval, releasesManaged } from './format';
import { health, HEALTH_COLORS, HEALTH_WORDS } from '../lib/health';
import { useData } from './detail/useData';
import { RunHistoryPanel } from './detail/RunHistory';
import { LiveLogPanel } from './detail/LiveLog';
import { ParityPanel, ConfigPanel, VariablesPanel, UnitsPanel } from './detail/panels';
import { LiveLogPanel, runKey } from './detail/LiveLog';
import { ParityPanel, ConfigPanel, UpstreamPanel, UnitsPanel, ReleasesUnitBanner } from './detail/panels';
// ============================================================================
// Detail — the mirror's instrument page. Left: the pass history and the log of
// the selected pass. Right: parity, upstream (URL/token/interval/scheduling),
// .forker.yaml, units. Everything the Actions-era version did, without the
// workflow vocabulary: a "run" is one sync pass the container performed.
// ============================================================================
export default function Detail() {
const { name = '' } = useParams();
const navigate = useNavigate();
const { offline } = useApp();
const { offline, worker } = useApp();
const [busy, setBusy] = useState(false);
const [recounting, setRecounting] = useState(false);
const [confirmDel, setConfirmDel] = useState(false);
const [delBusy, setDelBusy] = useState(false);
const [delRepo, setDelRepo] = useState(false);
const mirrors = useData(() => api.mirrors(), 15000, `mirrors`);
const runs = useData(() => api.mirrorRuns(name, 12), 10000, `runs:${name}`);
const runs = useData(() => api.mirrorRuns(name), 10000, `runs:${name}`);
const config = useData(() => api.mirrorConfig(name), 15000, `cfg:${name}`);
const variables = useData(() => api.mirrorVariables(name), 15000, `vars:${name}`);
const mirror = mirrors.data?.find((m) => m.name === name) || null;
// header dot: mirror health color, default ok
const healthState = mirror ? health(mirror, null) : 'ok';
const healthState = mirror ? health(mirror) : 'never';
const dotColor = HEALTH_COLORS[healthState];
// A pass in flight: the mirror's own lock, or the container listing it as running.
const live = !!mirror?.running || (worker?.scheduler?.running?.includes(name) ?? false);
// Run selection shared by history + log: a picked run stays picked while it
// exists; otherwise follow the default (in-progress run, else most recent).
const [pinned, setPinned] = useState<number | null>(null);
// Log selection is a pass FILE (unique); the default follows the newest pass
// unless the operator pinned another one that still exists.
const [pinned, setPinned] = useState<string | null>(null);
useEffect(() => { setPinned(null); }, [name]);
const list = runs.data;
const defaultId = list && list.length > 0
? (list.find((r) => r.status === 'in_progress') || list[0]).id
: null;
const selectedId = pinned !== null && list?.some((r) => r.id === pinned) ? pinned : defaultId;
const defaultKey = list && list.length > 0 ? runKey(list[0]) : null;
const selected = pinned !== null && list?.some((r) => runKey(r) === pinned) ? pinned : defaultKey;
const dispatch = async (workflow: string, label: string) => {
const reSync = async () => {
setBusy(true);
try {
await api.dispatch(name, workflow);
toast(`${label} dispatched`);
setPinned(null); // jump the log to the new run once it appears
const r = await api.sync(name);
toast(r.queued || r.running ? 'sync queued' : 'already scheduled — nothing to queue',
r.queued || r.running ? 'ok' : 'error');
setPinned(null); // jump the log to the newest pass
await runs.refresh();
await mirrors.refresh();
} catch (e) {
toast(e instanceof Error ? e.message : String(e), 'error');
} finally {
setBusy(false);
}
};
const recount = async () => {
setRecounting(true);
try {
await api.refresh(name);
toast('parity recounted');
await mirrors.refresh();
} catch (e) {
toast(e instanceof Error ? e.message : String(e), 'error');
} finally {
setRecounting(false);
}
};
// Whether this mirror is supposed to publish releases at all — a refs-only
// mirror legitimately sits at 0/N releases; the parity panel says "not
// mirrored" instead of red "behind" (shared rule with the dashboard chips).
const releases = releasesManaged(mirror?.config);
// Pause/resume is just the `enabled` config key — written through /config so
// the remote .forker.yaml and the container's record cannot disagree.
const setEnabled = async (on: boolean) => {
setBusy(true);
try {
await api.saveMirrorConfig(name, { enabled: on });
toast(on ? 'scheduling enabled' : 'scheduling paused');
await mirrors.refresh();
await config.refresh();
} catch (e) {
toast(e instanceof Error ? e.message : String(e), 'error');
} finally {
@@ -59,19 +103,21 @@ export default function Detail() {
const doDelete = useCallback(async () => {
setDelBusy(true);
try {
await api.deleteMirror(name);
toast('mirror deleted');
await api.deleteMirror(name, delRepo);
toast(delRepo ? 'mirror and repo deleted' : 'mirror unmanaged — the repo stays on the Gitea');
navigate('/');
} catch (e) {
toast(e instanceof Error ? e.message : String(e), 'error');
setDelBusy(false);
setConfirmDel(false);
}
}, [name, navigate]);
}, [name, navigate, delRepo]);
const lc = mirror?.lastCounts;
return (
<div className="flex flex-col gap-4">
{offline && <OfflineBanner />}
{offline && <OfflineBanner message="Worker unreachable — showing last cached state" />}
{/* ---------------- header: identity + actions ---------------- */}
<div className="flex flex-col gap-4 xl:flex-row xl:items-start xl:justify-between">
@@ -84,6 +130,9 @@ export default function Detail() {
<div className="mt-2 flex flex-wrap items-center gap-x-3 gap-y-2">
<StatusDot color={dotColor} pulse={healthState === 'running'} />
<h1 className="font-mono text-[20px] font-bold leading-none tabular text-text">{name}</h1>
<Badge color={dotColor}>{HEALTH_WORDS[healthState]}</Badge>
{mirror && !mirror.enabled && <Badge>paused</Badge>}
{mirror && <Badge>every {fmtInterval(mirror.intervalSec)}</Badge>}
</div>
{/* both urls: fork = where it lives (accent), upstream = origin (muted) */}
<div className="mt-2 flex min-w-0 flex-col gap-1">
@@ -91,7 +140,7 @@ export default function Detail() {
<a href={mirror.forkUrl} target="_blank" rel="noreferrer"
className="inline-flex min-h-6 w-fit min-w-0 items-baseline gap-2 font-mono text-[13px] text-accent hover:underline"
title={mirror.forkUrl}>
<span className="shrink-0 text-[12px] uppercase tracking-[0.08em] text-dim">fork</span>
<span className="shrink-0 text-[12px] uppercase tracking-[0.08em] text-dim">mirror</span>
<span className="truncate">{mirror.forkUrl.replace(/^https?:\/\//, '')}</span>
</a>
)}
@@ -99,26 +148,54 @@ export default function Detail() {
<a href={mirror.upstream} target="_blank" rel="noreferrer"
className="inline-flex min-h-6 w-fit min-w-0 items-baseline gap-2 font-mono text-[13px] text-muted transition-colors duration-ctl hover:text-accent hover:underline"
title={mirror.upstream}>
<span className="shrink-0 text-[12px] uppercase tracking-[0.08em] text-dim">origin</span>
<span className="shrink-0 text-[12px] uppercase tracking-[0.08em] text-dim">upstream</span>
<span className="truncate">{mirror.upstream.replace(/^https?:\/\//, '').replace(/\.git$/, '')}</span>
</a>
)}
</div>
</div>
<div className="flex shrink-0 flex-wrap items-center gap-2">
<Btn variant="primary" disabled={busy} onClick={() => void dispatch('sync.yml', 're-sync')}>
<RotateCw size={14} strokeWidth={2} className={busy ? 'animate-spin' : ''} />
Re-sync
</Btn>
<Btn variant="secondary" disabled={busy} onClick={() => void dispatch('release.yml', 'release')}>
Run release
<Btn variant="primary" disabled={busy || live} onClick={() => void reSync()}>
<RotateCw size={14} strokeWidth={2} className={busy || live ? 'animate-spin' : ''} />
{live ? 'Sync in flight' : 'Re-sync'}
</Btn>
{mirror && (
<Btn variant="secondary" disabled={busy} onClick={() => void setEnabled(!mirror.enabled)}>
{mirror.enabled ? <Pause size={14} strokeWidth={2} /> : <Play size={14} strokeWidth={2} />}
{mirror.enabled ? 'Pause' : 'Resume'}
</Btn>
)}
<Btn variant="danger" onClick={() => setConfirmDel(true)}>Delete</Btn>
</div>
</div>
{/* ---------------- last-pass report + the two silent failures ---------------- */}
{mirror && <ReleasesUnitBanner m={mirror} />}
{mirror?.lastError && (
<div className="flex items-start gap-3 rounded-panel border border-danger/40 bg-danger/[0.06] px-4 py-3">
<span className="mt-[6px] h-2 w-2 shrink-0 rounded-full bg-danger" aria-hidden />
<div className="min-w-0">
<div className="text-[13px] font-medium text-danger">Last pass failed</div>
<pre className="m-0 mt-1 overflow-x-auto whitespace-pre-wrap font-mono text-[12px] text-danger/90">{mirror.lastError}</pre>
</div>
</div>
)}
{mirror && (lc?.branches != null || lc?.tags != null || lc?.releases.length || mirror.releaseFailures.length > 0) && (
<div className="grid grid-cols-2 gap-4 sm:grid-cols-4">
<Stat label="Branches pushed" value={lc?.branches ?? '—'} />
<Stat label="Tags pushed" value={lc?.tags ?? '—'} sub={lc?.pruned ? `${lc.pruned} pruned` : undefined} />
<Stat label="Releases published" value={lc?.releases.length ?? 0}
sub={lc && lc.releases.length > 0 ? lc.releases.slice(0, 3).join(' ') : undefined} />
<Stat label="Release failures" value={mirror.releaseFailures.length}
danger={mirror.releaseFailures.length > 0}
sub={mirror.releaseFailures[0]} />
</div>
)}
{/* ---------------- 60/40 console grid ----------------
Desktop: main (history + log) left, side (parity/config/vars/units)
Desktop: main (history + log) left, side (parity/upstream/config/units)
right. Mobile: stacked, identity/parity first. */}
<div className="grid grid-cols-1 gap-4 lg:grid-cols-[minmax(0,3fr)_minmax(0,2fr)] lg:items-start">
<div className="order-2 flex min-w-0 flex-col gap-4 lg:order-1">
@@ -128,7 +205,7 @@ export default function Detail() {
error={runs.error}
onRetry={runs.refresh}
name={name}
selectedId={selectedId}
selectedKey={selected}
onSelect={setPinned}
/>
<LiveLogPanel
@@ -137,8 +214,9 @@ export default function Detail() {
error={runs.error}
onRetry={runs.refresh}
name={name}
selectedId={selectedId}
selected={selected}
onSelect={setPinned}
live={live}
/>
</div>
@@ -148,6 +226,15 @@ export default function Detail() {
loading={mirrors.loading}
error={mirrors.error}
onRetry={mirrors.refresh}
onRecount={() => void recount()}
recounting={recounting}
releasesManaged={releases}
/>
<UpstreamPanel
m={mirror}
loading={mirrors.loading}
error={mirrors.error}
onRetry={mirrors.refresh}
/>
<ConfigPanel
parsed={config.data?.parsed ?? null}
@@ -156,17 +243,13 @@ export default function Detail() {
onRetry={config.refresh}
name={name}
/>
<VariablesPanel
items={variables.data}
loading={variables.loading}
error={variables.error}
onRetry={variables.refresh}
/>
<UnitsPanel
name={name}
units={mirror?.units ?? null}
loading={mirrors.loading}
error={mirrors.error}
onRetry={mirrors.refresh}
unitFix={mirror?.unitFix ?? null}
/>
</div>
</div>
@@ -175,9 +258,36 @@ export default function Detail() {
open={confirmDel}
name={name}
busy={delBusy}
message={
<>
This stops the container from syncing <span className="font-mono text-text">{mirror?.full || name}</span> —
its branches, tags and releases stay on the Gitea.
<label className="mt-3 flex cursor-pointer items-start gap-2 text-[13px] text-muted">
<input type="checkbox" checked={delRepo} onChange={(e) => setDelRepo(e.target.checked)}
className="mt-[3px] h-4 w-4 shrink-0 accent-accent" />
<span>
Also delete the repository on the Gitea
<span className="block text-[12px] text-danger">permanent — all refs, releases and assets go with it</span>
</span>
</label>
</>
}
onConfirm={() => void doDelete()}
onClose={() => setConfirmDel(false)}
onClose={() => { setConfirmDel(false); setDelRepo(false); }}
/>
</div>
);
}
// Last-pass stat: same shape as StatCard, denser, sized to sit under the header.
function Stat({ label, value, sub, danger }: { label: string; value: ReactNode; sub?: string; danger?: boolean }) {
return (
<div className="rounded-panel border border-border bg-panel p-3">
<div className="text-[12px] font-medium uppercase tracking-[0.08em] text-dim">{label}</div>
<div className={`mt-1 font-mono text-[20px] font-bold leading-none tabular ${danger ? 'text-danger' : 'text-text'}`}>
{value}
</div>
{sub && <div className="mt-1 truncate font-mono text-[12px] text-muted" title={sub}>{sub}</div>}
</div>
);
}
-246
View File
@@ -1,246 +0,0 @@
import { useCallback, useState } from 'react';
import { Clock } from 'lucide-react';
import {
Badge, EmptyState, ErrorInline, OfflineBanner, Panel, SkeletonRow, StatusDot,
} from '../components/primitives';
import { api } from '../api/client';
import type { QueueEntry, Runner } from '../api/types';
import { useApp, usePoll } from '../lib/app-context';
import { Label, Spinner, C } from './shared';
import { fmtSec, errMsg } from './format';
// ============================================================================
// Runner — console instrument panel.
// Identity card (live dot, mono name, state chips) → Queue as a live list →
// Runners list. Same endpoints / same poll cadence as before (queue 3s,
// runners 10s); presentation only. Stacks cleanly at 390px: every row is a
// two-line card below sm.
// ============================================================================
function StateChip({ status }: { status: QueueEntry['status'] }) {
return (
<span className="inline-flex shrink-0 items-center gap-1 rounded-pill border border-border bg-chip px-2 py-[2px] font-mono text-[12px] leading-4">
{status === 'in_progress' ? (
<span className="text-accent"><Spinner size={10} /></span>
) : (
<Clock size={11} strokeWidth={1.5} className="text-muted" />
)}
<span className={status === 'in_progress' ? 'text-accent' : 'text-muted'}>
{status === 'in_progress' ? 'in_progress' : 'queued'}
</span>
</span>
);
}
// Big live dot: ok + glow when online (a "live state" — glow is sanctioned
// here), plain danger when offline, matching the Shell runner pill.
function IdentityDot({ runner }: { runner: Runner | null }) {
const online = runner?.status === 'online';
return (
<span aria-hidden
className={`h-[10px] w-[10px] shrink-0 rounded-full ${online ? 'bg-ok glow-ok' : 'bg-danger'} ${
online && runner?.busy ? 'animate-breathe' : ''}`} />
);
}
function IdentityCard({ runner }: { runner: Runner | null }) {
const online = runner?.status === 'online';
return (
<Panel
title="Identity"
action={
<Badge color={runner ? (online ? C.ok : C.danger) : C.muted} dot={online ? C.ok : C.danger}>
{runner ? runner.status : 'offline'}
</Badge>
}
>
<div className="flex min-w-0 flex-wrap items-center gap-3">
<IdentityDot runner={runner} />
<span className="min-w-0 max-w-full truncate font-mono text-[16px] font-bold leading-tight text-text"
title={runner ? runner.name : undefined}>
{runner ? runner.name : 'no runner'}
</span>
{runner && (
runner.busy ? (
<Badge color={C.accent}><Spinner size={10} /> busy</Badge>
) : (
<Badge>idle</Badge>
)
)}
</div>
<div className="mt-4 flex flex-col gap-2 border-t border-border pt-4">
<div className="flex flex-wrap items-center gap-2">
<Label className="w-[104px] shrink-0">Scope</Label>
<Badge>
{runner ? (
<span className="block max-w-[180px] truncate" title={runner.repo || runner.type}>
{runner.type === 'repo' ? `repo: ${runner.repo || '?'}` : runner.type}
</span>
) : '—'}
</Badge>
<Label className="w-[104px] shrink-0 sm:ml-2">Concurrency</Label>
<Badge color={C.accent}>1</Badge>
<span className="text-[12px] text-muted">serial runner (maxParallel=1) — jobs run one at a time</span>
</div>
<div className="flex flex-wrap items-center gap-2">
<Label className="w-[104px] shrink-0">Labels</Label>
{runner && runner.labels.length > 0 ? (
<span className="flex min-w-0 flex-wrap gap-1">
{runner.labels.map((l) => <Badge key={l}>{l}</Badge>)}
</span>
) : (
<span className="font-mono text-[12px] text-dim">—</span>
)}
</div>
{!runner && (
<div className="text-[12px] text-muted">No runner reported by the API — jobs will queue until one connects.</div>
)}
</div>
</Panel>
);
}
function QueueRow({ q, index }: { q: QueueEntry; index: number }) {
const running = q.status === 'in_progress';
return (
<li className="flex flex-col gap-1.5 border-b border-border px-4 py-3 transition-colors duration-ctl last:border-b-0 hover:bg-panel2/60 sm:flex-row sm:items-center sm:gap-3">
<div className="flex min-w-0 flex-1 items-center gap-2.5">
<span className="w-5 shrink-0 font-mono text-[12px] tabular text-dim">{String(index + 1).padStart(2, '0')}</span>
<StatusDot color={running ? C.accent : C.dim} pulse={running} />
<span className="min-w-0 flex-1 truncate font-mono text-[13px] text-text" title={q.repo}>{q.repo}</span>
<span className="shrink-0 font-mono text-[12px] tabular text-muted">#{q.runId}</span>
</div>
<div className="flex min-w-0 items-center gap-2 pl-[30px] sm:pl-0">
<StateChip status={q.status} />
<Badge><span className="block max-w-[150px] truncate" title={q.event}>{q.event}</span></Badge>
<span className="ml-auto shrink-0 font-mono text-[12px] tabular text-muted sm:w-[110px] sm:text-right"
title={running ? `running ${fmtSec(q.waitedSec)}` : `${fmtSec(q.waitedSec)} waited`}>
{running ? `running ${fmtSec(q.waitedSec)}` : `${fmtSec(q.waitedSec)} waited`}
</span>
</div>
</li>
);
}
function RunnerRow({ r }: { r: Runner }) {
const online = r.status === 'online';
return (
<li className={`flex flex-col gap-2 border-b border-border px-4 py-3 transition-colors duration-ctl last:border-b-0 hover:bg-panel2/60 sm:flex-row sm:items-center sm:gap-4 ${
online ? '' : 'opacity-50'}`}>
<div className="flex min-w-0 flex-1 items-center gap-2.5">
<StatusDot color={online ? C.ok : C.danger} pulse={online && r.busy} />
<span className="min-w-0 truncate font-mono text-[13px] text-text" title={r.name}>{r.name}</span>
</div>
<div className="flex min-w-0 flex-wrap items-center gap-1.5 pl-[30px] sm:flex-nowrap sm:pl-0">
<Badge dot={online ? C.ok : C.danger}>{r.status}</Badge>
<Badge>
<span className="block max-w-[180px] truncate" title={r.repo || r.type}>
{r.type === 'repo' ? `repo: ${r.repo || '?'}` : r.type}
</span>
</Badge>
<span className="inline-flex shrink-0 items-center gap-2">
<span className="font-mono text-[12px] tabular text-muted">{r.busy ? '1/1' : 'idle'}</span>
{r.busy && (
<span className="inline-block h-[3px] w-16 overflow-hidden rounded-pill bg-panel2" aria-hidden>
<span className="block h-full w-1/2 animate-breathe rounded-pill bg-accent" />
</span>
)}
</span>
<span className="flex min-w-0 flex-wrap gap-1">
{r.labels.map((l) => <Badge key={l}>{l}</Badge>)}
</span>
</div>
</li>
);
}
export default function RunnerView({ runner }: { runner: Runner | null }) {
const { offline } = useApp();
const [queue, setQueue] = useState<QueueEntry[] | null>(null);
const [runners, setRunners] = useState<Runner[] | null>(null);
const [err, setErr] = useState('');
const loadQueue = useCallback(async () => {
try {
setQueue(await api.queue());
setErr('');
} catch (e) {
setErr(errMsg(e));
}
}, []);
const loadRunners = useCallback(async () => {
try {
setRunners(await api.runners());
} catch (e) {
setErr(errMsg(e));
}
}, []);
usePoll(loadQueue, 3000);
usePoll(loadRunners, 10000);
const running = queue?.some((q) => q.status === 'in_progress') ?? false;
return (
<div className="flex min-w-0 flex-col gap-[16px]">
{offline && <OfflineBanner />}
<h1 className="text-[16px] font-semibold leading-none text-text">Runner</h1>
{err && <ErrorInline message={err} onRetry={() => { void loadQueue(); void loadRunners(); }} />}
<IdentityCard runner={runner} />
<Panel
title="Queue"
action={
queue === null ? undefined : (
<Badge color={queue.length ? (running ? C.accent : C.text) : undefined}>
<span className="tabular">{queue.length}</span>
</Badge>
)
}
>
{queue === null ? (
<div>
<SkeletonRow />
<SkeletonRow />
</div>
) : queue.length === 0 ? (
<EmptyState title="queue clear" hint="No runs waiting — the runner is idle and mirrors sync on their cron." />
) : (
<ul className="-m-4 list-none">
{queue.map((q, i) => <QueueRow key={q.runId} q={q} index={i} />)}
</ul>
)}
</Panel>
<Panel
title="Runners"
action={
runners === null ? undefined : (
<Badge color={runners.some((r) => r.status === 'online') ? C.ok : undefined}>
<span className="tabular">{runners.filter((r) => r.status === 'online').length}</span>
<span className="text-muted">/{runners.length}</span>
<span>online</span>
</Badge>
)
}
>
{runners === null ? (
<div>
<SkeletonRow />
<SkeletonRow />
</div>
) : runners.length === 0 ? (
<EmptyState title="no runners registered" hint="Register an act_runner on this Gitea — see runner/docker-compose.yml." />
) : (
<ul className="-m-4 list-none">
{runners.map((r) => <RunnerRow key={r.id} r={r} />)}
</ul>
)}
</Panel>
</div>
);
}
+193 -82
View File
@@ -1,19 +1,20 @@
import { useEffect, useState } from 'react';
import { useCallback, useState } from 'react';
import type { ReactNode } from 'react';
import { Copy, ExternalLink } from 'lucide-react';
import { Copy, ExternalLink, Lock, Terminal } from 'lucide-react';
import {
Badge, Btn, ErrorInline, IconBtn, OfflineBanner, Panel, SkeletonRow, toast,
} from '../components/primitives';
import { api } from '../api/client';
import { useApp } from '../lib/app-context';
import { Label, MonoInput, C } from './shared';
import { Label, C } from './shared';
import { fmtInterval, errMsg } from './format';
// ============================================================================
// Settings — console read-out panels. Connection / Template rows are mono
// value read-outs with an 11px uppercase micro-label; secrets stay write-only
// (the token field exists only in the not-configured state, as before).
// Same endpoints, same flow: /api/health for the version, connect via the
// app context. Presentation only.
// Settings — the container's environment read-out. There is no connection form
// any more: REMOTE + TOKEN are environment variables and the token never leaves
// the process, so the only thing the UI may change at runtime is the sync
// interval (POST /api/settings {interval}). Everything else is read-only and
// says so.
// ============================================================================
function CopyValue({ value, mono = true, copy = true }: { value: string; mono?: boolean; copy?: boolean }) {
@@ -49,116 +50,218 @@ function ReadRow({ label, children }: { label: string; children: ReactNode }) {
);
}
export default function Settings() {
const { settings, configured, offline, connect } = useApp();
const [version, setVersion] = useState('');
const [url, setUrl] = useState(settings?.url || '');
const [token, setToken] = useState('');
// A locked env-driven value: the var name is the useful part, since that is
// what an operator edits (and then restarts the container).
function EnvValue({ env, value, secret }: { env: string; value?: string | null; secret?: boolean }) {
return (
<span className="inline-flex min-w-0 flex-wrap items-center gap-2">
<span className="inline-flex shrink-0 items-center gap-1.5 rounded-pill border border-border bg-chip px-2 py-[2px] font-mono text-[12px] text-muted"
title={`environment variable ${env}`}>
<Terminal size={11} strokeWidth={1.5} />{env}
</span>
{secret ? (
<span className="inline-flex items-center gap-1.5 font-mono text-[13px] text-muted"
title="the token is held by the container and never returned by the API">
<Lock size={12} strokeWidth={1.5} />••••••••••••
<span className="text-[12px] text-dim">supplied by the environment</span>
</span>
) : value ? (
<CopyValue value={value} />
) : (
<span className="font-mono text-[13px] text-dim">unknown</span>
)}
</span>
);
}
const inputCls =
'focus-ring w-full min-w-0 rounded-ctl border border-border2 bg-panel2 px-3 py-2 font-mono text-[13px] text-text ' +
'placeholder:text-dim transition-colors duration-ctl focus:outline-none';
// The single editable field, with real validation before it is sent.
function IntervalEditor({ current, onSaved }: { current: number; onSaved: () => void }) {
const [draft, setDraft] = useState(String(current));
const [busy, setBusy] = useState(false);
const [err, setErr] = useState('');
const [err, setErr] = useState<string | null>(null);
const [saved, setSaved] = useState(false);
// gitea version is not part of /api/settings — pull it from /api/health
useEffect(() => {
let alive = true;
if (!configured) { setVersion(''); return; }
api.health()
.then((h) => { if (alive) setVersion(h.gitea ? h.gitea.version : ''); })
.catch(() => { if (alive) setVersion(''); });
return () => { alive = false; };
}, [configured, settings]);
const dirty = draft.trim() !== String(current);
const parsed = Number(draft.trim());
const valid = /^\d+$/.test(draft.trim()) && Number.isInteger(parsed) && parsed >= 30 && parsed <= 86400;
const doConnect = async () => {
const save = useCallback(async () => {
setBusy(true);
setErr('');
const ok = await connect(url.trim(), token.trim());
setBusy(false);
if (!ok) { setErr('Connection failed — check the URL and token.'); return; }
const s = await api.settings().catch(() => null);
toast(`connected as ${s?.user || 'user'}`);
setToken('');
};
setErr(null);
setSaved(false);
try {
await api.saveSettings(parsed);
setSaved(true);
toast(`sync interval set to ${fmtInterval(parsed)}`);
onSaved();
} catch (e) {
setErr(errMsg(e));
} finally {
setBusy(false);
}
}, [parsed, onSaved]);
return (
<div className="flex flex-col gap-3">
<div className="flex flex-wrap items-center gap-3">
<input
value={draft}
onChange={(e) => { setDraft(e.target.value); setSaved(false); setErr(null); }}
inputMode="numeric"
aria-label="Sync interval in seconds"
className={`${inputCls} max-w-[160px]`}
/>
<span className="font-mono text-[13px] tabular text-muted">
seconds {valid ? <span className="text-text">· {fmtInterval(parsed)} between passes</span> : ''}
</span>
<span className="ml-auto flex items-center gap-2">
{saved && <span className="font-mono text-[12px] text-ok">saved</span>}
<Btn variant="primary" disabled={!valid || !dirty || busy} onClick={() => void save()}>
{busy ? 'Saving…' : 'Save'}
</Btn>
</span>
</div>
{!valid && draft.trim() !== '' && (
<div className="text-[12px] leading-snug text-warn">
Whole seconds between 30 and 86400 (1 day). The worker clamps anything lower to 30.
</div>
)}
{err && <ErrorInline message={err} onRetry={() => void save()} />}
<div className="max-w-[68ch] text-[12px] leading-relaxed text-muted">
Applies to mirrors whose <span className="font-mono text-text">sync_interval</span> is 0 (inherit). It lives in
the running process, so a container restart goes back to the{' '}
<span className="font-mono text-text">INTERVAL</span> environment variable.
</div>
</div>
);
}
export default function Settings() {
const { settings, offline, worker, reload, refreshWorker } = useApp();
const boot = worker?.boot;
const version = settings?.version || boot?.gitea_version || '';
const owner = settings?.user || boot?.owner || '';
const template = settings?.template || boot?.template || '';
const interval = settings?.intervalSec ?? worker?.scheduler?.interval_sec ?? 0;
const isAdmin = settings?.tokenIsAdmin ?? boot?.is_admin;
return (
<div className="flex w-full min-w-0 max-w-[640px] flex-col gap-[16px]">
{offline && <OfflineBanner />}
{offline && <OfflineBanner message="Worker unreachable — showing last cached state" />}
<h1 className="text-[16px] font-semibold leading-none text-text">Settings</h1>
<div className="flex flex-wrap items-end justify-between gap-3">
<h1 className="text-[20px] font-bold leading-none tracking-tight text-text">Settings</h1>
<Badge color={C.dim}><Lock size={11} strokeWidth={1.5} />managed by environment</Badge>
</div>
{/* Gitea connection */}
{/* Gitea connection — read-only */}
<Panel
title="Gitea connection"
action={
settings !== null && (
configured
? <Badge color={C.ok} dot={C.ok}>connected</Badge>
: <Badge color={C.danger} dot={C.danger}>not connected</Badge>
)
}
action={settings !== null && <Badge color={C.ok} dot={C.ok}>connected</Badge>}
>
{settings === null ? (
{settings === null && !worker ? (
<div className="-mx-4 -mb-4">
<SkeletonRow />
<SkeletonRow />
</div>
) : configured ? (
) : (
<div className="flex flex-col">
<ReadRow label="Base URL">
<CopyValue value={settings.url} />
<ReadRow label="REMOTE">
<EnvValue env="REMOTE" value={settings?.url || boot?.remote} />
</ReadRow>
<ReadRow label="User">
<CopyValue value={settings.user || '—'} copy={!!settings.user} />
<ReadRow label="TOKEN">
<EnvValue env="TOKEN" secret />
</ReadRow>
<ReadRow label="Owner">
{owner ? <CopyValue value={owner} /> : <span className="font-mono text-[13px] text-dim">unknown</span>}
</ReadRow>
<ReadRow label="Gitea version">
{version
? <span className="font-mono text-[13px] tabular text-muted">{version}</span>
: <span className="font-mono text-[13px] text-dim">—</span>}
</ReadRow>
<ReadRow label="Credentials">
<ReadRow label="Token scope">
{isAdmin === undefined
? <span className="font-mono text-[13px] text-dim">unknown</span>
: isAdmin
? <Badge color={C.ok} dot={C.ok}>admin</Badge>
: <Badge color={C.warn} dot={C.warn}>non-admin</Badge>}
<span className="ml-2 text-[12px] text-muted">
{isAdmin === false
? 'the Releases-unit self-heal and workflow disabling need admin'
: 'the container can enable repo units and disable upstream workflows'}
</span>
</ReadRow>
<ReadRow label="Managed by">
<span className="text-[12px] leading-relaxed text-muted">
Stored in <span className="font-mono text-text">~/.repo-forker/credentials</span> (chmod 600).
Never uploaded; only sent to the Gitea base URL.
{settings?.tokenSource || 'REMOTE/TOKEN environment variables'}. There is no field for a token
in this UI: change the variables and restart the container. Nothing secret is stored by the app.
</span>
</ReadRow>
</div>
)}
</Panel>
{/* Runtime — the one editable thing */}
<Panel title="Sync runtime">
{settings === null && !worker ? (
<div className="-mx-4 -mb-4"><SkeletonRow /></div>
) : (
<div className="flex flex-col gap-[12px]">
<div>
<Label className="mb-[6px]">Gitea base URL</Label>
<MonoInput value={url} onChange={(e) => setUrl(e.target.value)} placeholder="https://git.lago.dev" spellCheck={false} />
</div>
<div>
<Label className="mb-[6px]">Token</Label>
<MonoInput value={token} onChange={(e) => setToken(e.target.value)} type="password" placeholder="Gitea token" spellCheck={false} />
</div>
{err && <ErrorInline message={err} onRetry={doConnect} />}
<div className="flex flex-col-reverse items-stretch gap-[12px] sm:flex-row sm:items-center sm:justify-between">
<div className="text-[12px] leading-relaxed text-muted">
Stored in <span className="font-mono">~/.repo-forker/credentials</span> (chmod 600).
Never uploaded; only sent to the Gitea base URL.
</div>
<Btn variant="primary" className="shrink-0"
disabled={!url.trim() || !token.trim() || busy} onClick={doConnect}>
{busy ? 'Connecting…' : 'Connect'}
</Btn>
</div>
<IntervalEditor current={interval} onSaved={() => { void reload(); void refreshWorker(); }} />
)}
{worker && worker.scheduler.interval_sec > 0
&& (worker.scheduler.effective_interval_sec ?? worker.scheduler.interval_sec) > worker.scheduler.interval_sec && (
<div className="mt-3 rounded-ctl border border-border2 bg-panel2/60 px-3 py-2 text-[12px] leading-relaxed text-muted">
<span className="font-mono text-text">
auto-pace: running at {fmtInterval(worker.scheduler.effective_interval_sec ?? worker.scheduler.interval_sec)}
</span>{' '}
— the plan keeps anonymous GitHub API use inside{' '}
{worker.scheduler.auto_pace
? <>~{worker.scheduler.auto_pace.est_calls_per_hour}/h of {worker.scheduler.auto_pace.budget_per_hour} </>
: ''}
(80% of GitHub’s 60/h window, the rest is left for manual triggers). INTERVAL stays a floor: it is
honored whenever it is already safe. Mirrors pinned with <span className="font-mono text-text">sync_interval</span>{' '}
or carrying their own token never enter the plan.
</div>
)}
{worker && (
<div className="mt-4 flex flex-col border-t border-border pt-3">
<ReadRow label="Parallelism">
<Badge color={C.accent}>{worker.scheduler.parallelism}</Badge>
<span className="ml-2 text-[12px] text-muted">
fixed at boot — set <span className="font-mono">PARALLELISM</span> and restart
</span>
</ReadRow>
<ReadRow label="Data dir">
{settings?.dataDir || worker.settings.data_dir
? <CopyValue value={settings?.dataDir || worker.settings.data_dir || ''} />
: <span className="font-mono text-[13px] text-dim">—</span>}
<span className="ml-2 text-[12px] text-muted">mirror caches, run logs, state (chmod 600)</span>
</ReadRow>
</div>
)}
</Panel>
{/* Template */}
<Panel title="Template">
{settings === null ? (
{settings === null && !worker ? (
<div className="-mx-4 -mb-4"><SkeletonRow /></div>
) : (
<div className="flex flex-col">
<ReadRow label="Mirror template">
<span className="inline-flex min-w-0 items-center gap-2">
<CopyValue value={settings.template || '—'} copy={!!settings.template} />
{template ? <CopyValue value={template} copy={!!template} /> : <span className="font-mono text-[13px] text-dim">—</span>}
<Badge>locked</Badge>
</span>
</ReadRow>
<div className="pt-3 text-[12px] leading-relaxed text-muted sm:pt-2.5">
all mirrors are generated from this repo; it never appears in the mirror list
the <span className="font-mono text-text">forker</span> branch this container copies into every new
mirror; it never appears in the mirror list
</div>
</div>
)}
@@ -167,15 +270,23 @@ export default function Settings() {
{/* About */}
<Panel title="About">
<div className="max-w-[60ch] text-[13px] leading-[1.6] text-muted">
Repo Forker turns a template repo into live mirrors: each generated fork mirrors an
upstream git repo (branches, tags, full history) and builds releases on a Gitea
Actions runner.
Repo Forker runs as one container: a scheduler that mirrors upstream repos onto your Gitea
(branches, tags, full history) and publishes releases per tag, plus this console. There is no
runner and no CI pipeline — the container holds the git objects, the logs and the credentials.
</div>
<a href="https://git.lago.dev/Lago/repo-forker" target="_blank" rel="noreferrer"
className="focus-ring mt-[12px] inline-flex min-h-[34px] items-center gap-1.5 rounded-ctl px-1 text-[13px] font-medium text-accent transition-colors duration-ctl hover:text-accdim hover:underline">
<ExternalLink size={14} strokeWidth={1.5} />
repo-forker on Gitea
</a>
<div className="mt-[12px] max-w-[60ch] text-[12px] leading-relaxed text-muted">
Because <span className="font-mono text-text">build_cmd</span> and{' '}
<span className="font-mono text-text">build_script</span> run inside this container with its token in
scope, anyone who can push to a mirror’s <span className="font-mono text-text">forker</span> branch can
run commands here. Publish the port to localhost, or front it with auth.
</div>
{boot?.remote && (
<a href={`${boot.remote.replace(/\/$/, '')}`} target="_blank" rel="noreferrer"
className="focus-ring mt-[12px] inline-flex min-h-[34px] items-center gap-1.5 rounded-ctl px-1 text-[13px] font-medium text-accent transition-colors duration-ctl hover:text-accdim hover:underline">
<ExternalLink size={14} strokeWidth={1.5} />
open {boot.remote.replace(/^https?:\/\//, '')}
</a>
)}
</Panel>
</div>
);
+170 -56
View File
@@ -1,15 +1,18 @@
import { Fragment, useRef, useState } from 'react';
import { Fragment, useCallback, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Check, X } from 'lucide-react';
import { Check, X, KeyRound } from 'lucide-react';
import { Btn, ErrorInline, OfflineBanner, Panel, StatusDot, Toggle } from '../components/primitives';
import { api } from '../api/client';
import { BOOLEAN_CONFIG_KEYS, KNOWN_CONFIG_KEYS } from '../api/types';
import type { FlatConfig } from '../api/types';
import { useApp } from '../lib/app-context';
import { BOOLEAN_CONFIG_KEYS, CREATE_STEPS, KNOWN_CONFIG_KEYS } from '../api/types';
import type { CreateMirrorStep, FlatConfig } from '../api/types';
import { useApp, usePoll } from '../lib/app-context';
import { C, Label, MonoInput, Spinner } from './shared';
import { deriveName, errMsg } from './format';
import { deriveName, errMsg, fmtInterval } from './format';
// The container's defaults (config.py CONFIG_DEFAULTS), minus sync_interval,
// which the form sends explicitly.
const DEFAULTS: FlatConfig = {
enabled: true,
mirror_branches: '*',
mirror_tags: true,
mirror_prune: true,
@@ -20,23 +23,30 @@ const DEFAULTS: FlatConfig = {
artifacts: '',
};
// The 5 fixed creation steps (DESIGN.md page 3). The server resolves the
// createMirror call when the whole sequence is done, so completion is
// revealed step by step as the call settles.
const STEP_NAMES = ['generate', 'variable', 'default-branch', 'config', 'first-sync'] as const;
// The worker's fixed creation sequence — these strings come from
// registry.create()/api.py, so the wizard labels match the server's step names.
const STEP_LABELS: Record<string, string> = {
'create-repo': 'repo created on the Gitea',
'forker-branch': 'forker branch + .forker.yaml',
'config': 'per-mirror config applied',
'default-branch': 'default branch set to upstream’s',
'first-sync': 'first sync pass',
};
type WizStep = { name: string; status: 'ok' | 'error' | 'pending' };
type Phase = 'form' | 'creating' | 'done' | 'error';
type WizStep = { name: string; status: 'ok' | 'error' | 'pending' | 'running'; detail?: string };
type Phase = 'form' | 'creating' | 'watching' | 'done' | 'error';
const isBool = (k: string) => (BOOLEAN_CONFIG_KEYS as readonly string[]).includes(k);
// 12px row descriptions for the config grid (mirrors README's config table).
// 12px row descriptions for the config grid.
const CONFIG_HINTS: Record<string, string> = {
enabled: 'Let the worker schedule this mirror (off = created but paused)',
mirror_branches: '"*" = all branches, or a comma-separated list',
mirror_tags: 'Mirror every upstream tag',
mirror_prune: 'Delete mirror branches upstream removed',
mirror_upstream_releases: 'Also copy upstream releases and their assets',
on_new_tag: 'Build + publish a release when a new tag lands',
sync_interval: 'Seconds between passes for THIS mirror (0 = container default)',
build_cmd: 'Commands run in the tag tree to build assets',
build_script: 'Custom build script path — overrides build_cmd',
artifacts: 'Space-separated globs of files to attach to releases',
@@ -47,13 +57,14 @@ const CONFIG_PLACEHOLDERS: Record<string, string> = {
build_cmd: 'make && go build -o dist/app .',
build_script: 'forker/build-custom.sh',
artifacts: 'dist/*',
sync_interval: '0',
};
// ---- Console ribbon: 3 nodes on a hairline. Completed = ok ring + check,
// current = accent ring + glow (the sanctioned "you are here" glow),
// pending = border2 + dim. Numbers in mono.
function StepRibbon({ step }: { step: number }) {
const labels = ['Upstream', 'Config', 'Progress'];
const labels = ['Upstream', 'Config', 'Create'];
return (
<div className="flex items-start" role="group" aria-label="Setup progress">
{labels.map((label, i) => {
@@ -85,20 +96,30 @@ function StepRibbon({ step }: { step: number }) {
}
export default function Wizard() {
const { offline } = useApp();
const { offline, settings } = useApp();
const navigate = useNavigate();
const [step, setStep] = useState(1);
const [url, setUrl] = useState('');
const [name, setName] = useState('');
const [config, setConfig] = useState<FlatConfig>({ ...DEFAULTS });
const [token, setToken] = useState('');
const [config, setConfig] = useState<FlatConfig>({ ...DEFAULTS, sync_interval: 0 });
const [phase, setPhase] = useState<Phase>('form');
const [steps, setSteps] = useState<WizStep[]>([]);
const [repo, setRepo] = useState('');
// The worker derives the name itself when the field is empty (its rules
// differ from the preview above), so watch the name it actually used.
const [watchName, setWatchName] = useState('');
const [err, setErr] = useState('');
const [watchNote, setWatchNote] = useState('');
const startedRef = useRef(false);
const valid = /^https?:\/\/.+/.test(url);
const owner = settings?.user || '';
const valid = /^https?:\/\/.+/.test(url.trim());
const finalName = name.trim() || deriveName(url);
const target = owner ? `${owner}/${finalName}` : finalName;
const intervalDraft = String(config.sync_interval ?? 0);
const setField = (k: string, v: string | boolean | number) => setConfig((c) => ({ ...c, [k]: v }));
const start = async () => {
if (startedRef.current) return;
@@ -106,32 +127,79 @@ export default function Wizard() {
setStep(3);
setPhase('creating');
setErr('');
setSteps(STEP_NAMES.map((n) => ({ name: n, status: 'pending' as const })));
setWatchNote('');
setSteps(CREATE_STEPS.map((n) => ({ name: n, status: 'pending' as const })));
// sync_interval/enabled ride along in the config; the token is its own
// field because it is a secret stored in the container, not in the repo.
const body: { upstream: string; name?: string; token?: string; config: FlatConfig } = {
upstream: url.trim(),
name: name.trim() || undefined,
config,
};
if (token.trim()) body.token = token.trim();
try {
const r = await api.createMirror(url, name.trim() || undefined, config);
const server = r.steps.length
const r = await api.createMirror(body);
const server: CreateMirrorStep[] = r.steps.length
? r.steps
: STEP_NAMES.map((n, i) => ({
name: n,
status: r.ok ? ('ok' as const) : (i === STEP_NAMES.length - 1 ? ('error' as const) : ('pending' as const)),
}));
let i = 0;
const t = window.setInterval(() => {
i += 1;
setSteps((prev) => prev.map((s, j) => (j < i ? { ...s, status: server[j]?.status ?? s.status } : s)));
if (i >= server.length) {
window.clearInterval(t);
if (r.ok) { setRepo(r.repo || `Lago/${finalName}`); setPhase('done'); }
else { setErr(r.error || 'create failed'); setPhase('error'); }
}
}, 350);
: CREATE_STEPS.map((n) => ({ name: n, status: r.ok ? 'ok' : 'pending' }));
// The server appends first-sync as ok/"queued" because the pass is only
// enqueued; until the watcher proves otherwise that step is running, not done.
setSteps(server.map((s) => ({
name: s.name,
status: s.status === 'error' ? 'error'
: s.name === 'first-sync' && s.detail === 'queued' ? 'running'
: 'ok',
detail: s.detail,
})));
if (!r.ok) {
setErr(r.error || 'the worker did not report ok');
setPhase('error');
return;
}
const created = (r.repo || target).split('/').pop() || finalName;
setRepo(r.repo || target);
setWatchName(created);
// The first pass runs in the background — watch the mirror itself rather
// than pretending the HTTP call covered it.
setPhase('watching');
setWatchNote('queued');
} catch (e) {
setSteps(STEP_NAMES.map((n, j) => ({ name: n, status: j === 0 ? ('error' as const) : ('pending' as const) })));
setSteps((prev) => prev.map((s, i) => (i === 0 && s.status === 'pending' ? { ...s, status: 'error' } : s)));
setErr(errMsg(e));
setPhase('error');
}
};
// While the first pass runs, poll the new mirror (the same 10s cadence the
// dashboard uses; 5s here because this screen is about exactly one mirror).
const watch = useCallback(async () => {
if (phase !== 'watching') return;
try {
const m = await api.mirror(watchName || finalName);
if (m.running) {
setWatchNote('running');
setSteps((prev) => prev.map((s) => (s.name === 'first-sync' ? { ...s, status: 'running' } : s)));
return;
}
if (m.lastSync) {
if (m.lastSync.conclusion === 'failure') {
setSteps((prev) => prev.map((s) => (s.name === 'first-sync' ? { ...s, status: 'error' } : s)));
setErr(m.lastError || 'the first sync pass failed');
setPhase('error');
} else {
setSteps((prev) => prev.map((s) => (s.name === 'first-sync' ? { ...s, status: 'ok' } : s)));
setPhase('done');
}
return;
}
setWatchNote('queued');
} catch {
// not visible in the registry yet — keep waiting; a failed poll is not
// a creation failure, the create call already answered ok.
}
}, [phase, finalName, watchName]);
usePoll(watch, phase === 'watching' ? 5000 : 600000);
const retry = () => {
startedRef.current = false;
setStep(1);
@@ -139,11 +207,13 @@ export default function Wizard() {
setErr('');
setSteps([]);
setRepo('');
setWatchName('');
setWatchNote('');
};
const activeIdx =
phase === 'creating' && !steps.some((s) => s.status === 'error')
? steps.findIndex((s) => s.status === 'pending')
(phase === 'creating' || phase === 'watching') && !steps.some((s) => s.status === 'error')
? steps.findIndex((s) => s.status === 'pending' || s.status === 'running')
: -1;
const repoName = repo ? repo.split('/').pop() || finalName : finalName;
@@ -158,13 +228,25 @@ export default function Wizard() {
<MonoInput className="mt-1" value={url} onChange={(e) => setUrl(e.target.value)}
placeholder="https://github.com/owner/repo.git" aria-label="Upstream git URL" spellCheck={false} />
<div className="mt-1 max-w-[52ch] text-[12px] leading-snug text-muted">
Works with GitHub, Gitea, Codeberg, or any git host — public repos are fetched anonymously.
Works with GitHub, Gitea, Codeberg, or any git host. Public repos are fetched anonymously,
with no stored credentials offered to the fetch.
</div>
<Label className="mt-4">Name (optional)</Label>
<MonoInput className="mt-1" value={name} onChange={(e) => setName(e.target.value)}
placeholder={deriveName(url)} aria-label="Mirror name (optional)" spellCheck={false} />
<div className="mt-1 max-w-[52ch] text-[12px] leading-snug text-muted">
The mirror is generated as <span className="font-mono text-text">Lago/{finalName}</span>.
The mirror is created as <span className="font-mono text-text">{target}</span>.
</div>
<Label className="mt-4">Upstream token (optional)</Label>
<div className="relative mt-1">
<MonoInput value={token} onChange={(e) => setToken(e.target.value)} type="password"
placeholder="only for private upstreams" aria-label="Upstream token (optional)" spellCheck={false} />
<KeyRound size={14} strokeWidth={1.5} aria-hidden
className="pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 text-dim" />
</div>
<div className="mt-1 max-w-[52ch] text-[12px] leading-snug text-muted">
Stored in this container’s state file (chmod 600) and used only for this upstream. It is never
written to the repo and never sent back to the browser.
</div>
<div className="mt-4 flex justify-end">
<Btn variant="primary" disabled={!valid} onClick={() => setStep(2)}>Continue</Btn>
@@ -174,7 +256,7 @@ export default function Wizard() {
{step === 2 && (
<Panel title="Mirror config" action={
<span className="font-mono text-[12px] text-muted" title={`Lago/${finalName}`}>Lago/{finalName}</span>
<span className="font-mono text-[12px] text-muted" title={target}>{target}</span>
}>
<div>
{KNOWN_CONFIG_KEYS.map((key) => (
@@ -186,22 +268,35 @@ export default function Wizard() {
</div>
{isBool(key) ? (
<div className="flex sm:justify-end">
<Toggle on={!!config[key]} onChange={(v) => setConfig((c) => ({ ...c, [key]: v }))} />
<Toggle on={!!config[key]} onChange={(v) => setField(key, v)} />
</div>
) : key === 'sync_interval' ? (
<div className="flex items-center gap-2 sm:justify-end">
<MonoInput className="sm:max-w-[120px]" value={intervalDraft} inputMode="numeric"
onChange={(e) => setField(key, e.target.value.trim() === '' ? 0 : Number(e.target.value))}
placeholder="0" aria-label={key} spellCheck={false} />
<span className="shrink-0 font-mono text-[12px] text-dim">
{fmtInterval(Number(intervalDraft) > 0 ? Number(intervalDraft) : settings?.intervalSec || 0) || '—'}
</span>
</div>
) : (
<MonoInput value={String(config[key] ?? '')}
onChange={(e) => setConfig((c) => ({ ...c, [key]: e.target.value }))}
onChange={(e) => setField(key, e.target.value)}
placeholder={CONFIG_PLACEHOLDERS[key] ?? 'empty = refs only'} aria-label={key} spellCheck={false} />
)}
</div>
))}
</div>
<div className="mt-3 max-w-[52ch] text-[12px] leading-snug text-muted">
The parser is a simple grep — flat key: value only, no nesting. Empty build fields = refs-only mirror.
The parser is a simple grep — flat key: value only, no nesting. Empty build fields = refs-only mirror:
tags land, nothing is published.
</div>
<div className="mt-4 flex items-center justify-between gap-2">
<Btn variant="ghost" onClick={() => setStep(1)}>Back</Btn>
<Btn variant="primary" onClick={start}>Continue</Btn>
<Btn variant="primary" disabled={Number(intervalDraft) < 0 || Number.isNaN(Number(intervalDraft))}
onClick={() => void start()}>
Create mirror
</Btn>
</div>
</Panel>
)}
@@ -210,8 +305,11 @@ export default function Wizard() {
<Panel title={phase === 'done' ? 'Mirror created' : phase === 'error' ? 'Creation failed' : 'Creating…'}>
<div>
{steps.map((s, i) => {
const active = i === activeIdx;
const active = i === activeIdx && (s.status === 'pending' || s.status === 'running');
const last = i === steps.length - 1;
const detail = s.name === 'first-sync' && phase === 'watching'
? (watchNote === 'running' ? 'pass in flight' : 'queued')
: s.detail;
return (
<div key={s.name} className="flex items-stretch gap-3">
{/* node + rail: connector turns ok when the step is done */}
@@ -227,34 +325,50 @@ export default function Wizard() {
</span>
{!last && <span className={`my-1 w-px flex-1 ${s.status === 'ok' ? 'bg-ok/60' : 'bg-border'}`} />}
</div>
<div className="flex min-w-0 flex-1 items-center justify-between gap-3 py-3">
<span className={`truncate font-mono text-[13px] ${
s.status === 'error' ? 'text-danger' : s.status === 'pending' ? 'text-muted' : 'text-text'}`}
title={s.name}>
{s.name}
<div className="flex min-w-0 flex-1 flex-col justify-between gap-1 py-3 sm:flex-row sm:items-center sm:gap-3">
<span className="min-w-0">
<span className={`block truncate font-mono text-[13px] ${
s.status === 'error' ? 'text-danger' : s.status === 'pending' ? 'text-muted' : 'text-text'}`}
title={s.name}>
{s.name}
</span>
{(detail || STEP_LABELS[s.name]) && (
<span className="block truncate text-[12px] leading-snug text-dim" title={String(detail || STEP_LABELS[s.name])}>
{STEP_LABELS[s.name]}{detail ? ` · ${detail}` : ''}
</span>
)}
</span>
<span className={`inline-flex shrink-0 items-center gap-2 font-mono text-[12px] ${
s.status === 'ok' ? 'text-ok' : s.status === 'error' ? 'text-danger' : active ? 'text-accent' : 'text-muted'}`}>
{active && <StatusDot color={C.accent} pulse />}
{s.status === 'ok' ? 'done' : active ? 'running…' : s.status === 'error' ? 'failed' : 'pending'}
{s.status === 'ok' ? 'done' : s.status === 'running' ? 'running…'
: active ? 'waiting…' : s.status === 'error' ? 'failed' : 'pending'}
</span>
</div>
</div>
);
})}
</div>
{phase !== 'done' && (
{phase === 'watching' && (
<div className="mt-2 max-w-[52ch] text-[12px] leading-snug text-muted">
this runs generate → variable → default branch → config → first sync
the repo is created — the first pass is queued on the worker and takes as long as the upstream is big.
</div>
)}
{phase === 'error' && (
<div className="mt-4 flex flex-col gap-3">
<ErrorInline message={err} />
<div className="flex justify-end">
<div className="flex flex-wrap justify-end gap-2">
{repo && (
<Btn variant="secondary" onClick={() => navigate(`/mirrors/${repoName}`)}>
Open {repoName}
</Btn>
)}
<Btn variant="ghost" onClick={retry}>Try again</Btn>
</div>
<div className="text-[12px] text-muted">
Retrying is safe: a half-created mirror is adopted, not duplicated.
</div>
</div>
)}
@@ -265,14 +379,14 @@ export default function Wizard() {
<Check size={20} strokeWidth={2} />
</span>
<div className="min-w-0">
<div className="text-[14px] font-medium text-text">Mirror created</div>
<div className="text-[14px] font-medium text-text">First sync finished</div>
<div className="truncate font-mono text-[13px] text-accent" title={repo}>{repo}</div>
</div>
</div>
<div className="mt-4">
<Btn variant="primary" onClick={() => navigate(`/mirrors/${repoName}`)}>Open {repoName}</Btn>
</div>
<div className="mt-2 text-[12px] text-muted">the first sync is queued on the runner</div>
<div className="mt-2 text-[12px] text-muted">the worker re-syncs it on its own interval from now on</div>
</div>
)}
</Panel>
+299
View File
@@ -0,0 +1,299 @@
import { useCallback, useState } from 'react';
import type { ReactNode } from 'react';
import { AlertTriangle, Clock, RefreshCw } from 'lucide-react';
import {
Badge, EmptyState, ErrorInline, OfflineBanner, Panel, SkeletonRow, StatCard, StatusDot, Btn,
} from '../components/primitives';
import { api } from '../api/client';
import type { QueueEntry } from '../api/types';
import { useApp, usePoll, useWorker } from '../lib/app-context';
import { Label, Spinner, C } from './shared';
import { fmtSec, fmtInterval, agoSec } from './format';
import { LogViewer, useWorkerLogTail } from './detail/LiveLog';
// ============================================================================
// Worker — the container's own instrument panel. The runner page it replaces
// described a Gitea Actions runner; there is none any more. This process is
// the thing that syncs: a scheduler heartbeat plus PARALLELISM worker threads.
// Sections: identity (boot + Gitea + token scope) → scheduler/totals → queue
// (in flight + waiting) → the container's stdout.
// Poll cadence: /api/status 3s here (5s globally from the app context).
// ============================================================================
function StateChip({ status }: { status: QueueEntry['status'] }) {
return (
<span className="inline-flex shrink-0 items-center gap-1 rounded-pill border border-border bg-chip px-2 py-[2px] font-mono text-[12px] leading-4">
{status === 'in_progress' ? (
<span className="text-accent"><Spinner size={10} /></span>
) : (
<Clock size={11} strokeWidth={1.5} className="text-muted" />
)}
<span className={status === 'in_progress' ? 'text-accent' : 'text-muted'}>
{status === 'in_progress' ? 'in flight' : 'queued'}
</span>
</span>
);
}
function QueueRow({ q, index }: { q: QueueEntry; index: number }) {
const running = q.status === 'in_progress';
return (
<li className="flex flex-col gap-1.5 border-b border-border px-4 py-3 transition-colors duration-ctl last:border-b-0 hover:bg-panel2/60 sm:flex-row sm:items-center sm:gap-3">
<div className="flex min-w-0 flex-1 items-center gap-2.5">
<span className="w-5 shrink-0 font-mono text-[12px] tabular text-dim">{String(index + 1).padStart(2, '0')}</span>
<StatusDot color={running ? C.accent : C.dim} pulse={running} />
<span className="min-w-0 flex-1 truncate font-mono text-[13px] text-text" title={q.repo}>{q.repo}</span>
</div>
<div className="flex min-w-0 items-center gap-2 pl-[30px] sm:pl-0">
<StateChip status={q.status} />
<Badge><span className="block max-w-[150px] truncate" title={q.event}>{q.event}</span></Badge>
<span className="ml-auto shrink-0 font-mono text-[12px] tabular text-muted sm:w-[120px] sm:text-right"
title={running ? `running ${fmtSec(q.waitedSec)}` : `${fmtSec(q.waitedSec)} waiting for a slot`}>
{running ? `running ${fmtSec(q.waitedSec)}` : `${fmtSec(q.waitedSec)} waiting`}
</span>
</div>
</li>
);
}
// One read-only row: micro-label + mono value (shared shape with Settings).
function Row({ label, children }: { label: string; children: ReactNode }) {
return (
<div className="flex flex-col gap-1 border-b border-border py-2.5 last:border-b-0 sm:flex-row sm:items-center sm:gap-4">
<Label className="w-[132px] shrink-0">{label}</Label>
<div className="min-w-0 flex-1">{children}</div>
</div>
);
}
export default function WorkerView() {
const { offline, refreshWorker: load } = useApp();
// The shared /api/status stream, at this page's faster cadence (3s).
const { worker: status, error: err } = useWorker(3000);
const [queue, setQueue] = useState<QueueEntry[] | null>(null);
const [refreshing, setRefreshing] = useState(false);
const loadQueue = useCallback(async () => {
try {
setQueue(await api.queue());
} catch { /* the status stream carries the same counts */ }
}, []);
usePoll(loadQueue, 3000);
// The container's own stdout: boot banner, scheduler + queue chatter.
const workerLog = useWorkerLogTail(400);
// Re-read this page's two streams at once. It does not force a sync — the
// scheduler's heartbeat decides when work is taken — it just stops making
// the operator wait for the next 3s poll after a change elsewhere.
const tick = async () => {
setRefreshing(true);
try {
await Promise.all([load(), loadQueue()]);
} finally {
setRefreshing(false);
}
};
if (!status && !err) {
return (
<div className="flex min-w-0 flex-col gap-4">
<h1 className="text-[20px] font-bold leading-none tracking-tight text-text">Worker</h1>
<Panel title="Identity"><SkeletonRow /><SkeletonRow /></Panel>
<Panel title="Queue"><SkeletonRow /><SkeletonRow /></Panel>
</div>
);
}
const boot = status?.boot;
const sched = status?.scheduler;
const totals = status?.totals;
const runningCount = sched?.running.length || 0;
const live = runningCount > 0;
const bootErrors = boot?.errors?.length ? boot.errors : [];
return (
<div className="flex min-w-0 flex-col gap-4">
{offline && <OfflineBanner message="Worker unreachable — showing last cached state" />}
<div className="flex flex-wrap items-end justify-between gap-3">
<div className="min-w-0">
<Label>This container</Label>
<div className="mt-2 flex flex-wrap items-center gap-3">
<h1 className="text-[20px] font-bold leading-none tracking-tight text-text">Worker</h1>
<Badge color={err ? C.danger : C.ok} dot={err ? C.danger : C.ok}>
{err ? 'unreachable' : 'online'}
</Badge>
</div>
</div>
<Btn variant="secondary" onClick={() => void tick()} disabled={refreshing}>
<RefreshCw size={14} strokeWidth={2} className={refreshing ? 'animate-spin' : ''} /> Refresh
</Btn>
</div>
{err && <ErrorInline message={err} onRetry={() => void tick()} />}
{/* ---------- stats ---------- */}
<div className="grid grid-cols-2 gap-4 lg:grid-cols-4">
<StatCard label="Mirrors" value={totals ? totals.mirrors : '…'} sub="managed by this container" />
<StatCard label="Healthy"
value={totals ? <>{totals.healthy}<span className="text-[13px] font-normal text-muted">/{totals.mirrors}</span></> : '…'}
sub="success within 3× interval" />
<StatCard label="In flight" accent={live}
value={sched ? sched.queued + runningCount : '…'}
sub={live ? (sched?.running.join(', ') || 'a pass is running') : 'nothing running'} />
<StatCard label="Releases / assets"
value={totals ? `${totals.releases}` : '…'}
sub={totals ? `${totals.assets} assets mirrored` : 'published by the worker'} />
</div>
{/* ---------- identity: what this container is connected to ---------- */}
<Panel
title="Identity"
action={<Badge color={live ? C.accent : C.ok} dot={live ? C.accent : C.ok}>
{live ? 'working' : 'idle'}
</Badge>}
>
<div className="flex min-w-0 flex-wrap items-center gap-3">
<span aria-hidden
className={`h-[10px] w-[10px] shrink-0 rounded-full ${err ? 'bg-danger' : 'bg-ok glow-ok'} ${
live ? 'animate-breathe' : ''}`} />
<span className="min-w-0 max-w-full truncate font-mono text-[16px] font-bold leading-tight text-text"
title={boot?.remote}>
{boot?.remote ? boot.remote.replace(/^https?:\/\//, '') : 'no connection'}
</span>
{boot?.gitea_version && <Badge>Gitea <span className="tabular">{boot.gitea_version}</span></Badge>}
{boot?.is_admin === true && <Badge color={C.accent}>admin token</Badge>}
{boot?.is_admin === false && <Badge color={C.warn}>non-admin token</Badge>}
</div>
<div className="mt-3 flex flex-col">
<Row label="Owner">{boot?.owner ? <span className="font-mono text-[13px] text-text">{boot.owner}</span>
: <span className="font-mono text-[13px] text-dim">unknown</span>}</Row>
<Row label="User">{boot?.user ? <span className="font-mono text-[13px] text-text">{boot.user}</span>
: <span className="font-mono text-[13px] text-dim">—</span>}</Row>
<Row label="Template">{boot?.template ? <span className="font-mono text-[13px] text-text">{boot.template}</span>
: <span className="font-mono text-[13px] text-dim">—</span>}</Row>
<Row label="Uptime">{boot ? <span className="font-mono text-[13px] tabular text-muted">{fmtSec(boot.uptime_sec)}</span>
: <span className="font-mono text-[13px] text-dim">—</span>}</Row>
<Row label="Started">{boot ? <span className="font-mono text-[13px] tabular text-muted">{agoSec(boot.started_at)}</span>
: <span className="font-mono text-[13px] text-dim">—</span>}</Row>
</div>
{bootErrors.length > 0 && (
<div className="mt-3 flex flex-col gap-2">
{bootErrors.map((e, i) => (
<div key={i} className="flex items-start gap-2 rounded-panel border border-warn/40 bg-warn/[0.06] px-3 py-2">
<AlertTriangle size={14} strokeWidth={2} className="mt-[2px] shrink-0 text-warn" />
<pre className="m-0 min-w-0 flex-1 overflow-x-auto whitespace-pre-wrap font-mono text-[12px] text-warn">{e}</pre>
</div>
))}
<div className="text-[12px] leading-relaxed text-muted">
boot problems are non-fatal — the container keeps serving and retrying each pass.
</div>
</div>
)}
</Panel>
{/* ---------- scheduler ---------- */}
<Panel
title="Scheduler"
action={sched && (
<span className="inline-flex items-center gap-2">
<StatusDot color={live ? C.accent : C.dim} pulse={live} />
<span className="font-mono text-[12px] tabular text-muted">
{runningCount}/{sched.parallelism} slots
</span>
</span>
)}
>
<div className="flex flex-col">
<Row label="Interval">
<span className="font-mono text-[13px] tabular text-text">
{sched ? fmtInterval(sched.effective_interval_sec ?? sched.interval_sec) : '—'}
</span>
{sched && sched.interval_sec > 0 && (sched.effective_interval_sec ?? sched.interval_sec) > sched.interval_sec ? (
<Badge color={C.warn}>auto</Badge>
) : null}
<span className="ml-2 text-[12px] text-muted">
{sched && sched.interval_sec > 0 && (sched.effective_interval_sec ?? sched.interval_sec) > sched.interval_sec
? `raised from ${fmtInterval(sched.interval_sec)} to stay inside GitHub’s anonymous API budget`
: 'default per mirror — a mirror can override it with sync_interval'}
</span>
</Row>
{sched?.auto_pace && sched.auto_pace.github_repos > 0 ? (
<Row label="API budget">
<span className="font-mono text-[13px] tabular text-text">
~{sched.auto_pace.est_calls_per_hour}/h
</span>
<span className="ml-2 text-[12px] text-muted">
{sched.auto_pace.cost_per_pass} calls/pass across {sched.auto_pace.github_repos} anonymous GitHub{' '}
mirror{sched.auto_pace.github_repos === 1 ? '' : 's'} · plan caps at {sched.auto_pace.budget_per_hour}/h
(80% of GitHub’s 60) so manual triggers keep room
</span>
</Row>
) : null}
<Row label="Parallelism">
<Badge color={C.accent}>{sched ? sched.parallelism : '—'}</Badge>
<span className="ml-2 text-[12px] text-muted">
{sched && sched.parallelism === 1 ? 'one pass at a time — two never push the same repo' : 'concurrent passes'}
</span>
</Row>
<Row label="Last heartbeat">
<span className="font-mono text-[13px] tabular text-text">{sched?.last_tick ? agoSec(sched.last_tick) : 'never'}</span>
<span className="ml-2 text-[12px] text-muted">
the heartbeat runs every 15s and only decides when work is taken; each mirror’s own interval gates its sync
</span>
</Row>
<Row label="Queued">
<span className="font-mono text-[13px] tabular text-text">{sched ? sched.queued : '—'}</span>
<span className="ml-2 text-[12px] text-muted">waiting for a free slot</span>
</Row>
<Row label="Running">
{sched && sched.running.length > 0
? <span className="flex min-w-0 flex-wrap gap-1">{sched.running.map((r) => (
<Badge key={r} color={C.accent}><Spinner size={10} />{r}</Badge>))}</span>
: <span className="font-mono text-[13px] text-dim">—</span>}
</Row>
</div>
</Panel>
{/* ---------- queue ---------- */}
<Panel
title="Queue"
action={queue === null ? undefined : (
<Badge color={queue.length ? (live ? C.accent : C.text) : undefined}>
<span className="tabular">{queue.length}</span>
</Badge>
)}
>
{queue === null ? (
<div>
<SkeletonRow />
<SkeletonRow />
</div>
) : queue.length === 0 ? (
<EmptyState title="Queue clear" hint="Nothing waiting — mirrors sync on their own interval." />
) : (
<ul className="-m-4 list-none">
{queue.map((q, i) => <QueueRow key={`${q.repo}-${q.status}`} q={q} index={i} />)}
</ul>
)}
</Panel>
{/* ---------- the container's own log ---------- */}
<Panel
title="Worker log — this container's stdout"
action={<span className="font-mono text-[12px] uppercase tracking-[0.08em] text-dim">scheduler + queue</span>}
>
{/* the process log is tailed live: it grows with every scheduler tick
and every pass, so auto-follow is the default here */}
<LogViewer lines={workerLog.lines} loading={workerLog.logLoading} error={workerLog.logErr}
onRetry={workerLog.reload} live maxHeight={360} />
<div className="mt-3 text-[12px] leading-relaxed text-muted">
Boot banner, scheduler ticks and queue chatter — the process log, not a mirror’s sync log. Per-mirror
output lives on that mirror’s page.
</div>
</Panel>
</div>
);
}
+45 -8
View File
@@ -1,10 +1,11 @@
import type { ReactNode } from 'react';
import { RotateCw, ArrowRight, Trash2 } from 'lucide-react';
import { AlertTriangle, RotateCw, ArrowRight, Trash2 } from 'lucide-react';
import type { Mirror } from '../../api/types';
import type { HealthState } from '../../lib/health';
import { HEALTH_COLORS, runColor, timeAgo, duration } from '../../lib/health';
import { StatusDot, Badge, Sparkline, IconBtn } from '../../components/primitives';
import { Spinner } from '../shared';
import { releasesManaged } from '../format';
// ============================================================================
// Dashboard row renderers — one component per viewport regime, same data:
@@ -27,13 +28,18 @@ export function hostRepo(url: string): { host: string; repo: string } {
}
export function forkHref(m: Mirror): string {
return m.forkUrl || `https://git.lago.dev/${m.full}`;
// The worker always builds forkUrl from REMOTE, so no host guessing here.
return m.forkUrl || m.full;
}
export function ParityChips({ m }: { m: Mirror }) {
const p = m.parity;
const chip = (label: string, fork: number | null | undefined, upstream: number | null | undefined) => {
if (p && fork != null && upstream != null && fork < upstream) {
const releases = releasesManaged(m.config);
const chip = (label: string, fork: number | null | undefined, upstream: number | null | undefined, skipped = false) => {
// A null upstream count means "not countable for this provider" — never
// render that as behind. Only compare when BOTH sides are numbers.
// `skipped` (assets on a refs-only mirror) is the same kind of non-signal.
if (!skipped && p && fork != null && upstream != null && fork < upstream) {
// behind: fork/upstream in danger text
return <Badge key={label} color={HEALTH_COLORS.failed}>{label} {fork}/{upstream}</Badge>;
}
@@ -44,7 +50,7 @@ export function ParityChips({ m }: { m: Mirror }) {
<div className="flex flex-wrap items-center gap-1">
{chip('br', p?.branches, p?.upstream?.branches)}
{chip('tags', p?.tags, p?.upstream?.tags)}
{chip('assets', p?.assets, p?.upstream?.assets)}
{chip('assets', p?.assets, p?.upstream?.assets, !releases)}
</div>
);
}
@@ -102,6 +108,33 @@ export interface RowHandlers {
onDelete: (m: Mirror) => void;
}
// The silent-failure modes a green dot cannot express: a paused mirror, a
// broken release build, the Releases unit stuck off (assets 404), upstream CI
// files the worker had to disable. Color + weight, no glow (contract rule 5).
export function SignalFlags({ m }: { m: Mirror }) {
const flags: ReactNode[] = [];
if (!m.enabled) flags.push(<Badge key="paused">paused</Badge>);
if (m.unitFix === 'manual' || m.unitFix === 'off') {
flags.push(
<Badge key="unit" color={HEALTH_COLORS.stale}>
<AlertTriangle size={11} strokeWidth={1.5} />releases unit
</Badge>,
);
}
if (m.releaseFailures.length > 0) {
flags.push(
<Badge key="relf" color={HEALTH_COLORS.failed}>
{m.releaseFailures.length} release{m.releaseFailures.length > 1 ? 's' : ''} failed
</Badge>,
);
}
if (m.disabledWorkflows.length > 0) {
flags.push(<Badge key="wf">{m.disabledWorkflows.length} workflows off</Badge>);
}
if (flags.length === 0) return null;
return <span className="flex min-w-0 flex-wrap gap-1">{flags}</span>;
}
function RowActions({ m, h }: { m: Mirror; h: RowHandlers }) {
const busy = h.syncing === m.name;
return (
@@ -130,9 +163,12 @@ export function MirrorRow({ m, st, h }: { m: Mirror; st: HealthState; h: RowHand
{/* row-active bar: accent, no glow */}
<span aria-hidden
className="pointer-events-none absolute inset-y-0 left-0 w-[2px] bg-accent opacity-0 transition-opacity duration-ctl group-hover:opacity-100" />
<span className="flex min-w-0 items-center gap-3">
<StatusDot color={HEALTH_COLORS[st]} pulse={st === 'running'} />
<span className="truncate font-mono text-[13px] text-text" title={m.name}>{m.name}</span>
<span className="flex min-w-0 flex-col gap-1">
<span className="flex min-w-0 items-center gap-3">
<StatusDot color={HEALTH_COLORS[st]} pulse={st === 'running'} />
<span className="truncate font-mono text-[13px] text-text" title={m.name}>{m.name}</span>
</span>
<SignalFlags m={m} />
</span>
</td>
<td className={TD}><RepoStack m={m} /></td>
@@ -160,6 +196,7 @@ export function MirrorCard({ m, st, h }: { m: Mirror; st: HealthState; h: RowHan
<span className="min-w-0 flex-1 truncate font-mono text-[13px] text-text" title={m.name}>{m.name}</span>
<LastSyncCell m={m} align="right" />
</div>
{(() => { const f = <SignalFlags m={m} />; return f ? <div className="ml-5">{f}</div> : null; })()}
<div className="mt-3"><RepoStack m={m} /></div>
<div className="mt-3 flex flex-wrap items-center justify-between gap-2">
<ParityChips m={m} />
+130 -98
View File
@@ -3,70 +3,32 @@ import { ChevronDown } from 'lucide-react';
import { Panel, SkeletonRow, EmptyState, ErrorInline, StatusDot } from '../../components/primitives';
import { api } from '../../api/client';
import { usePoll } from '../../lib/app-context';
import type { RunInfo, LogLine } from '../../api/types';
import { runColor } from '../../lib/health';
import type { RunInfo, LogLine, LogResult } from '../../api/types';
import { C } from '../shared';
import { renderLogLines } from './log';
// ---------------------------------------------------------------- Live log
// The console centerpiece. Selects the last 5 runs; the <pre> auto-scrolls to
// the tail while the user is pinned at the bottom (scroll-up unpins, scrolling
// back re-pins) and re-fetches every 3s only while the selected run is
// in_progress. Selection is controlled by Detail so RunHistory can highlight
// the same run with the accent bar.
export function LiveLogPanel({ runs, loading, error, onRetry, name, selectedId, onSelect }: {
runs: RunInfo[] | null; loading: boolean; error: string | null;
onRetry: () => void; name: string;
selectedId: number | null; onSelect: (id: number) => void;
// ============================================================================
// The log console, shared by two places: a mirror's sync log (Detail) and the
// container's own stdout (Worker). Both arrive as LogLine[] and both tail a
// file the worker is still appending to, so the follow-the-tail behaviour
// lives here once:
// - the <pre> sticks to the bottom while the operator stays there
// - scrolling up unpins and offers "resume auto-follow"
// - it re-fetches every 3s only while `live` (work in flight)
// ============================================================================
export function LogViewer({ lines, loading, error, onRetry, live, maxHeight = 440 }: {
lines: LogLine[] | null; loading: boolean; error: string | null;
onRetry?: () => void; live: boolean; maxHeight?: number;
}) {
const [lines, setLines] = useState<LogLine[] | null>(null);
const [logErr, setLogErr] = useState<string | null>(null);
const [logLoading, setLogLoading] = useState(true);
const [following, setFollowing] = useState(true);
const pinned = useRef(true);
const [following, setFollowing] = useState(true);
const preRef = useRef<HTMLPreElement | null>(null);
const effectiveSel = selectedId;
const selected = runs?.find((r) => r.id === effectiveSel) || null;
const fetchLog = useCallback(async () => {
if (effectiveSel === null) return;
const id = effectiveSel;
try {
const r = await api.log(name, id);
if (id !== effectiveSel) return; // stale response
setLines(r.lines);
setLogErr(null);
} catch (e) {
if (id === effectiveSel) setLogErr(e instanceof Error ? e.message : String(e));
} finally {
if (id === effectiveSel) setLogLoading(false);
}
}, [name, effectiveSel]);
// fetch on selection change
useEffect(() => {
setLines(null);
setLogErr(null);
setLogLoading(true);
pinned.current = true;
setFollowing(true);
void fetchLog();
}, [effectiveSel, fetchLog]);
// live tail: only while the selected run is in_progress
const live = selected?.status === 'in_progress';
const tickLog = useCallback(() => {
if (live) void fetchLog();
}, [live, fetchLog]);
usePoll(tickLog, 3000);
// keep pinned at the tail; user scroll-up unpins, scroll to bottom re-pins
useEffect(() => {
const el = preRef.current;
if (!el) return;
if (pinned.current) el.scrollTop = el.scrollHeight;
if (el && pinned.current) el.scrollTop = el.scrollHeight;
}, [lines]);
const onScroll = () => {
@@ -93,33 +55,128 @@ export function LiveLogPanel({ runs, loading, error, onRetry, name, selectedId,
};
return (
<Panel
title="Live log"
action={selected ? (
<>
<div className="mb-2 flex items-center gap-2">
<button type="button" onClick={live && !following ? followNow : undefined}
title={live && !following ? 'Scroll to the latest line' : undefined}
className={`focus-ring inline-flex h-8 items-center gap-2 rounded-ctl px-2 font-mono text-[12px] uppercase tracking-[0.08em] ${
live && following ? 'text-accent' : live ? 'cursor-pointer text-warn' : 'text-dim'
}`}>
<StatusDot color={live ? (following ? C.accent : C.warn) : runColor(selected.status, selected.conclusion)}
pulse={live} />
live && following ? 'text-accent' : live ? 'cursor-pointer text-warn' : 'text-dim'}`}>
<StatusDot color={live ? (following ? C.accent : C.warn) : C.dim} pulse={live} />
{live ? (following ? 'auto-follow' : 'paused — scrolled up') : 'idle'}
</button>
) : undefined}
>
{/* run selector — chip surface, strong border, custom caret */}
</div>
{error ? (
<ErrorInline message={error} onRetry={onRetry} />
) : (
/* the console: darker inset on #bg, cyan hairline on top edge */
<div className="overflow-hidden rounded-panel border border-border border-t-accent/25 bg-bg">
<pre
ref={preRef}
onScroll={onScroll}
onWheel={unpin}
onTouchMove={unpin}
onKeyDown={unpin}
tabIndex={0}
style={{ maxHeight }}
className="overflow-auto p-4 font-mono text-[12px] leading-5 whitespace-pre text-muted">
{loading && !lines
? <span className="text-dim">loading log…</span>
: lines
? (lines.length === 0 ? <span className="text-dim">no log output</span> : renderLogLines(lines))
: <span className="text-dim">no log</span>}
</pre>
{live && !following && (
<button type="button" onClick={followNow}
className="focus-ring flex w-full items-center justify-center gap-2 border-t border-border bg-panel2 py-1.5 font-mono text-[12px] uppercase tracking-[0.08em] text-accent transition-colors duration-ctl hover:bg-chip">
resume auto-follow
</button>
)}
</div>
)}
</>
);
}
// Tail any log endpoint. `load` must be a stable callback (useCallback) that
// fetches one LogResult; changing it re-fetches. A response arriving after the
// selection moved on is dropped, so a slow fetch never paints the wrong pass,
// and while `live` the tail refreshes every 3s (the file is being appended to).
function useTailLog(load: () => Promise<LogResult>, live: boolean) {
const [lines, setLines] = useState<LogLine[] | null>(null);
const [logErr, setLogErr] = useState<string | null>(null);
const [logLoading, setLogLoading] = useState(true);
const seq = useRef(0);
const fetchLog = useCallback(async () => {
const mine = ++seq.current;
try {
const r = await load();
if (mine !== seq.current) return; // superseded
setLines(r.lines);
setLogErr(null);
} catch (e) {
if (mine === seq.current) setLogErr(e instanceof Error ? e.message : String(e));
} finally {
if (mine === seq.current) setLogLoading(false);
}
}, [load]);
useEffect(() => {
setLines(null);
setLogErr(null);
setLogLoading(true);
void fetchLog();
}, [fetchLog]);
const tick = useCallback(() => { if (live) void fetchLog(); }, [live, fetchLog]);
usePoll(tick, 3000);
return { lines, logErr, logLoading, reload: () => void fetchLog() };
}
export function useMirrorLogTail(name: string, file: string | undefined, live: boolean, tail = 800) {
const load = useCallback(() => api.log(name, { file, tail }), [name, file, tail]);
return useTailLog(load, live);
}
export function useWorkerLogTail(tail = 400) {
const load = useCallback(() => api.workerLog(tail), [tail]);
return useTailLog(load, true);
}
// A run row's identity: `file` is unique (timestamp+pid). The unix-second `id`
// collides when two passes land in the same second — display only, never a key.
export const runKey = (r: RunInfo): string => r.file || String(r.id);
// ---------------------------------------------------------------- Live log
// One row per sync pass; the selection is a log FILE so the console shows
// exactly the pass the operator picked (GET /mirrors/:name/log?file=…).
// While a pass is in flight the newest file IS the one being appended to, so
// `live` + the default selection (newest) gives a streaming tail.
export function LiveLogPanel({ runs, loading, error, onRetry, name, selected, onSelect, live }: {
runs: RunInfo[] | null; loading: boolean; error: string | null;
onRetry: () => void; name: string;
selected: string | null; onSelect: (key: string) => void;
live: boolean;
}) {
const selRun = runs?.find((r) => runKey(r) === selected) || null;
const { lines, logErr, logLoading, reload } = useMirrorLogTail(name, selRun?.file, live);
return (
<Panel title={live ? 'Sync log — pass in flight' : 'Sync log'}>
{/* pass selector — chip surface, strong border, custom caret */}
<div className="relative mb-3">
<select
value={effectiveSel ?? ''}
onChange={(e) => onSelect(Number(e.target.value))}
value={selected ?? ''}
onChange={(e) => onSelect(e.target.value)}
disabled={!runs || runs.length === 0}
aria-label="Select run to show in log"
aria-label="Select sync pass to show in the log"
className="focus-ring w-full appearance-none rounded-ctl border border-border2 bg-chip py-2 pl-3 pr-9 font-mono text-[13px] text-text focus:outline-none disabled:opacity-40">
{!runs || runs.length === 0 ? (
<option value="">no runs</option>
) : runs.slice(0, 5).map((r) => (
<option key={r.id} value={r.id}>
run #{r.id} — {r.conclusion || r.status}
<option value="">no syncs</option>
) : runs.slice(0, 8).map((r, i) => (
<option key={runKey(r)} value={runKey(r)}>
{i === 0 ? 'latest · ' : ''}{r.conclusion || r.status} · {r.file || `#${r.id}`}
</option>
))}
</select>
@@ -135,34 +192,9 @@ export function LiveLogPanel({ runs, loading, error, onRetry, name, selectedId,
) : error ? (
<ErrorInline message={error} onRetry={onRetry} />
) : !runs || runs.length === 0 ? (
<EmptyState title="No runs yet" hint="The log of the latest run will stream here." />
<EmptyState title="No syncs yet" hint="The log of the first sync pass lands here." />
) : (
<>
{logErr && <div className="mb-2"><ErrorInline message={logErr} onRetry={() => void fetchLog()} /></div>}
{/* the console: darker inset on #bg, cyan hairline on top edge */}
<div className="overflow-hidden rounded-panel border border-border border-t-accent/25 bg-bg">
<pre
ref={preRef}
onScroll={onScroll}
onWheel={unpin}
onTouchMove={unpin}
onKeyDown={unpin}
tabIndex={0}
className="max-h-[440px] overflow-auto p-4 font-mono text-[12px] leading-5 whitespace-pre text-muted">
{logLoading && !lines
? <span className="text-dim">loading log…</span>
: lines
? (lines.length === 0 ? <span className="text-dim">no log output</span> : renderLogLines(lines))
: <span className="text-dim">no log</span>}
</pre>
{live && !following && (
<button type="button" onClick={followNow}
className="focus-ring flex w-full items-center justify-center gap-2 border-t border-border bg-panel2 py-1.5 font-mono text-[12px] uppercase tracking-[0.08em] text-accent transition-colors duration-ctl hover:bg-chip">
resume auto-follow
</button>
)}
</div>
</>
<LogViewer lines={lines} loading={logLoading} error={logErr} onRetry={reload} live={live} />
)}
</Panel>
);
+25 -19
View File
@@ -8,12 +8,13 @@ import type { LogLine, RunInfo } from '../../api/types';
import { runColor, RUN_COLORS, duration, timeAgo } from '../../lib/health';
import { C } from '../shared';
import { renderLine } from './log';
import { runKey } from './LiveLog';
const LIVE: ReadonlySet<string> = new Set(['in_progress', 'queued']);
// expandable failure log: last 12 lines of the run's log, rendered through the
// same console-line renderer as the live log (fatal / ::error:: in danger).
export function FailureLog({ name, runId }: { name: string; runId: number }) {
// expandable failure log: last 20 lines of THAT pass (identified by its file),
// rendered through the same console-line renderer as the live log.
export function FailureLog({ name, file }: { name: string; file?: string }) {
const [lines, setLines] = useState<LogLine[] | null>(null);
const [err, setErr] = useState<string | null>(null);
const tried = useRef(false);
@@ -23,8 +24,8 @@ export function FailureLog({ name, runId }: { name: string; runId: number }) {
tried.current = true;
setErr(null);
try {
const r = await api.log(name, runId);
setLines(r.lines.slice(-12));
const r = await api.log(name, { file, tail: 20 });
setLines(r.lines);
} catch (e) {
setErr(e instanceof Error ? e.message : String(e));
}
@@ -47,7 +48,7 @@ export function FailureLog({ name, runId }: { name: string; runId: number }) {
}
function RunRow({ name, r, selected, onSelect }: {
name: string; r: RunInfo; selected: boolean; onSelect: (id: number) => void;
name: string; r: RunInfo; selected: boolean; onSelect: (key: string) => void;
}) {
const [open, setOpen] = useState(false);
const failed = r.conclusion === 'failure';
@@ -55,6 +56,7 @@ function RunRow({ name, r, selected, onSelect }: {
const stateColor = r.conclusion
? (RUN_COLORS[r.conclusion] ?? C.muted)
: (RUN_COLORS[r.status] ?? C.muted);
const key = runKey(r);
return (
<div
@@ -62,25 +64,29 @@ function RunRow({ name, r, selected, onSelect }: {
selected ? 'bg-panel2/60' : 'hover:bg-panel2/40'
}`}
>
{/* selection = the run the live log is showing (left accent bar) */}
{/* selection = the pass the sync log is showing (left accent bar) */}
{selected && <span aria-hidden className="absolute inset-y-0 left-0 w-[2px] bg-accent" />}
<div className="flex items-center gap-1 pr-4">
<button
type="button"
onClick={() => onSelect(r.id)}
title="Show this run in the live log"
onClick={() => onSelect(key)}
title="Show this pass in the sync log"
aria-current={selected || undefined}
className="focus-ring flex min-w-0 flex-1 flex-wrap items-center gap-x-2 gap-y-1 py-2.5 pl-4 pr-1 text-left"
>
<StatusDot color={runColor(r.status, r.conclusion)} pulse={LIVE.has(r.status)} />
<span className={`font-mono text-[13px] tabular ${selected ? 'text-text' : 'text-muted'}`}>
run #{r.id}
#{r.id}
</span>
<Badge>{r.event}</Badge>
<Badge color={stateColor} dot={stateColor}>{state}</Badge>
{r.headline && (
<span className="hidden min-w-0 flex-1 truncate font-mono text-[12px] text-dim lg:block" title={r.headline}>
{r.headline}
</span>
)}
<span className="ml-auto flex shrink-0 items-center gap-3 font-mono text-[12px] tabular text-muted">
<span title="duration">{duration(r.durationSec)}</span>
<span title={r.updatedAt}>{timeAgo(r.updatedAt)}</span>
<span title={r.updatedAt ?? undefined}>{timeAgo(r.updatedAt)}</span>
</span>
</button>
{failed && (
@@ -92,19 +98,19 @@ function RunRow({ name, r, selected, onSelect }: {
</Btn>
)}
</div>
{failed && open && <FailureLog name={name} runId={r.id} />}
{failed && open && <FailureLog name={name} file={r.file} />}
</div>
);
}
export function RunHistoryPanel({ runs, loading, error, onRetry, name, selectedId, onSelect }: {
export function RunHistoryPanel({ runs, loading, error, onRetry, name, selectedKey, onSelect }: {
runs: RunInfo[] | null; loading: boolean; error: string | null;
onRetry: () => void; name: string;
selectedId: number | null; onSelect: (id: number) => void;
selectedKey: string | null; onSelect: (key: string) => void;
}) {
return (
<Panel
title="Run history"
title="Sync history"
action={runs && runs.length > 0 ? (
<span className="font-mono text-[12px] uppercase tracking-[0.08em] tabular text-dim">last {runs.length}</span>
) : undefined}
@@ -118,12 +124,12 @@ export function RunHistoryPanel({ runs, loading, error, onRetry, name, selectedI
) : error ? (
<ErrorInline message={error} onRetry={onRetry} />
) : !runs || runs.length === 0 ? (
<EmptyState title="No runs yet" hint="Dispatch a re-sync to start the first mirror run." />
<EmptyState title="No syncs yet" hint="Queue a sync to start the first mirror pass." />
) : (
<div className="-mx-4 -mb-4">
{runs.map((r) => (
<RunRow key={r.id} name={name} r={r}
selected={r.id === selectedId} onSelect={onSelect} />
<RunRow key={runKey(r)} name={name} r={r}
selected={runKey(r) === selectedKey} onSelect={onSelect} />
))}
</div>
)}
+34 -6
View File
@@ -5,6 +5,15 @@ import { C } from '../shared';
const GROUP = /^\s*::group::(.*)$/;
const ENDGROUP = /^\s*::endgroup::/;
const MSG = /^\s*::(notice|warning|error)::(.*)$/;
// The worker's own vocabulary. A sync log has no CI annotations any more, so
// these markers are what carries meaning: ">> " is the run's result headline,
// "!! " is a failure inside a pass that still finished (a broken build_cmd on
// one tag, e.g.), "=== sync finished|failed" is the terminator, and WARN:/ERROR:
// are the levels the Python side prints.
const HEADLINE = /^>>\s+/;
const BANG = /^!!\s+/;
const LEVEL = /^(WARN|ERROR|FATAL)\b[:\s]?(.*)$/i;
const TERMINAL = /^===\s+sync\s+(finished|failed)\b/;
// leading CI-style timestamp (ISO…THH:MM:SS or bare HH:MM:SS) — dimmed gutter
const TS = /^(\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}[.,]?\d*Z?|\d{2}:\d{2}:\d{2}(?:[.,]\d+)?Z?)(\s+)([\s\S]*)$/;
const TIME = /\d{2}:\d{2}:\d{2}/;
@@ -19,8 +28,9 @@ export function failIdx(lines: LogLine[]): number {
}
// One console line: dim time gutter + leveled body.
// ::error:: / fatal: → danger, ::warning:: → warn, ::notice:: → accent,
// everything else → muted (the log is the only place dim/muted carry density).
// ::error:: / fatal: / ERROR: → danger, ::warning:: / WARN: / "!! " → warn,
// ::notice:: → accent, ">> " → ok, everything else → muted (the log is the only
// place dim/muted carry density).
export function renderLine(text: string, key: number): ReactNode {
let gutter = '';
let rest = text;
@@ -30,8 +40,12 @@ export function renderLine(text: string, key: number): ReactNode {
gutter = mm ? mm[0] : tm[1];
rest = tm[3];
}
const m = rest.match(MSG);
let body: ReactNode;
const m = rest.match(MSG);
const term = rest.match(TERMINAL);
const level = rest.match(LEVEL);
const bang = rest.match(BANG);
const head = rest.match(HEADLINE);
if (m) {
const c = m[1] === 'error' ? C.danger : m[1] === 'warning' ? C.warn : C.accent;
body = (
@@ -41,6 +55,20 @@ export function renderLine(text: string, key: number): ReactNode {
);
} else if (rest.includes('fatal:') || rest.includes('::error::')) {
body = <span className="text-danger">{rest}</span>;
} else if (term) {
const failed = term[1] === 'failed';
body = (
<span className={failed ? 'text-danger' : 'text-ok'}>
{failed ? rest : rest.replace(/^===\s+/, '')}
</span>
);
} else if (bang || (level && /^(ERROR|FATAL)$/i.test(level[1]))) {
body = <span className="text-danger">{bang ? rest.slice(2) : level![2]}</span>;
} else if (level) {
body = <span className="text-warn">{rest}</span>;
} else if (head) {
// the run's own summary line — the row header of a pass
body = <span className="text-ok">{rest.slice(2)}</span>;
} else {
body = <span className="text-muted">{rest}</span>;
}
@@ -52,9 +80,9 @@ export function renderLine(text: string, key: number): ReactNode {
);
}
// Render a raw job log: ::group::X … ::endgroup:: collapses into a <details>,
// ::notice:: / ::warning:: / ::error:: get a colored 2px left border.
// Each line is a flex row so <pre> line structure is preserved.
// Render a raw log: ::group::X … ::endgroup:: collapses into a <details>,
// annotated lines get a colored 2px left border. Each line is a flex row so
// <pre> line structure is preserved.
export function renderLogLines(lines: LogLine[]): ReactNode[] {
const out: ReactNode[] = [];
let k = 0;
+321 -77
View File
@@ -1,16 +1,30 @@
import { useState } from 'react';
import { Copy, Pencil } from 'lucide-react';
import { ExternalLink, KeyRound, Pencil, RefreshCw, Trash2 } from 'lucide-react';
import {
Panel, Badge, Btn, IconBtn, SkeletonRow, EmptyState, ErrorInline, Toggle, toast,
Panel, Badge, Btn, SkeletonRow, EmptyState, ErrorInline, Toggle, toast,
} from '../../components/primitives';
import { api } from '../../api/client';
import { KNOWN_CONFIG_KEYS, BOOLEAN_CONFIG_KEYS } from '../../api/types';
import type { FlatConfig, Parity, RepoVariable } from '../../api/types';
import { BOOLEAN_CONFIG_KEYS, KNOWN_CONFIG_KEYS } from '../../api/types';
import type { FlatConfig, Mirror, Parity, UnitFix } from '../../api/types';
import { HEALTH_COLORS } from '../../lib/health';
import { Label } from '../shared';
import { Label, MonoInput } from '../shared';
import { errMsg, fmtInterval } from '../format';
const BOOL_KEYS: readonly string[] = [...BOOLEAN_CONFIG_KEYS];
const inputCls =
'focus-ring w-full min-w-0 rounded-ctl border border-border2 bg-panel2 px-3 py-2 font-mono text-[13px] text-text ' +
'placeholder:text-dim transition-colors duration-ctl focus:outline-none';
function fmt(n: number | null | undefined): string {
return n === null || n === undefined ? '—' : String(n);
}
function displayValue(v: string | boolean | number | undefined): string {
if (typeof v === 'boolean') return v ? 'true' : 'false';
return v === undefined || v === null ? '' : String(v);
}
// ---------------------------------------------------------------- Parity
const PARITY_ROWS = [
{ key: 'branches', label: 'branches' },
@@ -19,16 +33,30 @@ const PARITY_ROWS = [
{ key: 'assets', label: 'assets' },
] as const;
function fmt(n: number | null | undefined): string {
return n === null || n === undefined ? '—' : String(n);
}
// behind → danger with fork/upstream numbers; equal → ok; unknown → plain chip
function DeltaBadge({ row, p }: { row: (typeof PARITY_ROWS)[number]; p: Parity }) {
// behind → danger with fork/upstream numbers; equal → ok; unknown → plain chip.
// An unknown upstream count (null) is NOT "behind": non-GitHub providers cannot
// always be counted, and crying wolf on every null would make the panel noise.
// releases/assets on a refs-only mirror are NOT "behind" either: nothing was
// ever supposed to publish them, and red there trains the operator to ignore
// the red that matters.
function DeltaBadge({ row, p, releasesManaged }: {
row: (typeof PARITY_ROWS)[number]; p: Parity; releasesManaged: boolean;
}) {
const up = p.upstream?.[row.key] ?? null;
const fk = p[row.key];
if ((row.key === 'releases' || row.key === 'assets') && !releasesManaged) {
return (
<span title="this mirror publishes no releases (on_new_tag off, and no build_cmd/build_script/mirror_upstream_releases)">
<Badge>not mirrored</Badge>
</span>
);
}
if (up === null || fk === null) {
return <Badge>—</Badge>;
return (
<span title="upstream count not available for this provider">
<Badge>{fk === null ? '—' : fmt(fk)}</Badge>
</span>
);
}
if (fk < up) {
return <Badge color={HEALTH_COLORS.failed} dot={HEALTH_COLORS.failed}>{fk}/{up} behind</Badge>;
@@ -36,17 +64,27 @@ function DeltaBadge({ row, p }: { row: (typeof PARITY_ROWS)[number]; p: Parity }
return <Badge color={HEALTH_COLORS.ok} dot={HEALTH_COLORS.ok}>in sync</Badge>;
}
export function ParityPanel({ p, loading, error, onRetry }: {
export function ParityPanel({ p, loading, error, onRetry, onRecount, recounting, releasesManaged = true }: {
p: Parity | null; loading: boolean; error: string | null; onRetry: () => void;
onRecount?: () => void; recounting?: boolean; releasesManaged?: boolean;
}) {
return (
<Panel title="Parity — upstream vs fork">
<Panel
title="Parity — upstream vs fork"
action={onRecount && (
<Btn variant="ghost" className="h-8 px-2 py-0 text-[12px]" disabled={recounting} onClick={onRecount}
title="Recount both sides now (hits the network — the worker only recounts after a pass)">
<RefreshCw size={14} strokeWidth={2} className={recounting ? 'animate-spin' : ''} />
{recounting ? 'Recounting…' : 'Recount'}
</Btn>
)}
>
{loading && p === null ? (
<SkeletonRow />
) : error ? (
<ErrorInline message={error} onRetry={onRetry} />
) : !p ? (
<EmptyState title="No parity data" hint="Counts appear after the first sync." />
<EmptyState title="No parity data" hint="Counts appear after the first sync, or on demand with Recount." />
) : (
<div className="flex flex-col">
<div className="mb-2 flex items-baseline justify-between gap-2">
@@ -64,7 +102,7 @@ export function ParityPanel({ p, loading, error, onRetry }: {
</div>
<div className="flex min-w-0 items-center justify-end gap-2">
<span className="font-mono text-[13px] tabular text-text">{fmt(p[row.key])}</span>
<DeltaBadge row={row} p={p} />
<DeltaBadge row={row} p={p} releasesManaged={releasesManaged} />
</div>
</div>
))}
@@ -75,16 +113,229 @@ export function ParityPanel({ p, loading, error, onRetry }: {
);
}
// ---------------------------------------------------------------- Config
const inputCls =
'focus-ring w-full min-w-0 rounded-ctl border border-border2 bg-panel2 px-3 py-2 font-mono text-[13px] text-text ' +
'placeholder:text-dim transition-colors duration-ctl focus:outline-none';
// ---------------------------------------------------------------- Upstream
// What used to be the Actions-variables panel. The upstream URL and its token
// are no longer repo variables — they are the container's mirror record, and
// the token never leaves the process: the API only says whether one is set.
export function UpstreamPanel({ m, loading, error, onRetry }: {
m: Mirror | null; loading: boolean; error: string | null; onRetry: () => void;
}) {
const [editing, setEditing] = useState(false);
const [upstream, setUpstream] = useState('');
const [token, setToken] = useState('');
const [interval, setInterval_] = useState('0');
const [enabled, setEnabled] = useState(true);
const [busy, setBusy] = useState(false);
const [err, setErr] = useState<string | null>(null);
const [clearing, setClearing] = useState(false);
function displayValue(v: string | boolean | undefined): string {
if (typeof v === 'boolean') return v ? 'true' : 'false';
return v ?? '';
const startEdit = () => {
if (!m) return;
setUpstream(m.upstream || '');
setToken('');
setInterval_(String(m.config?.sync_interval ?? 0));
setEnabled(m.enabled);
setErr(null);
setEditing(true);
};
const save = async () => {
if (!m) return;
const n = Number(interval.trim());
if (!Number.isInteger(n) || n < 0) {
setErr('sync_interval must be a whole number of seconds (0 = container default)');
return;
}
setBusy(true);
setErr(null);
try {
// `token` is only sent when the operator typed one — an empty field means
// "keep what is stored". Clearing is its own explicit action below.
const body: { upstream?: string; token?: string; config: FlatConfig } = {
config: { enabled, sync_interval: n },
};
const up = upstream.trim();
if (up && up !== m.upstream) body.upstream = up;
if (token.trim()) body.token = token.trim();
await api.updateMirror(m.name, body);
toast('upstream settings saved');
setEditing(false);
onRetry();
} catch (e) {
setErr(errMsg(e));
} finally {
setBusy(false);
}
};
const clearToken = async () => {
if (!m) return;
setClearing(true);
setErr(null);
try {
await api.updateMirror(m.name, { token: '' });
toast('upstream token cleared');
onRetry();
} catch (e) {
setErr(errMsg(e));
} finally {
setClearing(false);
}
};
return (
<Panel
title="Upstream"
action={!editing && m !== null && (
<Btn variant="ghost" className="h-8 px-2 py-0 text-[12px]" onClick={startEdit}>
<Pencil size={14} strokeWidth={2} /> Edit
</Btn>
)}
>
{loading && m === null ? (
<SkeletonRow />
) : error ? (
<ErrorInline message={error} onRetry={onRetry} />
) : !m ? (
<EmptyState title="No mirror" hint="The upstream is the git URL this mirror follows." />
) : editing ? (
<div className="flex flex-col gap-3">
<div>
<Label className="mb-1.5">Upstream git URL</Label>
<MonoInput value={upstream} onChange={(e) => setUpstream(e.target.value)}
placeholder="https://github.com/owner/repo.git" spellCheck={false} disabled={busy}
aria-label="Upstream git URL" />
<div className="mt-1 text-[12px] leading-snug text-muted">
Changing the upstream drops the container’s cached mirror; the next pass fetches fresh.
</div>
</div>
<div>
<Label className="mb-1.5">Upstream token</Label>
<MonoInput value={token} onChange={(e) => setToken(e.target.value)} type="password"
placeholder={m.hasToken ? '•••••••• (set — type to replace)' : 'none — leave empty for public upstreams'}
spellCheck={false} disabled={busy} aria-label="Upstream token" />
<div className="mt-1 text-[12px] leading-snug text-muted">
Only needed for private upstreams. Stored in the container’s state file — never written to the repo,
never sent back to the browser.
</div>
{m.hasToken && (
<div className="mt-2">
<Btn variant="danger" className="h-8 px-2 py-0 text-[12px]" disabled={clearing || busy}
onClick={() => void clearToken()}>
<Trash2 size={14} strokeWidth={2} /> {clearing ? 'Clearing…' : 'Clear stored token'}
</Btn>
</div>
)}
</div>
<div className="flex flex-col gap-1.5 sm:flex-row sm:items-center sm:gap-3">
<Label className="w-[132px] shrink-0">Sync interval</Label>
<input value={interval} onChange={(e) => setInterval_(e.target.value)} inputMode="numeric"
disabled={busy} aria-label="Sync interval in seconds" className={`${inputCls} sm:max-w-[160px}`} />
<span className="shrink-0 font-mono text-[12px] text-dim">
0 = container default ({fmtInterval(m.intervalSec)})
</span>
</div>
<div className="flex items-center gap-3">
<Label className="w-[132px] shrink-0">Enabled</Label>
<Toggle on={enabled} onChange={setEnabled} disabled={busy} />
<span className="text-[12px] text-muted">{enabled ? 'scheduled by the worker' : 'paused — not scheduled'}</span>
</div>
{err && <ErrorInline message={err} />}
<div className="mt-1 flex justify-end gap-2">
<Btn variant="ghost" disabled={busy} onClick={() => { setEditing(false); setErr(null); }}>Cancel</Btn>
<Btn variant="primary" disabled={busy} onClick={() => void save()}>
{busy ? 'Saving…' : 'Save'}
</Btn>
</div>
</div>
) : (
<div className="flex flex-col divide-y divide-border">
<div className="flex flex-col gap-1 py-2.5">
<Label className="mb-0.5">Git URL</Label>
<a href={m.upstream} target="_blank" rel="noreferrer"
className="inline-flex min-w-0 items-center gap-1.5 font-mono text-[13px] text-accent hover:underline"
title={m.upstream}>
<span className="min-w-0 truncate">{m.upstream.replace(/^https?:\/\//, '')}</span>
<ExternalLink size={12} strokeWidth={1.5} className="shrink-0" />
</a>
</div>
<div className="flex items-center justify-between gap-2 py-2.5">
<Label>Token</Label>
{m.hasToken
? <Badge color={HEALTH_COLORS.ok} dot={HEALTH_COLORS.ok}><KeyRound size={11} strokeWidth={1.5} />•••••••• set</Badge>
: <Badge>none — anonymous</Badge>}
</div>
<div className="flex items-center justify-between gap-2 py-2.5">
<Label>Sync interval</Label>
<span className="font-mono text-[13px] tabular text-text"
title={Number(m.config?.sync_interval) > 0 ? undefined : 'inherits the container interval'}>
{Number(m.config?.sync_interval) > 0 ? fmtInterval(Number(m.config.sync_interval)) : 'container default'}
<span className="ml-1 text-[12px] text-dim">· stale at {fmtInterval(3 * m.intervalSec)}</span>
</span>
</div>
<div className="flex items-center justify-between gap-2 py-2.5">
<Label>Scheduling</Label>
{m.enabled
? <Badge color={HEALTH_COLORS.ok} dot={HEALTH_COLORS.ok}>enabled</Badge>
: <Badge color={HEALTH_COLORS.stale}>paused</Badge>}
</div>
</div>
)}
</Panel>
);
}
// ---------------------------------------------------------------- Releases unit
// Gitea creates repos as forks without the Releases unit; the web download
// route then 404s on RequireUnitReader while the API keeps working, so the
// mirror looks fine and every asset link is broken. `unitFix` is the worker's
// own verdict after the last pass — "manual" means nothing can flip it from here.
export function unitWarning(units: string[] | null, unitFix: UnitFix): { text: string; manual: boolean } | null {
const missing = !!units && !units.some((u) => u.toLowerCase().replace(/\s/g, '') === 'releases');
if (unitFix === 'manual') {
return {
manual: true,
text: 'Releases unit is OFF and no API on this Gitea could enable it. Release assets are listed by the ' +
'API but 404 on the web download route. One-time fix: repo Settings → Repository → check Releases, ' +
'then recount parity.',
};
}
if (unitFix === 'off') {
return {
manual: true,
text: 'Releases unit is OFF — the worker will try to flip it on the next pass. Assets 404 on the web ' +
'download route until it does.',
};
}
if (missing) {
return {
manual: true,
text: 'This repo has no Releases unit. Release assets will 404 on the web download route — enable it in ' +
'repo Settings → Repository.',
};
}
return null;
}
export function ReleasesUnitBanner({ m }: { m: Mirror }) {
const w = unitWarning(m.units, m.unitFix);
if (!w) return null;
return (
<div className="flex flex-col gap-2 rounded-panel border border-warn/40 bg-warn/[0.06] px-4 py-3 sm:flex-row sm:items-start sm:gap-3">
<span className="mt-[3px] h-2 w-2 shrink-0 rounded-full bg-warn" aria-hidden />
<div className="min-w-0 flex-1">
<div className="text-[13px] font-medium text-warn">Releases unit missing — assets will 404</div>
<div className="mt-1 max-w-[80ch] text-[12px] leading-relaxed text-muted">{w.text}</div>
</div>
<a href={`${m.forkUrl}/settings`} target="_blank" rel="noreferrer"
className="focus-ring inline-flex min-h-[34px] shrink-0 items-center gap-1.5 rounded-ctl border border-border2 bg-chip px-3 font-mono text-[12px] text-text transition-colors duration-ctl hover:border-accent/40 hover:text-accent">
<ExternalLink size={14} strokeWidth={1.5} /> Repo settings
</a>
</div>
);
}
// ---------------------------------------------------------------- Config
export function ConfigPanel({ parsed, loading, error, onRetry, name }: {
parsed: FlatConfig | null; loading: boolean; error: string | null;
onRetry: () => void; name: string;
@@ -106,12 +357,12 @@ export function ConfigPanel({ parsed, loading, error, onRetry, name }: {
setErr(null);
try {
await api.saveMirrorConfig(name, draft);
toast('config saved');
toast('config saved — .forker.yaml on the forker branch');
setEditing(false);
setDraft(null);
onRetry(); // refresh
} catch (e) {
setErr(e instanceof Error ? e.message : String(e));
setErr(errMsg(e));
} finally {
setBusy(false);
}
@@ -132,7 +383,7 @@ export function ConfigPanel({ parsed, loading, error, onRetry, name }: {
) : error ? (
<ErrorInline message={error} onRetry={onRetry} />
) : !parsed ? (
<EmptyState title="No config" hint="The runner reads .forker.yaml from the forker branch." />
<EmptyState title="No config" hint="The worker reads .forker.yaml from the forker branch at the start of every pass." />
) : editing && draft ? (
<div className="flex flex-col gap-3">
{KNOWN_CONFIG_KEYS.map((k) => (
@@ -140,7 +391,7 @@ export function ConfigPanel({ parsed, loading, error, onRetry, name }: {
<span className="w-40 shrink-0 font-mono text-[12px] text-muted" title={k}>{k}</span>
{BOOL_KEYS.includes(k) ? (
<Toggle
on={draft[k] === true}
on={draft[k] === true || String(draft[k]).toLowerCase() === 'true'}
onChange={(v) => setDraft({ ...draft, [k]: v })}
disabled={busy}
/>
@@ -180,7 +431,7 @@ export function ConfigPanel({ parsed, loading, error, onRetry, name }: {
<span className={`min-w-0 flex-1 truncate font-mono text-[13px] tabular ${
BOOL_KEYS.includes(k) && val ? (val === 'true' ? 'text-ok' : 'text-muted') : 'text-text'
}`} title={val}>
{val === '' ? '—' : val}
{k === 'sync_interval' && val === '0' ? '0 (container default)' : val === '' ? '—' : val}
</span>
</div>
);
@@ -191,70 +442,63 @@ export function ConfigPanel({ parsed, loading, error, onRetry, name }: {
);
}
// ---------------------------------------------------------------- Variables
export function VariablesPanel({ items, loading, error, onRetry }: {
items: RepoVariable[] | null; loading: boolean; error: string | null; onRetry: () => void;
// ---------------------------------------------------------------- Units
// `unitFix` is the worker's verdict at the end of the last pass; the Probe
// button asks for it again right now (POST /unit) so an operator who just
// flipped the setting in the Gitea UI can confirm it without waiting a tick.
export function UnitsPanel({ name, units, loading, error, onRetry, unitFix }: {
name: string; units: string[] | null; loading: boolean; error: string | null;
onRetry: () => void; unitFix?: UnitFix;
}) {
const copy = async (v: RepoVariable) => {
const [probe, setProbe] = useState<{ busy: boolean; text: string | null; kind: 'ok' | 'warn' | 'danger' }>(
{ busy: false, text: null, kind: 'ok' });
const releasesOff = unitFix === 'manual' || unitFix === 'off';
const runProbe = async () => {
setProbe({ ...probe, busy: true });
try {
await navigator.clipboard.writeText(v.value);
toast('copied');
} catch {
toast('copy failed', 'error');
const r = await api.unit(name);
// null = the repo could not be read at all — that is not "off".
const kind = r.has_releases === true ? 'ok' : r.has_releases === null ? 'warn'
: r.fix === 'manual' ? 'danger' : 'warn';
const text = r.has_releases === true
? `Releases unit: on (${(r.units || []).length} units)`
: r.has_releases === null
? `repo unreadable (fix=${r.fix}) — is the mirror still on the Gitea?`
: `Releases unit: off · fix=${r.fix}${r.fix === 'manual' ? ' — no API can flip it' : ''}`;
setProbe({ busy: false, kind, text });
} catch (e) {
setProbe({ busy: false, kind: 'danger', text: errMsg(e) });
}
};
return (
<Panel title="Variables — Actions">
{loading && items === null ? (
<SkeletonRow />
) : error ? (
<ErrorInline message={error} onRetry={onRetry} />
) : !items || items.length === 0 ? (
<EmptyState title="No variables" hint="UPSTREAM_URL lives in the repo's Actions variables." />
) : (
<div className="flex flex-col divide-y divide-border">
{items.map((v) => {
const masked = /_TOKEN$|SECRET/.test(v.name);
return (
<div key={v.name} className="flex items-center gap-2 py-2">
<div className="flex min-w-0 flex-1 flex-col gap-0.5">
<span className="truncate font-mono text-[12px] uppercase tracking-[0.08em] text-dim" title={v.name}>
{v.name}
</span>
<span className="min-w-0 truncate font-mono text-[13px] text-text"
title={masked ? undefined : v.value}>
{masked ? '••••••••' : v.value}
</span>
</div>
<IconBtn label={`Copy ${v.name}`} className="shrink-0" onClick={() => void copy(v)}>
<Copy size={16} strokeWidth={1.5} />
</IconBtn>
</div>
);
})}
</div>
)}
</Panel>
);
}
// ---------------------------------------------------------------- Units
export function UnitsPanel({ units, loading, error, onRetry }: {
units: string[] | null; loading: boolean; error: string | null; onRetry: () => void;
}) {
return (
<Panel title="Units">
<Panel
title="Units"
action={
<Btn variant="ghost" className="h-8 px-2 py-0 text-[12px]" disabled={probe.busy} onClick={() => void runProbe()}>
<RefreshCw size={14} strokeWidth={2} className={probe.busy ? 'animate-spin' : ''} /> Probe
</Btn>
}
>
{loading && units === null ? (
<SkeletonRow />
) : error ? (
<ErrorInline message={error} onRetry={onRetry} />
) : !units || units.length === 0 ? (
<EmptyState title="No units" hint="Releases must be enabled for asset mirroring — see README." />
) : probe.text ? (
<div className={`mb-3 font-mono text-[12px] ${
probe.kind === 'ok' ? 'text-ok' : probe.kind === 'warn' ? 'text-warn' : 'text-danger'}`}>
{probe.text}
</div>
) : null}
{!units || units.length === 0 ? (
<EmptyState title="No units reported" hint="The repo could not be read — releases need the Releases unit enabled." />
) : (
<div className="flex flex-wrap gap-2">
{units.map((u) => (
<Badge key={u} dot={HEALTH_COLORS.ok}>{u}</Badge>
))}
{releasesOff && <Badge color={HEALTH_COLORS.stale} dot={HEALTH_COLORS.stale}>Releases (off)</Badge>}
</div>
)}
</Panel>
+41 -1
View File
@@ -1,4 +1,4 @@
// Shared formatting / derivation helpers for Wizard / RunnerView / Settings.
// Shared formatting / derivation helpers for Wizard / WorkerView / Settings.
// Derive a default mirror name from an upstream git URL.
export function deriveName(url: string): string {
@@ -8,6 +8,19 @@ export function deriveName(url: string): string {
return last.replace(/\.git$/i, '').toLowerCase() || 'new-mirror';
}
// Whether a mirror is supposed to publish releases at all. A refs-only mirror
// (on_new_tag off, or no mirror_upstream_releases / build_cmd / build_script)
// legitimately sits at 0/N upstream releases; parity surfaces must say
// "not mirrored", never red "behind" — red there trains people to ignore the
// red that matters.
export function releasesManaged(cfg: Record<string, unknown> | undefined | null): boolean {
const c = cfg || {};
if (c.on_new_tag === false) return false;
return c.mirror_upstream_releases === true
|| Boolean(String(c.build_cmd ?? '').trim())
|| Boolean(String(c.build_script ?? '').trim());
}
// Seconds → "Mm Ss" (mono, tabular-nums keeps it aligned).
export function fmtSec(totalSec: number): string {
const s = Math.max(0, Math.floor(totalSec));
@@ -16,6 +29,33 @@ export function fmtSec(totalSec: number): string {
return `${m}m ${rem}s`;
}
// A cadence in seconds, human-compact: 60 → "60s", 300 → "5m", 3600 → "1h".
// Distinct from fmtSec: this labels an interval, not elapsed time.
export function fmtInterval(sec: number): string {
const s = Math.max(0, Math.floor(sec));
if (s === 0) return '—';
if (s < 60) return `${s}s`;
if (s < 3600) return s % 60 ? `${Math.floor(s / 60)}m ${s % 60}s` : `${Math.floor(s / 60)}m`;
const h = Math.floor(s / 3600);
return s % 3600 ? `${h}h ${Math.floor((s % 3600) / 60)}m` : `${h}h`;
}
// A unix-seconds epoch (worker status: started_at, last_tick) → "12s ago".
export function agoSec(epochSec: number | null | undefined): string {
if (!epochSec) return '—';
const s = Math.max(0, Date.now() / 1000 - epochSec);
if (s < 60) return `${Math.floor(s)}s ago`;
if (s < 3600) return `${Math.floor(s / 60)}m ago`;
if (s < 86400) return `${Math.floor(s / 3600)}h ago`;
return `${Math.floor(s / 86400)}d ago`;
}
// Seconds → "5s ago" (for uptimes measured from a start instant).
export function sinceSec(totalSec: number | null | undefined): string {
if (totalSec === null || totalSec === undefined) return '—';
return agoSec(Date.now() / 1000 - totalSec);
}
// Exact failing line for ErrorInline.
export function errMsg(e: unknown): string {
return e instanceof Error ? e.message : String(e);
+1 -1
View File
@@ -1,4 +1,4 @@
// Small shared controls for Wizard / RunnerView / Settings (primitives are separate).
// Small shared controls for Wizard / WorkerView / Settings (primitives are separate).
import React from 'react';
const INPUT =
+11 -1
View File
@@ -1,7 +1,17 @@
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
// Dev loop: run the worker (`python3 -m forker …` or `docker compose up`) and
// `npm run dev` — /api is proxied there, so the dev app is identical to the one
// the container serves from ui/dist. Override with BACKEND=http://host:port.
// (8730 for Vite, so it never collides with the container's own 8731.)
const backend = process.env.BACKEND || 'http://127.0.0.1:8741';
export default defineConfig({
plugins: [react()],
server: { port: 8731 },
server: {
port: 8730,
proxy: { '/api': { target: backend, changeOrigin: true } },
},
build: { outDir: 'dist', sourcemap: false },
});