diff --git a/README.md b/README.md index 170e44b..33d37d4 100644 --- a/README.md +++ b/README.md @@ -111,7 +111,9 @@ more groups in the monitor editor. Each organization has a default group, automa assigned to new monitors and new channels. Existing monitors and channels are migrated to that group to preserve delivery. The default group can be renamed and its channels changed, but cannot be deleted. A channel in multiple assigned groups receives each -incident event once. Selecting no groups disables notifications for that monitor. +incident event once. Selecting no groups disables notifications for that monitor. Each group +can also define recurring quiet hours (`quiet_hours`) in a chosen time zone to suppress its +notifications during those periods while incidents continue to be recorded. The API exposes `/api/v1/org/alert-groups` for managing groups and `alert_group_ids` on monitor requests and responses. Omit the field when creating a monitor to use the diff --git a/internal/api/alert_groups.go b/internal/api/alert_groups.go index 0b3fc79..8c79291 100644 --- a/internal/api/alert_groups.go +++ b/internal/api/alert_groups.go @@ -2,6 +2,7 @@ package api import ( "context" + "encoding/json" "errors" "net/http" "slices" @@ -17,13 +18,18 @@ import ( type alertGroupRequest struct { Name string `json:"name" binding:"required,max=100"` ChannelIDs []uuid.UUID `json:"channel_ids" binding:"max=200"` + // QuietHours suppresses notifications from this group during the given + // windows. Omitting it on update preserves existing quiet hours; an + // empty array clears them. + QuietHours []quietHourRequest `json:"quiet_hours" binding:"max=20"` } type alertGroupView struct { - ID uuid.UUID `json:"id"` - Name string `json:"name"` - IsDefault bool `json:"is_default"` - ChannelIDs []uuid.UUID `json:"channel_ids"` + ID uuid.UUID `json:"id"` + Name string `json:"name"` + IsDefault bool `json:"is_default"` + ChannelIDs []uuid.UUID `json:"channel_ids"` + QuietHours []quietHourView `json:"quiet_hours"` } var errInvalidAlertGroup = errors.New("api: invalid alert group") @@ -38,7 +44,10 @@ func (s *Server) listAlertGroups(c *gin.Context) { return err } for _, row := range rows { - out = append(out, alertGroupView{ID: row.ID, Name: row.Name, IsDefault: row.IsDefault, ChannelIDs: row.ChannelIds}) + out = append(out, alertGroupView{ + ID: row.ID, Name: row.Name, IsDefault: row.IsDefault, + ChannelIDs: row.ChannelIds, QuietHours: decodeQuietHours(row.QuietHours), + }) } return nil }) @@ -68,6 +77,17 @@ func (s *Server) saveAlertGroup(c *gin.Context) { return } } + var quietRaw []byte + if 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") == "" { + quietRaw = []byte("[]") + } ctx := c.Request.Context() p := current(c) var row store.AlertGroup @@ -77,9 +97,9 @@ func (s *Server) saveAlertGroup(c *gin.Context) { err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error { var err error if c.Param("id") == "" { - row, err = q.CreateAlertGroup(ctx, store.CreateAlertGroupParams{OrgID: p.Org.ID, Name: req.Name}) + row, err = q.CreateAlertGroup(ctx, store.CreateAlertGroupParams{OrgID: p.Org.ID, Name: req.Name, QuietHours: quietRaw}) } else { - row, err = q.UpdateAlertGroup(ctx, store.UpdateAlertGroupParams{ID: id, Name: req.Name}) + row, err = q.UpdateAlertGroup(ctx, store.UpdateAlertGroupParams{ID: id, Name: req.Name, QuietHours: quietRaw}) } if err != nil { return err @@ -117,7 +137,10 @@ func (s *Server) saveAlertGroup(c *gin.Context) { if req.ChannelIDs == nil { req.ChannelIDs = []uuid.UUID{} } - c.JSON(status, alertGroupView{ID: row.ID, Name: row.Name, IsDefault: row.IsDefault, ChannelIDs: req.ChannelIDs}) + c.JSON(status, alertGroupView{ + ID: row.ID, Name: row.Name, IsDefault: row.IsDefault, + ChannelIDs: req.ChannelIDs, QuietHours: decodeQuietHours(row.QuietHours), + }) } func (s *Server) deleteAlertGroup(c *gin.Context) { diff --git a/internal/api/alert_groups_test.go b/internal/api/alert_groups_test.go index 69d4577..b87291d 100644 --- a/internal/api/alert_groups_test.go +++ b/internal/api/alert_groups_test.go @@ -152,3 +152,137 @@ func TestAlertGroups(t *testing.T) { t.Fatalf("explicit empty creation = %d %v", st, body) } } + +func TestAlertGroupQuietHours(t *testing.T) { + e := newEnv(t) + owner := e.browser(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}) + if st != http.StatusCreated { + t.Fatalf("create channel = %d %v", st, body) + } + return body["channel"].(map[string]any)["id"].(string) + } + quietCh := channel("QuietOnly") + sharedCh := channel("Shared") + activeCh := channel("ActiveOnly") + + // Invalid quiet hours are rejected. + st, body := owner.do("POST", "/api/v1/org/alert-groups", map[string]any{ + "name": "BadTZ", + "channel_ids": []string{quietCh}, + "quiet_hours": []map[string]any{{"start": "22:00", "end": "07:00", "time_zone": "Not/AZone"}}, + }) + expect(t, "invalid timezone", st, body, http.StatusUnprocessableEntity, "invalid_time_zone") + + st, body = owner.do("POST", "/api/v1/org/alert-groups", map[string]any{ + "name": "BadRange", + "channel_ids": []string{quietCh}, + "quiet_hours": []map[string]any{{"start": "12:00", "end": "12:00", "time_zone": "UTC"}}, + }) + expect(t, "equal non-zero times", st, body, http.StatusUnprocessableEntity, "invalid_quiet_hours") + + // Create a group that is muted 24/7 (00:00-00:00 every day) and an active group. + st, body = owner.do("POST", "/api/v1/org/alert-groups", map[string]any{ + "name": "Muted", + "channel_ids": []string{quietCh, sharedCh}, + "quiet_hours": []map[string]any{{"weekdays": []string{}, "start": "00:00", "end": "00:00", "time_zone": "UTC"}}, + }) + if st != http.StatusCreated { + t.Fatalf("create muted group = %d %v", st, body) + } + mutedGroup := body["id"].(string) + if qh := body["quiet_hours"].([]any); len(qh) != 1 { + t.Fatalf("quiet_hours = %v", qh) + } + + // Updating without quiet_hours preserves existing quiet hours. + st, body = owner.do("PUT", "/api/v1/org/alert-groups/"+mutedGroup, map[string]any{ + "name": "Muted Renamed", + "channel_ids": []string{quietCh, sharedCh}, + }) + if st != http.StatusOK || len(body["quiet_hours"].([]any)) != 1 { + t.Fatalf("preserve quiet_hours = %d %v", st, body) + } + + // Settings page shows the quiet hours inputs and active badge. + st, _, html := owner.page("/settings/channels") + if st != http.StatusOK || !strings.Contains(html, `name="quiet_hours.0.start"`) || !strings.Contains(html, "Quiet hours active") { + t.Fatalf("settings page = %d, lacks quiet hours UI", st) + } + + st, body = owner.do("POST", "/api/v1/org/alert-groups", map[string]any{ + "name": "AlwaysOn", + "channel_ids": []string{activeCh, sharedCh}, + "quiet_hours": []map[string]any{}, + }) + if st != http.StatusCreated { + t.Fatalf("create active group = %d %v", st, body) + } + activeGroup := body["id"].(string) + + // Monitor assigned only to Muted: incident opens & resolves, 0 notifications sent. + st, body = owner.do("POST", "/api/v1/org/monitors", map[string]any{ + "name": "SilentBackup", "type": "heartbeat", "interval_seconds": 3600, + "alert_group_ids": []string{mutedGroup}, + }) + if st != http.StatusCreated { + t.Fatalf("create monitor = %d %v", st, body) + } + monID := body["id"].(string) + token := body["target"].(string) + ping := func(suffix string) { + t.Helper() + resp, err := e.srv.Client().Post(e.srv.URL+"/hb/"+token+suffix, "text/plain", strings.NewReader("")) + if err != nil { + t.Fatal(err) + } + _ = resp.Body.Close() + if resp.StatusCode != http.StatusOK { + t.Fatalf("heartbeat %q = %d", suffix, resp.StatusCode) + } + } + 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) + } + 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)) + } + + // 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}, + }) + if st != http.StatusOK { + t.Fatalf("update monitor = %d %v", st, body) + } + 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)) + } + + // Explicitly clearing quiet_hours re-enables notifications on quietCh. + st, body = owner.do("PUT", "/api/v1/org/alert-groups/"+mutedGroup, map[string]any{ + "name": "Muted Renamed", + "channel_ids": []string{quietCh, sharedCh}, + "quiet_hours": []map[string]any{}, + }) + if st != http.StatusOK || len(body["quiet_hours"].([]any)) != 0 { + t.Fatalf("clear quiet_hours = %d %v", 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)) + } +} diff --git a/internal/api/alerting.go b/internal/api/alerting.go index a9034c1..16619dd 100644 --- a/internal/api/alerting.go +++ b/internal/api/alerting.go @@ -97,10 +97,25 @@ func (s *Server) transition(ctx context.Context, m store.MonitorsForResultsRow, if err != nil { return err } - channels, err := q.MonitorChannelIDs(ctx, m.ID) + routes, err := q.MonitorAlertRoutes(ctx, m.ID) if err != nil { return err } + quiet := map[uuid.UUID]bool{} + seen := map[uuid.UUID]bool{} + var channels []uuid.UUID + for _, r := range routes { + muted, ok := quiet[r.GroupID] + if !ok { + muted = isQuietRawAt(r.QuietHours, at) + quiet[r.GroupID] = muted + } + if muted || seen[r.ChannelID] { + continue + } + seen[r.ChannelID] = true + channels = append(channels, r.ChannelID) + } for _, ch := range channels { if err := q.EnqueueNotification(ctx, store.EnqueueNotificationParams{OrgID: m.OrgID, ChannelID: ch, IncidentID: inc.ID, Event: event}); err != nil { return err diff --git a/internal/api/apidocs.go b/internal/api/apidocs.go index abca9ec..207d7d6 100644 --- a/internal/api/apidocs.go +++ b/internal/api/apidocs.go @@ -127,9 +127,11 @@ var endpoints = []endpoint{ {method: "GET", path: "/api/v1/org/alert-groups", tag: "Alerting", summary: "List alert groups and their channels", perm: "notifications.read", resp: obj{"alert_groups": []alertGroupView{}}}, {method: "POST", path: "/api/v1/org/alert-groups", tag: "Alerting", summary: "Create an alert group", perm: "notifications.write", - req: alertGroupRequest{}, status: http.StatusCreated, resp: alertGroupView{}}, - {method: "PUT", path: "/api/v1/org/alert-groups/:id", tag: "Alerting", summary: "Rename an alert group and replace its channels", perm: "notifications.write", - req: alertGroupRequest{}, resp: alertGroupView{}}, + description: "Optional `quiet_hours` suppress notifications from this group during recurring local time windows (`start`/`end` as `HH:MM`, `start > end` wraps overnight, `00:00`–`00:00` or `24:00` covers the full day, empty `weekdays` means every day).", + req: alertGroupRequest{}, status: http.StatusCreated, resp: alertGroupView{}}, + {method: "PUT", path: "/api/v1/org/alert-groups/:id", tag: "Alerting", summary: "Update an alert group, its channels and quiet hours", perm: "notifications.write", + description: "Omitting `quiet_hours` preserves existing quiet hours; an empty array removes them.", + req: alertGroupRequest{}, resp: alertGroupView{}}, {method: "DELETE", path: "/api/v1/org/alert-groups/:id", tag: "Alerting", summary: "Delete an alert group", perm: "notifications.write", description: "The default group cannot be deleted. Deleting other groups removes their monitor assignments; no fallback group is assigned.", status: http.StatusNoContent}, {method: "GET", path: "/api/v1/org/channels", tag: "Alerting", summary: "List notification channels", perm: "notifications.read", diff --git a/internal/api/console.go b/internal/api/console.go index 9efe8f8..2870e29 100644 --- a/internal/api/console.go +++ b/internal/api/console.go @@ -770,11 +770,20 @@ func (s *Server) channelsView(c *gin.Context, p *principal, page web.Page, me we if err != nil { return err } + now := time.Now() for _, g := range groups { - row := web.AlertGroupRow{ID: g.ID.String(), Name: g.Name, Default: g.IsDefault} + qh := decodeQuietHours(g.QuietHours) + row := web.AlertGroupRow{ID: g.ID.String(), Name: g.Name, Default: g.IsDefault, QuietNow: isQuietAt(qh, now)} for _, ch := range rows { row.Channels = append(row.Channels, web.AlertGroupOption{ID: ch.ID.String(), Name: ch.Name, Checked: slices.Contains(g.ChannelIds, ch.ID)}) } + for _, w := range qh { + days := map[int]bool{} + for _, d := range w.Weekdays { + days[d] = true + } + row.QuietHours = append(row.QuietHours, web.AlertGroupQuietRow{Start: w.Start, End: w.End, TimeZone: w.TimeZone, Weekdays: days}) + } v.AlertGroups = append(v.AlertGroups, row) } return nil diff --git a/internal/api/gdpr.go b/internal/api/gdpr.go index fc79a8f..145899c 100644 --- a/internal/api/gdpr.go +++ b/internal/api/gdpr.go @@ -399,7 +399,10 @@ func (s *Server) buildOrgExport(ctx context.Context, p *principal) (orgExport, e } x.AlertGroups = []alertGroupView{} for _, g := range alertGroups { - x.AlertGroups = append(x.AlertGroups, alertGroupView{ID: g.ID, Name: g.Name, IsDefault: g.IsDefault, ChannelIDs: g.ChannelIds}) + x.AlertGroups = append(x.AlertGroups, alertGroupView{ + ID: g.ID, Name: g.Name, IsDefault: g.IsDefault, + ChannelIDs: g.ChannelIds, QuietHours: decodeQuietHours(g.QuietHours), + }) } alertAssignments, err := q.AllMonitorAlertGroups(ctx) if err != nil { diff --git a/internal/api/gdpr_test.go b/internal/api/gdpr_test.go index 9b215df..c3c10e2 100644 --- a/internal/api/gdpr_test.go +++ b/internal/api/gdpr_test.go @@ -101,7 +101,7 @@ func TestExports(t *testing.T) { } group := groups[0].(map[string]any) assigned := monitors[0].(map[string]any)["alert_group_ids"].([]any) - if group["is_default"] != true || len(group["channel_ids"].([]any)) != 1 || len(assigned) != 1 || assigned[0] != group["id"] { + if group["is_default"] != true || len(group["channel_ids"].([]any)) != 1 || len(group["quiet_hours"].([]any)) != 0 || len(assigned) != 1 || assigned[0] != group["id"] { t.Fatalf("export lost alert routing: group=%v assignments=%v", group, assigned) } if !bytes.Contains(raw, []byte(`"Shop"`)) || !bytes.Contains(raw, []byte(`"Hook"`)) { diff --git a/internal/api/quiet_hours.go b/internal/api/quiet_hours.go new file mode 100644 index 0000000..82b01f1 --- /dev/null +++ b/internal/api/quiet_hours.go @@ -0,0 +1,149 @@ +package api + +import ( + "encoding/json" + "slices" + "strconv" + "strings" + "time" +) + +// quietHourRequest is one recurring time window during which an alert group +// suppresses notifications. +type quietHourRequest struct { + // Weekdays are days of the week (0 = Sunday .. 6 = Saturday); empty + // means every day. + Weekdays flexInts `json:"weekdays" binding:"max=7"` + // Start and End are wall-clock times "HH:MM" in TimeZone. End may be + // "24:00"; Start > End wraps overnight into the next day, and + // "00:00" to "00:00" (or "24:00") covers the entire day. + Start string `json:"start" binding:"required,max=5"` + End string `json:"end" binding:"required,max=5"` + TimeZone string `json:"time_zone" binding:"required,max=64"` +} + +// quietHourView is one normalized quiet window returned by the API and stored +// on an alert group. +type quietHourView struct { + Weekdays []int `json:"weekdays"` + Start string `json:"start"` + End string `json:"end"` + TimeZone string `json:"time_zone"` +} + +// validateQuietHours validates and normalizes quiet windows, returning an +// error code on failure. +func validateQuietHours(in []quietHourRequest) ([]quietHourView, string) { + out := make([]quietHourView, 0, len(in)) + for _, w := range in { + tz := strings.TrimSpace(w.TimeZone) + if tz == "" || tz == "Local" { + return nil, "invalid_time_zone" + } + if _, err := time.LoadLocation(tz); err != nil { + return nil, "invalid_time_zone" + } + start := strings.TrimSpace(w.Start) + end := strings.TrimSpace(w.End) + sMin, okS := parseClockMinutes(start, false) + eMin, okE := parseClockMinutes(end, true) + if !okS || !okE { + 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 { + return nil, "invalid_quiet_hours" + } + days := make([]int, 0, len(w.Weekdays)) + for _, d := range w.Weekdays { + if d < 0 || d > 6 { + return nil, "invalid_quiet_hours" + } + days = append(days, d) + } + slices.Sort(days) + days = slices.Compact(days) + out = append(out, quietHourView{ + Weekdays: days, + Start: start, + End: end, + TimeZone: tz, + }) + } + 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) { + 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 { + return 0, false + } + if h == 24 && m == 0 && allow24 { + return 24 * 60, true + } + if h < 0 || h > 23 { + return 0, false + } + return h*60 + m, true +} + +func decodeQuietHours(raw []byte) []quietHourView { + if len(raw) == 0 { + return []quietHourView{} + } + var out []quietHourView + if err := json.Unmarshal(raw, &out); err != nil || out == nil { + return []quietHourView{} + } + for i := range out { + if out[i].Weekdays == nil { + out[i].Weekdays = []int{} + } + } + return out +} + +// 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 { + return false + } + lt := t.In(loadLocation(w.TimeZone)) + nowMin := lt.Hour()*60 + lt.Minute() + today := int(lt.Weekday()) + hasDay := func(d int) bool { + return len(w.Weekdays) == 0 || slices.Contains(w.Weekdays, d) + } + if sMin == 0 && (eMin == 0 || eMin == 24*60) { + return hasDay(today) + } + if sMin < eMin { + return hasDay(today) && nowMin >= sMin && nowMin < eMin + } + // 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) +} + +func isQuietAt(windows []quietHourView, t time.Time) bool { + for _, w := range windows { + if w.contains(t) { + return true + } + } + return false +} + +func isQuietRawAt(raw []byte, t time.Time) bool { + return isQuietAt(decodeQuietHours(raw), t) +} diff --git a/internal/api/quiet_hours_test.go b/internal/api/quiet_hours_test.go new file mode 100644 index 0000000..16389db --- /dev/null +++ b/internal/api/quiet_hours_test.go @@ -0,0 +1,109 @@ +package api + +import ( + "slices" + "testing" + "time" +) + +func TestValidateQuietHours(t *testing.T) { + got, code := validateQuietHours([]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"}, + }) + if code != "" { + t.Fatalf("unexpected error code %q", code) + } + if len(got) != 3 { + t.Fatalf("len = %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 got[1].Weekdays == nil || len(got[1].Weekdays) != 0 { + t.Errorf("nil weekdays should normalize to empty slice: %#v", got[1].Weekdays) + } + + invalid := []struct { + name string + 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"}, + } + 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) + } + } +} + +func TestQuietHoursContains(t *testing.T) { + berlin, err := time.LoadLocation("Europe/Berlin") + if err != nil { + t.Fatal(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. + 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"} + weekend24 := quietHourView{Weekdays: []int{0, 6}, Start: "00:00", End: "24:00", TimeZone: "Europe/Berlin"} + eveningEndZero := quietHourView{Weekdays: []int{5}, Start: "18:00", End: "00:00", TimeZone: "UTC"} + dailyNight := quietHourView{Weekdays: []int{}, Start: "23:00", End: "06:00", TimeZone: "Europe/Berlin"} + + cases := []struct { + name string + w 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}, + + {"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}, + + {"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}, + + {"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}, + + // 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}, + } + 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) + } + } +} diff --git a/internal/i18n/locales/de.json b/internal/i18n/locales/de.json index 5c8ae9d..d720082 100644 --- a/internal/i18n/locales/de.json +++ b/internal/i18n/locales/de.json @@ -25,6 +25,13 @@ "alert_groups.monitor_hint": "Wähle die Gruppen, die Alerts erhalten sollen. Ohne Auswahl werden für diesen Monitor keine Benachrichtigungen verschickt.", "alert_groups.new": "Neue Alertgruppe", "alert_groups.no_channels": "Erstelle unten einen Benachrichtigungskanal, um Alerts zu erhalten.", + "alert_groups.quiet_active": "Ruhezeit aktiv", + "alert_groups.quiet_add": "Ruhezeit hinzufügen", + "alert_groups.quiet_end": "Bis", + "alert_groups.quiet_hint": "Unterdrückt Benachrichtigungen dieser Gruppe in diesen Zeiträumen (Vorfälle werden weiter aufgezeichnet). Ohne Wochentagsauswahl gilt der Zeitraum täglich; 00:00 bis 00:00 gilt ganztägig.", + "alert_groups.quiet_remove": "Entfernen", + "alert_groups.quiet_start": "Von", + "alert_groups.quiet_title": "Ruhezeiten", "alert_groups.save": "Gruppe speichern", "alert_groups.title": "Alertgruppen", "alertmanager.config_hint": "Trage sie als Webhook-Empfänger in die alertmanager.yml ein; send_resolved ist nötig, damit Monitore wieder hochgehen.", @@ -488,6 +495,7 @@ "error.invalid_method": "Nur GET- und HEAD-Anfragen werden unterstützt.", "error.invalid_monitor": "Einer der Monitore existiert nicht oder ist doppelt aufgeführt.", "error.invalid_permissions": "Mindestens eine Berechtigung auswählen.", + "error.invalid_quiet_hours": "Prüfe Startzeit, Endzeit und Wochentage der Ruhezeiten.", "error.invalid_query": "Gib eine PromQL-Abfrage mit höchstens 2000 Zeichen ein.", "error.invalid_record": "Nicht unterstützter DNS-Record-Typ.", "error.invalid_region": "Unbekannte Region.", diff --git a/internal/i18n/locales/en.json b/internal/i18n/locales/en.json index 0c30e30..72cefb1 100644 --- a/internal/i18n/locales/en.json +++ b/internal/i18n/locales/en.json @@ -25,6 +25,13 @@ "alert_groups.monitor_hint": "Select the groups that should receive alerts. No selection disables notifications for this monitor.", "alert_groups.new": "New alert group", "alert_groups.no_channels": "Create a notification channel below to receive alerts.", + "alert_groups.quiet_active": "Quiet hours active", + "alert_groups.quiet_add": "Add quiet period", + "alert_groups.quiet_end": "Until", + "alert_groups.quiet_hint": "Suppress notifications from this group during these times (incidents are still recorded). Leave weekdays unchecked for every day; 00:00 to 00:00 covers the whole day.", + "alert_groups.quiet_remove": "Remove", + "alert_groups.quiet_start": "From", + "alert_groups.quiet_title": "Quiet hours", "alert_groups.save": "Save group", "alert_groups.title": "Alert groups", "alertmanager.config_hint": "Add it to alertmanager.yml as a webhook receiver; send_resolved is needed so monitors recover.", @@ -488,6 +495,7 @@ "error.invalid_method": "Only GET and HEAD requests are supported.", "error.invalid_monitor": "One of the monitors does not exist or is listed twice.", "error.invalid_permissions": "Choose at least one permission.", + "error.invalid_quiet_hours": "Check start time, end time and weekdays of the quiet hours.", "error.invalid_query": "Enter a PromQL query of at most 2000 characters.", "error.invalid_record": "Unsupported DNS record type.", "error.invalid_region": "Unknown region.", diff --git a/internal/migrations/sql/00040_alert_group_quiet_hours.sql b/internal/migrations/sql/00040_alert_group_quiet_hours.sql new file mode 100644 index 0000000..bfc0d57 --- /dev/null +++ b/internal/migrations/sql/00040_alert_group_quiet_hours.sql @@ -0,0 +1,6 @@ +-- +goose Up +ALTER TABLE alert_groups ADD COLUMN quiet_hours jsonb NOT NULL DEFAULT '[]'::jsonb + CHECK (jsonb_typeof(quiet_hours) = 'array'); + +-- +goose Down +ALTER TABLE alert_groups DROP COLUMN quiet_hours; diff --git a/internal/store/alert_groups.sql.go b/internal/store/alert_groups.sql.go index b39a4cb..d3d31b6 100644 --- a/internal/store/alert_groups.sql.go +++ b/internal/store/alert_groups.sql.go @@ -78,22 +78,24 @@ func (q *Queries) AllMonitorAlertGroups(ctx context.Context) ([]MonitorAlertGrou } const createAlertGroup = `-- name: CreateAlertGroup :one -INSERT INTO alert_groups (org_id, name) VALUES ($1, $2) RETURNING id, org_id, name, is_default +INSERT INTO alert_groups (org_id, name, quiet_hours) VALUES ($1, $2, $3) RETURNING id, org_id, name, is_default, quiet_hours ` type CreateAlertGroupParams struct { - OrgID uuid.UUID - Name string + OrgID uuid.UUID + Name string + QuietHours []byte } func (q *Queries) CreateAlertGroup(ctx context.Context, arg CreateAlertGroupParams) (AlertGroup, error) { - row := q.db.QueryRow(ctx, createAlertGroup, arg.OrgID, arg.Name) + row := q.db.QueryRow(ctx, createAlertGroup, arg.OrgID, arg.Name, arg.QuietHours) var i AlertGroup err := row.Scan( &i.ID, &i.OrgID, &i.Name, &i.IsDefault, + &i.QuietHours, ) return i, err } @@ -129,7 +131,7 @@ func (q *Queries) DeleteMonitorAlertGroups(ctx context.Context, monitorID uuid.U } const listAlertGroups = `-- name: ListAlertGroups :many -SELECT g.id, g.org_id, g.name, g.is_default, ARRAY(SELECT c.channel_id FROM alert_group_channels c WHERE c.group_id = g.id ORDER BY c.channel_id)::uuid[] AS channel_ids +SELECT g.id, g.org_id, g.name, g.is_default, g.quiet_hours, ARRAY(SELECT c.channel_id FROM alert_group_channels c WHERE c.group_id = g.id ORDER BY c.channel_id)::uuid[] AS channel_ids FROM alert_groups g ORDER BY g.is_default DESC, g.name, g.id ` @@ -138,6 +140,7 @@ type ListAlertGroupsRow struct { OrgID uuid.UUID Name string IsDefault bool + QuietHours []byte ChannelIds []uuid.UUID } @@ -155,6 +158,7 @@ func (q *Queries) ListAlertGroups(ctx context.Context) ([]ListAlertGroupsRow, er &i.OrgID, &i.Name, &i.IsDefault, + &i.QuietHours, &i.ChannelIds, ); err != nil { return nil, err @@ -191,26 +195,34 @@ func (q *Queries) MonitorAlertGroups(ctx context.Context, monitorID uuid.UUID) ( return items, nil } -const monitorChannelIDs = `-- name: MonitorChannelIDs :many -SELECT DISTINCT c.id FROM notification_channels c -JOIN alert_group_channels gc ON gc.channel_id = c.id AND gc.org_id = c.org_id -JOIN monitor_alert_groups mg ON mg.group_id = gc.group_id AND mg.org_id = gc.org_id +const monitorAlertRoutes = `-- name: MonitorAlertRoutes :many +SELECT g.id AS group_id, g.quiet_hours, c.id AS channel_id +FROM alert_groups g +JOIN monitor_alert_groups mg ON mg.group_id = g.id AND mg.org_id = g.org_id +JOIN alert_group_channels gc ON gc.group_id = g.id AND gc.org_id = g.org_id +JOIN notification_channels c ON c.id = gc.channel_id AND c.org_id = gc.org_id WHERE mg.monitor_id = $1 AND c.enabled ` -func (q *Queries) MonitorChannelIDs(ctx context.Context, monitorID uuid.UUID) ([]uuid.UUID, error) { - rows, err := q.db.Query(ctx, monitorChannelIDs, monitorID) +type MonitorAlertRoutesRow struct { + GroupID uuid.UUID + QuietHours []byte + ChannelID uuid.UUID +} + +func (q *Queries) MonitorAlertRoutes(ctx context.Context, monitorID uuid.UUID) ([]MonitorAlertRoutesRow, error) { + rows, err := q.db.Query(ctx, monitorAlertRoutes, monitorID) if err != nil { return nil, err } defer rows.Close() - items := []uuid.UUID{} + items := []MonitorAlertRoutesRow{} for rows.Next() { - var id uuid.UUID - if err := rows.Scan(&id); err != nil { + var i MonitorAlertRoutesRow + if err := rows.Scan(&i.GroupID, &i.QuietHours, &i.ChannelID); err != nil { return nil, err } - items = append(items, id) + items = append(items, i) } if err := rows.Err(); err != nil { return nil, err @@ -219,22 +231,27 @@ func (q *Queries) MonitorChannelIDs(ctx context.Context, monitorID uuid.UUID) ([ } const updateAlertGroup = `-- name: UpdateAlertGroup :one -UPDATE alert_groups SET name = $2 WHERE id = $1 RETURNING id, org_id, name, is_default +UPDATE alert_groups +SET name = $2, quiet_hours = coalesce($3, quiet_hours) +WHERE id = $1 +RETURNING id, org_id, name, is_default, quiet_hours ` type UpdateAlertGroupParams struct { - ID uuid.UUID - Name string + ID uuid.UUID + Name string + QuietHours []byte } func (q *Queries) UpdateAlertGroup(ctx context.Context, arg UpdateAlertGroupParams) (AlertGroup, error) { - row := q.db.QueryRow(ctx, updateAlertGroup, arg.ID, arg.Name) + row := q.db.QueryRow(ctx, updateAlertGroup, arg.ID, arg.Name, arg.QuietHours) var i AlertGroup err := row.Scan( &i.ID, &i.OrgID, &i.Name, &i.IsDefault, + &i.QuietHours, ) return i, err } diff --git a/internal/store/models.go b/internal/store/models.go index fcce215..5ca50ef 100644 --- a/internal/store/models.go +++ b/internal/store/models.go @@ -42,10 +42,11 @@ type AgentStorage struct { } type AlertGroup struct { - ID uuid.UUID - OrgID uuid.UUID - Name string - IsDefault bool + ID uuid.UUID + OrgID uuid.UUID + Name string + IsDefault bool + QuietHours []byte } type AlertGroupChannel struct { diff --git a/internal/store/querier.go b/internal/store/querier.go index d82c260..d89277b 100644 --- a/internal/store/querier.go +++ b/internal/store/querier.go @@ -196,7 +196,7 @@ type Querier interface { // Every role a member holds, with the scope it applies to. MemberGrants(ctx context.Context, arg MemberGrantsParams) ([]MemberGrantsRow, error) MonitorAlertGroups(ctx context.Context, monitorID uuid.UUID) ([]uuid.UUID, error) - MonitorChannelIDs(ctx context.Context, monitorID uuid.UUID) ([]uuid.UUID, error) + MonitorAlertRoutes(ctx context.Context, monitorID uuid.UUID) ([]MonitorAlertRoutesRow, error) MonitorIncidents(ctx context.Context, monitorID uuid.UUID) ([]Incident, error) MonitorRegions(ctx context.Context, monitorID uuid.UUID) ([]uuid.UUID, error) // System scope: monitors to hand to a checker of region, skipping ones that diff --git a/internal/store/queries/alert_groups.sql b/internal/store/queries/alert_groups.sql index f6edcdf..903f8a8 100644 --- a/internal/store/queries/alert_groups.sql +++ b/internal/store/queries/alert_groups.sql @@ -3,10 +3,13 @@ SELECT g.*, ARRAY(SELECT c.channel_id FROM alert_group_channels c WHERE c.group_ FROM alert_groups g ORDER BY g.is_default DESC, g.name, g.id; -- name: CreateAlertGroup :one -INSERT INTO alert_groups (org_id, name) VALUES ($1, $2) RETURNING *; +INSERT INTO alert_groups (org_id, name, quiet_hours) VALUES ($1, $2, $3) RETURNING *; -- name: UpdateAlertGroup :one -UPDATE alert_groups SET name = $2 WHERE id = $1 RETURNING *; +UPDATE alert_groups +SET name = $2, quiet_hours = coalesce(sqlc.narg(quiet_hours), quiet_hours) +WHERE id = $1 +RETURNING *; -- name: DeleteAlertGroup :execrows DELETE FROM alert_groups WHERE id = $1 AND NOT is_default; @@ -35,8 +38,10 @@ SELECT g.org_id, sqlc.arg(monitor_id), g.id FROM alert_groups g WHERE g.id = sqlc.arg(group_id) AND g.org_id = sqlc.arg(org_id) ON CONFLICT DO NOTHING; --- name: MonitorChannelIDs :many -SELECT DISTINCT c.id FROM notification_channels c -JOIN alert_group_channels gc ON gc.channel_id = c.id AND gc.org_id = c.org_id -JOIN monitor_alert_groups mg ON mg.group_id = gc.group_id AND mg.org_id = gc.org_id +-- name: MonitorAlertRoutes :many +SELECT g.id AS group_id, g.quiet_hours, c.id AS channel_id +FROM alert_groups g +JOIN monitor_alert_groups mg ON mg.group_id = g.id AND mg.org_id = g.org_id +JOIN alert_group_channels gc ON gc.group_id = g.id AND gc.org_id = g.org_id +JOIN notification_channels c ON c.id = gc.channel_id AND c.org_id = gc.org_id WHERE mg.monitor_id = $1 AND c.enabled; diff --git a/internal/web/alert_groups.templ b/internal/web/alert_groups.templ index 73bf0d5..cfcc5dc 100644 --- a/internal/web/alert_groups.templ +++ b/internal/web/alert_groups.templ @@ -1,6 +1,10 @@ package web -import "git.zb-server.de/ZB-Server/uptimesebi/internal/i18n" +import ( + "strconv" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/i18n" +) // AlertGroupOption is a selectable group or channel in an alert routing form. type AlertGroupOption struct { @@ -10,12 +14,29 @@ type AlertGroupOption struct { Checked bool } -// AlertGroupRow describes a group and its available notification channels. +// AlertGroupQuietRow is one quiet-hours window rendered in an alert group form. +type AlertGroupQuietRow struct { + Start string + End string + TimeZone string + Weekdays map[int]bool +} + +// AlertGroupRow describes a group, its channels and its quiet hours. type AlertGroupRow struct { - ID string - Name string - Default bool - Channels []AlertGroupOption + ID string + Name string + Default bool + QuietNow bool + Channels []AlertGroupOption + QuietHours []AlertGroupQuietRow +} + +func quietEndInput(end string) string { + if end == "24:00" { + return "00:00" + } + return end } templ alertGroupOptions(name string, options []AlertGroupOption) { @@ -31,16 +52,78 @@ templ alertGroupOptions(name string, options []AlertGroupOption) { } } +templ alertGroupQuietRow(prefix string, q AlertGroupQuietRow, canWrite bool) { +
{ i18n.T(ctx, "alert_groups.quiet_title") }
+{ i18n.T(ctx, "alert_groups.quiet_hint") }
+ +{ i18n.T(ctx, "alert_groups.intro") }
+") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var29 string + templ_7745c5c3_Var29, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "alert_groups.quiet_title")) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/alert_groups.templ`, Line: 88, Col: 115} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var29)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 43, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var30 string + templ_7745c5c3_Var30, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "alert_groups.quiet_hint")) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/alert_groups.templ`, Line: 89, Col: 77} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var30)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 44, "
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 51, "
") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - var templ_7745c5c3_Var8 string - templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "alert_groups.intro")) + var templ_7745c5c3_Var33 string + templ_7745c5c3_Var33, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "alert_groups.intro")) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/alert_groups.templ`, Line: 37, Col: 82} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/alert_groups.templ`, Line: 108, Col: 82} } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8)) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var33)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 14, "