package main
import (
"context"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"sync/atomic"
"testing"
"time"
"craftdesign.group/quarry/internal/api"
"craftdesign.group/quarry/internal/lease"
"craftdesign.group/quarry/internal/zitcli"
)
func zitRun(t *testing.T, dir string, args ...string) string {
t.Helper()
cmd := exec.Command("zit", args...)
cmd.Dir = dir
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("zit %v: %v\n%s", args, err, out)
}
return string(out)
}
// bigStore makes a store whose pack takes a couple of seconds, long
// enough for a write to land inside it.
func bigStore(t *testing.T) string {
t.Helper()
if _, err := exec.LookPath("zit"); err != nil {
t.Skip("zit not on PATH")
}
dir := t.TempDir()
zitRun(t, dir, "init")
if err := os.Mkdir(filepath.Join(dir, "d"), 0o755); err != nil {
t.Fatal(err)
}
for i := 0; i < 30000; i++ {
body := strings.Repeat(fmt.Sprintf("line %d %s\n", i, strings.Repeat("x", i%50)), 20)
if err := os.WriteFile(filepath.Join(dir, "d", fmt.Sprintf("f%d.txt", i)), []byte(body), 0o644); err != nil {
t.Fatal(err)
}
}
zitRun(t, dir, "add", ".")
zitRun(t, dir, "commit", "-m", "many")
return dir
}
func unguarded(fn func(lease.Token) error) error { return fn(lease.Unguarded("test")) }
// A write that lands during a pack aborts it cleanly: the store is
// intact and holds the write, the task reports aborted (not failed),
// no round is started for a store that did not change, and asking
// again packs the store as it now stands.
func TestPackAbortedByAWriteLeavesTheStoreIntact(t *testing.T) {
dir := bigStore(t)
var syncs atomic.Int32
repo := &api.Repo{
Zit: zitcli.New(dir), Guard: unguarded,
Sync: func() (int, error) { syncs.Add(1); return 0, nil },
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
m := testMaint(ctx, quiet)
if !m.RequestOnce("s", packTask, func(c context.Context) error { return runPack(c, repo) }) {
t.Fatal("FAIL: the pack was not queued")
}
waitFor(t, "pack running", func() bool { tk, ok := taskOf(m, "s", packTask); return ok && tk.State == "running" })
time.Sleep(300 * time.Millisecond)
zitRun(t, dir, "tag", "add", "--raw", "probe", "tip", "x")
waitFor(t, "pack ended", func() bool { tk, ok := taskOf(m, "s", packTask); return ok && tk.State == "idle" && tk.Last != nil })
tk, _ := taskOf(m, "s", packTask)
if tk.Last == nil || !tk.Last.Aborted {
t.Fatalf("FAIL: last = %+v, want aborted", tk.Last)
}
if tk.Last.Error != "" || tk.Last.Pack != nil {
t.Errorf("FAIL: an aborted pack carries error %q / result %+v, want neither", tk.Last.Error, tk.Last.Pack)
}
if got := zitRun(t, dir, "tag", "list", "--raw", "tip"); !strings.Contains(got, "probe") {
t.Errorf("FAIL: the write made during the pack is not in the store: %q", got)
}
if syncs.Load() != 0 {
t.Errorf("FAIL: a round was started after an aborted pack")
}
// The store is whole: the next pack, which verifies every frame,
// completes and reports sizes.
if !m.RequestOnce("s", packTask, func(c context.Context) error { return runPack(c, repo) }) {
t.Fatal("FAIL: the retry was refused")
}
waitFor(t, "retry ended", func() bool {
tk, ok := taskOf(m, "s", packTask)
return ok && tk.State == "idle" && tk.Last != nil && !tk.Last.Aborted
})
tk, _ = taskOf(m, "s", packTask)
if tk.Last == nil || tk.Last.Error != "" || tk.Last.Pack == nil || tk.Last.Pack.Before <= 0 || tk.Last.Pack.After <= 0 {
t.Errorf("FAIL: retry last = %+v, want sizes", tk.Last)
}
if !t.Failed() {
t.Log("ok")
}
}
// A second request for the same pack, while one is queued or running,
// adds nothing; once it has ended a new one is accepted.
func TestPackRequestIsRefusedWhileQueuedOrRunning(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
m := testMaint(ctx, quiet)
hold := make(chan struct{})
var runs atomic.Int32
run := func(context.Context) error { runs.Add(1); <-hold; return nil }
if !m.RequestOnce("s", packTask, run) {
t.Fatal("FAIL: first request refused")
}
if m.RequestOnce("s", packTask, run) {
t.Errorf("FAIL: a second request was queued while the first was pending")
}
waitFor(t, "running", func() bool { tk, ok := taskOf(m, "s", packTask); return ok && tk.State == "running" })
if m.RequestOnce("s", packTask, run) {
t.Errorf("FAIL: a second request was queued while the first was running")
}
if !m.RequestOnce("other", packTask, func(context.Context) error { return nil }) {
t.Errorf("FAIL: another store's pack was refused")
}
close(hold)
waitFor(t, "ended", func() bool { tk, ok := taskOf(m, "s", packTask); return ok && tk.State == "idle" })
if !m.RequestOnce("s", packTask, func(context.Context) error { return nil }) {
t.Errorf("FAIL: a request after the run ended was refused")
}
m.Wait()
if runs.Load() != 1 {
t.Errorf("FAIL: the held pack ran %d times, want 1", runs.Load())
}
if !t.Failed() {
t.Log("ok")
}
}