package main
import (
"errors"
"path/filepath"
"sync"
"testing"
"time"
"craftdesign.group/quarry/internal/events"
"craftdesign.group/quarry/internal/lease"
"craftdesign.group/quarry/internal/oltp"
)
// The write lease exists to serialise writers to one store. Two
// repositories of one project hold the same project code and different
// stores, so a writer on one node and a writer on another proceed
// together; two writers to one repository are serialised.
func TestTheWriteLeaseIsTheRepositorysNotTheProjects(t *testing.T) {
ev, err := events.Start(filepath.Join(t.TempDir(), "nats"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(ev.Close)
db, err := oltp.Open(filepath.Join(t.TempDir(), "oltp.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { db.Close() })
storeA, storeB := t.TempDir(), t.TempDir()
for name, path := range map[string]string{"a": storeA, "b": storeB} {
if err := db.AddRepo(name, path, "", oltp.Public); err != nil {
t.Fatal(err)
}
if err := db.SetRepoCode(name, "one-project"); err != nil {
t.Fatal(err)
}
}
node := func(id string) *registrar {
m, err := lease.New(ev.JS(), id, 5*time.Second)
if err != nil {
t.Fatal(err)
}
t.Cleanup(m.Close)
return ®istrar{odb: db, leases: m,
codes: map[string]string{"a": "one-project", "b": "one-project"},
codeMu: &sync.Mutex{}}
}
n1, n2 := node("node-1"), node("node-2")
// Both writes are in flight at once: n2's starts while n1's is held.
inside := make(chan struct{})
release := make(chan struct{})
done := make(chan error, 1)
go func() {
done <- n1.guardPush("a", func() error { close(inside); <-release; return nil })
}()
<-inside
if err := n2.guardPush("b", func() error { return nil }); err != nil {
t.Errorf("FAIL: a write to another repository's store was refused while a sibling of the same project wrote: %v", err)
}
if err := n2.guardPush("a", func() error { return nil }); !errors.Is(err, lease.ErrNotHolder) {
t.Errorf("FAIL: a second writer to the repository being written got %v, want it refused as another node's", err)
}
close(release)
if err := <-done; err != nil {
t.Errorf("FAIL: the first write: %v", err)
}
if repoLeaseKey("a") == repoLeaseKey("b") {
t.Errorf("FAIL: two repositories share a lease key")
}
}