Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
651e21a
feat(notify): add NotificationLog model and migration
maxjb-xyz Jun 2, 2026
675334a
feat(notify): add quiet-hours and rate-limit columns to NotificationDest
maxjb-xyz Jun 2, 2026
7cc49be
feat(notify): add quiet-hours window logic and decision constants
maxjb-xyz Jun 2, 2026
a48719a
refactor(notify): add injectable clock to Dispatcher
maxjb-xyz Jun 2, 2026
f753bea
feat(notify): add decision logging, counting helpers, and gate
maxjb-xyz Jun 2, 2026
05c52e0
feat(notify): thread suppressed-count note into provider messages
maxjb-xyz Jun 2, 2026
ab74919
feat(notify): gate Send through quiet-hours and rate-limit policy
maxjb-xyz Jun 2, 2026
505d9ee
test(notify): use shared-cache DB in dispatcher tests for goroutine s…
maxjb-xyz Jun 2, 2026
768ae7a
feat(notify): add deferred-digest flusher for quiet hours
maxjb-xyz Jun 2, 2026
495f1d6
feat(notify): run digest flusher on server startup
maxjb-xyz Jun 2, 2026
e6ad861
feat(api): accept and validate notification policy fields
maxjb-xyz Jun 2, 2026
acfcf6d
feat(web): notification policy editor (quiet hours + rate limit)
maxjb-xyz Jun 2, 2026
2fb1f9d
docs: document notification quiet hours and rate limiting
maxjb-xyz Jun 2, 2026
65ea8b3
fix(notify): close rate-limit race and fail open on gate errors
maxjb-xyz Jun 2, 2026
5beeb5a
feat(notify): prune old notification logs with a retention sweeper
maxjb-xyz Jun 2, 2026
caf5818
test(notify): cover update-policy path, suppressed-note branch; minor…
maxjb-xyz Jun 2, 2026
6133d9d
fix(notify): fail open when rate-slot reservation write fails
maxjb-xyz Jun 3, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions docs/site/docs/integrations/notifications.md
Original file line number Diff line number Diff line change
Expand Up @@ -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**.
38 changes: 38 additions & 0 deletions server/internal/db/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -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{},
Expand Down Expand Up @@ -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)
}
40 changes: 40 additions & 0 deletions server/internal/db/db_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
81 changes: 70 additions & 11 deletions server/internal/handlers/admin_notifications.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"errors"
"net/http"
"net/url"
"regexp"
"strings"

"blackbox/server/internal/auth"
Expand All @@ -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) {
Expand Down Expand Up @@ -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
Expand All @@ -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 {
Expand All @@ -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")
Expand Down Expand Up @@ -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
Expand All @@ -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 {
Expand All @@ -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")
Expand Down
Loading
Loading