package api
import (
"os/exec"
"path/filepath"
"regexp"
"strings"
"testing"
"time"
"craftdesign.group/quarry/internal/events"
"craftdesign.group/quarry/internal/index"
"craftdesign.group/quarry/internal/ingest"
"craftdesign.group/quarry/internal/oltp"
"craftdesign.group/quarry/internal/ops"
"craftdesign.group/quarry/internal/zitcli"
)
// waitStub is a sweep store that remembers the waiting reason per landing.
type waitStub struct {
rows []oltp.AutoAccept
waiting map[string]string
cleared map[string]bool
lapsed map[string]bool
}
func (s *waitStub) AutoAccepts() ([]oltp.AutoAccept, error) { return s.rows, nil }
func (s *waitStub) ClearAutoAccept(_, landing string) error {
s.cleared[landing] = true
return nil
}
func (s *waitStub) LapseAutoAccept(_, landing, _ string) error {
if s.lapsed == nil {
s.lapsed = map[string]bool{}
}
s.lapsed[landing] = true
return nil
}
func (s *waitStub) SetAutoWaiting(_, landing, reason string) { s.waiting[landing] = reason }
// armedRungs is the armed rows still live: a landing the sweep cleared
// is no longer armed.
func (s *waitStub) armed() []oltp.AutoAccept {
var out []oltp.AutoAccept
for _, r := range s.rows {
if !s.cleared[r.Landing] {
out = append(out, r)
}
}
return out
}
// threeRungs is a real store with low onto trunk, mid onto low and high
// onto mid, each touching its own file.
func threeRungs(t *testing.T) (dir string, ids map[string]string, ix *index.Index, sync func() (int, error)) {
t.Helper()
if _, err := exec.LookPath("zit"); err != nil {
t.Skip("zit not on PATH")
}
dir = t.TempDir()
zrun(t, dir, "init", ".")
zwrite(t, dir, "f.txt", "root\n")
zrun(t, dir, "add", "f.txt")
zrun(t, dir, "commit", "-m", "root", "--user", "u")
ids = map[string]string{}
for _, b := range []struct{ branch, from string }{{"low", "trunk"}, {"mid", "low"}, {"high", "mid"}} {
zrun(t, dir, "update", b.from)
zwrite(t, dir, b.branch+".txt", b.branch+"\n")
zrun(t, dir, "add", b.branch+".txt")
zrun(t, dir, "commit", "-m", b.branch, "--branch", b.branch, "--user", "u")
id, err := zitcli.New(dir).LandingOpen(testToken, "dan", b.branch, b.from, "land "+b.branch, "")
if err != nil {
t.Fatal(err)
}
ids[b.branch] = id
}
ev, err := events.Start(filepath.Join(t.TempDir(), "nats"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(ev.Close)
lastStoreEvents = ev
ix, err = index.Open(filepath.Join(t.TempDir(), "index.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { ix.Close() })
pipe := ingest.NewPipeline(zitcli.New(dir), ev, ix, "test", "n1")
if _, err := pipe.Sync(); err != nil {
t.Fatal(err)
}
return dir, ids, ix, pipe.Sync
}
func prefixDeps(t *testing.T, dir string, ix *index.Index, sync func() (int, error), ci *mergeRuns) (Deps, *oltp.DB) {
t.Helper()
db, err := oltp.Open(filepath.Join(t.TempDir(), "o.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { db.Close() })
if err := db.AddAccount("dan", "a-long-enough-password", false); err != nil {
t.Fatal(err)
}
return Deps{Version: "v", ZitVersion: zitcli.MinVersion, Checks: mergeChecks{}, CI: ci, Auto: db,
CIRunPair: func(_, _, _, _ string) error { return nil },
Repos: NewRepos(map[string]*Repo{"test": {Chat: "test", Index: ix, Zit: zitcli.New(dir), Sync: sync}})}, db
}
func stateOf(t *testing.T, ix *index.Index, id string) string {
t.Helper()
l, ok, err := ix.LandingByPrefix(id)
if err != nil || !ok {
t.Fatalf("no landing %s: %v", id, err)
}
return l.State
}
// ticket 467: every rung armed, the bottom green, the top still testing.
// The sweep lands the green prefix and says on each rung left why it
// waits; once the next rung is green the next sweep lands it.
func TestAnArmedStackLandsItsGreenPrefix(t *testing.T) {
dir, ids, ix, sync := threeRungs(t)
ci := &mergeRuns{pairRuns: &pairRuns{runs: map[string][]CIRun{}}}
ci.green(ztip(t, dir, "low"), ztip(t, dir, "trunk"))
d, _ := prefixDeps(t, dir, ix, sync, ci)
store := &waitStub{waiting: map[string]string{}, cleared: map[string]bool{}}
for _, b := range []string{"low", "mid", "high"} {
store.rows = append(store.rows, oltp.AutoAccept{Repo: "test", Landing: ids[b], Account: "dan", Tip: ztip(t, dir, b)})
}
landed := d.AutoAcceptSweep(store)
if len(landed) != 1 || landed[0] != "test/"+ids["low"] {
t.Errorf("FAIL: first sweep landed %v, want low alone", landed)
}
for b, want := range map[string]string{"low": "accepted", "mid": "open", "high": "open"} {
if got := stateOf(t, ix, ids[b]); got != want {
t.Errorf("FAIL: %s reads %q after the first sweep, want %q", b, got, want)
}
}
for _, b := range []string{"mid", "high"} {
if store.waiting[ids[b]] == "" {
t.Errorf("FAIL: armed rung %s has an empty autoWaiting", b)
}
}
if store.waiting[ids["mid"]] == store.waiting[ids["high"]] {
t.Errorf("FAIL: mid and high carry the same reason %q, each should say its own", store.waiting[ids["mid"]])
}
// mid goes green on its merge; the arms still standing are swept again.
// Judged on what it now sits on, trunk: no verdict against the rung
// it was stacked on is wanted.
ci.green(ztip(t, dir, "mid"), ztip(t, dir, "trunk"))
store.rows = store.armed()
landed = d.AutoAcceptSweep(store)
if len(landed) != 1 || landed[0] != "test/"+ids["mid"] {
t.Errorf("FAIL: second sweep landed %v, want mid alone", landed)
}
if got := stateOf(t, ix, ids["high"]); got != "open" {
t.Errorf("FAIL: high reads %q after the second sweep, want open", got)
}
if w := store.waiting[ids["high"]]; w == "" {
t.Errorf("FAIL: high has an empty autoWaiting after the second sweep")
} else if regexp.MustCompile(`\b(low|mid)\b`).MatchString(w) {
t.Errorf("FAIL: high waits on a landed rung: %q", w)
}
for b, w := range map[string]string{"mid": store.waiting[ids["mid"]]} {
if regexp.MustCompile(`\blow\b`).MatchString(w) {
t.Errorf("FAIL: %s names the landed rung low: %q", b, w)
}
}
if !t.Failed() {
t.Log("ok")
}
}
// An explicit press on the top stays whole: with a rung above the green
// bottom still testing, nothing lands.
func TestAPressedStackStillLandsAllOrNothing(t *testing.T) {
dir, ids, ix, sync := threeRungs(t)
ci := &mergeRuns{pairRuns: &pairRuns{runs: map[string][]CIRun{}}}
ci.green(ztip(t, dir, "low"), ztip(t, dir, "trunk"))
d, _ := prefixDeps(t, dir, ix, sync, ci)
r := ops.NewRegistry()
if err := RegisterAll(r, d); err != nil {
t.Fatal(err)
}
got, err := r.Invoke(as("dan", "i"), "landing.land", landingLandIn{Repo: "test", ID: ids["high"]})
if err != nil {
t.Fatal(err)
}
if out := got.(landingLandOut); len(out.Landed) != 0 {
t.Errorf("FAIL: a press with a pending rung landed %v", out.Landed)
}
if got := stateOf(t, ix, ids["low"]); got != "open" {
t.Errorf("FAIL: low reads %q after a press that could not land the stack, want open", got)
}
if !t.Failed() {
t.Log("ok")
}
}
// The listing's open count is the open landings it lists, a stack of
// three counting three.
func TestTheLandingListCountsEveryOpenLanding(t *testing.T) {
dir, _, ix, sync := threeRungs(t)
d, _ := prefixDeps(t, dir, ix, sync, &mergeRuns{pairRuns: &pairRuns{runs: map[string][]CIRun{}}})
r := ops.NewRegistry()
if err := RegisterAll(r, d); err != nil {
t.Fatal(err)
}
got, err := r.Invoke(as("dan", "i"), "landing.list", landingListIn{Repo: "test", State: "open"})
if err != nil {
t.Fatal(err)
}
out := got.(landingListOut)
if out.Open != 3 || out.Count != 3 || out.Decisions != 1 {
t.Errorf("FAIL: list reads open=%d count=%d decisions=%d, want 3, 3 and 1", out.Open, out.Count, out.Decisions)
}
if !t.Failed() {
t.Log("ok")
}
}
// trunkChecks requires the check on trunk alone: a rung above the base
// targets the rung below, which requires nothing.
type trunkChecks struct{}
func (trunkChecks) RequiredChecks(_, target string) []string {
if target == "trunk" {
return []string{"ci"}
}
return nil
}
// With checks required on trunk only (every rung is held to the base's
// set), a stack green throughout lands whole in one sweep.
func TestAnArmedStackWithTrunkOnlyChecksLandsInOneSweep(t *testing.T) {
dir, ids, ix, sync := threeRungs(t)
ci := &mergeRuns{pairRuns: &pairRuns{runs: map[string][]CIRun{}}}
ci.green(ztip(t, dir, "low"), ztip(t, dir, "trunk"))
ci.green(ztip(t, dir, "mid"), ztip(t, dir, "low"))
ci.green(ztip(t, dir, "high"), ztip(t, dir, "mid"))
d, _ := prefixDeps(t, dir, ix, sync, ci)
d.Checks = trunkChecks{}
store := &waitStub{waiting: map[string]string{}, cleared: map[string]bool{}}
for _, b := range []string{"low", "mid", "high"} {
store.rows = append(store.rows, oltp.AutoAccept{Repo: "test", Landing: ids[b], Account: "dan", Tip: ztip(t, dir, b)})
}
if landed := d.AutoAcceptSweep(store); len(landed) != 3 {
t.Errorf("FAIL: the sweep landed %v, want all three", landed)
}
for _, b := range []string{"low", "mid", "high"} {
if got := stateOf(t, ix, ids[b]); got != "accepted" {
t.Errorf("FAIL: %s reads %q, want accepted", b, got)
}
}
if !t.Failed() {
t.Log("ok")
}
}
// The sweep lands the base; a press on the top then lands the rest once
// they are green: the rung above the landed one is not "behind" for
// holding the merge of what landed beneath it.
func TestAPressAfterTheSweepLandedTheBaseLandsTheRest(t *testing.T) {
dir, ids, ix, sync := threeRungs(t)
ci := &mergeRuns{pairRuns: &pairRuns{runs: map[string][]CIRun{}}}
ci.green(ztip(t, dir, "low"), ztip(t, dir, "trunk"))
d, _ := prefixDeps(t, dir, ix, sync, ci)
store := &waitStub{waiting: map[string]string{}, cleared: map[string]bool{}}
for _, b := range []string{"low", "mid", "high"} {
store.rows = append(store.rows, oltp.AutoAccept{Repo: "test", Landing: ids[b], Account: "dan", Tip: ztip(t, dir, b)})
}
if landed := d.AutoAcceptSweep(store); len(landed) != 1 {
t.Fatalf("FAIL: the sweep landed %v, want the base alone", landed)
}
ci.green(ztip(t, dir, "mid"), ztip(t, dir, "trunk"))
ci.green(ztip(t, dir, "high"), ztip(t, dir, "mid"))
r := ops.NewRegistry()
if err := RegisterAll(r, d); err != nil {
t.Fatal(err)
}
got, err := r.Invoke(as("dan", "i"), "landing.land", landingLandIn{Repo: "test", ID: ids["high"]})
if err != nil {
t.Fatal(err)
}
if out := got.(landingLandOut); len(out.Landed) != 2 || out.Stopped != "" {
t.Errorf("FAIL: the press answered %+v, want mid and high landed", out)
}
if !t.Failed() {
t.Log("ok")
}
}
// An armed rung below the top whose tip moved since arming is lapsed and
// not carried by the top's walk; the top's arm lapses with it.
func TestAMovedArmedRungBelowTheTopIsNotLanded(t *testing.T) {
dir, ids, ix, sync := threeRungs(t)
ci := &mergeRuns{pairRuns: &pairRuns{runs: map[string][]CIRun{}}}
ci.green(ztip(t, dir, "low"), ztip(t, dir, "trunk"))
ci.green(ztip(t, dir, "mid"), ztip(t, dir, "low"))
ci.green(ztip(t, dir, "high"), ztip(t, dir, "mid"))
d, _ := prefixDeps(t, dir, ix, sync, ci)
store := &waitStub{waiting: map[string]string{}, cleared: map[string]bool{}}
store.rows = []oltp.AutoAccept{
{Repo: "test", Landing: ids["mid"], Account: "dan", Tip: ztip(t, dir, "low")},
{Repo: "test", Landing: ids["high"], Account: "dan", Tip: ztip(t, dir, "high")},
}
if landed := d.AutoAcceptSweep(store); len(landed) != 0 {
t.Errorf("FAIL: the sweep landed %v past a moved rung", landed)
}
if !store.lapsed[ids["mid"]] || !store.lapsed[ids["high"]] {
t.Errorf("FAIL: lapsed %v, want mid and high", store.lapsed)
}
if !t.Failed() {
t.Log("ok")
}
}
// handMerge merges low into trunk by hand, as a landing merge written
// from a clone, and lets edit add whatever the merge commit carries.
func handMerge(t *testing.T, dir string, edit func()) {
t.Helper()
zrun(t, dir, "update", "trunk")
zrun(t, dir, "merge", "low")
if edit != nil {
edit()
}
zrun(t, dir, "commit", "-m", "merge low", "--user", "u")
}
// A merge into the target counts as the movement it is unless its tree
// is exactly the clean merge of its parents: a file added in the merge
// commit, or an edit made in it, is work the rungs above never tested.
func TestAMergeWithEditsOfItsOwnIsWorkNotJustAMerge(t *testing.T) {
for _, c := range []struct {
name string
edit func(dir string)
want bool // true: the rung reads behind
}{
{"clean", nil, false},
{"extra file", func(dir string) {
zwrite(t, dir, "evil.txt", "evil\n")
zrun(t, dir, "add", "evil.txt")
}, true},
{"edited in the merge", func(dir string) { zwrite(t, dir, "low.txt", "resolved differently\n") }, true},
} {
dir, _, ix, sync := threeRungs(t)
handMerge(t, dir, func() {
if c.edit != nil {
c.edit(dir)
}
})
if _, err := sync(); err != nil {
t.Fatal(err)
}
d, _ := prefixDeps(t, dir, ix, sync, &mergeRuns{pairRuns: &pairRuns{runs: map[string][]CIRun{}}})
repo, _ := d.Repos.Get("test")
plain, err := ix.Behind("mid", "trunk")
if err != nil || plain == 0 {
t.Fatalf("FAIL: %s: Behind(mid, trunk) = %d, %v; the probe needs the merge to read behind", c.name, plain, err)
}
work, err := ix.BehindWork("mid", "trunk", cleanMergeOf(repo))
if err != nil {
t.Fatal(err)
}
if (work > 0) != c.want {
t.Errorf("FAIL: %s: BehindWork = %d, want behind=%v", c.name, work, c.want)
}
if nilWork, _ := ix.BehindWork("mid", "trunk", nil); nilWork == 0 {
t.Errorf("FAIL: %s: with no way to read a merge's tree it must count as work", c.name)
}
}
if !t.Failed() {
t.Log("ok")
}
}
// A plain accept and a stack walk merge onto one target one at a time:
// each waits for the repository's land lock.
func TestAPlainAcceptAndTheSweepTakeTheLandLock(t *testing.T) {
dir, ids, ix, sync := threeRungs(t)
d, _ := prefixDeps(t, dir, ix, sync, &mergeRuns{pairRuns: &pairRuns{runs: map[string][]CIRun{}}})
d.Checks = nil
r := ops.NewRegistry()
if err := RegisterAll(r, d); err != nil {
t.Fatal(err)
}
unlock := landLock("test")
acc := make(chan error, 1)
go func() {
_, err := r.Invoke(as("dan", "i"), "landing.accept", landingSayIn{Repo: "test", ID: ids["low"]})
acc <- err
}()
store := &waitStub{waiting: map[string]string{}, cleared: map[string]bool{}}
store.rows = []oltp.AutoAccept{
{Repo: "test", Landing: ids["mid"], Account: "dan", Tip: ztip(t, dir, "mid")},
{Repo: "test", Landing: ids["high"], Account: "dan", Tip: ztip(t, dir, "high")},
}
swept := make(chan struct{})
go func() { d.AutoAcceptSweep(store); close(swept) }()
select {
case err := <-acc:
t.Errorf("FAIL: a plain accept merged while the land lock was held (%v)", err)
case <-swept:
t.Errorf("FAIL: the sweep walked while the land lock was held")
case <-time.After(500 * time.Millisecond):
}
unlock()
for range 2 {
select {
case <-acc:
case <-swept:
case <-time.After(20 * time.Second):
t.Fatal("FAIL: a path never finished after the lock was released")
}
}
if !t.Failed() {
t.Log("ok")
}
}
// A base merged into trunk outside the forge reads accepted, yet the
// rung above it still names it as its target. The stack's checks are
// those of trunk where it went: the press and the sweep both refuse until
// the rungs have green runs against it.
func TestAStackOnAHandMergedBaseStillNeedsItsRunsOnTrunk(t *testing.T) {
setup := func(t *testing.T) (string, map[string]string, *index.Index, Deps, *mergeRuns) {
dir, ids, ix, sync := threeRungs(t)
handMerge(t, dir, nil)
if _, err := sync(); err != nil {
t.Fatal(err)
}
if got := stateOf(t, ix, ids["low"]); got != "accepted" {
t.Fatalf("FAIL: the hand merge left low %q, the probe needs accepted", got)
}
ci := &mergeRuns{pairRuns: &pairRuns{runs: map[string][]CIRun{}}}
d, _ := prefixDeps(t, dir, ix, sync, ci)
d.Checks = trunkChecks{}
return dir, ids, ix, d, ci
}
press := func(t *testing.T, d Deps, id string) landingLandOut {
r := ops.NewRegistry()
if err := RegisterAll(r, d); err != nil {
t.Fatal(err)
}
got, err := r.Invoke(as("dan", "i"), "landing.land", landingLandIn{Repo: "test", ID: id})
if err != nil {
t.Fatal(err)
}
return got.(landingLandOut)
}
rows := func(dir string, ids map[string]string) []oltp.AutoAccept {
var out []oltp.AutoAccept
for _, b := range []string{"mid", "high"} {
out = append(out, oltp.AutoAccept{Repo: "test", Landing: ids[b], Account: "dan", Tip: ztip(t, dir, b)})
}
return out
}
dir, ids, ix, d, ci := setup(t)
// The sweep comes first: a press may start runs of its own, and the
// sweep must be shown to land nothing before it has any.
store := &waitStub{waiting: map[string]string{}, cleared: map[string]bool{}, rows: rows(dir, ids)}
if landed := d.AutoAcceptSweep(store); len(landed) != 0 {
t.Errorf("FAIL: the sweep landed %v with no runs on trunk", landed)
}
if out := press(t, d, ids["high"]); len(out.Landed) != 0 {
t.Errorf("FAIL: a press landed %v with no runs on trunk", out.Landed)
}
ci.green(ztip(t, dir, "mid"), ztip(t, dir, "trunk"))
ci.green(ztip(t, dir, "high"), ztip(t, dir, "mid"))
if out := press(t, d, ids["high"]); len(out.Landed) != 2 {
t.Errorf("FAIL: with green runs the press landed %v, want mid and high", out.Landed)
}
if got := stateOf(t, ix, ids["high"]); got != "accepted" {
t.Errorf("FAIL: high reads %q after the press", got)
}
dir, ids, _, d, ci = setup(t)
ci.green(ztip(t, dir, "mid"), ztip(t, dir, "trunk"))
ci.green(ztip(t, dir, "high"), ztip(t, dir, "mid"))
store = &waitStub{waiting: map[string]string{}, cleared: map[string]bool{}, rows: rows(dir, ids)}
if landed := d.AutoAcceptSweep(store); len(landed) != 2 {
t.Errorf("FAIL: with green runs the sweep landed %v, want mid and high", landed)
}
if !t.Failed() {
t.Log("ok")
}
}
// An armed rung on a hand-merged base is judged where the base went
// (trunk): a failed run there is told to the armer, as for any rung.
func TestAnArmedRungOnAHandMergedBaseIsToldItsRunFailed(t *testing.T) {
dir, ids, ix, sync := threeRungs(t)
handMerge(t, dir, nil)
if _, err := sync(); err != nil {
t.Fatal(err)
}
ci := &mergeRuns{pairRuns: &pairRuns{runs: map[string][]CIRun{}}}
pair := "pair:" + ztip(t, dir, "mid") + ":" + ztip(t, dir, "trunk")
ci.runs[pair] = []CIRun{{Checkin: pair, Workflow: "ci", Pipeline: "ci", Status: "failure"}}
ci.order = append(ci.order, pair)
d, _ := prefixDeps(t, dir, ix, sync, ci)
d.Checks = trunkChecks{}
d.LandingNumbers = landingNumberDB(t)
store := &waitStub{waiting: map[string]string{}, cleared: map[string]bool{},
rows: []oltp.AutoAccept{{Repo: "test", Landing: ids["mid"], Account: "dan", Tip: ztip(t, dir, "mid")}}}
d.AutoAcceptSweep(store)
if w := store.waiting[ids["mid"]]; !strings.HasPrefix(w, "failed: ") {
t.Errorf("FAIL: the armer of a rung on a hand-merged base reads %q, want its failure", w)
}
if !t.Failed() {
t.Log("ok")
}
}
// Updating a rung from trunk, where its hand-merged base went, adds
// nothing of the rung's own: its arm stands.
func TestUpdatingARungOnAHandMergedBaseFromTrunkKeepsItsArm(t *testing.T) {
dir, ids, ix, sync := threeRungs(t)
handMerge(t, dir, nil)
armedTip := ztip(t, dir, "mid")
zrun(t, dir, "update", "mid")
zrun(t, dir, "merge", "trunk")
zrun(t, dir, "commit", "-m", "update mid from trunk", "--user", "u")
if _, err := sync(); err != nil {
t.Fatal(err)
}
if ztip(t, dir, "mid") == armedTip {
t.Fatalf("FAIL: the update wrote no check-in")
}
d, _ := prefixDeps(t, dir, ix, sync, &mergeRuns{pairRuns: &pairRuns{runs: map[string][]CIRun{}}})
if tip, _ := d.armedTipMoved(oltp.AutoAccept{Repo: "test", Landing: ids["mid"], Tip: armedTip}); tip != "" {
t.Errorf("FAIL: an update from trunk read as a change the armer has not seen (%s)", tip)
}
if !t.Failed() {
t.Log("ok")
}
}