feat(mail): send service identity mail through a leased worker
This commit is contained in:
1 parent
204c6bae62
commit
d21fd49a42
58 files changed
+7577
-164
No files matched your search
@@ -23,9 +23,13 @@ import (
|
||||
// time is not known yet";
|
||||
// - pending and unknown: "your email is being sent". unknown is not shown
|
||||
// as a failure: the message may have been accepted;
|
||||
// - accepted: "your email was sent". It means that the provider accepted
|
||||
// it, not that it reached the inbox;
|
||||
// - rejected: "your email could not be sent".
|
||||
// - accepted: "your email was handed to the email provider, which
|
||||
// accepted it". It is acceptance by the provider, not delivery to the
|
||||
// person: nothing confirms that it reached the inbox, and the text must
|
||||
// not say so;
|
||||
// - rejected: "your email could not be sent";
|
||||
// - cancelled: "your email was not sent because its link is no longer
|
||||
// valid; request a new one".
|
||||
type UserDeliveryStatus struct {
|
||||
Kind domain.MailKind
|
||||
Status domain.DeliveryStatus
|
||||
|
||||
@@ -6,8 +6,13 @@
|
||||
// DeliveryHandler consumes the event and, in the transaction of the
|
||||
// consumer's dedup marker, reads the request, resolves the recipient address
|
||||
// from the account, renders the current template version once, stores the
|
||||
// Delivery, and deletes the request. Sending the stored content is the job
|
||||
// of the delivery worker, which is planned.
|
||||
// Delivery, and deletes the request. Sending notifications is planned
|
||||
// (TASK-462); no worker claims them yet.
|
||||
//
|
||||
// Service mail of the account flows (email verification and password reset)
|
||||
// takes a shorter path: ServiceMailer stores its delivery directly in the
|
||||
// transaction that issues the token, bound to that token, and
|
||||
// ServiceMailSender (service_sender.go) claims, checks, and sends it.
|
||||
package notification
|
||||
|
||||
import (
|
||||
@@ -51,6 +56,13 @@ type NotificationRenderer interface {
|
||||
RenderNotification(data mailtemplate.NotificationData) (domain.MailContent, error)
|
||||
}
|
||||
|
||||
// ServiceMailRenderer renders the service mail of the account flows, which
|
||||
// carry a one-time token in their link, as the content a delivery stores.
|
||||
type ServiceMailRenderer interface {
|
||||
RenderVerification(data mailtemplate.VerificationData) (domain.MailContent, error)
|
||||
RenderPasswordReset(data mailtemplate.PasswordResetData) (domain.MailContent, error)
|
||||
}
|
||||
|
||||
// TemplateRenderer renders with the current versions of the embedded mail
|
||||
// templates.
|
||||
type TemplateRenderer struct {
|
||||
@@ -73,6 +85,30 @@ func (renderer TemplateRenderer) RenderNotification(data mailtemplate.Notificati
|
||||
return content, nil
|
||||
}
|
||||
|
||||
func (renderer TemplateRenderer) RenderVerification(data mailtemplate.VerificationData) (domain.MailContent, error) {
|
||||
rendered, err := renderer.renderer.RenderVerification(data)
|
||||
if err != nil {
|
||||
return domain.MailContent{}, fmt.Errorf("TemplateRenderer.RenderVerification - render: %w", err)
|
||||
}
|
||||
content, err := rendered.Content()
|
||||
if err != nil {
|
||||
return domain.MailContent{}, fmt.Errorf("TemplateRenderer.RenderVerification - convert rendering: %w", err)
|
||||
}
|
||||
return content, nil
|
||||
}
|
||||
|
||||
func (renderer TemplateRenderer) RenderPasswordReset(data mailtemplate.PasswordResetData) (domain.MailContent, error) {
|
||||
rendered, err := renderer.renderer.RenderPasswordReset(data)
|
||||
if err != nil {
|
||||
return domain.MailContent{}, fmt.Errorf("TemplateRenderer.RenderPasswordReset - render: %w", err)
|
||||
}
|
||||
content, err := rendered.Content()
|
||||
if err != nil {
|
||||
return domain.MailContent{}, fmt.Errorf("TemplateRenderer.RenderPasswordReset - convert rendering: %w", err)
|
||||
}
|
||||
return content, nil
|
||||
}
|
||||
|
||||
// NotificationRequest asks for one notification mail to one account.
|
||||
type NotificationRequest struct {
|
||||
RecipientUserID uuid.UUID
|
||||
|
||||
@@ -40,8 +40,8 @@ var (
|
||||
// is used up: the delivery waits for the reset in waiting_quota, and an
|
||||
// operator may decide otherwise.
|
||||
//
|
||||
// The sending worker (TASK-016) uses it in two transactions around one
|
||||
// transport call:
|
||||
// The sending worker (ServiceMailSender, TASK-016) uses it in two
|
||||
// transactions around one transport call:
|
||||
//
|
||||
// 1. PrepareSend in the transaction that claims a due delivery. It either
|
||||
// returns a permit, or parks the delivery in waiting_quota until the
|
||||
@@ -82,6 +82,9 @@ type QuotaPermit struct {
|
||||
reused bool
|
||||
}
|
||||
|
||||
// IdempotencyWindow returns the window the gate was built with.
|
||||
func (gate *QuotaGate) IdempotencyWindow() time.Duration { return gate.idempotencyWindow }
|
||||
|
||||
func (permit QuotaPermit) IsZero() bool { return permit.reservation.ID == uuid.Nil }
|
||||
|
||||
// Reused reports a permit that continues the open reservation of an earlier
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
package notification
|
||||
|
||||
import (
|
||||
"math/rand/v2"
|
||||
"time"
|
||||
)
|
||||
|
||||
// jitterShare is the share of a retry delay that jitter may add: up to a fifth,
|
||||
// so deliveries refused together do not all return in the same second, and
|
||||
// the wait never exceeds a fifth over the schedule.
|
||||
const jitterShare = 5
|
||||
|
||||
// RetryPolicy schedules the next attempt of a delivery whose last attempt the
|
||||
// provider refused for a reason that a later attempt may overcome
|
||||
// (temporary or rate_limited), and of a delivery on which the sending worker
|
||||
// itself failed. It is the minimum that the delivery state machine needs,
|
||||
// because a pending delivery must say when it is due; the attempt limit, the
|
||||
// unknown outcome policy, and manual retries belong to TASK-017.
|
||||
//
|
||||
// There is no limit on provider refusals on purpose: service mail carries a
|
||||
// token that expires, and the sending worker cancels the delivery with the
|
||||
// reason token_expired once it does, so those retries end by themselves.
|
||||
type RetryPolicy struct {
|
||||
// Initial is the wait after the first refused attempt; every further
|
||||
// refusal doubles it.
|
||||
Initial time.Duration
|
||||
// Max caps the doubling. A longer wait that the provider itself asked
|
||||
// for (Retry-After) is honored as it is.
|
||||
Max time.Duration
|
||||
// Jitter returns a value in [0, limit] that is added to the scheduled
|
||||
// delay, bounded by a fifth of it. Nil means none, which tests use to
|
||||
// get exact times; RandomJitter is the production source.
|
||||
Jitter func(limit time.Duration) time.Duration
|
||||
}
|
||||
|
||||
// RandomJitter is a uniformly random jitter source.
|
||||
func RandomJitter(limit time.Duration) time.Duration {
|
||||
if limit <= 0 {
|
||||
return 0
|
||||
}
|
||||
return rand.N(limit + 1) //nolint:gosec // Retry jitter needs no cryptographic randomness.
|
||||
}
|
||||
|
||||
// NextAttemptAt returns when the delivery is due again after attempt number
|
||||
// attempt (counted from 1) that ended at at. retryAfter is the provider's own
|
||||
// hint, zero when it gave none; the wait is never shorter than it.
|
||||
func (policy RetryPolicy) NextAttemptAt(at time.Time, attempt int32, retryAfter time.Duration) time.Time {
|
||||
delay := policy.Initial
|
||||
for step := int32(1); step < attempt && delay < policy.Max; step++ {
|
||||
delay = min(delay*2, policy.Max)
|
||||
}
|
||||
delay = min(delay, policy.Max)
|
||||
if policy.Jitter != nil {
|
||||
limit := delay / jitterShare
|
||||
delay += min(max(policy.Jitter(limit), 0), limit)
|
||||
}
|
||||
return at.Add(max(delay, retryAfter))
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
package notification
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
"lincodex/backend/internal/usecase/notification/mailtemplate"
|
||||
)
|
||||
|
||||
// TokenMailRequest asks for one service mail that carries a one-time token.
|
||||
//
|
||||
// The token record must be stored already, in the same transaction, because
|
||||
// the delivery is bound to it. RawToken is the secret that goes into the link
|
||||
// of the message; it exists only in memory and is stored nowhere except in
|
||||
// the rendered body, which the delivery keeps until the mail is sent or
|
||||
// cancelled.
|
||||
type TokenMailRequest struct {
|
||||
// Recipient is the address of the account now; the delivery keeps it as
|
||||
// the address to send to, and the worker compares it with the account
|
||||
// again before it sends.
|
||||
Recipient domain.EmailAddress
|
||||
Token domain.EmailToken
|
||||
RawToken domain.SecretToken
|
||||
// Lifetime is the validity of the token that the message states, in
|
||||
// whole hours.
|
||||
Lifetime domain.Hours
|
||||
}
|
||||
|
||||
// ServiceMailer stores service mail of the account flows (email verification
|
||||
// and password reset) as deliveries, in the transaction that issues the
|
||||
// token. No event or request row carries the token: the rendered body goes
|
||||
// straight into the delivery, which the account's deletion removes by
|
||||
// cascade.
|
||||
//
|
||||
// Service mail needs no consent of any purpose. It is part of the account
|
||||
// flow, not a product notification, so nothing here reads the consent
|
||||
// ledger; the worker checks the token and the account instead (see
|
||||
// ServiceMailSender).
|
||||
type ServiceMailer struct {
|
||||
renderer ServiceMailRenderer
|
||||
account domain.MailProviderAccount
|
||||
clock func() time.Time
|
||||
}
|
||||
|
||||
// NewServiceMailer pins new deliveries to account, the transport and account
|
||||
// configured when the mail is requested. clock is the application clock for
|
||||
// the creation time.
|
||||
func NewServiceMailer(renderer ServiceMailRenderer, account domain.MailProviderAccount, clock func() time.Time) *ServiceMailer {
|
||||
return &ServiceMailer{renderer: renderer, account: account, clock: clock}
|
||||
}
|
||||
|
||||
// EnqueueVerification stores the email verification message for request.Token
|
||||
// through unit, which must be the caller's transaction, and returns the
|
||||
// delivery ID. The delivery ID is the token ID, so repeating the call for
|
||||
// the same token stores nothing new. The mail is sent only if the
|
||||
// transaction commits and the token is still current when the worker gets
|
||||
// to it.
|
||||
func (mailer *ServiceMailer) EnqueueVerification(ctx context.Context, unit outbound.UnitOfWork, request TokenMailRequest) (uuid.UUID, error) {
|
||||
const location = "ServiceMailer.EnqueueVerification"
|
||||
if err := checkTokenMailRequest(location, request, domain.EmailTokenPurposeEmailVerification); err != nil {
|
||||
return uuid.Nil, err
|
||||
}
|
||||
content, err := mailer.renderer.RenderVerification(mailtemplate.VerificationData{Token: request.RawToken, TokenLifetime: request.Lifetime})
|
||||
if err != nil {
|
||||
return uuid.Nil, fmt.Errorf("%s - render message: %w", location, err)
|
||||
}
|
||||
return mailer.store(ctx, unit, location, request, content)
|
||||
}
|
||||
|
||||
// EnqueuePasswordReset stores the password reset message for request.Token;
|
||||
// see EnqueueVerification.
|
||||
func (mailer *ServiceMailer) EnqueuePasswordReset(ctx context.Context, unit outbound.UnitOfWork, request TokenMailRequest) (uuid.UUID, error) {
|
||||
const location = "ServiceMailer.EnqueuePasswordReset"
|
||||
if err := checkTokenMailRequest(location, request, domain.EmailTokenPurposePasswordReset); err != nil {
|
||||
return uuid.Nil, err
|
||||
}
|
||||
content, err := mailer.renderer.RenderPasswordReset(mailtemplate.PasswordResetData{Token: request.RawToken, TokenLifetime: request.Lifetime})
|
||||
if err != nil {
|
||||
return uuid.Nil, fmt.Errorf("%s - render message: %w", location, err)
|
||||
}
|
||||
return mailer.store(ctx, unit, location, request, content)
|
||||
}
|
||||
|
||||
func (mailer *ServiceMailer) store(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
location string,
|
||||
request TokenMailRequest,
|
||||
content domain.MailContent,
|
||||
) (uuid.UUID, error) {
|
||||
delivery, err := domain.NewDelivery(domain.NewDeliveryInput{
|
||||
ID: request.Token.ID,
|
||||
RecipientUserID: request.Token.UserID,
|
||||
Recipient: request.Recipient,
|
||||
Content: content,
|
||||
ProviderAccount: mailer.account,
|
||||
EmailTokenID: request.Token.ID,
|
||||
CreatedAt: mailer.clock(),
|
||||
})
|
||||
if err != nil {
|
||||
return uuid.Nil, fmt.Errorf("%s - build delivery: %w", location, err)
|
||||
}
|
||||
created, err := unit.Deliveries().Create(ctx, delivery)
|
||||
if err != nil {
|
||||
return uuid.Nil, fmt.Errorf("%s - store delivery: %w", location, err)
|
||||
}
|
||||
if !created {
|
||||
// The same token was enqueued before; the stored message stays as it
|
||||
// is, because a retry under the same idempotency key must repeat the
|
||||
// same body.
|
||||
existing, err := unit.Deliveries().Get(ctx, request.Token.ID)
|
||||
if err != nil {
|
||||
return uuid.Nil, fmt.Errorf("%s - read existing delivery: %w", location, err)
|
||||
}
|
||||
if existing.RecipientUserID() != request.Token.UserID || existing.Kind() != content.Kind() {
|
||||
return uuid.Nil, fmt.Errorf("%s - a delivery for another recipient or kind has the token ID: %w", location, domain.ErrInvalidDelivery)
|
||||
}
|
||||
}
|
||||
return request.Token.ID, nil
|
||||
}
|
||||
|
||||
// checkTokenMailRequest refuses a request whose token is not of the purpose
|
||||
// the message needs or has no ID, before anything is rendered.
|
||||
func checkTokenMailRequest(location string, request TokenMailRequest, purpose domain.EmailTokenPurpose) error {
|
||||
switch {
|
||||
case request.Token.ID == uuid.Nil || request.Token.UserID == uuid.Nil:
|
||||
return fmt.Errorf("%s - token must be built by domain.NewEmailToken: %w", location, domain.ErrInvalidEmailToken)
|
||||
case request.Token.Purpose != purpose:
|
||||
return fmt.Errorf("%s - token purpose does not match the message: %w", location, domain.ErrInvalidEmailToken)
|
||||
case request.RawToken.IsZero():
|
||||
return fmt.Errorf("%s - raw token must be set: %w", location, domain.ErrInvalidEmailToken)
|
||||
case request.Recipient.IsZero():
|
||||
return fmt.Errorf("%s - recipient must be set: %w", location, domain.ErrInvalidDelivery)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
package notification
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/usecase/notification/mailtemplate"
|
||||
)
|
||||
|
||||
type serviceMailHarness struct {
|
||||
mailer *ServiceMailer
|
||||
unit fakeUnit
|
||||
user uuid.UUID
|
||||
}
|
||||
|
||||
func newServiceMailHarness(t *testing.T) *serviceMailHarness {
|
||||
t.Helper()
|
||||
renderer, err := mailtemplate.NewRenderer(testOrigin)
|
||||
if err != nil {
|
||||
t.Fatalf("NewRenderer() error = %v", err)
|
||||
}
|
||||
return &serviceMailHarness{
|
||||
mailer: NewServiceMailer(NewTemplateRenderer(renderer), testAccount(t, "resend"), func() time.Time { return testNow }),
|
||||
unit: fakeUnit{deliveries: &fakeDeliveries{stored: make(map[uuid.UUID]domain.Delivery)}},
|
||||
user: uuid.MustParse("01926f3a-7c00-7000-8000-0000000000bb"),
|
||||
}
|
||||
}
|
||||
|
||||
func (h *serviceMailHarness) request(t *testing.T, purpose domain.EmailTokenPurpose) TokenMailRequest {
|
||||
t.Helper()
|
||||
raw, err := domain.NewSecretToken()
|
||||
if err != nil {
|
||||
t.Fatalf("NewSecretToken() error = %v", err)
|
||||
}
|
||||
token, err := domain.NewEmailToken(domain.NewEmailTokenInput{
|
||||
UserID: h.user, Purpose: purpose, TokenHash: raw.Hash(), RegistrationVersion: 1, IssuedAt: testNow, Lifetime: 24 * time.Hour,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewEmailToken() error = %v", err)
|
||||
}
|
||||
recipient, err := domain.NewEmailAddress(testRecipientAddress)
|
||||
if err != nil {
|
||||
t.Fatalf("NewEmailAddress() error = %v", err)
|
||||
}
|
||||
return TokenMailRequest{Recipient: recipient, Token: token, RawToken: raw, Lifetime: 24}
|
||||
}
|
||||
|
||||
func TestServiceMailerStoresATokenBoundDeliveryUnderTheTokenID(t *testing.T) {
|
||||
h := newServiceMailHarness(t)
|
||||
for name, test := range map[string]struct {
|
||||
purpose domain.EmailTokenPurpose
|
||||
enqueue func(*ServiceMailer, TokenMailRequest) (uuid.UUID, error)
|
||||
kind domain.MailKind
|
||||
path string
|
||||
}{
|
||||
"verification": {domain.EmailTokenPurposeEmailVerification, func(mailer *ServiceMailer, request TokenMailRequest) (uuid.UUID, error) {
|
||||
return mailer.EnqueueVerification(t.Context(), h.unit, request)
|
||||
}, domain.MailKindVerification, "/verify-email"},
|
||||
"password reset": {domain.EmailTokenPurposePasswordReset, func(mailer *ServiceMailer, request TokenMailRequest) (uuid.UUID, error) {
|
||||
return mailer.EnqueuePasswordReset(t.Context(), h.unit, request)
|
||||
}, domain.MailKindPasswordReset, "/reset-password"},
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
request := h.request(t, test.purpose)
|
||||
id, err := test.enqueue(h.mailer, request)
|
||||
if err != nil {
|
||||
t.Fatalf("enqueue error = %v", err)
|
||||
}
|
||||
if id != request.Token.ID {
|
||||
t.Fatalf("delivery ID = %s, want the token ID %s", id, request.Token.ID)
|
||||
}
|
||||
stored := h.unit.deliveries.stored[id]
|
||||
switch {
|
||||
case stored.Kind() != test.kind || stored.EmailTokenID() != request.Token.ID:
|
||||
t.Fatalf("delivery is %s bound to %s", stored.Kind(), stored.EmailTokenID())
|
||||
case stored.Status() != domain.DeliveryStatusPending || !stored.NextAttemptAt().Equal(testNow):
|
||||
t.Fatalf("delivery is %s due %s, want pending and due now", stored.Status(), stored.NextAttemptAt())
|
||||
case stored.RecipientUserID() != h.user || stored.ProviderAccount() != testAccount(t, "resend"):
|
||||
t.Fatal("the delivery is not addressed to the token's account on the configured provider account")
|
||||
}
|
||||
// The token travels in the fragment of the link, never in the
|
||||
// path or the query, where an access log would record it.
|
||||
link := testOrigin + test.path + "#token=" + request.RawToken.Reveal()
|
||||
if !strings.Contains(stored.Content().Text(), link) || !strings.Contains(stored.Content().HTML(), link) {
|
||||
t.Fatal("the stored message lacks the link with the token in its fragment")
|
||||
}
|
||||
if strings.Contains(stored.Content().Text(), "?token=") || strings.Contains(stored.Content().Text(), test.path+"/") {
|
||||
t.Fatal("the token is outside the fragment")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestServiceMailerRepeatsAreHarmless(t *testing.T) {
|
||||
h := newServiceMailHarness(t)
|
||||
request := h.request(t, domain.EmailTokenPurposeEmailVerification)
|
||||
first, err := h.mailer.EnqueueVerification(t.Context(), h.unit, request)
|
||||
if err != nil {
|
||||
t.Fatalf("first EnqueueVerification() error = %v", err)
|
||||
}
|
||||
second, err := h.mailer.EnqueueVerification(t.Context(), h.unit, request)
|
||||
if err != nil || second != first || len(h.unit.deliveries.stored) != 1 {
|
||||
t.Fatalf("second EnqueueVerification() = %s, %v with %d deliveries; want the same delivery", second, err, len(h.unit.deliveries.stored))
|
||||
}
|
||||
}
|
||||
|
||||
func TestServiceMailerRefusesAWrongTokenBeforeRendering(t *testing.T) {
|
||||
h := newServiceMailHarness(t)
|
||||
reset := h.request(t, domain.EmailTokenPurposePasswordReset)
|
||||
if _, err := h.mailer.EnqueueVerification(t.Context(), h.unit, reset); !errors.Is(err, domain.ErrInvalidEmailToken) {
|
||||
t.Fatalf("EnqueueVerification(reset token) error = %v, want ErrInvalidEmailToken", err)
|
||||
}
|
||||
verification := h.request(t, domain.EmailTokenPurposeEmailVerification)
|
||||
if _, err := h.mailer.EnqueuePasswordReset(t.Context(), h.unit, verification); !errors.Is(err, domain.ErrInvalidEmailToken) {
|
||||
t.Fatalf("EnqueuePasswordReset(verification token) error = %v, want ErrInvalidEmailToken", err)
|
||||
}
|
||||
for name, change := range map[string]func(*TokenMailRequest){
|
||||
"no token ID": func(request *TokenMailRequest) { request.Token = domain.EmailToken{} },
|
||||
"no raw token": func(request *TokenMailRequest) { request.RawToken = domain.SecretToken{} },
|
||||
"no recipient": func(request *TokenMailRequest) { request.Recipient = domain.EmailAddress{} },
|
||||
"zero lifetime": func(request *TokenMailRequest) { request.Lifetime = 0 },
|
||||
"lifetime >7d": func(request *TokenMailRequest) { request.Lifetime = 24 * 8 },
|
||||
} {
|
||||
request := h.request(t, domain.EmailTokenPurposeEmailVerification)
|
||||
change(&request)
|
||||
if _, err := h.mailer.EnqueueVerification(t.Context(), h.unit, request); err == nil {
|
||||
t.Fatalf("%s: EnqueueVerification() accepted the request", name)
|
||||
}
|
||||
}
|
||||
if len(h.unit.deliveries.stored) != 0 {
|
||||
t.Fatal("a refused request stored a delivery")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,725 @@
|
||||
package notification
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/inbound"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
const (
|
||||
// settleAttempts bounds how often the transaction that stores a send
|
||||
// result is repeated after a database failure. The provider answer lives
|
||||
// only in memory until it is stored, so one failure should not lose it.
|
||||
settleAttempts = 3
|
||||
// settleRetryDelay separates two attempts to store a send result.
|
||||
settleRetryDelay = 200 * time.Millisecond
|
||||
)
|
||||
|
||||
// dedupSafetyMargin is taken off the provider's idempotency window before it
|
||||
// is compared with the age of the first request: clocks of the provider and the
|
||||
// database differ a little, and a key about to expire is as good as expired.
|
||||
const dedupSafetyMargin = time.Hour
|
||||
|
||||
// errLeaseLost reports a result that another worker recorded first: the
|
||||
// settlement transaction is rolled back and nothing of this attempt is kept.
|
||||
var errLeaseLost = errors.New("delivery was recorded by another worker")
|
||||
|
||||
// ServiceMailSenderSettings are the named limits of the sending worker.
|
||||
type ServiceMailSenderSettings struct {
|
||||
// Account is the configured provider account. The sender claims only
|
||||
// deliveries pinned to it, and moves deliveries stored while no
|
||||
// transport ran onto it.
|
||||
Account domain.MailProviderAccount
|
||||
// RebindProvider is the provider name whose deliveries, before their
|
||||
// first attempt, are moved onto Account: the disabled transport. Empty
|
||||
// for none.
|
||||
RebindProvider string
|
||||
// Lease is how long a claimed delivery belongs to this sender, measured by
|
||||
// the database clock. Claim, the call, and the settlement all fit inside
|
||||
// it: the call is bounded by what is left of the lease after the claim and
|
||||
// the settlement budget.
|
||||
Lease time.Duration
|
||||
// StoreTimeout bounds the claim transaction, the check before the send,
|
||||
// and each try to store a result.
|
||||
StoreTimeout time.Duration
|
||||
// SettleBudget bounds the whole of storing a send result, retries
|
||||
// included; it is reserved inside the lease.
|
||||
SettleBudget time.Duration
|
||||
// ShutdownSettleBudget replaces SettleBudget when shutdown has begun, so
|
||||
// the process stops within its shutdown timeout.
|
||||
ShutdownSettleBudget time.Duration
|
||||
// MaxFailures is how many consecutive failures of the worker itself on one
|
||||
// delivery are retried before the delivery is cancelled with the reason
|
||||
// processing_failed.
|
||||
MaxFailures int32
|
||||
Retry RetryPolicy
|
||||
}
|
||||
|
||||
func (settings ServiceMailSenderSettings) validate() error {
|
||||
switch {
|
||||
case settings.Account.IsZero():
|
||||
return errors.New("notification.NewServiceMailSender - provider account must be set")
|
||||
case settings.Lease <= 0 || settings.StoreTimeout <= 0 || settings.SettleBudget <= 0 || settings.ShutdownSettleBudget <= 0 || settings.MaxFailures < 1:
|
||||
return errors.New("notification.NewServiceMailSender - lease, timeouts, and settle budgets must be positive and the failure limit at least 1")
|
||||
case settings.SettleBudget >= settings.Lease:
|
||||
return errors.New("notification.NewServiceMailSender - the settle budget must be shorter than the lease")
|
||||
case settings.Retry.Initial <= 0 || settings.Retry.Max < settings.Retry.Initial:
|
||||
return errors.New("notification.NewServiceMailSender - retry delays must be positive and the maximum not below the initial delay")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ServiceMailSender sends the service mail of the account flows (email
|
||||
// verification and password reset) that ServiceMailer stored. Several
|
||||
// senders may run against one database, in one process or many.
|
||||
//
|
||||
// One pass takes one delivery through three steps:
|
||||
//
|
||||
// 1. Claim transaction: ClaimDue leases the most overdue due delivery with
|
||||
// FOR UPDATE SKIP LOCKED, so no two senders hold the same one. The
|
||||
// token and the account are checked (domain.Delivery.CheckServiceMail);
|
||||
// a mail that must not go out is cancelled with a reason. Otherwise
|
||||
// QuotaGate.PrepareSend reserves the quota, or parks the delivery in
|
||||
// waiting_quota. The transaction commits before the transport is called,
|
||||
// so a slow provider never holds a row lock.
|
||||
// 2. One call to MailSender.Send with the stored content and the stable
|
||||
// idempotency key. The sender never retries: a failed attempt becomes the
|
||||
// delivery's next state and due time.
|
||||
// 3. Settlement transaction: QuotaGate.SettleSend and
|
||||
// DeliveryRepository.RecordAttempt in one transaction. The attempt is
|
||||
// recorded over the delivery's version, so of two senders that both
|
||||
// reached this step only the first is kept.
|
||||
//
|
||||
// A sender that stops after the claim leaves its lease to expire; another
|
||||
// sender then claims the delivery and calls the provider with the same
|
||||
// idempotency key, which the provider answers with the original result
|
||||
// instead of sending twice, and the quota gate reuses the open reservation.
|
||||
// Past the provider's idempotency window the earlier attempt is in doubt,
|
||||
// so the delivery is recorded as unknown instead of being sent again.
|
||||
//
|
||||
// Logs and results name a delivery only by its ID, never by address or
|
||||
// content.
|
||||
type ServiceMailSender struct {
|
||||
owner uuid.UUID
|
||||
// countingPaused stops counting failures of single rows; see
|
||||
// PauseFailureCounting.
|
||||
countingPaused atomic.Bool
|
||||
transactor outbound.Transactor
|
||||
sender outbound.MailSender
|
||||
gate *QuotaGate
|
||||
settings ServiceMailSenderSettings
|
||||
clock func() time.Time
|
||||
logger *slog.Logger
|
||||
}
|
||||
|
||||
// NewServiceMailSender builds a sender with a random lease owner ID. gate
|
||||
// must be built for settings.Account. clock is the application clock: due,
|
||||
// lease, and quota decisions use it, so tests move time with a fake one.
|
||||
func NewServiceMailSender(
|
||||
transactor outbound.Transactor,
|
||||
sender outbound.MailSender,
|
||||
gate *QuotaGate,
|
||||
settings ServiceMailSenderSettings,
|
||||
clock func() time.Time,
|
||||
logger *slog.Logger,
|
||||
) (*ServiceMailSender, error) {
|
||||
if err := settings.validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
owner := uuid.New()
|
||||
return &ServiceMailSender{
|
||||
owner: owner,
|
||||
transactor: transactor,
|
||||
sender: sender,
|
||||
gate: gate,
|
||||
settings: settings,
|
||||
clock: clock,
|
||||
logger: logger.With(slog.String("lease_owner", owner.String())),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// claimedSend is a delivery that passed the claim transaction and is ready to
|
||||
// be sent, or the final result of a delivery the transaction already decided.
|
||||
type claimedSend struct {
|
||||
delivery domain.Delivery
|
||||
permit QuotaPermit
|
||||
// decided is set when the claim transaction ended the pass: the result
|
||||
// is final and nothing is sent.
|
||||
decided bool
|
||||
result inbound.MailPassResult
|
||||
// failureCount is the number of consecutive failures of the worker on the
|
||||
// delivery before this pass.
|
||||
failureCount int32
|
||||
}
|
||||
|
||||
var _ inbound.MailPass = (*ServiceMailSender)(nil)
|
||||
|
||||
// PauseFailureCounting implements inbound.MailPass.
|
||||
func (sender *ServiceMailSender) PauseFailureCounting(paused bool) {
|
||||
sender.countingPaused.Store(paused)
|
||||
}
|
||||
|
||||
// isRowFault reports an error that the delivery itself causes and that
|
||||
// repeating cannot cure: it breaks a domain rule, cannot be restored, or is
|
||||
// refused by a data or integrity constraint. Every other error (a context that
|
||||
// ended, a timeout, a deadlock, a lost connection, a missing quota
|
||||
// configuration) says nothing about the row, so it is never counted against
|
||||
// it.
|
||||
func isRowFault(err error) bool {
|
||||
var unreadable *outbound.UnreadableDeliveryError
|
||||
return errors.As(err, &unreadable) ||
|
||||
errors.Is(err, domain.ErrInvalidDelivery) ||
|
||||
errors.Is(err, domain.ErrDeliveryTransition) ||
|
||||
errors.Is(err, domain.ErrInvalidMailContent) ||
|
||||
errors.Is(err, domain.ErrMailContentIntegrity) ||
|
||||
errors.Is(err, domain.ErrInvalidEmailAddress) ||
|
||||
errors.Is(err, outbound.ErrRowFault)
|
||||
}
|
||||
|
||||
// ProcessNext runs one pass. ctx ends the claim of new work; workCtx bounds
|
||||
// the transport call and should outlive ctx by a shutdown grace, so a send in
|
||||
// progress is not cut off at the first sign of shutdown. An error reports a
|
||||
// database failure; the delivery it concerned is left under its lease, which
|
||||
// expires, or was never claimed.
|
||||
func (sender *ServiceMailSender) ProcessNext(ctx, workCtx context.Context) (inbound.MailPassResult, error) {
|
||||
// The lease runs by the database clock from the claim, which is later
|
||||
// than this reading, so the budget below errs on the short side.
|
||||
started := time.Now()
|
||||
claim, err := sender.claim(ctx)
|
||||
if err != nil {
|
||||
return inbound.MailPassResult{}, fmt.Errorf("ServiceMailSender.ProcessNext - claim delivery: %w", err)
|
||||
}
|
||||
if claim.decided {
|
||||
return claim.result, nil
|
||||
}
|
||||
if decided, err := sender.beforeSend(workCtx, claim); err != nil || decided != nil {
|
||||
if err != nil {
|
||||
return inbound.MailPassResult{}, fmt.Errorf("ServiceMailSender.ProcessNext - check before sending: %w", err)
|
||||
}
|
||||
return *decided, nil
|
||||
}
|
||||
delivery := claim.delivery
|
||||
content := delivery.Content()
|
||||
// What is left of the lease after the claim and the reserve for storing
|
||||
// the answer is the most the call may take.
|
||||
callBudget := sender.settings.Lease - time.Since(started) - sender.settings.SettleBudget
|
||||
if callBudget <= 0 {
|
||||
return sender.releaseUnsent(ctx, claim)
|
||||
}
|
||||
sendCtx, cancel := context.WithTimeout(workCtx, callBudget)
|
||||
result, sendErr := sender.sender.Send(sendCtx, outbound.OutgoingMail{
|
||||
To: delivery.Recipient(),
|
||||
Subject: content.Subject(),
|
||||
TextBody: content.Text(),
|
||||
HTMLBody: content.HTML(),
|
||||
IdempotencyKey: delivery.IdempotencyKey(),
|
||||
})
|
||||
cancel()
|
||||
return sender.settle(ctx, claim, result, sendErr)
|
||||
}
|
||||
|
||||
// failingRow names a claimed delivery on which the claim transaction failed,
|
||||
// so a failure can be recorded for it outside that transaction.
|
||||
type failingRow struct {
|
||||
id uuid.UUID
|
||||
count int32
|
||||
}
|
||||
|
||||
func (sender *ServiceMailSender) claim(ctx context.Context) (claimedSend, error) {
|
||||
var claim claimedSend
|
||||
var failing *failingRow
|
||||
claimCtx, cancel := context.WithTimeout(ctx, sender.settings.StoreTimeout)
|
||||
defer cancel()
|
||||
err := sender.transactor.WithinTransaction(claimCtx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
now := sender.clock()
|
||||
claimed, err := unit.Deliveries().ClaimDue(ctx, outbound.DeliveryClaim{
|
||||
Owner: sender.owner,
|
||||
Account: sender.settings.Account,
|
||||
RebindProvider: sender.settings.RebindProvider,
|
||||
Kinds: domain.ServiceMailKinds(),
|
||||
Now: now,
|
||||
Lease: sender.settings.Lease,
|
||||
})
|
||||
if errors.Is(err, outbound.ErrNoDeliveryDue) {
|
||||
claim = claimedSend{decided: true, result: inbound.MailPassResult{Outcome: inbound.MailPassIdle}}
|
||||
return nil
|
||||
}
|
||||
var unreadable *outbound.UnreadableDeliveryError
|
||||
if errors.As(err, &unreadable) {
|
||||
if unreadable.Cancelled {
|
||||
// The store cancelled the broken row; committing keeps it
|
||||
// from blocking the queue. Its content is left as it is for
|
||||
// an operator.
|
||||
sender.logger.ErrorContext(ctx, "a due delivery does not match its content hash and was cancelled; an operator should inspect it",
|
||||
slog.String("delivery_id", unreadable.DeliveryID.String()),
|
||||
slog.String("reason", string(domain.DeliveryCancelContentInvalid)))
|
||||
claim = claimedSend{decided: true, result: inbound.MailPassResult{
|
||||
Outcome: inbound.MailPassCancelled,
|
||||
DeliveryID: unreadable.DeliveryID,
|
||||
CancelReason: domain.DeliveryCancelContentInvalid,
|
||||
}}
|
||||
return nil
|
||||
}
|
||||
failing = &failingRow{id: unreadable.DeliveryID, count: unreadable.FailureCount}
|
||||
return fmt.Errorf("claim due delivery: %w", err)
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("claim due delivery: %w", err)
|
||||
}
|
||||
failing = &failingRow{id: claimed.Delivery.ID(), count: claimed.FailureCount}
|
||||
claim, err = sender.prepare(ctx, unit, claimed, now)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
failing = nil
|
||||
claim.failureCount = claimed.FailureCount
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
// The transaction rolled back, and with it the lease: the same row
|
||||
// would be claimed again and fail again, and every delivery behind
|
||||
// it would wait. Record the failure in a transaction of its own so
|
||||
// the row moves back in the queue.
|
||||
if failing != nil && ctx.Err() == nil && isRowFault(err) {
|
||||
if result, recordErr := sender.recordRowFailure(ctx, *failing, err); recordErr == nil {
|
||||
return claimedSend{decided: true, result: result}, nil
|
||||
}
|
||||
}
|
||||
return claimedSend{}, err
|
||||
}
|
||||
return claim, nil
|
||||
}
|
||||
|
||||
// recordRowFailure counts a failure of the worker on a delivery in a short
|
||||
// transaction of its own and makes the row due later by the retry schedule;
|
||||
// after MaxFailures it cancels the row with processing_failed.
|
||||
func (sender *ServiceMailSender) recordRowFailure(ctx context.Context, failing failingRow, cause error) (inbound.MailPassResult, error) {
|
||||
var cancelled bool
|
||||
recordCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), sender.settings.StoreTimeout)
|
||||
defer cancel()
|
||||
err := sender.transactor.WithinTransaction(recordCtx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
now := sender.clock()
|
||||
var err error
|
||||
cancelled, err = unit.Deliveries().RecordFailure(ctx, failing.id, sender.owner, now,
|
||||
sender.settings.Retry.NextAttemptAt(now, failing.count+1, 0), sender.settings.MaxFailures, !sender.countingPaused.Load())
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return inbound.MailPassResult{}, fmt.Errorf("record failure: %w", err)
|
||||
}
|
||||
// The cause is a wrapped chain of rules and sentinels; it never quotes
|
||||
// the row.
|
||||
sender.logger.ErrorContext(ctx, "the sending worker failed on a delivery; it is retried later and cancelled after repeated failures",
|
||||
slog.String("delivery_id", failing.id.String()),
|
||||
slog.Int("consecutive_failures", int(failing.count)+1),
|
||||
slog.Bool("cancelled", cancelled),
|
||||
slog.Any("error", cause))
|
||||
if cancelled {
|
||||
return inbound.MailPassResult{Outcome: inbound.MailPassCancelled, DeliveryID: failing.id, CancelReason: domain.DeliveryCancelProcessingFailed}, nil
|
||||
}
|
||||
return inbound.MailPassResult{Outcome: inbound.MailPassRowFailed, DeliveryID: failing.id}, nil
|
||||
}
|
||||
|
||||
// beforeSend runs right before the transport is called: it takes the delivery
|
||||
// lock, reads the token and the account again, so a revocation after the claim
|
||||
// committed is honored, and notes the start of the first request. A mail that
|
||||
// is no longer valid is cancelled and its reservation given back.
|
||||
func (sender *ServiceMailSender) beforeSend(ctx context.Context, claim claimedSend) (*inbound.MailPassResult, error) {
|
||||
var decided *inbound.MailPassResult
|
||||
checkCtx, cancel := context.WithTimeout(ctx, sender.settings.StoreTimeout)
|
||||
defer cancel()
|
||||
err := sender.transactor.WithinTransaction(checkCtx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
delivery := claim.delivery
|
||||
held, err := unit.Deliveries().LockClaimed(ctx, delivery.ID(), sender.owner)
|
||||
if err != nil {
|
||||
return fmt.Errorf("lock delivery: %w", err)
|
||||
}
|
||||
if !held {
|
||||
result := resultOf(inbound.MailPassLeaseLost, delivery)
|
||||
decided = &result
|
||||
return nil
|
||||
}
|
||||
state, err := unit.Deliveries().ServiceMailState(ctx, delivery.ID())
|
||||
if err != nil {
|
||||
return fmt.Errorf("read token and account: %w", err)
|
||||
}
|
||||
now := sender.clock()
|
||||
if reason := delivery.CheckServiceMail(state, now); reason != "" {
|
||||
if _, err := sender.gate.SettleSend(ctx, unit, claim.permit, outbound.SendResult{}, errNotSent); err != nil {
|
||||
return fmt.Errorf("give the reservation back: %w", err)
|
||||
}
|
||||
cancelled, err := sender.cancel(ctx, unit, delivery, now, reason)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
decided = &cancelled.result
|
||||
return nil
|
||||
}
|
||||
if err := unit.Deliveries().MarkSendStarted(ctx, delivery.ID(), sender.owner); err != nil {
|
||||
return fmt.Errorf("mark send started: %w", err)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return decided, nil
|
||||
}
|
||||
|
||||
// errNotSent stands for "the message did not leave the process" when a
|
||||
// reservation is given back before the transport was called.
|
||||
var errNotSent = errors.New("message was not sent")
|
||||
|
||||
// releaseUnsent gives a claimed delivery back when no time is left to call
|
||||
// the transport, and the reservation with it.
|
||||
func (sender *ServiceMailSender) releaseUnsent(ctx context.Context, claim claimedSend) (inbound.MailPassResult, error) {
|
||||
return sender.settle(ctx, claim, outbound.SendResult{}, context.DeadlineExceeded)
|
||||
}
|
||||
|
||||
// prepare decides what a claimed delivery needs before the transport is
|
||||
// called, in the claim transaction.
|
||||
func (sender *ServiceMailSender) prepare(ctx context.Context, unit outbound.UnitOfWork, claimed outbound.ClaimedDelivery, now time.Time) (claimedSend, error) {
|
||||
delivery := claimed.Delivery
|
||||
if delivery.ProviderAccount() != sender.settings.Account {
|
||||
// Mail stored while no transport ran has no attempt, so no provider
|
||||
// holds its idempotency key and the account may change.
|
||||
rebound, err := delivery.Rebind(latest(now, delivery.UpdatedAt()), sender.settings.Account)
|
||||
if err != nil {
|
||||
return claimedSend{}, fmt.Errorf("rebind delivery: %w", err)
|
||||
}
|
||||
if err := unit.Deliveries().Rebind(ctx, rebound); err != nil {
|
||||
return claimedSend{}, fmt.Errorf("store rebound delivery: %w", err)
|
||||
}
|
||||
delivery = rebound
|
||||
}
|
||||
if sender.abandonedBeyondDeduplication(claimed) {
|
||||
return sender.recordInDoubt(ctx, unit, delivery, now)
|
||||
}
|
||||
state, err := unit.Deliveries().ServiceMailState(ctx, delivery.ID())
|
||||
if err != nil {
|
||||
return claimedSend{}, fmt.Errorf("read token and account: %w", err)
|
||||
}
|
||||
if reason := delivery.CheckServiceMail(state, now); reason != "" {
|
||||
return sender.cancel(ctx, unit, delivery, now, reason)
|
||||
}
|
||||
decision, err := sender.gate.PrepareSend(ctx, unit, delivery)
|
||||
if err != nil {
|
||||
return claimedSend{}, fmt.Errorf("prepare send: %w", err)
|
||||
}
|
||||
if !decision.Proceed() {
|
||||
return claimedSend{decided: true, result: resultOf(inbound.MailPassWaitingQuota, decision.Delivery)}, nil
|
||||
}
|
||||
return claimedSend{delivery: decision.Delivery, permit: decision.Permit}, nil
|
||||
}
|
||||
|
||||
// abandonedBeyondDeduplication reports a delivery whose earlier sender let its
|
||||
// lease expire after it had started the first request, and so long ago that
|
||||
// the provider may have forgotten the idempotency key: repeating the request
|
||||
// could send the mail twice. The provider keeps the key for its window from
|
||||
// the first request, so the age is counted from there, by the database clock,
|
||||
// however often the delivery was claimed since and whatever the lease is,
|
||||
// less a safety margin. A transport without provider-side deduplication
|
||||
// (window zero) never repeats a request that may have been sent. A lease
|
||||
// that never reached the request leaves nothing in doubt.
|
||||
func (sender *ServiceMailSender) abandonedBeyondDeduplication(claimed outbound.ClaimedDelivery) bool {
|
||||
if claimed.PreviousClaimedUntil.IsZero() || !claimed.FirstSendStarted {
|
||||
return false
|
||||
}
|
||||
window := sender.gate.IdempotencyWindow()
|
||||
if window <= 0 {
|
||||
return true
|
||||
}
|
||||
return claimed.SinceFirstSend >= max(window-dedupSafetyMargin, 0)
|
||||
}
|
||||
|
||||
// recordInDoubt records the lost attempt as unknown, without a next attempt,
|
||||
// so an operator decides; it is never treated as not sent.
|
||||
func (sender *ServiceMailSender) recordInDoubt(ctx context.Context, unit outbound.UnitOfWork, delivery domain.Delivery, now time.Time) (claimedSend, error) {
|
||||
next, attempt, err := delivery.RecordAttempt(domain.DeliveryAttemptInput{
|
||||
At: latest(now, delivery.UpdatedAt()),
|
||||
Outcome: domain.DeliveryOutcomeUnknown,
|
||||
})
|
||||
if err != nil {
|
||||
return claimedSend{}, fmt.Errorf("record lost attempt: %w", err)
|
||||
}
|
||||
if err := unit.Deliveries().RecordClaimedAttempt(ctx, sender.owner, next, attempt); err != nil {
|
||||
return claimedSend{}, fmt.Errorf("store lost attempt: %w", err)
|
||||
}
|
||||
sender.logger.WarnContext(ctx, "an earlier attempt of the delivery stopped without a result beyond the provider's idempotency window; the delivery is unknown and needs an operator",
|
||||
slog.String("delivery_id", delivery.ID().String()),
|
||||
slog.String("kind", string(delivery.Kind())))
|
||||
return claimedSend{decided: true, result: resultOf(inbound.MailPassUnknown, next)}, nil
|
||||
}
|
||||
|
||||
func (sender *ServiceMailSender) cancel(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
delivery domain.Delivery,
|
||||
now time.Time,
|
||||
reason domain.DeliveryCancelReason,
|
||||
) (claimedSend, error) {
|
||||
cancelled, err := delivery.Cancel(latest(now, delivery.UpdatedAt()), reason)
|
||||
if err != nil {
|
||||
return claimedSend{}, fmt.Errorf("cancel delivery: %w", err)
|
||||
}
|
||||
if err := unit.Deliveries().Cancel(ctx, cancelled); err != nil {
|
||||
return claimedSend{}, fmt.Errorf("store cancelled delivery: %w", err)
|
||||
}
|
||||
sender.logger.InfoContext(ctx, "service mail was not sent because it is no longer valid",
|
||||
slog.String("delivery_id", delivery.ID().String()),
|
||||
slog.String("kind", string(delivery.Kind())),
|
||||
slog.String("reason", string(reason)))
|
||||
return claimedSend{decided: true, result: resultOf(inbound.MailPassCancelled, cancelled)}, nil
|
||||
}
|
||||
|
||||
// settle stores the result of the transport call, repeating the transaction
|
||||
// after a database failure: the answer lives only here until it is stored.
|
||||
// When every try fails, the delivery stays under its lease; once it expires,
|
||||
// another claim repeats the request under the same idempotency key.
|
||||
func (sender *ServiceMailSender) settle(ctx context.Context, claim claimedSend, result outbound.SendResult, sendErr error) (inbound.MailPassResult, error) {
|
||||
const location = "ServiceMailSender.settle"
|
||||
result, sendErr = sender.checkedSendResult(ctx, claim.delivery, result, sendErr)
|
||||
// The result is stored even when ctx ended: shutdown must not lose it. The
|
||||
// whole of storing is bounded by the budget reserved inside the lease, and
|
||||
// by the shorter shutdown budget once shutdown has begun, so the process
|
||||
// stops within its shutdown timeout.
|
||||
budget := sender.settings.SettleBudget
|
||||
if ctx.Err() != nil {
|
||||
budget = min(budget, sender.settings.ShutdownSettleBudget)
|
||||
}
|
||||
storeCtx, cancelStore := context.WithTimeout(context.WithoutCancel(ctx), budget)
|
||||
defer cancelStore()
|
||||
var lastErr error
|
||||
for attempt := 1; attempt <= settleAttempts; attempt++ {
|
||||
var final inbound.MailPassResult
|
||||
tryCtx, cancel := context.WithTimeout(storeCtx, sender.settings.StoreTimeout)
|
||||
lastErr = sender.transactor.WithinTransaction(tryCtx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
var err error
|
||||
final, err = sender.applyResult(ctx, unit, claim, result, sendErr)
|
||||
return err
|
||||
})
|
||||
cancel()
|
||||
switch {
|
||||
case lastErr == nil:
|
||||
sender.logFinished(storeCtx, final)
|
||||
return final, nil
|
||||
case errors.Is(lastErr, errLeaseLost):
|
||||
sender.logger.InfoContext(storeCtx, "service mail was recorded by another worker first; this attempt is dropped",
|
||||
slog.String("delivery_id", claim.delivery.ID().String()))
|
||||
return resultOf(inbound.MailPassLeaseLost, claim.delivery), nil
|
||||
}
|
||||
if attempt < settleAttempts && !waitFor(storeCtx, settleRetryDelay) {
|
||||
break
|
||||
}
|
||||
}
|
||||
sender.logger.ErrorContext(storeCtx, "the result of a mail send could not be stored; the delivery stays under its lease and is claimed again after it expires, with the same idempotency key",
|
||||
slog.String("delivery_id", claim.delivery.ID().String()),
|
||||
slog.String("kind", string(claim.delivery.Kind())))
|
||||
return inbound.MailPassResult{}, fmt.Errorf("%s - store result: %w", location, lastErr)
|
||||
}
|
||||
|
||||
// checkedSendResult guards the stored state against a transport that breaks
|
||||
// the MailSender contract: a nil error with no outcome may mean that the
|
||||
// message left, so it counts as unknown, never as not sent.
|
||||
func (sender *ServiceMailSender) checkedSendResult(ctx context.Context, delivery domain.Delivery, result outbound.SendResult, sendErr error) (outbound.SendResult, error) {
|
||||
if sendErr != nil {
|
||||
return outbound.SendResult{}, sendErr
|
||||
}
|
||||
switch result.Outcome {
|
||||
case outbound.MailOutcomeAccepted, outbound.MailOutcomeRejected, outbound.MailOutcomeUnknown:
|
||||
return result, nil
|
||||
default:
|
||||
sender.logger.ErrorContext(ctx, "the mail transport returned no outcome; the attempt is recorded as unknown",
|
||||
slog.String("delivery_id", delivery.ID().String()))
|
||||
return outbound.SendResult{Outcome: outbound.MailOutcomeUnknown}, nil
|
||||
}
|
||||
}
|
||||
|
||||
// applyResult runs in the settlement transaction: the quota settlement and
|
||||
// the delivery's next state commit together.
|
||||
func (sender *ServiceMailSender) applyResult(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
claim claimedSend,
|
||||
result outbound.SendResult,
|
||||
sendErr error,
|
||||
) (inbound.MailPassResult, error) {
|
||||
delivery := claim.delivery
|
||||
// The delivery row is locked before the quota rows, the order of the claim,
|
||||
// and only while this worker still holds the lease.
|
||||
held, err := unit.Deliveries().LockClaimed(ctx, delivery.ID(), sender.owner)
|
||||
if err != nil {
|
||||
return inbound.MailPassResult{}, fmt.Errorf("lock delivery: %w", err)
|
||||
}
|
||||
if !held {
|
||||
return inbound.MailPassResult{}, errLeaseLost
|
||||
}
|
||||
until, err := sender.gate.SettleSend(ctx, unit, claim.permit, result, sendErr)
|
||||
if err != nil {
|
||||
return inbound.MailPassResult{}, fmt.Errorf("settle quota: %w", err)
|
||||
}
|
||||
now := sender.clock()
|
||||
if sendErr != nil {
|
||||
return sender.applyNotSent(ctx, unit, claim, now, sendErr)
|
||||
}
|
||||
at := latest(now, delivery.UpdatedAt())
|
||||
next, attempt, err := delivery.RecordAttempt(sender.attemptInput(delivery, result, at, until))
|
||||
if err != nil {
|
||||
return inbound.MailPassResult{}, fmt.Errorf("record attempt: %w", err)
|
||||
}
|
||||
if err := unit.Deliveries().RecordClaimedAttempt(ctx, sender.owner, next, attempt); err != nil {
|
||||
if errors.Is(err, outbound.ErrDeliveryVersionConflict) {
|
||||
return inbound.MailPassResult{}, errLeaseLost
|
||||
}
|
||||
return inbound.MailPassResult{}, fmt.Errorf("store attempt: %w", err)
|
||||
}
|
||||
return resultOf(outcomeOfStatus(next.Status()), next), nil
|
||||
}
|
||||
|
||||
// attemptInput maps a transport answer to the attempt the delivery records.
|
||||
// until is the quota reset that SettleSend returned for a provider quota
|
||||
// refusal.
|
||||
func (sender *ServiceMailSender) attemptInput(delivery domain.Delivery, result outbound.SendResult, at, until time.Time) domain.DeliveryAttemptInput {
|
||||
input := domain.DeliveryAttemptInput{
|
||||
At: at,
|
||||
Outcome: domain.DeliveryAttemptOutcome(result.Outcome),
|
||||
Rejection: domain.DeliveryRejection(result.Rejection),
|
||||
ProviderCode: string(result.ProviderCode),
|
||||
ProviderMessageID: result.ProviderMessageID,
|
||||
RetryAfter: result.RetryAfter,
|
||||
}
|
||||
switch {
|
||||
case result.Outcome == outbound.MailOutcomeAccepted:
|
||||
// An accepted attempt carries no code or wait hint.
|
||||
input.ProviderCode = ""
|
||||
input.RetryAfter = 0
|
||||
case result.Outcome == outbound.MailOutcomeRejected && (result.Rejection == outbound.MailRejectionTemporary || result.Rejection == outbound.MailRejectionRateLimited):
|
||||
input.NextAttemptAt = sender.settings.Retry.NextAttemptAt(at, delivery.AttemptCount()+1, result.RetryAfter)
|
||||
case result.Outcome == outbound.MailOutcomeRejected && result.Rejection == outbound.MailRejectionQuotaExhausted && !until.IsZero():
|
||||
// Zero means that the reset is unknown, and the delivery waits for an
|
||||
// operator.
|
||||
input.NextAttemptAt = latest(until, at)
|
||||
}
|
||||
return input
|
||||
}
|
||||
|
||||
// applyNotSent handles a Send error: nothing left the process, and SettleSend
|
||||
// gave the reservation back.
|
||||
//
|
||||
// - An invalid stored message ends the delivery (content_invalid).
|
||||
// - No transport, or a context that ended (shutdown, an exhausted call
|
||||
// budget) is nobody's fault: the lease ends and the delivery stays due.
|
||||
// - Any other error is a fault on this delivery or in the transport that a
|
||||
// plain retry may repeat forever, with the row at the head of the queue.
|
||||
// It is counted as a failure of the row: the delivery is due later by the
|
||||
// retry schedule, and after MaxFailures it is cancelled with
|
||||
// processing_failed for an operator.
|
||||
func (sender *ServiceMailSender) applyNotSent(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
claim claimedSend,
|
||||
now time.Time,
|
||||
sendErr error,
|
||||
) (inbound.MailPassResult, error) {
|
||||
delivery := claim.delivery
|
||||
switch {
|
||||
case errors.Is(sendErr, outbound.ErrInvalidOutgoingMail):
|
||||
cancelled, err := delivery.Cancel(latest(now, delivery.UpdatedAt()), domain.DeliveryCancelContentInvalid)
|
||||
if err != nil {
|
||||
return inbound.MailPassResult{}, fmt.Errorf("cancel delivery: %w", err)
|
||||
}
|
||||
if err := unit.Deliveries().Cancel(ctx, cancelled); err != nil {
|
||||
return inbound.MailPassResult{}, fmt.Errorf("store cancelled delivery: %w", err)
|
||||
}
|
||||
return resultOf(inbound.MailPassCancelled, cancelled), nil
|
||||
case errors.Is(sendErr, outbound.ErrMailChannelUnavailable), errors.Is(sendErr, context.Canceled), errors.Is(sendErr, context.DeadlineExceeded):
|
||||
if _, err := unit.Deliveries().ReleaseClaim(ctx, delivery.ID(), sender.owner); err != nil {
|
||||
return inbound.MailPassResult{}, fmt.Errorf("release claim: %w", err)
|
||||
}
|
||||
outcome := inbound.MailPassInterrupted
|
||||
if errors.Is(sendErr, outbound.ErrMailChannelUnavailable) {
|
||||
outcome = inbound.MailPassChannelUnavailable
|
||||
}
|
||||
return resultOf(outcome, delivery), nil
|
||||
default:
|
||||
// An error without an answer that is neither a cancellation nor the
|
||||
// missing transport says nothing certain about this row, so it is not
|
||||
// counted against it; the row only moves back by the retry schedule,
|
||||
// so it does not stay at the head of the queue, and the worker backs
|
||||
// off as for any pass that could not send.
|
||||
at := latest(now, delivery.UpdatedAt())
|
||||
if _, err := unit.Deliveries().RecordFailure(ctx, delivery.ID(), sender.owner, at,
|
||||
sender.settings.Retry.NextAttemptAt(at, claim.failureCount+1, 0), sender.settings.MaxFailures, false); err != nil {
|
||||
return inbound.MailPassResult{}, fmt.Errorf("record failure: %w", err)
|
||||
}
|
||||
sender.logger.ErrorContext(ctx, "the mail transport failed without an answer; the delivery is retried later",
|
||||
slog.String("delivery_id", delivery.ID().String()))
|
||||
return resultOf(inbound.MailPassInterrupted, delivery), nil
|
||||
}
|
||||
}
|
||||
|
||||
func (sender *ServiceMailSender) logFinished(ctx context.Context, result inbound.MailPassResult) {
|
||||
attributes := []any{
|
||||
slog.String("delivery_id", result.DeliveryID.String()),
|
||||
slog.String("kind", string(result.Kind)),
|
||||
slog.String("outcome", string(result.Outcome)),
|
||||
}
|
||||
switch result.Outcome {
|
||||
case inbound.MailPassRejected, inbound.MailPassUnknown:
|
||||
sender.logger.WarnContext(ctx, "service mail was not accepted by the provider", attributes...)
|
||||
case inbound.MailPassCancelled:
|
||||
sender.logger.InfoContext(ctx, "service mail was not sent because it is invalid", append(attributes, slog.String("reason", string(result.CancelReason)))...)
|
||||
case inbound.MailPassIdle, inbound.MailPassAccepted, inbound.MailPassRetry, inbound.MailPassWaitingQuota,
|
||||
inbound.MailPassChannelUnavailable, inbound.MailPassInterrupted, inbound.MailPassLeaseLost, inbound.MailPassRowFailed:
|
||||
sender.logger.InfoContext(ctx, "service mail pass finished", attributes...)
|
||||
}
|
||||
}
|
||||
|
||||
func outcomeOfStatus(status domain.DeliveryStatus) inbound.MailPassOutcome {
|
||||
switch status {
|
||||
case domain.DeliveryStatusAccepted:
|
||||
return inbound.MailPassAccepted
|
||||
case domain.DeliveryStatusRejected:
|
||||
return inbound.MailPassRejected
|
||||
case domain.DeliveryStatusPending:
|
||||
return inbound.MailPassRetry
|
||||
case domain.DeliveryStatusWaitingQuota:
|
||||
return inbound.MailPassWaitingQuota
|
||||
case domain.DeliveryStatusCancelled:
|
||||
return inbound.MailPassCancelled
|
||||
case domain.DeliveryStatusUnknown:
|
||||
return inbound.MailPassUnknown
|
||||
default:
|
||||
return inbound.MailPassUnknown
|
||||
}
|
||||
}
|
||||
|
||||
func resultOf(outcome inbound.MailPassOutcome, delivery domain.Delivery) inbound.MailPassResult {
|
||||
return inbound.MailPassResult{
|
||||
Outcome: outcome,
|
||||
DeliveryID: delivery.ID(),
|
||||
Kind: delivery.Kind(),
|
||||
CancelReason: delivery.CancelReason(),
|
||||
}
|
||||
}
|
||||
|
||||
// waitFor sleeps for delay and reports false when ctx ends first.
|
||||
func waitFor(ctx context.Context, delay time.Duration) bool {
|
||||
timer := time.NewTimer(delay)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return false
|
||||
case <-timer.C:
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,969 @@
|
||||
package notification
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/inbound"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
const (
|
||||
testSenderLease = 2 * time.Minute
|
||||
testTokenSecret = "SyntheticTokenSecret_0123456789-abcdefghij"
|
||||
testMessageID = "4ef9a417-02e9-4d39-ad75-9611e0fcc33c"
|
||||
)
|
||||
|
||||
var errSettlementDown = errors.New("settlement unavailable")
|
||||
|
||||
// leasedRow is a stored delivery with its lease.
|
||||
type leasedRow struct {
|
||||
delivery domain.Delivery
|
||||
owner uuid.UUID
|
||||
until time.Time
|
||||
attempts []domain.DeliveryAttempt
|
||||
// firstSend is when the first request started, by the fake clock; zero
|
||||
// when none did. failures counts failures of the worker on the row.
|
||||
firstSend time.Time
|
||||
failures int32
|
||||
}
|
||||
|
||||
// memoryDeliveries stores deliveries with the version rule and the lease of
|
||||
// the PostgreSQL store. Rollback is not modelled; the integration tests
|
||||
// cover the transactions and the concurrency.
|
||||
type memoryDeliveries struct {
|
||||
outbound.DeliveryRepository
|
||||
|
||||
now func() time.Time
|
||||
rows map[uuid.UUID]*leasedRow
|
||||
state domain.ServiceMailState
|
||||
// unreadable names a delivery that the store cannot restore: ClaimDue
|
||||
// cancels it and reports it, as the PostgreSQL store does.
|
||||
unreadable uuid.UUID
|
||||
// brokenDecode names a delivery whose row cannot be restored for a reason
|
||||
// other than a hash mismatch; ClaimDue reports it without cancelling.
|
||||
brokenDecode uuid.UUID
|
||||
// stateErr makes the token and account read fail; stateSeq, when set,
|
||||
// answers successive reads with successive states.
|
||||
stateErr error
|
||||
stateSeq []domain.ServiceMailState
|
||||
}
|
||||
|
||||
func (store *memoryDeliveries) Get(_ context.Context, id uuid.UUID) (domain.Delivery, error) {
|
||||
row, ok := store.rows[id]
|
||||
if !ok {
|
||||
return domain.Delivery{}, outbound.ErrDeliveryNotFound
|
||||
}
|
||||
return row.delivery, nil
|
||||
}
|
||||
|
||||
func (store *memoryDeliveries) ClaimDue(_ context.Context, claim outbound.DeliveryClaim) (outbound.ClaimedDelivery, error) {
|
||||
for _, row := range store.rows {
|
||||
delivery := row.delivery
|
||||
due := !delivery.NextAttemptAt().IsZero() && !delivery.NextAttemptAt().After(claim.Now)
|
||||
pinned := delivery.ProviderAccount() == claim.Account ||
|
||||
(delivery.ProviderAccount().Provider() == claim.RebindProvider && delivery.AttemptCount() == 0)
|
||||
waiting := delivery.Status() == domain.DeliveryStatusPending || delivery.Status() == domain.DeliveryStatusWaitingQuota
|
||||
free := row.owner == uuid.Nil || !row.until.After(claim.Now)
|
||||
if !due || !pinned || !waiting || !free || !containsKind(claim.Kinds, delivery.Kind()) {
|
||||
continue
|
||||
}
|
||||
previous := time.Time{}
|
||||
if row.owner != uuid.Nil {
|
||||
previous = row.until
|
||||
}
|
||||
if delivery.ID() == store.brokenDecode {
|
||||
return outbound.ClaimedDelivery{}, &outbound.UnreadableDeliveryError{DeliveryID: delivery.ID(), FailureCount: row.failures, Err: errors.New("restore row")}
|
||||
}
|
||||
if delivery.ID() == store.unreadable {
|
||||
cancelled, err := delivery.Cancel(claim.Now, domain.DeliveryCancelContentInvalid)
|
||||
if err != nil {
|
||||
return outbound.ClaimedDelivery{}, err
|
||||
}
|
||||
row.delivery = cancelled
|
||||
return outbound.ClaimedDelivery{}, &outbound.UnreadableDeliveryError{DeliveryID: delivery.ID(), Cancelled: true, Err: domain.ErrMailContentIntegrity}
|
||||
}
|
||||
row.owner, row.until = claim.Owner, claim.Now.Add(claim.Lease)
|
||||
claimed := outbound.ClaimedDelivery{Delivery: delivery, PreviousClaimedUntil: previous, FailureCount: row.failures}
|
||||
if !row.firstSend.IsZero() {
|
||||
claimed.FirstSendStarted, claimed.SinceFirstSend = true, claim.Now.Sub(row.firstSend)
|
||||
}
|
||||
return claimed, nil
|
||||
}
|
||||
return outbound.ClaimedDelivery{}, outbound.ErrNoDeliveryDue
|
||||
}
|
||||
|
||||
func containsKind(kinds []domain.MailKind, kind domain.MailKind) bool {
|
||||
for _, candidate := range kinds {
|
||||
if candidate == kind {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (store *memoryDeliveries) ReleaseClaim(_ context.Context, id, owner uuid.UUID) (bool, error) {
|
||||
row := store.rows[id]
|
||||
if row == nil || row.owner != owner {
|
||||
return false, nil
|
||||
}
|
||||
row.owner, row.until = uuid.Nil, time.Time{}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (store *memoryDeliveries) ServiceMailState(context.Context, uuid.UUID) (domain.ServiceMailState, error) {
|
||||
if store.stateErr != nil {
|
||||
return domain.ServiceMailState{}, store.stateErr
|
||||
}
|
||||
if len(store.stateSeq) > 0 {
|
||||
state := store.stateSeq[0]
|
||||
store.stateSeq = store.stateSeq[1:]
|
||||
return state, nil
|
||||
}
|
||||
return store.state, nil
|
||||
}
|
||||
|
||||
// replace stores next over the version before it and, when release is set,
|
||||
// ends the lease.
|
||||
func (store *memoryDeliveries) replace(next domain.Delivery, release bool) error {
|
||||
row := store.rows[next.ID()]
|
||||
if row == nil || row.delivery.Version() != next.Version()-1 {
|
||||
return outbound.ErrDeliveryVersionConflict
|
||||
}
|
||||
row.delivery = next
|
||||
if release {
|
||||
row.owner, row.until = uuid.Nil, time.Time{}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (store *memoryDeliveries) RecordAttempt(_ context.Context, next domain.Delivery, attempt domain.DeliveryAttempt) error {
|
||||
if err := store.replace(next, true); err != nil {
|
||||
return err
|
||||
}
|
||||
row := store.rows[next.ID()]
|
||||
row.attempts = append(row.attempts, attempt)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (store *memoryDeliveries) RecordClaimedAttempt(ctx context.Context, owner uuid.UUID, next domain.Delivery, attempt domain.DeliveryAttempt) error {
|
||||
row := store.rows[next.ID()]
|
||||
if row == nil || row.owner != owner {
|
||||
return outbound.ErrDeliveryVersionConflict
|
||||
}
|
||||
row.failures = 0
|
||||
return store.RecordAttempt(ctx, next, attempt)
|
||||
}
|
||||
|
||||
func (store *memoryDeliveries) LockClaimed(_ context.Context, id, owner uuid.UUID) (bool, error) {
|
||||
row := store.rows[id]
|
||||
return row != nil && row.owner == owner, nil
|
||||
}
|
||||
|
||||
func (store *memoryDeliveries) MarkSendStarted(_ context.Context, id, owner uuid.UUID) error {
|
||||
if row := store.rows[id]; row != nil && row.owner == owner && row.firstSend.IsZero() {
|
||||
row.firstSend = store.now()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (store *memoryDeliveries) RecordFailure(_ context.Context, id, owner uuid.UUID, at, nextAttemptAt time.Time, maxFailures int32, countFailure bool) (bool, error) {
|
||||
row := store.rows[id]
|
||||
if row == nil || (row.owner != uuid.Nil && row.owner != owner && row.until.After(store.now())) {
|
||||
return false, nil
|
||||
}
|
||||
if countFailure {
|
||||
row.failures++
|
||||
}
|
||||
row.owner, row.until = uuid.Nil, time.Time{}
|
||||
if countFailure && row.failures >= maxFailures {
|
||||
cancelled, err := row.delivery.Cancel(at, domain.DeliveryCancelProcessingFailed)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
row.delivery = cancelled
|
||||
return true, nil
|
||||
}
|
||||
// The row is due later; the fake keeps the state and moves the due time.
|
||||
moved, err := domain.RestoreDelivery(domain.DeliverySnapshot{
|
||||
ID: row.delivery.ID(), SourceEventID: row.delivery.SourceEventID(), RecipientUserID: row.delivery.RecipientUserID(),
|
||||
RecipientAddress: row.delivery.Recipient().Address(), Content: row.delivery.Content(), ProviderAccount: row.delivery.ProviderAccount(),
|
||||
IdempotencyKey: row.delivery.IdempotencyKey(), Status: row.delivery.Status(), AttemptCount: row.delivery.AttemptCount(),
|
||||
NextAttemptAt: nextAttemptAt, LastAttemptAt: row.delivery.LastAttemptAt(), ProviderMessageID: row.delivery.ProviderMessageID(),
|
||||
EmailTokenID: row.delivery.EmailTokenID(), Version: row.delivery.Version() + 1, CreatedAt: row.delivery.CreatedAt(), UpdatedAt: at,
|
||||
})
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
row.delivery = moved
|
||||
return false, nil
|
||||
}
|
||||
|
||||
func (store *memoryDeliveries) WaitForQuota(_ context.Context, next domain.Delivery) error {
|
||||
return store.replace(next, true)
|
||||
}
|
||||
|
||||
func (store *memoryDeliveries) Cancel(_ context.Context, next domain.Delivery) error {
|
||||
return store.replace(next, true)
|
||||
}
|
||||
|
||||
func (store *memoryDeliveries) Rebind(_ context.Context, next domain.Delivery) error {
|
||||
return store.replace(next, false)
|
||||
}
|
||||
|
||||
type senderUnit struct {
|
||||
outbound.UnitOfWork
|
||||
|
||||
deliveries *memoryDeliveries
|
||||
quotas *memoryQuotas
|
||||
}
|
||||
|
||||
func (unit senderUnit) Deliveries() outbound.DeliveryRepository { return unit.deliveries }
|
||||
func (unit senderUnit) MailQuotas() outbound.MailQuotaRepository { return unit.quotas }
|
||||
|
||||
// memoryTransactor runs the callback at once; settlementDown makes every
|
||||
// transaction after the claim and the check before the send fail, as a
|
||||
// database lost after the send does.
|
||||
type memoryTransactor struct {
|
||||
unit senderUnit
|
||||
calls int
|
||||
settlementDown bool
|
||||
}
|
||||
|
||||
func (transactor *memoryTransactor) WithinTransaction(ctx context.Context, fn func(ctx context.Context, unit outbound.UnitOfWork) error) error {
|
||||
transactor.calls++
|
||||
if transactor.settlementDown && transactor.calls > 2 {
|
||||
return errSettlementDown
|
||||
}
|
||||
return fn(ctx, transactor.unit)
|
||||
}
|
||||
|
||||
// scriptedMailSender answers every Send with one scripted result and keeps
|
||||
// what it was asked to send.
|
||||
type scriptedMailSender struct {
|
||||
result outbound.SendResult
|
||||
err error
|
||||
mails []outbound.OutgoingMail
|
||||
// onSend runs inside Send; deadline is the deadline of the call's context.
|
||||
onSend func()
|
||||
deadline time.Time
|
||||
}
|
||||
|
||||
func (sender *scriptedMailSender) Send(ctx context.Context, mail outbound.OutgoingMail) (outbound.SendResult, error) {
|
||||
sender.mails = append(sender.mails, mail)
|
||||
sender.deadline, _ = ctx.Deadline()
|
||||
if sender.onSend != nil {
|
||||
sender.onSend()
|
||||
}
|
||||
return sender.result, sender.err
|
||||
}
|
||||
|
||||
type senderTestHarness struct {
|
||||
now time.Time
|
||||
deliveries *memoryDeliveries
|
||||
quotas *memoryQuotas
|
||||
transport *scriptedMailSender
|
||||
transactor *memoryTransactor
|
||||
service *ServiceMailSender
|
||||
delivery domain.Delivery
|
||||
logs *bytes.Buffer
|
||||
}
|
||||
|
||||
func newSenderTestHarness(t *testing.T, window time.Duration) *senderTestHarness {
|
||||
t.Helper()
|
||||
h := &senderTestHarness{now: time.Date(2026, 10, 6, 12, 0, 0, 0, time.UTC), logs: &bytes.Buffer{}}
|
||||
clock := func() time.Time { return h.now }
|
||||
account := testAccount(t, "resend")
|
||||
limits, err := domain.NewMailQuotaLimits(100, 3000)
|
||||
if err != nil {
|
||||
t.Fatalf("NewMailQuotaLimits() error = %v", err)
|
||||
}
|
||||
logger := slog.New(slog.NewJSONHandler(h.logs, nil))
|
||||
h.quotas = newMemoryQuotas()
|
||||
h.deliveries = &memoryDeliveries{now: clock, rows: make(map[uuid.UUID]*leasedRow)}
|
||||
h.transport = &scriptedMailSender{}
|
||||
h.transactor = &memoryTransactor{unit: senderUnit{deliveries: h.deliveries, quotas: h.quotas}}
|
||||
h.service, err = NewServiceMailSender(h.transactor, h.transport, NewQuotaGate(account, limits, window, clock, logger), ServiceMailSenderSettings{
|
||||
Account: account,
|
||||
RebindProvider: "disabled",
|
||||
Lease: testSenderLease,
|
||||
StoreTimeout: time.Second,
|
||||
SettleBudget: time.Minute,
|
||||
ShutdownSettleBudget: time.Second,
|
||||
MaxFailures: 3,
|
||||
Retry: RetryPolicy{Initial: time.Minute, Max: 30 * time.Minute},
|
||||
}, clock, logger)
|
||||
if err != nil {
|
||||
t.Fatalf("NewServiceMailSender() error = %v", err)
|
||||
}
|
||||
h.delivery = h.addDelivery(t, account)
|
||||
return h
|
||||
}
|
||||
|
||||
// addDelivery stores a verification delivery bound to a token, due now, and
|
||||
// makes the token and the account current.
|
||||
func (h *senderTestHarness) addDelivery(t *testing.T, account domain.MailProviderAccount) domain.Delivery {
|
||||
t.Helper()
|
||||
content, err := domain.NewMailContent(domain.MailKindVerification, "verification.v1", testSubject,
|
||||
"https://lincodex.example/verify-email#token="+testTokenSecret+"\n", "<p>"+testBody+"</p>\n")
|
||||
if err != nil {
|
||||
t.Fatalf("NewMailContent() error = %v", err)
|
||||
}
|
||||
recipient, err := domain.NewEmailAddress(testRecipientAddress)
|
||||
if err != nil {
|
||||
t.Fatalf("NewEmailAddress() error = %v", err)
|
||||
}
|
||||
delivery, err := domain.NewDelivery(domain.NewDeliveryInput{
|
||||
ID: uuid.Must(uuid.NewV7()),
|
||||
RecipientUserID: uuid.Must(uuid.NewV7()),
|
||||
Recipient: recipient,
|
||||
Content: content,
|
||||
ProviderAccount: account,
|
||||
EmailTokenID: uuid.Must(uuid.NewV7()),
|
||||
CreatedAt: h.now,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewDelivery() error = %v", err)
|
||||
}
|
||||
h.deliveries.rows[delivery.ID()] = &leasedRow{delivery: delivery}
|
||||
h.deliveries.state = domain.ServiceMailState{
|
||||
TokenFound: true,
|
||||
TokenPurpose: domain.EmailTokenPurposeEmailVerification,
|
||||
TokenUserID: delivery.RecipientUserID(),
|
||||
TokenRegistrationVersion: 1,
|
||||
TokenExpiresAt: h.now.Add(72 * time.Hour),
|
||||
AccountRegistrationVersion: 1,
|
||||
AccountEmailKey: recipient.Normalized(),
|
||||
}
|
||||
return delivery
|
||||
}
|
||||
|
||||
func (h *senderTestHarness) pass(t *testing.T) inbound.MailPassResult {
|
||||
t.Helper()
|
||||
result, err := h.service.ProcessNext(t.Context(), t.Context())
|
||||
if err != nil {
|
||||
t.Fatalf("ProcessNext() error = %v", err)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func (h *senderTestHarness) stored() *leasedRow { return h.deliveries.rows[h.delivery.ID()] }
|
||||
|
||||
func (h *senderTestHarness) assertNoSecretsInLogs(t *testing.T) {
|
||||
t.Helper()
|
||||
for _, marker := range append([]string{testTokenSecret, "verify-email"}, privateMarkers...) {
|
||||
if strings.Contains(h.logs.String(), marker) {
|
||||
t.Fatalf("%q reached the logs: %s", marker, h.logs.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestServiceMailSenderMapsEveryTransportResultToTheDeliveryState(t *testing.T) {
|
||||
midnight := time.Date(2026, 10, 7, 0, 0, 0, 0, time.UTC)
|
||||
start := time.Date(2026, 10, 6, 12, 0, 0, 0, time.UTC)
|
||||
tests := []struct {
|
||||
name string
|
||||
result outbound.SendResult
|
||||
err error
|
||||
wantOutcome inbound.MailPassOutcome
|
||||
wantStatus domain.DeliveryStatus
|
||||
wantNext time.Time
|
||||
wantAttempts int
|
||||
wantUsed int64
|
||||
}{
|
||||
{
|
||||
name: "accepted by the provider",
|
||||
result: outbound.SendResult{Outcome: outbound.MailOutcomeAccepted, ProviderMessageID: testMessageID},
|
||||
wantOutcome: inbound.MailPassAccepted, wantStatus: domain.DeliveryStatusAccepted, wantAttempts: 1, wantUsed: 1,
|
||||
},
|
||||
{
|
||||
name: "permanent refusal",
|
||||
result: outbound.SendResult{Outcome: outbound.MailOutcomeRejected, Rejection: outbound.MailRejectionPermanent, ProviderCode: "validation_error"},
|
||||
wantOutcome: inbound.MailPassRejected, wantStatus: domain.DeliveryStatusRejected, wantAttempts: 1,
|
||||
},
|
||||
{
|
||||
name: "refused request",
|
||||
result: outbound.SendResult{Outcome: outbound.MailOutcomeRejected, Rejection: outbound.MailRejectionInvalidRequest, ProviderCode: "invalid_api_key"},
|
||||
wantOutcome: inbound.MailPassRejected, wantStatus: domain.DeliveryStatusRejected, wantAttempts: 1,
|
||||
},
|
||||
{
|
||||
name: "temporary refusal is due after the first backoff",
|
||||
result: outbound.SendResult{Outcome: outbound.MailOutcomeRejected, Rejection: outbound.MailRejectionTemporary},
|
||||
wantOutcome: inbound.MailPassRetry, wantStatus: domain.DeliveryStatusPending, wantNext: start.Add(time.Minute), wantAttempts: 1,
|
||||
},
|
||||
{
|
||||
name: "the provider's longer wait hint is honored",
|
||||
result: outbound.SendResult{Outcome: outbound.MailOutcomeRejected, Rejection: outbound.MailRejectionRateLimited, RetryAfter: 2 * time.Hour},
|
||||
wantOutcome: inbound.MailPassRetry, wantStatus: domain.DeliveryStatusPending, wantNext: start.Add(2 * time.Hour), wantAttempts: 1,
|
||||
},
|
||||
{
|
||||
name: "the provider's daily quota answer waits for midnight UTC",
|
||||
result: outbound.SendResult{
|
||||
Outcome: outbound.MailOutcomeRejected, Rejection: outbound.MailRejectionQuotaExhausted, ProviderCode: "daily_quota_exceeded",
|
||||
QuotaPeriod: domain.MailQuotaPeriodDay, RetryAfter: 12 * time.Hour,
|
||||
},
|
||||
wantOutcome: inbound.MailPassWaitingQuota, wantStatus: domain.DeliveryStatusWaitingQuota, wantNext: midnight, wantAttempts: 1, wantUsed: 100,
|
||||
},
|
||||
{
|
||||
name: "a quota answer without a reset waits for an operator",
|
||||
result: outbound.SendResult{Outcome: outbound.MailOutcomeRejected, Rejection: outbound.MailRejectionQuotaExhausted},
|
||||
wantOutcome: inbound.MailPassWaitingQuota, wantStatus: domain.DeliveryStatusWaitingQuota, wantAttempts: 1,
|
||||
},
|
||||
{
|
||||
name: "an uncertain answer is unknown, counted, and not retried",
|
||||
result: outbound.SendResult{Outcome: outbound.MailOutcomeUnknown, ProviderCode: "application_error"},
|
||||
wantOutcome: inbound.MailPassUnknown, wantStatus: domain.DeliveryStatusUnknown, wantAttempts: 1, wantUsed: 1,
|
||||
},
|
||||
{
|
||||
name: "a transport that answers without an outcome is unknown, never not sent",
|
||||
result: outbound.SendResult{},
|
||||
wantOutcome: inbound.MailPassUnknown, wantStatus: domain.DeliveryStatusUnknown, wantAttempts: 1, wantUsed: 1,
|
||||
},
|
||||
{
|
||||
name: "no transport leaves the delivery as it was",
|
||||
err: outbound.ErrMailChannelUnavailable,
|
||||
wantOutcome: inbound.MailPassChannelUnavailable, wantStatus: domain.DeliveryStatusPending, wantNext: start,
|
||||
},
|
||||
{
|
||||
name: "an interrupted call leaves the delivery as it was",
|
||||
err: context.Canceled,
|
||||
wantOutcome: inbound.MailPassInterrupted, wantStatus: domain.DeliveryStatusPending, wantNext: start,
|
||||
},
|
||||
{
|
||||
name: "a message no transport accepts ends the delivery",
|
||||
err: outbound.ErrInvalidOutgoingMail,
|
||||
wantOutcome: inbound.MailPassCancelled, wantStatus: domain.DeliveryStatusCancelled,
|
||||
},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
h := newSenderTestHarness(t, testIdempotencyWindow)
|
||||
h.transport.result, h.transport.err = test.result, test.err
|
||||
result := h.pass(t)
|
||||
if result.Outcome != test.wantOutcome || result.DeliveryID != h.delivery.ID() || result.Kind != domain.MailKindVerification {
|
||||
t.Fatalf("pass = %+v, want %s for the delivery", result, test.wantOutcome)
|
||||
}
|
||||
row := h.stored()
|
||||
if row.delivery.Status() != test.wantStatus || !row.delivery.NextAttemptAt().Equal(test.wantNext) || len(row.attempts) != test.wantAttempts {
|
||||
t.Fatalf("delivery is %s due %s with %d attempts, want %s due %s with %d",
|
||||
row.delivery.Status(), row.delivery.NextAttemptAt(), len(row.attempts), test.wantStatus, test.wantNext, test.wantAttempts)
|
||||
}
|
||||
if row.owner != uuid.Nil {
|
||||
t.Fatal("the delivery still holds a lease after the pass")
|
||||
}
|
||||
if used := h.quotas.used(domain.MailQuotaPeriodDay, h.now); used != test.wantUsed {
|
||||
t.Fatalf("recipients counted today = %d, want %d", used, test.wantUsed)
|
||||
}
|
||||
// One call, with the stored message and the stable key.
|
||||
mail := h.transport.mails[0]
|
||||
if len(h.transport.mails) != 1 || mail.IdempotencyKey != "delivery/"+h.delivery.ID().String() ||
|
||||
mail.To.Address() != testRecipientAddress || !strings.Contains(mail.TextBody, testTokenSecret) {
|
||||
t.Fatal("the transport was not called once with the stored message and its key")
|
||||
}
|
||||
h.assertNoSecretsInLogs(t)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestServiceMailSenderCancelsBeforeTheTransportWhenTheMailIsNoLongerValid(t *testing.T) {
|
||||
tests := map[string]struct {
|
||||
change func(*domain.ServiceMailState, time.Time)
|
||||
want domain.DeliveryCancelReason
|
||||
}{
|
||||
"token revoked": {func(state *domain.ServiceMailState, now time.Time) { state.TokenInvalidatedAt = now }, domain.DeliveryCancelTokenRevoked},
|
||||
"token consumed": {func(state *domain.ServiceMailState, now time.Time) { state.TokenConsumedAt = now }, domain.DeliveryCancelTokenConsumed},
|
||||
"token expired": {func(state *domain.ServiceMailState, now time.Time) { state.TokenExpiresAt = now }, domain.DeliveryCancelTokenExpired},
|
||||
"token missing": {func(state *domain.ServiceMailState, _ time.Time) { state.TokenFound = false }, domain.DeliveryCancelTokenMissing},
|
||||
"account moved": {func(state *domain.ServiceMailState, _ time.Time) { state.AccountRegistrationVersion++ }, domain.DeliveryCancelAccountNotCurrent},
|
||||
"address changed": {func(state *domain.ServiceMailState, _ time.Time) { state.AccountEmailKey = "moved@example.com" }, domain.DeliveryCancelRecipientMismatch},
|
||||
}
|
||||
for name, test := range tests {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
h := newSenderTestHarness(t, testIdempotencyWindow)
|
||||
test.change(&h.deliveries.state, h.now)
|
||||
result := h.pass(t)
|
||||
if result.Outcome != inbound.MailPassCancelled || result.CancelReason != test.want {
|
||||
t.Fatalf("pass = %+v, want cancelled with %s", result, test.want)
|
||||
}
|
||||
row := h.stored()
|
||||
if row.delivery.Status() != domain.DeliveryStatusCancelled || row.delivery.CancelReason() != test.want ||
|
||||
len(row.attempts) != 0 || row.owner != uuid.Nil {
|
||||
t.Fatalf("delivery is %s (%s) with %d attempts, want cancelled with that reason and no attempt", row.delivery.Status(), row.delivery.CancelReason(), len(row.attempts))
|
||||
}
|
||||
if len(h.transport.mails) != 0 || len(h.quotas.journal) != 0 {
|
||||
t.Fatal("an invalid mail reached the transport or the quota")
|
||||
}
|
||||
if again := h.pass(t); again.Outcome != inbound.MailPassIdle {
|
||||
t.Fatalf("pass after the cancellation = %+v, want idle", again)
|
||||
}
|
||||
h.assertNoSecretsInLogs(t)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestServiceMailSenderCancelsAnUnreadableDeliveryInsteadOfBlockingTheQueue(t *testing.T) {
|
||||
h := newSenderTestHarness(t, testIdempotencyWindow)
|
||||
h.deliveries.unreadable = h.delivery.ID()
|
||||
result := h.pass(t)
|
||||
if result.Outcome != inbound.MailPassCancelled || result.DeliveryID != h.delivery.ID() || result.CancelReason != domain.DeliveryCancelContentInvalid {
|
||||
t.Fatalf("pass = %+v, want cancelled as content_invalid", result)
|
||||
}
|
||||
if row := h.stored(); row.delivery.Status() != domain.DeliveryStatusCancelled || row.owner != uuid.Nil {
|
||||
t.Fatalf("delivery is %s, want cancelled without a lease", row.delivery.Status())
|
||||
}
|
||||
if len(h.transport.mails) != 0 {
|
||||
t.Fatal("an unreadable delivery reached the transport")
|
||||
}
|
||||
if !strings.Contains(h.logs.String(), h.delivery.ID().String()) {
|
||||
t.Fatal("the log does not name the cancelled delivery")
|
||||
}
|
||||
h.assertNoSecretsInLogs(t)
|
||||
if again := h.pass(t); again.Outcome != inbound.MailPassIdle {
|
||||
t.Fatalf("pass after the cancellation = %+v, want idle", again)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServiceMailSenderWaitsForALocalQuotaWithoutCallingTheTransport(t *testing.T) {
|
||||
h := newSenderTestHarness(t, testIdempotencyWindow)
|
||||
// The day is full.
|
||||
limits, err := domain.NewMailQuotaLimits(1, 3000)
|
||||
if err != nil {
|
||||
t.Fatalf("NewMailQuotaLimits() error = %v", err)
|
||||
}
|
||||
h.service.gate.limits = limits
|
||||
h.transport.result = outbound.SendResult{Outcome: outbound.MailOutcomeAccepted, ProviderMessageID: testMessageID}
|
||||
if result := h.pass(t); result.Outcome != inbound.MailPassAccepted {
|
||||
t.Fatalf("first pass = %+v, want accepted", result)
|
||||
}
|
||||
second := h.addDelivery(t, testAccount(t, "resend"))
|
||||
result := h.pass(t)
|
||||
midnight := time.Date(2026, 10, 7, 0, 0, 0, 0, time.UTC)
|
||||
row := h.deliveries.rows[second.ID()]
|
||||
if result.Outcome != inbound.MailPassWaitingQuota || row.delivery.Status() != domain.DeliveryStatusWaitingQuota || !row.delivery.NextAttemptAt().Equal(midnight) {
|
||||
t.Fatalf("pass = %+v, delivery %s due %s; want waiting_quota until %s", result, row.delivery.Status(), row.delivery.NextAttemptAt(), midnight)
|
||||
}
|
||||
if len(h.transport.mails) != 1 {
|
||||
t.Fatal("the transport was called for a delivery that the local quota deferred")
|
||||
}
|
||||
// A pass before the reset has nothing to do; at the reset it sends.
|
||||
if again := h.pass(t); again.Outcome != inbound.MailPassIdle {
|
||||
t.Fatalf("pass before the reset = %+v, want idle", again)
|
||||
}
|
||||
h.now = midnight
|
||||
if result := h.pass(t); result.Outcome != inbound.MailPassAccepted || result.DeliveryID != second.ID() {
|
||||
t.Fatalf("pass at the reset = %+v, want the waiting delivery accepted", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServiceMailSenderKeepsTheLeaseWhenTheResultCannotBeStored(t *testing.T) {
|
||||
h := newSenderTestHarness(t, testIdempotencyWindow)
|
||||
h.transactor.settlementDown = true
|
||||
h.transport.result = outbound.SendResult{Outcome: outbound.MailOutcomeAccepted, ProviderMessageID: testMessageID}
|
||||
if _, err := h.service.ProcessNext(t.Context(), t.Context()); !errors.Is(err, errSettlementDown) {
|
||||
t.Fatalf("ProcessNext() error = %v, want the settlement failure", err)
|
||||
}
|
||||
row := h.stored()
|
||||
if row.owner == uuid.Nil || row.delivery.Status() != domain.DeliveryStatusPending || len(row.attempts) != 0 {
|
||||
t.Fatal("a result that was not stored changed the delivery or freed it before its lease ended")
|
||||
}
|
||||
if got := h.transactor.calls; got != 2+settleAttempts {
|
||||
t.Fatalf("transactions = %d, want the claim, the check, and %d tries to store the result", got, settleAttempts)
|
||||
}
|
||||
h.assertNoSecretsInLogs(t)
|
||||
|
||||
// While the lease lives nobody sends it; afterwards a replacement
|
||||
// repeats the request under the same key and reuses the reservation.
|
||||
h.transactor.settlementDown = false
|
||||
if result := h.pass(t); result.Outcome != inbound.MailPassIdle {
|
||||
t.Fatalf("pass under a live lease = %+v, want idle", result)
|
||||
}
|
||||
h.now = h.now.Add(testSenderLease)
|
||||
if result := h.pass(t); result.Outcome != inbound.MailPassAccepted {
|
||||
t.Fatalf("pass after the lease expired = %+v, want accepted", result)
|
||||
}
|
||||
if len(h.transport.mails) != 2 || h.transport.mails[0].IdempotencyKey != h.transport.mails[1].IdempotencyKey {
|
||||
t.Fatal("the replacement did not reuse the idempotency key")
|
||||
}
|
||||
if used := h.quotas.used(domain.MailQuotaPeriodDay, h.now); used != 1 {
|
||||
t.Fatalf("recipients counted today = %d, want 1: the open reservation is reused", used)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServiceMailSenderDoesNotRepeatAnAttemptLostBeyondTheDeduplicationWindow(t *testing.T) {
|
||||
for name, window := range map[string]time.Duration{"after the provider's window": testIdempotencyWindow, "for a transport without deduplication": 0} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
h := newSenderTestHarness(t, window)
|
||||
h.transactor.settlementDown = true
|
||||
h.transport.result = outbound.SendResult{Outcome: outbound.MailOutcomeAccepted, ProviderMessageID: testMessageID}
|
||||
if _, err := h.service.ProcessNext(t.Context(), t.Context()); err == nil {
|
||||
t.Fatal("ProcessNext() with a failing settlement returned no error")
|
||||
}
|
||||
h.transactor.settlementDown = false
|
||||
h.now = h.now.Add(testSenderLease + max(window, time.Hour))
|
||||
result := h.pass(t)
|
||||
row := h.stored()
|
||||
if result.Outcome != inbound.MailPassUnknown || row.delivery.Status() != domain.DeliveryStatusUnknown || !row.delivery.NextAttemptAt().IsZero() {
|
||||
t.Fatalf("pass = %+v, delivery %s due %s; want unknown for an operator", result, row.delivery.Status(), row.delivery.NextAttemptAt())
|
||||
}
|
||||
if len(h.transport.mails) != 1 {
|
||||
t.Fatal("the request was repeated although the provider may have forgotten its key")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestServiceMailSenderMovesMailStoredWhileNoTransportRanOntoItsAccount(t *testing.T) {
|
||||
h := newSenderTestHarness(t, testIdempotencyWindow)
|
||||
// Replace the stored delivery by one pinned to the disabled transport.
|
||||
delete(h.deliveries.rows, h.delivery.ID())
|
||||
disabled, err := domain.NewMailProviderAccount("disabled", "main")
|
||||
if err != nil {
|
||||
t.Fatalf("NewMailProviderAccount() error = %v", err)
|
||||
}
|
||||
h.delivery = h.addDelivery(t, disabled)
|
||||
h.transport.result = outbound.SendResult{Outcome: outbound.MailOutcomeAccepted, ProviderMessageID: testMessageID}
|
||||
|
||||
if result := h.pass(t); result.Outcome != inbound.MailPassAccepted {
|
||||
t.Fatalf("pass = %+v, want accepted", result)
|
||||
}
|
||||
if got := h.stored().delivery.ProviderAccount(); got != testAccount(t, "resend") {
|
||||
t.Fatalf("delivery is pinned to %s, want the configured account", got.Provider())
|
||||
}
|
||||
|
||||
// A delivery pinned to another real account is not this worker's.
|
||||
other, err := domain.NewMailProviderAccount("resend", "other")
|
||||
if err != nil {
|
||||
t.Fatalf("NewMailProviderAccount() error = %v", err)
|
||||
}
|
||||
foreign := h.addDelivery(t, other)
|
||||
calls := len(h.transport.mails)
|
||||
if result := h.pass(t); result.Outcome != inbound.MailPassIdle || len(h.transport.mails) != calls || h.deliveries.rows[foreign.ID()].delivery.Status() != domain.DeliveryStatusPending {
|
||||
t.Fatalf("pass = %+v; a delivery of another account must wait untouched", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServiceMailSenderIsIdleWithoutADueDelivery(t *testing.T) {
|
||||
h := newSenderTestHarness(t, testIdempotencyWindow)
|
||||
delete(h.deliveries.rows, h.delivery.ID())
|
||||
if result := h.pass(t); result.Outcome != inbound.MailPassIdle || result.DeliveryID != uuid.Nil {
|
||||
t.Fatalf("pass = %+v, want idle", result)
|
||||
}
|
||||
if len(h.transport.mails) != 0 {
|
||||
t.Fatal("the transport was called without a delivery")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewServiceMailSenderRejectsUnusableSettings(t *testing.T) {
|
||||
account := testAccount(t, "resend")
|
||||
valid := ServiceMailSenderSettings{
|
||||
Account: account, Lease: time.Minute, StoreTimeout: time.Second, SettleBudget: time.Second, ShutdownSettleBudget: time.Second,
|
||||
MaxFailures: 1, Retry: RetryPolicy{Initial: time.Second, Max: time.Minute},
|
||||
}
|
||||
for name, change := range map[string]func(*ServiceMailSenderSettings){
|
||||
"no account": func(settings *ServiceMailSenderSettings) { settings.Account = domain.MailProviderAccount{} },
|
||||
"no lease": func(settings *ServiceMailSenderSettings) { settings.Lease = 0 },
|
||||
"no store timeout": func(settings *ServiceMailSenderSettings) { settings.StoreTimeout = 0 },
|
||||
"no settle budget": func(settings *ServiceMailSenderSettings) { settings.SettleBudget = 0 },
|
||||
"budget over lease": func(settings *ServiceMailSenderSettings) { settings.SettleBudget = time.Minute },
|
||||
"no failure limit": func(settings *ServiceMailSenderSettings) { settings.MaxFailures = 0 },
|
||||
"no initial delay": func(settings *ServiceMailSenderSettings) { settings.Retry.Initial = 0 },
|
||||
"maximum below start": func(settings *ServiceMailSenderSettings) { settings.Retry.Max = time.Millisecond },
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
settings := valid
|
||||
change(&settings)
|
||||
if _, err := NewServiceMailSender(nil, nil, nil, settings, time.Now, slog.New(slog.DiscardHandler)); err == nil {
|
||||
t.Fatal("NewServiceMailSender() accepted unusable settings")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRetryPolicyDoublesTheWaitUpToItsMaximumAndHonorsALongerHint(t *testing.T) {
|
||||
policy := RetryPolicy{Initial: time.Minute, Max: 30 * time.Minute}
|
||||
at := time.Date(2026, 10, 6, 12, 0, 0, 0, time.UTC)
|
||||
tests := []struct {
|
||||
attempt int32
|
||||
retryAfter time.Duration
|
||||
want time.Duration
|
||||
}{
|
||||
{1, 0, time.Minute},
|
||||
{2, 0, 2 * time.Minute},
|
||||
{3, 0, 4 * time.Minute},
|
||||
{6, 0, 30 * time.Minute},
|
||||
{40, 0, 30 * time.Minute},
|
||||
{1, 10 * time.Minute, 10 * time.Minute},
|
||||
{1, 10 * time.Second, time.Minute},
|
||||
{10, 2 * time.Hour, 2 * time.Hour},
|
||||
}
|
||||
for _, test := range tests {
|
||||
if got := policy.NextAttemptAt(at, test.attempt, test.retryAfter); !got.Equal(at.Add(test.want)) {
|
||||
t.Fatalf("NextAttemptAt(attempt %d, hint %s) = +%s, want +%s", test.attempt, test.retryAfter, got.Sub(at), test.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestServiceMailSenderMovesAFailingRowBackInTheQueueAndCancelsItAfterRepeatedFailures(t *testing.T) {
|
||||
causes := map[string]func(*senderTestHarness){
|
||||
"the token and account cannot be read": func(h *senderTestHarness) { h.deliveries.stateErr = fmt.Errorf("state: %w", domain.ErrInvalidDelivery) },
|
||||
"the row cannot be restored": func(h *senderTestHarness) { h.deliveries.brokenDecode = h.delivery.ID() },
|
||||
}
|
||||
for name, cause := range causes {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
h := newSenderTestHarness(t, testIdempotencyWindow)
|
||||
cause(h)
|
||||
poisoned := h.delivery
|
||||
healthy := h.addDelivery(t, testAccount(t, "resend"))
|
||||
h.deliveries.stateErr = nil
|
||||
if name == "the token and account cannot be read" {
|
||||
h.deliveries.stateErr = fmt.Errorf("state: %w", domain.ErrInvalidDelivery)
|
||||
}
|
||||
h.transport.result = outbound.SendResult{Outcome: outbound.MailOutcomeAccepted, ProviderMessageID: testMessageID}
|
||||
|
||||
// The first failure moves the row back by the retry schedule; the
|
||||
// delivery behind it is not blocked.
|
||||
result := h.pass(t)
|
||||
if result.Outcome != inbound.MailPassRowFailed || result.DeliveryID != poisoned.ID() {
|
||||
t.Fatalf("first pass = %+v, want row_failed for the failing delivery", result)
|
||||
}
|
||||
row := h.deliveries.rows[poisoned.ID()]
|
||||
if row.owner != uuid.Nil || row.failures != 1 || !row.delivery.NextAttemptAt().Equal(h.now.Add(time.Minute)) {
|
||||
t.Fatalf("failing row: lease %v, %d failures, due %s; want no lease, 1 failure, due in a minute", row.owner, row.failures, row.delivery.NextAttemptAt())
|
||||
}
|
||||
h.deliveries.stateErr = nil
|
||||
if next := h.pass(t); next.Outcome != inbound.MailPassAccepted || next.DeliveryID != healthy.ID() {
|
||||
t.Fatalf("second pass = %+v, want the healthy delivery sent", next)
|
||||
}
|
||||
|
||||
// It fails again each time it is due, and after MaxFailures it is
|
||||
// cancelled for an operator.
|
||||
if name == "the token and account cannot be read" {
|
||||
h.deliveries.stateErr = fmt.Errorf("state: %w", domain.ErrInvalidDelivery)
|
||||
}
|
||||
h.now = h.now.Add(time.Hour)
|
||||
if second := h.pass(t); second.Outcome != inbound.MailPassRowFailed {
|
||||
t.Fatalf("pass at the second due time = %+v, want row_failed", second)
|
||||
}
|
||||
h.now = h.now.Add(2 * time.Hour)
|
||||
final := h.pass(t)
|
||||
if final.Outcome != inbound.MailPassCancelled || final.CancelReason != domain.DeliveryCancelProcessingFailed {
|
||||
t.Fatalf("third failure = %+v, want cancelled as processing_failed", final)
|
||||
}
|
||||
if got := h.deliveries.rows[poisoned.ID()].delivery; got.Status() != domain.DeliveryStatusCancelled || got.CancelReason() != domain.DeliveryCancelProcessingFailed {
|
||||
t.Fatalf("delivery is %s (%s), want cancelled as processing_failed", got.Status(), got.CancelReason())
|
||||
}
|
||||
h.assertNoSecretsInLogs(t)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestServiceMailSenderMovesBackAFailingTransportCallWithoutCountingItAgainstTheRow(t *testing.T) {
|
||||
h := newSenderTestHarness(t, testIdempotencyWindow)
|
||||
h.transport.err = errors.New("transport misconfigured")
|
||||
for range 5 {
|
||||
result := h.pass(t)
|
||||
row := h.stored()
|
||||
if result.Outcome != inbound.MailPassInterrupted || row.failures != 0 || row.owner != uuid.Nil ||
|
||||
row.delivery.Status() != domain.DeliveryStatusPending || !row.delivery.NextAttemptAt().After(h.now) {
|
||||
t.Fatalf("pass = %+v; row: %d failures, %s due %s; want an uncounted failure, pending, due later", result, row.failures, row.delivery.Status(), row.delivery.NextAttemptAt())
|
||||
}
|
||||
if again := h.pass(t); again.Outcome != inbound.MailPassIdle {
|
||||
t.Fatalf("pass before the due time = %+v, want idle: the row must not stay at the head", again)
|
||||
}
|
||||
h.now = h.now.Add(time.Hour)
|
||||
}
|
||||
// However often the transport failed, the row was never cancelled; a
|
||||
// working transport sends it.
|
||||
h.transport.err, h.transport.result = nil, outbound.SendResult{Outcome: outbound.MailOutcomeAccepted, ProviderMessageID: testMessageID}
|
||||
if result := h.pass(t); result.Outcome != inbound.MailPassAccepted {
|
||||
t.Fatalf("pass with a working transport = %+v, want accepted", result)
|
||||
}
|
||||
if used := h.quotas.used(domain.MailQuotaPeriodDay, h.now); used != 1 {
|
||||
t.Fatalf("recipients counted = %d, want 1", used)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServiceMailSenderDoesNotCountTransientErrorsAgainstTheRow(t *testing.T) {
|
||||
transient := map[string]error{
|
||||
"deadline": context.DeadlineExceeded,
|
||||
"canceled": fmt.Errorf("claim: %w", context.Canceled),
|
||||
"deadlock": fmt.Errorf("postgres: %w", outbound.ErrTransactionConflict),
|
||||
"connection": &net.OpError{Op: "read", Err: errors.New("connection reset")},
|
||||
"io": io.ErrUnexpectedEOF,
|
||||
"quota setup": ErrQuotaNotConfigured,
|
||||
}
|
||||
for name, cause := range transient {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
h := newSenderTestHarness(t, testIdempotencyWindow)
|
||||
h.deliveries.stateErr = cause
|
||||
for range 10 {
|
||||
if _, err := h.service.ProcessNext(t.Context(), t.Context()); err == nil {
|
||||
t.Fatal("a transient error was swallowed instead of reported to the worker")
|
||||
}
|
||||
// The real transaction rolls the lease back; the fake does not.
|
||||
h.stored().owner = uuid.Nil
|
||||
}
|
||||
row := h.stored()
|
||||
if row.failures != 0 || row.delivery.Status() != domain.DeliveryStatusPending {
|
||||
t.Fatalf("row: %d failures, %s; want no count and not cancelled after ten transient errors", row.failures, row.delivery.Status())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestServiceMailSenderPausedCountingMovesRowsBackWithoutCountingThem(t *testing.T) {
|
||||
h := newSenderTestHarness(t, testIdempotencyWindow)
|
||||
h.deliveries.stateErr = fmt.Errorf("state: %w", domain.ErrInvalidDelivery)
|
||||
h.service.PauseFailureCounting(true)
|
||||
for range 5 {
|
||||
if result := h.pass(t); result.Outcome != inbound.MailPassRowFailed {
|
||||
t.Fatalf("pass = %+v, want row_failed", result)
|
||||
}
|
||||
h.now = h.now.Add(time.Hour)
|
||||
}
|
||||
if row := h.stored(); row.failures != 0 || row.delivery.Status() != domain.DeliveryStatusPending {
|
||||
t.Fatalf("row: %d failures, %s; want none counted while counting is paused", row.failures, row.delivery.Status())
|
||||
}
|
||||
h.service.PauseFailureCounting(false)
|
||||
h.pass(t)
|
||||
if row := h.stored(); row.failures != 1 {
|
||||
t.Fatalf("failures after counting resumed = %d, want 1", row.failures)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServiceMailSenderSuccessfulPreparationClearsTheFailureCount(t *testing.T) {
|
||||
h := newSenderTestHarness(t, testIdempotencyWindow)
|
||||
h.deliveries.stateErr = fmt.Errorf("state: %w", domain.ErrInvalidDelivery)
|
||||
h.pass(t)
|
||||
h.deliveries.stateErr = nil
|
||||
h.transport.result = outbound.SendResult{Outcome: outbound.MailOutcomeAccepted, ProviderMessageID: testMessageID}
|
||||
h.now = h.now.Add(time.Hour)
|
||||
h.pass(t)
|
||||
if got := h.stored().failures; got != 0 {
|
||||
t.Fatalf("failure count after a successful pass = %d, want 0", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServiceMailSenderRecordsAFailureOnlyForARowNobodyElseHolds(t *testing.T) {
|
||||
h := newSenderTestHarness(t, testIdempotencyWindow)
|
||||
other := uuid.New()
|
||||
row := h.stored()
|
||||
row.owner, row.until = other, h.now.Add(time.Minute)
|
||||
moved, err := h.deliveries.RecordFailure(t.Context(), h.delivery.ID(), h.service.owner, h.now, h.now.Add(time.Hour), 3, true)
|
||||
if err != nil || moved || row.failures != 0 || row.owner != other {
|
||||
t.Fatalf("RecordFailure() = %t, %v with %d failures and owner %v; want the row left alone under another worker's live lease", moved, err, row.failures, row.owner)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServiceMailSenderCountsTheDeduplicationWindowFromTheFirstRequest(t *testing.T) {
|
||||
h := newSenderTestHarness(t, testIdempotencyWindow)
|
||||
h.transport.result = outbound.SendResult{Outcome: outbound.MailOutcomeAccepted, ProviderMessageID: testMessageID}
|
||||
// Several workers in a row stop after the call. Each lease is short and
|
||||
// each takeover is within a day of the one before, but the first request
|
||||
// is older with every cycle.
|
||||
for cycle := range 3 {
|
||||
h.transactor.calls, h.transactor.settlementDown = 0, true
|
||||
if _, err := h.service.ProcessNext(t.Context(), t.Context()); err == nil {
|
||||
t.Fatalf("cycle %d: ProcessNext() with a failing settlement returned no error", cycle)
|
||||
}
|
||||
h.now = h.now.Add(testSenderLease + 8*time.Hour)
|
||||
}
|
||||
h.transactor.settlementDown = false
|
||||
// 24 hours and three leases after the first request: the provider may
|
||||
// have forgotten the key, whatever the latest lease says.
|
||||
result := h.pass(t)
|
||||
if result.Outcome != inbound.MailPassUnknown || len(h.transport.mails) != 3 {
|
||||
t.Fatalf("pass = %+v after %d calls, want unknown without a fourth call", result, len(h.transport.mails))
|
||||
}
|
||||
}
|
||||
|
||||
func TestServiceMailSenderKeepsTheKeyWithinTheSafetyMarginOfTheWindow(t *testing.T) {
|
||||
h := newSenderTestHarness(t, testIdempotencyWindow)
|
||||
h.transport.result = outbound.SendResult{Outcome: outbound.MailOutcomeAccepted, ProviderMessageID: testMessageID}
|
||||
h.transactor.settlementDown = true
|
||||
if _, err := h.service.ProcessNext(t.Context(), t.Context()); err == nil {
|
||||
t.Fatal("ProcessNext() with a failing settlement returned no error")
|
||||
}
|
||||
h.transactor.settlementDown = false
|
||||
// 22 hours after the first request is inside the 23-hour margin.
|
||||
h.now = h.now.Add(22 * time.Hour)
|
||||
if result := h.pass(t); result.Outcome != inbound.MailPassAccepted {
|
||||
t.Fatalf("pass 22 hours after the first request = %+v, want accepted under the same key", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServiceMailSenderHonorsARevocationAfterTheClaimCommitted(t *testing.T) {
|
||||
h := newSenderTestHarness(t, testIdempotencyWindow)
|
||||
revoked := h.deliveries.state
|
||||
revoked.TokenInvalidatedAt = h.now
|
||||
// The claim reads a current state; the check right before the send finds
|
||||
// the token revoked.
|
||||
h.deliveries.stateSeq = []domain.ServiceMailState{h.deliveries.state, revoked}
|
||||
result := h.pass(t)
|
||||
if result.Outcome != inbound.MailPassCancelled || result.CancelReason != domain.DeliveryCancelTokenRevoked {
|
||||
t.Fatalf("pass = %+v, want cancelled as token_revoked", result)
|
||||
}
|
||||
if len(h.transport.mails) != 0 {
|
||||
t.Fatal("a revoked token was sent")
|
||||
}
|
||||
if used := h.quotas.used(domain.MailQuotaPeriodDay, h.now); used != 0 {
|
||||
t.Fatalf("recipients counted = %d, want the reservation given back", used)
|
||||
}
|
||||
if row := h.stored(); row.owner != uuid.Nil || row.delivery.Status() != domain.DeliveryStatusCancelled {
|
||||
t.Fatal("the cancelled delivery still holds a lease or is not cancelled")
|
||||
}
|
||||
}
|
||||
|
||||
func TestServiceMailSenderDropsAResultWhenItLostTheLeaseDuringTheCall(t *testing.T) {
|
||||
h := newSenderTestHarness(t, testIdempotencyWindow)
|
||||
h.transport.result = outbound.SendResult{Outcome: outbound.MailOutcomeAccepted, ProviderMessageID: testMessageID}
|
||||
// Another worker takes the delivery while this one is in the call.
|
||||
h.transport.onSend = func() { h.stored().owner = uuid.New() }
|
||||
result := h.pass(t)
|
||||
if result.Outcome != inbound.MailPassLeaseLost || len(h.stored().attempts) != 0 {
|
||||
t.Fatalf("pass = %+v with %d attempts, want lease_lost and none recorded", result, len(h.stored().attempts))
|
||||
}
|
||||
}
|
||||
|
||||
func TestServiceMailSenderBoundsTheCallByWhatIsLeftOfTheLease(t *testing.T) {
|
||||
h := newSenderTestHarness(t, testIdempotencyWindow)
|
||||
h.transport.result = outbound.SendResult{Outcome: outbound.MailOutcomeAccepted, ProviderMessageID: testMessageID}
|
||||
before := time.Now()
|
||||
h.pass(t)
|
||||
// Lease 2 minutes, settle budget 1 minute: the call gets at most a minute.
|
||||
if limit := h.transport.deadline.Sub(before); limit > testSenderLease-time.Minute+time.Second || limit <= 0 {
|
||||
t.Fatalf("the call may take %s, want at most the lease minus the settle budget", limit)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRetryPolicyJitterIsBoundedAndInjectable(t *testing.T) {
|
||||
at := time.Date(2026, 10, 6, 12, 0, 0, 0, time.UTC)
|
||||
full := RetryPolicy{Initial: 10 * time.Minute, Max: time.Hour, Jitter: func(limit time.Duration) time.Duration { return limit }}
|
||||
if got := full.NextAttemptAt(at, 1, 0); !got.Equal(at.Add(12 * time.Minute)) {
|
||||
t.Fatalf("NextAttemptAt() with the largest jitter = +%s, want +12m (a fifth over)", got.Sub(at))
|
||||
}
|
||||
wild := RetryPolicy{Initial: 10 * time.Minute, Max: time.Hour, Jitter: func(time.Duration) time.Duration { return time.Hour }}
|
||||
if got := wild.NextAttemptAt(at, 1, 0); !got.Equal(at.Add(12 * time.Minute)) {
|
||||
t.Fatalf("NextAttemptAt() with a source over its limit = +%s, want it clamped to +12m", got.Sub(at))
|
||||
}
|
||||
none := RetryPolicy{Initial: 10 * time.Minute, Max: time.Hour}
|
||||
if got := none.NextAttemptAt(at, 1, 0); !got.Equal(at.Add(10 * time.Minute)) {
|
||||
t.Fatalf("NextAttemptAt() without jitter = +%s, want +10m", got.Sub(at))
|
||||
}
|
||||
for range 200 {
|
||||
if got := (RetryPolicy{Initial: time.Minute, Max: time.Hour, Jitter: RandomJitter}).NextAttemptAt(at, 1, 0).Sub(at); got < time.Minute || got > 72*time.Second {
|
||||
t.Fatalf("random jitter gave +%s, want within [1m, 1m12s]", got)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user