Files
beacon-server/db/alerts_final_integration_test.go

270 lines
11 KiB
Go

// Copyright 2026 Beacon Contributors
// SPDX-License-Identifier: AGPL-3.0-or-later
package db
import (
"slices"
"strings"
"testing"
"time"
"github.com/MeshCore-Beacon/beacon-server/internal/alerts"
"github.com/MeshCore-Beacon/beacon-server/internal/api"
"github.com/google/uuid"
)
// A reboot that is older than the newest twelve readings is still newer than the cursor, so it is still found.
func TestAlertRebootBeyondTwelveReadingsPostgres(t *testing.T) {
ctx, pool, s := userStore(t)
u := newUser(t, ctx, s, "alice")
now := time.Now()
key := atlasKey(1)
var obs uuid.UUID
if err := pool.QueryRow(ctx, `INSERT INTO observers (public_key, display_name, last_seen, last_status_at) VALUES ($1, 'North', $2, $2) RETURNING id`, key, now).Scan(&obs); err != nil {
t.Fatal(err)
}
// Judged before the last pass: uptime 10000. The restart came next, then twelve ordinary samples.
for i := 0; i < 14; i++ {
up := int64(i * 60)
if i == 0 {
up = 10000
}
if _, err := pool.Exec(ctx, `INSERT INTO observer_telemetry (id, observer_id, reported_at, uptime_seconds) VALUES ($1, $2, $3, $4)`,
i+1, obs, now.Add(time.Duration(i-13)*time.Minute), up); err != nil {
t.Fatal(err)
}
}
if _, err := pool.Exec(ctx, `INSERT INTO user_alert_rules (user_id, target_kind, target_public_key, kind, state, cursor_at)
VALUES ($1, 'observer', $2, 'rebooted', 'ok', $3)`, u.ID, key, now.Add(-13*time.Minute)); err != nil {
t.Fatal(err)
}
if err := alerts.NewTask(AlertEval{s}, time.Now).Run(ctx); err != nil {
t.Fatal(err)
}
if n := len(outbox(t, ctx, s)); n != 1 {
t.Fatalf("%d notices for a reboot among thirteen unread readings, want 1", n)
}
}
// Two adverts past the limit in a row still count when a normal one follows before the next pass.
func TestAlertClockBreachBetweenPassesPostgres(t *testing.T) {
ctx, pool, s := userStore(t)
svc := alertSvc(s)
u := newUser(t, ctx, s, "alice")
key := atlasKey(1)
advertWithDrift(t, ctx, s, key, 0)
pinAtlas(t, ctx, s, u, 0, api.StoredPin{Kind: "node", Key: key})
if _, err := svc.PutRule(ctx, u.ID, alerts.RuleInput{TargetKind: "node", PublicKey: key, Kind: "clock", Threshold: ipp(300), Enabled: true}); err != nil {
t.Fatal(err)
}
if _, err := pool.Exec(ctx, `UPDATE user_alert_rules SET cursor_at = now() - interval '1 day', state = 'ok'`); err != nil {
t.Fatal(err)
}
for _, d := range []int64{600, 600, 0} {
advertWithDrift(t, ctx, s, key, d)
time.Sleep(5 * time.Millisecond)
}
task := alerts.NewTask(AlertEval{s}, time.Now)
if err := task.Run(ctx); err != nil {
t.Fatal(err)
}
if n := len(outbox(t, ctx, s)); n != 1 {
t.Fatalf("600, 600, 0 since the last pass: %d notices, want 1", n)
}
if got := ruleStateOf(t, ctx, pool, "clock"); got != "ok" {
t.Fatalf("state after the recovery: %s", got)
}
// Nothing new: no second notice.
if err := task.Run(ctx); err != nil {
t.Fatal(err)
}
if n := len(outbox(t, ctx, s)); n != 1 {
t.Fatalf("the breach was announced again: %d notices", n)
}
}
// A repeater nobody is assigned to, read by a poller this server does not manage: its trusted readings offer the
// telemetry kinds and their rules are judged. When the readings stop, telemetry_stopped fires and keeps firing.
func TestAlertTelemetryWithoutAssignmentPostgres(t *testing.T) {
ctx, pool, s := userStore(t)
svc := alertSvc(s)
u := newUser(t, ctx, s, "alice")
rep, silent := atlasKey(1), atlasKey(2)
insertNode(t, ctx, s, rep, 2, "Hilltop")
insertNode(t, ctx, s, silent, 2, "Valley")
insertReading(t, ctx, s, rep, time.Now().Add(-4*time.Hour), 3000, nil)
insertReading(t, ctx, s, rep, time.Now().Add(-5*time.Hour), 3000, nil)
pinAtlas(t, ctx, s, u, 0, api.StoredPin{Kind: "node", Key: rep}, api.StoredPin{Kind: "node", Key: silent})
ov, err := svc.Overview(ctx, u.ID)
if err != nil || len(ov.Targets) != 2 {
t.Fatalf("%+v %v", ov, err)
}
if got := ov.Targets[0]; !got.Caps.Polled || !slices.Contains(got.Available, "battery_low") || !slices.Contains(got.Available, "telemetry_stopped") {
t.Fatalf("a repeater with readings and no assignment: %+v", got)
}
if got := ov.Targets[1]; got.Caps.Polled || got.UnavailableCodes["battery_low"] != alerts.CodeNotPolled || got.UnavailableCodes["telemetry_stopped"] != alerts.CodeNotPolled {
t.Fatalf("a repeater with no readings: %+v", got)
}
// Any repeater takes the short gone_quiet windows.
if _, err := svc.PutRule(ctx, u.ID, alerts.RuleInput{TargetKind: "node", PublicKey: silent, Kind: "gone_quiet", Threshold: ipp(3), Enabled: true}); err != nil {
t.Fatalf("gone_quiet 3 on an unpolled repeater: %v", err)
}
for kind, th := range map[string]int{"battery_low": 3500, "telemetry_stopped": 6} {
if _, err := svc.PutRule(ctx, u.ID, alerts.RuleInput{TargetKind: "node", PublicKey: rep, Kind: kind, Threshold: ipp(th), Enabled: true}); err != nil {
t.Fatalf("%s: %v", kind, err)
}
}
task := alerts.NewTask(AlertEval{s}, time.Now)
run := func() {
t.Helper()
if err := task.Run(ctx); err != nil {
t.Fatal(err)
}
}
run()
if got := ruleStateOf(t, ctx, pool, "battery_low"); got != "firing" {
t.Fatalf("battery_low without an assignment: %s", got)
}
if got := ruleStateOf(t, ctx, pool, "telemetry_stopped"); got != "ok" {
t.Fatalf("telemetry_stopped with a reading 4 hours old and a 6 hour limit: %s", got)
}
// The rule was set now, with the last reading 4 hours old: the clock starts at the rule, not in the past.
if _, err := pool.Exec(ctx, `UPDATE user_alert_rules SET cursor_at = now() - interval '3 hours' WHERE kind = 'telemetry_stopped'`); err != nil {
t.Fatal(err)
}
if _, err := pool.Exec(ctx, `UPDATE repeater_readings SET sampled_at = sampled_at - interval '3 hours' WHERE target_public_key = $1`, rep); err != nil {
t.Fatal(err)
}
run()
if got := ruleStateOf(t, ctx, pool, "telemetry_stopped"); got != "ok" {
t.Fatalf("telemetry_stopped 3 hours after it was set: %s", got)
}
// A month on there is no current source, so the battery rule is inactive, and the stopped rule fires.
if _, err := pool.Exec(ctx, `UPDATE user_alert_rules SET cursor_at = cursor_at - interval '30 days' WHERE kind = 'telemetry_stopped'`); err != nil {
t.Fatal(err)
}
if _, err := pool.Exec(ctx, `UPDATE repeater_readings SET sampled_at = sampled_at - interval '30 days', received_at = received_at - interval '30 days' WHERE target_public_key = $1`, rep); err != nil {
t.Fatal(err)
}
run()
if got := ruleStateOf(t, ctx, pool, "telemetry_stopped"); got != "firing" {
t.Fatalf("telemetry_stopped a month after the last reading: %s", got)
}
if got := ruleStateOf(t, ctx, pool, "battery_low"); got != "inactive" {
t.Fatalf("battery_low with no current source: %s", got)
}
// Retention deletes the readings; the rule remembers when the last one was and keeps firing.
if _, err := pool.Exec(ctx, `DELETE FROM repeater_readings WHERE target_public_key = $1`, rep); err != nil {
t.Fatal(err)
}
run()
if got := ruleStateOf(t, ctx, pool, "telemetry_stopped"); got != "firing" {
t.Fatalf("telemetry_stopped after retention deleted the readings: %s", got)
}
insertReading(t, ctx, s, rep, time.Now().Add(-time.Minute), 4000, nil)
run()
if got := ruleStateOf(t, ctx, pool, "telemetry_stopped"); got != "ok" {
t.Fatalf("telemetry_stopped after a new reading: %s", got)
}
}
// With polling switched off the assignment rows that remain are no current source: repeater telemetry kinds are
// unavailable (not_polled) and their rules read inactive. Observer status alerts do not depend on it.
func TestAlertTelemetryStopsWhenPollingIsOffPostgres(t *testing.T) {
ctx, pool, s := userStore(t)
svc := alertSvc(s)
u := newUser(t, ctx, s, "alice")
rep := atlasKey(1)
insertNode(t, ctx, s, rep, 2, "Hilltop")
insertReading(t, ctx, s, rep, time.Now().Add(-10*time.Minute), 3000, nil)
insertReading(t, ctx, s, rep, time.Now().Add(-20*time.Minute), 3000, nil)
assignPoller(t, ctx, s, rep)
pinAtlas(t, ctx, s, u, 0, api.StoredPin{Kind: "node", Key: rep})
if _, err := pool.Exec(ctx, `INSERT INTO user_alert_rules (user_id, target_kind, target_public_key, kind, threshold, cursor_at)
VALUES ($1, 'node', $2, 'battery_low', 3500, now() - interval '3 days')`, u.ID, rep); err != nil {
t.Fatal(err)
}
// Set two days ago with a 1 hour limit: firing while polling is on.
if _, err := pool.Exec(ctx, `INSERT INTO user_alert_rules (user_id, target_kind, target_public_key, kind, threshold, cursor_at)
VALUES ($1, 'node', $2, 'telemetry_stopped', 3, now() - interval '2 days')`, u.ID, rep); err != nil {
t.Fatal(err)
}
task := alerts.NewTask(AlertEval{s}, time.Now)
if err := task.Run(ctx); err != nil {
t.Fatal(err)
}
if got := ruleStateOf(t, ctx, pool, "battery_low"); got != "firing" {
t.Fatalf("with polling on: %s", got)
}
if got := ruleStateOf(t, ctx, pool, "telemetry_stopped"); got != "ok" {
t.Fatalf("telemetry_stopped with a reading 10 minutes old: %s", got)
}
s.SetPollingEnabled(false)
ov, err := svc.Overview(ctx, u.ID)
if err != nil || len(ov.Targets) != 1 || ov.Targets[0].Caps.Polled {
t.Fatalf("still polled with polling off: %+v %v", ov, err)
}
if got := ov.Targets[0].UnavailableCodes["battery_low"]; got != alerts.CodeNotPolled {
t.Fatalf("battery_low with polling off: code %q, available %v", got, ov.Targets[0].Available)
}
if err := task.Run(ctx); err != nil {
t.Fatal(err)
}
if got := ruleStateOf(t, ctx, pool, "battery_low"); got != "inactive" {
t.Fatalf("rule with polling off: %s", got)
}
// The stopped rule would otherwise fire for every repeater once its hours passed.
if got := ruleStateOf(t, ctx, pool, "telemetry_stopped"); got != "inactive" {
t.Fatalf("telemetry_stopped with polling off: %s", got)
}
}
// The sender takes the notices of a finished pass only, so a pass that is still being evaluated is not split across
// mails; one that never finished is released after the timeout.
func TestAlertMailWaitsForTheFinishedPassPostgres(t *testing.T) {
ctx, pool, s := userStore(t)
u := newUser(t, ctx, s, "alice")
if err := s.SetUserEmailVerified(ctx, u.ID, time.Now()); err != nil {
t.Fatal(err)
}
pass := uuid.New()
if _, err := pool.Exec(ctx, `INSERT INTO alert_passes (pass_id) VALUES ($1)`, pass); err != nil {
t.Fatal(err)
}
m := &recMail{}
sender := alerts.NewSender(AlertEval{s}, alerts.SenderConfig{Mail: m})
queueNotice(t, ctx, s, u.ID, pass, "battery_low", "Hill", time.Now())
if err := sender.Run(ctx); err != nil {
t.Fatal(err)
}
queueNotice(t, ctx, s, u.ID, pass, "rebooted", "Hill", time.Now())
if err := sender.Run(ctx); err != nil {
t.Fatal(err)
}
if len(m.got) != 0 {
t.Fatalf("a pass still being evaluated was sent: %v", m.got)
}
if _, err := pool.Exec(ctx, `UPDATE alert_passes SET finished_at = now() WHERE pass_id = $1`, pass); err != nil {
t.Fatal(err)
}
if err := sender.Run(ctx); err != nil {
t.Fatal(err)
}
if len(m.got) != 1 || !strings.Contains(m.got[0], "2 alerts") {
t.Fatalf("a finished pass should go out as one mail: %v", m.got)
}
// A pass the process never finished is released after the timeout.
stuck := uuid.New()
if _, err := pool.Exec(ctx, `INSERT INTO alert_passes (pass_id, started_at) VALUES ($1, now() - interval '16 minutes')`, stuck); err != nil {
t.Fatal(err)
}
queueNotice(t, ctx, s, u.ID, stuck, "rebooted", "Hill", time.Now())
if err := sender.Run(ctx); err != nil {
t.Fatal(err)
}
if len(m.got) != 2 {
t.Fatalf("an interrupted pass was never released: %v", m.got)
}
}