diff --git a/docs/site/docs/integrations/notifications.md b/docs/site/docs/integrations/notifications.md index 5e24646..5172b03 100644 --- a/docs/site/docs/integrations/notifications.md +++ b/docs/site/docs/integrations/notifications.md @@ -20,6 +20,34 @@ Examples include: - AI review notifications after incident analysis completes - Incident deep-links when you configure an instance base URL +## Quiet Hours & Rate Limiting + +Each notification destination can be tuned independently so a 3 AM reboot or a +flapping container does not wake you. + +### Quiet hours + +Set a daily window (start and end time) during which the destination is +silenced. The window is evaluated in the **server's configured timezone** and +may wrap past midnight (e.g. `22:00`–`07:00`). When a notification lands inside +the window, the destination's mode decides what happens: + +- **Drop** — the notification is silently not sent. The incident still appears + in the timeline; you simply are not pinged. +- **Defer & digest** — held notifications are rolled up and sent as a single + digest when the window ends. A digest left pending across a server restart is + flushed on the next startup. + +### Rate limit + +Cap a destination at a maximum number of notifications per **hour** or per +**day** (a sliding window). Once the cap is reached, further notifications are +**dropped**, and the next notification that *is* allowed through carries a +`(+N suppressed)` note so you know something was held back. + +Both controls default to **off**; existing destinations keep firing exactly as +before until you enable them. + ## Where To Configure It Use **Admin > Integrations > Notifications**. diff --git a/server/internal/db/db.go b/server/internal/db/db.go index 71dbbf6..79564c1 100644 --- a/server/internal/db/db.go +++ b/server/internal/db/db.go @@ -67,6 +67,7 @@ func Init(path string) (*gorm.DB, error) { &models.IncidentEntry{}, &models.SystemdUnitConfig{}, &models.NotificationDest{}, + &models.NotificationLog{}, &models.ExcludedTarget{}, &models.AuditLog{}, &models.WebhookDelivery{}, @@ -239,3 +240,40 @@ func sweepExpiredOIDCStates(ctx context.Context, database *gorm.DB) { func StartOIDCStateSweeper(ctx context.Context, database *gorm.DB) { go sweepExpiredOIDCStates(ctx, database) } + +// notificationLogRetention is longer than the largest rate-limit window (24h) +// so sliding-window counts always have their backing rows. +const notificationLogRetention = 48 * time.Hour + +// deleteOldNotificationLogs prunes notification log rows older than the +// retention horizon, while preserving pending held rows (decision = "held" with +// no flushed_at) that a deferred-digest flush still needs. +func deleteOldNotificationLogs(database *gorm.DB) { + cutoff := time.Now().Add(-notificationLogRetention) + result := database.Where( + "created_at < ? AND (decision != ? OR flushed_at IS NOT NULL)", cutoff, "held", + ).Delete(&models.NotificationLog{}) + if result.Error != nil { + log.Printf("notification log sweep error: %v", result.Error) + } +} + +func sweepOldNotificationLogs(ctx context.Context, database *gorm.DB) { + deleteOldNotificationLogs(database) + + ticker := time.NewTicker(time.Hour) + defer ticker.Stop() + + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + deleteOldNotificationLogs(database) + } + } +} + +func StartNotificationLogSweeper(ctx context.Context, database *gorm.DB) { + go sweepOldNotificationLogs(ctx, database) +} diff --git a/server/internal/db/db_test.go b/server/internal/db/db_test.go index 00caed3..1751261 100644 --- a/server/internal/db/db_test.go +++ b/server/internal/db/db_test.go @@ -305,6 +305,46 @@ func TestStartOIDCStateSweeper_DeletesExpiredStatesImmediately(t *testing.T) { assert.Equal(t, int64(1), freshCount) } +func TestStartNotificationLogSweeper_PrunesOldButKeepsPendingHeld(t *testing.T) { + database, err := db.Init(":memory:") + require.NoError(t, err) + closeDBOnCleanup(t, database) + + old := time.Now().Add(-72 * time.Hour) + flushedAt := old.Add(time.Hour) + rows := []models.NotificationLog{ + {ID: "log-old-sent", DestID: "d1", Decision: "sent", CreatedAt: old}, + {ID: "log-old-held-flushed", DestID: "d1", Decision: "held", FlushedAt: &flushedAt, CreatedAt: old}, + {ID: "log-old-held-pending", DestID: "d1", Decision: "held", CreatedAt: old}, + {ID: "log-fresh-sent", DestID: "d1", Decision: "sent", CreatedAt: time.Now()}, + } + for i := range rows { + require.NoError(t, database.Create(&rows[i]).Error) + } + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + db.StartNotificationLogSweeper(ctx, database) + + require.Eventually(t, func() bool { + var oldSent int64 + if err := database.Model(&models.NotificationLog{}).Where("id = ?", "log-old-sent").Count(&oldSent).Error; err != nil { + return false + } + return oldSent == 0 + }, time.Second, 10*time.Millisecond) + + exists := func(id string) int64 { + var n int64 + require.NoError(t, database.Model(&models.NotificationLog{}).Where("id = ?", id).Count(&n).Error) + return n + } + assert.Equal(t, int64(0), exists("log-old-sent"), "old sent row should be pruned") + assert.Equal(t, int64(0), exists("log-old-held-flushed"), "old flushed held row should be pruned") + assert.Equal(t, int64(1), exists("log-old-held-pending"), "pending held row must be preserved") + assert.Equal(t, int64(1), exists("log-fresh-sent"), "fresh row must be preserved") +} + func TestInit_FileDB_WALModeEnabled(t *testing.T) { tmp, err := os.CreateTemp("", "blackbox-wal-test-*.db") require.NoError(t, err) diff --git a/server/internal/handlers/admin_notifications.go b/server/internal/handlers/admin_notifications.go index d567e86..95d0d7c 100644 --- a/server/internal/handlers/admin_notifications.go +++ b/server/internal/handlers/admin_notifications.go @@ -5,6 +5,7 @@ import ( "errors" "net/http" "net/url" + "regexp" "strings" "blackbox/server/internal/auth" @@ -29,6 +30,40 @@ var validNotifyEvents = map[string]struct{}{ notify.EventAIReviewGenerated: {}, } +var hhmmRe = regexp.MustCompile(`^([01]\d|2[0-3]):[0-5]\d$`) + +// policyInput holds the per-destination quiet-hours and rate-limit settings +// shared by the create and update request bodies. +type policyInput struct { + QuietHoursEnabled bool `json:"quiet_hours_enabled"` + QuietHoursStart string `json:"quiet_hours_start"` + QuietHoursEnd string `json:"quiet_hours_end"` + QuietHoursMode string `json:"quiet_hours_mode"` + RateLimitEnabled bool `json:"rate_limit_enabled"` + RateLimitCount int `json:"rate_limit_count"` + RateLimitUnit string `json:"rate_limit_unit"` +} + +func validatePolicy(p policyInput) error { + if p.QuietHoursEnabled { + if !hhmmRe.MatchString(p.QuietHoursStart) || !hhmmRe.MatchString(p.QuietHoursEnd) { + return errors.New("quiet hours start/end must be HH:MM (24h)") + } + if p.QuietHoursMode != "drop" && p.QuietHoursMode != "defer" { + return errors.New("quiet hours mode must be drop or defer") + } + } + if p.RateLimitEnabled { + if p.RateLimitCount < 1 { + return errors.New("rate limit count must be at least 1") + } + if p.RateLimitUnit != "hour" && p.RateLimitUnit != "day" { + return errors.New("rate limit unit must be hour or day") + } + } + return nil +} + func ListNotificationDests(db *gorm.DB) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { if !requireAdminRequest(w, r) { @@ -58,6 +93,7 @@ func CreateNotificationDest(db *gorm.DB) http.HandlerFunc { URL string `json:"url"` Events []string `json:"events"` Enabled bool `json:"enabled"` + policyInput } if !decodeJSONBody(w, r, 16<<10, &req) { return @@ -68,6 +104,10 @@ func CreateNotificationDest(db *gorm.DB) http.HandlerFunc { writeError(w, http.StatusBadRequest, err.Error()) return } + if err := validatePolicy(req.policyInput); err != nil { + writeError(w, http.StatusBadRequest, err.Error()) + return + } eventsJSON, err := json.Marshal(events) if err != nil { @@ -76,12 +116,19 @@ func CreateNotificationDest(db *gorm.DB) http.HandlerFunc { } dest := models.NotificationDest{ - ID: ulid.Make().String(), - Name: name, - Type: destType, - URL: destURL, - Events: string(eventsJSON), - Enabled: req.Enabled, + ID: ulid.Make().String(), + Name: name, + Type: destType, + URL: destURL, + Events: string(eventsJSON), + Enabled: req.Enabled, + QuietHoursEnabled: req.QuietHoursEnabled, + QuietHoursStart: req.QuietHoursStart, + QuietHoursEnd: req.QuietHoursEnd, + QuietHoursMode: req.QuietHoursMode, + RateLimitEnabled: req.RateLimitEnabled, + RateLimitCount: req.RateLimitCount, + RateLimitUnit: req.RateLimitUnit, } if err := db.Create(&dest).Error; err != nil { writeError(w, http.StatusInternalServerError, "failed to create notification destination") @@ -113,6 +160,7 @@ func UpdateNotificationDest(db *gorm.DB) http.HandlerFunc { URL string `json:"url"` Events []string `json:"events"` Enabled bool `json:"enabled"` + policyInput } if !decodeJSONBody(w, r, 16<<10, &req) { return @@ -123,6 +171,10 @@ func UpdateNotificationDest(db *gorm.DB) http.HandlerFunc { writeError(w, http.StatusBadRequest, err.Error()) return } + if err := validatePolicy(req.policyInput); err != nil { + writeError(w, http.StatusBadRequest, err.Error()) + return + } eventsJSON, err := json.Marshal(events) if err != nil { @@ -133,11 +185,18 @@ func UpdateNotificationDest(db *gorm.DB) http.HandlerFunc { result := db.Model(&models.NotificationDest{}). Where("id = ?", id). Updates(map[string]interface{}{ - "name": name, - "type": destType, - "url": destURL, - "events": string(eventsJSON), - "enabled": req.Enabled, + "name": name, + "type": destType, + "url": destURL, + "events": string(eventsJSON), + "enabled": req.Enabled, + "quiet_hours_enabled": req.QuietHoursEnabled, + "quiet_hours_start": req.QuietHoursStart, + "quiet_hours_end": req.QuietHoursEnd, + "quiet_hours_mode": req.QuietHoursMode, + "rate_limit_enabled": req.RateLimitEnabled, + "rate_limit_count": req.RateLimitCount, + "rate_limit_unit": req.RateLimitUnit, }) if result.Error != nil { writeError(w, http.StatusInternalServerError, "failed to update notification destination") diff --git a/server/internal/handlers/admin_notifications_test.go b/server/internal/handlers/admin_notifications_test.go index bdc32b1..e5a12cd 100644 --- a/server/internal/handlers/admin_notifications_test.go +++ b/server/internal/handlers/admin_notifications_test.go @@ -256,6 +256,138 @@ func TestTestNotificationDest_Failure(t *testing.T) { assert.NotEmpty(t, resp["error"]) } +func TestValidatePolicyFields(t *testing.T) { + bad := []struct { + name string + p policyInput + }{ + {"bad start", policyInput{QuietHoursEnabled: true, QuietHoursStart: "9am", QuietHoursEnd: "07:00", QuietHoursMode: "drop"}}, + {"bad mode", policyInput{QuietHoursEnabled: true, QuietHoursStart: "22:00", QuietHoursEnd: "07:00", QuietHoursMode: "mute"}}, + {"rate count zero", policyInput{RateLimitEnabled: true, RateLimitCount: 0, RateLimitUnit: "hour"}}, + {"rate bad unit", policyInput{RateLimitEnabled: true, RateLimitCount: 3, RateLimitUnit: "week"}}, + } + for _, c := range bad { + t.Run(c.name, func(t *testing.T) { + if err := validatePolicy(c.p); err == nil { + t.Fatalf("expected error for %s", c.name) + } + }) + } + + ok := policyInput{ + QuietHoursEnabled: true, QuietHoursStart: "22:00", QuietHoursEnd: "07:00", QuietHoursMode: "defer", + RateLimitEnabled: true, RateLimitCount: 5, RateLimitUnit: "day", + } + if err := validatePolicy(ok); err != nil { + t.Fatalf("expected valid, got %v", err) + } +} + +func TestCreateNotificationDest_WithPolicy(t *testing.T) { + database := newNotificationTestDB(t) + body, err := json.Marshal(map[string]interface{}{ + "name": "Phone push", + "type": "ntfy", + "url": "https://ntfy.sh/mytopic", + "events": []string{notify.EventIncidentOpenedConfirmed}, + "enabled": true, + "quiet_hours_enabled": true, + "quiet_hours_start": "22:00", + "quiet_hours_end": "07:00", + "quiet_hours_mode": "defer", + "rate_limit_enabled": true, + "rate_limit_count": 5, + "rate_limit_unit": "hour", + }) + require.NoError(t, err) + + req := adminNotificationRequest(http.MethodPost, "/api/admin/notifications", bytes.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + + CreateNotificationDest(database)(w, req) + + require.Equal(t, http.StatusCreated, w.Code) + var dest models.NotificationDest + require.NoError(t, json.NewDecoder(w.Body).Decode(&dest)) + assert.True(t, dest.QuietHoursEnabled) + assert.Equal(t, "defer", dest.QuietHoursMode) + assert.Equal(t, "22:00", dest.QuietHoursStart) + assert.True(t, dest.RateLimitEnabled) + assert.Equal(t, 5, dest.RateLimitCount) + assert.Equal(t, "hour", dest.RateLimitUnit) +} + +func TestCreateNotificationDest_InvalidPolicy(t *testing.T) { + database := newNotificationTestDB(t) + body, err := json.Marshal(map[string]interface{}{ + "name": "Bad policy", + "type": "ntfy", + "url": "https://ntfy.sh/mytopic", + "events": []string{notify.EventIncidentOpenedConfirmed}, + "enabled": true, + "quiet_hours_enabled": true, + "quiet_hours_start": "9am", + "quiet_hours_end": "07:00", + "quiet_hours_mode": "drop", + }) + require.NoError(t, err) + + req := adminNotificationRequest(http.MethodPost, "/api/admin/notifications", bytes.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + + CreateNotificationDest(database)(w, req) + + assert.Equal(t, http.StatusBadRequest, w.Code) +} + +func TestUpdateNotificationDest_WithPolicy(t *testing.T) { + database := newNotificationTestDB(t) + require.NoError(t, database.Create(&models.NotificationDest{ + ID: "dest-pol", + Name: "Phone", + Type: "ntfy", + URL: "https://ntfy.sh/mytopic", + Events: `["incident_opened_confirmed"]`, + Enabled: true, + }).Error) + + body, err := json.Marshal(map[string]interface{}{ + "name": "Phone", + "type": "ntfy", + "url": "https://ntfy.sh/mytopic", + "events": []string{notify.EventIncidentOpenedConfirmed}, + "enabled": true, + "quiet_hours_enabled": true, + "quiet_hours_start": "23:30", + "quiet_hours_end": "06:15", + "quiet_hours_mode": "defer", + "rate_limit_enabled": true, + "rate_limit_count": 3, + "rate_limit_unit": "day", + }) + require.NoError(t, err) + + req := adminNotificationRequest(http.MethodPut, "/api/admin/notifications/dest-pol", bytes.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + req = withNotificationRouteParam(req, "id", "dest-pol") + w := httptest.NewRecorder() + + UpdateNotificationDest(database)(w, req) + + require.Equal(t, http.StatusOK, w.Code) + var dest models.NotificationDest + require.NoError(t, json.NewDecoder(w.Body).Decode(&dest)) + assert.True(t, dest.QuietHoursEnabled) + assert.Equal(t, "23:30", dest.QuietHoursStart) + assert.Equal(t, "06:15", dest.QuietHoursEnd) + assert.Equal(t, "defer", dest.QuietHoursMode) + assert.True(t, dest.RateLimitEnabled) + assert.Equal(t, 3, dest.RateLimitCount) + assert.Equal(t, "day", dest.RateLimitUnit) +} + func newNotificationTestDB(t *testing.T) *gorm.DB { t.Helper() diff --git a/server/internal/models/notification_dest.go b/server/internal/models/notification_dest.go index fb2929c..6d7c058 100644 --- a/server/internal/models/notification_dest.go +++ b/server/internal/models/notification_dest.go @@ -3,12 +3,24 @@ package models import "time" type NotificationDest struct { - ID string `gorm:"primaryKey" json:"id"` - Name string `json:"name"` - Type string `json:"type"` - URL string `json:"url"` - Events string `json:"events"` - Enabled bool `json:"enabled"` + ID string `gorm:"primaryKey" json:"id"` + Name string `json:"name"` + Type string `json:"type"` + URL string `json:"url"` + Events string `json:"events"` + Enabled bool `json:"enabled"` + + // Quiet hours (server timezone). Window may wrap midnight. + QuietHoursEnabled bool `json:"quiet_hours_enabled"` + QuietHoursStart string `json:"quiet_hours_start"` // "HH:MM" + QuietHoursEnd string `json:"quiet_hours_end"` // "HH:MM" + QuietHoursMode string `json:"quiet_hours_mode"` // "drop" | "defer" + + // Rate limit: at most RateLimitCount sends per RateLimitUnit (sliding window). + RateLimitEnabled bool `json:"rate_limit_enabled"` + RateLimitCount int `json:"rate_limit_count"` + RateLimitUnit string `json:"rate_limit_unit"` // "hour" | "day" + CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` } diff --git a/server/internal/models/notification_dest_test.go b/server/internal/models/notification_dest_test.go new file mode 100644 index 0000000..e89a890 --- /dev/null +++ b/server/internal/models/notification_dest_test.go @@ -0,0 +1,37 @@ +package models + +import ( + "testing" + + "github.com/glebarez/sqlite" + "gorm.io/gorm" +) + +func TestNotificationDestPolicyColumns(t *testing.T) { + gdb, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{}) + if err != nil { + t.Fatalf("open: %v", err) + } + if err := gdb.AutoMigrate(&NotificationDest{}); err != nil { + t.Fatalf("migrate: %v", err) + } + + in := NotificationDest{ + ID: "d1", Name: "n", Type: "ntfy", URL: "https://x/y", Events: "[]", Enabled: true, + QuietHoursEnabled: true, QuietHoursStart: "22:00", QuietHoursEnd: "07:00", QuietHoursMode: "defer", + RateLimitEnabled: true, RateLimitCount: 5, RateLimitUnit: "hour", + } + if err := gdb.Create(&in).Error; err != nil { + t.Fatalf("create: %v", err) + } + var out NotificationDest + if err := gdb.First(&out, "id = ?", "d1").Error; err != nil { + t.Fatalf("read: %v", err) + } + if !out.QuietHoursEnabled || out.QuietHoursStart != "22:00" || out.QuietHoursMode != "defer" { + t.Fatalf("quiet hours not persisted: %+v", out) + } + if !out.RateLimitEnabled || out.RateLimitCount != 5 || out.RateLimitUnit != "hour" { + t.Fatalf("rate limit not persisted: %+v", out) + } +} diff --git a/server/internal/models/notification_log.go b/server/internal/models/notification_log.go new file mode 100644 index 0000000..fde4ad2 --- /dev/null +++ b/server/internal/models/notification_log.go @@ -0,0 +1,20 @@ +package models + +import "time" + +// NotificationLog records every per-destination send decision made by the +// dispatcher. It powers sliding-window rate counting, the suppressed-count +// note, the deferred-digest hold queue, and "why was/wasn't I paged?" +// observability. +type NotificationLog struct { + ID string `gorm:"primaryKey" json:"id"` + DestID string `gorm:"index:idx_notiflog_dest_created;index:idx_notiflog_dest_decision" json:"dest_id"` + IncidentID string `json:"incident_id"` + Event string `json:"event"` + // Decision is one of: sent, held, dropped_rate, dropped_quiet, failed, digest. + Decision string `gorm:"index:idx_notiflog_dest_decision" json:"decision"` + Note string `json:"note"` + CreatedAt time.Time `gorm:"index:idx_notiflog_dest_created" json:"created_at"` + // FlushedAt is set on held rows when they are rolled into a digest. + FlushedAt *time.Time `gorm:"index:idx_notiflog_dest_decision" json:"flushed_at,omitempty"` +} diff --git a/server/internal/models/notification_log_test.go b/server/internal/models/notification_log_test.go new file mode 100644 index 0000000..0219b31 --- /dev/null +++ b/server/internal/models/notification_log_test.go @@ -0,0 +1,41 @@ +package models + +import ( + "testing" + "time" + + "github.com/glebarez/sqlite" + "gorm.io/gorm" +) + +func TestNotificationLogRoundTrip(t *testing.T) { + gdb, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{}) + if err != nil { + t.Fatalf("open: %v", err) + } + if err := gdb.AutoMigrate(&NotificationLog{}); err != nil { + t.Fatalf("migrate: %v", err) + } + + now := time.Now().UTC().Truncate(time.Second) + in := NotificationLog{ + ID: "log1", + DestID: "dest1", + IncidentID: "inc1", + Event: "incident_opened_confirmed", + Decision: "sent", + Note: "(+2 suppressed in the last hour)", + CreatedAt: now, + } + if err := gdb.Create(&in).Error; err != nil { + t.Fatalf("create: %v", err) + } + + var out NotificationLog + if err := gdb.First(&out, "id = ?", "log1").Error; err != nil { + t.Fatalf("read: %v", err) + } + if out.Decision != "sent" || out.Note != in.Note || out.FlushedAt != nil { + t.Fatalf("round-trip mismatch: %+v", out) + } +} diff --git a/server/internal/notify/digest.go b/server/internal/notify/digest.go new file mode 100644 index 0000000..291e705 --- /dev/null +++ b/server/internal/notify/digest.go @@ -0,0 +1,128 @@ +package notify + +import ( + "context" + "fmt" + "log" + "strings" + "time" + + "blackbox/server/internal/models" + "github.com/oklog/ulid/v2" + "gorm.io/gorm" +) + +const flushInterval = time.Minute + +// Flusher emits a digest of held notifications when a destination's quiet +// window ends. +type Flusher struct { + db *gorm.DB + now func() time.Time +} + +func NewFlusher(db *gorm.DB) *Flusher { + return &Flusher{db: db, now: time.Now} +} + +// Run flushes once immediately (to catch rows held across a restart) then on a +// ticker until ctx is cancelled. +func (f *Flusher) Run(ctx context.Context) { + if err := f.flushAll(ctx); err != nil { + log.Printf("notify: initial digest flush: %v", err) + } + ticker := time.NewTicker(flushInterval) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + if err := f.flushAll(ctx); err != nil { + log.Printf("notify: digest flush: %v", err) + } + } + } +} + +// flushAll sends a digest for every defer-mode destination that is currently +// outside its quiet window and has pending held rows. +func (f *Flusher) flushAll(ctx context.Context) error { + var dests []models.NotificationDest + if err := f.db.Where("enabled = ? AND quiet_hours_enabled = ? AND quiet_hours_mode = ?", true, true, "defer"). + Find(&dests).Error; err != nil { + return err + } + now := f.now() + for _, dest := range dests { + if inQuietWindow(now, dest.QuietHoursStart, dest.QuietHoursEnd) { + continue + } + if err := f.flushDest(ctx, dest, now); err != nil { + log.Printf("notify: flush dest %q: %v", dest.Name, err) + } + } + return nil +} + +func (f *Flusher) flushDest(ctx context.Context, dest models.NotificationDest, now time.Time) error { + var held []models.NotificationLog + if err := f.db.Where("dest_id = ? AND decision = ? AND flushed_at IS NULL", dest.ID, decisionHeld). + Order("created_at ASC").Find(&held).Error; err != nil { + return err + } + if len(held) == 0 { + return nil + } + + ids := make([]string, 0, len(held)) + for _, h := range held { + ids = append(ids, h.IncidentID) + } + var incidents []models.Incident + if err := f.db.Where("id IN ?", ids).Find(&incidents).Error; err != nil { + return err + } + + if err := f.sendDigest(ctx, dest, incidents); err != nil { + return err + } + + if err := f.db.Model(&models.NotificationLog{}). + Where("dest_id = ? AND decision = ? AND flushed_at IS NULL", dest.ID, decisionHeld). + Update("flushed_at", now).Error; err != nil { + return err + } + return f.db.Create(&models.NotificationLog{ + ID: ulid.Make().String(), DestID: dest.ID, Decision: decisionDigest, + Note: fmt.Sprintf("digest of %d held", len(held)), CreatedAt: now, + }).Error +} + +// sendDigest renders one rollup message and posts it via the destination's +// channel. It bypasses the rate limit (already a single message). +func (f *Flusher) sendDigest(ctx context.Context, dest models.NotificationDest, incidents []models.Incident) error { + title := fmt.Sprintf("%d notifications held during quiet hours (%s–%s)", + len(incidents), dest.QuietHoursStart, dest.QuietHoursEnd) + + var lines []string + for _, inc := range incidents { + conf := inc.Confidence + if conf == "" { + conf = "unknown" + } + lines = append(lines, fmt.Sprintf("• [%s] %s", conf, inc.Title)) + } + body := title + "\n" + strings.Join(lines, "\n") + + sendCtx, cancel := context.WithTimeout(ctx, notifyTimeout) + defer cancel() + + digestInc := models.Incident{ + ID: "digest", Title: title, Services: "[]", NodeNames: "[]", Metadata: "{}", + OpenedAt: f.now(), Confidence: "confirmed", Status: "open", + } + // Reuse the provider senders, passing the rollup as the suppressed note so + // the per-incident body stays the digest title and the lines append below. + return sendTo(sendCtx, dest, digestInc, EventIncidentOpenedConfirmed, "", body, false) +} diff --git a/server/internal/notify/digest_test.go b/server/internal/notify/digest_test.go new file mode 100644 index 0000000..2fe406d --- /dev/null +++ b/server/internal/notify/digest_test.go @@ -0,0 +1,78 @@ +package notify + +import ( + "context" + "testing" + "time" + + "blackbox/server/internal/models" +) + +func TestFlushDeferredDigest(t *testing.T) { + // 08:00 — OUTSIDE a 22:00–07:00 window, so held rows should flush. + now := time.Date(2026, 6, 2, 8, 0, 0, 0, time.UTC) + d := newTestDispatcher(t, now) + + var sentBodies int + orig := ntfySender + ntfySender = func(ctx context.Context, url string, inc models.Incident, event, incURL, note string, test bool) error { + sentBodies++ + return nil + } + defer func() { ntfySender = orig }() + + dest := models.NotificationDest{ + ID: "d1", Type: "ntfy", URL: "https://x/y", Enabled: true, + QuietHoursEnabled: true, QuietHoursStart: "22:00", QuietHoursEnd: "07:00", QuietHoursMode: "defer", + } + d.db.Create(&dest) + // Two held rows recorded overnight, plus the incidents they reference. + d.db.Create(&models.Incident{ID: "i1", Title: "DB down", Services: "[]", NodeNames: "[]", Metadata: "{}", Confidence: "confirmed"}) + d.db.Create(&models.Incident{ID: "i2", Title: "Proxy flap", Services: "[]", NodeNames: "[]", Metadata: "{}", Confidence: "suspected"}) + if err := d.logDecision(d.db, "d1", "i1", "incident_opened_confirmed", decisionHeld, "", now.Add(-3*time.Hour)); err != nil { + t.Fatalf("logDecision i1: %v", err) + } + if err := d.logDecision(d.db, "d1", "i2", "incident_opened_suspected", decisionHeld, "", now.Add(-2*time.Hour)); err != nil { + t.Fatalf("logDecision i2: %v", err) + } + + f := NewFlusher(d.db) + f.now = func() time.Time { return now } + if err := f.flushAll(context.Background()); err != nil { + t.Fatalf("flushAll: %v", err) + } + + if sentBodies != 1 { + t.Fatalf("expected exactly one digest send, got %d", sentBodies) + } + var pending int64 + d.db.Model(&models.NotificationLog{}). + Where("dest_id = ? AND decision = ? AND flushed_at IS NULL", "d1", decisionHeld).Count(&pending) + if pending != 0 { + t.Fatalf("expected held rows flushed, %d still pending", pending) + } +} + +func TestFlushSkipsInsideWindow(t *testing.T) { + // 03:00 — INSIDE the window, must not flush. + now := time.Date(2026, 6, 2, 3, 0, 0, 0, time.UTC) + d := newTestDispatcher(t, now) + dest := models.NotificationDest{ID: "d1", Type: "ntfy", URL: "https://x/y", Enabled: true, + QuietHoursEnabled: true, QuietHoursStart: "22:00", QuietHoursEnd: "07:00", QuietHoursMode: "defer"} + d.db.Create(&dest) + d.db.Create(&models.Incident{ID: "i1", Title: "x", Services: "[]", NodeNames: "[]", Metadata: "{}"}) + if err := d.logDecision(d.db, "d1", "i1", "incident_opened_confirmed", decisionHeld, "", now.Add(-1*time.Hour)); err != nil { + t.Fatalf("logDecision i1: %v", err) + } + + f := NewFlusher(d.db) + f.now = func() time.Time { return now } + if err := f.flushAll(context.Background()); err != nil { + t.Fatalf("flushAll: %v", err) + } + var pending int64 + d.db.Model(&models.NotificationLog{}).Where("decision = ? AND flushed_at IS NULL", decisionHeld).Count(&pending) + if pending != 1 { + t.Fatalf("held row should remain pending inside window, pending=%d", pending) + } +} diff --git a/server/internal/notify/discord.go b/server/internal/notify/discord.go index 087c9a6..8673945 100644 --- a/server/internal/notify/discord.go +++ b/server/internal/notify/discord.go @@ -112,8 +112,12 @@ func BuildDiscordEmbed(inc models.Incident, event string, incURL string, test bo return embed } -func sendDiscord(ctx context.Context, webhookURL string, inc models.Incident, event string, incURL string, test bool) error { - payload := discordPayload{Embeds: []DiscordEmbed{BuildDiscordEmbed(inc, event, incURL, test)}} +func sendDiscord(ctx context.Context, webhookURL string, inc models.Incident, event, incURL, note string, test bool) error { + embed := BuildDiscordEmbed(inc, event, incURL, test) + if note != "" { + embed.Fields = append(embed.Fields, discordField{Name: "Suppressed", Value: note, Inline: false}) + } + payload := discordPayload{Embeds: []DiscordEmbed{embed}} body, err := json.Marshal(payload) if err != nil { return fmt.Errorf("marshal discord payload: %w", err) diff --git a/server/internal/notify/discord_test.go b/server/internal/notify/discord_test.go index 75af78f..86106c2 100644 --- a/server/internal/notify/discord_test.go +++ b/server/internal/notify/discord_test.go @@ -115,7 +115,7 @@ func TestSendDiscord_PostsPayload(t *testing.T) { Metadata: "{}", } - err := ExportedSendDiscord(context.Background(), srv.URL, inc, EventIncidentOpenedConfirmed, "", false) + err := ExportedSendDiscord(context.Background(), srv.URL, inc, EventIncidentOpenedConfirmed, "", "", false) require.NoError(t, err) var payload map[string]any @@ -125,6 +125,35 @@ func TestSendDiscord_PostsPayload(t *testing.T) { assert.Len(t, embeds, 1) } +func TestSendDiscord_AppendsSuppressedNote(t *testing.T) { + var body []byte + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var err error + body, err = io.ReadAll(r.Body) + require.NoError(t, err) + w.WriteHeader(http.StatusNoContent) + })) + defer srv.Close() + + inc := models.Incident{ + ID: "i5", + Status: "open", + Confidence: "confirmed", + Title: "test incident", + Services: `["svc"]`, + NodeNames: `["node"]`, + OpenedAt: time.Now(), + Metadata: "{}", + } + + note := "(+2 suppressed in the last hour)" + err := ExportedSendDiscord(context.Background(), srv.URL, inc, EventIncidentOpenedConfirmed, "", note, false) + require.NoError(t, err) + + assert.Contains(t, string(body), "Suppressed") + assert.Contains(t, string(body), note) +} + func TestSendDiscord_ReturnsErrorOnNon2xx(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusUnauthorized) @@ -135,7 +164,7 @@ func TestSendDiscord_ReturnsErrorOnNon2xx(t *testing.T) { Services: `[]`, NodeNames: `[]`, Metadata: "{}", - }, EventIncidentOpenedConfirmed, "", false) + }, EventIncidentOpenedConfirmed, "", "", false) assert.Error(t, err) } diff --git a/server/internal/notify/notify.go b/server/internal/notify/notify.go index 1589741..7c2e56a 100644 --- a/server/internal/notify/notify.go +++ b/server/internal/notify/notify.go @@ -7,9 +7,11 @@ import ( "log" "net/http" "strings" + "sync" "time" "blackbox/server/internal/models" + "github.com/oklog/ulid/v2" "gorm.io/gorm" ) @@ -33,19 +35,29 @@ const ( ) var ( - discordSender func(ctx context.Context, webhookURL string, inc models.Incident, event string, incURL string, test bool) error = sendDiscord - slackSender func(ctx context.Context, webhookURL string, inc models.Incident, event string, incURL string, test bool) error = sendSlack - ntfySender func(ctx context.Context, topicURL string, inc models.Incident, event string, incURL string, test bool) error = sendNtfy + discordSender func(ctx context.Context, webhookURL string, inc models.Incident, event, incURL, note string, test bool) error = sendDiscord + slackSender func(ctx context.Context, webhookURL string, inc models.Incident, event, incURL, note string, test bool) error = sendSlack + ntfySender func(ctx context.Context, topicURL string, inc models.Incident, event, incURL, note string, test bool) error = sendNtfy ) // Dispatcher fans out incident events to enabled notification destinations. type Dispatcher struct { - db *gorm.DB + db *gorm.DB + now func() time.Time + // destLocks serializes the gate decision + rate-slot reservation per + // destination so concurrent sends cannot both pass the rate cap. + destLocks sync.Map // dest.ID -> *sync.Mutex } // NewDispatcher creates a Dispatcher backed by the given database. func NewDispatcher(db *gorm.DB) *Dispatcher { - return &Dispatcher{db: db} + return &Dispatcher{db: db, now: time.Now} +} + +// destLock returns the per-destination mutex, creating it on first use. +func (d *Dispatcher) destLock(id string) *sync.Mutex { + mu, _ := d.destLocks.LoadOrStore(id, &sync.Mutex{}) + return mu.(*sync.Mutex) } // Send loads enabled destinations, filters them by event subscription, and @@ -74,16 +86,91 @@ func (d *Dispatcher) Send(ctx context.Context, event string, inc models.Incident sendSem <- struct{}{} defer func() { <-sendSem }() - sendCtx, cancel := context.WithTimeout(context.Background(), notifyTimeout) - defer cancel() - - if err := sendTo(sendCtx, dest, inc, event, incURL, false); err != nil { - log.Printf("notify: send to %q (%s): %v", dest.Name, dest.Type, err) - } + d.evaluateAndSend(dest, inc, event, incURL) }() } } +// evaluateAndSend gates a single destination, records the decision, and sends +// when allowed. Errors are logged, never returned (fire-and-forget). +func (d *Dispatcher) evaluateAndSend(dest models.NotificationDest, inc models.Incident, event, incURL string) { + // Gate the destination and, for an allowed send, reserve the rate slot under + // the per-destination lock. Holding the lock across decide + the sent-row + // insert closes the read-then-write race where two concurrent evaluations + // could both pass the cap. HTTP delivery happens outside the lock so a slow + // destination cannot stall others. + mu := d.destLock(dest.ID) + mu.Lock() + + decision, note, err := d.decide(d.db, dest) + if err != nil { + mu.Unlock() + // Fail open: a transient counting-query error must not silently swallow + // a notification. Deliver best-effort and record the outcome. + log.Printf("notify: decide for %q: %v (sending anyway)", dest.Name, err) + d.deliver(dest, inc, event, incURL, "") + return + } + + if decision != decisionSent { + if err := d.logDecision(d.db, dest.ID, inc.ID, event, decision, "", d.now()); err != nil { + log.Printf("notify: log %s for %q: %v", decision, dest.Name, err) + } + mu.Unlock() + return + } + + // Reserve the slot by writing the sent row now; it counts toward the cap + // immediately. If delivery fails we downgrade it to "failed" below so it no + // longer counts. + row := &models.NotificationLog{ + ID: ulid.Make().String(), + DestID: dest.ID, + IncidentID: inc.ID, + Event: event, + Decision: decisionSent, + Note: note, + CreatedAt: d.now(), + } + if err := d.db.Create(row).Error; err != nil { + mu.Unlock() + // Fail open: if the reservation write fails, rate enforcement degrades + // but the notification must still be delivered. + log.Printf("notify: reserve sent for %q: %v (sending anyway)", dest.Name, err) + d.deliver(dest, inc, event, incURL, note) + return + } + mu.Unlock() + + sendCtx, cancel := context.WithTimeout(context.Background(), notifyTimeout) + defer cancel() + + if err := sendTo(sendCtx, dest, inc, event, incURL, note, false); err != nil { + log.Printf("notify: send to %q (%s): %v", dest.Name, dest.Type, err) + if uerr := d.db.Model(&models.NotificationLog{}).Where("id = ?", row.ID). + Updates(map[string]interface{}{"decision": decisionFailed, "note": err.Error()}).Error; uerr != nil { + log.Printf("notify: mark failed for %q: %v", dest.Name, uerr) + } + } +} + +// deliver sends without rate reservation and records the outcome. Used for the +// fail-open path when the gate decision could not be computed. +func (d *Dispatcher) deliver(dest models.NotificationDest, inc models.Incident, event, incURL, note string) { + sendCtx, cancel := context.WithTimeout(context.Background(), notifyTimeout) + defer cancel() + + decision := decisionSent + logNote := note + if err := sendTo(sendCtx, dest, inc, event, incURL, note, false); err != nil { + log.Printf("notify: send to %q (%s): %v", dest.Name, dest.Type, err) + decision, logNote = decisionFailed, err.Error() + } + if err := d.logDecision(d.db, dest.ID, inc.ID, event, decision, logNote, d.now()); err != nil { + log.Printf("notify: log %s for %q: %v", decision, dest.Name, err) + } +} + // SendTest sends a synthetic payload to a single destination and returns any // delivery error directly to the caller. func (d *Dispatcher) SendTest(ctx context.Context, dest models.NotificationDest) error { @@ -95,7 +182,7 @@ func (d *Dispatcher) SendTest(ctx context.Context, dest models.NotificationDest) sendCtx, cancel := context.WithTimeout(sendCtx, notifyTimeout) defer cancel() - return sendTo(sendCtx, dest, testIncident(), EventIncidentOpenedConfirmed, "", true) + return sendTo(sendCtx, dest, testIncident(), EventIncidentOpenedConfirmed, "", "", true) } func (d *Dispatcher) incidentURL(ctx context.Context, incidentID string) string { @@ -130,14 +217,14 @@ func destWantsEvent(dest models.NotificationDest, event string) bool { return false } -func sendTo(ctx context.Context, dest models.NotificationDest, inc models.Incident, event string, incURL string, test bool) error { +func sendTo(ctx context.Context, dest models.NotificationDest, inc models.Incident, event, incURL, note string, test bool) error { switch dest.Type { case "discord": - return discordSender(ctx, dest.URL, inc, event, incURL, test) + return discordSender(ctx, dest.URL, inc, event, incURL, note, test) case "slack": - return slackSender(ctx, dest.URL, inc, event, incURL, test) + return slackSender(ctx, dest.URL, inc, event, incURL, note, test) case "ntfy": - return ntfySender(ctx, dest.URL, inc, event, incURL, test) + return ntfySender(ctx, dest.URL, inc, event, incURL, note, test) default: return fmt.Errorf("unknown destination type: %s", dest.Type) } diff --git a/server/internal/notify/notify_clock_test.go b/server/internal/notify/notify_clock_test.go new file mode 100644 index 0000000..593365f --- /dev/null +++ b/server/internal/notify/notify_clock_test.go @@ -0,0 +1,18 @@ +package notify + +import ( + "testing" + "time" +) + +func TestDispatcherClockDefaultsAndOverride(t *testing.T) { + d := NewDispatcher(nil) + if d.now == nil { + t.Fatal("default clock must be set") + } + fixed := time.Date(2026, 6, 2, 3, 0, 0, 0, time.UTC) + d.now = func() time.Time { return fixed } + if !d.now().Equal(fixed) { + t.Fatal("clock override failed") + } +} diff --git a/server/internal/notify/notify_test.go b/server/internal/notify/notify_test.go index 7c97fbd..14429d8 100644 --- a/server/internal/notify/notify_test.go +++ b/server/internal/notify/notify_test.go @@ -29,7 +29,7 @@ func TestDispatcher_Send_RoutesToEnabledDest(t *testing.T) { }).Error) var hits atomic.Int32 - restoreDiscordSender(t, func(ctx context.Context, webhookURL string, inc models.Incident, event string, incURL string, test bool) error { + restoreDiscordSender(t, func(ctx context.Context, webhookURL string, inc models.Incident, event, incURL, note string, test bool) error { hits.Add(1) return nil }) @@ -56,7 +56,7 @@ func TestDispatcher_Send_SkipsDisabledDest(t *testing.T) { }).Error) var hits atomic.Int32 - restoreDiscordSender(t, func(ctx context.Context, webhookURL string, inc models.Incident, event string, incURL string, test bool) error { + restoreDiscordSender(t, func(ctx context.Context, webhookURL string, inc models.Incident, event, incURL, note string, test bool) error { hits.Add(1) return nil }) @@ -82,7 +82,7 @@ func TestDispatcher_Send_SkipsNonMatchingEvent(t *testing.T) { }).Error) var hits atomic.Int32 - restoreDiscordSender(t, func(ctx context.Context, webhookURL string, inc models.Incident, event string, incURL string, test bool) error { + restoreDiscordSender(t, func(ctx context.Context, webhookURL string, inc models.Incident, event, incURL, note string, test bool) error { hits.Add(1) return nil }) @@ -97,7 +97,7 @@ func TestDispatcher_Send_SkipsNonMatchingEvent(t *testing.T) { func TestDispatcher_SendTest_ReturnsSenderError(t *testing.T) { database := newTestDB(t) expectedErr := errors.New("provider failed") - restoreDiscordSender(t, func(ctx context.Context, webhookURL string, inc models.Incident, event string, incURL string, test bool) error { + restoreDiscordSender(t, func(ctx context.Context, webhookURL string, inc models.Incident, event, incURL, note string, test bool) error { return expectedErr }) @@ -154,7 +154,7 @@ func newTestDB(t *testing.T) *gorm.DB { return database } -func restoreDiscordSender(t *testing.T, fn func(context.Context, string, models.Incident, string, string, bool) error) { +func restoreDiscordSender(t *testing.T, fn func(context.Context, string, models.Incident, string, string, string, bool) error) { t.Helper() previous := discordSender diff --git a/server/internal/notify/ntfy.go b/server/internal/notify/ntfy.go index 3ea7606..e23f5ae 100644 --- a/server/internal/notify/ntfy.go +++ b/server/internal/notify/ntfy.go @@ -47,8 +47,9 @@ func BuildNtfyMessage(inc models.Incident, event string, incURL string, test boo return title, body, priority, tags } -func sendNtfy(ctx context.Context, topicURL string, inc models.Incident, event string, incURL string, test bool) error { +func sendNtfy(ctx context.Context, topicURL string, inc models.Incident, event, incURL, note string, test bool) error { title, body, priority, tags := BuildNtfyMessage(inc, event, incURL, test) + body = appendNote(body, note) req, err := http.NewRequestWithContext(ctx, http.MethodPost, topicURL, bytes.NewBufferString(body)) if err != nil { diff --git a/server/internal/notify/ntfy_test.go b/server/internal/notify/ntfy_test.go index 1c504b1..9fe8cb2 100644 --- a/server/internal/notify/ntfy_test.go +++ b/server/internal/notify/ntfy_test.go @@ -119,7 +119,7 @@ func TestSendNtfy_SetsHeaders(t *testing.T) { Metadata: "{}", } - err := ExportedSendNtfy(context.Background(), srv.URL, inc, EventIncidentOpenedConfirmed, "", false) + err := ExportedSendNtfy(context.Background(), srv.URL, inc, EventIncidentOpenedConfirmed, "", "", false) require.NoError(t, err) assert.Equal(t, "nginx down", capturedTitle) @@ -138,7 +138,7 @@ func TestSendNtfy_ReturnsErrorOnNon2xx(t *testing.T) { Services: `[]`, NodeNames: `[]`, Metadata: "{}", - }, EventIncidentOpenedConfirmed, "", false) + }, EventIncidentOpenedConfirmed, "", "", false) assert.Error(t, err) } diff --git a/server/internal/notify/policy.go b/server/internal/notify/policy.go new file mode 100644 index 0000000..8aef698 --- /dev/null +++ b/server/internal/notify/policy.go @@ -0,0 +1,89 @@ +package notify + +import ( + "fmt" + "time" + + "blackbox/server/internal/models" + "github.com/oklog/ulid/v2" + "gorm.io/gorm" +) + +// logDecision inserts a NotificationLog row. createdAt is explicit so the gate +// and tests control time via the dispatcher clock. +func (d *Dispatcher) logDecision(db *gorm.DB, destID, incidentID, event, decision, note string, createdAt time.Time) error { + return db.Create(&models.NotificationLog{ + ID: ulid.Make().String(), + DestID: destID, + IncidentID: incidentID, + Event: event, + Decision: decision, + Note: note, + CreatedAt: createdAt, + }).Error +} + +// sentCountSince counts sent rows for a destination at or after `since`. +func (d *Dispatcher) sentCountSince(db *gorm.DB, destID string, since time.Time) (int64, error) { + var n int64 + err := db.Model(&models.NotificationLog{}). + Where("dest_id = ? AND decision = ? AND created_at >= ?", destID, decisionSent, since). + Count(&n).Error + return n, err +} + +// droppedRateSinceLastSent counts dropped_rate rows recorded after the most +// recent sent row for a destination (or all of them if it never sent). +func (d *Dispatcher) droppedRateSinceLastSent(db *gorm.DB, destID string) (int64, error) { + var last models.NotificationLog + err := db.Where("dest_id = ? AND decision = ?", destID, decisionSent). + Order("created_at DESC").First(&last).Error + + q := db.Model(&models.NotificationLog{}). + Where("dest_id = ? AND decision = ?", destID, decisionDroppedRate) + if err == nil { + q = q.Where("created_at > ?", last.CreatedAt) + } else if err != gorm.ErrRecordNotFound { + return 0, err + } + + var n int64 + if err := q.Count(&n).Error; err != nil { + return 0, err + } + return n, nil +} + +// decide evaluates quiet hours then the rate limit for a destination and +// returns the decision plus any suppressed-count note to append on a send. It +// performs reads only; the caller writes the resulting log row and sends. +func (d *Dispatcher) decide(db *gorm.DB, dest models.NotificationDest) (decision, note string, err error) { + now := d.now() + + if dest.QuietHoursEnabled && inQuietWindow(now, dest.QuietHoursStart, dest.QuietHoursEnd) { + if dest.QuietHoursMode == "defer" { + return decisionHeld, "", nil + } + return decisionDroppedQuiet, "", nil + } + + if dest.RateLimitEnabled && dest.RateLimitCount > 0 { + window := rateWindow(dest.RateLimitUnit) + count, err := d.sentCountSince(db, dest.ID, now.Add(-window)) + if err != nil { + return "", "", err + } + if count >= int64(dest.RateLimitCount) { + return decisionDroppedRate, "", nil + } + suppressed, err := d.droppedRateSinceLastSent(db, dest.ID) + if err != nil { + return "", "", err + } + if suppressed > 0 { + note = fmt.Sprintf("(+%d suppressed in the last %s)", suppressed, dest.RateLimitUnit) + } + } + + return decisionSent, note, nil +} diff --git a/server/internal/notify/policy_test.go b/server/internal/notify/policy_test.go new file mode 100644 index 0000000..e3c0876 --- /dev/null +++ b/server/internal/notify/policy_test.go @@ -0,0 +1,115 @@ +package notify + +import ( + "testing" + "time" + + "blackbox/server/internal/models" +) + +// newTestDispatcher builds a Dispatcher over a fully-migrated in-memory DB +// (via newTestDB, which uses a shared-cache DSN with a single connection so +// goroutine sends see the same schema) and pins its clock to `now`. +func newTestDispatcher(t *testing.T, now time.Time) *Dispatcher { + t.Helper() + d := NewDispatcher(newTestDB(t)) + d.now = func() time.Time { return now } + return d +} + +func mustLog(t *testing.T, d *Dispatcher, destID, decision string, at time.Time) { + t.Helper() + if err := d.logDecision(d.db, destID, "inc", "evt", decision, "", at); err != nil { + t.Fatalf("logDecision: %v", err) + } +} + +func TestSentCountInWindowAndSuppressed(t *testing.T) { + base := time.Date(2026, 6, 2, 12, 0, 0, 0, time.UTC) + d := newTestDispatcher(t, base) + + // 2 sends 30m and 10m ago, 1 send 2h ago (outside the hour window). + mustLog(t, d, "dest1", decisionSent, base.Add(-30*time.Minute)) + mustLog(t, d, "dest1", decisionSent, base.Add(-10*time.Minute)) + mustLog(t, d, "dest1", decisionSent, base.Add(-2*time.Hour)) + // 3 rate drops after the most recent sent. + mustLog(t, d, "dest1", decisionDroppedRate, base.Add(-5*time.Minute)) + mustLog(t, d, "dest1", decisionDroppedRate, base.Add(-4*time.Minute)) + mustLog(t, d, "dest1", decisionDroppedRate, base.Add(-3*time.Minute)) + + got, err := d.sentCountSince(d.db, "dest1", base.Add(-time.Hour)) + if err != nil { + t.Fatalf("sentCountSince: %v", err) + } + if got != 2 { + t.Fatalf("sentCountSince = %d, want 2", got) + } + + sup, err := d.droppedRateSinceLastSent(d.db, "dest1") + if err != nil { + t.Fatalf("droppedRateSinceLastSent: %v", err) + } + if sup != 3 { + t.Fatalf("droppedRateSinceLastSent = %d, want 3", sup) + } +} + +func TestDecideMatrix(t *testing.T) { + // 03:00 UTC — inside a 22:00-07:00 quiet window. + base := time.Date(2026, 6, 2, 3, 0, 0, 0, time.UTC) + + t.Run("quiet drop", func(t *testing.T) { + d := newTestDispatcher(t, base) + dest := models.NotificationDest{ID: "x", QuietHoursEnabled: true, QuietHoursStart: "22:00", QuietHoursEnd: "07:00", QuietHoursMode: "drop"} + dec, note, err := d.decide(d.db, dest) + if err != nil || dec != decisionDroppedQuiet || note != "" { + t.Fatalf("got (%q,%q,%v)", dec, note, err) + } + }) + + t.Run("quiet defer", func(t *testing.T) { + d := newTestDispatcher(t, base) + dest := models.NotificationDest{ID: "x", QuietHoursEnabled: true, QuietHoursStart: "22:00", QuietHoursEnd: "07:00", QuietHoursMode: "defer"} + dec, _, _ := d.decide(d.db, dest) + if dec != decisionHeld { + t.Fatalf("got %q want held", dec) + } + }) + + t.Run("rate limited", func(t *testing.T) { + day := time.Date(2026, 6, 2, 12, 0, 0, 0, time.UTC) + d := newTestDispatcher(t, day) + dest := models.NotificationDest{ID: "x", RateLimitEnabled: true, RateLimitCount: 2, RateLimitUnit: "hour"} + mustLog(t, d, "x", decisionSent, day.Add(-10*time.Minute)) + mustLog(t, d, "x", decisionSent, day.Add(-5*time.Minute)) + dec, _, _ := d.decide(d.db, dest) + if dec != decisionDroppedRate { + t.Fatalf("got %q want dropped_rate", dec) + } + }) + + t.Run("sent with suppressed note", func(t *testing.T) { + day := time.Date(2026, 6, 2, 12, 0, 0, 0, time.UTC) + d := newTestDispatcher(t, day) + dest := models.NotificationDest{ID: "x", RateLimitEnabled: true, RateLimitCount: 5, RateLimitUnit: "hour"} + mustLog(t, d, "x", decisionSent, day.Add(-30*time.Minute)) + mustLog(t, d, "x", decisionDroppedRate, day.Add(-2*time.Minute)) + mustLog(t, d, "x", decisionDroppedRate, day.Add(-1*time.Minute)) + dec, note, _ := d.decide(d.db, dest) + if dec != decisionSent { + t.Fatalf("got %q want sent", dec) + } + if note != "(+2 suppressed in the last hour)" { + t.Fatalf("note = %q", note) + } + }) + + t.Run("no policy sends clean", func(t *testing.T) { + d := newTestDispatcher(t, base) + dest := models.NotificationDest{ID: "x"} + dec, note, _ := d.decide(d.db, dest) + if dec != decisionSent || note != "" { + t.Fatalf("got (%q,%q)", dec, note) + } + }) +} diff --git a/server/internal/notify/send_test.go b/server/internal/notify/send_test.go new file mode 100644 index 0000000..64eb8e0 --- /dev/null +++ b/server/internal/notify/send_test.go @@ -0,0 +1,117 @@ +package notify + +import ( + "context" + "sync" + "sync/atomic" + "testing" + "time" + + "blackbox/server/internal/models" +) + +func TestSendRecordsDecisions(t *testing.T) { + // 03:00 inside a 22:00-07:00 drop window -> dropped_quiet, no HTTP send. + base := time.Date(2026, 6, 2, 3, 0, 0, 0, time.UTC) + d := newTestDispatcher(t, base) + + var mu sync.Mutex + sent := 0 + orig := ntfySender + ntfySender = func(ctx context.Context, url string, inc models.Incident, event, incURL, note string, test bool) error { + mu.Lock() + sent++ + mu.Unlock() + return nil + } + defer func() { ntfySender = orig }() + + dest := models.NotificationDest{ + ID: "d1", Type: "ntfy", URL: "https://x/y", Enabled: true, + Events: `["incident_opened_confirmed"]`, + QuietHoursEnabled: true, QuietHoursStart: "22:00", QuietHoursEnd: "07:00", QuietHoursMode: "drop", + } + if err := d.db.Create(&dest).Error; err != nil { + t.Fatalf("seed dest: %v", err) + } + + d.Send(context.Background(), EventIncidentOpenedConfirmed, models.Incident{ID: "inc1", Metadata: "{}"}) + + // Send fans out in goroutines; wait briefly for the decision row. + waitForLogRows(t, d, "d1", 1) + + var row models.NotificationLog + if err := d.db.First(&row, "dest_id = ?", "d1").Error; err != nil { + t.Fatalf("read log: %v", err) + } + if row.Decision != decisionDroppedQuiet { + t.Fatalf("decision = %q want dropped_quiet", row.Decision) + } + mu.Lock() + defer mu.Unlock() + if sent != 0 { + t.Fatalf("expected no HTTP send during quiet drop, got %d", sent) + } +} + +func TestRateLimitHardCapUnderConcurrency(t *testing.T) { + base := time.Date(2026, 6, 2, 12, 0, 0, 0, time.UTC) + d := newTestDispatcher(t, base) + + var sent int32 + orig := ntfySender + ntfySender = func(ctx context.Context, url string, inc models.Incident, event, incURL, note string, test bool) error { + atomic.AddInt32(&sent, 1) + time.Sleep(5 * time.Millisecond) // widen the race window + return nil + } + defer func() { ntfySender = orig }() + + dest := models.NotificationDest{ + ID: "d1", Type: "ntfy", URL: "https://x/y", Enabled: true, + Events: `["incident_opened_confirmed"]`, + RateLimitEnabled: true, RateLimitCount: 1, RateLimitUnit: "hour", + } + if err := d.db.Create(&dest).Error; err != nil { + t.Fatalf("seed dest: %v", err) + } + + const n = 6 + var wg sync.WaitGroup + for i := 0; i < n; i++ { + wg.Add(1) + go func() { + defer wg.Done() + d.evaluateAndSend(dest, models.Incident{ID: "inc", Metadata: "{}"}, EventIncidentOpenedConfirmed, "") + }() + } + wg.Wait() + + var sentRows, droppedRows int64 + d.db.Model(&models.NotificationLog{}).Where("dest_id = ? AND decision = ?", "d1", decisionSent).Count(&sentRows) + d.db.Model(&models.NotificationLog{}).Where("dest_id = ? AND decision = ?", "d1", decisionDroppedRate).Count(&droppedRows) + + if sentRows != 1 { + t.Fatalf("hard cap breached: %d sent rows, want 1", sentRows) + } + if droppedRows != int64(n-1) { + t.Fatalf("expected %d dropped_rate rows, got %d", n-1, droppedRows) + } + if got := atomic.LoadInt32(&sent); got != 1 { + t.Fatalf("expected 1 actual delivery, got %d", got) + } +} + +func waitForLogRows(t *testing.T, d *Dispatcher, destID string, want int64) { + t.Helper() + deadline := time.Now().Add(2 * time.Second) + for time.Now().Before(deadline) { + var n int64 + d.db.Model(&models.NotificationLog{}).Where("dest_id = ?", destID).Count(&n) + if n >= want { + return + } + time.Sleep(10 * time.Millisecond) + } + t.Fatalf("timed out waiting for %d log rows", want) +} diff --git a/server/internal/notify/slack.go b/server/internal/notify/slack.go index 1277eff..eac5d82 100644 --- a/server/internal/notify/slack.go +++ b/server/internal/notify/slack.go @@ -91,8 +91,15 @@ func BuildSlackPayload(inc models.Incident, event string, incURL string, test bo return SlackPayload{Attachments: []SlackAttachment{attachment}} } -func sendSlack(ctx context.Context, webhookURL string, inc models.Incident, event string, incURL string, test bool) error { +func sendSlack(ctx context.Context, webhookURL string, inc models.Incident, event, incURL, note string, test bool) error { payload := BuildSlackPayload(inc, event, incURL, test) + if note != "" && len(payload.Attachments) > 0 { + payload.Attachments[0].Fields = append(payload.Attachments[0].Fields, slackField{ + Title: "Suppressed", + Value: note, + Short: false, + }) + } body, err := json.Marshal(payload) if err != nil { return fmt.Errorf("marshal slack payload: %w", err) diff --git a/server/internal/notify/slack_test.go b/server/internal/notify/slack_test.go index a803af2..8da87d6 100644 --- a/server/internal/notify/slack_test.go +++ b/server/internal/notify/slack_test.go @@ -96,7 +96,7 @@ func TestSendSlack_PostsPayload(t *testing.T) { NodeNames: `["node"]`, OpenedAt: time.Now(), Metadata: "{}", - }, EventIncidentOpenedConfirmed, "", false) + }, EventIncidentOpenedConfirmed, "", "", false) require.NoError(t, err) var payload map[string]any @@ -115,7 +115,7 @@ func TestSendSlack_ReturnsErrorOnNon2xx(t *testing.T) { Services: `[]`, NodeNames: `[]`, Metadata: "{}", - }, EventIncidentOpenedConfirmed, "", false) + }, EventIncidentOpenedConfirmed, "", "", false) assert.Error(t, err) } diff --git a/server/internal/notify/window.go b/server/internal/notify/window.go new file mode 100644 index 0000000..c9cd517 --- /dev/null +++ b/server/internal/notify/window.go @@ -0,0 +1,71 @@ +package notify + +import ( + "strconv" + "strings" + "time" +) + +// Decision values recorded in NotificationLog.Decision. +const ( + decisionSent = "sent" + decisionHeld = "held" + decisionDroppedRate = "dropped_rate" + decisionDroppedQuiet = "dropped_quiet" + decisionFailed = "failed" + decisionDigest = "digest" +) + +// parseHHMM converts "HH:MM" (24h) to minutes-since-midnight. ok is false on +// any malformed input. +func parseHHMM(s string) (int, bool) { + parts := strings.Split(strings.TrimSpace(s), ":") + if len(parts) != 2 { + return 0, false + } + h, err1 := strconv.Atoi(parts[0]) + m, err2 := strconv.Atoi(parts[1]) + if err1 != nil || err2 != nil || h < 0 || h > 23 || m < 0 || m > 59 { + return 0, false + } + return h*60 + m, true +} + +// inWindowMinutes reports whether nowMin (minutes-since-midnight) falls in +// [start, end). A window where start > end wraps past midnight. A zero-length +// or malformed window is never "in". +func inWindowMinutes(nowMin int, start, end string) bool { + s, ok1 := parseHHMM(start) + e, ok2 := parseHHMM(end) + if !ok1 || !ok2 || s == e { + return false + } + if s < e { + return nowMin >= s && nowMin < e + } + return nowMin >= s || nowMin < e +} + +// inQuietWindow evaluates the window for a wall-clock time in its location. +func inQuietWindow(now time.Time, start, end string) bool { + return inWindowMinutes(now.Hour()*60+now.Minute(), start, end) +} + +// rateWindow maps a unit string to its sliding-window duration. +func rateWindow(unit string) time.Duration { + if unit == "day" { + return 24 * time.Hour + } + return time.Hour +} + +// appendNote appends a non-empty note to a message body on its own paragraph. +func appendNote(body, note string) string { + if note == "" { + return body + } + if body == "" { + return note + } + return body + "\n\n" + note +} diff --git a/server/internal/notify/window_test.go b/server/internal/notify/window_test.go new file mode 100644 index 0000000..867e6e5 --- /dev/null +++ b/server/internal/notify/window_test.go @@ -0,0 +1,50 @@ +package notify + +import "testing" + +func TestInWindow(t *testing.T) { + cases := []struct { + name string + now, start, end string + want bool + }{ + {"same-day inside", "10:30", "09:00", "17:00", true}, + {"same-day before", "08:59", "09:00", "17:00", false}, + {"same-day at start (inclusive)", "09:00", "09:00", "17:00", true}, + {"same-day at end (exclusive)", "17:00", "09:00", "17:00", false}, + {"wrap inside after midnight", "02:00", "22:00", "07:00", true}, + {"wrap inside before midnight", "23:30", "22:00", "07:00", true}, + {"wrap outside", "12:00", "22:00", "07:00", false}, + {"wrap at end (exclusive)", "07:00", "22:00", "07:00", false}, + {"zero-length", "10:00", "10:00", "10:00", false}, + {"bad format", "10:00", "9am", "5pm", false}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + now := mustMinutes(t, c.now) + if got := inWindowMinutes(now, c.start, c.end); got != c.want { + t.Fatalf("inWindowMinutes(%s,%s,%s)=%v want %v", c.now, c.start, c.end, got, c.want) + } + }) + } +} + +func mustMinutes(t *testing.T, hhmm string) int { + m, ok := parseHHMM(hhmm) + if !ok { + t.Fatalf("parseHHMM(%q) failed", hhmm) + } + return m +} + +func TestAppendNote(t *testing.T) { + if got := appendNote("body", ""); got != "body" { + t.Fatalf("empty note: %q", got) + } + if got := appendNote("body", "(+2 suppressed in the last hour)"); got != "body\n\n(+2 suppressed in the last hour)" { + t.Fatalf("with note: %q", got) + } + if got := appendNote("", "(+1 suppressed in the last day)"); got != "(+1 suppressed in the last day)" { + t.Fatalf("empty body: %q", got) + } +} diff --git a/server/main.go b/server/main.go index 8d6670d..2eb5486 100644 --- a/server/main.go +++ b/server/main.go @@ -105,8 +105,11 @@ func main() { restoreMCPState(database, mcpMgr) db.StartOIDCStateSweeper(rootCtx, database) + db.StartNotificationLogSweeper(rootCtx, database) eventHub := hub.New() notifier := notify.NewDispatcher(database) + digestFlusher := notify.NewFlusher(database) + go digestFlusher.Run(rootCtx) handlers.StartNodeStatusMonitor(rootCtx, database, eventHub, 0) incidentCh := incidents.NewChannel() incidentMgr := incidents.NewManager(database, eventHub, notifier) diff --git a/web/src/api/client.ts b/web/src/api/client.ts index a1321e4..ab2f917 100644 --- a/web/src/api/client.ts +++ b/web/src/api/client.ts @@ -619,7 +619,17 @@ function normalizeIncidentEntryLink(value: unknown): IncidentEntryLink | null { } } -export interface NotificationDest { +export interface NotificationPolicy { + quiet_hours_enabled: boolean + quiet_hours_start: string + quiet_hours_end: string + quiet_hours_mode: 'drop' | 'defer' + rate_limit_enabled: boolean + rate_limit_count: number + rate_limit_unit: 'hour' | 'day' +} + +export interface NotificationDest extends NotificationPolicy { id: string name: string type: 'discord' | 'slack' | 'ntfy' @@ -630,7 +640,7 @@ export interface NotificationDest { updated_at: string } -export interface NotificationDestInput { +export interface NotificationDestInput extends NotificationPolicy { name: string type: 'discord' | 'slack' | 'ntfy' url: string @@ -731,6 +741,10 @@ function normalizeNotificationDest(data: Record): NotificationD destType = 'discord' } + const quietMode = data.quiet_hours_mode === 'defer' ? 'defer' : 'drop' + const rateUnit = data.rate_limit_unit === 'day' ? 'day' : 'hour' + const rateCount = typeof data.rate_limit_count === 'number' && data.rate_limit_count >= 1 ? data.rate_limit_count : 1 + return { id: String(data.id ?? ''), name: String(data.name ?? ''), @@ -738,6 +752,13 @@ function normalizeNotificationDest(data: Record): NotificationD url: String(data.url ?? ''), events, enabled: data.enabled === true, + quiet_hours_enabled: data.quiet_hours_enabled === true, + quiet_hours_start: String(data.quiet_hours_start ?? ''), + quiet_hours_end: String(data.quiet_hours_end ?? ''), + quiet_hours_mode: quietMode, + rate_limit_enabled: data.rate_limit_enabled === true, + rate_limit_count: rateCount, + rate_limit_unit: rateUnit, created_at: String(data.created_at ?? ''), updated_at: String(data.updated_at ?? ''), } diff --git a/web/src/pages/AdminPage.tsx b/web/src/pages/AdminPage.tsx index aed664d..5b9d7c5 100644 --- a/web/src/pages/AdminPage.tsx +++ b/web/src/pages/AdminPage.tsx @@ -32,6 +32,7 @@ import { } from '../api/client' import type { AISettingsInput, AdminUser, AuditLogPage, MCPSettingsInput, Node, NotificationDest, NotificationDestInput, OIDCProviderConfig, WebhookDeliveryPage } from '../api/client' import { readErrorMessage } from '../api/errorUtils' +import { validatePolicyForm } from './notificationPolicy' import { useMediaQuery } from '../hooks/useMediaQuery' import { useSession } from '../session' import PageHeader from '../components/PageHeader' @@ -138,9 +139,17 @@ function emptyNotificationDestForm(): NotificationDestInput { url: '', events: [], enabled: true, + quiet_hours_enabled: false, + quiet_hours_start: '22:00', + quiet_hours_end: '07:00', + quiet_hours_mode: 'drop', + rate_limit_enabled: false, + rate_limit_count: 5, + rate_limit_unit: 'hour', } } + function oidcCallbackURL(providerID: string): string { const trimmed = providerID.trim() if (!trimmed) return '' @@ -446,6 +455,11 @@ export default function AdminPage() {
{ e.preventDefault() + const policyError = validatePolicyForm(notificationForm) + if (policyError) { + setNotificationSaveError(policyError) + return + } setNotificationSaving(true) setNotificationSaveError(null) try { @@ -559,6 +573,81 @@ export default function AdminPage() { /> ENABLED + +
+ + {notificationForm.quiet_hours_enabled && ( +
+ + + +
+ )} +
+ +
+ + {notificationForm.rate_limit_enabled && ( +
+ + +
+ )} +
@@ -698,6 +787,13 @@ export default function AdminPage() { url: dest.url, events: [...dest.events], enabled: dest.enabled, + quiet_hours_enabled: dest.quiet_hours_enabled, + quiet_hours_start: dest.quiet_hours_start || '22:00', + quiet_hours_end: dest.quiet_hours_end || '07:00', + quiet_hours_mode: dest.quiet_hours_mode, + rate_limit_enabled: dest.rate_limit_enabled, + rate_limit_count: dest.rate_limit_count || 5, + rate_limit_unit: dest.rate_limit_unit, }) setNotificationFormOpen(true) setNotificationEditingId(dest.id) diff --git a/web/src/pages/notificationPolicy.ts b/web/src/pages/notificationPolicy.ts new file mode 100644 index 0000000..a32e9eb --- /dev/null +++ b/web/src/pages/notificationPolicy.ts @@ -0,0 +1,26 @@ +import type { NotificationPolicy } from '../api/client' + +const HHMM_RE = /^([01]\d|2[0-3]):[0-5]\d$/ + +// validatePolicyForm mirrors the server-side validatePolicy rules, returning an +// error message or null when the policy is acceptable. Lives in its own pure +// module (no JSX) so it can be unit-tested under the Node test runner. +export function validatePolicyForm(p: NotificationPolicy): string | null { + if (p.quiet_hours_enabled) { + if (!HHMM_RE.test(p.quiet_hours_start) || !HHMM_RE.test(p.quiet_hours_end)) { + return 'Quiet hours start/end must be HH:MM (24h)' + } + if (p.quiet_hours_mode !== 'drop' && p.quiet_hours_mode !== 'defer') { + return 'Quiet hours mode must be drop or defer' + } + } + if (p.rate_limit_enabled) { + if (!Number.isFinite(p.rate_limit_count) || p.rate_limit_count < 1) { + return 'Rate limit count must be at least 1' + } + if (p.rate_limit_unit !== 'hour' && p.rate_limit_unit !== 'day') { + return 'Rate limit unit must be hour or day' + } + } + return null +} diff --git a/web/tests/admin-notifications-policy.test.ts b/web/tests/admin-notifications-policy.test.ts new file mode 100644 index 0000000..48747b4 --- /dev/null +++ b/web/tests/admin-notifications-policy.test.ts @@ -0,0 +1,52 @@ +import test from 'node:test' +import assert from 'node:assert/strict' + +import { validatePolicyForm } from '../src/pages/notificationPolicy.ts' + +test('rejects quiet hours enabled without valid times', () => { + assert.ok(validatePolicyForm({ + quiet_hours_enabled: true, + quiet_hours_start: '9am', + quiet_hours_end: '07:00', + quiet_hours_mode: 'drop', + rate_limit_enabled: false, + rate_limit_count: 0, + rate_limit_unit: 'hour', + })) +}) + +test('rejects rate limit count below 1', () => { + assert.ok(validatePolicyForm({ + quiet_hours_enabled: false, + quiet_hours_start: '22:00', + quiet_hours_end: '07:00', + quiet_hours_mode: 'drop', + rate_limit_enabled: true, + rate_limit_count: 0, + rate_limit_unit: 'hour', + })) +}) + +test('accepts a valid policy', () => { + assert.equal(validatePolicyForm({ + quiet_hours_enabled: true, + quiet_hours_start: '22:00', + quiet_hours_end: '07:00', + quiet_hours_mode: 'defer', + rate_limit_enabled: true, + rate_limit_count: 5, + rate_limit_unit: 'day', + }), null) +}) + +test('accepts all-disabled policy', () => { + assert.equal(validatePolicyForm({ + quiet_hours_enabled: false, + quiet_hours_start: '', + quiet_hours_end: '', + quiet_hours_mode: 'drop', + rate_limit_enabled: false, + rate_limit_count: 0, + rate_limit_unit: 'hour', + }), null) +})