Files
uptimesebi/internal/schedule/schedule_test.go
Sebastian UnterschützandClaude Opus 5.5 4f57cafbdd fix(schedule): keep monitors created while reconciliation reads the database
Reconciliation removed every monitor missing from its database read,
including ones created in the meantime; they stayed unscheduled until
the next run a minute later. Upserts now record when they happened and
reconciliation only prunes entries older than its read.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-22 08:48:10 +01:00

227 lines
6.6 KiB
Go

package schedule
import (
"context"
"os"
"testing"
"time"
"github.com/google/uuid"
"github.com/redis/go-redis/v9"
)
func newTest(t *testing.T) (*Scheduler, *time.Time) {
t.Helper()
url := os.Getenv("UPTIME_TEST_REDIS_URL")
if url == "" {
t.Skip("UPTIME_TEST_REDIS_URL not set")
}
opts, err := redis.ParseURL(url)
if err != nil {
t.Fatal(err)
}
rdb := redis.NewClient(opts)
t.Cleanup(func() { _ = rdb.Close() })
if err := rdb.FlushDB(context.Background()).Err(); err != nil {
t.Fatal(err)
}
now := time.UnixMilli(1_800_000_000_000)
s := New(rdb)
s.now = func() time.Time { return now }
return s, &now
}
func takeAll(t *testing.T, s *Scheduler, inst uuid.UUID) []Entry {
t.Helper()
e, err := s.Take(context.Background(), inst, 1000, 0)
if err != nil {
t.Fatalf("Take() failed: %v", err)
}
return e
}
func mustDispatch(t *testing.T, s *Scheduler) int {
t.Helper()
n, err := s.Dispatch(context.Background())
if err != nil {
t.Fatalf("Dispatch() failed: %v", err)
}
return n
}
// TestDispatchSpreadsRandomly runs many monitors against three instances of
// one region and expects every instance to get a substantial share.
func TestDispatchSpreadsRandomly(t *testing.T) {
s, _ := newTest(t)
ctx := context.Background()
insts := []uuid.UUID{uuid.New(), uuid.New(), uuid.New()}
for _, in := range insts {
if err := s.Heartbeat(ctx, "eu", in); err != nil {
t.Fatal(err)
}
}
const monitors = 600
for range monitors {
if err := s.Upsert(ctx, Monitor{ID: uuid.New(), Interval: time.Minute, Regions: []string{"eu"}}, nil); err != nil {
t.Fatal(err)
}
}
if n := mustDispatch(t, s); n != monitors {
t.Fatalf("Dispatch() = %d, want %d", n, monitors)
}
total := 0
for _, in := range insts {
got := len(takeAll(t, s, in))
total += got
if got < monitors/3-80 || got > monitors/3+80 {
t.Errorf("instance received %d of %d jobs, want about %d", got, monitors, monitors/3)
}
}
if total != monitors {
t.Errorf("instances received %d jobs, want %d", total, monitors)
}
}
func TestDispatchReschedulesAndKeepsRegionsApart(t *testing.T) {
s, now := newTest(t)
ctx := context.Background()
eu, us := uuid.New(), uuid.New()
_ = s.Heartbeat(ctx, "eu", eu)
_ = s.Heartbeat(ctx, "us", us)
m := Monitor{ID: uuid.New(), Interval: 30 * time.Second, Regions: []string{"eu", "us"}}
_ = s.Upsert(ctx, m, nil)
mustDispatch(t, s)
for _, in := range []uuid.UUID{eu, us} {
if got := takeAll(t, s, in); len(got) != 1 || got[0].MonitorID != m.ID || !got[0].ScheduledAt.Equal(*now) {
t.Errorf("instance jobs = %+v, want one run of %v at %v", got, m.ID, *now)
}
}
if n := mustDispatch(t, s); n != 0 {
t.Errorf("Dispatch() before next interval = %d, want 0", n)
}
*now = now.Add(30 * time.Second)
_ = s.Heartbeat(ctx, "eu", eu)
_ = s.Heartbeat(ctx, "us", us)
if n := mustDispatch(t, s); n != 2 {
t.Errorf("Dispatch() after interval = %d, want 2", n)
}
// Leaving a region stops runs there.
_ = s.Upsert(ctx, Monitor{ID: m.ID, Interval: m.Interval, Regions: []string{"eu"}}, m.Regions)
takeAll(t, s, eu)
takeAll(t, s, us)
*now = now.Add(30 * time.Second)
_ = s.Heartbeat(ctx, "eu", eu)
_ = s.Heartbeat(ctx, "us", us)
mustDispatch(t, s)
if got := takeAll(t, s, us); len(got) != 0 {
t.Errorf("us instance got %d jobs after region removal, want 0", len(got))
}
}
func TestStaleInstanceJobsMoveToLiveOne(t *testing.T) {
s, now := newTest(t)
ctx := context.Background()
dead, alive := uuid.New(), uuid.New()
_ = s.Heartbeat(ctx, "eu", dead)
m := Monitor{ID: uuid.New(), Interval: time.Hour, Regions: []string{"eu"}}
_ = s.Upsert(ctx, m, nil)
mustDispatch(t, s)
*now = now.Add(StaleAfter + time.Second)
_ = s.Heartbeat(ctx, "eu", alive)
mustDispatch(t, s)
got := takeAll(t, s, alive)
if len(got) != 1 || got[0].MonitorID != m.ID {
t.Errorf("live instance jobs = %+v, want the stale instance's run", got)
}
if n, _ := s.Instances(ctx, "eu"); n != 1 {
t.Errorf("Instances() = %d, want 1", n)
}
}
func TestReleaseHandsJobsOver(t *testing.T) {
s, _ := newTest(t)
ctx := context.Background()
leaving, staying := uuid.New(), uuid.New()
_ = s.Heartbeat(ctx, "eu", leaving)
m := Monitor{ID: uuid.New(), Interval: time.Hour, Regions: []string{"eu"}}
_ = s.Upsert(ctx, m, nil)
mustDispatch(t, s)
_ = s.Heartbeat(ctx, "eu", staying)
if err := s.Release(ctx, "eu", leaving); err != nil {
t.Fatal(err)
}
if got := takeAll(t, s, staying); len(got) != 1 {
t.Errorf("staying instance got %d jobs, want 1", len(got))
}
}
func TestRemoveAndReconcile(t *testing.T) {
s, _ := newTest(t)
ctx := context.Background()
in := uuid.New()
_ = s.Heartbeat(ctx, "eu", in)
keep := Monitor{ID: uuid.New(), Interval: time.Minute, Regions: []string{"eu"}}
gone := Monitor{ID: uuid.New(), Interval: time.Minute, Regions: []string{"eu"}}
_ = s.Upsert(ctx, keep, nil)
_ = s.Upsert(ctx, gone, nil)
if err := s.Reconcile(ctx, []Monitor{keep}, s.now().Add(time.Millisecond)); err != nil {
t.Fatal(err)
}
mustDispatch(t, s)
got := takeAll(t, s, in)
if len(got) != 1 || got[0].MonitorID != keep.ID {
t.Errorf("jobs after Reconcile = %+v, want only %v", got, keep.ID)
}
}
func TestTakeWaits(t *testing.T) {
s, _ := newTest(t)
ctx := context.Background()
in := uuid.New()
start := time.Now()
got, err := s.Take(ctx, in, 10, 300*time.Millisecond)
if err != nil || len(got) != 0 {
t.Fatalf("Take() on empty queue = %v, %v", got, err)
}
if waited := time.Since(start); waited < 250*time.Millisecond {
t.Errorf("Take() returned after %v, want it to wait about 300ms", waited)
}
}
func TestTakeReturnsWhenCancelled(t *testing.T) {
s, _ := newTest(t)
ctx, cancel := context.WithCancel(context.Background())
go func() { time.Sleep(100 * time.Millisecond); cancel() }()
start := time.Now()
_, _ = s.Take(ctx, uuid.New(), 10, 20*time.Second)
if took := time.Since(start); took > 2*time.Second {
t.Errorf("Take() returned %v after cancellation, want within about a second", took)
}
}
// TestReconcileKeepsMonitorsCreatedDuringRead covers a monitor created after
// reconciliation read the database but before it pruned Redis.
func TestReconcileKeepsMonitorsCreatedDuringRead(t *testing.T) {
s, now := newTest(t)
ctx := context.Background()
in := uuid.New()
_ = s.Heartbeat(ctx, "eu", in)
asOf := *now
*now = now.Add(50 * time.Millisecond)
fresh := Monitor{ID: uuid.New(), Interval: time.Minute, Regions: []string{"eu"}}
_ = s.Upsert(ctx, fresh, nil)
if err := s.Reconcile(ctx, nil, asOf); err != nil {
t.Fatal(err)
}
mustDispatch(t, s)
if got := takeAll(t, s, in); len(got) != 1 || got[0].MonitorID != fresh.ID {
t.Errorf("jobs after Reconcile = %+v, want the freshly created monitor", got)
}
}