package cibridge
import (
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
)
// RFC 0023: "Webhooks and CI | paused | paused". A held repository runs
// no CI, so a runner of it is refused on every bridge route with a reason
// it can log and a delay it must wait out, and the engine is never asked:
// nothing it has queued is claimed, nothing it has running is reported
// into. Nothing is deleted, so the lifted repository resumes.
func TestHeldRepositoryRefusesItsRunnersAtTheBridge(t *testing.T) {
var engineCalls atomic.Int32
engine := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
engineCalls.Add(1)
w.WriteHeader(http.StatusOK)
}))
defer engine.Close()
var held atomic.Bool
deliver := func(string, string, string, []string) (map[string]string, error) { return nil, nil }
token := func(string, string) (map[string]string, string, error) { return nil, "", nil }
h, err := Handler(engine.URL, "ADMIN", func(string) string { return "g" },
func(r string) bool { return r == "alpha" }, deliver, token,
WithHeld(func(repo string) bool { return repo == "alpha" && held.Load() }),
WithChanged(func(string, string) (ChangedPaths, error) { return ChangedPaths{}, nil }))
if err != nil {
t.Fatal(err)
}
routes := []string{
"/r/alpha/ci/bridge/v1/workers/connect",
"/r/alpha/ci/bridge/v1/tasks/poll",
"/r/alpha/ci/bridge/v1/tasks/t1/resolve",
"/r/alpha/ci/bridge/v1/tasks/t1/logs",
"/r/alpha/ci/bridge/v1/tasks/t1/secrets",
"/r/alpha/ci/bridge/v1/tasks/t1/token",
"/r/alpha/ci/bridge/v1/tasks/t1/changed",
}
ask := func(path string) *httptest.ResponseRecorder {
req := httptest.NewRequest("POST", path, strings.NewReader(`{"names":["X"]}`))
req.Header.Set("Authorization", "Bearer WT")
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
return rec
}
for _, p := range routes {
if rec := ask(p); rec.Header().Get(ReasonHeader) == ReasonRepoHeld {
t.Errorf("FAIL: %s refused as held while the repository was up", p)
}
}
held.Store(true)
before := engineCalls.Load()
for _, p := range routes {
rec := ask(p)
if rec.Code != http.StatusUnavailableForLegalReasons {
t.Errorf("FAIL: %s answered %d, want 451", p, rec.Code)
}
if got := rec.Header().Get(ReasonHeader); got != ReasonRepoHeld {
t.Errorf("FAIL: %s reason %q, want %q", p, got, ReasonRepoHeld)
}
if rec.Header().Get("Retry-After") == "" {
t.Errorf("FAIL: %s names no delay to wait", p)
}
}
if n := engineCalls.Load() - before; n != 0 {
t.Errorf("FAIL: the engine was asked %d times on a held repository's behalf", n)
}
held.Store(false)
if rec := ask(routes[1]); rec.Header().Get(ReasonHeader) == ReasonRepoHeld || rec.Code != http.StatusOK {
t.Errorf("FAIL: the lifted repository's poll answered %d %q", rec.Code, rec.Header().Get(ReasonHeader))
}
if !t.Failed() {
t.Log("ok")
}
}