Skip to content
quarry Artifact [f47ab96621]
Login

Artifact [f47ab96621]

Artifact f47ab96621a688c16eaa231d526a4707c17fdb46052712030b10cb04389853fb:


package main

import (
	"context"
	"errors"
	"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")) }

// fakeZitOnPath puts a script named "zit" first on PATH for this test.
func fakeZitOnPath(t *testing.T, script string) {
	t.Helper()
	dir := t.TempDir()
	if err := os.WriteFile(filepath.Join(dir, "zit"), []byte("#!/bin/sh\n"+script+"\n"), 0o755); err != nil {
		t.Fatal(err)
	}
	t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH"))
}

// A pack zit abandons because the store was written is reported on the
// lane as aborted, not failed: no error, no sizes, and no round started
// for a store that did not change.
func TestPackAbortedIsReportedAsAborted(t *testing.T) {
	fakeZitOnPath(t, `echo "zit pack: repository changed during pack; aborted (original is intact)" >&2; exit 1`)
	dir := t.TempDir()
	if err := os.WriteFile(filepath.Join(dir, ".zit"), make([]byte, 10), 0o644); err != nil {
		t.Fatal(err)
	}
	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)
	m.RequestOnce("s", packTask, func(c context.Context) error { return runPack(c, repo) })
	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 || tk.Last.Error != "" || tk.Last.Pack != nil {
		t.Errorf("FAIL: last = %+v, want aborted with no error and no result", tk.Last)
	}
	if syncs.Load() != 0 {
		t.Errorf("FAIL: a round was started after an aborted pack")
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// With real zit: a write during a pack aborts it, the store stays whole
// and holds the write, and the next pack completes. Whether the write
// lands inside the pack depends on the machine, so it retries with
// growing delays and skips, never fails, when no abort is ever seen.
func TestPackRealAbortLeavesStoreIntact(t *testing.T) {
	if testing.Short() {
		t.Skip("builds a large store")
	}
	dir := bigStore(t)
	c := zitcli.New(dir)
	deadline := time.Now().Add(2 * time.Minute)
	for delay := 100 * time.Millisecond; time.Now().Before(deadline); delay += 100 * time.Millisecond {
		zitRun(t, dir, "tag", "add", "--raw", fmt.Sprintf("seed%d", delay/time.Millisecond), "tip", "x")
		type result struct{ err error }
		done := make(chan result, 1)
		go func() {
			_, err := c.Pack(lease.Unguarded("test"), context.Background())
			done <- result{err}
		}()
		time.Sleep(delay)
		zitRun(t, dir, "tag", "add", "--raw", "probe", "tip", "x")
		r := <-done
		if r.err == nil {
			continue
		}
		if !errors.Is(r.err, zitcli.ErrPackAborted) {
			t.Fatalf("FAIL: pack failed with something other than an abort: %v", r.err)
		}
		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")
		}
		if _, err := c.Pack(lease.Unguarded("test"), context.Background()); err != nil {
			t.Errorf("FAIL: the store did not pack again after the abort: %v", err)
		}
		if !t.Failed() {
			t.Log("ok")
		}
		return
	}
	t.Skip("no write landed inside a pack on this machine")
}

// 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")
	}
}