diff --git a/internal/server/alerts.go b/internal/server/alerts.go index f7e62a2..7d063df 100644 --- a/internal/server/alerts.go +++ b/internal/server/alerts.go @@ -536,13 +536,27 @@ func (a *alerter) snapshot() (open, recent []Incident) { if ri, rj := notify.Rank(open[i].Severity), notify.Rank(open[j].Severity); ri != rj { return ri > rj } - return open[i].Opened.Before(open[j].Opened) + if !open[i].Opened.Equal(open[j].Opened) { + return open[i].Opened.Before(open[j].Opened) + } + // Many open in one evaluation (a restart, a wide outage), so ties + // are common: break them on the id, or the list reshuffles with + // map order on every refresh and a click lands on another row. + return idLess(open[i].ID, open[j].ID) }) n := min(len(a.history), 50) recent = append([]Incident{}, a.history[:n]...) return open, recent } +// idLess orders incident ids by number: B-0999 before B-1000 before B-10000. +func idLess(a, b string) bool { + if len(a) != len(b) { + return len(a) < len(b) + } + return a < b +} + // run delivers queued notices until ctx ends. func (a *alerter) run(ctx context.Context) { for { diff --git a/internal/server/alerts_test.go b/internal/server/alerts_test.go index 4ba030f..7bbbe7b 100644 --- a/internal/server/alerts_test.go +++ b/internal/server/alerts_test.go @@ -3,6 +3,7 @@ package server import ( "context" "errors" + "fmt" "net/http" "net/http/httptest" "os" @@ -336,3 +337,37 @@ func TestAcknowledgingTellsFollowersOnly(t *testing.T) { t.Fatal("acknowledging a held incident told the follower") } } + +// Incidents that open in the same evaluation keep one order across +// snapshots (#32): severity, then opened, then id by number. +func TestSnapshotOrderIsStable(t *testing.T) { + a := testAlerter(&spy{id: "phone", min: "warning"}) + t0 := time.Now() + var cs []Condition + for i := range 40 { + sev := "warning" + if i%3 == 0 { + sev = "critical" + } + cs = append(cs, Condition{Key: fmt.Sprintf("unit/node%d/app.service", i), Severity: sev, Title: "app failed", Host: fmt.Sprintf("node%d", i)}) + } + a.evaluate(t0, cs) + first, _ := a.snapshot() + for range 20 { + again, _ := a.snapshot() + for i := range first { + if again[i].ID != first[i].ID { + t.Fatalf("row %d: %s, then %s", i, first[i].ID, again[i].ID) + } + } + } + for i := 1; i < len(first); i++ { + p, c := first[i-1], first[i] + if p.Severity == c.Severity && !idLess(p.ID, c.ID) { + t.Fatalf("%s before %s", p.ID, c.ID) + } + } + if !idLess("B-9999", "B-10000") || idLess("B-0002", "B-0001") { + t.Fatal("idLess") + } +} diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts index d21fac6..c377c49 100644 --- a/web/src/lib/api.ts +++ b/web/src/lib/api.ts @@ -237,14 +237,35 @@ export class SignedOut extends Error { export async function get(url: string): Promise { const r = await fetch(url, { credentials: 'same-origin', headers: { Accept: 'application/json' } }); if (r.status === 401) throw new SignedOut(await r.json()); - if (!r.ok) throw new Error(`${url}: ${r.status} ${r.statusText}`); + if (!r.ok) throw await failed(r); return r.json() as Promise; } +/** + * An error obs-beacond answered with. Its text is the server's own message + * ("This is the demo: it shows everything and changes nothing.") when there + * is one, and String(e) gives just that, without "Error: ". + */ +export class APIError extends Error { + status: number; + constructor(message: string, status: number) { + super(message); + this.status = status; + } + toString() { + return this.message; + } +} + +async function failed(r: Response): Promise { + const j = (await r.json().catch(() => ({}))) as { error?: string }; + return new APIError(j.error || `The server answered ${r.status} ${r.statusText}`.trim(), r.status); +} + /** POSTs carry X-Beacon, which obs-beacond requires and a cross-site form can't add. */ export async function post(url: string): Promise { const r = await fetch(url, { method: 'POST', credentials: 'same-origin', headers: { 'X-Beacon': '1' } }); - if (!r.ok) throw new Error(`${url}: ${r.status} ${r.statusText}`); + if (!r.ok) throw await failed(r); } /** A JSON request that changes something (PUT, POST with a body), with X-Beacon. */ @@ -255,7 +276,7 @@ export async function send(url: string, method: string, body?: unkn body: body === undefined ? undefined : JSON.stringify(body) }); const j = await r.json().catch(() => ({})); - if (!r.ok) throw new Error((j as { error?: string }).error ?? `${r.status} ${r.statusText}`); + if (!r.ok) throw new APIError((j as { error?: string }).error || `The server answered ${r.status} ${r.statusText}`.trim(), r.status); return j as T; } @@ -267,7 +288,7 @@ export async function sendYAML(url: string, yaml: string): Promise< body: yaml }); const j = await r.json().catch(() => ({})); - if (!r.ok) throw new Error((j as { error?: string }).error ?? `${r.status} ${r.statusText}`); + if (!r.ok) throw new APIError((j as { error?: string }).error || `The server answered ${r.status} ${r.statusText}`.trim(), r.status); return j as T; }