package main
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"testing"
"time"
"craftdesign.group/quarry/internal/api"
"craftdesign.group/quarry/internal/ci"
"craftdesign.group/quarry/internal/events"
"craftdesign.group/quarry/internal/index"
"craftdesign.group/quarry/internal/ingest"
"craftdesign.group/quarry/internal/lease"
"craftdesign.group/quarry/internal/oltp"
"craftdesign.group/quarry/internal/zitcli"
)
// pairFixture is a repository with a landing open from feat onto trunk,
// indexed, and a fake engine that records the runs started and the
// runs cancelled.
type pairFixture struct {
dir string
id string
pipe *ingest.Pipeline
ix *index.Index
cli *zitcli.Client
srv *httptest.Server
mu sync.Mutex
cancelled []string
runs int
labels map[string]map[string]string
}
func newPairFixture(t *testing.T) *pairFixture {
t.Helper()
if _, err := exec.LookPath("zit"); err != nil {
t.Skip("zit not on PATH")
}
f := &pairFixture{labels: map[string]map[string]string{}}
dir := t.TempDir()
f.dir = dir
write := func(name, body string) {
t.Helper()
os.MkdirAll(filepath.Dir(filepath.Join(dir, name)), 0o755)
if err := os.WriteFile(filepath.Join(dir, name), []byte(body), 0o644); err != nil {
t.Fatal(err)
}
}
zitIn(t, dir, "init", ".")
write("ci/test.json", `{"name":"test","version":"1.0","steps":[]}`)
write("f.txt", "root\n")
zitIn(t, dir, "add", "ci/test.json", "f.txt")
zitIn(t, dir, "commit", "-m", "root", "--user", "u")
write("g.txt", "feat\n")
zitIn(t, dir, "add", "g.txt")
zitIn(t, dir, "commit", "-m", "feat", "--branch", "feat", "--user", "u")
f.cli = zitcli.New(dir)
id, err := f.cli.LandingOpen(lease.Unguarded("test"), "dan", "feat", "trunk", "land feat", "")
if err != nil {
t.Fatal(err)
}
f.id = id
ev, err := events.Start(filepath.Join(t.TempDir(), "nats"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(ev.Close)
f.ix, err = index.Open(filepath.Join(t.TempDir(), "index.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { f.ix.Close() })
f.pipe = ingest.NewPipeline(f.cli, ev, f.ix, "r", "n1")
if _, err := f.pipe.Sync(); err != nil {
t.Fatal(err)
}
f.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
f.mu.Lock()
defer f.mu.Unlock()
switch {
case r.URL.Path == "/workflows":
w.WriteHeader(http.StatusCreated)
w.Write([]byte(`{"status":"registered"}`))
case r.URL.Path == "/runs" && r.Method == http.MethodPost:
var body struct {
Labels map[string]string `json:"labels"`
}
json.NewDecoder(r.Body).Decode(&body)
f.runs++
f.labels[fmt.Sprintf("r-%d", f.runs)] = body.Labels
w.WriteHeader(http.StatusCreated)
fmt.Fprintf(w, `{"run_id":"r-%d"}`, f.runs)
case r.URL.Path == "/runs":
w.Write([]byte(`[]`))
case strings.HasSuffix(r.URL.Path, "/cancel"):
f.cancelled = append(f.cancelled, strings.TrimSuffix(strings.TrimPrefix(r.URL.Path, "/runs/"), "/cancel"))
case strings.HasPrefix(r.URL.Path, "/runs/"):
id := strings.TrimPrefix(r.URL.Path, "/runs/")
json.NewEncoder(w).Encode(ci.Run{RunID: id, Status: "running", Labels: f.labels[id]})
default:
http.NotFound(w, r)
}
}))
t.Cleanup(f.srv.Close)
return f
}
// registrar is a registrar over the fixture's repository and engine, as
// a freshly started process has it: nothing seen yet.
func (f *pairFixture) registrar(t *testing.T, rg *registrar) *registrar {
t.Helper()
if rg == nil {
rg = newTestRegistrar(t, 25)
}
rg.engine = ci.New(f.srv.URL)
rg.deps = &api.Deps{Repos: api.NewRepos(map[string]*api.Repo{"r": {Chat: "r", Index: f.ix, Zit: f.cli}})}
return rg
}
// A CLOSED LANDING'S MERGE RUNS ARE CANCELLED.
//
// Accepted or rejected, a landing is decided, and a verdict on its
// merge answers nobody. pikchr-studio's first deploy after a landing
// waited for a merge test started 40 seconds before the accept to run
// to its end, holding the runner the accept's own check-in needed.
func TestAClosedLandingsMergeRunsAreCancelled(t *testing.T) {
f := newPairFixture(t)
rg := f.registrar(t, nil)
ix, mu := f.ix, &f.mu
rg.landingSweep("r", ix) // seeds the open set, and starts the landing's merge run
mu.Lock()
started := f.runs
mu.Unlock()
if started != 1 {
t.Fatalf("FAIL: the open landing started %d merge runs, want 1", started)
}
rg.landingSweep("r", ix)
mu.Lock()
if len(f.cancelled) != 0 {
t.Fatalf("FAIL: an open landing's merge run was cancelled: %v", f.cancelled)
}
mu.Unlock()
zitIn(t, f.dir, "landing", "reject", f.id, "--user", "dan")
if _, err := f.pipe.Sync(); err != nil {
t.Fatal(err)
}
rg.landingSweep("r", ix)
mu.Lock()
defer mu.Unlock()
if len(f.cancelled) != 1 || f.cancelled[0] != "r-1" {
t.Fatalf("FAIL: after the landing closed, cancelled %v; want its merge run r-1", f.cancelled)
}
t.Log("ok: the merge run of an open landing kept, of a closed one cancelled")
}
// A LANDING THAT CLOSED WHILE THE FORGE WAS DOWN HAS ITS MERGE RUNS
// CANCELLED (#494).
//
// The open landings a registrar knows of are its own memory. A landing
// accepted or rejected across a restart was never seen to close, so its
// merge runs stayed live at the engine and a fresh runner took them
// first: valet ran a merge whose landing was already accepted while
// trunk's own runs waited. The first sweep after a start cancels the
// merge runs no open landing owns, and keeps the ones it does.
func TestALandingClosedAcrossARestartHasItsMergeRunsCancelled(t *testing.T) {
f := newPairFixture(t)
before := f.registrar(t, nil)
before.landingSweep("r", f.ix) // starts the landing's merge run, r-1
f.mu.Lock()
started := f.runs
f.mu.Unlock()
if started != 1 {
t.Fatalf("FAIL: the open landing started %d merge runs, want 1", started)
}
// Restarted with the landing still open: its run is kept.
f.registrar(t, ®istrar{odb: before.odb, repoQuota: 25}).landingSweep("r", f.ix)
f.mu.Lock()
if len(f.cancelled) != 0 {
t.Errorf("FAIL: a restart cancelled an open landing's merge run: %v", f.cancelled)
}
f.mu.Unlock()
// Down while the landing is rejected, then started again.
pastThisSecond()
zitIn(t, f.dir, "landing", "reject", f.id, "--user", "dan")
if _, err := f.pipe.Sync(); err != nil {
t.Fatal(err)
}
f.registrar(t, ®istrar{odb: before.odb, repoQuota: 25}).landingSweep("r", f.ix)
f.mu.Lock()
defer f.mu.Unlock()
if len(f.cancelled) != 1 || f.cancelled[0] != "r-1" {
t.Errorf("FAIL: after a restart over the landing's close, cancelled %v; want its merge run r-1", f.cancelled)
}
if !t.Failed() {
t.Log("ok")
}
}
// pastThisSecond waits into the next second: run start times are
// recorded to the second, and the orphan pass keeps a run of the second
// its read was taken in.
func pastThisSecond() {
now := time.Now()
time.Sleep(now.Truncate(time.Second).Add(time.Second + 10*time.Millisecond).Sub(now))
}
// failingTips is the index with chosen reads failing.
type failingTips struct {
ix *index.Index
tip, of bool // fail BranchTip, BranchOf
}
func (f failingTips) BranchTip(b string) (string, error) {
if f.tip {
return "", errors.New("index is closed")
}
return f.ix.BranchTip(b)
}
func (f failingTips) BranchOf(h []string) (map[string]string, error) {
if f.of {
return nil, errors.New("index is closed")
}
return f.ix.BranchOf(h)
}
// THE ORPHAN PASS CANCELS NOTHING UNLESS IT READ EVERYTHING (#494).
//
// A merge run it cancels is never started again, so a pass that misread
// which landings are open would stop a live landing's required check
// for good. Any read error, a list of open landings at its cap, a held
// repository, and a run recorded after the pass read the landings each
// leave every run alone, and all but the last ask for the pass again.
func TestTheOrphanPassCancelsNothingItCannotBeSureOf(t *testing.T) {
f := newPairFixture(t)
rg := f.registrar(t, nil)
rg.landingSweep("r", f.ix) // starts the landing's merge run, r-1
open, err := f.ix.Landings("open", openLandingsMax)
if err != nil || len(open) != 1 {
t.Fatalf("open landings: %v %v", open, err)
}
pastThisSecond()
later := time.Now().Add(time.Second)
// While the landing is open, a failed tip read must not drop it.
if done := rg.cancelOrphanPairs("r", f.ix, failingTips{ix: f.ix, tip: true}, open, later); done {
t.Errorf("FAIL: a pass whose tip read failed reported itself complete")
}
zitIn(t, f.dir, "landing", "reject", f.id, "--user", "dan")
if _, err := f.pipe.Sync(); err != nil {
t.Fatal(err)
}
closed, err := f.ix.Landings("open", openLandingsMax)
if err != nil || len(closed) != 0 {
t.Fatalf("open landings after the reject: %v %v", closed, err)
}
if err := rg.odb.AddRepo("r", f.dir, "", oltp.Public); err != nil {
t.Fatal(err)
}
full := make([]index.LandingSummary, openLandingsMax)
cases := []struct {
name string
tips tipReader
open []index.LandingSummary
asOf time.Time
held bool
wantDone bool
}{
{"branch lookup fails", failingTips{ix: f.ix, of: true}, closed, later, false, false},
{"open landings at the cap", f.ix, full, later, false, false},
{"repository held", f.ix, closed, later, true, false},
{"run recorded after the read", f.ix, closed, time.Now().Add(-time.Hour), false, true},
}
for _, c := range cases {
if c.held {
if err := rg.odb.SetTakedown(oltp.Takedown{Repo: "r", Strength: oltp.LegalHold, Category: "preservation", Actor: "dmestas"}); err != nil {
t.Fatal(err)
}
rg.refreshPrivate()
}
if done := rg.cancelOrphanPairs("r", f.ix, c.tips, c.open, c.asOf); done != c.wantDone {
t.Errorf("FAIL: %s: pass complete = %v, want %v", c.name, done, c.wantDone)
}
if c.held {
if err := rg.odb.EndTakedown("r", oltp.LegalHold, "dmestas", "test", "lifted"); err != nil {
t.Fatal(err)
}
rg.refreshPrivate()
}
}
f.mu.Lock()
if len(f.cancelled) != 0 {
t.Errorf("FAIL: cancelled %v in passes that could not be sure", f.cancelled)
}
f.mu.Unlock()
// With everything read, the closed landing's run is cancelled.
if done := rg.cancelOrphanPairs("r", f.ix, f.ix, closed, later); !done {
t.Errorf("FAIL: a pass that read everything reported itself incomplete")
}
f.mu.Lock()
defer f.mu.Unlock()
if len(f.cancelled) != 1 || f.cancelled[0] != "r-1" {
t.Errorf("FAIL: a complete pass cancelled %v; want r-1", f.cancelled)
}
if !t.Failed() {
t.Log("ok")
}
}