package runner
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"craftdesign.group/quarry/internal/cibridge"
)
// A runner of a repository under a takedown (RFC 0023) is refused at the
// bridge with ReasonRepoHeld. It must wait out what it was told rather
// than ask every few seconds: the delay is the bridge's Retry-After, a
// long default when none comes, and the ordinary pause for any other
// failure.
func TestHeldRepositoryPausesAPollNotSpinsIt(t *testing.T) {
held := &statusError{Code: 451, Path: "/v1/tasks/poll", Reason: cibridge.ReasonRepoHeld, RetryAfter: 300 * time.Second}
if got, isHeld := pauseAfter(held); got != 300*time.Second || !isHeld {
t.Errorf("FAIL: a held refusal pauses %s (held=%v), want the bridge's 5m0s", got, isHeld)
}
held.RetryAfter = 0
if got, isHeld := pauseAfter(held); got < time.Minute || !isHeld {
t.Errorf("FAIL: a held refusal with no delay pauses %s (held=%v), want at least a minute", got, isHeld)
}
if got, isHeld := pauseAfter(&statusError{Code: 503}); got != pollFailPause || isHeld {
t.Errorf("FAIL: an ordinary failure pauses %s (held=%v), want %s", got, isHeld, pollFailPause)
}
var calls atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
calls.Add(1)
w.Header().Set(cibridge.ReasonHeader, cibridge.ReasonRepoHeld)
w.Header().Set("Retry-After", "300")
w.WriteHeader(http.StatusUnavailableForLegalReasons)
}))
defer srv.Close()
var mu sync.Mutex
var logged []string
r, err := New(Config{Bridge: srv.URL, Token: "WT", Tasks: []string{"t"}, MaxTasks: 1, WorkDir: t.TempDir(),
Checkout: appCheckout{}, Logf: func(f string, a ...any) {
mu.Lock()
defer mu.Unlock()
logged = append(logged, f)
}})
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
go func() { r.pollLoop(ctx, "t"); close(done) }()
time.Sleep(700 * time.Millisecond)
cancel()
select {
case <-done:
case <-time.After(2 * time.Second):
t.Fatal("FAIL: the poll loop did not stop on cancel while paused")
}
if n := calls.Load(); n != 1 {
t.Errorf("FAIL: %d polls in the pause, want 1", n)
}
mu.Lock()
defer mu.Unlock()
if len(logged) != 1 || !strings.Contains(logged[0], "poll") {
t.Errorf("FAIL: %d log lines for the refusal, want 1: %v", len(logged), logged)
}
if !t.Failed() {
t.Log("ok")
}
}