828 lines
37 KiB
Go
828 lines
37 KiB
Go
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, rejected, or cancelled delivery,
|
|
// a quota wait or a cancellation 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, cancelled --RecordAttempt--> refused (ErrDeliveryTransition)
|
|
// pending, waiting_quota --WaitForQuota---> waiting_quota (no attempt is recorded)
|
|
// pending, waiting_quota --Cancel---------> cancelled (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.
|
|
//
|
|
// Only accepted means that a provider took the message, and even then it is
|
|
// not delivery to a person: no status claims that the mail reached an inbox
|
|
// or was read.
|
|
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: "accepted by the provider". 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"
|
|
// DeliveryStatusCancelled means the message was deliberately not sent
|
|
// and never will be: no attempt of it is recorded, and the reason says
|
|
// why (see DeliveryCancelReason). It is terminal and is not an attempt.
|
|
DeliveryStatusCancelled DeliveryStatus = "cancelled"
|
|
)
|
|
|
|
// ParseDeliveryStatus accepts a known status.
|
|
func ParseDeliveryStatus(value string) (DeliveryStatus, error) {
|
|
switch status := DeliveryStatus(value); status {
|
|
case DeliveryStatusPending, DeliveryStatusAccepted, DeliveryStatusRejected, DeliveryStatusUnknown,
|
|
DeliveryStatusWaitingQuota, DeliveryStatusCancelled:
|
|
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 || status == DeliveryStatusCancelled
|
|
}
|
|
|
|
// 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"
|
|
)
|
|
|
|
// DeliveryCancelReason says why a delivery was cancelled: the message was
|
|
// deliberately not sent, and no attempt of it is recorded. The values are stored and must stay
|
|
// stable; each names the first failed check of the service mail rules (see
|
|
// Delivery.CheckServiceMail) or an invalid stored message.
|
|
type DeliveryCancelReason string
|
|
|
|
const (
|
|
// DeliveryCancelTokenMissing: the delivery is bound to no token, or the
|
|
// token row does not exist.
|
|
DeliveryCancelTokenMissing DeliveryCancelReason = "token_missing"
|
|
// DeliveryCancelTokenPurposeMismatch: the token authorizes another
|
|
// purpose than the kind of the mail.
|
|
DeliveryCancelTokenPurposeMismatch DeliveryCancelReason = "token_purpose_mismatch"
|
|
// DeliveryCancelTokenOwnerMismatch: the token belongs to another account
|
|
// than the recipient.
|
|
DeliveryCancelTokenOwnerMismatch DeliveryCancelReason = "token_owner_mismatch"
|
|
// DeliveryCancelTokenConsumed: the token was already used.
|
|
DeliveryCancelTokenConsumed DeliveryCancelReason = "token_consumed"
|
|
// DeliveryCancelTokenRevoked: a resend, a re-registration, or another
|
|
// revocation replaced the token.
|
|
DeliveryCancelTokenRevoked DeliveryCancelReason = "token_revoked"
|
|
// DeliveryCancelTokenExpired: the token passed its lifetime.
|
|
DeliveryCancelTokenExpired DeliveryCancelReason = "token_expired"
|
|
// DeliveryCancelAccountNotCurrent: the account moved on since the token
|
|
// was issued: it was registered again, or its state no longer calls for
|
|
// the mail (for example the address is verified already).
|
|
DeliveryCancelAccountNotCurrent DeliveryCancelReason = "account_not_current"
|
|
// DeliveryCancelRecipientMismatch: the address stored with the delivery is
|
|
// no longer the address of the account.
|
|
DeliveryCancelRecipientMismatch DeliveryCancelReason = "recipient_mismatch"
|
|
// DeliveryCancelContentInvalid: the stored message is one that no
|
|
// transport accepts, so retrying cannot help.
|
|
DeliveryCancelContentInvalid DeliveryCancelReason = "content_invalid"
|
|
// DeliveryCancelProcessingFailed: the sending worker failed on this row
|
|
// again and again for a reason of its own, so it stopped trying and left
|
|
// the row to an operator.
|
|
DeliveryCancelProcessingFailed DeliveryCancelReason = "processing_failed"
|
|
// DeliveryCancelRightsRevoked: a notification's basis no longer holds
|
|
// when it is about to be sent. The organization is hidden from the
|
|
// candidate, the candidate withdrew publication (C2), or the invitation
|
|
// was answered, expired, or passed its deadline (see
|
|
// Delivery.CheckInvitationNotice).
|
|
DeliveryCancelRightsRevoked DeliveryCancelReason = "rights_revoked"
|
|
// DeliveryCancelRecipientIneligible: the recipient account is gone or its
|
|
// address is not verified, so a notification may not go to it.
|
|
DeliveryCancelRecipientIneligible DeliveryCancelReason = "recipient_ineligible"
|
|
// DeliveryCancelSourceClosed: the record a notification is about does not
|
|
// exist, belongs to another organization, or the notification names no
|
|
// record at all, so there is no right to check.
|
|
DeliveryCancelSourceClosed DeliveryCancelReason = "source_closed"
|
|
)
|
|
|
|
// DeliveryCancelReasons lists every cancel reason, for metrics that expose
|
|
// their series at zero.
|
|
func DeliveryCancelReasons() []DeliveryCancelReason {
|
|
return []DeliveryCancelReason{
|
|
DeliveryCancelTokenMissing, DeliveryCancelTokenPurposeMismatch, DeliveryCancelTokenOwnerMismatch,
|
|
DeliveryCancelTokenConsumed, DeliveryCancelTokenRevoked, DeliveryCancelTokenExpired,
|
|
DeliveryCancelAccountNotCurrent, DeliveryCancelRecipientMismatch, DeliveryCancelContentInvalid,
|
|
DeliveryCancelProcessingFailed, DeliveryCancelRightsRevoked, DeliveryCancelRecipientIneligible,
|
|
DeliveryCancelSourceClosed,
|
|
}
|
|
}
|
|
|
|
// ParseDeliveryCancelReason accepts a known reason.
|
|
func ParseDeliveryCancelReason(value string) (DeliveryCancelReason, error) {
|
|
switch reason := DeliveryCancelReason(value); reason {
|
|
case DeliveryCancelTokenMissing, DeliveryCancelTokenPurposeMismatch, DeliveryCancelTokenOwnerMismatch,
|
|
DeliveryCancelTokenConsumed, DeliveryCancelTokenRevoked, DeliveryCancelTokenExpired,
|
|
DeliveryCancelAccountNotCurrent, DeliveryCancelRecipientMismatch, DeliveryCancelContentInvalid,
|
|
DeliveryCancelProcessingFailed, DeliveryCancelRightsRevoked, DeliveryCancelRecipientIneligible,
|
|
DeliveryCancelSourceClosed:
|
|
return reason, nil
|
|
default:
|
|
return "", invalidDelivery("domain.ParseDeliveryCancelReason", "unknown cancel reason")
|
|
}
|
|
}
|
|
|
|
// 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
|
|
subject MailSubject
|
|
providerAccount MailProviderAccount
|
|
idempotencyKey string
|
|
status DeliveryStatus
|
|
attemptCount int32
|
|
nextAttemptAt time.Time
|
|
lastAttemptAt time.Time
|
|
providerMessageID string
|
|
emailTokenID uuid.UUID
|
|
cancelReason DeliveryCancelReason
|
|
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
|
|
// EmailTokenID is the token whose link the content carries. Set it for a
|
|
// kind that CarriesBearerToken, so the sending worker can check the token
|
|
// before it sends; a delivery of such a kind without it is cancelled by
|
|
// the worker with the reason token_missing. It must be uuid.Nil for a
|
|
// notification.
|
|
EmailTokenID uuid.UUID
|
|
// Subject names the record a notification is about; the sending worker
|
|
// checks its rights before the send. Only a notification may name one, and
|
|
// the zero value names none.
|
|
Subject MailSubject
|
|
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")
|
|
case input.EmailTokenID != uuid.Nil && !input.Content.Kind().CarriesBearerToken():
|
|
return Delivery{}, invalidDelivery(location, "only a delivery of a token kind is bound to a token")
|
|
case !input.Subject.IsZero() && input.Content.Kind() != MailKindNotification:
|
|
return Delivery{}, invalidDelivery(location, "only a notification names a subject")
|
|
}
|
|
return Delivery{
|
|
id: input.ID,
|
|
sourceEventID: input.SourceEventID,
|
|
recipientUserID: input.RecipientUserID,
|
|
recipient: input.Recipient,
|
|
content: input.Content,
|
|
subject: input.Subject,
|
|
providerAccount: input.ProviderAccount,
|
|
emailTokenID: input.EmailTokenID,
|
|
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
|
|
// EmailTokenID is uuid.Nil for a delivery without a token binding.
|
|
EmailTokenID uuid.UUID
|
|
// CancelReason is set exactly for a cancelled delivery.
|
|
CancelReason DeliveryCancelReason
|
|
// Subject is the zero value for a delivery without a subject.
|
|
Subject MailSubject
|
|
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)
|
|
}
|
|
if err := checkStoredFields(location, snapshot); err != nil {
|
|
return Delivery{}, err
|
|
}
|
|
if err := checkCancellationAndBinding(location, snapshot); err != nil {
|
|
return Delivery{}, err
|
|
}
|
|
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,
|
|
subject: snapshot.Subject,
|
|
providerAccount: snapshot.ProviderAccount,
|
|
idempotencyKey: snapshot.IdempotencyKey,
|
|
status: snapshot.Status,
|
|
attemptCount: snapshot.AttemptCount,
|
|
nextAttemptAt: snapshot.NextAttemptAt,
|
|
lastAttemptAt: snapshot.LastAttemptAt,
|
|
providerMessageID: snapshot.ProviderMessageID,
|
|
emailTokenID: snapshot.EmailTokenID,
|
|
cancelReason: snapshot.CancelReason,
|
|
version: snapshot.Version,
|
|
createdAt: snapshot.CreatedAt,
|
|
updatedAt: snapshot.UpdatedAt,
|
|
}, nil
|
|
}
|
|
|
|
// checkStoredFields checks the invariants of a stored row that do not
|
|
// depend on its cancellation or token binding.
|
|
func checkStoredFields(location string, snapshot DeliverySnapshot) error {
|
|
switch {
|
|
case snapshot.ID == uuid.Nil || snapshot.RecipientUserID == uuid.Nil:
|
|
return invalidDelivery(location, "delivery and recipient user IDs must not be nil")
|
|
case snapshot.Content.IsZero() || snapshot.ProviderAccount.IsZero():
|
|
return invalidDelivery(location, "content and provider account must be set")
|
|
case !idempotencyKeyPattern.MatchString(snapshot.IdempotencyKey):
|
|
return invalidDelivery(location, "idempotency key must have 1 to 256 printable ASCII characters")
|
|
case snapshot.Version <= 0 || snapshot.AttemptCount < 0:
|
|
return invalidDelivery(location, "version must be positive and the attempt count not negative")
|
|
case snapshot.CreatedAt.IsZero() || snapshot.UpdatedAt.Before(snapshot.CreatedAt):
|
|
return invalidDelivery(location, "update time must not precede the creation time")
|
|
case (snapshot.AttemptCount == 0) != snapshot.LastAttemptAt.IsZero():
|
|
return invalidDelivery(location, "last attempt time must be set exactly when an attempt was made")
|
|
case (snapshot.Status == DeliveryStatusAccepted) != (snapshot.ProviderMessageID != ""):
|
|
return invalidDelivery(location, "provider message ID must be set exactly for an accepted delivery")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// checkCancellationAndBinding checks the cancel reason and the token binding
|
|
// of a stored row. A token kind may lack its binding (rows older than the
|
|
// binding), and the sending worker cancels it; a notification never has one.
|
|
func checkCancellationAndBinding(location string, snapshot DeliverySnapshot) error {
|
|
switch {
|
|
case (snapshot.Status == DeliveryStatusCancelled) != (snapshot.CancelReason != ""):
|
|
return invalidDelivery(location, "cancel reason must be set exactly for a cancelled delivery")
|
|
case snapshot.EmailTokenID != uuid.Nil && !snapshot.Content.Kind().CarriesBearerToken():
|
|
return invalidDelivery(location, "only a delivery of a token kind is bound to a token")
|
|
case !snapshot.Subject.IsZero() && snapshot.Content.Kind() != MailKindNotification:
|
|
return invalidDelivery(location, "only a notification names a subject")
|
|
}
|
|
if snapshot.CancelReason != "" {
|
|
if _, err := ParseDeliveryCancelReason(string(snapshot.CancelReason)); err != nil {
|
|
return fmt.Errorf("%s - restore cancel reason: %w", location, err)
|
|
}
|
|
}
|
|
return 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 }
|
|
|
|
// Subject is the record a notification is about; zero for other deliveries.
|
|
func (delivery Delivery) Subject() MailSubject { return delivery.subject }
|
|
|
|
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 }
|
|
|
|
// EmailTokenID is the token the content's link carries, or uuid.Nil.
|
|
func (delivery Delivery) EmailTokenID() uuid.UUID { return delivery.emailTokenID }
|
|
|
|
// CancelReason says why a cancelled delivery was not sent; empty for any
|
|
// other status.
|
|
func (delivery Delivery) CancelReason() DeliveryCancelReason { return delivery.cancelReason }
|
|
|
|
// Version is the optimistic concurrency version, advanced by every change.
|
|
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
|
|
}
|
|
|
|
// Cancel ends a pending or waiting_quota delivery without an attempt: the
|
|
// message must not be sent, for the given reason. at is the decision time.
|
|
// It returns the next state with the next version and no next attempt; no
|
|
// attempt record is written, because the message is not sent. An unknown
|
|
// delivery is refused like in WaitForQuota: an earlier attempt may have been
|
|
// accepted, so it must not be reported as not sent. The terminal statuses are
|
|
// refused as well.
|
|
func (delivery Delivery) Cancel(at time.Time, reason DeliveryCancelReason) (Delivery, error) {
|
|
const location = "Delivery.Cancel"
|
|
if err := delivery.checkChangeTime(location, at); err != nil {
|
|
return Delivery{}, err
|
|
}
|
|
if _, err := ParseDeliveryCancelReason(string(reason)); err != nil {
|
|
return Delivery{}, fmt.Errorf("%s - %w", location, err)
|
|
}
|
|
if delivery.status != DeliveryStatusPending && delivery.status != DeliveryStatusWaitingQuota {
|
|
return Delivery{}, fmt.Errorf("%s - delivery is %s: %w", location, delivery.status, ErrDeliveryTransition)
|
|
}
|
|
next := delivery
|
|
next.status = DeliveryStatusCancelled
|
|
next.cancelReason = reason
|
|
next.nextAttemptAt = time.Time{}
|
|
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
|
|
}
|
|
|
|
// StopAutomaticRetry ends the automatic retry schedule without claiming that
|
|
// an uncertain delivery was not sent. The delivery remains unknown, with no
|
|
// due time, so only an audited operator decision can start another send cycle.
|
|
// It also accepts pending or waiting_quota when a later confirmed refusal
|
|
// leaves an earlier unknown outcome unresolved after the automatic cutoff.
|
|
func (delivery Delivery) StopAutomaticRetry(at time.Time) (Delivery, error) {
|
|
const location = "Delivery.StopAutomaticRetry"
|
|
if err := delivery.checkChangeTime(location, at); err != nil {
|
|
return Delivery{}, err
|
|
}
|
|
if (delivery.status != DeliveryStatusUnknown && delivery.status != DeliveryStatusPending && delivery.status != DeliveryStatusWaitingQuota) || delivery.nextAttemptAt.IsZero() {
|
|
return Delivery{}, fmt.Errorf("%s - delivery is %s without a scheduled retry: %w", location, delivery.status, ErrDeliveryTransition)
|
|
}
|
|
next := delivery
|
|
next.status = DeliveryStatusUnknown
|
|
next.nextAttemptAt = time.Time{}
|
|
next.version = delivery.version + 1
|
|
next.updatedAt = at
|
|
return next, nil
|
|
}
|
|
|
|
// ScheduleUnknownRetry keeps an unknown delivery in the due queue until a
|
|
// provider quota reset. It does not change the outcome or append an attempt.
|
|
func (delivery Delivery) ScheduleUnknownRetry(at, nextAttemptAt time.Time) (Delivery, error) {
|
|
const location = "Delivery.ScheduleUnknownRetry"
|
|
if err := delivery.checkChangeTime(location, at); err != nil {
|
|
return Delivery{}, err
|
|
}
|
|
if delivery.status != DeliveryStatusUnknown || delivery.nextAttemptAt.IsZero() {
|
|
return Delivery{}, fmt.Errorf("%s - delivery is %s without an automatic retry: %w", location, delivery.status, ErrDeliveryTransition)
|
|
}
|
|
if nextAttemptAt.IsZero() || nextAttemptAt.Before(at) {
|
|
return Delivery{}, invalidDelivery(location, "next retry time must be set and not precede the decision")
|
|
}
|
|
next := delivery
|
|
next.nextAttemptAt = nextAttemptAt
|
|
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),
|
|
)
|
|
}
|