Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

refactor: split alert notification policy

rcourtman9d4fabf91549
diff --git a/docs/release-control/v6/internal/subsystems/alerts.md b/docs/release-control/v6/internal/subsystems/alerts.md
index 34237ada53..0e30ffbc21 100644
--- a/docs/release-control/v6/internal/subsystems/alerts.md
+++ b/docs/release-control/v6/internal/subsystems/alerts.md
@@ -54,6 +54,7 @@ operator-facing alert routing behavior for live runtime alerts.
32. `internal/alerts/config/types.go`
33. `internal/alerts/config/normalize.go`
34. `internal/alerts/config/identity.go`
+35. `internal/alerts/notification_policy.go`
## Shared Boundaries
@@ -210,6 +211,12 @@ helpers now live under `internal/alerts/config/`; the parent `alerts` package
may re-export aliases and wrappers for compatibility, but consumer packages
must keep importing `internal/alerts` unless they are explicitly taking
ownership of alert configuration internals.
+Alert notification policy now lives in `internal/alerts/notification_policy.go`.
+That file owns dispatch suppression, flapping suppression, quiet-hours
+suppression, monitor-only notification suppression, cooldown decisions, and
+per-alert rate limiting; future notification-gating changes should extend that
+policy owner rather than burying new checks inside metric or resource-specific
+evaluators.
Commercial alert handoffs now follow the same shared navigation boundary.
`frontend-modern/src/components/Alerts/InvestigateAlertButton.tsx` may resolve
the canonical `ai_alerts` destination from the shared license/commercial
diff --git a/internal/alerts/alerts.go b/internal/alerts/alerts.go
index 0ad7473172..ef74e50f02 100644
--- a/internal/alerts/alerts.go
+++ b/internal/alerts/alerts.go
@@ -575,174 +575,6 @@ func (m *Manager) addRecentlyResolvedWithPrimaryLock(resolved *ResolvedAlert) {
m.mu.Lock()
}
-// checkFlappingLocked detects alert flapping and returns true if alert should be suppressed.
-// It modifies flappingHistory, flappingActive, and suppressedUntil maps.
-// IMPORTANT: Caller MUST hold m.mu before calling this function.
-func (m *Manager) checkFlappingLocked(trackingKey string) bool {
- if !m.config.FlappingEnabled {
- return false
- }
-
- now := time.Now()
- windowDuration := time.Duration(m.config.FlappingWindowSeconds) * time.Second
-
- // Record this state change
- m.flappingHistory[trackingKey] = append(m.flappingHistory[trackingKey], now)
-
- // Remove state changes outside the window
- history := m.flappingHistory[trackingKey]
- validHistory := []time.Time{}
- for _, t := range history {
- if now.Sub(t) <= windowDuration {
- validHistory = append(validHistory, t)
- }
- }
- // Limit to max 10 entries to prevent unbounded growth
- const maxFlappingHistory = 10
- if len(validHistory) > maxFlappingHistory {
- validHistory = validHistory[len(validHistory)-maxFlappingHistory:]
- }
- m.flappingHistory[trackingKey] = validHistory
-
- // Check if we've exceeded the threshold
- if len(validHistory) >= m.config.FlappingThreshold {
- // Mark as flapping
- if !m.flappingActive[trackingKey] {
- log.Warn().
- Str("trackingKey", trackingKey).
- Int("stateChanges", len(validHistory)).
- Int("threshold", m.config.FlappingThreshold).
- Int("windowSeconds", m.config.FlappingWindowSeconds).
- Msg("Flapping detected - suppressing alert")
-
- m.flappingActive[trackingKey] = true
-
- // Set cooldown period
- cooldownDuration := time.Duration(m.config.FlappingCooldownMinutes) * time.Minute
- m.suppressedUntil[trackingKey] = now.Add(cooldownDuration)
-
- // Record suppression metric
- if recordAlertSuppressed != nil {
- recordAlertSuppressed("flapping")
- }
- }
- return true
- }
-
- return false
-}
-
-func (m *Manager) dispatchAlert(alert *Alert, async bool) bool {
- callbacks := m.getAlertCallbacks()
- if len(callbacks) == 0 || alert == nil {
- return false
- }
-
- // Don't dispatch notifications for acknowledged alerts
- if alert.Acknowledged {
- log.Debug().
- Str("alertID", alert.ID).
- Str("ackUser", alert.AckUser).
- Msg("Alert notification suppressed - already acknowledged")
- return false
- }
-
- trackingKey := canonicalTrackingKeyForAlert(alert)
-
- // Check for flapping (caller must hold m.mu)
- if m.checkFlappingLocked(trackingKey) {
- log.Debug().
- Str("alertID", alert.ID).
- Str("trackingKey", trackingKey).
- Msg("Alert suppressed due to flapping")
- return false
- }
-
- // Check activation state - only dispatch notifications if active
- if m.config.ActivationState != ActivationActive {
- log.Debug().
- Str("alertID", alert.ID).
- Str("activationState", string(m.config.ActivationState)).
- Msg("Alert notification suppressed - not activated")
- return false
- }
-
- if suppressed, reason := m.shouldSuppressNotification(alert); suppressed {
- log.Debug().
- Str("alertID", alert.ID).
- Str("type", alert.Type).
- Str("level", string(alert.Level)).
- Str("quietHoursRule", reason).
- Msg("Alert notification suppressed during quiet hours")
- return false
- }
-
- if isMonitorOnlyAlert(alert) {
- log.Info().
- Str("alertID", alert.ID).
- Str("resource", alert.ResourceName).
- Bool("monitorOnly", true).
- Msg("Monitor-only alert detected, skipping alert dispatch")
- return false
- }
-
- // Record metric for fired alert
- if recordAlertFired != nil {
- recordAlertFired(alert)
- }
-
- alertCopy := cloneAlertForOutput(alert)
- if async {
- go func(a *Alert, fns []func(*Alert)) {
- defer func() {
- if r := recover(); r != nil {
- log.Error().
- Interface("panic", r).
- Str("alertID", a.ID).
- Str("type", a.Type).
- Msg("Panic in onAlert callback")
- }
- }()
- for _, callback := range fns {
- callback(a)
- }
- }(alertCopy, callbacks)
- } else {
- // Synchronous calls also need panic recovery to prevent service crash
- func(fns []func(*Alert)) {
- defer func() {
- if r := recover(); r != nil {
- log.Error().
- Interface("panic", r).
- Str("alertID", alertCopy.ID).
- Str("type", alertCopy.Type).
- Msg("Panic in onAlert callback (synchronous)")
- }
- }()
- for _, callback := range fns {
- callback(alertCopy)
- }
- }(callbacks)
- }
- return true
-}
-
-func isMonitorOnlyAlert(alert *Alert) bool {
- if alert == nil || alert.Metadata == nil {
- return false
- }
-
- if value, ok := alert.Metadata["monitorOnly"]; ok {
- switch v := value.(type) {
- case bool:
- return v
- case string:
- return strings.EqualFold(v, "true")
- }
- }
- return false
-}
-
// UpdateConfig updates the alert configuration
func (m *Manager) UpdateConfig(config AlertConfig) {
m.mu.Lock()
@@ -1466,226 +1298,6 @@ func getThresholdForMetricFromConfig(config ThresholdConfig, metricType string)
return ensureHysteresisThreshold(th)
}
-// isInQuietHours checks if the current time is within quiet hours
-func (m *Manager) isInQuietHours() bool {
- if !m.config.Schedule.QuietHours.Enabled {
- return false
- }
-
- // Use cached location if available
- loc := m.quietHoursLoc
- if loc == nil {
- // Fallback to loading if not cached yet (shouldn't happen with UpdateConfig)
- var err error
- loc, err = time.LoadLocation(m.config.Schedule.QuietHours.Timezone)
- if err != nil {
- log.Warn().Err(err).Str("timezone", m.config.Schedule.QuietHours.Timezone).Msg("failed to load timezone, using local time")
- loc = time.Local
- }
- m.quietHoursLoc = loc
- }
-
- nowFn := m.now
- if nowFn == nil {
- nowFn = time.Now
- }
- now := nowFn().In(loc).Truncate(time.Minute)
- dayName := strings.ToLower(now.Format("Monday"))
-
- // Check if today is enabled for quiet hours
- if enabled, ok := m.config.Schedule.QuietHours.Days[dayName]; !ok || !enabled {
- return false
- }
-
- // Parse start and end times
- startTime, err := time.ParseInLocation("15:04", m.config.Schedule.QuietHours.Start, loc)
- if err != nil {
- log.Warn().Err(err).Str("start", m.config.Schedule.QuietHours.Start).Msg("failed to parse quiet hours start time")
- return false
- }
-
- endTime, err := time.ParseInLocation("15:04", m.config.Schedule.QuietHours.End, loc)
- if err != nil {
- log.Warn().Err(err).Str("end", m.config.Schedule.QuietHours.End).Msg("failed to parse quiet hours end time")
- return false
- }
-
- // Set to today's date
- startTime = time.Date(now.Year(), now.Month(), now.Day(), startTime.Hour(), startTime.Minute(), 0, 0, loc)
- endTime = time.Date(now.Year(), now.Month(), now.Day(), endTime.Hour(), endTime.Minute(), 0, 0, loc)
-
- // Quiet hours are configured with minute precision, so treat the start and
- // end minute as inclusive for user-facing schedules such as 00:00-23:59.
- endExclusive := endTime.Add(time.Minute)
-
- // Handle overnight quiet hours (e.g., 22:00 to 08:00)
- if endTime.Before(startTime) {
- if !now.Before(startTime) || now.Before(endExclusive) {
- return true
- }
- } else {
- if !now.Before(startTime) && now.Before(endExclusive) {
- return true
- }
- }
-
- return false
-}
-
-func quietHoursCategoryForAlert(alert *Alert) string {
- if alert == nil {
- return ""
- }
-
- switch alert.Type {
- case "cpu", "memory", "disk", "diskRead", "diskWrite", "networkIn", "networkOut", "temperature":
- return "performance"
- case "queue-depth", "queue-deferred", "queue-hold", "message-age",
- "docker-container-health", "docker-container-restart-loop",
- "docker-container-oom-kill", "docker-container-memory-limit":
- return "performance"
- case "usage", "disk-health", "disk-wearout", "zfs-pool-state", "zfs-pool-errors", "zfs-device", "storage-incident", "backup-storage-incident", "backup-posture-incident":
- return "storage"
- case "resource-incident":
- if metadataStringValue(alert.Metadata, "incidentCategory") == unifiedresources.IncidentCategoryAvailability {
- return "offline"
- }
- return "performance"
- case "connectivity", "offline", "powered-off", "docker-host-offline":
- return "offline"
- }
-
- if strings.HasPrefix(alert.Type, "docker-container-") {
- if alert.Type == "docker-container-state" {
- return "offline"
- }
- return "performance"
- }
-
- return ""
-}
-
-func (m *Manager) shouldSuppressNotification(alert *Alert) (bool, string) {
- if alert == nil {
- return false, ""
- }
-
- if !m.isInQuietHours() {
- return false, ""
- }
-
- if alert.Level != AlertLevelCritical {
- return true, "non-critical"
- }
-
- category := quietHoursCategoryForAlert(alert)
- switch category {
- case "performance":
- if m.config.Schedule.QuietHours.Suppress.Performance {
- return true, category
- }
- case "storage":
- if m.config.Schedule.QuietHours.Suppress.Storage {
- return true, category
- }
- case "offline":
- if m.config.Schedule.QuietHours.Suppress.Offline {
- return true, category
- }
- }
-
- return false, ""
-}
-
-// ShouldSuppressNotification checks if a notification should be suppressed
-// during quiet hours. This is used by paths that bypass dispatchAlert, such as escalation.
-func (m *Manager) ShouldSuppressNotification(alert *Alert) bool {
- if alert == nil {
- return false
- }
-
- m.mu.RLock()
- defer m.mu.RUnlock()
-
- suppressed, reason := m.shouldSuppressNotification(alert)
- if suppressed {
- log.Debug().
- Str("alertID", alert.ID).
- Str("type", alert.Type).
- Str("level", string(alert.Level)).
- Str("quietHoursRule", reason).
- Msg("Notification suppressed during quiet hours")
- }
- return suppressed
-}
-
-// ShouldSuppressResolvedNotification checks if a recovery notification should be suppressed
-// during quiet hours. Recovery notifications follow the same quiet hours rules as their
-// corresponding alerts - if the original alert would have been suppressed, so is the recovery.
-func (m *Manager) ShouldSuppressResolvedNotification(alert *Alert) bool {
- if alert == nil {
- return false
- }
-
- m.mu.RLock()
- defer m.mu.RUnlock()
-
- if alert.Acknowledged {
- log.Debug().
- Str("alertID", alert.ID).
- Str("type", alert.Type).
- Msg("Recovery notification suppressed for acknowledged alert")
- return true
- }
-
- if alert.LastNotified == nil {
- log.Debug().
- Str("alertID", alert.ID).
- Str("type", alert.Type).
- Msg("Recovery notification suppressed because firing notification was never sent")
- return true
- }
-
- suppressed, reason := m.shouldSuppressNotification(alert)
- if suppressed {
- log.Debug().
- Str("alertID", alert.ID).
- Str("type", alert.Type).
- Str("level", string(alert.Level)).
- Str("quietHoursRule", reason).
- Msg("Recovery notification suppressed during quiet hours")
- }
- return suppressed
-}
-
-// shouldNotifyAfterCooldown decides whether a re-notification can be sent for
-// an existing alert based on the configured cooldown.
-//
-// Cooldown semantics:
-// - cooldown > 0: re-notify after that many minutes have passed since the
-// last notification.
-// - cooldown <= 0: cooldown is disabled, so only the first notification for
-// an alert occurrence is allowed. The alert evaluation loop runs every
-// metric tick, so treating disabled cooldown as "always allow" causes
-// repeated notifications for the same active alert.
-//
-// Level-escalation re-notifications are handled separately at the call site.
-// Returns true if a notification should be sent, false otherwise.
-func (m *Manager) shouldNotifyAfterCooldown(alert *Alert) bool {
- if alert.LastNotified == nil {
- return true
- }
-
- if m.config.Schedule.Cooldown <= 0 {
- return false
- }
-
- cooldownDuration := time.Duration(m.config.Schedule.Cooldown) * time.Minute
- timeSinceLastNotification := time.Since(*alert.LastNotified)
-
- return timeSinceLastNotification >= cooldownDuration
-}
-
// GetConfig returns the current alert configuration
func (m *Manager) GetConfig() AlertConfig {
m.mu.RLock()
@@ -9073,37 +8685,6 @@ func (m *Manager) guestHasMonitorOnlyAlerts(guestID string) bool {
return false
}
-// checkRateLimit checks if an alert has exceeded rate limit
-func (m *Manager) checkRateLimit(alertID string) bool {
- if m.config.Schedule.MaxAlertsHour <= 0 {
- return true // No rate limit
- }
-
- now := time.Now()
- cutoff := now.Add(-1 * time.Hour)
-
- // Clean old entries and count recent alerts
- var recentAlerts []time.Time
- if times, exists := m.alertRateLimit[alertID]; exists {
- for _, t := range times {
- if t.After(cutoff) {
- recentAlerts = append(recentAlerts, t)
- }
- }
- }
-
- // Check if we've hit the limit
- if len(recentAlerts) >= m.config.Schedule.MaxAlertsHour {
- return false
- }
-
- // Add current time
- recentAlerts = append(recentAlerts, now)
- m.alertRateLimit[alertID] = recentAlerts
-
- return true
-}
-
// escalationChecker runs periodically to check for alerts that need escalation and cleanup
func (m *Manager) escalationChecker() {
ticker := time.NewTicker(1 * time.Minute)
diff --git a/internal/alerts/callback_config_coverage_test.go b/internal/alerts/callback_config_coverage_test.go
index 3f1c343d28..a619c03686 100644
--- a/internal/alerts/callback_config_coverage_test.go
+++ b/internal/alerts/callback_config_coverage_test.go
@@ -311,6 +311,43 @@ func TestSubscribeAlertCallbackUnsubscribeKeepsOtherSubscribers(t *testing.T) {
}
}
+func TestDispatchAlertSuppressesMonitorOnlyAlert(t *testing.T) {
+ m := newTestManager(t)
+
+ alert := &Alert{
+ ID: "monitor-only-alert",
+ Type: "cpu",
+ Level: AlertLevelWarning,
+ ResourceID: "vm-102",
+ ResourceName: "worker-1",
+ StartTime: time.Now().Add(-time.Minute),
+ LastSeen: time.Now(),
+ Metadata: map[string]interface{}{
+ "monitorOnly": true,
+ },
+ }
+
+ notifyDone := make(chan string, 1)
+ m.SubscribeAlertCallback(func(alert *Alert) {
+ notifyDone <- alert.ID
+ })
+
+ m.mu.Lock()
+ m.config.ActivationState = ActivationActive
+ dispatched := m.dispatchAlert(alert, false)
+ m.mu.Unlock()
+
+ if dispatched {
+ t.Fatal("expected monitor-only alert dispatch to be suppressed")
+ }
+
+ select {
+ case got := <-notifyDone:
+ t.Fatalf("monitor-only alert fired callback with alert ID %q", got)
+ case <-time.After(100 * time.Millisecond):
+ }
+}
+
func TestOnAlertHistoryRegistersCallback(t *testing.T) {
m := newTestManager(t)
diff --git a/internal/alerts/notification_policy.go b/internal/alerts/notification_policy.go
new file mode 100644
index 0000000000..3a0d770d39
--- /dev/null
+++ b/internal/alerts/notification_policy.go
@@ -0,0 +1,428 @@
+package alerts
+
+import (
+ "strings"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+ "github.com/rs/zerolog/log"
+)
+
+// checkFlappingLocked detects alert flapping and returns true if alert should be suppressed.
+// It modifies flappingHistory, flappingActive, and suppressedUntil maps.
+// IMPORTANT: Caller MUST hold m.mu before calling this function.
+func (m *Manager) checkFlappingLocked(trackingKey string) bool {
+ if !m.config.FlappingEnabled {
+ return false
+ }
+
+ now := time.Now()
+ windowDuration := time.Duration(m.config.FlappingWindowSeconds) * time.Second
+
+ // Record this state change
+ m.flappingHistory[trackingKey] = append(m.flappingHistory[trackingKey], now)
+
+ // Remove state changes outside the window
+ history := m.flappingHistory[trackingKey]
+ validHistory := []time.Time{}
+ for _, t := range history {
+ if now.Sub(t) <= windowDuration {
+ validHistory = append(validHistory, t)
+ }
+ }
+ // Limit to max 10 entries to prevent unbounded growth
+ const maxFlappingHistory = 10
+ if len(validHistory) > maxFlappingHistory {
+ validHistory = validHistory[len(validHistory)-maxFlappingHistory:]
+ }
+ m.flappingHistory[trackingKey] = validHistory
+
+ // Check if we've exceeded the threshold
+ if len(validHistory) >= m.config.FlappingThreshold {
+ // Mark as flapping
+ if !m.flappingActive[trackingKey] {
+ log.Warn().
+ Str("trackingKey", trackingKey).
+ Int("stateChanges", len(validHistory)).
+ Int("threshold", m.config.FlappingThreshold).
+ Int("windowSeconds", m.config.FlappingWindowSeconds).
+ Msg("Flapping detected - suppressing alert")
+
+ m.flappingActive[trackingKey] = true
+
+ // Set cooldown period
+ cooldownDuration := time.Duration(m.config.FlappingCooldownMinutes) * time.Minute
+ m.suppressedUntil[trackingKey] = now.Add(cooldownDuration)
+
+ // Record suppression metric
+ if recordAlertSuppressed != nil {
+ recordAlertSuppressed("flapping")
+ }
+ }
+ return true
+ }
+
+ return false
+}
+
+func (m *Manager) dispatchAlert(alert *Alert, async bool) bool {
+ callbacks := m.getAlertCallbacks()
+ if len(callbacks) == 0 || alert == nil {
+ return false
+ }
+
+ // Don't dispatch notifications for acknowledged alerts
+ if alert.Acknowledged {
+ log.Debug().
+ Str("alertID", alert.ID).
+ Str("ackUser", alert.AckUser).
+ Msg("Alert notification suppressed - already acknowledged")
+ return false
+ }
+
+ trackingKey := canonicalTrackingKeyForAlert(alert)
+
+ // Check for flapping (caller must hold m.mu)
+ if m.checkFlappingLocked(trackingKey) {
+ log.Debug().
+ Str("alertID", alert.ID).
+ Str("trackingKey", trackingKey).
+ Msg("Alert suppressed due to flapping")
+ return false
+ }
+
+ // Check activation state - only dispatch notifications if active
+ if m.config.ActivationState != ActivationActive {
+ log.Debug().
+ Str("alertID", alert.ID).
+ Str("activationState", string(m.config.ActivationState)).
+ Msg("Alert notification suppressed - not activated")
+ return false
+ }
+
+ if suppressed, reason := m.shouldSuppressNotification(alert); suppressed {
+ log.Debug().
+ Str("alertID", alert.ID).
+ Str("type", alert.Type).
+ Str("level", string(alert.Level)).
+ Str("quietHoursRule", reason).
+ Msg("Alert notification suppressed during quiet hours")
+ return false
+ }
+
+ if isMonitorOnlyAlert(alert) {
+ log.Info().
+ Str("alertID", alert.ID).
+ Str("resource", alert.ResourceName).
+ Bool("monitorOnly", true).
+ Msg("Monitor-only alert detected, skipping alert dispatch")
+ return false
+ }
+
+ // Record metric for fired alert
+ if recordAlertFired != nil {
+ recordAlertFired(alert)
+ }
+
+ alertCopy := cloneAlertForOutput(alert)
+ if async {
+ go func(a *Alert, fns []func(*Alert)) {
+ defer func() {
+ if r := recover(); r != nil {
+ log.Error().
+ Interface("panic", r).
+ Str("alertID", a.ID).
+ Str("type", a.Type).
+ Msg("Panic in onAlert callback")
+ }
+ }()
+ for _, callback := range fns {
+ callback(a)
+ }
+ }(alertCopy, callbacks)
+ } else {
+ // Synchronous calls also need panic recovery to prevent service crash
+ func(fns []func(*Alert)) {
+ defer func() {
+ if r := recover(); r != nil {
+ log.Error().
+ Interface("panic", r).
+ Str("alertID", alertCopy.ID).
+ Str("type", alertCopy.Type).
+ Msg("Panic in onAlert callback (synchronous)")
+ }
+ }()
+ for _, callback := range fns {
+ callback(alertCopy)
+ }
+ }(callbacks)
+ }
+ return true
+}
+
+func isMonitorOnlyAlert(alert *Alert) bool {
+ if alert == nil || alert.Metadata == nil {
+ return false
+ }
+
+ if value, ok := alert.Metadata["monitorOnly"]; ok {
+ switch v := value.(type) {
+ case bool:
+ return v
+ case string:
+ return strings.EqualFold(v, "true")
+ }
+ }
+ return false
+}
+
+// isInQuietHours checks if the current time is within quiet hours
+func (m *Manager) isInQuietHours() bool {
+ if !m.config.Schedule.QuietHours.Enabled {
+ return false
+ }
+
+ // Use cached location if available
+ loc := m.quietHoursLoc
+ if loc == nil {
+ // Fallback to loading if not cached yet (shouldn't happen with UpdateConfig)
+ var err error
+ loc, err = time.LoadLocation(m.config.Schedule.QuietHours.Timezone)
+ if err != nil {
+ log.Warn().Err(err).Str("timezone", m.config.Schedule.QuietHours.Timezone).Msg("failed to load timezone, using local time")
+ loc = time.Local
+ }
+ m.quietHoursLoc = loc
+ }
+
+ nowFn := m.now
+ if nowFn == nil {
+ nowFn = time.Now
+ }
+ now := nowFn().In(loc).Truncate(time.Minute)
+ dayName := strings.ToLower(now.Format("Monday"))
+
+ // Check if today is enabled for quiet hours
+ if enabled, ok := m.config.Schedule.QuietHours.Days[dayName]; !ok || !enabled {
+ return false
+ }
+
+ // Parse start and end times
+ startTime, err := time.ParseInLocation("15:04", m.config.Schedule.QuietHours.Start, loc)
+ if err != nil {
+ log.Warn().Err(err).Str("start", m.config.Schedule.QuietHours.Start).Msg("failed to parse quiet hours start time")
+ return false
+ }
+
+ endTime, err := time.ParseInLocation("15:04", m.config.Schedule.QuietHours.End, loc)
+ if err != nil {
+ log.Warn().Err(err).Str("end", m.config.Schedule.QuietHours.End).Msg("failed to parse quiet hours end time")
+ return false
+ }
+
+ // Set to today's date
+ startTime = time.Date(now.Year(), now.Month(), now.Day(), startTime.Hour(), startTime.Minute(), 0, 0, loc)
+ endTime = time.Date(now.Year(), now.Month(), now.Day(), endTime.Hour(), endTime.Minute(), 0, 0, loc)
+
+ // Quiet hours are configured with minute precision, so treat the start and
+ // end minute as inclusive for user-facing schedules such as 00:00-23:59.
+ endExclusive := endTime.Add(time.Minute)
+
+ // Handle overnight quiet hours (e.g., 22:00 to 08:00)
+ if endTime.Before(startTime) {
+ if !now.Before(startTime) || now.Before(endExclusive) {
+ return true
+ }
+ } else {
+ if !now.Before(startTime) && now.Before(endExclusive) {
+ return true
+ }
+ }
+
+ return false
+}
+
+func quietHoursCategoryForAlert(alert *Alert) string {
+ if alert == nil {
+ return ""
+ }
+
+ switch alert.Type {
+ case "cpu", "memory", "disk", "diskRead", "diskWrite", "networkIn", "networkOut", "temperature":
+ return "performance"
+ case "queue-depth", "queue-deferred", "queue-hold", "message-age",
+ "docker-container-health", "docker-container-restart-loop",
+ "docker-container-oom-kill", "docker-container-memory-limit":
+ return "performance"
+ case "usage", "disk-health", "disk-wearout", "zfs-pool-state", "zfs-pool-errors", "zfs-device", "storage-incident", "backup-storage-incident", "backup-posture-incident":
+ return "storage"
+ case "resource-incident":
+ if metadataStringValue(alert.Metadata, "incidentCategory") == unifiedresources.IncidentCategoryAvailability {
+ return "offline"
+ }
+ return "performance"
+ case "connectivity", "offline", "powered-off", "docker-host-offline":
+ return "offline"
+ }
+
+ if strings.HasPrefix(alert.Type, "docker-container-") {
+ if alert.Type == "docker-container-state" {
+ return "offline"
+ }
+ return "performance"
+ }
+
+ return ""
+}
+
+func (m *Manager) shouldSuppressNotification(alert *Alert) (bool, string) {
+ if alert == nil {
+ return false, ""
+ }
+
+ if !m.isInQuietHours() {
+ return false, ""
+ }
+
+ if alert.Level != AlertLevelCritical {
+ return true, "non-critical"
+ }
+
+ category := quietHoursCategoryForAlert(alert)
+ switch category {
+ case "performance":
+ if m.config.Schedule.QuietHours.Suppress.Performance {
+ return true, category
+ }
+ case "storage":
+ if m.config.Schedule.QuietHours.Suppress.Storage {
+ return true, category
+ }
+ case "offline":
+ if m.config.Schedule.QuietHours.Suppress.Offline {
+ return true, category
+ }
+ }
+
+ return false, ""
+}
+
+// ShouldSuppressNotification checks if a notification should be suppressed
+// during quiet hours. This is used by paths that bypass dispatchAlert, such as escalation.
+func (m *Manager) ShouldSuppressNotification(alert *Alert) bool {
+ if alert == nil {
+ return false
+ }
+
+ m.mu.RLock()
+ defer m.mu.RUnlock()
+
+ suppressed, reason := m.shouldSuppressNotification(alert)
+ if suppressed {
+ log.Debug().
+ Str("alertID", alert.ID).
+ Str("type", alert.Type).
+ Str("level", string(alert.Level)).
+ Str("quietHoursRule", reason).
+ Msg("Notification suppressed during quiet hours")
+ }
+ return suppressed
+}
+
+// ShouldSuppressResolvedNotification checks if a recovery notification should be suppressed
+// during quiet hours. Recovery notifications follow the same quiet hours rules as their
+// corresponding alerts - if the original alert would have been suppressed, so is the recovery.
+func (m *Manager) ShouldSuppressResolvedNotification(alert *Alert) bool {
+ if alert == nil {
+ return false
+ }
+
+ m.mu.RLock()
+ defer m.mu.RUnlock()
+
+ if alert.Acknowledged {
+ log.Debug().
+ Str("alertID", alert.ID).
+ Str("type", alert.Type).
+ Msg("Recovery notification suppressed for acknowledged alert")
+ return true
+ }
+
+ if alert.LastNotified == nil {
+ log.Debug().
+ Str("alertID", alert.ID).
+ Str("type", alert.Type).
+ Msg("Recovery notification suppressed because firing notification was never sent")
+ return true
+ }
+
+ suppressed, reason := m.shouldSuppressNotification(alert)
+ if suppressed {
+ log.Debug().
+ Str("alertID", alert.ID).
+ Str("type", alert.Type).
+ Str("level", string(alert.Level)).
+ Str("quietHoursRule", reason).
+ Msg("Recovery notification suppressed during quiet hours")
+ }
+ return suppressed
+}
+
+// shouldNotifyAfterCooldown decides whether a re-notification can be sent for
+// an existing alert based on the configured cooldown.
+//
+// Cooldown semantics:
+// - cooldown > 0: re-notify after that many minutes have passed since the
+// last notification.
+// - cooldown <= 0: cooldown is disabled, so only the first notification for
+// an alert occurrence is allowed. The alert evaluation loop runs every
+// metric tick, so treating disabled cooldown as "always allow" causes
+// repeated notifications for the same active alert.
+//
+// Level-escalation re-notifications are handled separately at the call site.
+// Returns true if a notification should be sent, false otherwise.
+func (m *Manager) shouldNotifyAfterCooldown(alert *Alert) bool {
+ if alert.LastNotified == nil {
+ return true
+ }
+
+ if m.config.Schedule.Cooldown <= 0 {
+ return false
+ }
+
+ cooldownDuration := time.Duration(m.config.Schedule.Cooldown) * time.Minute
+ timeSinceLastNotification := time.Since(*alert.LastNotified)
+
+ return timeSinceLastNotification >= cooldownDuration
+}
+
+// checkRateLimit checks if an alert has exceeded rate limit
+func (m *Manager) checkRateLimit(alertID string) bool {
+ if m.config.Schedule.MaxAlertsHour <= 0 {
+ return true // No rate limit
+ }
+
+ now := time.Now()
+ cutoff := now.Add(-1 * time.Hour)
+
+ // Clean old entries and count recent alerts
+ var recentAlerts []time.Time
+ if times, exists := m.alertRateLimit[alertID]; exists {
+ for _, t := range times {
+ if t.After(cutoff) {
+ recentAlerts = append(recentAlerts, t)
+ }
+ }
+ }
+
+ // Check if we've hit the limit
+ if len(recentAlerts) >= m.config.Schedule.MaxAlertsHour {
+ return false
+ }
+
+ // Add current time
+ recentAlerts = append(recentAlerts, now)
+ m.alertRateLimit[alertID] = recentAlerts
+
+ return true
+}