package api
import (
"encoding/json"
"path/filepath"
"testing"
"time"
"github.com/nats-io/nats.go"
"craftdesign.group/quarry/internal/evt"
"craftdesign.group/quarry/internal/oltp"
"craftdesign.group/quarry/internal/ops"
"craftdesign.group/quarry/internal/zitcli"
)
// acceptedEvents counts the landing.accepted events the store's fold
// raises, by landing id, from when it is called.
type acceptedEvents struct {
t *testing.T
sub *nats.Subscription
}
func watchAccepts(t *testing.T, pipeSync func() (int, error)) *acceptedEvents {
t.Helper()
// The first round after a build rebuilds from the census, which is
// not news; the second settles the once-per-process tip check, and
// only then does a round take the bus, which is the path under test.
if _, err := pipeSync(); err != nil {
t.Fatal(err)
}
sub, err := lastStoreEvents.JS().SubscribeSync("quarry.evt.test.landing.accepted", nats.DeliverNew())
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { sub.Unsubscribe() })
return &acceptedEvents{t: t, sub: sub}
}
// drain reads what has been raised so far, per landing.
func (a *acceptedEvents) drain() map[string]int {
a.t.Helper()
seen := map[string]int{}
for {
m, err := a.sub.NextMsg(500 * time.Millisecond)
if err != nil {
return seen
}
var e struct {
Kind evt.Kind
Payload map[string]any
}
if err := json.Unmarshal(m.Data, &e); err != nil {
a.t.Fatalf("body: %v", err)
}
id, _ := e.Payload["landing"].(string)
seen[id]++
}
}
// exactlyOnce asserts each named landing was announced once, and no
// other landing at all.
func (a *acceptedEvents) exactlyOnce(what string, ids ...string) {
a.t.Helper()
got := a.drain()
for _, id := range ids {
if got[id] != 1 {
a.t.Errorf("FAIL: %s: landing %.12s raised %d landing.accepted, want exactly 1 (all: %v)", what, id, got[id], got)
}
delete(got, id)
}
if len(got) != 0 {
a.t.Errorf("FAIL: %s: landing.accepted raised for landings nobody accepted: %v", what, got)
}
}
// #426: every way a landing is accepted raises landing.accepted from
// the one place a landing's state is folded, once. The paths: the
// accept op (what the page and the API call), the armed sweep, a stack
// landed whole, an accept made with zit and arriving by sync, and a
// branch merged by a plain push with no reply posted at all.
func TestEveryAcceptPathRaisesLandingAcceptedOnce(t *testing.T) {
t.Run("the accept op", func(t *testing.T) {
dir, ids, ix, pipeSync := premergeStore(t)
watch := watchAccepts(t, pipeSync)
root := ztip(t, dir, "trunk")
ci := &mergeRuns{pairRuns: &pairRuns{runs: map[string][]CIRun{}}}
ci.green(ztip(t, dir, "one"), root)
d := Deps{Version: "v", Checks: mergeChecks{}, CI: ci, Repos: NewRepos(map[string]*Repo{
"test": {Chat: "test", Index: ix, Zit: zitcli.New(dir), Sync: pipeSync}})}
if _, err := d.landingSay(as("dan", "i"), landingSayIn{Repo: "test", ID: ids[0]}, "accept"); err != nil {
t.Fatal(err)
}
// A later sync folds nothing new and must say nothing again.
if _, err := pipeSync(); err != nil {
t.Fatal(err)
}
watch.exactlyOnce("accept op", ids[0])
if !t.Failed() {
t.Log("ok")
}
})
t.Run("the armed sweep", func(t *testing.T) {
dir, ids, ix, pipeSync := premergeStore(t)
watch := watchAccepts(t, pipeSync)
root := ztip(t, dir, "trunk")
ci := &mergeRuns{pairRuns: &pairRuns{runs: map[string][]CIRun{}}}
ci.green(ztip(t, dir, "two"), root)
d := Deps{Version: "v", ZitVersion: zitcli.MinVersion, Checks: mergeChecks{}, CI: ci, Notify: &fakeNotify{},
Repos: NewRepos(map[string]*Repo{"test": {Chat: "test", Index: ix, Zit: zitcli.New(dir), Sync: pipeSync}})}
store := &sweepStub{rows: []oltp.AutoAccept{{Repo: "test", Landing: ids[1], Account: "dan", Tip: ztip(t, dir, "two")}}}
if landed := d.AutoAcceptSweep(store); len(landed) != 1 {
t.Fatalf("FAIL: the sweep landed %v, want the armed landing", landed)
}
watch.exactlyOnce("armed sweep", ids[1])
if !t.Failed() {
t.Log("ok")
}
})
t.Run("a stack landed whole", func(t *testing.T) {
dir, ids, ix, pipeSync := strataStore(t)
watch := watchAccepts(t, pipeSync)
root := ztip(t, dir, "trunk")
ci := &mergeRuns{pairRuns: &pairRuns{runs: map[string][]CIRun{}}}
ci.green(ztip(t, dir, "low"), root)
ci.green(ztip(t, dir, "high"), ztip(t, dir, "low")) // a rung is tested with its own target
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)
}
d := Deps{Version: "v", 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: pipeSync}})}
r := ops.NewRegistry()
if err := RegisterAll(r, d); err != nil {
t.Fatal(err)
}
if _, err := r.Invoke(as("dan", "i"), "landing.land", landingLandIn{Repo: "test", ID: ids["high"]}); err != nil {
t.Fatal(err)
}
watch.exactlyOnce("stack land", ids["low"], ids["high"])
if !t.Failed() {
t.Log("ok")
}
})
t.Run("an accept made with zit and synced in", func(t *testing.T) {
dir, ids, ix, pipeSync := premergeStore(t)
watch := watchAccepts(t, pipeSync)
if _, err := zitcli.New(dir).LandingAccept(testToken, ids[0], "dan", "", "", ztip(t, dir, "one")); err != nil {
t.Fatal(err)
}
if _, err := pipeSync(); err != nil {
t.Fatal(err)
}
if l, ok, _ := ix.LandingByPrefix(ids[0]); !ok || l.State != "accepted" {
t.Fatalf("FAIL: the synced landing reads %q, want accepted", l.State)
}
watch.exactlyOnce("accept by sync", ids[0])
if !t.Failed() {
t.Log("ok")
}
})
t.Run("a branch merged by a plain push", func(t *testing.T) {
dir, ids, ix, pipeSync := premergeStore(t)
watch := watchAccepts(t, pipeSync)
zrun(t, dir, "update", "trunk")
zrun(t, dir, "merge", "one")
zrun(t, dir, "commit", "-m", "merge one by hand", "--user", "u")
if _, err := pipeSync(); err != nil {
t.Fatal(err)
}
if l, ok, _ := ix.LandingByPrefix(ids[0]); !ok || l.State != "accepted" {
t.Fatalf("FAIL: the merged landing reads %q, want accepted", l.State)
}
watch.exactlyOnce("plain push", ids[0])
if !t.Failed() {
t.Log("ok")
}
})
}