Files
uptimesebi/internal/api/regionwatch_test.go
T
Sebastian UnterschützandClaude Opus 5.5 1138d555aa
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Successful in 11m10s
ci / test (pull_request) Successful in 12m19s
ci / build (pull_request) Successful in 18m13s
ci / image (pull_request) Successful in 5m20s
perf: load console pages in time for organizations with many monitors
Every console page that shows monitor status (monitors, incidents,
monitor details, evidence) went through one loader that read, for all of
the organization's monitors:

- the newest result per monitor and region, by scanning a day of raw
  results;
- the bars of the selected range, from raw results for ranges up to 24h,
  though only one page of monitors is shown;
- when each monitor first reported, scanning two days of results.

With 3000 monitors that took about a second, growing with the number of
results. Now:

- latest_results keeps the newest result per monitor and region,
  updated as results are stored (migration 00055 fills it from the last
  day);
- bars are loaded only for the monitors a page shows;
- first data is loaded per monitor on its page, and the monitor list asks
  only for the organization's earliest data, by index;
- monitor, region and incident queries name the organization, so their
  indexes are used instead of row security filtering whole tables.

Public status pages also read only their own monitors' latest results
and hourly buckets instead of the whole organization's.

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

136 lines
5.2 KiB
Go

package api_test
import (
"context"
"net/http"
"strings"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
"git.zb-server.de/ZB-Server/uptimesebi/internal/config"
"git.zb-server.de/ZB-Server/uptimesebi/internal/notify/notifytest"
)
func TestUncheckedMonitorsAndRegionsWithoutChecker(t *testing.T) {
mail := notifytest.NewSMTP(t)
e := newEnvWith(t, func(c *config.API) {
c.SMTPURL, c.SignupVerify, c.RegionAlertAfter = mail.URL(), "off", 3*time.Minute
})
ctx := context.Background()
owner := e.browser(t)
ownerEmail := "o@" + uniq("rw") + ".test"
owner.signup(ownerEmail, uniq("rw-"))
// An organization's own region: its owners hear about it.
regionName := uniq("Office ")
_, reg := owner.do("POST", "/api/v1/org/regions", map[string]any{"key": uniq("office-"), "name": regionName})
region := reg["id"].(string)
regionID := uuid.MustParse(region)
st, agent := owner.do("POST", "/api/v1/org/agents", map[string]any{"kind": "checker", "name": "office-1", "region_id": region})
if st != http.StatusCreated {
t.Fatalf("create agent = %d %v", st, agent)
}
tok := agent["token"].(string)
mailed := func(to, want string) {
t.Helper()
waitFor(t, 5*time.Second, "a mail saying "+want, func() bool {
for _, m := range mail.Messages() {
if strings.Contains(strings.Join(m.To, ","), to) && strings.Contains(m.Data, want) && strings.Contains(m.Data, regionName) {
return true
}
}
return false
})
}
// A monitor whose only region last reported ten minutes ago is not
// up: nobody is checking it.
_, mon := owner.do("POST", "/api/v1/org/monitors", map[string]any{"name": "Shop", "type": "http", "target": "https://example.test", "interval_seconds": 60, "regions": []string{region}})
id := mon["id"].(string)
org := uuid.MustParse(owner.orgID())
if err := e.asSystem(t, func(tx pgx.Tx) error {
if _, err := tx.Exec(ctx, `UPDATE monitors SET created_at = now() - interval '1 hour' WHERE id = $1`, id); err != nil {
return err
}
if _, err := tx.Exec(ctx, `INSERT INTO check_results (time, org_id, monitor_id, region, checker_id, ok, latency_ms) VALUES (now() - interval '10 minutes', $1, $2, $3, $4, true, 10)`,
org, id, region, uuid.New()); err != nil {
return err
}
// As the API keeps it when the result arrives.
_, err := tx.Exec(ctx, `INSERT INTO latest_results (time, org_id, monitor_id, region, ok, latency_ms) VALUES (now() - interval '10 minutes', $1, $2, $3, true, 10)`,
org, id, region)
return err
}); err != nil {
t.Fatal(err)
}
_, _, dash := owner.page("/")
for _, want := range []string{"not being checked", "1 monitor is not being checked"} {
if !strings.Contains(dash, want) {
t.Errorf("dashboard lacks %q", want)
}
}
if _, _, detail := owner.page("/monitors/" + id); !strings.Contains(detail, "no data since") || !strings.Contains(detail, "1 monitor is not being checked") {
t.Error("the monitor page does not say the region has no recent data")
}
// On a status page it shows as unknown, not as operational.
slug := uniq("rw-")
_, page := owner.do("POST", "/api/v1/org/statuspages", map[string]any{"slug": slug, "title": "Shop status"})
owner.do("PUT", "/api/v1/org/statuspages/"+page["id"].(string)+"/monitors", map[string]any{"monitors": []map[string]any{{"monitor_id": id}}})
owner.do("PUT", "/api/v1/org/statuspages/"+page["id"].(string), map[string]any{"slug": slug, "title": "Shop status", "published": true})
snap, err := e.statuspageClient(t, &org).Page(ctx, "", slug)
if err != nil || len(snap.Sections) != 1 || snap.Sections[0].Components[0].Status != agentapi.PageUnknown {
t.Errorf("status page = %+v, %v; want the component unknown", snap.Sections, err)
}
// The region has a checker but no live instance: the watch notes it at
// once and tells the owners once it has lasted.
now := time.Now()
if err := e.api.WatchRegionsOf(ctx, now, regionID); err != nil {
t.Fatal(err)
}
if _, _, dash := owner.page("/"); !strings.Contains(dash, "Region "+regionName+" has had no active checker since") {
t.Error("the dashboard does not name the region without a checker")
}
if err := e.api.WatchRegionsOf(ctx, now.Add(5*time.Minute), regionID); err != nil {
t.Fatal(err)
}
mailed(ownerEmail, "has no active checker")
sent := len(mail.Messages())
if err := e.api.WatchRegionsOf(ctx, now.Add(10*time.Minute), regionID); err != nil {
t.Fatal(err)
}
time.Sleep(200 * time.Millisecond)
if n := countMails(mail.Messages()[sent:], regionName); n != 0 {
t.Errorf("the region was announced %d more times", n)
}
// A checker coming back is announced too.
e.startChecker(t, tok)
waitFor(t, 15*time.Second, "the checker to count as live", func() bool {
_ = e.api.WatchRegionsOf(ctx, time.Now(), regionID)
for _, m := range mail.Messages() {
if strings.Contains(m.Data, "is checking again") && strings.Contains(m.Data, regionName) {
return true
}
}
return false
})
if _, _, dash := owner.page("/"); strings.Contains(dash, "Region "+regionName+" has had no active checker") {
t.Error("the dashboard still names the region")
}
}
func countMails(ms []notifytest.Message, about string) int {
n := 0
for _, m := range ms {
if strings.Contains(m.Data, about) {
n++
}
}
return n
}