package runner
import (
"context"
"encoding/json"
"net/http/httptest"
"os"
"path/filepath"
"testing"
"time"
)
// drainRig runs a runner against a fake bridge with one job queued whose
// shell is script; it returns once the job has started.
type drainRig struct {
br *fakeBridge
r *Runner
cancel context.CancelFunc
done chan struct{}
}
func startDrainRig(t *testing.T, budget time.Duration, script string) *drainRig {
t.Helper()
marker := filepath.Join(t.TempDir(), "started")
job, _ := json.Marshal(Job{Name: "build", Steps: []JobStep{{Run: "touch " + marker + "; " + script}}})
tk := task("a", "c1")
tk.Metadata = map[string]string{JobKey: string(job)}
br := &fakeBridge{queue: map[string][]polled{"t-job": {tk}}, resolved: map[string]map[string]any{}, logs: map[string]string{}}
srv := httptest.NewServer(br.handler())
t.Cleanup(srv.Close)
r, err := New(Config{
Bridge: srv.URL, Token: "WT", Tasks: []string{"t-job"}, MaxTasks: 2,
WorkDir: t.TempDir(), Checkout: appCheckout{}, Heartbeat: time.Hour,
DrainBudget: budget, Logf: t.Logf,
})
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithCancel(context.Background())
g := &drainRig{br: br, r: r, cancel: cancel, done: make(chan struct{})}
go func() { r.Run(ctx); close(g.done) }()
t.Cleanup(cancel)
for deadline := time.Now().Add(10 * time.Second); time.Now().Before(deadline); time.Sleep(20 * time.Millisecond) {
if _, err := os.Stat(marker); err == nil {
return g
}
}
t.Fatal("FAIL: the job did not start within 10s")
return nil
}
func (g *drainRig) waitDone(t *testing.T, within time.Duration) {
t.Helper()
select {
case <-g.done:
case <-time.After(within):
t.Fatalf("FAIL: Run did not return within %s", within)
}
}
func (g *drainRig) actions() []string {
g.br.mu.Lock()
defer g.br.mu.Unlock()
return append([]string(nil), g.br.actions...)
}
// A STOP LETS THE RUNNING JOB FINISH AND CLAIMS NOTHING NEW (#419).
func TestDrainLetsTheJobFinishAndClaimsNothingNew(t *testing.T) {
g := startDrainRig(t, time.Minute, "sleep 1; echo finished-ok")
g.r.Drain()
g.br.mu.Lock()
g.br.queue["t-job"] = []polled{task("late", "c2")}
g.br.mu.Unlock()
g.waitDone(t, 15*time.Second)
g.br.mu.Lock()
defer g.br.mu.Unlock()
if got := g.br.resolved["a"]["action"]; got != "complete" {
t.Errorf("FAIL: the finished job was reported %v, want complete", got)
}
if n := len(g.br.queue["t-job"]); n != 1 {
t.Errorf("FAIL: %d tasks left queued, want the late one untouched", n)
}
if _, ok := g.br.resolved["late"]; ok {
t.Errorf("FAIL: a task queued after the stop was run")
}
if !t.Failed() {
t.Log("ok")
}
}
// A JOB THAT OUTLASTS THE BUDGET IS ENDED AND HANDED BACK, NOT FAILED.
func TestDrainHandsBackAJobThatOutlastsTheBudget(t *testing.T) {
g := startDrainRig(t, 300*time.Millisecond, "sleep 30; echo never")
g.r.Drain()
g.waitDone(t, 15*time.Second)
g.br.mu.Lock()
defer g.br.mu.Unlock()
got := g.br.resolved["a"]
if got["action"] != "pause" || got["duration_ms"] != float64(1) {
t.Errorf("FAIL: hand-back request = %v, want action pause, duration_ms 1", got)
}
if _, ok := got["checkpoint"]; !ok {
t.Errorf("FAIL: the hand-back carries no checkpoint, which the bridge's pause writes")
}
for _, a := range g.br.actions {
if a == "a fail" || a == "a complete" {
t.Errorf("FAIL: reported %q for a task that was handed back", a)
}
}
if !t.Failed() {
t.Log("ok")
}
}
// A SECOND SIGNAL ENDS AT ONCE, STILL HANDING THE TASK BACK.
func TestASecondSignalEndsAtOnceAndHandsBack(t *testing.T) {
g := startDrainRig(t, time.Hour, "sleep 30; echo never")
g.r.Drain()
g.cancel()
g.waitDone(t, 15*time.Second)
g.br.mu.Lock()
defer g.br.mu.Unlock()
if got := g.br.resolved["a"]["action"]; got != "pause" {
t.Errorf("FAIL: second signal reported %v, want a hand-back (pause)", got)
}
for _, a := range g.br.actions {
if a == "a fail" || a == "a complete" {
t.Errorf("FAIL: reported %q for a task that was handed back", a)
}
}
if !t.Failed() {
t.Log("ok")
}
}