Skip to content
quarry Artifact [4b6b31cf20]
Login

Artifact [4b6b31cf20]

Artifact 4b6b31cf20dea4f892a6e2692e0193446b2d40b33458328e77c994c0602455bd:


package api

import (
	"errors"
	"testing"
	"time"

	"craftdesign.group/quarry/internal/ingest"
	"craftdesign.group/quarry/internal/ops"
	"craftdesign.group/quarry/internal/zitcli"
)

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

// A write that succeeded is not reported failed because its own round was
// refused by the subprocess gate: that is index lag, as a busy round is.
// A settle still refuses.
func TestSyncedTreatsAGateRefusalAsLag(t *testing.T) {
	r := &Repo{Sync: func() (int, error) { return 0, nil }, TrySync: func() (int, error) { return 0, zitcli.ErrBusy }}
	if err := r.synced(); err != nil {
		t.Errorf("FAIL: synced = %v after a gate refusal, want nil (lag)", err)
	}
	if err := r.settleSynced(); !errors.Is(err, ops.ErrUnavailable) {
		t.Errorf("FAIL: settleSynced = %v on a gate refusal, want ErrUnavailable", err)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}