Files
notifier/internal/domain/notification.go
T
igodwin 21990f2533 fix(service,queue): eliminate data races, add retry backoff, tenant scoping
- Copy discipline for notifications: the store, the queue, workers, and
  API callers each own clones; no notification object is shared across
  goroutines (races previously flagged by -race between workers mutating
  Status/RetryCount and handlers JSON-encoding the same pointer).
- Retry progress derives from QueueMessage.Attempt so it survives
  requeues; exponential backoff (1s base, 30s cap) honors the documented
  queue.retry_backoff setting instead of hammering failing providers in a
  tight loop; shutdown abandons pending backoff waits cleanly.
- Stop() cancels a service-lifetime context so idle workers blocked in
  Dequeue exit immediately instead of waiting out their poll timeout.
- LocalQueue no longer holds its mutex while sending on the queue
  channel (Enqueue/Nack) — with a full buffer this deadlocked the entire
  worker pool, since draining requires the same mutex.
- Tenant scoping: notifications are stamped with the caller's ClientID;
  non-admin clients can only read/cancel/retry their own (cross-tenant
  access reports not-found to avoid leaking existence).
- Sentinel errors ErrNotificationNotFound/ErrNotificationAlreadySent.
- New race, backoff, and tenant-scoping test suites.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-18 09:15:57 -07:00

195 lines
6.1 KiB
Go

package domain
import (
"errors"
"time"
)
// Sentinel errors for notification lookup and state transitions.
// Match with errors.Is.
var (
ErrNotificationNotFound = errors.New("notification not found")
ErrNotificationAlreadySent = errors.New("notification already sent")
)
// Priority defines the urgency level of a notification
type Priority int
const (
PriorityLow Priority = iota
PriorityNormal
PriorityHigh
PriorityCritical
)
// NotificationType defines the channel through which to send the notification
type NotificationType string
const (
TypeEmail NotificationType = "email"
TypeSlack NotificationType = "slack"
TypeNtfy NotificationType = "ntfy"
TypeStdout NotificationType = "stdout"
)
// ContentType defines the format of the notification body
type ContentType string
const (
ContentTypeText ContentType = "text"
ContentTypeHTML ContentType = "html"
)
// NotificationStatus represents the current state of a notification
type NotificationStatus string
const (
StatusPending NotificationStatus = "pending"
StatusQueued NotificationStatus = "queued"
StatusProcessing NotificationStatus = "processing"
StatusSent NotificationStatus = "sent"
StatusFailed NotificationStatus = "failed"
StatusRetrying NotificationStatus = "retrying"
)
// Notification represents a notification message with metadata
type Notification struct {
// ID is a unique identifier for the notification
ID string `json:"id"`
// Type specifies which notifier should handle this notification
Type NotificationType `json:"type"`
// Account specifies which named account/instance to use for this notifier type (optional)
// If not specified, the default account for the notifier type will be used
Account string `json:"account,omitempty"`
// Priority determines urgency and retry behavior
Priority Priority `json:"priority"`
// Status tracks the current state of the notification
Status NotificationStatus `json:"status"`
// Subject is the notification subject/title (used for email, slack, ntfy)
Subject string `json:"subject"`
// Body is the main content of the notification
Body string `json:"body"`
// HTMLBody is an optional HTML body for email notifications. If non-empty, the email is
// sent as multipart/alternative with Body as text/plain and HTMLBody as text/html.
// Ignored for non-email notification types.
HTMLBody string `json:"html_body,omitempty"`
// ContentType specifies the format of the body (text or html).
// Deprecated: prefer setting HTMLBody alongside a plain-text Body.
ContentType ContentType `json:"content_type,omitempty"`
// Recipients contains the target addresses (email, slack channel, ntfy topic, etc.)
// For email: these are the "To" recipients
Recipients []string `json:"recipients"`
// CC contains carbon copy recipients (email only, optional)
CC []string `json:"cc,omitempty"`
// BCC contains blind carbon copy recipients (email only, optional)
BCC []string `json:"bcc,omitempty"`
// Metadata contains additional provider-specific data
Metadata map[string]interface{} `json:"metadata,omitempty"`
// CreatedAt is when the notification was created
CreatedAt time.Time `json:"created_at"`
// ScheduledFor allows delayed sending (optional)
ScheduledFor *time.Time `json:"scheduled_for,omitempty"`
// SentAt is when the notification was successfully sent
SentAt *time.Time `json:"sent_at,omitempty"`
// RetryCount tracks how many times sending has been attempted
RetryCount int `json:"retry_count"`
// MaxRetries defines the maximum retry attempts
MaxRetries int `json:"max_retries"`
// LastError stores the most recent error message if failed
LastError string `json:"last_error,omitempty"`
// ClientID identifies the API client that submitted the notification, used
// to scope visibility of notifications to the tenant that created them.
// Empty when auth is disabled.
ClientID string `json:"client_id,omitempty"`
}
// Clone returns a copy of the notification that shares no mutable state with
// the original. The service layer stores and hands out clones so that
// concurrent readers (REST/gRPC handlers) and writers (queue workers) never
// observe or race on the same underlying slices, maps, or pointer fields.
func (n *Notification) Clone() *Notification {
if n == nil {
return nil
}
clone := *n
if n.Recipients != nil {
clone.Recipients = append([]string(nil), n.Recipients...)
}
if n.CC != nil {
clone.CC = append([]string(nil), n.CC...)
}
if n.BCC != nil {
clone.BCC = append([]string(nil), n.BCC...)
}
if n.Metadata != nil {
clone.Metadata = make(map[string]interface{}, len(n.Metadata))
for k, v := range n.Metadata {
clone.Metadata[k] = v
}
}
if n.ScheduledFor != nil {
scheduledFor := *n.ScheduledFor
clone.ScheduledFor = &scheduledFor
}
if n.SentAt != nil {
sentAt := *n.SentAt
clone.SentAt = &sentAt
}
return &clone
}
// NotificationResult represents the outcome of sending a notification
type NotificationResult struct {
// NotificationID references the original notification
NotificationID string `json:"notification_id"`
// Success indicates if the notification was sent successfully
Success bool `json:"success"`
// Message provides additional context about the result
Message string `json:"message,omitempty"`
// Error contains error details if the notification failed
Error string `json:"error,omitempty"`
// SentAt is when the notification was sent
SentAt time.Time `json:"sent_at"`
// ProviderResponse contains raw response data from the notification provider
ProviderResponse map[string]interface{} `json:"provider_response,omitempty"`
}
// NotificationFilter is used for querying notifications
type NotificationFilter struct {
IDs []string `json:"ids,omitempty"`
Types []NotificationType `json:"types,omitempty"`
Statuses []NotificationStatus `json:"statuses,omitempty"`
Recipients []string `json:"recipients,omitempty"`
CreatedAfter *time.Time `json:"created_after,omitempty"`
CreatedBefore *time.Time `json:"created_before,omitempty"`
Limit int `json:"limit,omitempty"`
Offset int `json:"offset,omitempty"`
}