package zitcli
import (
"context"
"errors"
"testing"
"time"
"craftdesign.group/quarry/internal/obs"
"craftdesign.group/quarry/internal/ops"
)
// The gate admits its bound and no more: the next caller waits, and a
// caller whose request is cancelled while waiting is told busy rather
// than queued. Busy is an ErrUnavailable, so the surfaces above answer
// 503 with Retry-After.
func TestAdmissionBoundsSubprocesses(t *testing.T) {
a := newAdmission(2)
if !a.acquire(context.Background()) || !a.acquire(context.Background()) {
t.Fatal("the first two callers were refused")
}
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
defer cancel()
start := time.Now()
if a.acquire(ctx) {
t.Fatal("a third caller was admitted past the bound")
}
if time.Since(start) > busyWait {
t.Errorf("a cancelled caller waited the full busyWait")
}
a.release()
if !a.acquire(context.Background()) {
t.Fatal("a released slot was not reusable")
}
// The lane counts what happened, for the ops page.
if a.admitted != 3 || a.refused != 1 {
t.Errorf("lane counted admitted=%d refused=%d, want 3 and 1", a.admitted, a.refused)
}
if !errors.Is(ErrBusy, ops.ErrUnavailable) {
t.Errorf("ErrBusy is not an ErrUnavailable")
}
}
// A command minted while the gate is full fails at once with ErrBusy
// instead of spawning.
func TestCommandFailsBusyWhenTheGateIsFull(t *testing.T) {
old := Parallel()
SetParallel(1)
t.Cleanup(func() { SetParallel(old) })
if !gate.acquire(context.Background()) {
t.Fatal("could not fill the gate")
}
defer gate.release()
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Millisecond)
defer cancel()
cmd, done := New(t.TempDir()).command(ctx, "version")
defer done()
if _, err := cmd.Output(); !errors.Is(err, ErrBusy) {
t.Fatalf("command past the bound ran or failed otherwise: %v", err)
}
}
// Background callers (a reason on the context) hold at most half the
// slots; an interactive caller still finds one.
func TestAdmissionCapsBackgroundShare(t *testing.T) {
a := newAdmission(8)
bgCtx := obs.WithReason(context.Background(), obs.ReasonWarm)
for i := 0; i < 4; i++ {
if !a.acquireAs(bgCtx, true) {
t.Fatalf("FAIL: background holder %d refused under the cap", i)
}
}
ctx, cancel := context.WithTimeout(bgCtx, 50*time.Millisecond)
defer cancel()
if a.acquireAs(ctx, true) {
t.Errorf("FAIL: a fifth background caller was admitted past half the slots")
}
if !a.acquireAs(context.Background(), false) {
t.Errorf("FAIL: an interactive caller was refused while slots were free")
}
if got := len(a.slots); got != 5 {
t.Errorf("FAIL: slots held = %d, want 5 (a refused background caller must not leak one)", got)
}
a.releaseAs(true)
if !a.acquireAs(context.Background(), true) {
t.Errorf("FAIL: a released background share was not reusable")
}
if bgShare(1) != 1 || bgShare(2) != 1 || bgShare(8) != 4 {
t.Errorf("FAIL: bgShare = %d,%d,%d", bgShare(1), bgShare(2), bgShare(8))
}
if !t.Failed() {
t.Log("ok")
}
}
// A shared run begun by a warm stays background, held to the share, when
// nobody else joins it; an interactive caller joining it promotes it, so
// a visitor is not refused while interactive slots are free.
func TestSharedFlightIsPromotedOnlyWhenAnInteractiveCallerJoins(t *testing.T) {
old := Parallel()
SetParallel(2) // background share: 1
t.Cleanup(func() { SetParallel(old) })
bg := obs.WithReason(context.Background(), obs.ReasonWarm)
if !gate.acquireAs(bg, true) {
t.Fatal("could not fill the background share")
}
defer gate.releaseAs(true)
c := New(t.TempDir())
runWith := func(key string, join bool) error {
var refused error
entered := make(chan struct{})
res := make(chan error, 2)
go func() {
_, err := shared(&c.flights, bg, key, func() (int, bool) { return 0, false }, func(int) {},
func(rctx context.Context) (int, error) {
close(entered)
cmd, done := c.command(rctx, "version")
defer done()
refused = cmd.Err
return 1, nil
})
res <- err
}()
<-entered
if join {
time.Sleep(50 * time.Millisecond) // the run is waiting for the share
_, err := shared(&c.flights, context.Background(), key, func() (int, bool) { return 0, false }, func(int) {},
func(context.Context) (int, error) { return 0, nil })
if err != nil {
return err
}
}
if err := <-res; err != nil {
return err
}
return refused
}
if err := runWith("alone", false); !errors.Is(err, ErrBusy) {
t.Errorf("FAIL: a warm's shared run with no joiner escaped the background share: %v", err)
}
if err := runWith("joined", true); err != nil {
t.Errorf("FAIL: a warm's shared run joined by a visitor was refused: %v", err)
}
if !t.Failed() {
t.Log("ok")
}
}
// A free slot is never lost to an already-expired context.
func TestAdmissionFreeSlotIgnoresAnExpiredContext(t *testing.T) {
a := newAdmission(4)
ctx, cancel := context.WithCancel(obs.WithReason(context.Background(), obs.ReasonIngest))
cancel()
for i := 0; i < 20; i++ {
if !a.acquireAs(ctx, true) || !a.acquireAs(ctx, false) {
t.Fatalf("FAIL: round %d: a free slot was refused to a cancelled context", i)
}
a.releaseAs(true)
a.releaseAs(false)
}
if !t.Failed() {
t.Log("ok")
}
}