package api
import (
"errors"
"path/filepath"
"sync"
"testing"
"craftdesign.group/quarry/internal/oltp"
"craftdesign.group/quarry/internal/ops"
)
func TestTwoPromotionsOfOneLocalTicketAtOnceWriteOneTicketArtifact(t *testing.T) {
ix, z, _ := attachStore(t)
db, err := oltp.Open(filepath.Join(t.TempDir(), "oltp.db"))
if err != nil {
t.Fatal(err)
}
defer db.Close()
local, err := db.LocalTicketNew("test", "lou", "", map[string]string{"title": "promote me once", "status": "Open"})
if err != nil {
t.Fatal(err)
}
r := ops.NewRegistry()
if err := RegisterAll(r, Deps{Version: "v", Repos: NewRepos(map[string]*Repo{"test": {Index: ix, Zit: z}}), Local: db}); err != nil {
t.Fatal(err)
}
const n = 2
var start, done sync.WaitGroup
start.Add(1)
ids := make([]string, n)
errs := make([]error, n)
for i := 0; i < n; i++ {
done.Add(1)
go func(i int) {
defer done.Done()
start.Wait()
out, err := r.Invoke(as("adm", "a"), "ticket.promote", ticketPromoteIn{Repo: "test", ID: local[:12]})
if err == nil {
ids[i] = out.(ticketPromoteOut).ID
}
errs[i] = err
}(i)
}
start.Done()
done.Wait()
written := map[string]bool{}
var refused []error
for i := range ids {
if errs[i] == nil {
written[ids[i]] = true
} else {
refused = append(refused, errs[i])
}
}
if len(written) != 1 || len(refused) != n-1 {
t.Fatalf("FAIL: %d concurrent promotions wrote ticket artifacts %v and refused %v; want one artifact and one refusal", n, written, refused)
}
t.Logf("ok: one promotion wrote the ticket artifact")
if !errors.Is(refused[0], ops.ErrInvalid) {
t.Fatalf("FAIL: the losing promotion failed with %v, want a refusal", refused[0])
}
t.Logf("ok: the other was refused: %v", refused[0])
for id := range written {
if to, ok := db.LocalTicketRedirect("test", local[:12]); !ok || to != id {
t.Fatalf("FAIL: the local id redirects to %q (%v), want the one artifact %s", to, ok, id)
}
}
t.Logf("ok: the local id redirects to the one artifact")
}