feat(alerting): add quiet hours to alert groups
This commit is contained in:
1 parent
bf529a7711
commit
ee3769f578
21 files changed
+1310
-130
No files matched your search
@@ -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) {
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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",
|
||||
|
||||
+10
-1
@@ -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
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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"`)) {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user