Files
uptimesebi/internal/metrics/metrics_test.go
T
Sebastian UnterschützandClaude Opus 5.5 94c529a97e
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Successful in 11m48s
ci / test (pull_request) Successful in 13m35s
ci / build (pull_request) Successful in 10m22s
ci / image (pull_request) Successful in 3m35s
fix(schedule): drop runs left queued for too long; shorter result claims
A checker that fell behind kept working off runs from minutes ago while
dispatch queued newer runs of the same monitors behind them, so a backlog
never shrank: pawhost and realtoxmedia stayed at about 50K overdue checks.
Queued runs now record when they were dispatched, and Take drops runs
that waited longer than two intervals. A newer run of the monitor has
been queued by then, since the next run is due at most one and a half
intervals after a dispatch. uptimesebi_checks_stale_total counts them.

Result claims, one Redis key per check result, lived 2 hours although
retries come within minutes. At about 530 results a second that was
4.5 million keys and 1.1 GiB of the shared Redis. They now live 10
minutes.

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

138 lines
4.8 KiB
Go

package metrics
import (
"context"
"errors"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/gin-gonic/gin"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/testutil"
"github.com/redis/go-redis/v9"
)
func TestHTTPCountsRoutesAndTimesShortRequests(t *testing.T) {
gin.SetMode(gin.TestMode)
m := New("selfhosted")
r := gin.New()
r.Use(m.HTTP("/stream"))
r.GET("/items/:id", func(c *gin.Context) { c.Status(http.StatusTeapot) })
r.GET("/stream", func(c *gin.Context) { c.Status(http.StatusOK) })
for _, path := range []string{"/items/1", "/items/2", "/stream", "/nowhere"} {
r.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, path, nil))
}
if got := testutil.ToFloat64(m.requests.WithLabelValues("GET", "/items/:id", "418")); got != 2 {
t.Errorf("requests for the route = %v, want 2", got)
}
if got := testutil.ToFloat64(m.requests.WithLabelValues("GET", "unmatched", "404")); got != 1 {
t.Errorf("unmatched requests = %v, want 1", got)
}
// The stream is counted, not timed.
if got := testutil.CollectAndCount(m.duration); got != 2 {
t.Errorf("timed series = %d, want 2: the route and unmatched paths, not the stream", got)
}
if got := testutil.ToFloat64(m.inFlight); got != 0 {
t.Errorf("in flight after the requests = %v, want 0", got)
}
}
func TestJobRecordsOutcome(t *testing.T) {
m := New("cloud")
boom := errors.New("boom")
if err := m.Job("housekeeping", func() error { return nil }); err != nil {
t.Fatalf("Job() = %v, want nil", err)
}
if err := m.Job("housekeeping", func() error { return boom }); !errors.Is(err, boom) {
t.Fatalf("Job() = %v, want the run's error", err)
}
if got := testutil.ToFloat64(m.jobRuns.WithLabelValues("housekeeping", "ok")); got != 1 {
t.Errorf("ok runs = %v, want 1", got)
}
if got := testutil.ToFloat64(m.jobRuns.WithLabelValues("housekeeping", "failed")); got != 1 {
t.Errorf("failed runs = %v, want 1", got)
}
if got := testutil.ToFloat64(m.jobSuccess.WithLabelValues("housekeeping")); got < float64(time.Now().Add(-time.Minute).Unix()) {
t.Errorf("last success = %v, want about now", got)
}
}
func TestCountersAndHandler(t *testing.T) {
m := New("cloud")
m.Dispatched(3)
m.Stale(2)
m.Stale(0)
m.Result("fsn", true, 2*time.Second)
m.Result("fsn", false, -time.Second)
m.Rejected("duplicate", 2)
m.Rejected("bad_time", 0)
m.Notification("slack", nil, time.Second)
m.Notification("slack", errors.New("x"), time.Second)
m.SubscriberMail(nil)
m.Incident("opened")
for name, c := range map[string]struct {
got, want float64
}{
"dispatched": {testutil.ToFloat64(m.dispatched), 3},
"stale": {testutil.ToFloat64(m.stale), 2},
"ok results": {testutil.ToFloat64(m.results.WithLabelValues("fsn", "true")), 1},
"failed results": {testutil.ToFloat64(m.results.WithLabelValues("fsn", "false")), 1},
"duplicates": {testutil.ToFloat64(m.rejected.WithLabelValues("duplicate")), 2},
"sent": {testutil.ToFloat64(m.notifications.WithLabelValues("slack", "sent")), 1},
"failed": {testutil.ToFloat64(m.notifications.WithLabelValues("slack", "failed")), 1},
"subscriber": {testutil.ToFloat64(m.subscriberMail.WithLabelValues("sent")), 1},
"incidents": {testutil.ToFloat64(m.incidents.WithLabelValues("opened")), 1},
} {
if c.got != c.want {
t.Errorf("%s = %v, want %v", name, c.got, c.want)
}
}
if got := testutil.CollectAndCount(m.rejected); got != 1 {
t.Errorf("rejection series = %d, want 1: zero rejections add none", got)
}
rec := httptest.NewRecorder()
m.Handler().ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/metrics", nil))
body, _ := io.ReadAll(rec.Body)
for _, want := range []string{`uptimesebi_build_info{commit="none",edition="cloud",version="dev"} 1`, "go_goroutines", "uptimesebi_checks_dispatched_total 3"} {
if !strings.Contains(string(body), want) {
t.Errorf("metrics lack %q", want)
}
}
}
func TestPoolCollectors(t *testing.T) {
// Neither pool connects before it is used.
pool, err := pgxpool.New(context.Background(), "postgres://u@127.0.0.1:1/db")
if err != nil {
t.Fatal(err)
}
defer pool.Close()
rdb := redis.NewClient(&redis.Options{Addr: "127.0.0.1:1"})
defer func() { _ = rdb.Close() }()
m := New("cloud")
m.Register(DBPool(pool), RedisPool(rdb))
for _, c := range []prometheus.Collector{DBPool(pool), RedisPool(rdb)} {
if problems, err := testutil.CollectAndLint(c); err != nil || len(problems) > 0 {
t.Errorf("pool metrics lint: %v %v", problems, err)
}
}
if got := testutil.CollectAndCount(DBPool(pool)); got != 7 {
t.Errorf("DB pool series = %d, want 7", got)
}
if got := testutil.CollectAndCount(RedisPool(rdb)); got != 6 {
t.Errorf("Redis pool series = %d, want 6", got)
}
if _, err := m.Gatherer().Gather(); err != nil {
t.Errorf("Gather() = %v", err)
}
}