Files
uptimesebi/internal/schedule/schedule_test.go
T
Sebastian UnterschützandClaude Opus 5.5 e9984f8271
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Successful in 10m23s
ci / test (pull_request) Successful in 12m59s
ci / build (pull_request) Canceled after 7m17s
ci / image (pull_request) Canceled after 0s
feat(api): Prometheus metrics for operators
The API serves Prometheus metrics on a listener of its own
(UPTIME_API_METRICS_LISTEN, default :9090, "off" disables it), so the
public ingress never exposes them:

- requests by route and status, with durations except for long polls
  and agent streams
- dispatched checks, stored and rejected results per region, how late
  results arrive, live checkers and overdue checks per platform region
- notification and subscriber mail deliveries, incidents opened and
  resolved
- runs, duration and last success of the background jobs
- platform totals (orgs, users, monitors by type, status pages,
  subscribers, open incidents, pending notifications), read at most
  every 15 seconds when scraped
- the Postgres and Redis connection pools, Go runtime and build info

The Helm chart exposes the port on the API service and can add a
ServiceMonitor for the Prometheus Operator.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-29 11:56:46 +01:00

272 lines
7.9 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)
}
// Not rounded up to the second that BLPOP counts in.
if waited := time.Since(start); waited < 250*time.Millisecond || waited > 800*time.Millisecond {
t.Errorf("Take() returned after %v, want it to wait about 300ms", waited)
}
}
func TestTakeGetsAJobDuringAShortWait(t *testing.T) {
s, _ := newTest(t)
ctx := context.Background()
in, monitor := uuid.New(), uuid.New()
go func() {
time.Sleep(100 * time.Millisecond)
s.rdb.RPush(ctx, jobsPrefix+in.String(), monitor.String()+"|1800000000000")
}()
got, err := s.Take(ctx, in, 10, 600*time.Millisecond)
if err != nil || len(got) != 1 || got[0].MonitorID != monitor {
t.Fatalf("Take() = %v, %v; want the job pushed while waiting", got, err)
}
}
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)
}
}
func TestOverdueCountsRunsLeftBehind(t *testing.T) {
s, now := newTest(t)
ctx := context.Background()
for range 2 {
_ = s.Upsert(ctx, Monitor{ID: uuid.New(), Interval: time.Minute, Regions: []string{"eu"}}, nil)
}
overdue := func() int64 {
t.Helper()
n, err := s.Overdue(ctx, "eu", 10*time.Second)
if err != nil {
t.Fatalf("Overdue() failed: %v", err)
}
return n
}
if n := overdue(); n != 0 {
t.Errorf("Overdue() right after scheduling = %d, want 0", n)
}
// No instance takes the runs.
*now = now.Add(11 * time.Second)
mustDispatch(t, s)
if n := overdue(); n != 2 {
t.Errorf("Overdue() without instances = %d, want 2", n)
}
_ = s.Heartbeat(ctx, "eu", uuid.New())
mustDispatch(t, s)
if n := overdue(); n != 0 {
t.Errorf("Overdue() after dispatch = %d, want 0", n)
}
}