feat(alerting): add quiet hours to alert groups #108

Merged
Sebi merged 2 commits from feat/alert-group-quiet-hours into main 2026-11-22 19:17:01 +00:00
4 changed files with 162 additions and 94 deletions
Showing only changes of commit 1c31003baf - Show all commits

No files matched your search

+9 -3
View File
@@ -78,14 +78,20 @@ func (s *Server) saveAlertGroup(c *gin.Context) {
}
}
var quietRaw []byte
if req.QuietHours != nil {
switch {
case req.QuietHours != nil:
qh, code := validateQuietHours(req.QuietHours)
if code != "" {
fail(c, http.StatusUnprocessableEntity, code)
return
}
quietRaw, _ = json.Marshal(qh)
} else if c.Param("id") == "" {
var err error
quietRaw, err = json.Marshal(qh)
if err != nil {
internalError(c, err)
return
}
case c.Param("id") == "":
quietRaw = []byte("[]")
}
ctx := c.Request.Context()
+24 -13
View File
@@ -159,9 +159,15 @@ func TestAlertGroupQuietHours(t *testing.T) {
owner.signup("q@"+uniq("agq")+".test", uniq("agq-"))
channel := func(name string) string {
t.Helper()
st, body := owner.do("POST", "/api/v1/org/channels", map[string]any{"name": name, "type": "webhook", "url": "https://example.test/hook", "enabled": true})
req := map[string]any{
"name": name,
"type": "webhook",
"url": "https://example.test/hook",
"enabled": true,
}
st, body := owner.do("POST", "/api/v1/org/channels", req)
if st != http.StatusCreated {
t.Fatalf("create channel = %d %v", st, body)
t.Fatalf("POST /api/v1/org/channels = %d %v, want %d", st, body, http.StatusCreated)
}
return body["channel"].(map[string]any)["id"].(string)
}
@@ -245,30 +251,35 @@ func TestAlertGroupQuietHours(t *testing.T) {
}
}
count := func(ch string) int {
return e.count(t, `SELECT count(*) FROM notifications n JOIN incidents i ON i.id=n.incident_id WHERE i.monitor_id=$1 AND n.channel_id=$2`, monID, ch)
const q = `SELECT count(*) FROM notifications n
JOIN incidents i ON i.id = n.incident_id
WHERE i.monitor_id = $1 AND n.channel_id = $2`
return e.count(t, q, monID, ch)
}
ping("/fail")
ping("")
if inc := e.count(t, `SELECT count(*) FROM incidents WHERE monitor_id=$1`, monID); inc != 1 {
t.Fatalf("incidents = %d, want 1", inc)
}
if count(quietCh) != 0 || count(sharedCh) != 0 {
t.Fatalf("muted group sent notifications: quiet=%d shared=%d", count(quietCh), count(sharedCh))
if q, s := count(quietCh), count(sharedCh); q != 0 || s != 0 {
t.Fatalf("muted notifications quiet/shared = %d/%d, want 0/0", q, s)
}
// Assign both Muted and AlwaysOn: only AlwaysOn's channels (activeCh + sharedCh) notify,
// while quietCh stays silent.
st, body = owner.do("PUT", "/api/v1/org/monitors/"+monID, map[string]any{
"name": "SilentBackup", "type": "heartbeat", "interval_seconds": 3600,
"alert_group_ids": []string{mutedGroup, activeGroup},
"name": "SilentBackup",
"type": "heartbeat",
"interval_seconds": 3600,
"alert_group_ids": []string{mutedGroup, activeGroup},
})
if st != http.StatusOK {
t.Fatalf("update monitor = %d %v", st, body)
t.Fatalf("PUT /api/v1/org/monitors/%s = %d %v, want %d", monID, st, body, http.StatusOK)
}
ping("/fail")
ping("")
if count(quietCh) != 0 || count(activeCh) != 2 || count(sharedCh) != 2 {
t.Fatalf("mixed quiet/active deliveries quiet/active/shared = %d/%d/%d, want 0/2/2", count(quietCh), count(activeCh), count(sharedCh))
if q, a, s := count(quietCh), count(activeCh), count(sharedCh); q != 0 || a != 2 || s != 2 {
t.Fatalf("mixed deliveries quiet/active/shared = %d/%d/%d, want 0/2/2", q, a, s)
}
// Explicitly clearing quiet_hours re-enables notifications on quietCh.
@@ -278,11 +289,11 @@ func TestAlertGroupQuietHours(t *testing.T) {
"quiet_hours": []map[string]any{},
})
if st != http.StatusOK || len(body["quiet_hours"].([]any)) != 0 {
t.Fatalf("clear quiet_hours = %d %v", st, body)
t.Fatalf("clear quiet_hours = %d %v, want 200 with empty quiet_hours", st, body)
}
ping("/fail")
ping("")
if count(quietCh) != 2 || count(activeCh) != 4 || count(sharedCh) != 4 {
t.Fatalf("after clearing quiet hours quiet/active/shared = %d/%d/%d, want 2/4/4", count(quietCh), count(activeCh), count(sharedCh))
if q, a, s := count(quietCh), count(activeCh), count(sharedCh); q != 2 || a != 4 || s != 4 {
t.Fatalf("after clearing quiet hours quiet/active/shared = %d/%d/%d, want 2/4/4", q, a, s)
}
}
+33 -25
View File
@@ -45,14 +45,14 @@ func validateQuietHours(in []quietHourRequest) ([]quietHourView, string) {
}
start := strings.TrimSpace(w.Start)
end := strings.TrimSpace(w.End)
sMin, okS := parseClockMinutes(start, false)
eMin, okE := parseClockMinutes(end, true)
if !okS || !okE {
startMin, startOK := parseClockMinutes(start)
endMin, endOK := parseEndMinutes(end)
if !startOK || !endOK {
return nil, "invalid_quiet_hours"
}
// Identical non-zero times would be an empty window; 00:00-00:00
// (like 00:00-24:00) means the whole day.
if sMin == eMin && sMin != 0 {
if startMin == endMin && startMin != 0 {
return nil, "invalid_quiet_hours"
}
days := make([]int, 0, len(w.Weekdays))
@@ -74,26 +74,33 @@ func validateQuietHours(in []quietHourRequest) ([]quietHourView, string) {
return out, ""
}
// parseClockMinutes parses "HH:MM" into minutes since midnight. When allow24
// is true, "24:00" is also accepted as 1440.
func parseClockMinutes(s string, allow24 bool) (int, bool) {
// parseClockMinutes parses "HH:MM" (00:00..23:59) into minutes since midnight.
func parseClockMinutes(s string) (int, bool) {
if len(s) != 5 || s[2] != ':' {
return 0, false
}
h, err1 := strconv.Atoi(s[:2])
m, err2 := strconv.Atoi(s[3:])
if err1 != nil || err2 != nil || m < 0 || m > 59 {
hour, err := strconv.Atoi(s[:2])
if err != nil || hour < 0 || hour > 23 {
return 0, false
}
if h == 24 && m == 0 && allow24 {
return 24 * 60, true
}
if h < 0 || h > 23 {
minute, err := strconv.Atoi(s[3:])
if err != nil || minute < 0 || minute > 59 {
return 0, false
}
return h*60 + m, true
return hour*60 + minute, true
}
// parseEndMinutes parses a window end time, accepting "24:00" in addition to
// 00:00..23:59.
func parseEndMinutes(s string) (int, bool) {
if s == "24:00" {
return 24 * 60, true
}
return parseClockMinutes(s)
}
// decodeQuietHours decodes stored JSONB quiet windows, always returning a
// non-nil slice so JSON responses serialize as [] rather than null.
func decodeQuietHours(raw []byte) []quietHourView {
if len(raw) == 0 {
return []quietHourView{}
@@ -112,29 +119,30 @@ func decodeQuietHours(raw []byte) []quietHourView {
// contains reports whether t falls inside w in w's time zone.
func (w quietHourView) contains(t time.Time) bool {
sMin, okS := parseClockMinutes(w.Start, false)
eMin, okE := parseClockMinutes(w.End, true)
if !okS || !okE {
startMin, startOK := parseClockMinutes(w.Start)
endMin, endOK := parseEndMinutes(w.End)
if !startOK || !endOK {
return false
}
lt := t.In(loadLocation(w.TimeZone))
nowMin := lt.Hour()*60 + lt.Minute()
today := int(lt.Weekday())
local := t.In(loadLocation(w.TimeZone))
nowMin := local.Hour()*60 + local.Minute()
today := int(local.Weekday())
hasDay := func(d int) bool {
return len(w.Weekdays) == 0 || slices.Contains(w.Weekdays, d)
}
if sMin == 0 && (eMin == 0 || eMin == 24*60) {
if startMin == 0 && (endMin == 0 || endMin == 24*60) {
return hasDay(today)
}
if sMin < eMin {
return hasDay(today) && nowMin >= sMin && nowMin < eMin
if startMin < endMin {
return hasDay(today) && nowMin >= startMin && nowMin < endMin
}
// Overnight window (Start > End), e.g. 22:00-07:00 or 18:00-00:00:
// covers [Start, 24:00) on matching days and [00:00, End) on the next day.
yesterday := (today + 6) % 7
return (hasDay(today) && nowMin >= sMin) || (hasDay(yesterday) && nowMin < eMin)
return (hasDay(today) && nowMin >= startMin) || (hasDay(yesterday) && nowMin < endMin)
}
// isQuietAt reports whether any window in windows suppresses notifications at t.
func isQuietAt(windows []quietHourView, t time.Time) bool {
for _, w := range windows {
if w.contains(t) {
+96 -53
View File
@@ -7,22 +7,23 @@ import (
)
func TestValidateQuietHours(t *testing.T) {
got, code := validateQuietHours([]quietHourRequest{
in := []quietHourRequest{
{Weekdays: flexInts{5, 1, 5, 3}, Start: "22:00", End: "07:00", TimeZone: "Europe/Berlin"},
{Weekdays: nil, Start: "00:00", End: "24:00", TimeZone: "UTC"},
{Weekdays: flexInts{0, 6}, Start: "00:00", End: "00:00", TimeZone: "UTC"},
})
}
got, code := validateQuietHours(in)
if code != "" {
t.Fatalf("unexpected error code %q", code)
t.Fatalf("validateQuietHours(%+v) error code = %q, want %q", in, code, "")
}
if len(got) != 3 {
t.Fatalf("len = %d, want 3", len(got))
t.Fatalf("len(validateQuietHours(...)) = %d, want 3", len(got))
}
if !slices.Equal(got[0].Weekdays, []int{1, 3, 5}) {
t.Errorf("weekdays not sorted/deduped: %v", got[0].Weekdays)
if want := []int{1, 3, 5}; !slices.Equal(got[0].Weekdays, want) {
t.Errorf("got[0].Weekdays = %v, want %v", got[0].Weekdays, want)
}
if got[1].Weekdays == nil || len(got[1].Weekdays) != 0 {
t.Errorf("nil weekdays should normalize to empty slice: %#v", got[1].Weekdays)
t.Errorf("got[1].Weekdays = %#v, want non-nil empty []int{}", got[1].Weekdays)
}
invalid := []struct {
@@ -30,33 +31,73 @@ func TestValidateQuietHours(t *testing.T) {
req quietHourRequest
want string
}{
{"empty tz", quietHourRequest{Start: "22:00", End: "07:00", TimeZone: ""}, "invalid_time_zone"},
{"local tz", quietHourRequest{Start: "22:00", End: "07:00", TimeZone: "Local"}, "invalid_time_zone"},
{"unknown tz", quietHourRequest{Start: "22:00", End: "07:00", TimeZone: "Mars/Olympus"}, "invalid_time_zone"},
{"bad start", quietHourRequest{Start: "24:00", End: "07:00", TimeZone: "UTC"}, "invalid_quiet_hours"},
{"bad end", quietHourRequest{Start: "22:00", End: "24:01", TimeZone: "UTC"}, "invalid_quiet_hours"},
{"short format", quietHourRequest{Start: "9:00", End: "17:00", TimeZone: "UTC"}, "invalid_quiet_hours"},
{"equal non-zero", quietHourRequest{Start: "12:00", End: "12:00", TimeZone: "UTC"}, "invalid_quiet_hours"},
{"weekday negative", quietHourRequest{Weekdays: flexInts{-1}, Start: "22:00", End: "07:00", TimeZone: "UTC"}, "invalid_quiet_hours"},
{"weekday > 6", quietHourRequest{Weekdays: flexInts{7}, Start: "22:00", End: "07:00", TimeZone: "UTC"}, "invalid_quiet_hours"},
{
name: "empty time zone",
req: quietHourRequest{Start: "22:00", End: "07:00", TimeZone: ""},
want: "invalid_time_zone",
},
{
name: "local time zone",
req: quietHourRequest{Start: "22:00", End: "07:00", TimeZone: "Local"},
want: "invalid_time_zone",
},
{
name: "unknown time zone",
req: quietHourRequest{Start: "22:00", End: "07:00", TimeZone: "Mars/Olympus"},
want: "invalid_time_zone",
},
{
name: "invalid start hour",
req: quietHourRequest{Start: "24:00", End: "07:00", TimeZone: "UTC"},
want: "invalid_quiet_hours",
},
{
name: "invalid end minute",
req: quietHourRequest{Start: "22:00", End: "24:01", TimeZone: "UTC"},
want: "invalid_quiet_hours",
},
{
name: "short clock format",
req: quietHourRequest{Start: "9:00", End: "17:00", TimeZone: "UTC"},
want: "invalid_quiet_hours",
},
{
name: "equal non-zero start and end",
req: quietHourRequest{Start: "12:00", End: "12:00", TimeZone: "UTC"},
want: "invalid_quiet_hours",
},
{
name: "negative weekday",
req: quietHourRequest{Weekdays: flexInts{-1}, Start: "22:00", End: "07:00", TimeZone: "UTC"},
want: "invalid_quiet_hours",
},
{
name: "weekday out of range",
req: quietHourRequest{Weekdays: flexInts{7}, Start: "22:00", End: "07:00", TimeZone: "UTC"},
want: "invalid_quiet_hours",
},
}
for _, tc := range invalid {
if _, code := validateQuietHours([]quietHourRequest{tc.req}); code != tc.want {
t.Errorf("%s: code = %q, want %q", tc.name, code, tc.want)
}
t.Run(tc.name, func(t *testing.T) {
_, got := validateQuietHours([]quietHourRequest{tc.req})
if got != tc.want {
t.Errorf("validateQuietHours(%+v) error code = %q, want %q", tc.req, got, tc.want)
}
})
}
}
func TestQuietHoursContains(t *testing.T) {
berlin, err := time.LoadLocation("Europe/Berlin")
if err != nil {
t.Fatal(err)
t.Fatalf("time.LoadLocation(%q) error = %v", "Europe/Berlin", err)
}
at := func(y int, m time.Month, d, hh, mm int, loc *time.Location) time.Time {
return time.Date(y, m, d, hh, mm, 0, 0, loc)
}
// 2026-11-23 is Monday, 2026-11-27 is Friday, 2026-11-28 is Saturday, 2026-11-29 is Sunday.
// 2026-11-23 is Monday, 2026-11-27 is Friday, 2026-11-28 is Saturday,
// and 2026-11-29 is Sunday.
daytime := quietHourView{Weekdays: []int{1, 2, 3, 4, 5}, Start: "09:00", End: "17:00", TimeZone: "Europe/Berlin"}
overnight := quietHourView{Weekdays: []int{1, 2, 3, 4, 5}, Start: "22:00", End: "07:00", TimeZone: "Europe/Berlin"}
weekendZero := quietHourView{Weekdays: []int{0, 6}, Start: "00:00", End: "00:00", TimeZone: "Europe/Berlin"}
@@ -65,45 +106,47 @@ func TestQuietHoursContains(t *testing.T) {
dailyNight := quietHourView{Weekdays: []int{}, Start: "23:00", End: "06:00", TimeZone: "Europe/Berlin"}
cases := []struct {
name string
w quietHourView
ts time.Time
want bool
name string
window quietHourView
ts time.Time
want bool
}{
{"daytime before start", daytime, at(2026, 11, 23, 8, 59, berlin), false},
{"daytime at start", daytime, at(2026, 11, 23, 9, 0, berlin), true},
{"daytime inside", daytime, at(2026, 11, 23, 16, 59, berlin), true},
{"daytime at end", daytime, at(2026, 11, 23, 17, 0, berlin), false},
{"daytime wrong day", daytime, at(2026, 11, 28, 12, 0, berlin), false},
{name: "daytime before start", window: daytime, ts: at(2026, 11, 23, 8, 59, berlin), want: false},
{name: "daytime at start", window: daytime, ts: at(2026, 11, 23, 9, 0, berlin), want: true},
{name: "daytime inside", window: daytime, ts: at(2026, 11, 23, 16, 59, berlin), want: true},
{name: "daytime at end", window: daytime, ts: at(2026, 11, 23, 17, 0, berlin), want: false},
{name: "daytime wrong day", window: daytime, ts: at(2026, 11, 28, 12, 0, berlin), want: false},
{"overnight mon before", overnight, at(2026, 11, 23, 21, 59, berlin), false},
{"overnight mon start", overnight, at(2026, 11, 23, 22, 0, berlin), true},
{"overnight mon early morning (from sun)", overnight, at(2026, 11, 23, 3, 0, berlin), false},
{"overnight tue early morning (from mon)", overnight, at(2026, 11, 24, 6, 59, berlin), true},
{"overnight tue at end", overnight, at(2026, 11, 24, 7, 0, berlin), false},
{"overnight sat early morning (from fri)", overnight, at(2026, 11, 28, 3, 0, berlin), true},
{"overnight sat late evening", overnight, at(2026, 11, 28, 23, 0, berlin), false},
{"overnight sun early morning", overnight, at(2026, 11, 29, 3, 0, berlin), false},
{name: "overnight mon before", window: overnight, ts: at(2026, 11, 23, 21, 59, berlin), want: false},
{name: "overnight mon start", window: overnight, ts: at(2026, 11, 23, 22, 0, berlin), want: true},
{name: "overnight mon early from sun", window: overnight, ts: at(2026, 11, 23, 3, 0, berlin), want: false},
{name: "overnight tue early from mon", window: overnight, ts: at(2026, 11, 24, 6, 59, berlin), want: true},
{name: "overnight tue at end", window: overnight, ts: at(2026, 11, 24, 7, 0, berlin), want: false},
{name: "overnight sat early from fri", window: overnight, ts: at(2026, 11, 28, 3, 0, berlin), want: true},
{name: "overnight sat late", window: overnight, ts: at(2026, 11, 28, 23, 0, berlin), want: false},
{name: "overnight sun early", window: overnight, ts: at(2026, 11, 29, 3, 0, berlin), want: false},
{"weekend 00-00 sat", weekendZero, at(2026, 11, 28, 0, 0, berlin), true},
{"weekend 00-00 sun late", weekendZero, at(2026, 11, 29, 23, 59, berlin), true},
{"weekend 00-00 mon", weekendZero, at(2026, 11, 30, 0, 0, berlin), false},
{"weekend 00-24 sat", weekend24, at(2026, 11, 28, 15, 0, berlin), true},
{"weekend 00-24 mon", weekend24, at(2026, 11, 30, 0, 0, berlin), false},
{name: "weekend 00-00 sat", window: weekendZero, ts: at(2026, 11, 28, 0, 0, berlin), want: true},
{name: "weekend 00-00 sun late", window: weekendZero, ts: at(2026, 11, 29, 23, 59, berlin), want: true},
{name: "weekend 00-00 mon", window: weekendZero, ts: at(2026, 11, 30, 0, 0, berlin), want: false},
{name: "weekend 00-24 sat", window: weekend24, ts: at(2026, 11, 28, 15, 0, berlin), want: true},
{name: "weekend 00-24 mon", window: weekend24, ts: at(2026, 11, 30, 0, 0, berlin), want: false},
{"evening 18-00 fri inside", eveningEndZero, at(2026, 11, 27, 23, 59, time.UTC), true},
{"evening 18-00 sat midnight", eveningEndZero, at(2026, 11, 28, 0, 0, time.UTC), false},
{name: "evening 18-00 fri inside", window: eveningEndZero, ts: at(2026, 11, 27, 23, 59, time.UTC), want: true},
{name: "evening 18-00 sat midnight", window: eveningEndZero, ts: at(2026, 11, 28, 0, 0, time.UTC), want: false},
// Winter (CET = UTC+1) vs summer (CEST = UTC+2) in Europe/Berlin.
{"daily winter 22:30 UTC is 23:30 CET", dailyNight, at(2026, 1, 15, 22, 30, time.UTC), true},
{"daily winter 21:30 UTC is 22:30 CET", dailyNight, at(2026, 1, 15, 21, 30, time.UTC), false},
{"daily summer 21:30 UTC is 23:30 CEST", dailyNight, at(2026, 7, 15, 21, 30, time.UTC), true},
{"daily summer 03:30 UTC is 05:30 CEST", dailyNight, at(2026, 7, 15, 3, 30, time.UTC), true},
{"daily summer 04:00 UTC is 06:00 CEST", dailyNight, at(2026, 7, 15, 4, 0, time.UTC), false},
{name: "daily winter 22:30 UTC is 23:30 CET", window: dailyNight, ts: at(2026, 1, 15, 22, 30, time.UTC), want: true},
{name: "daily winter 21:30 UTC is 22:30 CET", window: dailyNight, ts: at(2026, 1, 15, 21, 30, time.UTC), want: false},
{name: "daily summer 21:30 UTC is 23:30 CEST", window: dailyNight, ts: at(2026, 7, 15, 21, 30, time.UTC), want: true},
{name: "daily summer 03:30 UTC is 05:30 CEST", window: dailyNight, ts: at(2026, 7, 15, 3, 30, time.UTC), want: true},
{name: "daily summer 04:00 UTC is 06:00 CEST", window: dailyNight, ts: at(2026, 7, 15, 4, 0, time.UTC), want: false},
}
for _, tc := range cases {
if got := tc.w.contains(tc.ts); got != tc.want {
t.Errorf("%s: contains(%s) = %t, want %t", tc.name, tc.ts.Format(time.RFC3339), got, tc.want)
}
t.Run(tc.name, func(t *testing.T) {
if got := tc.window.contains(tc.ts); got != tc.want {
t.Errorf("contains(%s) = %t, want %t", tc.ts.Format(time.RFC3339), got, tc.want)
}
})
}
}