package runner
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"craftdesign.group/quarry/internal/cibridge"
)
// A refused worker token is said once, in plain words, and the runner
// then waits instead of asking every few seconds. A token of another
// repository names it (the bridge's ReasonOtherRepo); a token the
// engine does not accept is the plain 401.
func TestRefusedWorkerTokenIsSaidOnceAndBackedOff(t *testing.T) {
cases := map[string]func(w http.ResponseWriter){
"other": func(w http.ResponseWriter) {
w.Header().Set(cibridge.ReasonHeader, cibridge.ReasonOtherRepo)
w.WriteHeader(http.StatusForbidden)
w.Write([]byte(`{"reason":"other-repo","repository":"beta"}`))
},
"unknown": func(w http.ResponseWriter) { http.Error(w, "unauthorized", http.StatusUnauthorized) },
}
for name, answer := range cases {
var calls atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
calls.Add(1)
answer(w)
}))
var mu sync.Mutex
var logged []string
r, err := New(Config{Bridge: srv.URL + "/r/alpha/ci/bridge", 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, fmt.Sprintf(f, a...))
}})
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(300 * time.Millisecond)
cancel()
<-done
srv.Close()
if n := calls.Load(); n != 1 {
t.Errorf("FAIL: %s: %d polls, want 1 then a pause", name, n)
}
mu.Lock()
if len(logged) != 1 {
t.Errorf("FAIL: %s: %d log lines, want 1: %v", name, len(logged), logged)
} else if name == "other" && !(strings.Contains(logged[0], "beta") && strings.Contains(logged[0], "alpha")) {
t.Errorf("FAIL: %s: the line does not name both repositories: %q", name, logged[0])
}
mu.Unlock()
if name == "unknown" {
if wait, _ := pauseAfter(&statusError{Code: 401}); wait < time.Minute {
t.Errorf("FAIL: a refused token pauses %s", wait)
}
}
}
if !t.Failed() {
t.Log("ok")
}
}
// The same refusal twice in a row is one line, across both loops; a
// success clears it so a later refusal is said again.
func TestRefusalNoticeRepeatsOnlyAfterSuccess(t *testing.T) {
var n int
r := &Runner{cfg: Config{Logf: func(string, ...any) { n++ }}}
r.noticeRefusal("a")
r.noticeRefusal("a")
r.clearRefusal()
r.noticeRefusal("a")
if n != 2 {
t.Errorf("FAIL: %d lines, want 2", n)
}
if !t.Failed() {
t.Log("ok")
}
}