package checker import ( "context" "log/slog" "sync" "sync/atomic" "testing" "time" "github.com/google/uuid" "git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi" "git.zb-server.de/ZB-Server/uptimesebi/internal/check" ) // backlogAPI hands out queued jobs as fast as the checker asks for them. type backlogAPI struct { mu sync.Mutex queued int polls int reported atomic.Int64 } func (b *backlogAPI) Jobs(ctx context.Context, max int, wait time.Duration) ([]agentapi.Job, error) { b.mu.Lock() b.polls++ n := min(max, b.queued) b.queued -= n b.mu.Unlock() if n == 0 { select { case <-time.After(min(wait, 50*time.Millisecond)): case <-ctx.Done(): } return nil, nil } jobs := make([]agentapi.Job, n) for i := range jobs { jobs[i] = agentapi.Job{MonitorID: uuid.New(), Type: "tcp", Target: "x:1"} } return jobs, nil } func (b *backlogAPI) Report(_ context.Context, rs []agentapi.Result) error { b.reported.Add(int64(len(rs))) return nil } func (b *backlogAPI) Release(context.Context) error { return nil } // TestFullCheckerTakesWorkAsSlotsFree runs a backlog through a single slot. // A checker pausing a second whenever its slots are full would need about a // second per job. func TestFullCheckerTakesWorkAsSlotsFree(t *testing.T) { const jobs = 10 api := &backlogAPI{queued: jobs} r := New(api, 1, slog.New(slog.DiscardHandler)) var ran atomic.Int64 r.run = func(context.Context, check.Spec) check.Outcome { time.Sleep(5 * time.Millisecond) ran.Add(1) return check.Outcome{OK: true} } ctx, cancel := context.WithCancel(context.Background()) done := make(chan error, 1) go func() { done <- r.Run(ctx, time.Second) }() start := time.Now() for ran.Load() < jobs && time.Since(start) < 5*time.Second { time.Sleep(5 * time.Millisecond) } took := time.Since(start) cancel() if err := <-done; err != nil { t.Errorf("Run() = %v", err) } if n := ran.Load(); n != jobs { t.Fatalf("ran %d checks in %v, want %d", n, took, jobs) } if took > 2*time.Second { t.Errorf("%d checks through one slot took %v, want well under a second each", jobs, took) } if n := api.reported.Load(); n != jobs { t.Errorf("reported %d results, want %d", n, jobs) } } // TestWaitForSlotKeepsPolling bounds the wait, so a checker whose slots // stay busy still polls as a heartbeat. func TestWaitForSlotKeepsPolling(t *testing.T) { r := New(nil, 1, slog.New(slog.DiscardHandler)) r.slots <- struct{}{} start := time.Now() r.waitForSlot(context.Background(), 50*time.Millisecond) if took := time.Since(start); took < 50*time.Millisecond || took > time.Second { t.Errorf("waitForSlot() with every slot busy returned after %v, want the bound of 50ms", took) } go func() { time.Sleep(20 * time.Millisecond) r.release() }() start = time.Now() r.waitForSlot(context.Background(), 5*time.Second) if took := time.Since(start); took > time.Second { t.Errorf("waitForSlot() returned %v after a slot was freed, want at once", took) } }