Some checks failed
ci / cargo test (abacus) (push) Has been cancelled
ci / cargo test (agent-runtime) (push) Has been cancelled
ci / cargo test (context-passport) (push) Has been cancelled
ci / cargo test (game-economy) (push) Has been cancelled
ci / cargo test (ledgerline) (push) Has been cancelled
ci / cargo test (mint) (push) Has been cancelled
ci / cargo test (rago) (push) Has been cancelled
ci / cargo test (relay) (push) Has been cancelled
ci / node suites (push) Has been cancelled
ci / cargo test (toolgate) (push) Has been cancelled
ci / cargo test (turnstile) (push) Has been cancelled
ci / cargo test (vend) (push) Has been cancelled
apps/gitea -> apps/rithub-server; compose services/containers renamed (rithub-server-app/postgres/act-runner) with explicit project name and volume names pinned to the exact existing Docker volumes (no data loss); our own GITEA_* compose/env var names -> RIT_*; new rit-admin CLI wrapper on railyard-box; giteaSession.mjs/giteaOAuth.mjs/giteaInfo.mjs -> ritSession/ritOAuth/ritInfo across 6 apps; GiteaForgeAdapter -> RitForgeAdapter + giteaSyncService/importGiteaRepos/syncGiteaRepos -> rit* in ritgram (tsc clean); apps/console/lib/gitea.ts -> lib/ritProvision.ts; Go internal/giteaclient -> internal/ritclient in rithub-async-import (go build/test clean); new /auth/rit + /forges/rit/connect routes with /gitea back-compat aliases; locale/swagger/footer/captcha template text scrubbed of remaining "Gitea" strings. Deployed to railyard-box: old containers stopped/removed, /srv/railyard-gitea renamed to /srv/rithub-server with a symlink kept, docker compose up -d from the new path, act_runner network-alias fix for its persisted instance URL. Live-verified: docker compose config diff showed zero unintended value changes, DB row counts unchanged (19 users, 635 repos), full route regression 200/expected, 0 "gitea" in headers/bodies on every checked page, real git clone+push over HTTPS and SSH with a disposable account (deleted after). Deferred on purpose (documented in plans/railyard.md): the forge discriminator / DB column names / Postgres role+volume names (data migrations, not a naming change) and the upstream GITEA__ env-to-ini keys and X-Gitea-* wire headers (hardcoded in the vendored engine binary). See plans/railyard.md RIT-OPS/RIT-BRD entry for the full old->new map and live evidence. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
223 lines
6.7 KiB
Go
223 lines
6.7 KiB
Go
package migrate
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"log"
|
|
"net/http"
|
|
"time"
|
|
|
|
"github.com/caelum0x/railyard/apps/rithub-async-import/internal/ritclient"
|
|
"github.com/caelum0x/railyard/apps/rithub-async-import/internal/jobs"
|
|
)
|
|
|
|
// RepoCreator is the subset of ritclient.Client the async path needs.
|
|
// Kept as a small interface at the point of use so tests can supply a
|
|
// fake without touching the real network.
|
|
type RepoCreator interface {
|
|
AuthenticatedUser(ctx context.Context, token string) (*ritclient.User, error)
|
|
CreateEmptyRepo(ctx context.Context, token, owner string, opts ritclient.CreateRepoOptions, isOrg bool) (*ritclient.Repo, error)
|
|
UpdateRepoDescription(ctx context.Context, token, owner, name, description string) error
|
|
}
|
|
|
|
// JobStore is the subset of jobs.Store the handler needs.
|
|
type JobStore interface {
|
|
Create(job jobs.Job) error
|
|
Get(id string) (jobs.Job, bool)
|
|
Update(id string, mutate func(*jobs.Job)) error
|
|
}
|
|
|
|
// Worker runs the slow part of a migration (clone + push) in the
|
|
// background. Production wiring passes worker.Run (see worker.go); tests
|
|
// pass a fake that updates the store instantly.
|
|
type Worker func(ctx context.Context, job jobs.Job, req Request, token string)
|
|
|
|
// Handler serves the async-import HTTP surface.
|
|
type Handler struct {
|
|
Upstream RepoCreator
|
|
Store JobStore
|
|
UpstreamBase string // e.g. http://127.0.0.1:3350 — used only for the sync-passthrough proxy
|
|
HTTPClient *http.Client // used only for the sync-passthrough proxy
|
|
Worker Worker
|
|
WorkerTTL time.Duration // background context timeout per job; zero means DefaultWorkerTTL
|
|
Logger *log.Logger
|
|
}
|
|
|
|
// DefaultWorkerTTL bounds how long a single background migration may run
|
|
// before its context is canceled, so a stuck clone/push can't leak a
|
|
// goroutine forever.
|
|
const DefaultWorkerTTL = 2 * time.Hour
|
|
|
|
func (h *Handler) logf(format string, args ...any) {
|
|
if h.Logger != nil {
|
|
h.Logger.Printf(format, args...)
|
|
}
|
|
}
|
|
|
|
// ServeMigrate handles POST /api/v1/repos/migrate.
|
|
func (h *Handler) ServeMigrate(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodPost {
|
|
writeError(w, http.StatusMethodNotAllowed, "method not allowed")
|
|
return
|
|
}
|
|
body, err := io.ReadAll(r.Body)
|
|
if err != nil {
|
|
writeError(w, http.StatusBadRequest, "reading request body: "+err.Error())
|
|
return
|
|
}
|
|
|
|
var req Request
|
|
// A body that doesn't even parse as our (superset-compatible) shape
|
|
// is still forwarded as-is to upstream rather than rejected here —
|
|
// this handler's job is to add an opt-in async path, never to be a
|
|
// stricter validator than the real engine for the sync path.
|
|
if jsonErr := json.Unmarshal(body, &req); jsonErr != nil || !req.Async {
|
|
h.proxySync(w, r, body)
|
|
return
|
|
}
|
|
|
|
if err := req.validate(); err != nil {
|
|
writeError(w, http.StatusBadRequest, err.Error())
|
|
return
|
|
}
|
|
|
|
token, ok := bearerToken(r.Header.Get("Authorization"))
|
|
if !ok {
|
|
writeError(w, http.StatusUnauthorized, "async migrate requires an Authorization: token <t> or Bearer <t> header")
|
|
return
|
|
}
|
|
|
|
ctx := r.Context()
|
|
user, err := h.Upstream.AuthenticatedUser(ctx, token)
|
|
if err != nil {
|
|
relayUpstreamError(w, err)
|
|
return
|
|
}
|
|
|
|
owner := req.RepoOwner
|
|
if owner == "" {
|
|
owner = user.Login
|
|
}
|
|
isOrg := owner != user.Login
|
|
|
|
id, err := jobs.NewID()
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "generating job id: "+err.Error())
|
|
return
|
|
}
|
|
|
|
description := req.Description
|
|
marked := "[migrating] " + description
|
|
repo, err := h.Upstream.CreateEmptyRepo(ctx, token, owner, ritclient.CreateRepoOptions{
|
|
Name: req.RepoName,
|
|
Description: marked,
|
|
Private: req.Private,
|
|
AutoInit: false,
|
|
}, isOrg)
|
|
if err != nil {
|
|
relayUpstreamError(w, err)
|
|
return
|
|
}
|
|
|
|
now := time.Now().UTC()
|
|
job := jobs.Job{
|
|
ID: id,
|
|
Status: jobs.StatusCloning,
|
|
RepoOwner: owner,
|
|
RepoName: req.RepoName,
|
|
CloneAddr: req.CloneAddr,
|
|
HTMLURL: repo.HTMLURL,
|
|
CreatedAt: now,
|
|
UpdatedAt: now,
|
|
}
|
|
if err := h.Store.Create(job); err != nil {
|
|
writeError(w, http.StatusInternalServerError, "recording job: "+err.Error())
|
|
return
|
|
}
|
|
|
|
writeJSON(w, http.StatusAccepted, map[string]any{
|
|
"id": job.ID,
|
|
"status": job.Status,
|
|
"repo_owner": job.RepoOwner,
|
|
"repo_name": job.RepoName,
|
|
"html_url": job.HTMLURL,
|
|
"status_url": fmt.Sprintf("/api/v1/repos/migrate/status/%s", job.ID),
|
|
})
|
|
|
|
ttl := h.WorkerTTL
|
|
if ttl <= 0 {
|
|
ttl = DefaultWorkerTTL
|
|
}
|
|
// Deliberately detached from r.Context(): the HTTP request is about
|
|
// to finish (that's the whole point of returning 202 immediately),
|
|
// and its context would be canceled the moment the response is
|
|
// written, killing the migration before it starts.
|
|
bgCtx, cancel := context.WithTimeout(context.Background(), ttl)
|
|
go func() {
|
|
defer cancel()
|
|
h.Worker(bgCtx, job, req, token)
|
|
}()
|
|
}
|
|
|
|
// proxySync forwards a request byte-for-byte to the real upstream
|
|
// /api/v1/repos/migrate endpoint and relays its response verbatim. This
|
|
// is the "existing sync endpoint keeps working for small repos" half of
|
|
// the contract — any caller that never sets async:true sees the exact
|
|
// behavior it always has.
|
|
func (h *Handler) proxySync(w http.ResponseWriter, r *http.Request, body []byte) {
|
|
upstreamReq, err := http.NewRequestWithContext(r.Context(), http.MethodPost, h.UpstreamBase+"/api/v1/repos/migrate", bytes.NewReader(body))
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "building upstream request: "+err.Error())
|
|
return
|
|
}
|
|
upstreamReq.Header.Set("Content-Type", "application/json")
|
|
if auth := r.Header.Get("Authorization"); auth != "" {
|
|
upstreamReq.Header.Set("Authorization", auth)
|
|
}
|
|
client := h.HTTPClient
|
|
if client == nil {
|
|
client = http.DefaultClient
|
|
}
|
|
resp, err := client.Do(upstreamReq)
|
|
if err != nil {
|
|
writeError(w, http.StatusBadGateway, "upstream request failed: "+err.Error())
|
|
return
|
|
}
|
|
defer resp.Body.Close()
|
|
respBody, err := io.ReadAll(resp.Body)
|
|
if err != nil {
|
|
writeError(w, http.StatusBadGateway, "reading upstream response: "+err.Error())
|
|
return
|
|
}
|
|
if ct := resp.Header.Get("Content-Type"); ct != "" {
|
|
w.Header().Set("Content-Type", ct)
|
|
}
|
|
w.WriteHeader(resp.StatusCode)
|
|
_, _ = w.Write(respBody)
|
|
}
|
|
|
|
func relayUpstreamError(w http.ResponseWriter, err error) {
|
|
var apiErr *ritclient.APIError
|
|
if errors.As(err, &apiErr) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(apiErr.Status)
|
|
_, _ = w.Write(apiErr.Body)
|
|
return
|
|
}
|
|
writeError(w, http.StatusBadGateway, err.Error())
|
|
}
|
|
|
|
func writeError(w http.ResponseWriter, status int, message string) {
|
|
writeJSON(w, status, map[string]string{"message": message})
|
|
}
|
|
|
|
func writeJSON(w http.ResponseWriter, status int, v any) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(status)
|
|
_ = json.NewEncoder(w).Encode(v)
|
|
}
|