package api
import (
"errors"
"testing"
"time"
"craftdesign.group/quarry/internal/ingest"
"craftdesign.group/quarry/internal/ops"
)
// A write whose store is busy with another round returns at once with
// success: the write is durable, the running round takes it in (#481).
// A settle in the same state answers busy instead of merging on a stale
// index, and neither waits past its bound.
func TestSyncedNeverWaitsOnABusyStore(t *testing.T) {
ow, os := writeSyncWait, settleSyncWait
writeSyncWait, settleSyncWait = 50*time.Millisecond, 80*time.Millisecond
t.Cleanup(func() { writeSyncWait, settleSyncWait = ow, os })
calls := 0
r := &Repo{
Sync: func() (int, error) { t.Error("FAIL: Sync used where TrySync is set"); return 0, nil },
TrySync: func() (int, error) { calls++; return 0, ingest.ErrRoundBusy },
}
start := time.Now()
if err := r.synced(); err != nil {
t.Errorf("FAIL: synced on a busy store = %v, want nil", err)
}
if d := time.Since(start); d > time.Second {
t.Errorf("FAIL: synced waited %v", d)
}
if err := r.settleSynced(); !errors.Is(err, ops.ErrUnavailable) {
t.Errorf("FAIL: settleSynced on a busy store = %v, want ErrUnavailable", err)
}
if calls < 2 {
t.Errorf("FAIL: TrySync tried %d times, want a retry within the bound", calls)
}
// A store that frees up within the bound is synced normally.
settleSyncWait = time.Second
n := 0
r.TrySync = func() (int, error) {
n++
if n < 3 {
return 0, ingest.ErrRoundBusy
}
return 1, nil
}
if err := r.settleSynced(); err != nil {
t.Errorf("FAIL: settleSynced once free = %v", err)
}
if !t.Failed() {
t.Log("ok")
}
}