feat(identity): add server sessions and audited mail recovery
This commit is contained in:
1 parent
20c03288d6
commit
4ee53d9a74
58 files changed
+5359
-567
No files matched your search
@@ -3,6 +3,7 @@
|
||||
package integration_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -20,6 +21,7 @@ import (
|
||||
"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"
|
||||
@@ -145,6 +147,7 @@ func TestServiceMailSending(t *testing.T) {
|
||||
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)
|
||||
@@ -173,6 +176,7 @@ func TestServiceMailSending(t *testing.T) {
|
||||
// their start instead.
|
||||
truncateTables(ctx, t, pool, slices.Concat(mailSenderTables, usersDependentTables)...)
|
||||
clock.Set(mailSenderStart)
|
||||
fixture.SetClock(clock.Now)
|
||||
fixture.SetDelay(0)
|
||||
}
|
||||
|
||||
@@ -246,6 +250,45 @@ func TestServiceMailSending(t *testing.T) {
|
||||
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())
|
||||
@@ -917,21 +960,27 @@ func TestServiceMailSending(t *testing.T) {
|
||||
t.Fatalf("attempts = %+v, want a temporary refusal and then acceptance", attempts)
|
||||
}
|
||||
|
||||
// An uncertain answer is never retried by the worker and never read
|
||||
// as not sent.
|
||||
// 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().IsZero() {
|
||||
t.Fatalf("delivery is %s with next attempt %s, want unknown without one", got.Status(), got.NextAttemptAt())
|
||||
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.MailPassIdle || len(fixture.Requests()) != callsBefore {
|
||||
t.Fatalf("pass after an unknown outcome = %+v, want idle without a call", result)
|
||||
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.
|
||||
@@ -947,6 +996,344 @@ func TestServiceMailSending(t *testing.T) {
|
||||
}
|
||||
})
|
||||
|
||||
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())
|
||||
|
||||
Reference in new issue
Block a user