Alerts: keep one order; show the server's message on errors #47

Merged
jcoffey-dev merged 1 commits from fix/alerts-stable-order into main 2026-11-16 05:32:48 +00:00
3 changed files with 75 additions and 5 deletions

No files matched your search

+15 -1
View File
@@ -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 {
+35
View File
@@ -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")
}
}
+25 -4
View File
@@ -237,14 +237,35 @@ export class SignedOut extends Error {
export async function get<T>(url: string): Promise<T> {
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<T>;
}
/**
* 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<APIError> {
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<void> {
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<T = unknown>(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<T = unknown>(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;
}