Files
uptimesebi/internal/api/checker_test.go
T
Sebastian UnterschützandClaude Opus 5.5 538c43b563
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Successful in 6m29s
ci / test (pull_request) Successful in 12m55s
ci / build (pull_request) Successful in 16m45s
ci / image (pull_request) Successful in 5m41s
feat(agents): talk to the API over a WebSocket and push page changes
Checkers and status page servers keep one WebSocket open to the API at
/agent/v1/stream and send their requests over it. The API answers them
through the agent API as if they had come over HTTP, each authenticated
again, so the protocol stays the same and a revoked token ends the
stream. While the stream is down agents fall back to plain HTTP, and an
API without it is asked again every five minutes.

Over the stream the API tells status page servers which of their pages
changed, so they fetch them at once instead of on their next refresh:
when a region of a monitor changes between up and down, an incident
opens or resolves, or anything of the organization is edited. Changes
are announced through Redis to every API instance and sent at most every
five seconds per stream. A page that changes while it is fetched is
fetched once more.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-26 17:21:30 +01:00

299 lines
9.7 KiB
Go

package api_test
import (
"context"
"errors"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"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/buildinfo"
"git.zb-server.de/ZB-Server/uptimesebi/internal/checker"
"git.zb-server.de/ZB-Server/uptimesebi/internal/config"
"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, &region.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())
// Checkers talk to the API over the stream, as in production.
client.UseStream(ctx, agentapi.StreamOptions{})
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 TestAgentUpdate(t *testing.T) {
e := newEnvWith(t, func(c *config.API) { c.AgentImage = "mirror.example/acme/uptimesebi" })
tok, _ := e.platformChecker(t, uniq("up-"))
ctx := context.Background()
instance := uuid.New()
client := agentapi.NewClient(e.srv.URL, tok, instance, "v1.0.0").WithHTTPClient(e.srv.Client())
u, err := client.Update(ctx)
if err != nil || u.Version != "dev" || u.Image != "" {
t.Errorf("unreleased platform: Update = %+v, %v", u, err)
}
old := buildinfo.Version
buildinfo.Version = "v1.4.2"
t.Cleanup(func() { buildinfo.Version = old })
u, err = client.Update(ctx)
if err != nil || u.Version != "v1.4.2" || u.Image != "mirror.example/acme/uptimesebi-checker:1.4.2" {
t.Errorf("Update = %+v, %v", u, err)
}
// The launcher asking is not an instance of the agent.
if n := e.count(t, `SELECT count(*) FROM agent_instances WHERE id = $1`, instance); n != 0 {
t.Errorf("the update check registered an instance")
}
if _, err := agentapi.NewClient(e.srv.URL, "usa_wrong", uuid.New(), "t").WithHTTPClient(e.srv.Client()).Update(ctx); !errors.Is(err, agentapi.ErrUnauthorized) {
t.Errorf("Update(wrong token) = %v", err)
}
}
func TestInstallScript(t *testing.T) {
e := newEnvWith(t, func(c *config.API) {
c.PublicURL = "https://uptime.example.com"
c.AgentImage = "mirror.example/acme/uptimesebi"
})
resp, err := e.srv.Client().Get(e.srv.URL + "/install.sh")
if err != nil {
t.Fatal(err)
}
defer func() { _ = resp.Body.Close() }()
body, _ := io.ReadAll(resp.Body)
if resp.StatusCode != http.StatusOK || !strings.HasPrefix(resp.Header.Get("Content-Type"), "text/x-shellscript") {
t.Fatalf("GET /install.sh = %d %s", resp.StatusCode, resp.Header.Get("Content-Type"))
}
for _, want := range []string{"#!/bin/sh", "API_URL='https://uptime.example.com'", "IMAGE='mirror.example/acme/uptimesebi'", "TAG='edge'"} {
if !strings.Contains(string(body), want) {
t.Errorf("the script lacks %q", want)
}
}
}
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)
}
}