feat(notification): add durable mail delivery state

This commit is contained in:
shira committed 2026-10-06 10:52:47 +03:00
1 parent 391c8a6cec
commit 2db585fbff
41 files changed
+4903 -108

No files matched your search

+600
View File
@@ -0,0 +1,600 @@
package domain
import (
"errors"
"fmt"
"log/slog"
"math"
"regexp"
"time"
"github.com/google/uuid"
)
// deliveryIdempotencyKeyPrefix and the delivery ID form the key sent to the
// provider: stable for every attempt of one delivery, unique per delivery,
// and free of personal data.
const deliveryIdempotencyKeyPrefix = "delivery/"
var (
// ErrInvalidDelivery reports a delivery, a stored delivery row, or an
// attempt result that breaks a delivery rule. Errors name the rule, never
// the recipient or the content.
ErrInvalidDelivery = errors.New("invalid delivery")
// ErrDeliveryTransition reports a change that the delivery's state does
// not allow: an attempt on an accepted or rejected delivery, a quota wait
// outside pending or waiting_quota, or a new provider account after the
// first attempt.
ErrDeliveryTransition = errors.New("delivery status does not allow the transition")
// Provider names follow config.EmailProvider values; the account is an
// operator label for the provider account, never a credential.
mailProviderPattern = regexp.MustCompile(`^[a-z][a-z0-9_]{0,31}$`)
mailProviderAccountPattern = regexp.MustCompile(`^[a-z0-9][a-z0-9._-]{0,63}$`)
// A provider code is a documented snake_case error name; see
// outbound.MailProviderCode.
mailProviderCodePattern = regexp.MustCompile(`^[a-z][a-z0-9_]{0,63}$`)
// A provider message ID is printable ASCII without spaces, at most 128
// characters, as the Resend transport accepts it.
providerMessageIDPattern = regexp.MustCompile(`^[!-~]{1,128}$`)
idempotencyKeyPattern = regexp.MustCompile(`^[!-~]{1,256}$`)
)
// DeliveryStatus is the state of one delivery. The values follow the
// outcomes of the MailSender port.
//
// Transitions:
//
// pending, waiting_quota, unknown --RecordAttempt--> accepted | rejected | pending | waiting_quota | unknown
// accepted, rejected --RecordAttempt--> refused (ErrDeliveryTransition)
// pending, waiting_quota --WaitForQuota---> waiting_quota (no attempt is recorded)
//
// The attempt outcome decides the target: accepted gives accepted; a
// permanent or invalid_request rejection gives rejected; a temporary or
// rate_limited rejection gives pending again with a scheduled next attempt; a
// quota_exhausted rejection gives waiting_quota until the expected reset, or
// without a time when the reset is unknown; unknown gives unknown.
type DeliveryStatus string
const (
// DeliveryStatusPending waits for its first or next attempt at
// NextAttemptAt.
DeliveryStatusPending DeliveryStatus = "pending"
// DeliveryStatusAccepted means the provider accepted the message and
// returned its ID. It is not delivery to or reading by the recipient.
DeliveryStatusAccepted DeliveryStatus = "accepted"
// DeliveryStatusRejected means the provider refused the message for good;
// the cause must be fixed before mail of this kind can succeed.
DeliveryStatusRejected DeliveryStatus = "rejected"
// DeliveryStatusUnknown means the last attempt may have reached the
// provider without a conclusive answer (delivery_uncertain). A retry must
// reuse the idempotency key and the stored content; it is never treated
// as not sent.
DeliveryStatusUnknown DeliveryStatus = "unknown"
// DeliveryStatusWaitingQuota means the provider or local quota is used
// up. The next attempt waits for the reset at NextAttemptAt; without a
// time the reset is unknown (for example a monthly provider quota) and an
// operator or the quota rule decides.
DeliveryStatusWaitingQuota DeliveryStatus = "waiting_quota"
)
// ParseDeliveryStatus accepts a known status.
func ParseDeliveryStatus(value string) (DeliveryStatus, error) {
switch status := DeliveryStatus(value); status {
case DeliveryStatusPending, DeliveryStatusAccepted, DeliveryStatusRejected, DeliveryStatusUnknown, DeliveryStatusWaitingQuota:
return status, nil
default:
return "", invalidDelivery("domain.ParseDeliveryStatus", "unknown delivery status")
}
}
// IsTerminal reports a status that accepts no further attempt.
func (status DeliveryStatus) IsTerminal() bool {
return status == DeliveryStatusAccepted || status == DeliveryStatusRejected
}
// requiresNextAttempt reports a status that the sending worker picks up again
// by itself, so it must say when.
func (status DeliveryStatus) requiresNextAttempt() bool {
return status == DeliveryStatusPending
}
// DeliveryAttemptOutcome is what one attempt established; the values equal
// outbound.MailOutcome.
type DeliveryAttemptOutcome string
const (
DeliveryOutcomeAccepted DeliveryAttemptOutcome = "accepted"
DeliveryOutcomeRejected DeliveryAttemptOutcome = "rejected"
DeliveryOutcomeUnknown DeliveryAttemptOutcome = "unknown"
)
// DeliveryRejection is the reason of a rejected attempt; the values equal
// outbound.MailRejection.
type DeliveryRejection string
const (
DeliveryRejectionPermanent DeliveryRejection = "permanent"
DeliveryRejectionInvalidRequest DeliveryRejection = "invalid_request"
DeliveryRejectionRateLimited DeliveryRejection = "rate_limited"
DeliveryRejectionQuotaExhausted DeliveryRejection = "quota_exhausted"
DeliveryRejectionTemporary DeliveryRejection = "temporary"
)
// MailProviderAccount names the transport and the provider account that a
// delivery is pinned to, for example resend and "main". It is configuration
// identity, never a credential. A delivery keeps it for its whole life: a
// configuration change applies to new deliveries only, because providers and
// accounts share no idempotency keys.
type MailProviderAccount struct {
provider string
account string
}
// NewMailProviderAccount validates a provider name (lowercase snake_case of
// at most 32 characters) and an account label (lowercase letters, digits,
// ".", "_", or "-", at most 64 characters).
func NewMailProviderAccount(provider, account string) (MailProviderAccount, error) {
if !mailProviderPattern.MatchString(provider) {
return MailProviderAccount{}, invalidDelivery("domain.NewMailProviderAccount", "provider must be a lowercase snake_case name of at most 32 characters")
}
if !mailProviderAccountPattern.MatchString(account) {
return MailProviderAccount{}, invalidDelivery("domain.NewMailProviderAccount", "account must be a lowercase label of at most 64 characters")
}
return MailProviderAccount{provider: provider, account: account}, nil
}
func (identity MailProviderAccount) Provider() string { return identity.provider }
func (identity MailProviderAccount) Account() string { return identity.account }
func (identity MailProviderAccount) IsZero() bool { return identity.provider == "" }
// Delivery is the durable state of sending one message to one recipient: the
// recipient, the immutable rendered content, the provider account it is
// pinned to, the idempotency key, and the attempt state. The content is fixed
// at creation, so a later template version never changes what a retry sends.
//
// Delivery is a value: RecordAttempt returns the next state and leaves the
// receiver unchanged. String, GoString, Format, and LogValue show the ID,
// kind, status, and provider, never the recipient or the content.
type Delivery struct {
id uuid.UUID
sourceEventID uuid.UUID
recipientUserID uuid.UUID
recipient EmailAddress
content MailContent
providerAccount MailProviderAccount
idempotencyKey string
status DeliveryStatus
attemptCount int32
nextAttemptAt time.Time
lastAttemptAt time.Time
providerMessageID string
version int64
createdAt time.Time
updatedAt time.Time
}
// NewDeliveryInput describes a new delivery. ID must be stable for the
// logical request, so a repeated request maps to the same delivery: the
// mail request ID, or another ID the caller derives from its source record.
type NewDeliveryInput struct {
ID uuid.UUID
// SourceEventID is the domain event the delivery was created from;
// uuid.Nil for a delivery created directly in a business transaction.
SourceEventID uuid.UUID
RecipientUserID uuid.UUID
Recipient EmailAddress
Content MailContent
ProviderAccount MailProviderAccount
CreatedAt time.Time
}
// NewDelivery validates input and returns a pending delivery that is due at
// CreatedAt, with version 1 and the idempotency key "delivery/<id>".
func NewDelivery(input NewDeliveryInput) (Delivery, error) {
const location = "domain.NewDelivery"
switch {
case input.ID == uuid.Nil:
return Delivery{}, invalidDelivery(location, "delivery ID must not be nil")
case input.RecipientUserID == uuid.Nil:
return Delivery{}, invalidDelivery(location, "recipient user ID must not be nil")
case input.Recipient.IsZero():
return Delivery{}, invalidDelivery(location, "recipient address must be set")
case input.Content.IsZero():
return Delivery{}, invalidDelivery(location, "content must be built by NewMailContent")
case input.ProviderAccount.IsZero():
return Delivery{}, invalidDelivery(location, "provider account must be set")
case input.CreatedAt.IsZero():
return Delivery{}, invalidDelivery(location, "creation time must be set")
}
return Delivery{
id: input.ID,
sourceEventID: input.SourceEventID,
recipientUserID: input.RecipientUserID,
recipient: input.Recipient,
content: input.Content,
providerAccount: input.ProviderAccount,
idempotencyKey: deliveryIdempotencyKeyPrefix + input.ID.String(),
status: DeliveryStatusPending,
nextAttemptAt: input.CreatedAt,
version: 1,
createdAt: input.CreatedAt,
updatedAt: input.CreatedAt,
}, nil
}
// DeliverySnapshot is a stored delivery row. A zero time means "not set".
type DeliverySnapshot struct {
ID uuid.UUID
SourceEventID uuid.UUID
RecipientUserID uuid.UUID
RecipientAddress string
Content MailContent
ProviderAccount MailProviderAccount
IdempotencyKey string
Status DeliveryStatus
AttemptCount int32
NextAttemptAt time.Time
LastAttemptAt time.Time
ProviderMessageID string
Version int64
CreatedAt time.Time
UpdatedAt time.Time
}
// RestoreDelivery rebuilds a stored delivery and checks the invariants that
// the database also enforces. The recipient is restored without the current
// address syntax rules, so a later, stricter rule does not make stored rows
// unreadable.
func RestoreDelivery(snapshot DeliverySnapshot) (Delivery, error) {
const location = "domain.RestoreDelivery"
recipient, err := RestoreEmailAddress(snapshot.RecipientAddress, normalizeEmailKey(snapshot.RecipientAddress))
if err != nil {
return Delivery{}, fmt.Errorf("%s - restore recipient: %w", location, err)
}
if _, err := ParseDeliveryStatus(string(snapshot.Status)); err != nil {
return Delivery{}, fmt.Errorf("%s - restore status: %w", location, err)
}
switch {
case snapshot.ID == uuid.Nil || snapshot.RecipientUserID == uuid.Nil:
return Delivery{}, invalidDelivery(location, "delivery and recipient user IDs must not be nil")
case snapshot.Content.IsZero() || snapshot.ProviderAccount.IsZero():
return Delivery{}, invalidDelivery(location, "content and provider account must be set")
case !idempotencyKeyPattern.MatchString(snapshot.IdempotencyKey):
return Delivery{}, invalidDelivery(location, "idempotency key must have 1 to 256 printable ASCII characters")
case snapshot.Version <= 0 || snapshot.AttemptCount < 0:
return Delivery{}, invalidDelivery(location, "version must be positive and the attempt count not negative")
case snapshot.CreatedAt.IsZero() || snapshot.UpdatedAt.Before(snapshot.CreatedAt):
return Delivery{}, invalidDelivery(location, "update time must not precede the creation time")
case (snapshot.AttemptCount == 0) != snapshot.LastAttemptAt.IsZero():
return Delivery{}, invalidDelivery(location, "last attempt time must be set exactly when an attempt was made")
case (snapshot.Status == DeliveryStatusAccepted) != (snapshot.ProviderMessageID != ""):
return Delivery{}, invalidDelivery(location, "provider message ID must be set exactly for an accepted delivery")
}
if err := checkNextAttempt(location, snapshot.Status, snapshot.NextAttemptAt); err != nil {
return Delivery{}, err
}
return Delivery{
id: snapshot.ID,
sourceEventID: snapshot.SourceEventID,
recipientUserID: snapshot.RecipientUserID,
recipient: recipient,
content: snapshot.Content,
providerAccount: snapshot.ProviderAccount,
idempotencyKey: snapshot.IdempotencyKey,
status: snapshot.Status,
attemptCount: snapshot.AttemptCount,
nextAttemptAt: snapshot.NextAttemptAt,
lastAttemptAt: snapshot.LastAttemptAt,
providerMessageID: snapshot.ProviderMessageID,
version: snapshot.Version,
createdAt: snapshot.CreatedAt,
updatedAt: snapshot.UpdatedAt,
}, nil
}
func checkNextAttempt(location string, status DeliveryStatus, nextAttemptAt time.Time) error {
switch {
case status.IsTerminal() && !nextAttemptAt.IsZero():
return invalidDelivery(location, "an accepted or rejected delivery has no next attempt")
case status.requiresNextAttempt() && nextAttemptAt.IsZero():
return invalidDelivery(location, "a pending delivery needs a next attempt time")
}
return nil
}
func (delivery Delivery) IsZero() bool { return delivery.id == uuid.Nil }
func (delivery Delivery) ID() uuid.UUID { return delivery.id }
// SourceEventID is the event the delivery was created from, or uuid.Nil.
func (delivery Delivery) SourceEventID() uuid.UUID { return delivery.sourceEventID }
func (delivery Delivery) RecipientUserID() uuid.UUID { return delivery.recipientUserID }
// Recipient is the address captured when the delivery was created. Use it
// only to send the message; never log it.
func (delivery Delivery) Recipient() EmailAddress { return delivery.recipient }
func (delivery Delivery) Kind() MailKind { return delivery.content.Kind() }
func (delivery Delivery) Content() MailContent { return delivery.content }
func (delivery Delivery) ProviderAccount() MailProviderAccount { return delivery.providerAccount }
// IdempotencyKey is sent with every attempt of this delivery.
func (delivery Delivery) IdempotencyKey() string { return delivery.idempotencyKey }
func (delivery Delivery) Status() DeliveryStatus { return delivery.status }
func (delivery Delivery) AttemptCount() int32 { return delivery.attemptCount }
// NextAttemptAt is when the delivery is due; zero when no automatic attempt
// is scheduled (accepted, rejected, unknown without a retry, or waiting_quota
// with an unknown reset).
func (delivery Delivery) NextAttemptAt() time.Time { return delivery.nextAttemptAt }
// LastAttemptAt is zero before the first attempt.
func (delivery Delivery) LastAttemptAt() time.Time { return delivery.lastAttemptAt }
// ProviderMessageID is set once the provider accepted the message.
func (delivery Delivery) ProviderMessageID() string { return delivery.providerMessageID }
// Version is the optimistic concurrency version, advanced by every attempt.
func (delivery Delivery) Version() int64 { return delivery.version }
func (delivery Delivery) CreatedAt() time.Time { return delivery.createdAt }
func (delivery Delivery) UpdatedAt() time.Time { return delivery.updatedAt }
// DeliveryAttemptInput is the result of one transport attempt. The fields
// mirror outbound.SendResult; At is when the attempt ended.
//
// NextAttemptAt is chosen by the caller's retry policy. It is required when
// the outcome leaves the delivery pending (temporary or rate_limited),
// optional for waiting_quota and unknown, where zero means that no automatic
// attempt is scheduled, and must be zero for accepted and for permanent or
// invalid_request rejections. It must not precede At.
type DeliveryAttemptInput struct {
At time.Time
Outcome DeliveryAttemptOutcome
Rejection DeliveryRejection
ProviderCode string
ProviderMessageID string
RetryAfter time.Duration
NextAttemptAt time.Time
}
// DeliveryAttempt is one recorded attempt. Number counts from 1 within its
// delivery. A zero NextAttemptAt means none was scheduled.
type DeliveryAttempt struct {
DeliveryID uuid.UUID
Number int32
At time.Time
Outcome DeliveryAttemptOutcome
Rejection DeliveryRejection
ProviderCode string
ProviderMessageID string
RetryAfter time.Duration
StatusAfter DeliveryStatus
NextAttemptAt time.Time
}
// RecordAttempt applies an attempt result and returns the next state of the
// delivery together with the attempt record. The receiver is not changed. An
// attempt on an accepted or rejected delivery returns ErrDeliveryTransition;
// a result that breaks the rules of DeliveryAttemptInput returns
// ErrInvalidDelivery. The returned delivery has the next version; storage
// applies it only over the receiver's version.
func (delivery Delivery) RecordAttempt(input DeliveryAttemptInput) (Delivery, DeliveryAttempt, error) {
const location = "Delivery.RecordAttempt"
if delivery.IsZero() {
return Delivery{}, DeliveryAttempt{}, invalidDelivery(location, "delivery was not built by NewDelivery or RestoreDelivery")
}
if delivery.status.IsTerminal() {
return Delivery{}, DeliveryAttempt{}, fmt.Errorf("%s - delivery is %s: %w", location, delivery.status, ErrDeliveryTransition)
}
if delivery.attemptCount == math.MaxInt32 {
return Delivery{}, DeliveryAttempt{}, invalidDelivery(location, "attempt numbers are exhausted")
}
switch {
case input.At.IsZero():
return Delivery{}, DeliveryAttempt{}, invalidDelivery(location, "attempt time must be set")
case input.At.Before(delivery.updatedAt):
return Delivery{}, DeliveryAttempt{}, invalidDelivery(location, "attempt time must not precede the last change of the delivery")
}
attempt := DeliveryAttempt{
DeliveryID: delivery.id,
Number: delivery.attemptCount + 1,
At: input.At,
Outcome: input.Outcome,
Rejection: input.Rejection,
ProviderCode: input.ProviderCode,
ProviderMessageID: input.ProviderMessageID,
RetryAfter: input.RetryAfter,
NextAttemptAt: input.NextAttemptAt,
}
statusAfter, err := validateAttempt(location, attempt)
if err != nil {
return Delivery{}, DeliveryAttempt{}, err
}
attempt.StatusAfter = statusAfter
next := delivery
next.status = statusAfter
next.attemptCount = attempt.Number
next.lastAttemptAt = input.At
next.nextAttemptAt = input.NextAttemptAt
if input.Outcome == DeliveryOutcomeAccepted {
next.providerMessageID = input.ProviderMessageID
}
next.version = delivery.version + 1
next.updatedAt = input.At
return next, attempt, nil
}
// WaitForQuota parks a pending or waiting_quota delivery in waiting_quota
// without an attempt, for example when a local quota defers the send before
// the transport is called. until is the expected reset; zero means unknown,
// so no automatic attempt is scheduled. at is the decision time. It returns
// the next state with the next version; no attempt record is written. An
// unknown delivery is refused: parking it would hide that an earlier attempt
// may have been accepted, and its retry is decided by the retry policy.
func (delivery Delivery) WaitForQuota(at, until time.Time) (Delivery, error) {
const location = "Delivery.WaitForQuota"
if err := delivery.checkChangeTime(location, at); err != nil {
return Delivery{}, err
}
if delivery.status != DeliveryStatusPending && delivery.status != DeliveryStatusWaitingQuota {
return Delivery{}, fmt.Errorf("%s - delivery is %s: %w", location, delivery.status, ErrDeliveryTransition)
}
if !until.IsZero() && until.Before(at) {
return Delivery{}, invalidDelivery(location, "quota reset must not precede the decision")
}
next := delivery
next.status = DeliveryStatusWaitingQuota
next.nextAttemptAt = until
next.version = delivery.version + 1
next.updatedAt = at
return next, nil
}
// Rebind pins a delivery that has no attempt yet to another provider
// account, for example after the stand moved from EMAIL_PROVIDER=disabled to
// a real transport. Once an attempt was made, a provider may hold the
// idempotency key, so the account is fixed and Rebind returns
// ErrDeliveryTransition, as it does for an accepted or rejected delivery.
func (delivery Delivery) Rebind(at time.Time, providerAccount MailProviderAccount) (Delivery, error) {
const location = "Delivery.Rebind"
if err := delivery.checkChangeTime(location, at); err != nil {
return Delivery{}, err
}
if providerAccount.IsZero() {
return Delivery{}, invalidDelivery(location, "provider account must be set")
}
if delivery.attemptCount != 0 || delivery.status.IsTerminal() {
return Delivery{}, fmt.Errorf("%s - delivery has attempts or is %s: %w", location, delivery.status, ErrDeliveryTransition)
}
next := delivery
next.providerAccount = providerAccount
next.version = delivery.version + 1
next.updatedAt = at
return next, nil
}
// checkChangeTime rejects a zero delivery and a change time before the last
// recorded change.
func (delivery Delivery) checkChangeTime(location string, at time.Time) error {
if delivery.IsZero() {
return invalidDelivery(location, "delivery was not built by NewDelivery or RestoreDelivery")
}
if at.IsZero() || at.Before(delivery.updatedAt) {
return invalidDelivery(location, "change time must be set and not precede the last change")
}
return nil
}
// RestoreDeliveryAttempt checks a stored attempt with the rules that
// RecordAttempt applied when it was made.
func RestoreDeliveryAttempt(attempt DeliveryAttempt) (DeliveryAttempt, error) {
const location = "domain.RestoreDeliveryAttempt"
if attempt.DeliveryID == uuid.Nil || attempt.Number <= 0 || attempt.At.IsZero() {
return DeliveryAttempt{}, invalidDelivery(location, "attempt needs a delivery ID, a positive number, and a time")
}
statusAfter, err := validateAttempt(location, attempt)
if err != nil {
return DeliveryAttempt{}, err
}
if attempt.StatusAfter != statusAfter {
return DeliveryAttempt{}, invalidDelivery(location, "stored status does not follow from the attempt outcome")
}
return attempt, nil
}
// validateAttempt checks the result fields and returns the status the
// outcome leads to.
func validateAttempt(location string, attempt DeliveryAttempt) (DeliveryStatus, error) {
if attempt.ProviderCode != "" && !mailProviderCodePattern.MatchString(attempt.ProviderCode) {
return "", invalidDelivery(location, "provider code must be a lowercase snake_case name of at most 64 characters")
}
if attempt.RetryAfter < 0 {
return "", invalidDelivery(location, "retry-after must not be negative")
}
statusAfter, err := statusAfterAttempt(location, attempt)
if err != nil {
return "", err
}
if err := checkNextAttempt(location, statusAfter, attempt.NextAttemptAt); err != nil {
return "", err
}
if !attempt.NextAttemptAt.IsZero() && attempt.NextAttemptAt.Before(attempt.At) {
return "", invalidDelivery(location, "next attempt must not precede the attempt")
}
return statusAfter, nil
}
func statusAfterAttempt(location string, attempt DeliveryAttempt) (DeliveryStatus, error) {
if attempt.Outcome != DeliveryOutcomeAccepted && attempt.ProviderMessageID != "" {
return "", invalidDelivery(location, "only an accepted attempt carries a provider message ID")
}
if attempt.Outcome != DeliveryOutcomeRejected && attempt.Rejection != "" {
return "", invalidDelivery(location, "only a rejected attempt carries a rejection reason")
}
switch attempt.Outcome {
case DeliveryOutcomeAccepted:
if !providerMessageIDPattern.MatchString(attempt.ProviderMessageID) {
return "", invalidDelivery(location, "an accepted attempt needs a provider message ID of 1 to 128 printable ASCII characters")
}
if attempt.ProviderCode != "" || attempt.RetryAfter != 0 {
return "", invalidDelivery(location, "an accepted attempt carries no provider code or retry-after")
}
return DeliveryStatusAccepted, nil
case DeliveryOutcomeUnknown:
return DeliveryStatusUnknown, nil
case DeliveryOutcomeRejected:
switch attempt.Rejection {
case DeliveryRejectionPermanent, DeliveryRejectionInvalidRequest:
return DeliveryStatusRejected, nil
case DeliveryRejectionTemporary, DeliveryRejectionRateLimited:
return DeliveryStatusPending, nil
case DeliveryRejectionQuotaExhausted:
return DeliveryStatusWaitingQuota, nil
default:
return "", invalidDelivery(location, "a rejected attempt needs a known rejection reason")
}
default:
return "", invalidDelivery(location, "attempt outcome must be accepted, rejected, or unknown")
}
}
func invalidDelivery(location, reason string) error {
return fmt.Errorf("%s - %s: %w", location, reason, ErrInvalidDelivery)
}
func (delivery Delivery) String() string {
if delivery.IsZero() {
return "[empty delivery]"
}
return fmt.Sprintf("[delivery %s %s %s]", delivery.id, delivery.content.Kind(), delivery.status)
}
func (delivery Delivery) GoString() string { return delivery.String() }
// Format applies String to every verb; without it %+v would print the fields.
func (delivery Delivery) Format(state fmt.State, _ rune) {
_, _ = state.Write([]byte(delivery.String()))
}
// LogValue carries only bounded or opaque fields: the ID, kind, status, and
// provider. The recipient, its account ID, and the content stay out of logs.
func (delivery Delivery) LogValue() slog.Value {
return slog.GroupValue(
slog.String("delivery_id", delivery.id.String()),
slog.String("kind", string(delivery.content.Kind())),
slog.String("status", string(delivery.status)),
slog.String("provider", delivery.providerAccount.provider),
)
}
+526
View File
@@ -0,0 +1,526 @@
package domain
import (
"bytes"
"errors"
"fmt"
"log/slog"
"strings"
"testing"
"time"
"github.com/google/uuid"
)
const (
testDeliveryAddress = "Recipient.Person@Example.com"
testDeliverySubject = "Subject with a private detail"
testDeliveryText = "Text body https://lincodex.example/verify-email#token=SyntheticToken_0123456789-abcdefghij\n"
testDeliveryHTML = "<p>HTML body with a private detail</p>\n"
testMessageID = "4ef9a417-02e9-4d39-ad75-9611e0fcc33c"
)
var testDeliveryCreated = time.Date(2026, 10, 6, 9, 0, 0, 0, time.UTC)
func testMailContent(t *testing.T) MailContent {
t.Helper()
content, err := NewMailContent(MailKindVerification, "verification.v1", testDeliverySubject, testDeliveryText, testDeliveryHTML)
if err != nil {
t.Fatalf("NewMailContent() error = %v", err)
}
return content
}
func testProviderAccount(t *testing.T) MailProviderAccount {
t.Helper()
account, err := NewMailProviderAccount("resend", "main")
if err != nil {
t.Fatalf("NewMailProviderAccount() error = %v", err)
}
return account
}
func testDeliveryInput(t *testing.T) NewDeliveryInput {
t.Helper()
recipient, err := NewEmailAddress(testDeliveryAddress)
if err != nil {
t.Fatalf("NewEmailAddress() error = %v", err)
}
return NewDeliveryInput{
ID: uuid.MustParse("01926f3a-7c00-7000-8000-000000000001"),
RecipientUserID: uuid.MustParse("01926f3a-7c00-7000-8000-000000000002"),
Recipient: recipient,
Content: testMailContent(t),
ProviderAccount: testProviderAccount(t),
CreatedAt: testDeliveryCreated,
}
}
func newTestDelivery(t *testing.T) Delivery {
t.Helper()
delivery, err := NewDelivery(testDeliveryInput(t))
if err != nil {
t.Fatalf("NewDelivery() error = %v", err)
}
return delivery
}
// after returns a time minutes after the creation of the test delivery.
func after(minutes int) time.Time {
return testDeliveryCreated.Add(time.Duration(minutes) * time.Minute)
}
func mustRecord(t *testing.T, delivery Delivery, input DeliveryAttemptInput) Delivery {
t.Helper()
next, _, err := delivery.RecordAttempt(input)
if err != nil {
t.Fatalf("RecordAttempt(%s/%s) error = %v", input.Outcome, input.Rejection, err)
}
return next
}
func TestMailContentHashCoversEveryPart(t *testing.T) {
base := MailContentHash("verification.v1", "subject", "text", "html")
if base != MailContentHash("verification.v1", "subject", "text", "html") {
t.Fatal("the same parts give different hashes")
}
for name, other := range map[string][MailContentHashSize]byte{
"version": MailContentHash("verification.v2", "subject", "text", "html"),
"subject": MailContentHash("verification.v1", "subject!", "text", "html"),
"text": MailContentHash("verification.v1", "subject", "text!", "html"),
"html": MailContentHash("verification.v1", "subject", "text", "html!"),
"shifted border": MailContentHash("verification.v1", "subjec", "ttext", "html"),
} {
if other == base {
t.Fatalf("content hash ignores a change of the %s", name)
}
}
}
func TestNewMailContentRejectsUnsendableContent(t *testing.T) {
tests := []struct {
name string
kind MailKind
version, subject, text, htmlBody string
}{
{name: "unknown kind", kind: "digest", version: "digest.v1", subject: "s", text: "t"},
{name: "version of another kind", kind: MailKindNotification, version: "verification.v1", subject: "s", text: "t"},
{name: "version prefix of another kind", kind: MailKindPasswordReset, version: "password.v1", subject: "s", text: "t"},
{name: "version without number", kind: MailKindNotification, version: "notification.v0", subject: "s", text: "t"},
{name: "blank subject", kind: MailKindNotification, version: "notification.v1", subject: " ", text: "t"},
{name: "subject with a header line", kind: MailKindNotification, version: "notification.v1", subject: "s\r\nBcc: x@example.com", text: "t"},
{name: "subject too long", kind: MailKindNotification, version: "notification.v1", subject: strings.Repeat("я", maxMailSubjectRunes+1), text: "t"},
{name: "blank bodies", kind: MailKindNotification, version: "notification.v1", subject: "s", text: " \n", htmlBody: ""},
{name: "NUL in body", kind: MailKindNotification, version: "notification.v1", subject: "s", text: "t\x00"},
{name: "invalid UTF-8", kind: MailKindNotification, version: "notification.v1", subject: "s", text: "\xff"},
{name: "oversized body", kind: MailKindNotification, version: "notification.v1", subject: "s", text: strings.Repeat("t", maxMailPartBytes+1)},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
_, err := NewMailContent(test.kind, test.version, test.subject, test.text, test.htmlBody)
if !errors.Is(err, ErrInvalidMailContent) {
t.Fatalf("NewMailContent() error = %v, want ErrInvalidMailContent", err)
}
})
}
}
func TestRestoreMailContentDetectsAChangedBody(t *testing.T) {
content := testMailContent(t)
hash := content.Hash()
restored, err := RestoreMailContent(content.Kind(), content.TemplateVersion(), content.Subject(), content.Text(), content.HTML(), hash[:])
if err != nil || restored.Hash() != hash {
t.Fatalf("RestoreMailContent() = %v, %v, want the stored content", restored, err)
}
_, err = RestoreMailContent(content.Kind(), content.TemplateVersion(), content.Subject(), content.Text()+"changed", content.HTML(), hash[:])
if !errors.Is(err, ErrMailContentIntegrity) {
t.Fatalf("RestoreMailContent(changed text) error = %v, want ErrMailContentIntegrity", err)
}
_, err = RestoreMailContent(content.Kind(), content.TemplateVersion(), content.Subject(), content.Text(), content.HTML(), hash[:16])
if !errors.Is(err, ErrMailContentIntegrity) {
t.Fatalf("RestoreMailContent(short hash) error = %v, want ErrMailContentIntegrity", err)
}
}
func TestNewDeliveryStartsPendingWithAStableKey(t *testing.T) {
input := testDeliveryInput(t)
delivery := newTestDelivery(t)
switch {
case delivery.ID() != input.ID || delivery.RecipientUserID() != input.RecipientUserID:
t.Fatal("NewDelivery() changed the IDs")
case delivery.Recipient().Address() != testDeliveryAddress:
t.Fatal("NewDelivery() changed the recipient")
case delivery.Kind() != MailKindVerification || delivery.Content().Hash() != input.Content.Hash():
t.Fatal("NewDelivery() changed the content")
case delivery.IdempotencyKey() != "delivery/"+input.ID.String():
t.Fatalf("IdempotencyKey() = %q", delivery.IdempotencyKey())
case delivery.Status() != DeliveryStatusPending || !delivery.NextAttemptAt().Equal(testDeliveryCreated):
t.Fatalf("new delivery is %s due at %s, want pending and due at creation", delivery.Status(), delivery.NextAttemptAt())
case delivery.AttemptCount() != 0 || !delivery.LastAttemptAt().IsZero() || delivery.ProviderMessageID() != "":
t.Fatal("new delivery has attempt state")
case delivery.Version() != 1 || !delivery.CreatedAt().Equal(testDeliveryCreated) || !delivery.UpdatedAt().Equal(testDeliveryCreated):
t.Fatal("new delivery has the wrong version or times")
}
}
func TestNewDeliveryRejectsIncompleteInput(t *testing.T) {
tests := map[string]func(*NewDeliveryInput){
"nil ID": func(input *NewDeliveryInput) { input.ID = uuid.Nil },
"nil recipient user": func(input *NewDeliveryInput) { input.RecipientUserID = uuid.Nil },
"zero recipient": func(input *NewDeliveryInput) { input.Recipient = EmailAddress{} },
"zero content": func(input *NewDeliveryInput) { input.Content = MailContent{} },
"zero provider": func(input *NewDeliveryInput) { input.ProviderAccount = MailProviderAccount{} },
"zero creation time": func(input *NewDeliveryInput) { input.CreatedAt = time.Time{} },
}
for name, change := range tests {
t.Run(name, func(t *testing.T) {
input := testDeliveryInput(t)
change(&input)
if _, err := NewDelivery(input); !errors.Is(err, ErrInvalidDelivery) {
t.Fatalf("NewDelivery() error = %v, want ErrInvalidDelivery", err)
}
})
}
}
func TestNewMailProviderAccountRejectsCredentialsAndFreeText(t *testing.T) {
for _, test := range []struct{ provider, account string }{
{"", "main"},
{"Resend", "main"},
{"resend", ""},
{"resend", "re_SecretKeyValue"},
{"resend", "main account"},
{"resend", strings.Repeat("a", 65)},
} {
if _, err := NewMailProviderAccount(test.provider, test.account); !errors.Is(err, ErrInvalidDelivery) {
t.Fatalf("NewMailProviderAccount(%q, %q) error = %v, want ErrInvalidDelivery", test.provider, test.account, err)
}
}
}
// TestDeliveryStatusTransitions applies every attempt outcome to every
// status that accepts an attempt, and checks that the terminal statuses
// accept none.
func TestDeliveryStatusTransitions(t *testing.T) {
outcomes := []struct {
name string
input DeliveryAttemptInput
want DeliveryStatus
}{
{"accepted", DeliveryAttemptInput{Outcome: DeliveryOutcomeAccepted, ProviderMessageID: testMessageID}, DeliveryStatusAccepted},
{"permanent", DeliveryAttemptInput{Outcome: DeliveryOutcomeRejected, Rejection: DeliveryRejectionPermanent, ProviderCode: "validation_error"}, DeliveryStatusRejected},
{"invalid request", DeliveryAttemptInput{Outcome: DeliveryOutcomeRejected, Rejection: DeliveryRejectionInvalidRequest, ProviderCode: "invalid_api_key"}, DeliveryStatusRejected},
{"temporary", DeliveryAttemptInput{Outcome: DeliveryOutcomeRejected, Rejection: DeliveryRejectionTemporary, NextAttemptAt: after(90)}, DeliveryStatusPending},
{"rate limited", DeliveryAttemptInput{Outcome: DeliveryOutcomeRejected, Rejection: DeliveryRejectionRateLimited, RetryAfter: time.Second, NextAttemptAt: after(90)}, DeliveryStatusPending},
{"quota", DeliveryAttemptInput{Outcome: DeliveryOutcomeRejected, Rejection: DeliveryRejectionQuotaExhausted, ProviderCode: "daily_quota_exceeded", RetryAfter: time.Hour, NextAttemptAt: after(120)}, DeliveryStatusWaitingQuota},
{"quota with unknown reset", DeliveryAttemptInput{Outcome: DeliveryOutcomeRejected, Rejection: DeliveryRejectionQuotaExhausted, ProviderCode: "monthly_quota_exceeded"}, DeliveryStatusWaitingQuota},
{"unknown with retry", DeliveryAttemptInput{Outcome: DeliveryOutcomeUnknown, ProviderCode: "concurrent_idempotent_requests", NextAttemptAt: after(90)}, DeliveryStatusUnknown},
{"unknown without retry", DeliveryAttemptInput{Outcome: DeliveryOutcomeUnknown, ProviderCode: "invalid_idempotent_request"}, DeliveryStatusUnknown},
}
start := newTestDelivery(t)
starts := map[DeliveryStatus]Delivery{
DeliveryStatusPending: start,
DeliveryStatusWaitingQuota: mustRecord(t, start, DeliveryAttemptInput{
At: after(1), Outcome: DeliveryOutcomeRejected, Rejection: DeliveryRejectionQuotaExhausted, NextAttemptAt: after(60),
}),
DeliveryStatusUnknown: mustRecord(t, start, DeliveryAttemptInput{At: after(1), Outcome: DeliveryOutcomeUnknown}),
}
for from, delivery := range starts {
for _, outcome := range outcomes {
t.Run(string(from)+" then "+outcome.name, func(t *testing.T) {
input := outcome.input
input.At = after(30)
next, attempt, err := delivery.RecordAttempt(input)
if err != nil {
t.Fatalf("RecordAttempt() error = %v", err)
}
if next.Status() != outcome.want || attempt.StatusAfter != outcome.want {
t.Fatalf("status = %s, attempt status = %s, want %s", next.Status(), attempt.StatusAfter, outcome.want)
}
if next.AttemptCount() != delivery.AttemptCount()+1 || attempt.Number != next.AttemptCount() {
t.Fatalf("attempt number = %d, count = %d after %d", attempt.Number, next.AttemptCount(), delivery.AttemptCount())
}
if next.Version() != delivery.Version()+1 || !next.LastAttemptAt().Equal(input.At) || !next.UpdatedAt().Equal(input.At) {
t.Fatal("the attempt did not advance the version and times")
}
if !next.NextAttemptAt().Equal(input.NextAttemptAt) {
t.Fatalf("NextAttemptAt() = %s, want %s", next.NextAttemptAt(), input.NextAttemptAt)
}
if wantID := input.ProviderMessageID; next.ProviderMessageID() != wantID {
t.Fatalf("ProviderMessageID() = %q, want %q", next.ProviderMessageID(), wantID)
}
if next.IdempotencyKey() != delivery.IdempotencyKey() || next.Content().Hash() != delivery.Content().Hash() {
t.Fatal("an attempt changed the key or the content")
}
})
}
}
terminal := map[DeliveryStatus]Delivery{
DeliveryStatusAccepted: mustRecord(t, start, DeliveryAttemptInput{At: after(1), Outcome: DeliveryOutcomeAccepted, ProviderMessageID: testMessageID}),
DeliveryStatusRejected: mustRecord(t, start, DeliveryAttemptInput{At: after(1), Outcome: DeliveryOutcomeRejected, Rejection: DeliveryRejectionPermanent}),
}
for from, delivery := range terminal {
for _, outcome := range outcomes {
t.Run(string(from)+" refuses "+outcome.name, func(t *testing.T) {
input := outcome.input
input.At = after(30)
if _, _, err := delivery.RecordAttempt(input); !errors.Is(err, ErrDeliveryTransition) {
t.Fatalf("RecordAttempt() error = %v, want ErrDeliveryTransition", err)
}
})
}
}
}
func TestRecordAttemptLeavesTheReceiverUnchanged(t *testing.T) {
delivery := newTestDelivery(t)
next := mustRecord(t, delivery, DeliveryAttemptInput{At: after(1), Outcome: DeliveryOutcomeAccepted, ProviderMessageID: testMessageID})
if delivery.Status() != DeliveryStatusPending || delivery.Version() != 1 || delivery.AttemptCount() != 0 {
t.Fatal("RecordAttempt() changed its receiver")
}
if next.Status() != DeliveryStatusAccepted || next.ProviderMessageID() != testMessageID || !next.NextAttemptAt().IsZero() {
t.Fatalf("accepted delivery = %s with ID %q due %s", next.Status(), next.ProviderMessageID(), next.NextAttemptAt())
}
}
func TestRecordAttemptRejectsInconsistentResults(t *testing.T) {
delivery := mustRecord(t, newTestDelivery(t), DeliveryAttemptInput{At: after(10), Outcome: DeliveryOutcomeUnknown})
tests := map[string]DeliveryAttemptInput{
"zero time": {Outcome: DeliveryOutcomeUnknown},
"before the previous attempt": {At: after(5), Outcome: DeliveryOutcomeUnknown},
"unknown outcome": {At: after(20), Outcome: "delivered"},
"accepted without message ID": {At: after(20), Outcome: DeliveryOutcomeAccepted},
"accepted with spaces in ID": {At: after(20), Outcome: DeliveryOutcomeAccepted, ProviderMessageID: "an id"},
"accepted with provider code": {At: after(20), Outcome: DeliveryOutcomeAccepted, ProviderMessageID: testMessageID, ProviderCode: "validation_error"},
"accepted with next attempt": {At: after(20), Outcome: DeliveryOutcomeAccepted, ProviderMessageID: testMessageID, NextAttemptAt: after(30)},
"rejected without reason": {At: after(20), Outcome: DeliveryOutcomeRejected},
"rejected with unknown reason": {At: after(20), Outcome: DeliveryOutcomeRejected, Rejection: "bounced"},
"rejected with message ID": {At: after(20), Outcome: DeliveryOutcomeRejected, Rejection: DeliveryRejectionPermanent, ProviderMessageID: testMessageID},
"permanent with next attempt": {At: after(20), Outcome: DeliveryOutcomeRejected, Rejection: DeliveryRejectionPermanent, NextAttemptAt: after(30)},
"temporary without next": {At: after(20), Outcome: DeliveryOutcomeRejected, Rejection: DeliveryRejectionTemporary},
"next before the attempt": {At: after(20), Outcome: DeliveryOutcomeRejected, Rejection: DeliveryRejectionTemporary, NextAttemptAt: after(15)},
"unknown with a rejection": {At: after(20), Outcome: DeliveryOutcomeUnknown, Rejection: DeliveryRejectionTemporary},
"provider free text": {At: after(20), Outcome: DeliveryOutcomeUnknown, ProviderCode: "Upstream said: no"},
"negative retry-after": {At: after(20), Outcome: DeliveryOutcomeUnknown, RetryAfter: -time.Second},
"oversized provider message ID": {At: after(20), Outcome: DeliveryOutcomeAccepted, ProviderMessageID: strings.Repeat("a", 129)},
}
for name, input := range tests {
t.Run(name, func(t *testing.T) {
if _, _, err := delivery.RecordAttempt(input); !errors.Is(err, ErrInvalidDelivery) {
t.Fatalf("RecordAttempt() error = %v, want ErrInvalidDelivery", err)
}
})
}
if _, _, err := (Delivery{}).RecordAttempt(DeliveryAttemptInput{At: after(20), Outcome: DeliveryOutcomeUnknown}); !errors.Is(err, ErrInvalidDelivery) {
t.Fatalf("RecordAttempt() on a zero delivery error = %v, want ErrInvalidDelivery", err)
}
}
func deliverySnapshot(delivery Delivery) DeliverySnapshot {
return DeliverySnapshot{
ID: delivery.ID(),
SourceEventID: delivery.SourceEventID(),
RecipientUserID: delivery.RecipientUserID(),
RecipientAddress: delivery.Recipient().Address(),
Content: delivery.Content(),
ProviderAccount: delivery.ProviderAccount(),
IdempotencyKey: delivery.IdempotencyKey(),
Status: delivery.Status(),
AttemptCount: delivery.AttemptCount(),
NextAttemptAt: delivery.NextAttemptAt(),
LastAttemptAt: delivery.LastAttemptAt(),
ProviderMessageID: delivery.ProviderMessageID(),
Version: delivery.Version(),
CreatedAt: delivery.CreatedAt(),
UpdatedAt: delivery.UpdatedAt(),
}
}
func TestRestoreDeliveryChecksTheStoredInvariants(t *testing.T) {
accepted := mustRecord(t, newTestDelivery(t), DeliveryAttemptInput{At: after(1), Outcome: DeliveryOutcomeAccepted, ProviderMessageID: testMessageID})
restored, err := RestoreDelivery(deliverySnapshot(accepted))
if err != nil {
t.Fatalf("RestoreDelivery() error = %v", err)
}
if restored.Status() != DeliveryStatusAccepted || restored.ProviderMessageID() != testMessageID ||
restored.Recipient().Normalized() != strings.ToLower(testDeliveryAddress) || restored.Version() != accepted.Version() {
t.Fatal("RestoreDelivery() did not keep the stored state")
}
tests := map[string]func(*DeliverySnapshot){
"unknown status": func(snapshot *DeliverySnapshot) { snapshot.Status = "sent" },
"accepted without message ID": func(snapshot *DeliverySnapshot) { snapshot.ProviderMessageID = "" },
"terminal with next attempt": func(snapshot *DeliverySnapshot) { snapshot.NextAttemptAt = after(5) },
"pending without next": func(snapshot *DeliverySnapshot) {
snapshot.Status, snapshot.ProviderMessageID = DeliveryStatusPending, ""
},
"attempts without last time": func(snapshot *DeliverySnapshot) { snapshot.LastAttemptAt = time.Time{} },
"zero version": func(snapshot *DeliverySnapshot) { snapshot.Version = 0 },
"empty idempotency key": func(snapshot *DeliverySnapshot) { snapshot.IdempotencyKey = "" },
"updated before creation": func(snapshot *DeliverySnapshot) { snapshot.UpdatedAt = testDeliveryCreated.Add(-time.Second) },
"empty recipient": func(snapshot *DeliverySnapshot) { snapshot.RecipientAddress = "" },
}
for name, change := range tests {
t.Run(name, func(t *testing.T) {
snapshot := deliverySnapshot(accepted)
change(&snapshot)
if _, err := RestoreDelivery(snapshot); err == nil {
t.Fatal("RestoreDelivery() accepted a broken row")
}
})
}
}
func TestRestoreDeliveryAttemptChecksTheStatusAfter(t *testing.T) {
_, attempt, err := newTestDelivery(t).RecordAttempt(DeliveryAttemptInput{
At: after(1), Outcome: DeliveryOutcomeRejected, Rejection: DeliveryRejectionRateLimited, RetryAfter: 2 * time.Second, NextAttemptAt: after(2),
})
if err != nil {
t.Fatalf("RecordAttempt() error = %v", err)
}
if _, err := RestoreDeliveryAttempt(attempt); err != nil {
t.Fatalf("RestoreDeliveryAttempt() error = %v", err)
}
attempt.StatusAfter = DeliveryStatusRejected
if _, err := RestoreDeliveryAttempt(attempt); !errors.Is(err, ErrInvalidDelivery) {
t.Fatalf("RestoreDeliveryAttempt(mismatched status) error = %v, want ErrInvalidDelivery", err)
}
}
// deliveryHolder has the delivery in an unexported field, where fmt does not
// call its methods.
type deliveryHolder struct {
delivery Delivery
content MailContent
}
func TestDeliveryNeverPrintsTheRecipientOrContent(t *testing.T) {
delivery := newTestDelivery(t)
holder := deliveryHolder{delivery: delivery, content: delivery.Content()}
var output bytes.Buffer
for _, format := range []string{"%v", "%+v", "%#v", "%s", "%q"} {
fmt.Fprintf(&output, format+"\n", delivery)
fmt.Fprintf(&output, format+"\n", delivery.Content())
}
// For an enclosing struct fmt prints the pointer fields as addresses with
// the value verbs. Other verbs report a bad verb with the pointee, the
// known limit shared with EmailAddress and SecretToken.
for _, format := range []string{"%v", "%+v", "%#v"} {
fmt.Fprintf(&output, format+"\n", holder)
fmt.Fprintf(&output, format+"\n", &holder)
}
for _, logger := range []*slog.Logger{
slog.New(slog.NewTextHandler(&output, nil)),
slog.New(slog.NewJSONHandler(&output, nil)),
} {
logger.Info("delivery", "delivery", delivery, "content", delivery.Content(), "holder", holder)
}
printed := output.String()
for _, secret := range []string{
testDeliveryAddress, strings.ToLower(testDeliveryAddress), testDeliverySubject, "SyntheticToken", "private detail",
delivery.RecipientUserID().String(),
} {
if strings.Contains(printed, secret) {
t.Fatalf("printed delivery contains %q:\n%s", secret, printed)
}
}
for _, expected := range []string{delivery.ID().String(), "verification.v1", "pending", "resend"} {
if !strings.Contains(printed, expected) {
t.Fatalf("printed delivery lacks the bounded field %q:\n%s", expected, printed)
}
}
}
func TestNewDeliveryKeepsTheSourceEvent(t *testing.T) {
input := testDeliveryInput(t)
if delivery := newTestDelivery(t); delivery.SourceEventID() != uuid.Nil {
t.Fatal("a delivery without a source event names one")
}
input.SourceEventID = uuid.MustParse("01926f3a-7c00-7000-8000-0000000000ee")
delivery, err := NewDelivery(input)
if err != nil || delivery.SourceEventID() != input.SourceEventID {
t.Fatalf("NewDelivery() = %v, %v; want the source event kept", delivery, err)
}
restored, err := RestoreDelivery(deliverySnapshot(delivery))
if err != nil || restored.SourceEventID() != input.SourceEventID {
t.Fatalf("RestoreDelivery() = %v, %v; want the source event kept", restored, err)
}
}
func TestWaitForQuotaParksWithoutAnAttempt(t *testing.T) {
pending := newTestDelivery(t)
for name, until := range map[string]time.Time{"known reset": after(60), "unknown reset": {}} {
t.Run(name, func(t *testing.T) {
waiting, err := pending.WaitForQuota(after(1), until)
if err != nil {
t.Fatalf("WaitForQuota() error = %v", err)
}
if waiting.Status() != DeliveryStatusWaitingQuota || !waiting.NextAttemptAt().Equal(until) ||
waiting.AttemptCount() != 0 || waiting.Version() != 2 || !waiting.UpdatedAt().Equal(after(1)) {
t.Fatalf("waiting delivery = %s due %s with %d attempts at version %d", waiting.Status(), waiting.NextAttemptAt(), waiting.AttemptCount(), waiting.Version())
}
if _, err := RestoreDelivery(deliverySnapshot(waiting)); err != nil {
t.Fatalf("RestoreDelivery(waiting) error = %v", err)
}
// A later decision may move the reset again.
if moved, err := waiting.WaitForQuota(after(2), after(90)); err != nil || !moved.NextAttemptAt().Equal(after(90)) {
t.Fatalf("second WaitForQuota() = %s, %v", moved.NextAttemptAt(), err)
}
})
}
unknown := mustRecord(t, pending, DeliveryAttemptInput{At: after(1), Outcome: DeliveryOutcomeUnknown})
accepted := mustRecord(t, pending, DeliveryAttemptInput{At: after(1), Outcome: DeliveryOutcomeAccepted, ProviderMessageID: testMessageID})
for name, delivery := range map[string]Delivery{"unknown": unknown, "accepted": accepted} {
if _, err := delivery.WaitForQuota(after(5), after(60)); !errors.Is(err, ErrDeliveryTransition) {
t.Fatalf("WaitForQuota() on %s error = %v, want ErrDeliveryTransition", name, err)
}
}
for name, times := range map[string][2]time.Time{
"reset before the decision": {after(5), after(4)},
"decision before the change": {testDeliveryCreated.Add(-time.Minute), after(4)},
"zero decision time": {{}, after(4)},
} {
if _, err := pending.WaitForQuota(times[0], times[1]); !errors.Is(err, ErrInvalidDelivery) {
t.Fatalf("WaitForQuota() with %s error = %v, want ErrInvalidDelivery", name, err)
}
}
// An attempt after the wait must not precede the wait.
waiting, err := pending.WaitForQuota(after(10), time.Time{})
if err != nil {
t.Fatalf("WaitForQuota() error = %v", err)
}
if _, _, err := waiting.RecordAttempt(DeliveryAttemptInput{At: after(5), Outcome: DeliveryOutcomeUnknown}); !errors.Is(err, ErrInvalidDelivery) {
t.Fatalf("RecordAttempt() before the wait error = %v, want ErrInvalidDelivery", err)
}
}
func TestRebindIsAllowedOnlyBeforeTheFirstAttempt(t *testing.T) {
pending := newTestDelivery(t)
other, err := NewMailProviderAccount("resend", "eu")
if err != nil {
t.Fatalf("NewMailProviderAccount() error = %v", err)
}
rebound, err := pending.Rebind(after(1), other)
if err != nil {
t.Fatalf("Rebind() error = %v", err)
}
if rebound.ProviderAccount() != other || rebound.Version() != 2 || rebound.IdempotencyKey() != pending.IdempotencyKey() ||
rebound.Status() != DeliveryStatusPending || !rebound.NextAttemptAt().Equal(pending.NextAttemptAt()) {
t.Fatal("Rebind() changed more than the provider account and version")
}
if waiting, err := pending.WaitForQuota(after(1), time.Time{}); err != nil {
t.Fatalf("WaitForQuota() error = %v", err)
} else if _, err := waiting.Rebind(after(2), other); err != nil {
t.Fatalf("Rebind() of a waiting delivery without attempts error = %v", err)
}
if _, err := pending.Rebind(after(1), MailProviderAccount{}); !errors.Is(err, ErrInvalidDelivery) {
t.Fatalf("Rebind(zero account) error = %v, want ErrInvalidDelivery", err)
}
attempted := mustRecord(t, pending, DeliveryAttemptInput{At: after(1), Outcome: DeliveryOutcomeRejected, Rejection: DeliveryRejectionTemporary, NextAttemptAt: after(2)})
if _, err := attempted.Rebind(after(3), other); !errors.Is(err, ErrDeliveryTransition) {
t.Fatalf("Rebind() after an attempt error = %v, want ErrDeliveryTransition", err)
}
}
+214
View File
@@ -0,0 +1,214 @@
package domain
import (
"crypto/sha256"
"crypto/subtle"
"encoding/hex"
"errors"
"fmt"
"io"
"log/slog"
"regexp"
"strings"
"unicode/utf8"
)
const (
// maxMailSubjectRunes matches the rendered subject bound of the mail
// templates; a longer stored subject is not a rendering.
maxMailSubjectRunes = 150
// maxMailPartBytes bounds one stored body part. Rendered service mail is
// a few kilobytes; the bound keeps a broken renderer from filling a row.
maxMailPartBytes = 256 << 10
// MailContentHashSize is the size of the SHA-256 content digest.
MailContentHashSize = sha256.Size
)
var (
// ErrInvalidMailContent reports content that no transport could send or
// that does not belong to its kind. Errors name the rule, never the text.
ErrInvalidMailContent = errors.New("invalid mail content")
// ErrMailContentIntegrity reports stored content whose parts no longer
// match the stored digest: the row was changed outside the application.
ErrMailContentIntegrity = errors.New("mail content does not match its hash")
// "<kind>.v<N>", the template version naming of the mail templates.
mailTemplateVersionPattern = regexp.MustCompile(`^[a-z][a-z_]*\.v[1-9][0-9]{0,8}$`)
)
// MailKind names what a message is for. The values equal the template kinds
// of the mail templates.
type MailKind string
const (
MailKindVerification MailKind = "verification"
MailKindPasswordReset MailKind = "password_reset"
MailKindNotification MailKind = "notification"
)
// ParseMailKind accepts a known kind.
func ParseMailKind(value string) (MailKind, error) {
switch kind := MailKind(value); kind {
case MailKindVerification, MailKindPasswordReset, MailKindNotification:
return kind, nil
default:
return "", fmt.Errorf("domain.ParseMailKind - unknown mail kind: %w", ErrInvalidMailContent)
}
}
// CarriesBearerToken reports kinds whose body holds a one-time bearer token
// in a link. Their stored bodies are secrets until the token expires.
func (kind MailKind) CarriesBearerToken() bool {
return kind == MailKindVerification || kind == MailKindPasswordReset
}
// MailContentHash is SHA-256 over the template version, subject, text part,
// and HTML part, each encoded as a netstring ("<len>:<part>,"), so moving
// bytes from one part to the next changes the digest. The mail templates and
// stored deliveries use this one definition.
func MailContentHash(templateVersion, subject, text, html string) [MailContentHashSize]byte {
digest := sha256.New()
for _, part := range []string{templateVersion, subject, text, html} {
// hash.Hash.Write never returns an error.
_, _ = fmt.Fprintf(digest, "%d:", len(part))
_, _ = io.WriteString(digest, part)
_, _ = io.WriteString(digest, ",")
}
var sum [MailContentHashSize]byte
copy(sum[:], digest.Sum(nil))
return sum
}
// MailContent is one immutable rendered message: its kind, template version,
// subject, plain-text part, HTML part, and content hash. A body of a kind
// that CarriesBearerToken holds a live token.
//
// The parts sit behind a pointer with read-only accessors, so printing an
// enclosing struct shows only an address. String, GoString, Format, and
// LogValue show the kind, version, and hash, never the subject or bodies.
type MailContent struct {
value *mailContentValue
}
type mailContentValue struct {
kind MailKind
templateVersion string
subject string
text string
html string
hash [MailContentHashSize]byte
}
// NewMailContent validates a rendering and computes its hash. The template
// version must name the kind ("<kind>.v<N>"), the subject must be one line
// of 1 to 150 characters, and at least one body part must be non-blank.
func NewMailContent(kind MailKind, templateVersion, subject, text, html string) (MailContent, error) {
if _, err := ParseMailKind(string(kind)); err != nil {
return MailContent{}, fmt.Errorf("domain.NewMailContent - validate kind: %w", err)
}
if err := validateMailContent(kind, templateVersion, subject, text, html); err != nil {
return MailContent{}, err
}
return MailContent{value: &mailContentValue{
kind: kind,
templateVersion: templateVersion,
subject: subject,
text: text,
html: html,
hash: MailContentHash(templateVersion, subject, text, html),
}}, nil
}
// RestoreMailContent rebuilds stored content and checks it against the
// stored hash. A mismatch wraps ErrMailContentIntegrity.
func RestoreMailContent(kind MailKind, templateVersion, subject, text, html string, hash []byte) (MailContent, error) {
content, err := NewMailContent(kind, templateVersion, subject, text, html)
if err != nil {
return MailContent{}, fmt.Errorf("domain.RestoreMailContent - validate stored content: %w", err)
}
stored := content.value.hash
if subtle.ConstantTimeCompare(hash, stored[:]) != 1 {
return MailContent{}, fmt.Errorf("domain.RestoreMailContent - %w", ErrMailContentIntegrity)
}
return content, nil
}
func validateMailContent(kind MailKind, templateVersion, subject, text, html string) error {
switch {
case !mailTemplateVersionPattern.MatchString(templateVersion) || !strings.HasPrefix(templateVersion, string(kind)+".v"):
return invalidMailContent("template version must be <kind>.v<N> of the content kind")
case !utf8.ValidString(subject) || !utf8.ValidString(text) || !utf8.ValidString(html):
return invalidMailContent("subject and body parts must be valid UTF-8")
case strings.TrimSpace(subject) == "" || utf8.RuneCountInString(subject) > maxMailSubjectRunes:
return invalidMailContent(fmt.Sprintf("subject must have 1 to %d characters", maxMailSubjectRunes))
// A control character in the subject could inject header lines.
case strings.ContainsFunc(subject, isMailControlCharacter):
return invalidMailContent("subject must not contain control characters")
case strings.TrimSpace(text) == "" && strings.TrimSpace(html) == "":
return invalidMailContent("text or HTML part must not be blank")
case len(text) > maxMailPartBytes || len(html) > maxMailPartBytes:
return invalidMailContent("body parts must have at most 256 KiB each")
// PostgreSQL text cannot store NUL.
case strings.ContainsRune(text, 0) || strings.ContainsRune(html, 0):
return invalidMailContent("body parts must not contain NUL characters")
}
return nil
}
func isMailControlCharacter(character rune) bool {
return character < ' ' || character == 0x7f
}
func invalidMailContent(reason string) error {
return fmt.Errorf("domain.NewMailContent - %s: %w", reason, ErrInvalidMailContent)
}
// IsZero reports content not built by NewMailContent or RestoreMailContent.
func (content MailContent) IsZero() bool { return content.value == nil }
func (content MailContent) Kind() MailKind { return content.read().kind }
func (content MailContent) TemplateVersion() string { return content.read().templateVersion }
func (content MailContent) Subject() string { return content.read().subject }
// Text returns the plain-text part. It may hold a bearer token; never log it.
func (content MailContent) Text() string { return content.read().text }
// HTML returns the HTML part. It may hold a bearer token; never log it.
func (content MailContent) HTML() string { return content.read().html }
// Hash returns the SHA-256 content digest. It is not secret: a digest over a
// body that holds a 256-bit token cannot be reversed.
func (content MailContent) Hash() [MailContentHashSize]byte { return content.read().hash }
func (content MailContent) read() mailContentValue {
if content.value == nil {
return mailContentValue{}
}
return *content.value
}
func (content MailContent) String() string {
if content.value == nil {
return "[empty mail content]"
}
return fmt.Sprintf("[mail content %s %s, redacted]", content.value.templateVersion, hex.EncodeToString(content.value.hash[:]))
}
func (content MailContent) GoString() string { return content.String() }
// Format applies String to every verb; without it %+v would print the fields.
func (content MailContent) Format(state fmt.State, _ rune) {
_, _ = state.Write([]byte(content.String()))
}
func (content MailContent) LogValue() slog.Value {
value := content.read()
return slog.GroupValue(
slog.String("kind", string(value.kind)),
slog.String("template_version", value.templateVersion),
slog.String("content_hash", hex.EncodeToString(value.hash[:])),
)
}
+102
View File
@@ -0,0 +1,102 @@
package domain
import (
"errors"
"fmt"
"log/slog"
"strings"
"time"
"unicode/utf8"
"github.com/google/uuid"
)
const (
// Raw caller text is bounded before the template normalizes it; the
// rendered subject and body have tighter template limits.
maxMailRequestSubjectRunes = 1000
maxMailRequestBodyRunes = 16000
maxMailRequestLinkPathSize = 256
redactedNotificationText = "[redacted notification text]"
)
// ErrInvalidMailRequest reports a mail request that cannot be stored.
// Errors name the rule, never the text.
var ErrInvalidMailRequest = errors.New("invalid mail request")
// NotificationText is the caller text of a notification mail: the subject,
// the body, and a path inside the application for the link. It is personal
// data addressed to the recipient, so String, GoString, Format, LogValue,
// and MarshalJSON redact it.
type NotificationText struct {
Subject string
Body string
LinkPath string
}
func (text NotificationText) String() string { return redactedNotificationText }
func (text NotificationText) GoString() string { return redactedNotificationText }
// Format redacts every verb; without it %+v would print the fields.
func (text NotificationText) Format(state fmt.State, _ rune) {
_, _ = state.Write([]byte(redactedNotificationText))
}
func (text NotificationText) LogValue() slog.Value { return slog.StringValue(redactedNotificationText) }
// MarshalJSON redacts the text, because slog and other encoders reach a
// nested struct through encoding/json. Nothing serializes the text as JSON.
func (text NotificationText) MarshalJSON() ([]byte, error) {
return []byte(`"` + redactedNotificationText + `"`), nil
}
// MailRequest is a stored request for one mail to one account. It lives in
// the database only until the delivery consumer turned it into a Delivery,
// so the event that announces it carries the request ID and no text.
// Deleting the account deletes a request that is still waiting.
type MailRequest struct {
ID uuid.UUID
RecipientUserID uuid.UUID
Kind MailKind
Notification NotificationText
CreatedAt time.Time
}
// NewMailRequest checks the storage rules of a request. Only notification
// mail is requested this way: mail with a one-time token is created in the
// transaction that issues the token. Whether the text renders is checked by
// the template, not here.
func NewMailRequest(request MailRequest) (MailRequest, error) {
text := request.Notification
switch {
case request.ID == uuid.Nil || request.RecipientUserID == uuid.Nil:
return MailRequest{}, invalidMailRequest("request and recipient user IDs must not be nil")
case request.Kind != MailKindNotification:
return MailRequest{}, invalidMailRequest("only notification mail can be requested")
case request.CreatedAt.IsZero():
return MailRequest{}, invalidMailRequest("creation time must be set")
case !utf8.ValidString(text.Subject) || !utf8.ValidString(text.Body) || !utf8.ValidString(text.LinkPath):
return MailRequest{}, invalidMailRequest("text must be valid UTF-8")
// PostgreSQL text cannot store NUL.
case strings.ContainsRune(text.Subject, 0) || strings.ContainsRune(text.Body, 0) || strings.ContainsRune(text.LinkPath, 0):
return MailRequest{}, invalidMailRequest("text must not contain NUL characters")
case utf8.RuneCountInString(text.Subject) > maxMailRequestSubjectRunes ||
utf8.RuneCountInString(text.Body) > maxMailRequestBodyRunes ||
len(text.LinkPath) > maxMailRequestLinkPathSize:
return MailRequest{}, invalidMailRequest("subject, body, or link path is too long")
}
return request, nil
}
// LogValue carries the IDs and kind only.
func (request MailRequest) LogValue() slog.Value {
return slog.GroupValue(
slog.String("mail_request_id", request.ID.String()),
slog.String("kind", string(request.Kind)),
)
}
func invalidMailRequest(reason string) error {
return fmt.Errorf("domain.NewMailRequest - %s: %w", reason, ErrInvalidMailRequest)
}
@@ -0,0 +1,68 @@
package domain
import (
"bytes"
"errors"
"fmt"
"log/slog"
"strings"
"testing"
"time"
"github.com/google/uuid"
)
func testMailRequest() MailRequest {
return MailRequest{
ID: uuid.MustParse("01926f3a-7c00-7000-8000-000000000101"),
RecipientUserID: uuid.MustParse("01926f3a-7c00-7000-8000-000000000102"),
Kind: MailKindNotification,
Notification: NotificationText{Subject: "PRIVATE-SUBJECT", Body: "PRIVATE-BODY", LinkPath: "/candidate/invitations"},
CreatedAt: time.Date(2026, 10, 6, 9, 0, 0, 0, time.UTC),
}
}
func TestNewMailRequestChecksTheStorageRules(t *testing.T) {
if _, err := NewMailRequest(testMailRequest()); err != nil {
t.Fatalf("NewMailRequest() error = %v", err)
}
tests := map[string]func(*MailRequest){
"nil ID": func(request *MailRequest) { request.ID = uuid.Nil },
"nil recipient": func(request *MailRequest) { request.RecipientUserID = uuid.Nil },
"token mail kind": func(request *MailRequest) { request.Kind = MailKindVerification },
"zero creation time": func(request *MailRequest) { request.CreatedAt = time.Time{} },
"NUL in the body": func(request *MailRequest) { request.Notification.Body += "\x00" },
"invalid UTF-8": func(request *MailRequest) { request.Notification.Subject = "\xff" },
"oversized body": func(request *MailRequest) {
request.Notification.Body = strings.Repeat("я", maxMailRequestBodyRunes+1)
},
"oversized link": func(request *MailRequest) {
request.Notification.LinkPath = "/" + strings.Repeat("a", maxMailRequestLinkPathSize)
},
}
for name, change := range tests {
t.Run(name, func(t *testing.T) {
request := testMailRequest()
change(&request)
if _, err := NewMailRequest(request); !errors.Is(err, ErrInvalidMailRequest) {
t.Fatalf("NewMailRequest() error = %v, want ErrInvalidMailRequest", err)
}
})
}
}
func TestMailRequestNeverPrintsItsText(t *testing.T) {
request := testMailRequest()
var output bytes.Buffer
for _, format := range []string{"%v", "%+v", "%#v", "%s"} {
fmt.Fprintf(&output, format+"\n", request)
fmt.Fprintf(&output, format+"\n", &request)
}
type holder struct{ Request MailRequest }
for _, logger := range []*slog.Logger{slog.New(slog.NewJSONHandler(&output, nil)), slog.New(slog.NewTextHandler(&output, nil))} {
logger.Info("request", "request", request, "holder", holder{Request: request})
}
if printed := output.String(); strings.Contains(printed, "PRIVATE") {
t.Fatalf("printed mail request contains its text:\n%s", printed)
}
}