package api_test import ( "context" "encoding/json" "strings" "testing" "time" "github.com/google/uuid" "github.com/jackc/pgx/v5" "git.zb-server.de/ZB-Server/uptimesebi/internal/store" ) // TestLatestResultsKeepTheNewest checks that a result arriving late does // not replace a newer one, and that a batch keeps its newest per region. func TestLatestResultsKeepTheNewest(t *testing.T) { e := newEnv(t) _, region := e.platformChecker(t, uniq("eu-")) owner := e.browser(t) owner.signup("o@"+uniq("lr")+".test", uniq("lr-")) _, m := owner.do("POST", "/api/v1/org/monitors", map[string]any{"name": "Shop", "type": "http", "target": "https://shop.test", "interval_seconds": 60, "regions": []string{region}}) id, org := uuid.MustParse(m["id"].(string)), uuid.MustParse(owner.orgID()) now := time.Now().Truncate(time.Millisecond) upsert := func(rows ...map[string]any) { t.Helper() for _, r := range rows { r["monitor_id"], r["org_id"], r["region"] = id, org, region } b, _ := json.Marshal(rows) if err := e.asSystem(t, func(tx pgx.Tx) error { return store.New(tx).UpsertLatestResults(context.Background(), b) }); err != nil { t.Fatal(err) } } latest := func() (time.Time, bool) { t.Helper() var ( at time.Time ok bool ) if err := e.asSystem(t, func(tx pgx.Tx) error { return tx.QueryRow(context.Background(), `SELECT time, ok FROM latest_results WHERE monitor_id = $1`, id).Scan(&at, &ok) }); err != nil { t.Fatal(err) } return at, ok } upsert(map[string]any{"time": now.Add(-time.Minute), "ok": true}, map[string]any{"time": now, "ok": false, "error": "down"}) if at, ok := latest(); !at.Equal(now) || ok { t.Errorf("after a batch latest = %v ok=%t, want the newest (%v, failed)", at, ok, now) } upsert(map[string]any{"time": now.Add(-30 * time.Second), "ok": true}) if at, _ := latest(); !at.Equal(now) { t.Errorf("a late result replaced the newest: %v", at) } upsert(map[string]any{"time": now.Add(time.Minute), "ok": true, "latency_ms": 12}) if at, ok := latest(); !at.Equal(now.Add(time.Minute)) || !ok { t.Errorf("a newer result was not kept: %v ok=%t", at, ok) } _, body := owner.do("GET", "/api/v1/org/monitors", nil) if got := body["monitors"].([]any)[0].(map[string]any)["latest"].([]any); len(got) != 1 { t.Errorf("the API lists %d latest results, want 1", len(got)) } if _, _, html := owner.page("/monitors/" + id.String()); !strings.Contains(html, "12 ms") { t.Error("the monitor page does not show the latest result") } }