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.

Thread alert emails with their resolved notifications

rcourtman175309b8f770
diff --git a/docs/release-control/v6/internal/subsystems/notifications.md b/docs/release-control/v6/internal/subsystems/notifications.md
index ef3637d3a8..944f0a19d5 100644
--- a/docs/release-control/v6/internal/subsystems/notifications.md
+++ b/docs/release-control/v6/internal/subsystems/notifications.md
@@ -177,6 +177,17 @@ cannot treat raw config strings as header fragments or `RCPT TO` input.
That same SMTP boundary also owns MIME-safe body construction. Text and HTML
payloads must be emitted through canonical multipart writers with encoded body
parts instead of being concatenated directly into handcrafted message bodies.
+That same SMTP boundary also owns email threading identity. An email that
+covers exactly one alert occurrence must carry In-Reply-To and References
+headers set to a deterministic incident thread ID derived from the alert ID
+plus firing start time, so mail clients thread the firing, re-notification,
+and resolved messages of one incident together. The per-send Message-ID must
+stay unique: re-notified incidents emit multiple emails, and providers that
+de-duplicate on Message-ID would silently drop repeats, so incident identity
+may ride only in the threading headers. Grouped emails covering multiple
+alerts must not carry a group-level thread identity, because firing and
+resolved batches are not guaranteed to contain the same alert set and a
+group-level reference would attach messages to the wrong thread.
Scheduled report delivery uses that same enhanced email boundary. Report
attachments must be emitted as MIME attachment parts by
`internal/notifications/email_enhanced.go`, and oversized-report fallback copy
diff --git a/internal/notifications/email_enhanced.go b/internal/notifications/email_enhanced.go
index d144033ac8..e4c66f1dd3 100644
--- a/internal/notifications/email_enhanced.go
+++ b/internal/notifications/email_enhanced.go
@@ -2,8 +2,10 @@ package notifications
import (
"bytes"
+ "crypto/sha256"
"crypto/tls"
"encoding/base64"
+ "encoding/hex"
"fmt"
"io"
"mime/multipart"
@@ -188,7 +190,32 @@ func writeMultipartBodyPart(writer *multipart.Writer, contentType, body string)
return nil
}
-func buildMultipartEmailMessage(addresses resolvedEmailAddresses, subject, htmlBody, textBody string, now time.Time) ([]byte, error) {
+// alertThreadMessageID derives a deterministic RFC 5322 message ID for an
+// alert incident (alert ID + firing start time). Emails about the incident
+// carry it in In-Reply-To/References so clients thread the firing,
+// re-notification, and resolved messages together. It is never used as a
+// Message-ID: re-notified incidents send multiple emails, and providers that
+// de-duplicate on Message-ID would silently drop the repeats.
+func alertThreadMessageID(alertID string, startTime time.Time) string {
+ sum := sha256.Sum256([]byte(alertID + "|" + strconv.FormatInt(startTime.UnixNano(), 10)))
+ return fmt.Sprintf("<pulse-alert-%s@pulse-monitoring>", hex.EncodeToString(sum[:12]))
+}
+
+func writeEmailThreadingHeaders(message *bytes.Buffer, threadID string) error {
+ threadID = sanitizeEmailHeaderValue(threadID)
+ if threadID == "" {
+ return nil
+ }
+ if _, err := fmt.Fprintf(message, "In-Reply-To: %s\r\n", threadID); err != nil {
+ return fmt.Errorf("write in-reply-to header: %w", err)
+ }
+ if _, err := fmt.Fprintf(message, "References: %s\r\n", threadID); err != nil {
+ return fmt.Errorf("write references header: %w", err)
+ }
+ return nil
+}
+
+func buildMultipartEmailMessage(addresses resolvedEmailAddresses, subject, htmlBody, textBody, threadID string, now time.Time) ([]byte, error) {
var message bytes.Buffer
var body bytes.Buffer
@@ -214,6 +241,9 @@ func buildMultipartEmailMessage(addresses resolvedEmailAddresses, subject, htmlB
if _, err := fmt.Fprintf(&message, "Message-ID: <%d@pulse-monitoring>\r\n", now.UnixNano()); err != nil {
return nil, fmt.Errorf("write message-id header: %w", err)
}
+ if err := writeEmailThreadingHeaders(&message, threadID); err != nil {
+ return nil, err
+ }
if _, err := message.WriteString("MIME-Version: 1.0\r\n"); err != nil {
return nil, fmt.Errorf("write mime-version header: %w", err)
}
@@ -241,9 +271,9 @@ func buildMultipartEmailMessage(addresses resolvedEmailAddresses, subject, htmlB
return message.Bytes(), nil
}
-func buildMultipartEmailMessageWithAttachments(addresses resolvedEmailAddresses, subject, htmlBody, textBody string, attachments []EmailAttachment, now time.Time) ([]byte, error) {
+func buildMultipartEmailMessageWithAttachments(addresses resolvedEmailAddresses, subject, htmlBody, textBody string, attachments []EmailAttachment, threadID string, now time.Time) ([]byte, error) {
if len(attachments) == 0 {
- return buildMultipartEmailMessage(addresses, subject, htmlBody, textBody, now)
+ return buildMultipartEmailMessage(addresses, subject, htmlBody, textBody, threadID, now)
}
var message bytes.Buffer
@@ -270,6 +300,9 @@ func buildMultipartEmailMessageWithAttachments(addresses resolvedEmailAddresses,
if _, err := fmt.Fprintf(&message, "Message-ID: <%d@pulse-monitoring>\r\n", now.UnixNano()); err != nil {
return nil, fmt.Errorf("write message-id header: %w", err)
}
+ if err := writeEmailThreadingHeaders(&message, threadID); err != nil {
+ return nil, err
+ }
if _, err := message.WriteString("MIME-Version: 1.0\r\n"); err != nil {
return nil, fmt.Errorf("write mime-version header: %w", err)
}
@@ -446,10 +479,20 @@ func NewEnhancedEmailManager(config EmailProviderConfig) *EnhancedEmailManager {
// Total attempts = MaxRetries * MaxAttempts (e.g., 3 * 3 = 9 SMTP calls for a single notification)
// This ensures delivery even during transient failures at either layer.
func (e *EnhancedEmailManager) SendEmailWithRetry(subject, htmlBody, textBody string) error {
- return e.SendEmailWithAttachments(subject, htmlBody, textBody, nil)
+ return e.sendEmailWithOptions(subject, htmlBody, textBody, nil, "")
+}
+
+// SendEmailThreaded is SendEmailWithRetry plus an incident thread ID emitted
+// as In-Reply-To/References so clients thread the incident's emails together.
+func (e *EnhancedEmailManager) SendEmailThreaded(subject, htmlBody, textBody, threadID string) error {
+ return e.sendEmailWithOptions(subject, htmlBody, textBody, nil, threadID)
}
func (e *EnhancedEmailManager) SendEmailWithAttachments(subject, htmlBody, textBody string, attachments []EmailAttachment) error {
+ return e.sendEmailWithOptions(subject, htmlBody, textBody, attachments, "")
+}
+
+func (e *EnhancedEmailManager) sendEmailWithOptions(subject, htmlBody, textBody string, attachments []EmailAttachment, threadID string) error {
var lastErr error
for attempt := 0; attempt <= e.config.MaxRetries; attempt++ {
@@ -469,7 +512,7 @@ func (e *EnhancedEmailManager) SendEmailWithAttachments(subject, htmlBody, textB
}
// Try to send
- err := e.sendEmailOnceWithAttachments(subject, htmlBody, textBody, attachments)
+ err := e.sendEmailOnceWithOptions(subject, htmlBody, textBody, attachments, threadID)
if err == nil {
if attempt > 0 {
log.Info().
@@ -516,16 +559,16 @@ func (e *EnhancedEmailManager) checkRateLimit() error {
// sendEmailOnce sends a single email.
func (e *EnhancedEmailManager) sendEmailOnce(subject, htmlBody, textBody string) error {
- return e.sendEmailOnceWithAttachments(subject, htmlBody, textBody, nil)
+ return e.sendEmailOnceWithOptions(subject, htmlBody, textBody, nil, "")
}
-func (e *EnhancedEmailManager) sendEmailOnceWithAttachments(subject, htmlBody, textBody string, attachments []EmailAttachment) error {
+func (e *EnhancedEmailManager) sendEmailOnceWithOptions(subject, htmlBody, textBody string, attachments []EmailAttachment, threadID string) error {
addresses, err := e.resolveEmailAddresses()
if err != nil {
return err
}
- msg, err := buildMultipartEmailMessageWithAttachments(addresses, subject, htmlBody, textBody, attachments, time.Now())
+ msg, err := buildMultipartEmailMessageWithAttachments(addresses, subject, htmlBody, textBody, attachments, threadID, time.Now())
if err != nil {
return err
}
diff --git a/internal/notifications/email_enhanced_test.go b/internal/notifications/email_enhanced_test.go
index 1d372d5abd..3da00f9b14 100644
--- a/internal/notifications/email_enhanced_test.go
+++ b/internal/notifications/email_enhanced_test.go
@@ -350,7 +350,7 @@ func TestBuildMultipartEmailMessage_EncodesMultipartBodies(t *testing.T) {
textBody := "Text line 1\nBcc: [email protected]\n.\n--pretend-boundary"
htmlBody := "<p>Hello</p>\nContent-Type: text/plain\n.\n--pretend-boundary"
- msg, err := buildMultipartEmailMessage(addresses, "Alert Subject", htmlBody, textBody, time.Unix(1711711711, 1234).UTC())
+ msg, err := buildMultipartEmailMessage(addresses, "Alert Subject", htmlBody, textBody, "", time.Unix(1711711711, 1234).UTC())
if err != nil {
t.Fatalf("buildMultipartEmailMessage() error = %v", err)
}
@@ -443,6 +443,7 @@ func TestBuildMultipartEmailMessageWithAttachments_EncodesReportAttachment(t *te
"<p>Attached</p>",
"Attached",
[]EmailAttachment{attachment},
+ "",
time.Unix(1711711711, 1234).UTC(),
)
if err != nil {
@@ -463,6 +464,85 @@ func TestBuildMultipartEmailMessageWithAttachments_EncodesReportAttachment(t *te
}
}
+func TestAlertThreadMessageID_DeterministicPerIncident(t *testing.T) {
+ start := time.Unix(1711711711, 1234).UTC()
+
+ first := alertThreadMessageID("alert-1", start)
+ second := alertThreadMessageID("alert-1", start)
+ if first != second {
+ t.Fatalf("same incident produced different thread IDs: %q vs %q", first, second)
+ }
+ if !strings.HasPrefix(first, "<pulse-alert-") || !strings.HasSuffix(first, "@pulse-monitoring>") {
+ t.Fatalf("thread ID %q is not an RFC 5322 message ID in the pulse-monitoring domain", first)
+ }
+
+ if other := alertThreadMessageID("alert-2", start); other == first {
+ t.Fatalf("different alert IDs produced the same thread ID %q", first)
+ }
+ if refired := alertThreadMessageID("alert-1", start.Add(time.Hour)); refired == first {
+ t.Fatalf("re-fired incident (new start time) produced the same thread ID %q", first)
+ }
+}
+
+func TestBuildMultipartEmailMessage_ThreadingHeaders(t *testing.T) {
+ addresses := resolvedEmailAddresses{
+ from: &mail.Address{Address: "[email protected]"},
+ to: []*mail.Address{{Address: "[email protected]"}},
+ }
+ threadID := alertThreadMessageID("alert-1", time.Unix(1711711711, 0).UTC())
+
+ msg, err := buildMultipartEmailMessage(addresses, "Alert", "<p>hi</p>", "hi", threadID, time.Unix(1711711711, 1234).UTC())
+ if err != nil {
+ t.Fatalf("buildMultipartEmailMessage() error = %v", err)
+ }
+ parsed, err := mail.ReadMessage(bytes.NewReader(msg))
+ if err != nil {
+ t.Fatalf("mail.ReadMessage() error = %v", err)
+ }
+ if got := parsed.Header.Get("In-Reply-To"); got != threadID {
+ t.Fatalf("In-Reply-To = %q, want %q", got, threadID)
+ }
+ if got := parsed.Header.Get("References"); got != threadID {
+ t.Fatalf("References = %q, want %q", got, threadID)
+ }
+ if got := parsed.Header.Get("Message-ID"); got == threadID {
+ t.Fatalf("Message-ID must stay unique per send, got the thread ID %q", got)
+ }
+
+ plain, err := buildMultipartEmailMessage(addresses, "Alert", "<p>hi</p>", "hi", "", time.Unix(1711711711, 1234).UTC())
+ if err != nil {
+ t.Fatalf("buildMultipartEmailMessage() error = %v", err)
+ }
+ raw := string(plain)
+ if strings.Contains(raw, "In-Reply-To:") || strings.Contains(raw, "References:") {
+ t.Fatalf("unthreaded message must not carry threading headers:\n%s", raw)
+ }
+}
+
+func TestBuildMultipartEmailMessageWithAttachments_ThreadingHeaders(t *testing.T) {
+ addresses := resolvedEmailAddresses{
+ from: &mail.Address{Address: "[email protected]"},
+ to: []*mail.Address{{Address: "[email protected]"}},
+ }
+ threadID := alertThreadMessageID("alert-1", time.Unix(1711711711, 0).UTC())
+ attachment := EmailAttachment{Filename: "report.pdf", ContentType: "application/pdf", Data: []byte("%PDF-1.7\n")}
+
+ msg, err := buildMultipartEmailMessageWithAttachments(addresses, "Alert", "<p>hi</p>", "hi", []EmailAttachment{attachment}, threadID, time.Unix(1711711711, 1234).UTC())
+ if err != nil {
+ t.Fatalf("buildMultipartEmailMessageWithAttachments() error = %v", err)
+ }
+ parsed, err := mail.ReadMessage(bytes.NewReader(msg))
+ if err != nil {
+ t.Fatalf("mail.ReadMessage() error = %v", err)
+ }
+ if got := parsed.Header.Get("In-Reply-To"); got != threadID {
+ t.Fatalf("In-Reply-To = %q, want %q", got, threadID)
+ }
+ if got := parsed.Header.Get("References"); got != threadID {
+ t.Fatalf("References = %q, want %q", got, threadID)
+ }
+}
+
func TestTestConnection_TLSRouting(t *testing.T) {
tests := []struct {
name string
diff --git a/internal/notifications/notifications.go b/internal/notifications/notifications.go
index d5872ef68e..b402e1b914 100644
--- a/internal/notifications/notifications.go
+++ b/internal/notifications/notifications.go
@@ -1482,6 +1482,17 @@ func (n *NotificationManager) logNotificationJobError(job notificationDeliveryJo
logger.Msg(message)
}
+// alertListThreadID returns the incident thread ID when the email covers
+// exactly one alert. Grouped emails don't thread: firing and resolved
+// batches rarely contain the same alert set, so a group-level reference
+// would attach messages to the wrong thread more often than the right one.
+func alertListThreadID(alertList []*alerts.Alert) string {
+ if len(alertList) != 1 || alertList[0] == nil {
+ return ""
+ }
+ return alertThreadMessageID(alertList[0].ID, alertList[0].StartTime)
+}
+
// sendGroupedEmail sends a grouped email notification
func (n *NotificationManager) sendGroupedEmail(config EmailConfig, alertList []*alerts.Alert) error {
@@ -1492,7 +1503,7 @@ func (n *NotificationManager) sendGroupedEmail(config EmailConfig, alertList []*
subject, htmlBody, textBody := EmailTemplate(alertList, false)
// Send using HTML-aware method
- return n.sendHTMLEmailWithError(subject, htmlBody, textBody, config)
+ return n.sendThreadedHTMLEmailWithError(subject, htmlBody, textBody, alertListThreadID(alertList), config)
}
func (n *NotificationManager) sendResolvedEmail(config EmailConfig, alertList []*alerts.Alert, resolvedAt time.Time) error {
@@ -1505,7 +1516,7 @@ func (n *NotificationManager) sendResolvedEmail(config EmailConfig, alertList []
return fmt.Errorf("failed to build resolved email content")
}
- return n.sendHTMLEmailWithError(subject, htmlBody, textBody, config)
+ return n.sendThreadedHTMLEmailWithError(subject, htmlBody, textBody, alertListThreadID(alertList), config)
}
func (n *NotificationManager) sendGroupedApprise(config AppriseConfig, alertList []*alerts.Alert) error {
@@ -1870,7 +1881,7 @@ func (n *NotificationManager) sendResolvedApprise(config AppriseConfig, alertLis
// sendEmail sends an email notification
func (n *NotificationManager) sendSingleEmailWithError(alert *alerts.Alert, config EmailConfig) error {
subject, htmlBody, textBody := EmailTemplate([]*alerts.Alert{alert}, true)
- return n.sendHTMLEmailWithError(subject, htmlBody, textBody, config)
+ return n.sendThreadedHTMLEmailWithError(subject, htmlBody, textBody, alertListThreadID([]*alerts.Alert{alert}), config)
}
func (n *NotificationManager) sendEmail(alert *alerts.Alert) {
@@ -1980,6 +1991,12 @@ func (n *NotificationManager) emailDeliveryManager(config EmailConfig) (*Enhance
// sendHTMLEmailWithError sends an HTML email with multipart content and returns any error
func (n *NotificationManager) sendHTMLEmailWithError(subject, htmlBody, textBody string, config EmailConfig) error {
+ return n.sendThreadedHTMLEmailWithError(subject, htmlBody, textBody, "", config)
+}
+
+// sendThreadedHTMLEmailWithError is sendHTMLEmailWithError plus an optional
+// incident thread ID (see alertThreadMessageID).
+func (n *NotificationManager) sendThreadedHTMLEmailWithError(subject, htmlBody, textBody, threadID string, config EmailConfig) error {
config = normalizeEmailConfig(config)
recipients := effectiveEmailRecipients(config)
@@ -1999,7 +2016,7 @@ func (n *NotificationManager) sendHTMLEmailWithError(subject, htmlBody, textBody
Bool("startTLS", manager.config.StartTLS).
Msg("attempting to send email via SMTP with enhanced support")
- err := manager.SendEmailWithRetry(subject, htmlBody, textBody)
+ err := manager.SendEmailThreaded(subject, htmlBody, textBody, threadID)
if err != nil {
log.Error().
diff --git a/internal/notifications/notifications_test.go b/internal/notifications/notifications_test.go
index 5a41ab868c..37ba239d51 100644
--- a/internal/notifications/notifications_test.go
+++ b/internal/notifications/notifications_test.go
@@ -17,6 +17,29 @@ import (
const legacySnakeAlertIdentifierField = "alert_id"
+func TestAlertListThreadID(t *testing.T) {
+ start := time.Unix(1711711711, 0).UTC()
+ alert := &alerts.Alert{ID: "alert-1", StartTime: start}
+
+ // Firing and resolved emails for the same incident derive the same
+ // thread ID, which is what makes clients thread them together.
+ got := alertListThreadID([]*alerts.Alert{alert})
+ if want := alertThreadMessageID("alert-1", start); got != want {
+ t.Fatalf("single-alert thread ID = %q, want %q", got, want)
+ }
+
+ if got := alertListThreadID(nil); got != "" {
+ t.Fatalf("empty list thread ID = %q, want empty", got)
+ }
+ if got := alertListThreadID([]*alerts.Alert{nil}); got != "" {
+ t.Fatalf("nil alert thread ID = %q, want empty", got)
+ }
+ grouped := []*alerts.Alert{alert, {ID: "alert-2", StartTime: start}}
+ if got := alertListThreadID(grouped); got != "" {
+ t.Fatalf("grouped email thread ID = %q, want empty (groups do not thread)", got)
+ }
+}
+
func flushPending(n *NotificationManager) {
n.mu.Lock()
if n.queue != nil {