//go:build integration package integration_test import ( "bytes" "context" "errors" "fmt" "log/slog" "net/http" "net/http/httptest" "slices" "strings" "sync" "sync/atomic" "testing" "time" "github.com/google/uuid" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgxpool" "lincodex/backend/internal/adapter/primary/cli/mailretry" "lincodex/backend/internal/adapter/secondary/mail/disabled" "lincodex/backend/internal/adapter/secondary/mail/resend" "lincodex/backend/internal/adapter/secondary/mail/resend/resendfixture" postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" "lincodex/backend/internal/adapter/secondary/prometheus" "lincodex/backend/internal/domain" "lincodex/backend/internal/port/inbound" "lincodex/backend/internal/port/outbound" "lincodex/backend/internal/usecase/notification" "lincodex/backend/internal/usecase/notification/mailtemplate" "lincodex/backend/internal/worker/mailsender" "lincodex/backend/internal/worker/retry" ) const ( mailSenderTestTimeout = 5 * time.Minute mailSenderAccount = "integration" // The lease runs by the database clock, so the tests that let it expire // wait in real time; it is short for that. mailSenderLease = 3 * time.Second mailSenderSettleBudget = 1500 * time.Millisecond // mailSenderTokenLifetime is long enough to outlast the idempotency // window, so a test can move past it without the token expiring first. mailSenderTokenLifetime = 72 * time.Hour mailSenderFrom = "Lincodex " // mailSenderConcurrentWorkers drain the queue at once; each pass holds // its own connection. mailSenderConcurrentWorkers = 4 mailSenderQueued = 8 ) var ( mailSenderStart = time.Date(2026, 10, 6, 12, 0, 0, 0, time.UTC) mailSenderTables = []pgx.Identifier{{"mail_quota_reservations"}, {"mail_quota_usage"}} ) // testClock is the application clock of the sending tests. Several workers // read it at once, so it is guarded. type testClock struct { mu sync.Mutex now time.Time } func (clock *testClock) Now() time.Time { clock.mu.Lock() defer clock.mu.Unlock() return clock.now } func (clock *testClock) Advance(by time.Duration) { clock.mu.Lock() defer clock.mu.Unlock() clock.now = clock.now.Add(by) } func (clock *testClock) Set(at time.Time) { clock.mu.Lock() defer clock.mu.Unlock() clock.now = at } // settlementOutage lets the first two transactions through, the claim and the // check before the send, // and fails every later one, as a worker does that loses the database right // after it called the provider. type settlementOutage struct { inner outbound.Transactor calls atomic.Int32 } func (outage *settlementOutage) WithinTransaction(ctx context.Context, fn func(ctx context.Context, unit outbound.UnitOfWork) error) error { if outage.calls.Add(1) > 2 { return errors.New("settlement unavailable") } return outage.inner.WithinTransaction(ctx, fn) } // failingTransport fails every call without an answer, as a misconfigured // transport can. type failingTransport struct{ err error } func (transport failingTransport) Send(context.Context, outbound.OutgoingMail) (outbound.SendResult, error) { return outbound.SendResult{}, transport.err } // countingPass counts the passes of a worker loop. type countingPass struct { inner inbound.MailPass passes atomic.Int32 } func (pass *countingPass) PauseFailureCounting(paused bool) { pass.inner.PauseFailureCounting(paused) } func (pass *countingPass) ProcessNext(ctx, workCtx context.Context) (inbound.MailPassResult, error) { pass.passes.Add(1) return pass.inner.ProcessNext(ctx, workCtx) } type senderHarness struct { pool *pgxpool.Pool transactor *postgresadapter.Transactor identity *postgresadapter.IdentityStore deliveries outbound.DeliveryRepository mailer *notification.ServiceMailer fixture *resendfixture.Server transport outbound.MailSender account domain.MailProviderAccount clock *testClock logs *syncBuffer publicURL string users int } func TestServiceMailSending(t *testing.T) { env := bootstrap(t, postgresService) ctx, cancel := context.WithTimeout(t.Context(), mailSenderTestTimeout) defer cancel() pool := env.newPoolWithMaxConns(ctx, t, mailSenderConcurrentWorkers*2+4) templates, err := mailtemplate.NewRenderer(env.Config.AppPublicURL) if err != nil { t.Fatalf("NewRenderer() error = %v", err) } fixture := resendfixture.New() t.Cleanup(fixture.Close) clock := &testClock{now: mailSenderStart} fixture.SetClock(clock.Now) transport, err := resend.NewLoopbackSender(resendfixture.APIKey, mailSenderFrom, 10*time.Second, fixture.URL(), clock.Now) if err != nil { t.Fatalf("NewLoopbackSender() error = %v", err) } account, err := domain.NewMailProviderAccount("resend", mailSenderAccount) if err != nil { t.Fatalf("NewMailProviderAccount() error = %v", err) } harness := &senderHarness{ pool: pool, transactor: postgresadapter.NewTransactor(pool), identity: postgresadapter.NewIdentityStore(pool), deliveries: postgresadapter.NewDeliveryStore(pool).Deliveries(), mailer: notification.NewServiceMailer(notification.NewTemplateRenderer(templates), account, clock.Now), fixture: fixture, transport: transport, account: account, clock: clock, logs: &syncBuffer{}, publicURL: env.Config.AppPublicURL, } reset := func(t *testing.T) { t.Helper() // The fixture keeps what it received; a new one per subtest would // need a new transport, so the tests compare against the counts at // their start instead. truncateTables(ctx, t, pool, slices.Concat(mailSenderTables, usersDependentTables)...) clock.Set(mailSenderStart) fixture.SetClock(clock.Now) fixture.SetDelay(0) } t.Run("a service email for an account without C2 is accepted by the local Resend fixture", func(t *testing.T) { reset(t) calls := len(fixture.Requests()) user := harness.createUser(ctx, t, false) raw, token, deliveryID := harness.enqueueVerification(ctx, t, user, mailSenderTokenLifetime) // The account has no consent record of any purpose: C2 is the // publication of the candidate card, and a service mail needs none. assertRowCount(ctx, t, pool, pgx.Identifier{"consent_records"}, 0) stored := harness.delivery(ctx, t, deliveryID) switch { case stored.Status() != domain.DeliveryStatusPending || stored.Kind() != domain.MailKindVerification: t.Fatalf("enqueued delivery is %s of kind %s", stored.Status(), stored.Kind()) case stored.EmailTokenID() != token.ID || deliveryID != token.ID: t.Fatal("the delivery is not bound to the token it was enqueued for") case stored.IdempotencyKey() != "delivery/"+deliveryID.String(): t.Fatalf("idempotency key = %q", stored.IdempotencyKey()) } sender := harness.newSender(t, harness.transactor, 100, 3000) result := harness.pass(ctx, t, sender) if result.Outcome != inbound.MailPassAccepted || result.DeliveryID != deliveryID { t.Fatalf("pass = %+v, want accepted for the enqueued delivery", result) } requests := fixture.Requests()[calls:] if len(requests) != 1 { t.Fatalf("the fixture received %d calls, want 1", len(requests)) } request := requests[0] link := harness.publicURL + "/verify-email#token=" + raw.Reveal() switch { case request.IdempotencyKey != "delivery/"+deliveryID.String(): t.Fatalf("idempotency key sent = %q", request.IdempotencyKey) case len(request.To) != 1 || request.To[0] != user.Email.Address(): t.Fatal("the message was not addressed to the account") case !strings.Contains(request.Text, link) || !strings.Contains(request.HTML, link): t.Fatal("the message does not carry the verification link with its token in the fragment") case strings.Contains(request.Text, "?token=") || strings.Contains(request.HTML, "?token="): t.Fatal("the token travels in a query") } accepted := harness.delivery(ctx, t, deliveryID) if accepted.Status() != domain.DeliveryStatusAccepted || accepted.ProviderMessageID() == "" || accepted.AttemptCount() != 1 || !accepted.NextAttemptAt().IsZero() { t.Fatalf("delivery is %s with %d attempts and message ID %q, want accepted by the provider after one attempt", accepted.Status(), accepted.AttemptCount(), accepted.ProviderMessageID()) } attempts := harness.attempts(ctx, t, deliveryID) if len(attempts) != 1 || attempts[0].Outcome != domain.DeliveryOutcomeAccepted || attempts[0].StatusAfter != domain.DeliveryStatusAccepted { t.Fatalf("attempts = %+v, want one accepted attempt", attempts) } harness.assertQuotaUsage(ctx, t, 1) harness.assertClaimReleased(ctx, t, deliveryID) // The account sees the provider's acceptance, and a second pass has // nothing to do. status, found, err := notification.NewDeliveryStatusReader(harness.deliveries).LatestForUser(ctx, user.ID, domain.MailKindVerification) if err != nil || !found || status.Status != domain.DeliveryStatusAccepted { t.Fatalf("LatestForUser() = %+v, %t, %v; want accepted", status, found, err) } if again := harness.pass(ctx, t, sender); again.Outcome != inbound.MailPassIdle { t.Fatalf("second pass = %+v, want idle", again) } if len(fixture.Requests()[calls:]) != 1 { t.Fatal("the second pass called the provider again") } harness.assertLogsHoldNoSecrets(t, user.Email.Address(), raw.Reveal(), "verify-email") }) t.Run("an accepted request with a lost response retries under the same key within 24 hours", func(t *testing.T) { reset(t) calls := len(fixture.Requests()) messages := fixture.Messages() user := harness.createUser(ctx, t, false) _, _, deliveryID := harness.enqueueVerification(ctx, t, user, mailSenderTokenLifetime) sender := harness.newSender(t, harness.transactor, 100, 3000) fixture.Script(resendfixture.Reply{DropAfterAccept: true}) if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassUnknown { t.Fatalf("pass after the fixture accepted and dropped the response = %+v, want unknown", result) } uncertain := harness.delivery(ctx, t, deliveryID) if uncertain.Status() != domain.DeliveryStatusUnknown || !uncertain.NextAttemptAt().Equal(mailSenderStart.Add(time.Minute)) { t.Fatalf("delivery is %s due %s, want unknown with a bounded retry", uncertain.Status(), uncertain.NextAttemptAt()) } if fixture.Messages()-messages != 1 { t.Fatalf("fixture accepted %d messages, want exactly one before the retry", fixture.Messages()-messages) } harness.clock.Advance(time.Minute) if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassAccepted { t.Fatalf("pass within the provider window = %+v, want the original acceptance", result) } requests := fixture.Requests()[calls:] if len(requests) != 2 || requests[0].IdempotencyKey != requests[1].IdempotencyKey || requests[0].IdempotencyKey != "delivery/"+deliveryID.String() || !requests[1].Replayed || !slices.Equal(requests[0].To, requests[1].To) || requests[0].Subject != requests[1].Subject || requests[0].Text != requests[1].Text || requests[0].HTML != requests[1].HTML { t.Fatalf("provider calls = %+v, want the same pinned key and stored body, replayed once", requests) } stored := harness.delivery(ctx, t, deliveryID) if stored.ProviderAccount() != harness.account || stored.Status() != domain.DeliveryStatusAccepted || stored.AttemptCount() != 2 || fixture.Messages()-messages != 1 { t.Fatalf("delivery is %s on %s after %d attempts, fixture has %d new message(s); want pinned account, accepted, two calls, one message", stored.Status(), stored.ProviderAccount().Account(), stored.AttemptCount(), fixture.Messages()-messages) } }) t.Run("a worker that holds a delivery keeps every other worker off it", func(t *testing.T) { reset(t) calls := len(fixture.Requests()) arrivals := fixture.Arrivals() user := harness.createUser(ctx, t, false) _, _, deliveryID := harness.enqueueVerification(ctx, t, user, mailSenderTokenLifetime) first := harness.newSender(t, harness.transactor, 100, 3000) second := harness.newSender(t, harness.transactor, 100, 3000) // The provider answers slowly, so the first worker is in the middle // of its send, holding the lease, when the second one looks. fixture.SetDelay(500 * time.Millisecond) firstResult := make(chan inbound.MailPassResult, 1) go func() { result, err := first.ProcessNext(ctx, ctx) if err != nil { t.Errorf("first ProcessNext() error = %v", err) } firstResult <- result }() waitFor(ctx, t, "the first worker's request to reach the provider", func() bool { return fixture.Arrivals() == arrivals+1 }) if result := harness.pass(ctx, t, second); result.Outcome != inbound.MailPassIdle { t.Fatalf("the second worker's pass = %+v, want idle while the first one holds the delivery", result) } if result := <-firstResult; result.Outcome != inbound.MailPassAccepted || result.DeliveryID != deliveryID { t.Fatalf("the first worker's pass = %+v, want accepted", result) } fixture.SetDelay(0) requests := fixture.Requests()[calls:] if len(requests) != 1 || requests[0].IdempotencyKey != "delivery/"+deliveryID.String() || requests[0].Replayed { t.Fatalf("provider calls = %+v, want exactly one under the delivery key", requests) } assertRowCount(ctx, t, pool, pgx.Identifier{"delivery_attempts"}, 1) if got := harness.delivery(ctx, t, deliveryID); got.Status() != domain.DeliveryStatusAccepted || got.AttemptCount() != 1 { t.Fatalf("delivery is %s with %d attempts, want accepted after one", got.Status(), got.AttemptCount()) } }) t.Run("workers racing for a queue send each delivery exactly once", func(t *testing.T) { reset(t) calls := len(fixture.Requests()) messages := fixture.Messages() ids := make(map[uuid.UUID]bool, mailSenderQueued) for range mailSenderQueued { user := harness.createUser(ctx, t, false) _, _, id := harness.enqueueVerification(ctx, t, user, mailSenderTokenLifetime) ids[id] = true } var accepted atomic.Int32 var workers sync.WaitGroup for range mailSenderConcurrentWorkers { sender := harness.newSender(t, harness.transactor, 100, 3000) workers.Go(func() { for { result, err := sender.ProcessNext(ctx, ctx) if err != nil { t.Errorf("ProcessNext() error = %v", err) return } if result.Outcome == inbound.MailPassIdle { return } if result.Outcome == inbound.MailPassAccepted { accepted.Add(1) } } }) } workers.Wait() if accepted.Load() != mailSenderQueued { t.Fatalf("%d deliveries were accepted, want %d", accepted.Load(), mailSenderQueued) } requests := fixture.Requests()[calls:] keys := make(map[string]int, len(requests)) for _, request := range requests { keys[request.IdempotencyKey]++ if request.Replayed { t.Fatalf("a delivery was sent twice: %s", request.IdempotencyKey) } } if len(requests) != mailSenderQueued || len(keys) != mailSenderQueued || fixture.Messages()-messages != mailSenderQueued { t.Fatalf("provider calls = %d with %d keys and %d messages, want %d of each", len(requests), len(keys), fixture.Messages()-messages, mailSenderQueued) } for id := range ids { if got := harness.delivery(ctx, t, id); got.Status() != domain.DeliveryStatusAccepted || got.AttemptCount() != 1 { t.Fatalf("a delivery is %s with %d attempts, want accepted after one", got.Status(), got.AttemptCount()) } } harness.assertQuotaUsage(ctx, t, mailSenderQueued) }) t.Run("a worker that stopped after sending is replaced and the provider sees the same key", func(t *testing.T) { reset(t) calls := len(fixture.Requests()) messages := fixture.Messages() user := harness.createUser(ctx, t, false) _, _, deliveryID := harness.enqueueVerification(ctx, t, user, mailSenderTokenLifetime) // The first worker's request is accepted, but the database fails // before it can store the answer: it dies holding the lease. failing := harness.newSender(t, &settlementOutage{inner: harness.transactor}, 100, 3000) if _, err := failing.ProcessNext(ctx, ctx); err == nil { t.Fatal("ProcessNext() with a failing settlement returned no error") } if got := harness.delivery(ctx, t, deliveryID); got.Status() != domain.DeliveryStatusPending || got.AttemptCount() != 0 { t.Fatalf("the delivery is %s with %d attempts, want pending with none: nothing was stored", got.Status(), got.AttemptCount()) } if owner, _ := harness.claimOf(ctx, t, deliveryID); owner == nil { t.Fatal("the stopped worker's lease is gone") } // While the lease lives, no other worker takes the delivery. replacement := harness.newSender(t, harness.transactor, 100, 3000) if result := harness.pass(ctx, t, replacement); result.Outcome != inbound.MailPassIdle { t.Fatalf("pass under a live lease = %+v, want idle", result) } // After the lease expires the replacement repeats the request under // the same key; the provider answers with the original message. time.Sleep(mailSenderLease + 300*time.Millisecond) if result := harness.pass(ctx, t, replacement); result.Outcome != inbound.MailPassAccepted { t.Fatalf("pass after the lease expired = %+v, want accepted", result) } requests := fixture.Requests()[calls:] if len(requests) != 2 || requests[0].IdempotencyKey != requests[1].IdempotencyKey || requests[0].IdempotencyKey != "delivery/"+deliveryID.String() || !requests[1].Replayed { t.Fatalf("provider calls = %+v, want two calls under one key, the second a replay", requests) } if fixture.Messages()-messages != 1 { t.Fatalf("the provider holds %d new messages, want 1", fixture.Messages()-messages) } assertRowCount(ctx, t, pool, pgx.Identifier{"delivery_attempts"}, 1) // The open reservation was reused: the message counts once. harness.assertQuotaUsage(ctx, t, 1) assertRowCount(ctx, t, pool, pgx.Identifier{"mail_quota_reservations"}, 1) }) t.Run("an attempt lost beyond the idempotency window is unknown and is not sent again", func(t *testing.T) { reset(t) calls := len(fixture.Requests()) user := harness.createUser(ctx, t, false) _, _, deliveryID := harness.enqueueVerification(ctx, t, user, mailSenderTokenLifetime) failing := harness.newSender(t, &settlementOutage{inner: harness.transactor}, 100, 3000) if _, err := failing.ProcessNext(ctx, ctx); err == nil { t.Fatal("ProcessNext() with a failing settlement returned no error") } // Every worker was gone for longer than the provider remembers keys, // counted from the first request, whatever the latest lease says. harness.exec(ctx, t, "UPDATE deliveries SET first_send_started_at = first_send_started_at - interval '25 hours' WHERE id = $1", deliveryID) time.Sleep(mailSenderLease + 300*time.Millisecond) replacement := harness.newSender(t, harness.transactor, 100, 3000) if result := harness.pass(ctx, t, replacement); result.Outcome != inbound.MailPassUnknown { t.Fatalf("pass = %+v, want unknown", result) } if len(fixture.Requests()[calls:]) != 1 { t.Fatal("the delivery was sent again although the provider may have forgotten its key") } got := harness.delivery(ctx, t, deliveryID) if got.Status() != domain.DeliveryStatusUnknown || got.AttemptCount() != 1 || !got.NextAttemptAt().IsZero() { t.Fatalf("delivery is %s with %d attempts and a next attempt %s, want unknown after one, for an operator", got.Status(), got.AttemptCount(), got.NextAttemptAt()) } if again := harness.pass(ctx, t, replacement); again.Outcome != inbound.MailPassIdle { t.Fatalf("pass after the unknown record = %+v, want idle", again) } }) t.Run("a revoked token or an account that moved on sends nothing and ends with a reason", func(t *testing.T) { tests := []struct { name string change func(ctx context.Context, t *testing.T, user domain.User, token domain.EmailToken, raw domain.SecretToken) want domain.DeliveryCancelReason }{ { name: "token revoked by a resend", change: func(ctx context.Context, t *testing.T, user domain.User, _ domain.EmailToken, _ domain.SecretToken) { t.Helper() invalidated, err := harness.identity.EmailTokens().InvalidateActive(ctx, user.ID, domain.EmailTokenPurposeEmailVerification, harness.clock.Now()) if err != nil || invalidated != 1 { t.Fatalf("InvalidateActive() = %d, %v; want 1", invalidated, err) } }, want: domain.DeliveryCancelTokenRevoked, }, { name: "token already used", change: func(ctx context.Context, t *testing.T, _ domain.User, _ domain.EmailToken, raw domain.SecretToken) { t.Helper() if _, err := harness.identity.EmailTokens().Consume(ctx, raw.Hash(), domain.EmailTokenPurposeEmailVerification, harness.clock.Now()); err != nil { t.Fatalf("Consume() error = %v", err) } }, want: domain.DeliveryCancelTokenConsumed, }, { name: "token expired", change: func(_ context.Context, _ *testing.T, _ domain.User, token domain.EmailToken, _ domain.SecretToken) { harness.clock.Set(token.ExpiresAt) }, want: domain.DeliveryCancelTokenExpired, }, { name: "account registered again", change: func(ctx context.Context, t *testing.T, user domain.User, _ domain.EmailToken, _ domain.SecretToken) { t.Helper() harness.exec(ctx, t, "UPDATE users SET registration_version = registration_version + 1 WHERE id = $1", user.ID) }, want: domain.DeliveryCancelAccountNotCurrent, }, { name: "address already verified", change: func(ctx context.Context, t *testing.T, user domain.User, token domain.EmailToken, _ domain.SecretToken) { t.Helper() if _, err := harness.identity.Users().MarkEmailVerified(ctx, user.ID, token.RegistrationVersion, harness.clock.Now()); err != nil { t.Fatalf("MarkEmailVerified() error = %v", err) } }, want: domain.DeliveryCancelAccountNotCurrent, }, { name: "address of the account changed", change: func(ctx context.Context, t *testing.T, user domain.User, _ domain.EmailToken, _ domain.SecretToken) { t.Helper() harness.exec(ctx, t, "UPDATE users SET email = 'moved.on@example.com', email_normalized = 'moved.on@example.com' WHERE id = $1", user.ID) }, want: domain.DeliveryCancelRecipientMismatch, }, { name: "token of another purpose", change: func(ctx context.Context, t *testing.T, _ domain.User, token domain.EmailToken, _ domain.SecretToken) { t.Helper() harness.exec(ctx, t, "UPDATE email_tokens SET purpose = 'password_reset' WHERE id = $1", token.ID) }, want: domain.DeliveryCancelTokenPurposeMismatch, }, } reset(t) calls := len(fixture.Requests()) sender := harness.newSender(t, harness.transactor, 100, 3000) for _, test := range tests { user := harness.createUser(ctx, t, false) raw, token, deliveryID := harness.enqueueVerification(ctx, t, user, time.Hour) test.change(ctx, t, user, token, raw) result := harness.pass(ctx, t, sender) if result.Outcome != inbound.MailPassCancelled || result.CancelReason != test.want || result.DeliveryID != deliveryID { t.Fatalf("%s: pass = %+v, want cancelled with reason %s", test.name, result, test.want) } got := harness.delivery(ctx, t, deliveryID) if got.Status() != domain.DeliveryStatusCancelled || got.CancelReason() != test.want || got.AttemptCount() != 0 || !got.NextAttemptAt().IsZero() || got.ProviderMessageID() != "" { t.Fatalf("%s: delivery is %s (%s) with %d attempts, want cancelled with reason %s and no attempt", test.name, got.Status(), got.CancelReason(), got.AttemptCount(), test.want) } harness.assertClaimReleased(ctx, t, deliveryID) if again := harness.pass(ctx, t, sender); again.Outcome != inbound.MailPassIdle { t.Fatalf("%s: pass after the cancellation = %+v, want idle", test.name, again) } if _, _, err := got.RecordAttempt(domain.DeliveryAttemptInput{At: harness.clock.Now(), Outcome: domain.DeliveryOutcomeUnknown}); !errors.Is(err, domain.ErrDeliveryTransition) { t.Fatalf("%s: an attempt on a cancelled delivery error = %v, want ErrDeliveryTransition", test.name, err) } status, found, err := notification.NewDeliveryStatusReader(harness.deliveries).LatestForUser(ctx, user.ID, domain.MailKindVerification) if err != nil || !found || status.Status != domain.DeliveryStatusCancelled { t.Fatalf("%s: LatestForUser() = %+v, %t, %v; want cancelled", test.name, status, found, err) } harness.clock.Set(mailSenderStart) } if got := len(fixture.Requests()[calls:]); got != 0 { t.Fatalf("the provider received %d calls, want none: an invalid mail was sent", got) } // Nothing was reserved or counted for mail that never went out. assertRowCount(ctx, t, pool, pgx.Identifier{"mail_quota_reservations"}, 0) harness.assertQuotaUsage(ctx, t, 0) }) t.Run("a delivery that cannot be restored is cancelled and does not block the queue", func(t *testing.T) { reset(t) calls := len(fixture.Requests()) poisoned := harness.createUser(ctx, t, false) _, _, poisonedID := harness.enqueueVerification(ctx, t, poisoned, mailSenderTokenLifetime) healthy := harness.createUser(ctx, t, false) _, _, healthyID := harness.enqueueVerification(ctx, t, healthy, mailSenderTokenLifetime) // The content trigger refuses any change of a stored body, so the // test lifts it for one statement to break the content hash, as a // manual edit of the table would. harness.exec(ctx, t, "ALTER TABLE deliveries DISABLE TRIGGER deliveries_refuse_content_change") _, err := pool.Exec(ctx, "UPDATE deliveries SET content_sha256 = $2 WHERE id = $1", poisonedID, make([]byte, 32)) harness.exec(ctx, t, "ALTER TABLE deliveries ENABLE TRIGGER deliveries_refuse_content_change") if err != nil { t.Fatalf("break the content hash: %v", err) } if _, err := harness.deliveries.Get(ctx, poisonedID); !errors.Is(err, domain.ErrMailContentIntegrity) { t.Fatalf("Get() of the broken delivery error = %v, want ErrMailContentIntegrity", err) } sender := harness.newSender(t, harness.transactor, 100, 3000) result := harness.pass(ctx, t, sender) if result.Outcome != inbound.MailPassCancelled || result.DeliveryID != poisonedID || result.CancelReason != domain.DeliveryCancelContentInvalid { t.Fatalf("pass = %+v, want the broken delivery cancelled as content_invalid", result) } var status, reason string var version int64 if err := pool.QueryRow(ctx, "SELECT status, cancel_reason, version FROM deliveries WHERE id = $1", poisonedID).Scan(&status, &reason, &version); err != nil || status != "cancelled" || reason != "content_invalid" || version != 2 { t.Fatalf("broken delivery is %q (%q) at version %d, %v; want cancelled content_invalid at version 2", status, reason, version, err) } harness.assertClaimReleased(ctx, t, poisonedID) if len(fixture.Requests()[calls:]) != 0 { t.Fatal("a broken delivery reached the provider") } // The delivery behind it is sent in the next pass. if next := harness.pass(ctx, t, sender); next.Outcome != inbound.MailPassAccepted || next.DeliveryID != healthyID { t.Fatalf("next pass = %+v, want the healthy delivery accepted", next) } harness.assertLogsHoldNoSecrets(t, poisoned.Email.Address(), healthy.Email.Address()) }) t.Run("a row that fails for a reason of its own moves back in the queue and is cancelled after repeated failures", func(t *testing.T) { reset(t) calls := len(fixture.Requests()) broken := harness.createUser(ctx, t, false) _, _, brokenID := harness.enqueueVerification(ctx, t, broken, mailSenderTokenLifetime) healthy := harness.createUser(ctx, t, false) _, _, healthyID := harness.enqueueVerification(ctx, t, healthy, mailSenderTokenLifetime) // A subject with a line break passes the table and fails the domain's // rules, so the row cannot be restored although its hash is intact: // a deterministic fault that is not a hash mismatch. harness.exec(ctx, t, "ALTER TABLE deliveries DISABLE TRIGGER deliveries_refuse_content_change") _, err := pool.Exec(ctx, "UPDATE deliveries SET subject = E'broken\nsubject' WHERE id = $1", brokenID) harness.exec(ctx, t, "ALTER TABLE deliveries ENABLE TRIGGER deliveries_refuse_content_change") if err != nil { t.Fatalf("break the subject: %v", err) } sender := harness.newSender(t, harness.transactor, 100, 3000) result := harness.pass(ctx, t, sender) if result.Outcome != inbound.MailPassRowFailed || result.DeliveryID != brokenID { t.Fatalf("first pass = %+v, want row_failed for the broken delivery", result) } var failures int var due time.Time if err := pool.QueryRow(ctx, "SELECT failure_count, next_attempt_at FROM deliveries WHERE id = $1", brokenID).Scan(&failures, &due); err != nil || failures != 1 || !due.Equal(mailSenderStart.Add(time.Minute)) { t.Fatalf("broken row: %d failures due %s, %v; want 1 failure due a minute later", failures, due, err) } harness.assertClaimReleased(ctx, t, brokenID) // It is not claimed again at once, and the delivery behind it is sent. if next := harness.pass(ctx, t, sender); next.Outcome != inbound.MailPassAccepted || next.DeliveryID != healthyID { t.Fatalf("second pass = %+v, want the healthy delivery accepted", next) } // Each failure pushes the row further; the third cancels it. harness.clock.Advance(time.Hour) if again := harness.pass(ctx, t, sender); again.Outcome != inbound.MailPassRowFailed { t.Fatalf("pass at the second due time = %+v, want row_failed", again) } harness.clock.Advance(2 * time.Hour) final := harness.pass(ctx, t, sender) if final.Outcome != inbound.MailPassCancelled || final.CancelReason != domain.DeliveryCancelProcessingFailed { t.Fatalf("third failure = %+v, want cancelled as processing_failed", final) } var status, reason string var redacted *time.Time if err := pool.QueryRow(ctx, "SELECT status, cancel_reason, body_redacted_at FROM deliveries WHERE id = $1", brokenID).Scan(&status, &reason, &redacted); err != nil || status != "cancelled" || reason != "processing_failed" || redacted == nil { t.Fatalf("broken row is %q (%q) redacted %v, %v; want cancelled processing_failed with its bodies cleared", status, reason, redacted, err) } if len(fixture.Requests()[calls:]) != 1 { t.Fatal("the broken delivery reached the provider") } harness.assertLogsHoldNoSecrets(t, broken.Email.Address(), healthy.Email.Address()) }) t.Run("a transport error without an answer moves the row back without counting it, not a loop at the head of the queue", func(t *testing.T) { reset(t) user := harness.createUser(ctx, t, false) _, _, deliveryID := harness.enqueueVerification(ctx, t, user, mailSenderTokenLifetime) faulty := *harness faulty.transport = failingTransport{err: errors.New("transport is misconfigured")} sender := faulty.newSender(t, harness.transactor, 100, 3000) result := faulty.pass(ctx, t, sender) if result.Outcome != inbound.MailPassInterrupted || result.DeliveryID != deliveryID { t.Fatalf("pass = %+v, want interrupted: the fault is not counted against the row", result) } var failures int if err := pool.QueryRow(ctx, "SELECT failure_count FROM deliveries WHERE id = $1", deliveryID).Scan(&failures); err != nil || failures != 0 { t.Fatalf("failure_count = %d, %v; want 0", failures, err) } got := harness.delivery(ctx, t, deliveryID) if got.Status() != domain.DeliveryStatusPending || got.AttemptCount() != 0 || !got.NextAttemptAt().Equal(mailSenderStart.Add(time.Minute)) { t.Fatalf("delivery is %s due %s after %d attempts, want pending due a minute later with none", got.Status(), got.NextAttemptAt(), got.AttemptCount()) } harness.assertClaimReleased(ctx, t, deliveryID) harness.assertQuotaUsage(ctx, t, 0) if again := faulty.pass(ctx, t, sender); again.Outcome != inbound.MailPassIdle { t.Fatalf("pass before the due time = %+v, want idle", again) } }) t.Run("a failure is recorded only for a row that no other worker holds", func(t *testing.T) { reset(t) user := harness.createUser(ctx, t, false) _, _, deliveryID := harness.enqueueVerification(ctx, t, user, mailSenderTokenLifetime) holder, stranger := uuid.New(), uuid.New() if _, err := harness.deliveries.ClaimDue(ctx, outbound.DeliveryClaim{ Owner: holder, Account: harness.account, Kinds: domain.ServiceMailKinds(), Now: harness.clock.Now(), Lease: mailSenderLease, }); err != nil { t.Fatalf("ClaimDue() error = %v", err) } at := harness.clock.Now() // A stranger whose claim rolled back must not touch a row that the // holder has just claimed. moved, err := harness.deliveries.RecordFailure(ctx, deliveryID, stranger, at, at.Add(time.Hour), 3, true) if err != nil || moved { t.Fatalf("RecordFailure() by a stranger = %t, %v; want it to leave the row alone", moved, err) } var failures int var due time.Time if err := pool.QueryRow(ctx, "SELECT failure_count, next_attempt_at FROM deliveries WHERE id = $1", deliveryID).Scan(&failures, &due); err != nil || failures != 0 || !due.Equal(at) { t.Fatalf("row after a stranger's failure: %d failures due %s, %v; want it untouched", failures, due, err) } if owner, _ := harness.claimOf(ctx, t, deliveryID); owner == nil || *owner != holder { t.Fatal("a stranger's failure cleared the holder's lease") } // The holder itself may record it; counting can be switched off. if _, err := harness.deliveries.RecordFailure(ctx, deliveryID, holder, at, at.Add(time.Hour), 3, false); err != nil { t.Fatalf("RecordFailure() by the holder error = %v", err) } if err := pool.QueryRow(ctx, "SELECT failure_count FROM deliveries WHERE id = $1", deliveryID).Scan(&failures); err != nil || failures != 0 { t.Fatalf("failure_count after an uncounted failure = %d, %v; want 0", failures, err) } harness.assertClaimReleased(ctx, t, deliveryID) }) t.Run("the first request, not the latest lease, starts the idempotency window", func(t *testing.T) { reset(t) calls := len(fixture.Requests()) user := harness.createUser(ctx, t, false) _, _, deliveryID := harness.enqueueVerification(ctx, t, user, mailSenderTokenLifetime) // Three workers in a row stop after the call. Each takeover is only // seconds after the lease before it, so counting from the latest lease // would never see the age of the first request. for cycle := range 3 { failing := harness.newSender(t, &settlementOutage{inner: harness.transactor}, 100, 3000) if _, err := failing.ProcessNext(ctx, ctx); err == nil { t.Fatalf("cycle %d: ProcessNext() with a failing settlement returned no error", cycle) } time.Sleep(mailSenderLease + 300*time.Millisecond) harness.exec(ctx, t, "UPDATE deliveries SET first_send_started_at = first_send_started_at - interval '8 hours' WHERE id = $1", deliveryID) } replacement := harness.newSender(t, harness.transactor, 100, 3000) // 24 hours after the first request, 23 with the safety margin. if result := harness.pass(ctx, t, replacement); result.Outcome != inbound.MailPassUnknown { t.Fatalf("pass = %+v, want unknown: the first request is 24 hours old", result) } if got := len(fixture.Requests()[calls:]); got != 3 { t.Fatalf("provider calls = %d, want the three of the lost workers and no fourth", got) } }) t.Run("the lease follows the database clock and a result is recorded only by the lease holder", func(t *testing.T) { reset(t) user := harness.createUser(ctx, t, false) _, _, deliveryID := harness.enqueueVerification(ctx, t, user, mailSenderTokenLifetime) owner, other := uuid.New(), uuid.New() claimed, err := harness.deliveries.ClaimDue(ctx, outbound.DeliveryClaim{ Owner: owner, Account: harness.account, Kinds: domain.ServiceMailKinds(), Now: harness.clock.Now(), Lease: mailSenderLease, }) if err != nil || claimed.Delivery.ID() != deliveryID { t.Fatalf("ClaimDue() = %v, %v; want the enqueued delivery", claimed.Delivery.ID(), err) } // The fake application clock is a day apart from the database clock // at most; the lease must be measured by the database one. var live, bounded bool if err := pool.QueryRow(ctx, `SELECT claimed_until > clock_timestamp(), claimed_until <= clock_timestamp() + interval '3 seconds' FROM deliveries WHERE id = $1`, deliveryID).Scan(&live, &bounded); err != nil || !live || !bounded { t.Fatalf("lease live = %t, within its length = %t, %v; want a lease of 3 seconds by the database clock", live, bounded, err) } next, attempt, err := claimed.Delivery.RecordAttempt(domain.DeliveryAttemptInput{ At: harness.clock.Now(), Outcome: domain.DeliveryOutcomeAccepted, ProviderMessageID: deliveryMessageID, }) if err != nil { t.Fatalf("RecordAttempt() error = %v", err) } if err := harness.deliveries.RecordClaimedAttempt(ctx, other, next, attempt); !errors.Is(err, outbound.ErrDeliveryVersionConflict) { t.Fatalf("RecordClaimedAttempt() by a stranger error = %v, want ErrDeliveryVersionConflict", err) } if held, err := harness.deliveries.LockClaimed(ctx, deliveryID, other); err != nil || held { t.Fatalf("LockClaimed() by a stranger = %t, %v; want false", held, err) } if err := harness.deliveries.RecordClaimedAttempt(ctx, owner, next, attempt); err != nil { t.Fatalf("RecordClaimedAttempt() by the holder error = %v", err) } }) t.Run("the claim query reads the small due index, not the notification backlog", func(t *testing.T) { reset(t) user := harness.createUser(ctx, t, true) harness.exec(ctx, t, `INSERT INTO deliveries ( id, recipient_user_id, recipient_email, kind, template_version, subject, text_body, html_body, content_sha256, provider, provider_account, idempotency_key, status, attempt_count, next_attempt_at, version, created_at, updated_at ) SELECT gen_random_uuid(), $1, 'backlog@example.com', 'notification', 'notification.v1', 's', 't', '', decode(repeat('00', 32), 'hex'), 'resend', $2, 'delivery/backlog-' || n, 'pending', 0, $3::timestamptz - interval '1 day', 1, $3, $3 FROM generate_series(1, 5000) AS n`, user.ID, mailSenderAccount, mailSenderStart) harness.exec(ctx, t, "ANALYZE deliveries") rows, err := pool.Query(ctx, `EXPLAIN (COSTS OFF) SELECT due.id FROM deliveries AS due WHERE due.kind IN ('verification', 'password_reset') AND due.kind = any($1::text[]) AND due.status IN ('pending', 'waiting_quota') AND due.next_attempt_at IS NOT NULL AND due.next_attempt_at <= $2::timestamptz AND due.provider = 'resend' AND due.provider_account = $3 AND (due.claim_owner IS NULL OR due.claimed_until <= clock_timestamp()) ORDER BY due.next_attempt_at, due.id LIMIT 1 FOR UPDATE SKIP LOCKED`, []string{"verification", "password_reset"}, mailSenderStart, mailSenderAccount) if err != nil { t.Fatalf("explain the claim: %v", err) } defer rows.Close() var plan strings.Builder for rows.Next() { var line string if err := rows.Scan(&line); err != nil { t.Fatalf("scan the plan: %v", err) } plan.WriteString(line + "\n") } if !strings.Contains(plan.String(), "deliveries_due_idx") || strings.Contains(plan.String(), "Seq Scan") { t.Fatalf("the claim does not use deliveries_due_idx over 5000 notification rows:\n%s", plan.String()) } }) t.Run("overdue service mail ignores a notification backlog", func(t *testing.T) { reset(t) user := harness.createUser(ctx, t, true) content, err := domain.NewMailContent(domain.MailKindNotification, "notification.v1", "s", "t\n", "") if err != nil { t.Fatalf("NewMailContent() error = %v", err) } notificationDelivery, err := domain.NewDelivery(domain.NewDeliveryInput{ ID: uuid.Must(uuid.NewV7()), RecipientUserID: user.ID, Recipient: user.Email, Content: content, ProviderAccount: harness.account, CreatedAt: mailSenderStart.Add(-48 * time.Hour), }) if err != nil { t.Fatalf("NewDelivery() error = %v", err) } if created, err := harness.deliveries.Create(ctx, notificationDelivery); err != nil || !created { t.Fatalf("Create() = %t, %v", created, err) } reader := postgresadapter.NewDeliveryStatisticsStore(pool) statistics, err := reader.DeliveryStatistics(ctx) if err != nil || !statistics.EarliestPendingAttemptAt.IsZero() { t.Fatalf("DeliveryStatistics() earliest = %s, %v; want none for a notification-only backlog", statistics.EarliestPendingAttemptAt, err) } other := harness.createUser(ctx, t, false) _, _, serviceID := harness.enqueueVerification(ctx, t, other, mailSenderTokenLifetime) statistics, err = reader.DeliveryStatistics(ctx) due := harness.delivery(ctx, t, serviceID).NextAttemptAt() if err != nil || !statistics.EarliestPendingAttemptAt.Equal(due) { t.Fatalf("DeliveryStatistics() earliest = %s, %v; want the service mail's due time %s", statistics.EarliestPendingAttemptAt, err, due) } }) t.Run("a token mail loses its bodies when it ends, and only then", func(t *testing.T) { reset(t) accepted := harness.createUser(ctx, t, false) raw, _, acceptedID := harness.enqueueVerification(ctx, t, accepted, mailSenderTokenLifetime) revoked := harness.createUser(ctx, t, false) revokedRaw, _, revokedID := harness.enqueueVerification(ctx, t, revoked, mailSenderTokenLifetime) if invalidated, err := harness.identity.EmailTokens().InvalidateActive(ctx, revoked.ID, domain.EmailTokenPurposeEmailVerification, harness.clock.Now()); err != nil || invalidated != 1 { t.Fatalf("InvalidateActive() = %d, %v", invalidated, err) } // While the mail waits, its body is the token's only home. var text string if err := pool.QueryRow(ctx, "SELECT text_body FROM deliveries WHERE id = $1", acceptedID).Scan(&text); err != nil || !strings.Contains(text, raw.Reveal()) { t.Fatalf("a waiting mail has no body: %v", err) } _, err := pool.Exec(ctx, "UPDATE deliveries SET text_body = '', html_body = '', body_redacted_at = now() WHERE id = $1", acceptedID) assertSQLRefusal(t, err, "deliveries_content_immutable") sender := harness.newSender(t, harness.transactor, 100, 3000) for range 2 { harness.pass(ctx, t, sender) } for name, id := range map[string]uuid.UUID{"accepted": acceptedID, "cancelled": revokedID} { var text, html string var redactedAt *time.Time if err := pool.QueryRow(ctx, "SELECT text_body, html_body, body_redacted_at FROM deliveries WHERE id = $1", id).Scan(&text, &html, &redactedAt); err != nil || text != "" || html != "" || redactedAt == nil { t.Fatalf("%s delivery keeps a body (%d, %d bytes) or no redaction time: %v", name, len(text), len(html), err) } got := harness.delivery(ctx, t, id) if !got.Content().Redacted() || got.Content().Text() != "" || got.Content().Subject() == "" { t.Fatalf("%s delivery restores as %v, want redacted content with its subject", name, got.Content()) } } // Neither the token nor its mail is in the table any more. var leaked int if err := pool.QueryRow(ctx, "SELECT count(*) FROM deliveries WHERE text_body LIKE $1 OR html_body LIKE $1 OR text_body LIKE $2 OR html_body LIKE $2", "%"+raw.Reveal()+"%", "%"+revokedRaw.Reveal()+"%").Scan(&leaked); err != nil || leaked != 0 { t.Fatalf("%d rows still hold a token, %v", leaked, err) } // A redacted row cannot get a body back, or lose its mark. for _, statement := range []string{ "UPDATE deliveries SET text_body = 'again' WHERE id = $1", "UPDATE deliveries SET body_redacted_at = NULL WHERE id = $1", } { _, err := pool.Exec(ctx, statement, acceptedID) assertSQLRefusal(t, err, "deliveries_content_immutable") } // The account still sees its status. status, found, err := notification.NewDeliveryStatusReader(harness.deliveries).LatestForUser(ctx, accepted.ID, domain.MailKindVerification) if err != nil || !found || status.Status != domain.DeliveryStatusAccepted { t.Fatalf("LatestForUser() = %+v, %t, %v; want accepted", status, found, err) } }) t.Run("a deleted account leaves nothing to send", func(t *testing.T) { reset(t) calls := len(fixture.Requests()) user := harness.createUser(ctx, t, false) _, _, deliveryID := harness.enqueueVerification(ctx, t, user, time.Hour) harness.exec(ctx, t, "DELETE FROM users WHERE id = $1", user.ID) if _, err := harness.deliveries.Get(ctx, deliveryID); !errors.Is(err, outbound.ErrDeliveryNotFound) { t.Fatalf("Get() after the account was deleted error = %v, want ErrDeliveryNotFound", err) } sender := harness.newSender(t, harness.transactor, 100, 3000) if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassIdle || len(fixture.Requests()[calls:]) != 0 { t.Fatalf("pass = %+v with %d provider calls, want idle and none", result, len(fixture.Requests()[calls:])) } }) t.Run("provider answers become delivery states and due times without an internal retry", func(t *testing.T) { reset(t) calls := len(fixture.Requests()) user := harness.createUser(ctx, t, false) _, _, deliveryID := harness.enqueueVerification(ctx, t, user, mailSenderTokenLifetime) sender := harness.newSender(t, harness.transactor, 100, 3000) // A refusal for now: the delivery is pending again, due later, and // nothing repeats the request before that. fixture.Script(resendfixture.Reply{Status: http.StatusServiceUnavailable, Name: "service_unavailable"}) if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassRetry { t.Fatalf("pass after a 503 = %+v, want retry", result) } pending := harness.delivery(ctx, t, deliveryID) wantDue := mailSenderStart.Add(time.Minute) if pending.Status() != domain.DeliveryStatusPending || !pending.NextAttemptAt().Equal(wantDue) || pending.AttemptCount() != 1 { t.Fatalf("delivery is %s due %s after %d attempts, want pending due %s after one", pending.Status(), pending.NextAttemptAt(), pending.AttemptCount(), wantDue) } harness.assertQuotaUsage(ctx, t, 0) // the refused request did not count if again := harness.pass(ctx, t, sender); again.Outcome != inbound.MailPassIdle || len(fixture.Requests()[calls:]) != 1 { t.Fatalf("pass before the due time = %+v with %d provider calls, want idle and 1", again, len(fixture.Requests()[calls:])) } harness.clock.Set(wantDue) if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassAccepted { t.Fatalf("pass at the due time = %+v, want accepted", result) } requests := fixture.Requests()[calls:] if len(requests) != 2 || requests[0].IdempotencyKey != requests[1].IdempotencyKey { t.Fatalf("provider calls = %+v, want two calls under one key", requests) } attempts := harness.attempts(ctx, t, deliveryID) if len(attempts) != 2 || attempts[0].Rejection != domain.DeliveryRejectionTemporary || attempts[1].Outcome != domain.DeliveryOutcomeAccepted { t.Fatalf("attempts = %+v, want a temporary refusal and then acceptance", attempts) } // An uncertain answer remains unknown, but gets a bounded retry while // the provider still holds the idempotency key. other := harness.createUser(ctx, t, false) _, _, uncertainID := harness.enqueueVerification(ctx, t, other, mailSenderTokenLifetime) fixture.Script(resendfixture.Reply{Status: http.StatusInternalServerError, Name: "application_error"}) if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassUnknown { t.Fatalf("pass after a 500 = %+v, want unknown", result) } if got := harness.delivery(ctx, t, uncertainID); got.Status() != domain.DeliveryStatusUnknown || !got.NextAttemptAt().Equal(harness.clock.Now().Add(time.Minute)) { t.Fatalf("delivery is %s with next attempt %s, want unknown with bounded retry", got.Status(), got.NextAttemptAt()) } harness.clock.Advance(24 * time.Hour) // PostgreSQL owns the cutoff clock; move its start time to exercise // the same DB-clock age calculation without sleeping for a day. harness.exec(ctx, t, "UPDATE deliveries SET first_send_started_at = clock_timestamp() - interval '24 hours' WHERE id = $1", uncertainID) callsBefore := len(fixture.Requests()) if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassUnknown || len(fixture.Requests()) != callsBefore { t.Fatalf("pass after the deduplication cutoff = %+v, want unknown without a call", result) } if got := harness.delivery(ctx, t, uncertainID); got.Status() != domain.DeliveryStatusUnknown || !got.NextAttemptAt().IsZero() { t.Fatalf("delivery after cutoff is %s due %s, want terminal unknown without automatic retry", got.Status(), got.NextAttemptAt()) } // A permanent refusal ends the delivery. harness.clock.Set(mailSenderStart) third := harness.createUser(ctx, t, false) _, _, refusedID := harness.enqueueVerification(ctx, t, third, mailSenderTokenLifetime) fixture.Script(resendfixture.Reply{Status: http.StatusForbidden, Name: "validation_error"}) if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassRejected { t.Fatalf("pass after a 403 = %+v, want rejected", result) } if got := harness.delivery(ctx, t, refusedID); got.Status() != domain.DeliveryStatusRejected { t.Fatalf("delivery is %s, want rejected", got.Status()) } }) t.Run("an earlier unknown answer remains uncertain after a confirmed 429", func(t *testing.T) { for _, test := range []struct { name string age time.Duration wantOutcome inbound.MailPassOutcome wantStatus domain.DeliveryStatus wantCalls int }{ {name: "retry remains allowed before cutoff", age: 22 * time.Hour, wantOutcome: inbound.MailPassAccepted, wantStatus: domain.DeliveryStatusAccepted, wantCalls: 3}, {name: "cutoff stops without a phantom attempt", age: 24 * time.Hour, wantOutcome: inbound.MailPassUnknown, wantStatus: domain.DeliveryStatusUnknown, wantCalls: 2}, } { t.Run(test.name, func(t *testing.T) { reset(t) calls := len(fixture.Requests()) messages := fixture.Messages() user := harness.createUser(ctx, t, false) _, _, deliveryID := harness.enqueueVerification(ctx, t, user, mailSenderTokenLifetime) sender := harness.newSender(t, harness.transactor, 100, 3000) fixture.Script(resendfixture.Reply{DropAfterAccept: true}) if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassUnknown { t.Fatalf("accepted request with dropped response = %+v, want unknown", result) } harness.clock.Advance(time.Minute) fixture.Script(resendfixture.Reply{Status: http.StatusTooManyRequests, Name: "rate_limit_exceeded", RetryAfter: "60"}) if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassRetry { t.Fatalf("confirmed 429 = %+v, want retry", result) } pending := harness.delivery(ctx, t, deliveryID) if pending.Status() != domain.DeliveryStatusPending || pending.AttemptCount() != 2 { t.Fatalf("delivery after 429 is %s after %d attempts, want pending after two", pending.Status(), pending.AttemptCount()) } attempts := harness.attempts(ctx, t, deliveryID) if len(attempts) != 2 || attempts[0].Outcome != domain.DeliveryOutcomeUnknown || attempts[1].Rejection != domain.DeliveryRejectionRateLimited { t.Fatalf("attempts = %+v, want unknown then confirmed rate limit", attempts) } harness.clock.Set(mailSenderStart.Add(test.age)) harness.exec(ctx, t, "UPDATE deliveries SET first_send_started_at = clock_timestamp() - make_interval(secs => $2::float8) WHERE id = $1", deliveryID, test.age.Seconds()) result := harness.pass(ctx, t, sender) stored := harness.delivery(ctx, t, deliveryID) if result.Outcome != test.wantOutcome || stored.Status() != test.wantStatus || len(fixture.Requests())-calls != test.wantCalls { t.Fatalf("pass = %+v, delivery %s, provider requests %d; want %s and %d calls", result, stored.Status(), len(fixture.Requests())-calls, test.wantOutcome, test.wantCalls) } requests := fixture.Requests()[calls:] if requests[0].IdempotencyKey != requests[1].IdempotencyKey || !slices.Equal(requests[0].To, requests[1].To) || requests[0].Subject != requests[1].Subject || requests[0].Text != requests[1].Text || requests[0].HTML != requests[1].HTML { t.Fatal("unknown and confirmed-refusal requests did not keep the same pinned key and body") } if test.wantStatus == domain.DeliveryStatusUnknown && (stored.AttemptCount() != 2 || !stored.NextAttemptAt().IsZero() || len(attempts) != 2 || fixture.Messages()-messages != 1) { t.Fatalf("cutoff state = %s due %s after %d attempts, fixture accepted %d messages; want no new call or attempt", stored.Status(), stored.NextAttemptAt(), stored.AttemptCount(), fixture.Messages()-messages) } }) } }) t.Run("manual retry audits the decision, honors 429 Retry-After, and stops after another unknown", func(t *testing.T) { reset(t) calls := len(fixture.Requests()) messages := fixture.Messages() user := harness.createUser(ctx, t, false) _, _, deliveryID := harness.enqueueVerification(ctx, t, user, mailSenderTokenLifetime) sender := harness.newSender(t, harness.transactor, 100, 3000) fixture.Script(resendfixture.Reply{Status: http.StatusInternalServerError, Name: "application_error"}) if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassUnknown { t.Fatalf("initial 500 pass = %+v, want unknown", result) } operator, err := notification.NewDeliveryRetryOperator( harness.transactor, harness.deliveries, harness.account, resend.IdempotencyWindow, harness.clock.Now, ) if err != nil { t.Fatalf("NewDeliveryRetryOperator() error = %v", err) } if _, err := operator.RetryUnknown(ctx, deliveryID, "operator:mail-ops", true); !errors.Is(err, outbound.ErrDeliveryRetryNotAllowed) { t.Fatalf("RetryUnknown() before cutoff error = %v, want not allowed", err) } if _, err := operator.RetryUnknown(ctx, deliveryID, "operator:mail-ops", false); !errors.Is(err, notification.ErrDuplicateRiskAcknowledgementRequired) { t.Fatalf("RetryUnknown() without acknowledgement error = %v, want acknowledgement required", err) } // Claim while the original result is still inside the safe window, // then age the DB-clock timestamp before MarkSendStarted. The last // storage check must refuse the call even though the claim succeeded. harness.clock.Advance(time.Minute) owner := uuid.New() var claimed outbound.ClaimedDelivery if err := harness.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { var err error claimed, err = unit.Deliveries().ClaimDue(ctx, outbound.DeliveryClaim{ Owner: owner, Account: harness.account, Kinds: domain.ServiceMailKinds(), Now: harness.clock.Now(), Lease: time.Minute, }) return err }); err != nil || claimed.Delivery.ID() != deliveryID { t.Fatalf("claim for the cutoff check = %s, %v; want the uncertain delivery", claimed.Delivery.ID(), err) } harness.exec(ctx, t, "UPDATE deliveries SET first_send_started_at = clock_timestamp() - interval '24 hours' WHERE id = $1", deliveryID) started, err := harness.deliveries.MarkSendStarted(ctx, deliveryID, owner, true, 23*time.Hour) if err != nil || started { t.Fatalf("MarkSendStarted() at the DB-clock cutoff = %t, %v; want no send", started, err) } if released, err := harness.deliveries.ReleaseClaim(ctx, deliveryID, owner); err != nil || !released { t.Fatalf("ReleaseClaim() after cutoff refusal = %t, %v; want released", released, err) } harness.clock.Set(mailSenderStart.Add(23 * time.Hour)) harness.exec(ctx, t, "UPDATE deliveries SET first_send_started_at = clock_timestamp() - interval '23 hours' WHERE id = $1", deliveryID) if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassUnknown { t.Fatalf("pass at the automatic cutoff = %+v, want automatic retry stopped", result) } stopped := harness.delivery(ctx, t, deliveryID) if stopped.Status() != domain.DeliveryStatusUnknown || !stopped.NextAttemptAt().IsZero() { t.Fatalf("delivery after automatic cutoff is %s due %s, want unknown without automatic retry", stopped.Status(), stopped.NextAttemptAt()) } lookup := func(key string) (string, bool) { switch key { case "DATABASE_URL": return env.Config.DatabaseURL, true case "EMAIL_PROVIDER": return "resend", true case "EMAIL_ACCOUNT": return mailSenderAccount, true default: return "", false } } var cliOutput bytes.Buffer if err := mailretry.Run(ctx, []string{"inspect", "--delivery", deliveryID.String()}, lookup, &cliOutput); err != nil { t.Fatalf("mail-retry inspect error = %v", err) } if !strings.Contains(cliOutput.String(), notification.DuplicateRiskWarning) || strings.Contains(cliOutput.String(), user.Email.Address()) { t.Fatalf("mail-retry inspect output = %q; want duplicate warning without recipient data", cliOutput.String()) } cliOutput.Reset() if err := mailretry.Run(ctx, []string{ "retry", "--delivery", deliveryID.String(), "--actor", "operator:mail-ops", "--acknowledge-duplicate-risk", }, lookup, &cliOutput); err != nil { t.Fatalf("mail-retry retry error = %v", err) } if !strings.Contains(cliOutput.String(), notification.DuplicateRiskWarning) || !strings.Contains(cliOutput.String(), "retry scheduled; audit decision recorded") { t.Fatalf("mail-retry retry output = %q; want warning and audited scheduling", cliOutput.String()) } if _, err := operator.RetryUnknown(ctx, deliveryID, "operator:mail-ops", true); !errors.Is(err, outbound.ErrDeliveryRetryNotAllowed) { t.Fatalf("duplicate RetryUnknown() error = %v, want not allowed", err) } var decisions int if err := pool.QueryRow(ctx, "SELECT count(*) FROM delivery_retry_decisions WHERE delivery_id = $1", deliveryID).Scan(&decisions); err != nil || decisions != 1 { t.Fatalf("audited decisions = %d, %v; want exactly one", decisions, err) } fixture.Script(resendfixture.Reply{Status: http.StatusTooManyRequests, Name: "rate_limit_exceeded", RetryAfter: "300"}) if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassRetry { t.Fatalf("manual 429 pass = %+v, want scheduled retry", result) } rateLimited := harness.delivery(ctx, t, deliveryID) wantRetryAt := harness.clock.Now().Add(5 * time.Minute) if rateLimited.Status() != domain.DeliveryStatusPending || !rateLimited.NextAttemptAt().Equal(wantRetryAt) { t.Fatalf("429 state is %s due %s, want pending due at Retry-After %s", rateLimited.Status(), rateLimited.NextAttemptAt(), wantRetryAt) } harness.clock.Set(wantRetryAt) fixture.Script(resendfixture.Reply{DropAfterAccept: true}) if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassUnknown { t.Fatalf("manual send with accepted connection drop = %+v, want unknown", result) } unknown := harness.delivery(ctx, t, deliveryID) if unknown.Status() != domain.DeliveryStatusUnknown || !unknown.NextAttemptAt().IsZero() || unknown.AttemptCount() != 3 { t.Fatalf("manual drop state is %s due %s after %d attempts, want terminal unknown after 3", unknown.Status(), unknown.NextAttemptAt(), unknown.AttemptCount()) } callsAfterUnknown := len(fixture.Requests()) if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassIdle || len(fixture.Requests()) != callsAfterUnknown { t.Fatalf("pass after manual unknown = %+v with %d requests, want idle", result, len(fixture.Requests())-calls) } if err := pool.QueryRow(ctx, "SELECT count(*) FROM delivery_retry_decisions WHERE delivery_id = $1", deliveryID).Scan(&decisions); err != nil || decisions != 1 { t.Fatalf("audited decisions without another operator command = %d, %v; want still one", decisions, err) } requests := fixture.Requests()[calls:] if len(requests) != 3 || fixture.Messages()-messages != 1 { t.Fatalf("provider saw %d requests and accepted %d messages; want 3 requests and one accepted message", len(requests), fixture.Messages()-messages) } for _, request := range requests[1:] { if request.IdempotencyKey != requests[0].IdempotencyKey || !slices.Equal(request.To, requests[0].To) || request.Subject != requests[0].Subject || request.Text != requests[0].Text || request.HTML != requests[0].HTML { t.Fatal("the manual retries changed the pinned key or stored body") } } if requests[2].Replayed { t.Fatal("the final request was unexpectedly replayed before the fixture accepted its first manual request") } }) t.Run("an expired manual send-start is recorded before another authorized send", func(t *testing.T) { reset(t) calls := len(fixture.Requests()) user := harness.createUser(ctx, t, false) _, _, deliveryID := harness.enqueueVerification(ctx, t, user, mailSenderTokenLifetime) sender := harness.newSender(t, harness.transactor, 100, 3000) fixture.Script(resendfixture.Reply{Status: http.StatusInternalServerError, Name: "application_error"}) if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassUnknown { t.Fatalf("initial 500 pass = %+v, want unknown", result) } harness.clock.Set(mailSenderStart.Add(23 * time.Hour)) harness.exec(ctx, t, "UPDATE deliveries SET first_send_started_at = clock_timestamp() - interval '23 hours' WHERE id = $1", deliveryID) if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassUnknown { t.Fatalf("pass at automatic cutoff = %+v, want terminal unknown", result) } lookup := func(key string) (string, bool) { switch key { case "DATABASE_URL": return env.Config.DatabaseURL, true case "EMAIL_PROVIDER": return "resend", true case "EMAIL_ACCOUNT": return mailSenderAccount, true default: return "", false } } retryCommand := func() { t.Helper() var output bytes.Buffer if err := mailretry.Run(ctx, []string{ "retry", "--delivery", deliveryID.String(), "--actor", "operator:mail-ops", "--acknowledge-duplicate-risk", }, lookup, &output); err != nil { t.Fatalf("mail-retry command error = %v", err) } if !strings.Contains(output.String(), notification.DuplicateRiskWarning) || !strings.Contains(output.String(), "retry scheduled; audit decision recorded") || strings.Contains(output.String(), user.Email.Address()) { t.Fatalf("mail-retry output = %q; want warning and safe scheduling result", output.String()) } } dbClock := func() time.Time { t.Helper() var now time.Time if err := pool.QueryRow(ctx, "SELECT clock_timestamp()").Scan(&now); err != nil { t.Fatalf("read database clock: %v", err) } return now } retryCommand() authorized := harness.delivery(ctx, t, deliveryID) if authorized.Status() != domain.DeliveryStatusUnknown || authorized.NextAttemptAt().IsZero() { t.Fatalf("authorized delivery state = %s due %s; want scheduled unknown work", authorized.Status(), authorized.NextAttemptAt()) } // Authorization keeps the later of the app and database timestamps. // The cutoff pass above uses the fake app clock, so advancing only to // database-now can still leave the delivery not due yet. dueAfterAuthorization := authorized.NextAttemptAt().Add(time.Second) if databaseNow := dbClock().Add(time.Second); databaseNow.After(dueAfterAuthorization) { dueAfterAuthorization = databaseNow } harness.clock.Set(dueAfterAuthorization) owner := uuid.New() var claimed outbound.ClaimedDelivery if err := harness.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { var err error claimed, err = unit.Deliveries().ClaimDue(ctx, outbound.DeliveryClaim{ Owner: owner, Account: harness.account, Kinds: domain.ServiceMailKinds(), Now: harness.clock.Now(), Lease: mailSenderLease, }) return err }); err != nil || claimed.Delivery.ID() != deliveryID || !claimed.ManualRetryPending { t.Fatalf("manual send claim = %s, pending %t, error %v; want the authorized delivery", claimed.Delivery.ID(), claimed.ManualRetryPending, err) } started, err := harness.deliveries.MarkSendStarted(ctx, deliveryID, owner, true, 23*time.Hour) if err != nil || !started { t.Fatalf("MarkSendStarted() for operator decision = %t, %v; want started", started, err) } harness.exec(ctx, t, "UPDATE deliveries SET claimed_until = clock_timestamp() - interval '1 second' WHERE id = $1", deliveryID) callsBeforeRecovery := len(fixture.Requests()) retryCommand() if len(fixture.Requests()) != callsBeforeRecovery { t.Fatal("operator recovery called the provider instead of only recording the lost result and scheduling work") } recovered := harness.delivery(ctx, t, deliveryID) attempts := harness.attempts(ctx, t, deliveryID) if recovered.AttemptCount() != 2 || recovered.Status() != domain.DeliveryStatusUnknown || recovered.NextAttemptAt().IsZero() || len(attempts) != 2 || attempts[0].Outcome != domain.DeliveryOutcomeUnknown || attempts[1].Outcome != domain.DeliveryOutcomeUnknown || attempts[1].At.Before(attempts[0].At) { t.Fatalf("recovered delivery = %s due %s after %d attempts, attempts %+v; want the lost manual call appended as unknown and another decision scheduled", recovered.Status(), recovered.NextAttemptAt(), recovered.AttemptCount(), attempts) } rows, err := pool.Query(ctx, ` SELECT attempt_count, duplicate_risk_acknowledged, previous_lease_expired FROM delivery_retry_decisions WHERE delivery_id = $1 ORDER BY decision_id`, deliveryID) if err != nil { t.Fatalf("read retry decisions: %v", err) } defer rows.Close() var decisions []struct { attemptCount int32 duplicateRiskAcknowledged bool previousLeaseExpired bool } for rows.Next() { var decision struct { attemptCount int32 duplicateRiskAcknowledged bool previousLeaseExpired bool } if err := rows.Scan(&decision.attemptCount, &decision.duplicateRiskAcknowledged, &decision.previousLeaseExpired); err != nil { t.Fatalf("scan retry decision: %v", err) } decisions = append(decisions, decision) } if err := rows.Err(); err != nil { t.Fatalf("read retry decisions: %v", err) } if len(decisions) != 2 || decisions[0].attemptCount != 1 || decisions[1].attemptCount != 2 || !decisions[0].duplicateRiskAcknowledged || !decisions[1].duplicateRiskAcknowledged || decisions[0].previousLeaseExpired || !decisions[1].previousLeaseExpired { t.Fatalf("retry decisions = %+v; want each decision tied to its unknown attempt and second decision marked as lease recovery", decisions) } dueAfterRecovery := recovered.NextAttemptAt().Add(time.Second) if databaseNow := dbClock().Add(time.Second); databaseNow.After(dueAfterRecovery) { dueAfterRecovery = databaseNow } harness.clock.Set(dueAfterRecovery) fixture.Script(resendfixture.Reply{}) if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassAccepted { t.Fatalf("pass after recovered operator decision = %+v, want accepted", result) } requests := fixture.Requests()[calls:] if len(requests) != 2 || requests[0].IdempotencyKey != requests[1].IdempotencyKey || !slices.Equal(requests[0].To, requests[1].To) || requests[0].Subject != requests[1].Subject || requests[0].Text != requests[1].Text || requests[0].HTML != requests[1].HTML { t.Fatalf("provider requests after recovery = %+v; want initial and manually authorized request with the pinned key and body", requests) } }) t.Run("a used-up quota parks the delivery in a user-visible waiting status", func(t *testing.T) { reset(t) calls := len(fixture.Requests()) // The local gate: one message per day. sender := harness.newSender(t, harness.transactor, 1, 5) first := harness.createUser(ctx, t, false) harness.enqueueVerification(ctx, t, first, mailSenderTokenLifetime) second := harness.createUser(ctx, t, false) _, _, waitingID := harness.enqueueVerification(ctx, t, second, mailSenderTokenLifetime) if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassAccepted { t.Fatalf("first pass = %+v, want accepted", result) } result := harness.pass(ctx, t, sender) if result.Outcome != inbound.MailPassWaitingQuota || result.DeliveryID != waitingID { t.Fatalf("second pass = %+v, want waiting_quota for the second delivery", result) } midnight := time.Date(2026, 10, 7, 0, 0, 0, 0, time.UTC) status, found, err := notification.NewDeliveryStatusReader(harness.deliveries).LatestForUser(ctx, second.ID, domain.MailKindVerification) if err != nil || !found || !status.WaitingForQuota() || !status.WaitingUntil.Equal(midnight) { t.Fatalf("LatestForUser() = %+v, %t, %v; want waiting until %s", status, found, err, midnight) } if len(fixture.Requests()[calls:]) != 1 { t.Fatal("the provider was called for a delivery that the local quota deferred") } // Not due yet one second before the reset; sent right after it. harness.clock.Set(midnight.Add(-time.Second)) if again := harness.pass(ctx, t, sender); again.Outcome != inbound.MailPassIdle { t.Fatalf("pass before the reset = %+v, want idle", again) } harness.clock.Set(midnight) if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassAccepted || result.DeliveryID != waitingID { t.Fatalf("pass at the reset = %+v, want the waiting delivery accepted", result) } // The provider's own refusal for its quota also waits for the reset. third := harness.createUser(ctx, t, false) _, _, refusedID := harness.enqueueVerification(ctx, t, third, mailSenderTokenLifetime) fixture.Script(resendfixture.Reply{Status: http.StatusTooManyRequests, Name: "daily_quota_exceeded"}) wide := harness.newSender(t, harness.transactor, 100, 3000) nextMidnight := midnight.AddDate(0, 0, 1) if result := harness.pass(ctx, t, wide); result.Outcome != inbound.MailPassWaitingQuota || result.DeliveryID != refusedID { t.Fatalf("pass after the provider quota answer = %+v, want waiting_quota", result) } if got := harness.delivery(ctx, t, refusedID); got.Status() != domain.DeliveryStatusWaitingQuota || !got.NextAttemptAt().Equal(nextMidnight) { t.Fatalf("delivery is %s until %s, want waiting_quota until %s", got.Status(), got.NextAttemptAt(), nextMidnight) } }) t.Run("product notifications are not sent by this worker", func(t *testing.T) { reset(t) calls := len(fixture.Requests()) user := harness.createUser(ctx, t, true) content, err := domain.NewMailContent(domain.MailKindNotification, "notification.v1", "Синтетическое уведомление", "PRIVATE-BODY notification\n", "") if err != nil { t.Fatalf("NewMailContent() error = %v", err) } delivery, err := domain.NewDelivery(domain.NewDeliveryInput{ ID: uuid.Must(uuid.NewV7()), RecipientUserID: user.ID, Recipient: user.Email, Content: content, ProviderAccount: harness.account, CreatedAt: harness.clock.Now(), }) if err != nil { t.Fatalf("NewDelivery() error = %v", err) } if created, err := harness.deliveries.Create(ctx, delivery); err != nil || !created { t.Fatalf("Create() = %t, %v; want the notification stored", created, err) } sender := harness.newSender(t, harness.transactor, 100, 3000) if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassIdle || len(fixture.Requests()[calls:]) != 0 { t.Fatalf("pass = %+v with %d provider calls, want idle and none: product notification sending is not implemented", result, len(fixture.Requests()[calls:])) } if got := harness.delivery(ctx, t, delivery.ID()); got.Status() != domain.DeliveryStatusPending || got.AttemptCount() != 0 { t.Fatalf("the notification is %s with %d attempts, want it untouched", got.Status(), got.AttemptCount()) } }) t.Run("EMAIL_PROVIDER=disabled sends nothing, keeps the mail, and does not spin", func(t *testing.T) { reset(t) disabledAccount, err := domain.NewMailProviderAccount("disabled", mailSenderAccount) if err != nil { t.Fatalf("NewMailProviderAccount() error = %v", err) } stored := *harness stored.account = disabledAccount stored.mailer = notification.NewServiceMailer(notification.NewTemplateRenderer(templates), disabledAccount, clock.Now) stored.transport = disabled.NewSender() calls := len(fixture.Requests()) user := harness.createUser(ctx, t, false) _, _, deliveryID := stored.enqueueVerification(ctx, t, user, mailSenderTokenLifetime) if got := harness.delivery(ctx, t, deliveryID); got.ProviderAccount() != disabledAccount { t.Fatal("the mail stored while no transport runs is not pinned to disabled") } sender := stored.newSender(t, harness.transactor, 100, 3000) if result := stored.pass(ctx, t, sender); result.Outcome != inbound.MailPassChannelUnavailable { t.Fatalf("pass = %+v, want channel_unavailable", result) } got := harness.delivery(ctx, t, deliveryID) if got.Status() != domain.DeliveryStatusPending || got.AttemptCount() != 0 || got.Version() != 1 { t.Fatalf("delivery is %s with %d attempts at version %d, want it untouched", got.Status(), got.AttemptCount(), got.Version()) } harness.assertClaimReleased(ctx, t, deliveryID) harness.assertQuotaUsageFor(ctx, t, disabledAccount, 0) // The worker loop backs off instead of claiming again at once. metrics := prometheus.New() counted := &countingPass{inner: sender} worker, err := mailsender.New(counted, metrics, slog.New(slog.NewJSONHandler(harness.logs, nil)), mailsender.Settings{ PollInterval: 50 * time.Millisecond, Backoff: retry.Backoff{Initial: 400 * time.Millisecond, Max: time.Second}, ShutdownGrace: time.Second, }) if err != nil { t.Fatalf("mailsender.New() error = %v", err) } runCtx, stop := context.WithCancel(ctx) stopped := make(chan struct{}) go func() { defer close(stopped) worker.Run(runCtx) }() waitFor(ctx, t, "the sender gauge to show the loop", func() bool { return strings.Contains(scrapeMetrics(metrics), "lincodex_mail_sender_running 1\n") }) time.Sleep(900 * time.Millisecond) stop() <-stopped if passes := counted.passes.Load(); passes > 4 { t.Fatalf("the loop made %d passes in under a second, want it to back off", passes) } if !strings.Contains(scrapeMetrics(metrics), "lincodex_mail_sender_running 0\n") { t.Fatal("the sender gauge did not return to 0 after the loop stopped") } if len(fixture.Requests()[calls:]) != 0 { t.Fatal("the disabled transport reached the provider") } harness.assertQuotaUsageFor(ctx, t, disabledAccount, 0) // The stand now enables a transport: the mail is moved to its // account, before any attempt, and sent. live := harness.newSenderWithRebind(t, harness.transactor, 100, 3000, "disabled") if result := harness.pass(ctx, t, live); result.Outcome != inbound.MailPassAccepted || result.DeliveryID != deliveryID { t.Fatalf("pass with a transport = %+v, want accepted", result) } rebound := harness.delivery(ctx, t, deliveryID) if rebound.ProviderAccount() != harness.account || rebound.Status() != domain.DeliveryStatusAccepted { t.Fatalf("delivery is %s on %s, want accepted on the configured account", rebound.Status(), rebound.ProviderAccount().Provider()) } }) t.Run("the schema keeps cancellation, leases, and the token binding consistent", func(t *testing.T) { reset(t) user := harness.createUser(ctx, t, false) _, token, deliveryID := harness.enqueueVerification(ctx, t, user, time.Hour) other := harness.createUser(ctx, t, false) _, otherToken, _ := harness.enqueueVerification(ctx, t, other, time.Hour) checks := []struct { name string statement string args []any constraint string trigger bool }{ { name: "a cancelled delivery has a reason", statement: "UPDATE deliveries SET status = 'cancelled', next_attempt_at = NULL WHERE id = $1", args: []any{deliveryID}, constraint: "deliveries_cancel_reason_matches_status", }, { name: "a reason belongs only to a cancelled delivery", statement: "UPDATE deliveries SET cancel_reason = 'token_revoked' WHERE id = $1", args: []any{deliveryID}, constraint: "deliveries_cancel_reason_matches_status", }, { name: "a lease has an owner and a deadline together", statement: "UPDATE deliveries SET claim_owner = $2 WHERE id = $1", args: []any{deliveryID, uuid.New()}, constraint: "deliveries_claim_complete", }, { name: "a terminal delivery holds no lease", statement: "UPDATE deliveries SET status = 'rejected', next_attempt_at = NULL, claim_owner = $2, claimed_until = now() WHERE id = $1", args: []any{deliveryID, uuid.New()}, constraint: "deliveries_claim_complete", }, { name: "the kind of a stored delivery never changes", statement: "UPDATE deliveries SET kind = 'notification', template_version = 'notification.v1' WHERE id = $1", args: []any{deliveryID}, constraint: "deliveries_content_immutable", trigger: true, }, { name: "a notification carries no token", statement: `INSERT INTO deliveries ( id, recipient_user_id, recipient_email, kind, template_version, subject, text_body, html_body, content_sha256, provider, provider_account, idempotency_key, status, attempt_count, next_attempt_at, version, created_at, updated_at, email_token_id ) SELECT gen_random_uuid(), recipient_user_id, recipient_email, 'notification', 'notification.v1', subject, text_body, html_body, content_sha256, provider, provider_account, 'delivery/' || gen_random_uuid()::text, status, attempt_count, next_attempt_at, version, created_at, updated_at, email_token_id FROM deliveries WHERE id = $1`, args: []any{deliveryID}, constraint: "deliveries_token_only_for_token_kinds", }, { name: "the token binding never changes", statement: "UPDATE deliveries SET email_token_id = $2 WHERE id = $1", args: []any{deliveryID, otherToken.ID}, constraint: "deliveries_content_immutable", trigger: true, }, } for _, check := range checks { _, err := pool.Exec(ctx, check.statement, check.args...) if check.trigger { assertSQLRefusal(t, err, check.constraint) continue } var pgError interface{ SQLState() string } if !errors.As(err, &pgError) || pgError.SQLState() != checkViolationCode { t.Fatalf("%s: error = %v, want a check violation", check.name, err) } if !strings.Contains(err.Error(), check.constraint) { t.Fatalf("%s: error = %v, want constraint %s", check.name, err, check.constraint) } } // A token that a delivery references cannot disappear on its own. if _, err := pool.Exec(ctx, "DELETE FROM email_tokens WHERE id = $1", token.ID); err == nil { t.Fatal("a token that a delivery is bound to was deleted") } // Deleting the account removes both. harness.exec(ctx, t, "DELETE FROM users WHERE id = $1", user.ID) assertRowCount(ctx, t, pool, pgx.Identifier{"email_tokens"}, 1) assertRowCount(ctx, t, pool, pgx.Identifier{"deliveries"}, 1) }) } func (harness *senderHarness) createUser(ctx context.Context, t *testing.T, verified bool) domain.User { t.Helper() harness.users++ hash, err := domain.NewPasswordHash(identityTestPasswordHash) if err != nil { t.Fatalf("NewPasswordHash() error = %v", err) } user, err := domain.NewUser(domain.Registration{ Email: mustEmail(t, fmt.Sprintf("Synthetic.User%d@Example.com", harness.users)), PasswordHash: hash, Scenario: domain.ScenarioCandidate, RegisteredAt: harness.clock.Now(), }) if err != nil { t.Fatalf("NewUser() error = %v", err) } if err := harness.identity.Users().Create(ctx, user); err != nil { t.Fatalf("create the account: %v", err) } if !verified { return user } confirmed, err := harness.identity.Users().MarkEmailVerified(ctx, user.ID, user.RegistrationVersion, harness.clock.Now()) if err != nil { t.Fatalf("verify the account: %v", err) } return confirmed } // enqueueVerification issues a token and stores its mail in one transaction, // as the registration flow will. func (harness *senderHarness) enqueueVerification(ctx context.Context, t *testing.T, user domain.User, lifetime time.Duration) (domain.SecretToken, domain.EmailToken, uuid.UUID) { t.Helper() raw, err := domain.NewSecretToken() if err != nil { t.Fatalf("NewSecretToken() error = %v", err) } token, err := domain.NewEmailToken(domain.NewEmailTokenInput{ UserID: user.ID, Purpose: domain.EmailTokenPurposeEmailVerification, TokenHash: raw.Hash(), RegistrationVersion: user.RegistrationVersion, IssuedAt: harness.clock.Now(), Lifetime: lifetime, }) if err != nil { t.Fatalf("NewEmailToken() error = %v", err) } var deliveryID uuid.UUID err = harness.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { if err := unit.EmailTokens().Insert(ctx, token); err != nil { return err } deliveryID, err = harness.mailer.EnqueueVerification(ctx, unit, notification.TokenMailRequest{ Recipient: user.Email, Token: token, RawToken: raw, Lifetime: domain.Hours(lifetime / time.Hour), }) return err }) if err != nil { t.Fatalf("enqueue the verification mail: %v", err) } return raw, token, deliveryID } func (harness *senderHarness) newSender(t *testing.T, transactor outbound.Transactor, daily, monthly int64) *notification.ServiceMailSender { t.Helper() return harness.newSenderWithRebind(t, transactor, daily, monthly, "") } func (harness *senderHarness) newSenderWithRebind(t *testing.T, transactor outbound.Transactor, daily, monthly int64, rebindProvider string) *notification.ServiceMailSender { t.Helper() limits, err := domain.NewMailQuotaLimits(daily, monthly) if err != nil { t.Fatalf("NewMailQuotaLimits() error = %v", err) } logger := slog.New(slog.NewJSONHandler(harness.logs, nil)) // The idempotency window is the one of Resend; the disabled transport // has none, which only matters after a lost attempt. gate := notification.NewQuotaGate(harness.account, limits, resend.IdempotencyWindow, harness.clock.Now, logger) sender, err := notification.NewServiceMailSender(transactor, harness.transport, gate, notification.ServiceMailSenderSettings{ Account: harness.account, RebindProvider: rebindProvider, Lease: mailSenderLease, StoreTimeout: 30 * time.Second, SettleBudget: mailSenderSettleBudget, ShutdownSettleBudget: time.Second, MaxFailures: 3, Retry: notification.RetryPolicy{Initial: time.Minute, Max: 30 * time.Minute}, }, harness.clock.Now, logger) if err != nil { t.Fatalf("NewServiceMailSender() error = %v", err) } return sender } func (harness *senderHarness) pass(ctx context.Context, t *testing.T, sender *notification.ServiceMailSender) inbound.MailPassResult { t.Helper() result, err := sender.ProcessNext(ctx, ctx) if err != nil { t.Fatalf("ProcessNext() error = %v", err) } return result } func (harness *senderHarness) delivery(ctx context.Context, t *testing.T, id uuid.UUID) domain.Delivery { t.Helper() delivery, err := harness.deliveries.Get(ctx, id) if err != nil { t.Fatalf("Get(%s) error = %v", id, err) } return delivery } func (harness *senderHarness) attempts(ctx context.Context, t *testing.T, id uuid.UUID) []domain.DeliveryAttempt { t.Helper() attempts, err := harness.deliveries.ListAttempts(ctx, id) if err != nil { t.Fatalf("ListAttempts(%s) error = %v", id, err) } return attempts } func (harness *senderHarness) exec(ctx context.Context, t *testing.T, statement string, args ...any) { t.Helper() if _, err := harness.pool.Exec(ctx, statement, args...); err != nil { t.Fatalf("exec %q: %v", statement, err) } } func (harness *senderHarness) claimOf(ctx context.Context, t *testing.T, id uuid.UUID) (*uuid.UUID, *time.Time) { t.Helper() var owner *uuid.UUID var until *time.Time if err := harness.pool.QueryRow(ctx, "SELECT claim_owner, claimed_until FROM deliveries WHERE id = $1", id).Scan(&owner, &until); err != nil { t.Fatalf("read the lease of %s: %v", id, err) } return owner, until } func (harness *senderHarness) assertClaimReleased(ctx context.Context, t *testing.T, id uuid.UUID) { t.Helper() if owner, until := harness.claimOf(ctx, t, id); owner != nil || until != nil { t.Fatalf("delivery %s still holds a lease", id) } } func (harness *senderHarness) assertQuotaUsage(ctx context.Context, t *testing.T, want int64) { t.Helper() harness.assertQuotaUsageFor(ctx, t, harness.account, want) } // assertQuotaUsageFor checks the recipients counted today and this month // under account, by the fake clock. func (harness *senderHarness) assertQuotaUsageFor(ctx context.Context, t *testing.T, account domain.MailProviderAccount, want int64) { t.Helper() usage, err := postgresadapter.NewMailQuotaStore(harness.pool).MailQuotas().Usage(ctx, account, domain.MailQuotaWindowsAt(harness.clock.Now())) if err != nil { t.Fatalf("Usage() error = %v", err) } if usage.DayUsed != want || usage.MonthUsed != want { t.Fatalf("quota usage under %s = %d today and %d this month, want %d", account.Provider(), usage.DayUsed, usage.MonthUsed, want) } } func (harness *senderHarness) assertLogsHoldNoSecrets(t *testing.T, forbidden ...string) { t.Helper() logs := harness.logs.String() for _, marker := range forbidden { if marker != "" && strings.Contains(logs, marker) { t.Fatalf("a secret or an address reached the logs:\n%s", logs) } } } func scrapeMetrics(metrics *prometheus.Metrics) string { recorder := httptest.NewRecorder() metrics.Handler().ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/metrics", nil)) return recorder.Body.String() }