package main
import (
"context"
"errors"
"sync"
"sync/atomic"
"testing"
"time"
"craftdesign.group/quarry/internal/obs"
"craftdesign.group/quarry/internal/zitcli"
)
func testMaint(ctx context.Context, load func() []string) *maintenance {
return newMaintenanceAt(ctx, load, 5*time.Millisecond, time.Now)
}
func quiet() []string { return nil }
func waitFor(t *testing.T, what string, cond func() bool) {
t.Helper()
for end := time.Now().Add(5 * time.Second); time.Now().Before(end); time.Sleep(2 * time.Millisecond) {
if cond() {
return
}
}
t.Errorf("FAIL: %s", what)
}
func taskOf(m *maintenance, store, task string) (zitcli.MaintTask, bool) {
for _, t := range m.Snapshot() {
if t.Store == store && t.Task == task {
return t, true
}
}
return zitcli.MaintTask{}, false
}
// One lane of width one: tasks run one at a time, in the order they
// were asked for.
func TestMaintenanceRunsOneAtATimeInOrder(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
m := testMaint(ctx, quiet)
var mu sync.Mutex
var order []string
var live, peak atomic.Int32
run := func(name string) func(context.Context) error {
return func(context.Context) error {
n := live.Add(1)
if n > peak.Load() {
peak.Store(n)
}
time.Sleep(5 * time.Millisecond)
mu.Lock()
order = append(order, name)
mu.Unlock()
live.Add(-1)
return nil
}
}
m.Request("a", "warm", run("a"))
m.Request("b", "warm", run("b"))
m.Request("c", "warm", run("c"))
waitFor(t, "the three tasks did not all run", func() bool { mu.Lock(); defer mu.Unlock(); return len(order) == 3 })
if peak.Load() != 1 {
t.Errorf("FAIL: %d tasks ran at once on a width-one lane", peak.Load())
}
mu.Lock()
if len(order) == 3 && (order[0] != "a" || order[1] != "b" || order[2] != "c") {
t.Errorf("FAIL: ran in order %v, want a b c", order)
}
mu.Unlock()
m.Wait()
if !t.Failed() {
t.Log("ok")
}
}
// A duplicate request for a store and task that is already queued is
// the same work: it coalesces, and runs once.
func TestMaintenanceCoalescesDuplicatesOfAQueuedTask(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var blocked atomic.Bool
blocked.Store(true)
m := testMaint(ctx, func() []string {
if blocked.Load() {
return []string{"test"}
}
return nil
})
var runs atomic.Int32
run := func(context.Context) error { runs.Add(1); return nil }
if !m.Request("a", "warm", run) {
t.Errorf("FAIL: the first request was refused")
}
if m.Request("a", "warm", run) || m.Request("a", "warm", run) {
t.Errorf("FAIL: a duplicate of a queued task was accepted")
}
if !m.Request("a", "other", run) || !m.Request("b", "warm", run) {
t.Errorf("FAIL: a different task or store was coalesced")
}
blocked.Store(false)
m.Wait()
if runs.Load() != 3 {
t.Errorf("FAIL: %d runs, want 3", runs.Load())
}
if !t.Failed() {
t.Log("ok")
}
}
// A request that arrives while the task is running is not lost: one
// more run is queued behind it.
func TestMaintenanceQueuesOneRunBehindARunningTask(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
m := testMaint(ctx, quiet)
started := make(chan struct{}, 4)
release := make(chan struct{})
var runs atomic.Int32
run := func(context.Context) error {
runs.Add(1)
started <- struct{}{}
<-release
return nil
}
m.Request("a", "warm", run)
<-started
if !m.Request("a", "warm", run) {
t.Errorf("FAIL: a request during a run was dropped")
}
if m.Request("a", "warm", run) {
t.Errorf("FAIL: two runs queued behind one")
}
close(release)
m.Wait()
if runs.Load() != 2 {
t.Errorf("FAIL: %d runs, want 2", runs.Load())
}
if !t.Failed() {
t.Log("ok")
}
}
// Admission is by load: while any signal is up the task does not start,
// it says which signals, and it starts once they all clear.
func TestMaintenanceWaitsOnLoadAndSaysWhich(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var mu sync.Mutex
reasons := []string{"memory", "deploy"}
m := testMaint(ctx, func() []string { mu.Lock(); defer mu.Unlock(); return append([]string(nil), reasons...) })
var ran atomic.Bool
m.Request("a", "warm", func(context.Context) error { ran.Store(true); return nil })
waitFor(t, "the task never reported waiting", func() bool {
tk, ok := taskOf(m, "a", "warm")
return ok && tk.State == "waiting" && len(tk.WaitingOn) == 2
})
time.Sleep(30 * time.Millisecond)
if ran.Load() {
t.Errorf("FAIL: the task ran while load signals were up")
}
mu.Lock()
reasons = []string{"deploy"}
mu.Unlock()
time.Sleep(30 * time.Millisecond)
if ran.Load() {
t.Errorf("FAIL: the task ran while one signal was still up")
}
tk, _ := taskOf(m, "a", "warm")
if len(tk.WaitingOn) != 1 || tk.WaitingOn[0] != "deploy" {
t.Errorf("FAIL: waiting on %v, want [deploy]", tk.WaitingOn)
}
mu.Lock()
reasons = nil
mu.Unlock()
waitFor(t, "the task did not run once load cleared", ran.Load)
m.Wait()
if !t.Failed() {
t.Log("ok")
}
}
// A second task is queued, not waiting, while the first holds the lane.
func TestMaintenanceTellsQueuedFromWaiting(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
m := testMaint(ctx, func() []string { return []string{"busy"} })
m.Request("a", "warm", func(context.Context) error { return nil })
m.Request("b", "warm", func(context.Context) error { return nil })
waitFor(t, "states are not waiting and queued", func() bool {
a, _ := taskOf(m, "a", "warm")
b, _ := taskOf(m, "b", "warm")
return a.State == "waiting" && b.State == "queued"
})
if !t.Failed() {
t.Log("ok")
}
}
// A finished task keeps its last result: how long it took and the error,
// if any.
func TestMaintenanceRemembersTheLastResult(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
m := testMaint(ctx, quiet)
m.Request("a", "warm", func(context.Context) error { time.Sleep(20 * time.Millisecond); return errors.New("boom") })
m.Request("b", "warm", func(context.Context) error { return nil })
m.Wait()
a, _ := taskOf(m, "a", "warm")
b, _ := taskOf(m, "b", "warm")
if a.State != "idle" || a.Last == nil || a.Last.Error != "boom" || a.Last.DurationMs < 20 {
t.Errorf("FAIL: a failed task reads %+v", a)
}
if b.Last == nil || b.Last.Error != "" {
t.Errorf("FAIL: a clean task reads %+v", b)
}
if !t.Failed() {
t.Log("ok")
}
}
// Every task runs as background work, so the subprocess gate's cap
// applies to it.
func TestMaintenanceTasksCarryTheBackgroundReason(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
m := testMaint(ctx, quiet)
got := make(chan string, 1)
m.Request("a", "warm", func(c context.Context) error { got <- obs.Reason(c); return nil })
if r := <-got; r != obs.ReasonMaint {
t.Errorf("FAIL: the task ran with reason %q, want %q", r, obs.ReasonMaint)
}
m.Wait()
if !t.Failed() {
t.Log("ok")
}
}
// A task that has waited more than a day shows as overdue; a fresh one
// does not.
func TestMaintenanceFlagsATaskWaitingOverADay(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var skew atomic.Int64
m := newMaintenanceAt(ctx, func() []string { return []string{"busy"} }, 5*time.Millisecond,
func() time.Time { return time.Now().Add(time.Duration(skew.Load())) })
m.Request("a", "warm", func(context.Context) error { return nil })
if tk, _ := taskOf(m, "a", "warm"); tk.Overdue {
t.Errorf("FAIL: a task that just arrived is overdue")
}
skew.Store(int64(25 * time.Hour))
if tk, _ := taskOf(m, "a", "warm"); !tk.Overdue {
t.Errorf("FAIL: a task that waited 25h is not overdue: %+v", tk)
}
if !t.Failed() {
t.Log("ok")
}
}
// Shutdown ends a running task and drops the waiting and queued ones
// without running them.
func TestMaintenanceStopsCleanlyAtShutdown(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
m := testMaint(ctx, quiet)
started := make(chan struct{})
var cancelled atomic.Bool
var later atomic.Bool
m.Request("a", "warm", func(c context.Context) error {
close(started)
<-c.Done()
cancelled.Store(true)
return c.Err()
})
<-started
m.Request("b", "warm", func(context.Context) error { later.Store(true); return nil })
cancel()
done := make(chan struct{})
go func() { m.Wait(); close(done) }()
select {
case <-done:
case <-time.After(5 * time.Second):
t.Fatal("FAIL: Wait did not return after shutdown")
}
if !cancelled.Load() {
t.Errorf("FAIL: the running task was not cancelled")
}
if later.Load() {
t.Errorf("FAIL: a queued task ran after shutdown")
}
if m.Request("c", "warm", func(context.Context) error { later.Store(true); return nil }) {
t.Errorf("FAIL: a stopped scheduler accepted work")
}
if !t.Failed() {
t.Log("ok")
}
}
// A waiting task is cancelled too.
func TestMaintenanceStopsAWaitingTask(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
m := testMaint(ctx, func() []string { return []string{"busy"} })
var ran atomic.Bool
m.Request("a", "warm", func(context.Context) error { ran.Store(true); return nil })
waitFor(t, "never waited", func() bool { tk, _ := taskOf(m, "a", "warm"); return tk.State == "waiting" })
cancel()
m.Wait()
if ran.Load() {
t.Errorf("FAIL: a waiting task ran after shutdown")
}
if !t.Failed() {
t.Log("ok")
}
}
// With no scheduler (tests, a registrar built bare) a request runs at
// once rather than vanishing.
func TestNilMaintenanceRunsTheTask(t *testing.T) {
var m *maintenance
done := make(chan struct{})
m.Request("a", "warm", func(context.Context) error { close(done); return nil })
select {
case <-done:
case <-time.After(5 * time.Second):
t.Fatal("FAIL: a nil scheduler dropped the task")
}
}
// The warm a repository gets at registration is upkeep nobody is
// waiting on yet: it goes through the maintenance lane, and its reads
// do not start until the load clears.
func TestBootWarmWaitsOnTheMaintenanceLane(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var blocked atomic.Bool
blocked.Store(true)
m := testMaint(ctx, func() []string {
if blocked.Load() {
return []string{"busy"}
}
return nil
})
s := &stubWarm{tip: "abc"}
w := warmer{maint: m, store: "s"}
var once sync.Once
<-warmEarly(ctx, &w, &once, s, s)
waitFor(t, "the boot warm never reached the lane", func() bool {
tk, ok := taskOf(m, "s", "warm reads")
return ok && tk.State == "waiting"
})
time.Sleep(20 * time.Millisecond)
if len(s.order()) != 0 {
t.Errorf("FAIL: the boot warm read the store while load was up: %v", s.order())
}
blocked.Store(false)
m.Wait()
if indexOf(s.order(), "root") < 0 {
t.Errorf("FAIL: the boot warm never ran: %v", s.order())
}
if !t.Failed() {
t.Log("ok")
}
}
// The warm after a fold that moved the tip is the reader's: it starts at
// once, whatever the maintenance lane is waiting on.
func TestPostFoldWarmDoesNotWaitOnTheMaintenanceLane(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
m := testMaint(ctx, func() []string { return []string{"busy"} })
s := &stubWarm{tip: "abc", entered: make(chan struct{}, 1)}
w := warmer{maint: m, store: "s"}
w.start(ctx, s, s)
select {
case <-s.entered:
case <-time.After(5 * time.Second):
t.Fatal("FAIL: the post-fold warm waited on the maintenance lane")
}
if !t.Failed() {
t.Log("ok")
}
}
// The lane's slot is held only while a task runs: a task held back by
// load leaves the lane idle, so the lane list never says running for
// work that has not started.
func TestMaintenanceLaneIsBusyOnlyWhileATaskRuns(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var blocked atomic.Bool
blocked.Store(true)
m := testMaint(ctx, func() []string {
if blocked.Load() {
return []string{"busy"}
}
return nil
})
started := make(chan struct{})
release := make(chan struct{})
m.Request("a", "warm", func(context.Context) error { close(started); <-release; return nil })
waitFor(t, "never waited", func() bool { tk, _ := taskOf(m, "a", "warm"); return tk.State == "waiting" })
if n := m.Lane().Stats().InFlight; n != 0 {
t.Errorf("FAIL: the lane holds %d while its task waits on load", n)
}
blocked.Store(false)
<-started
if n := m.Lane().Stats().InFlight; n != 1 {
t.Errorf("FAIL: the lane holds %d while its task runs, want 1", n)
}
close(release)
m.Wait()
if !t.Failed() {
t.Log("ok")
}
}
// A store that is removed takes its tasks with it: queued and waiting
// ones never run, a running one is cancelled, its rows go, and other
// stores' work is untouched.
func TestMaintenanceForgetDropsAStoresTasks(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
m := testMaint(ctx, quiet)
started := make(chan struct{})
var cancelled, ranGone, ranOther atomic.Bool
m.Request("gone", "warm", func(c context.Context) error {
close(started)
<-c.Done()
cancelled.Store(true)
return c.Err()
})
<-started
m.Request("gone", "other", func(context.Context) error { ranGone.Store(true); return nil })
m.Request("kept", "warm", func(context.Context) error { ranOther.Store(true); return nil })
m.Forget("gone")
// Forget returns only once the running task has ended, so a store can
// be closed straight after.
if !cancelled.Load() {
t.Errorf("FAIL: the running task of a removed store was not cancelled")
}
m.Wait()
if ranGone.Load() {
t.Errorf("FAIL: a queued task ran against a removed store")
}
if !ranOther.Load() {
t.Errorf("FAIL: another store's task was dropped")
}
for _, tk := range m.Snapshot() {
if tk.Store == "gone" {
t.Errorf("FAIL: a removed store still has a row: %+v", tk)
}
}
// A store that comes back under the same name starts clean.
if !m.Request("gone", "warm", func(context.Context) error { return nil }) {
t.Errorf("FAIL: a re-added store's task was refused")
}
m.Wait()
if !t.Failed() {
t.Log("ok")
}
}
// A task waiting on load is forgotten too.
func TestMaintenanceForgetDropsAWaitingTask(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
m := testMaint(ctx, func() []string { return []string{"busy"} })
var ran atomic.Bool
m.Request("gone", "warm", func(context.Context) error { ran.Store(true); return nil })
waitFor(t, "never waited", func() bool { tk, _ := taskOf(m, "gone", "warm"); return tk.State == "waiting" })
m.Forget("gone")
m.Wait()
if ran.Load() {
t.Errorf("FAIL: a waiting task ran after its store was forgotten")
}
if len(m.Snapshot()) != 0 {
t.Errorf("FAIL: rows remain: %+v", m.Snapshot())
}
if !t.Failed() {
t.Log("ok")
}
}