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/". 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), ) }