feat(mail): send service identity mail through a leased worker

This commit is contained in:
shira committed 2026-10-06 21:08:11 +03:00
1 parent 204c6bae62
commit d21fd49a42
58 files changed
+7577 -164

No files matched your search

+182 -27
View File
@@ -23,9 +23,9 @@ var (
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.
// 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
@@ -47,14 +47,19 @@ var (
// Transitions:
//
// pending, waiting_quota, unknown --RecordAttempt--> accepted | rejected | pending | waiting_quota | unknown
// accepted, rejected --RecordAttempt--> refused (ErrDeliveryTransition)
// 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 (
@@ -62,7 +67,8 @@ const (
// 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.
// 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.
@@ -77,12 +83,17 @@ const (
// 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:
case DeliveryStatusPending, DeliveryStatusAccepted, DeliveryStatusRejected, DeliveryStatusUnknown,
DeliveryStatusWaitingQuota, DeliveryStatusCancelled:
return status, nil
default:
return "", invalidDelivery("domain.ParseDeliveryStatus", "unknown delivery status")
@@ -91,7 +102,7 @@ func ParseDeliveryStatus(value string) (DeliveryStatus, error) {
// IsTerminal reports a status that accepts no further attempt.
func (status DeliveryStatus) IsTerminal() bool {
return status == DeliveryStatusAccepted || status == DeliveryStatusRejected
return status == DeliveryStatusAccepted || status == DeliveryStatusRejected || status == DeliveryStatusCancelled
}
// requiresNextAttempt reports a status that the sending worker picks up again
@@ -122,6 +133,69 @@ const (
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"
)
// 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,
}
}
// 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:
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
@@ -172,6 +246,8 @@ type Delivery struct {
nextAttemptAt time.Time
lastAttemptAt time.Time
providerMessageID string
emailTokenID uuid.UUID
cancelReason DeliveryCancelReason
version int64
createdAt time.Time
updatedAt time.Time
@@ -189,7 +265,13 @@ type NewDeliveryInput struct {
Recipient EmailAddress
Content MailContent
ProviderAccount MailProviderAccount
CreatedAt time.Time
// 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
CreatedAt time.Time
}
// NewDelivery validates input and returns a pending delivery that is due at
@@ -209,6 +291,8 @@ func NewDelivery(input NewDeliveryInput) (Delivery, error) {
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")
}
return Delivery{
id: input.ID,
@@ -217,6 +301,7 @@ func NewDelivery(input NewDeliveryInput) (Delivery, error) {
recipient: input.Recipient,
content: input.Content,
providerAccount: input.ProviderAccount,
emailTokenID: input.EmailTokenID,
idempotencyKey: deliveryIdempotencyKeyPrefix + input.ID.String(),
status: DeliveryStatusPending,
nextAttemptAt: input.CreatedAt,
@@ -240,9 +325,13 @@ type DeliverySnapshot struct {
NextAttemptAt time.Time
LastAttemptAt time.Time
ProviderMessageID string
Version int64
CreatedAt time.Time
UpdatedAt time.Time
// EmailTokenID is uuid.Nil for a delivery without a token binding.
EmailTokenID uuid.UUID
// CancelReason is set exactly for a cancelled delivery.
CancelReason DeliveryCancelReason
Version int64
CreatedAt time.Time
UpdatedAt time.Time
}
// RestoreDelivery rebuilds a stored delivery and checks the invariants that
@@ -258,21 +347,11 @@ func RestoreDelivery(snapshot DeliverySnapshot) (Delivery, error) {
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 := 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
@@ -290,12 +369,54 @@ func RestoreDelivery(snapshot DeliverySnapshot) (Delivery, error) {
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")
}
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():
@@ -343,7 +464,14 @@ func (delivery Delivery) LastAttemptAt() time.Time { return delivery.lastAttempt
// 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.
// 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 }
@@ -462,6 +590,33 @@ func (delivery Delivery) WaitForQuota(at, until time.Time) (Delivery, error) {
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