A checker that lost the answer to a report, for example when its request was cancelled while the API was still working, sent the batch again and the API stored it twice, skewing statistics and counting failures twice towards an incident. Results are now claimed in Redis by instance, monitor and schedule time, and repeats are dropped. Found by CI, where TestCheckersPerRegion saw a stopped checker's batch arrive twice. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
245 lines
7.5 KiB
Go
245 lines
7.5 KiB
Go
package api_test
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"log/slog"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
|
|
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
|
|
"git.zb-server.de/ZB-Server/uptimesebi/internal/api"
|
|
"git.zb-server.de/ZB-Server/uptimesebi/internal/checker"
|
|
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
|
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
|
|
)
|
|
|
|
// platformChecker creates a platform region with a checker agent directly
|
|
// in the database, as "api agent create" would, and returns the agent token
|
|
// and the region ID.
|
|
func (e *env) platformChecker(t *testing.T, key string) (string, string) {
|
|
t.Helper()
|
|
ctx := context.Background()
|
|
var (
|
|
tok string
|
|
region store.Region
|
|
)
|
|
err := tenant.New(e.dbPool).Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
|
var err error
|
|
if region, err = q.EnsurePlatformRegion(ctx, store.EnsurePlatformRegionParams{Key: key}); err != nil {
|
|
return err
|
|
}
|
|
var params store.CreateAgentParams
|
|
tok, params = api.NewAgentToken(nil, "checker", "test-"+key, ®ion.ID)
|
|
_, err = q.CreateAgent(ctx, params)
|
|
return err
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("creating agent: %v", err)
|
|
}
|
|
return tok, region.ID.String()
|
|
}
|
|
|
|
// startChecker runs a checker instance until the returned stop is called.
|
|
func (e *env) startChecker(t *testing.T, token string) (uuid.UUID, func()) {
|
|
t.Helper()
|
|
id := uuid.New()
|
|
client := agentapi.NewClient(e.srv.URL, token, id, "test").WithHTTPClient(e.srv.Client())
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
done := make(chan struct{})
|
|
go func() {
|
|
defer close(done)
|
|
_ = checker.New(client, 8, slog.New(slog.DiscardHandler)).Run(ctx, 5*time.Second)
|
|
}()
|
|
var once bool
|
|
stop := func() {
|
|
if once {
|
|
return
|
|
}
|
|
once = true
|
|
cancel()
|
|
<-done
|
|
}
|
|
t.Cleanup(stop)
|
|
return id, stop
|
|
}
|
|
|
|
func TestCheckersPerRegion(t *testing.T) {
|
|
e := newEnv(t)
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
t.Cleanup(cancel)
|
|
go e.api.RunScheduler(ctx)
|
|
|
|
target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
if r.URL.Path == "/down" {
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
}
|
|
}))
|
|
defer target.Close()
|
|
|
|
euTok, eu := e.platformChecker(t, uniq("eu-"))
|
|
usTok, us := e.platformChecker(t, uniq("us-"))
|
|
euA, stopA := e.startChecker(t, euTok)
|
|
euB, _ := e.startChecker(t, euTok)
|
|
usC, _ := e.startChecker(t, usTok)
|
|
|
|
owner := e.browser(t)
|
|
owner.signup("o@"+uniq("c")+".test", uniq("chk-"))
|
|
org := owner.orgID()
|
|
|
|
// Instances register on their first poll.
|
|
waitFor(t, 5*time.Second, "both eu instances registered", func() bool {
|
|
_, body := owner.do("GET", "/api/v1/org/regions", nil)
|
|
for _, r := range body["regions"].([]any) {
|
|
r := r.(map[string]any)
|
|
if r["id"] == eu && r["instances"] == float64(2) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
})
|
|
|
|
const n = 30
|
|
for i := range n {
|
|
path := "/up"
|
|
if i == 0 {
|
|
path = "/down"
|
|
}
|
|
regions := []string{eu}
|
|
if i < 3 {
|
|
regions = append(regions, us)
|
|
}
|
|
st, body := owner.do("POST", "/api/v1/org/monitors", map[string]any{
|
|
"name": "m", "type": "http", "target": target.URL + path, "interval_seconds": 3600, "regions": regions,
|
|
})
|
|
if st != http.StatusCreated {
|
|
t.Fatalf("create monitor = %d %v", st, body)
|
|
}
|
|
}
|
|
|
|
count := func(checker uuid.UUID) (total, failed int) {
|
|
_ = e.dbPool.QueryRow(context.Background(),
|
|
`SELECT count(*), count(*) FILTER (WHERE NOT ok) FROM check_results WHERE org_id = $1 AND checker_id = $2`,
|
|
org, checker).Scan(&total, &failed)
|
|
return total, failed
|
|
}
|
|
waitFor(t, 15*time.Second, "all first runs reported", func() bool {
|
|
a, _ := count(euA)
|
|
b, _ := count(euB)
|
|
c, _ := count(usC)
|
|
return a+b == n && c == 3
|
|
})
|
|
a, aFailed := count(euA)
|
|
b, bFailed := count(euB)
|
|
if a < 5 || b < 5 {
|
|
t.Errorf("eu instances ran %d and %d checks, want both to get a random share of %d", a, b, n)
|
|
}
|
|
if aFailed+bFailed != 1 {
|
|
t.Errorf("failed eu checks = %d, want 1 (the /down monitor)", aFailed+bFailed)
|
|
}
|
|
|
|
_, body := owner.do("GET", "/api/v1/org/monitors", nil)
|
|
withLatest := 0
|
|
for _, m := range body["monitors"].([]any) {
|
|
if len(m.(map[string]any)["latest"].([]any)) > 0 {
|
|
withLatest++
|
|
}
|
|
}
|
|
if withLatest != n {
|
|
t.Errorf("monitors with latest results = %d, want %d", withLatest, n)
|
|
}
|
|
|
|
// Stopping one eu instance leaves the other to take every eu check.
|
|
stopA()
|
|
st, body := owner.do("POST", "/api/v1/org/monitors", map[string]any{
|
|
"name": "after", "type": "tcp", "target": target.Listener.Addr().String(), "interval_seconds": 3600, "regions": []string{eu},
|
|
})
|
|
if st != http.StatusCreated {
|
|
t.Fatalf("create monitor = %d %v", st, body)
|
|
}
|
|
before, _ := count(euB)
|
|
waitFor(t, 10*time.Second, "remaining eu instance runs the new monitor", func() bool {
|
|
now, _ := count(euB)
|
|
return now == before+1
|
|
})
|
|
if after, _ := count(euA); after != a {
|
|
t.Errorf("stopped instance ran %d more checks", after-a)
|
|
}
|
|
}
|
|
|
|
func TestAgentAuth(t *testing.T) {
|
|
e := newEnv(t)
|
|
tok, _ := e.platformChecker(t, uniq("x-"))
|
|
ctx := context.Background()
|
|
if _, err := agentapi.NewClient(e.srv.URL, "usa_wrong", uuid.New(), "t").WithHTTPClient(e.srv.Client()).Hello(ctx); !errors.Is(err, agentapi.ErrUnauthorized) {
|
|
t.Errorf("Hello(wrong token) = %v, want %v", err, agentapi.ErrUnauthorized)
|
|
}
|
|
h, err := agentapi.NewClient(e.srv.URL, tok, uuid.New(), "t").WithHTTPClient(e.srv.Client()).Hello(ctx)
|
|
if err != nil || h.Kind != "checker" {
|
|
t.Errorf("Hello() = %+v, %v; want checker", h, err)
|
|
}
|
|
// User API tokens and sessions do not open the agent API.
|
|
owner := e.browser(t)
|
|
owner.signup("a@"+uniq("a")+".test", uniq("auth-"))
|
|
st, _ := owner.do("GET", "/agent/v1/hello", nil)
|
|
if st == http.StatusOK {
|
|
t.Error("session opened the agent API")
|
|
}
|
|
}
|
|
|
|
func (b *browser) orgID() string {
|
|
b.t.Helper()
|
|
_, me := b.do("GET", "/api/v1/me", nil)
|
|
return me["active_org"].(string)
|
|
}
|
|
|
|
func waitFor(t *testing.T, d time.Duration, what string, cond func() bool) {
|
|
t.Helper()
|
|
deadline := time.Now().Add(d)
|
|
for !cond() {
|
|
if time.Now().After(deadline) {
|
|
t.Fatalf("timed out waiting for: %s", what)
|
|
}
|
|
time.Sleep(100 * time.Millisecond)
|
|
}
|
|
}
|
|
|
|
// A checker that lost the answer to a report sends it again; the results
|
|
// must not be stored twice.
|
|
func TestResultReportIsIdempotent(t *testing.T) {
|
|
e := newEnv(t)
|
|
tok, region := e.platformChecker(t, uniq("eu-"))
|
|
owner := e.browser(t)
|
|
owner.signup("o@"+uniq("id")+".test", uniq("id-"))
|
|
_, m := owner.do("POST", "/api/v1/org/monitors", map[string]any{
|
|
"name": "m", "type": "tcp", "target": "example.com:443", "interval_seconds": 3600, "regions": []string{region},
|
|
})
|
|
monitor := uuid.MustParse(m["id"].(string))
|
|
client := agentapi.NewClient(e.srv.URL, tok, uuid.New(), "test").WithHTTPClient(e.srv.Client())
|
|
at := time.Now().Truncate(time.Millisecond)
|
|
batch := []agentapi.Result{
|
|
{MonitorID: monitor, ScheduledAt: at, StartedAt: at, OK: true},
|
|
{MonitorID: monitor, ScheduledAt: at.Add(time.Second), StartedAt: at.Add(time.Second), OK: false},
|
|
}
|
|
for range 3 {
|
|
if err := client.Report(context.Background(), batch); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
if n := e.count(t, `SELECT count(*) FROM check_results WHERE monitor_id = $1`, monitor); n != 2 {
|
|
t.Errorf("stored results = %d, want 2", n)
|
|
}
|
|
// Another instance's run of the same schedule time is its own result.
|
|
other := agentapi.NewClient(e.srv.URL, tok, uuid.New(), "test").WithHTTPClient(e.srv.Client())
|
|
if err := other.Report(context.Background(), batch[:1]); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if n := e.count(t, `SELECT count(*) FROM check_results WHERE monitor_id = $1`, monitor); n != 3 {
|
|
t.Errorf("stored results = %d, want 3", n)
|
|
}
|
|
}
|