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
@@ -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