//go:build integration package integration_test import ( "context" "errors" "log/slog" "strings" "sync" "testing" "time" "github.com/google/uuid" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgx/v5/pgxpool" "lincodex/backend/config" "lincodex/backend/internal/adapter/secondary/mail/resend" postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" "lincodex/backend/internal/domain" "lincodex/backend/internal/port/outbound" "lincodex/backend/internal/usecase/notification" ) const ( quotaTestTimeout = 3 * time.Minute // quotaConcurrentSenders reserve at once; each holds its own connection, // so they really contend for the window rows. quotaConcurrentSenders = 12 quotaAccount = "integration" ) var ( mailQuotaUsageTable = pgx.Identifier{"mail_quota_usage"} mailQuotaReservationsTable = pgx.Identifier{"mail_quota_reservations"} ) // quotaHarness drives notification.QuotaGate against PostgreSQL with a fake // clock that the test moves. type quotaHarness struct { pool *pgxpool.Pool transactor *postgresadapter.Transactor deliveries outbound.DeliveryRepository recipients *deliveryHarness logs *syncBuffer now time.Time } func TestMailQuota(t *testing.T) { env := bootstrap(t, postgresService) ctx, cancel := context.WithTimeout(t.Context(), quotaTestTimeout) defer cancel() pool := env.newPoolWithMaxConns(ctx, t, quotaConcurrentSenders+1) harness := "aHarness{ pool: pool, transactor: postgresadapter.NewTransactor(pool), deliveries: postgresadapter.NewDeliveryStore(pool).Deliveries(), logs: &syncBuffer{}, } harness.recipients = &deliveryHarness{env: env, pool: pool, identity: postgresadapter.NewIdentityStore(pool), logs: harness.logs} reset := func(t *testing.T, now time.Time) domain.User { t.Helper() truncateTables(ctx, t, pool, append([]pgx.Identifier{mailQuotaUsageTable, mailQuotaReservationsTable}, append(deliveryTables, identityTables...)...)...) harness.now = now harness.recipients.now = now return harness.recipients.createRecipient(ctx, t, true) } t.Run("concurrent reservations admit exactly the remaining daily quota", func(t *testing.T) { now := time.Date(2026, 10, 6, 15, 0, 0, 0, time.UTC) recipient := reset(t, now) gate := harness.gate(t, "resend", 10, 3000) account := mustProviderAccount(t, "resend") midnight := time.Date(2026, 10, 7, 0, 0, 0, 0, time.UTC) // The first round starts on windows that have no row yet, so the // row creation races as well; the second starts at 7 of 10. harness.reserveConcurrently(ctx, t, gate, harness.createDeliveries(ctx, t, recipient, account, quotaConcurrentSenders), 10, midnight) harness.assertUsage(ctx, t, account, now, 10, 10) recipient2 := reset(t, now) for _, delivery := range harness.createDeliveries(ctx, t, recipient2, account, 7) { if !harness.prepare(ctx, t, gate, delivery).Proceed() { t.Fatal("a send within the daily limit was not admitted") } } harness.reserveConcurrently(ctx, t, gate, harness.createDeliveries(ctx, t, recipient2, account, quotaConcurrentSenders), 3, midnight) harness.assertUsage(ctx, t, account, now, 10, 10) harness.assertLogsHoldNoPersonalData(t) }) t.Run("the fake clock crosses midnight UTC and the month boundary", func(t *testing.T) { start := time.Date(2026, 10, 30, 22, 0, 0, 0, time.UTC) recipient := reset(t, start) gate := harness.gate(t, "resend", 2, 3) account := mustProviderAccount(t, "resend") deliveries := harness.createDeliveries(ctx, t, recipient, account, 4) for _, delivery := range deliveries[:2] { if !harness.prepare(ctx, t, gate, delivery).Proceed() { t.Fatal("a send within the limits was not admitted") } } // The day is full: the third waits for 00:00 UTC. dayReset := time.Date(2026, 10, 31, 0, 0, 0, 0, time.UTC) third := harness.prepare(ctx, t, gate, deliveries[2]) harness.assertWaiting(ctx, t, third, deliveries[2].ID(), dayReset) // One second before midnight it still waits; at midnight it goes. harness.now = dayReset.Add(-time.Second) harness.assertWaiting(ctx, t, harness.prepare(ctx, t, gate, harness.get(ctx, t, deliveries[2].ID())), deliveries[2].ID(), dayReset) harness.now = dayReset if !harness.prepare(ctx, t, gate, harness.get(ctx, t, deliveries[2].ID())).Proceed() { t.Fatal("the waiting delivery was not admitted after midnight UTC") } // The new day has room, but the month is full: the fourth waits for // the first day of the next month. monthReset := time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC) harness.assertWaiting(ctx, t, harness.prepare(ctx, t, gate, deliveries[3]), deliveries[3].ID(), monthReset) harness.now = monthReset if !harness.prepare(ctx, t, gate, harness.get(ctx, t, deliveries[3].ID())).Proceed() { t.Fatal("the waiting delivery was not admitted in the new month") } harness.assertUsage(ctx, t, account, start, 2, 3) harness.assertUsage(ctx, t, account, dayReset, 1, 3) harness.assertUsage(ctx, t, account, monthReset, 1, 1) assertRowCount(ctx, t, pool, mailQuotaUsageTable, 5) }) t.Run("a lowered limit defers sends and switching to SMTP does not skip the quota", func(t *testing.T) { now := time.Date(2026, 10, 6, 9, 0, 0, 0, time.UTC) recipient := reset(t, now) resend := mustProviderAccount(t, "resend") gate := harness.gateFromConfig(t, map[string]string{"EMAIL_PROVIDER": "resend", "RESEND_API_KEY": "re_integration"}) for _, delivery := range harness.createDeliveries(ctx, t, recipient, resend, 4) { if !harness.prepare(ctx, t, gate, delivery).Proceed() { t.Fatal("a send within the default limit was not admitted") } } // The operator lowers the daily limit below today's usage. lowered := harness.gateFromConfig(t, map[string]string{"EMAIL_PROVIDER": "resend", "RESEND_API_KEY": "re_integration", "EMAIL_QUOTA_DAILY": "3"}) waiting := harness.createDeliveries(ctx, t, recipient, resend, 1)[0] harness.assertWaiting(ctx, t, harness.prepare(ctx, t, lowered, waiting), waiting.ID(), time.Date(2026, 10, 7, 0, 0, 0, 0, time.UTC)) harness.assertUsage(ctx, t, resend, now, 4, 4) // smtp needs stated limits: without them the process does not start. smtpSettings := map[string]string{ "EMAIL_PROVIDER": "smtp", "SMTP_HOST": "smtp.example.com", "SMTP_PORT": "587", "SMTP_USERNAME": "mailer", "SMTP_PASSWORD": "integration-password", "SMTP_TLS_MODE": "starttls", } if _, err := loadQuotaConfig(smtpSettings); err == nil { t.Fatal("smtp without EMAIL_QUOTA_DAILY and EMAIL_QUOTA_MONTHLY was accepted") } smtpSettings["EMAIL_QUOTA_DAILY"] = "2" smtpSettings["EMAIL_QUOTA_MONTHLY"] = "2" smtpGate := harness.gateFromConfig(t, smtpSettings) smtp := mustProviderAccount(t, "smtp") relayed := harness.createDeliveries(ctx, t, recipient, smtp, 3) for _, delivery := range relayed[:2] { if !harness.prepare(ctx, t, smtpGate, delivery).Proceed() { t.Fatal("an SMTP send within its limit was not admitted") } } harness.assertWaiting(ctx, t, harness.prepare(ctx, t, smtpGate, relayed[2]), relayed[2].ID(), time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC)) harness.assertUsage(ctx, t, smtp, now, 2, 2) // A delivery pinned to the old account is not sent through the relay // without a limit: the gate refuses it and reserves nothing. err := harness.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { _, err := smtpGate.PrepareSend(ctx, unit, waiting) return err }) if !errors.Is(err, notification.ErrQuotaNotConfigured) { t.Fatalf("PrepareSend() for a Resend delivery under smtp error = %v, want ErrQuotaNotConfigured", err) } harness.assertUsage(ctx, t, resend, now, 4, 4) }) t.Run("a provider quota answer refines the local count", func(t *testing.T) { now := time.Date(2026, 10, 6, 20, 0, 0, 0, time.UTC) recipient := reset(t, now) gate := harness.gate(t, "resend", 100, 3000) account := mustProviderAccount(t, "resend") deliveries := harness.createDeliveries(ctx, t, recipient, account, 4) midnight := time.Date(2026, 10, 7, 0, 0, 0, 0, time.UTC) // A temporary failure before the request was written gives the // reservation back. temporary := harness.prepare(ctx, t, gate, deliveries[0]) harness.settle(ctx, t, gate, temporary, outbound.SendResult{ Outcome: outbound.MailOutcomeRejected, Rejection: outbound.MailRejectionTemporary, }, now.Add(time.Minute)) harness.assertUsage(ctx, t, account, now, 0, 0) // Resend refuses with daily_quota_exceeded although the local count // is 1 of 100, for example because the account also sends elsewhere. refused := harness.prepare(ctx, t, gate, deliveries[1]) stored := harness.settle(ctx, t, gate, refused, outbound.SendResult{ Outcome: outbound.MailOutcomeRejected, Rejection: outbound.MailRejectionQuotaExhausted, ProviderCode: "daily_quota_exceeded", RetryAfter: midnight.Sub(now), QuotaPeriod: domain.MailQuotaPeriodDay, }, time.Time{}) if stored.Status() != domain.DeliveryStatusWaitingQuota || !stored.NextAttemptAt().Equal(midnight) || stored.AttemptCount() != 1 { t.Fatalf("refused delivery is %s due %s after %d attempts, want waiting_quota due %s", stored.Status(), stored.NextAttemptAt(), stored.AttemptCount(), midnight) } harness.assertUsage(ctx, t, account, now, 100, 0) var exhaustedAt time.Time if err := pool.QueryRow(ctx, "SELECT provider_exhausted_at FROM mail_quota_usage WHERE period_kind = 'day'").Scan(&exhaustedAt); err != nil || !exhaustedAt.Equal(now) { t.Fatalf("provider_exhausted_at = %s, %v; want %s", exhaustedAt, err, now) } // The gate now stops before the provider. harness.assertWaiting(ctx, t, harness.prepare(ctx, t, gate, deliveries[2]), deliveries[2].ID(), midnight) // Next day: Resend refuses with monthly_quota_exceeded and no hint. // The month is marked full and the delivery waits for the month // start. harness.now = midnight monthly := harness.prepare(ctx, t, gate, harness.get(ctx, t, deliveries[1].ID())) stored = harness.settle(ctx, t, gate, monthly, outbound.SendResult{ Outcome: outbound.MailOutcomeRejected, Rejection: outbound.MailRejectionQuotaExhausted, ProviderCode: "monthly_quota_exceeded", QuotaPeriod: domain.MailQuotaPeriodMonth, }, time.Time{}) monthReset := time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC) if stored.Status() != domain.DeliveryStatusWaitingQuota || !stored.NextAttemptAt().Equal(monthReset) { t.Fatalf("refused delivery is %s due %s, want waiting_quota due %s", stored.Status(), stored.NextAttemptAt(), monthReset) } harness.assertUsage(ctx, t, account, midnight, 0, 3000) harness.assertWaiting(ctx, t, harness.prepare(ctx, t, gate, deliveries[3]), deliveries[3].ID(), monthReset) harness.assertLogsHoldNoPersonalData(t) }) t.Run("deleting an account keeps the usage counted", func(t *testing.T) { now := time.Date(2026, 10, 6, 12, 0, 0, 0, time.UTC) recipient := reset(t, now) gate := harness.gate(t, "resend", 3, 3000) account := mustProviderAccount(t, "resend") for _, delivery := range harness.createDeliveries(ctx, t, recipient, account, 3) { permit := harness.prepare(ctx, t, gate, delivery) harness.settle(ctx, t, gate, permit, outbound.SendResult{Outcome: outbound.MailOutcomeAccepted, ProviderMessageID: uuid.NewString()}, time.Time{}) } if _, err := pool.Exec(ctx, "DELETE FROM users WHERE id = $1", recipient.ID); err != nil { t.Fatalf("delete the recipient account: %v", err) } assertRowCount(ctx, t, pool, pgx.Identifier{"deliveries"}, 0) assertRowCount(ctx, t, pool, pgx.Identifier{"delivery_attempts"}, 0) harness.assertUsage(ctx, t, account, now, 3, 3) // A send for another account the same day is still over the limit. harness.recipients.now = now other := harness.createRecipientWithAddress(ctx, t, "other.recipient@example.com") delivery := harness.createDeliveries(ctx, t, other, account, 1)[0] harness.assertWaiting(ctx, t, harness.prepare(ctx, t, gate, delivery), delivery.ID(), time.Date(2026, 10, 7, 0, 0, 0, 0, time.UTC)) }) t.Run("releases, marks, and reservations in opposite row orders never deadlock", func(t *testing.T) { dayOne := time.Date(2026, 10, 6, 10, 0, 0, 0, time.UTC) reset(t, dayOne) account := mustProviderAccount(t, "resend") limits, err := domain.NewMailQuotaLimits(1_000_000, 1_000_000) if err != nil { t.Fatalf("NewMailQuotaLimits() error = %v", err) } // Day one creates the month row before the day-two row, so a scan // of day two meets the month row first in heap order: the order in // which an UPDATE without the ordered lock locked them, against a // reservation that locks the day first. earlier := make([]outbound.MailQuotaReservation, quotaStressRounds) for index := range earlier { earlier[index] = harness.reserveDirectly(ctx, t, account, limits, dayOne) } dayTwo := dayOne.Add(24 * time.Hour) current := make([]outbound.MailQuotaReservation, quotaStressRounds) for index := range current { current[index] = harness.reserveDirectly(ctx, t, account, limits, dayTwo) } // Heap-order plans, as in the queued case below. heapOrder := postgresadapter.NewTransactor(env.newPoolWithRuntimeParams(ctx, t, map[string]string{"enable_indexscan": "off"})) settle := func(settlement outbound.MailQuotaSettlement) error { return heapOrder.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { _, err := unit.MailQuotas().Settle(ctx, settlement) return err }) } reserve := func() error { return heapOrder.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { _, err := unit.MailQuotas().Reserve(ctx, outbound.MailQuotaReserveRequest{Reservation: newReservation(t, account, dayTwo), Limits: limits}) return err }) } for round := range quotaStressRounds { // A release of day two, a release of day one that marks day two // across midnight, and two reservations of day two start at once. errs := runAtOnce( func() error { return settle(outbound.MailQuotaSettlement{Reservation: current[round], Outcome: outbound.MailQuotaOutcomeRejected, Release: true, At: dayTwo}) }, func() error { return settle(outbound.MailQuotaSettlement{ Reservation: earlier[round], Outcome: outbound.MailQuotaOutcomeRejected, Release: true, At: dayTwo, ExhaustedPeriod: domain.MailQuotaPeriodDay, ExhaustedWindows: domain.MailQuotaWindowsAt(dayTwo), ExhaustedLimit: 1, }) }, reserve, reserve, ) for _, err := range errs { if err != nil { t.Fatalf("round %d: concurrent quota write error = %v (deadlock: %t)", round, err, errors.Is(err, outbound.ErrTransactionConflict)) } } } }) t.Run("a release queued behind a reservation on the day row does not deadlock", func(t *testing.T) { day := time.Date(2026, 10, 7, 10, 0, 0, 0, time.UTC) account := mustProviderAccount(t, "resend") limits, err := domain.NewMailQuotaLimits(1000, 1000) if err != nil { t.Fatalf("NewMailQuotaLimits() error = %v", err) } // Without the index the planner scans in heap order, as the bitmap // plan that reproduced the deadlock did. The fixed lock order must // not depend on the plan. heapOrder := postgresadapter.NewTransactor(env.newPoolWithRuntimeParams(ctx, t, map[string]string{"enable_indexscan": "off"})) for _, releaseFirst := range []bool{false, true} { reset(t, day) // The month row is written before the day row, so a scan meets // it first: the order in which an UPDATE without the ordered // lock took the rows, against a reservation that takes the day // row first. opened := newReservation(t, account, day) for _, statement := range []string{ "INSERT INTO mail_quota_usage VALUES ('resend', 'integration', 'month', '2026-10-01', 1, NULL, $1)", "INSERT INTO mail_quota_usage VALUES ('resend', 'integration', 'day', '2026-10-07', 1, NULL, $1)", } { if _, err := pool.Exec(ctx, statement, day); err != nil { t.Fatalf("prepare usage rows: %v", err) } } if _, err := pool.Exec(ctx, `INSERT INTO mail_quota_reservations (id, delivery_id, provider, provider_account, day_start, month_start, recipients, reserved_at) VALUES ($1, $2, 'resend', 'integration', '2026-10-07', '2026-10-01', 1, $3)`, opened.ID, opened.DeliveryID, day); err != nil { t.Fatalf("prepare the open reservation: %v", err) } // A third transaction holds the day row, so both writers queue // on it in a chosen order. blocker, err := pool.Begin(ctx) if err != nil { t.Fatalf("begin the blocking transaction: %v", err) } if _, err := blocker.Exec(ctx, "SELECT 1 FROM mail_quota_usage WHERE period_kind = 'day' FOR UPDATE"); err != nil { t.Fatalf("lock the day row: %v", err) } release := func() error { return heapOrder.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { _, err := unit.MailQuotas().Settle(ctx, outbound.MailQuotaSettlement{Reservation: opened, Outcome: outbound.MailQuotaOutcomeRejected, Release: true, At: day}) return err }) } reserve := func() error { return heapOrder.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { _, err := unit.MailQuotas().Reserve(ctx, outbound.MailQuotaReserveRequest{Reservation: newReservation(t, account, day), Limits: limits}) return err }) } first, second := reserve, release if releaseFirst { first, second = release, reserve } results := make(chan error, 2) go func() { results <- first() }() harness.waitForLockWaiters(ctx, t, 1) go func() { results <- second() }() harness.waitForLockWaiters(ctx, t, 2) if err := blocker.Rollback(ctx); err != nil { t.Fatalf("release the day row: %v", err) } for range 2 { if err := <-results; err != nil { t.Fatalf("release first %t: queued quota write error = %v (deadlock: %t)", releaseFirst, err, errors.Is(err, outbound.ErrTransactionConflict)) } } harness.assertUsage(ctx, t, account, day, 1, 1) } }) t.Run("a release happens once and a retry inside the idempotency window reuses its reservation", func(t *testing.T) { now := time.Date(2026, 10, 6, 10, 0, 0, 0, time.UTC) recipient := reset(t, now) gate := harness.gate(t, "resend", 100, 3000) account := mustProviderAccount(t, "resend") deliveries := harness.createDeliveries(ctx, t, recipient, account, 2) // A transport error is settled twice, as after a commit whose // answer was lost: the journal releases it once. notSent := harness.prepare(ctx, t, gate, deliveries[0]) harness.prepare(ctx, t, gate, deliveries[1]) for range 2 { err := harness.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { _, err := gate.SettleSend(ctx, unit, notSent.Permit, outbound.SendResult{}, context.Canceled) return err }) if err != nil { t.Fatalf("SettleSend() error = %v", err) } } harness.assertUsage(ctx, t, account, now, 1, 1) // An unknown attempt keeps its reservation; the retry an hour later // reuses it, and the one after the 24-hour window counts again. uncertain := harness.prepare(ctx, t, gate, deliveries[1]) if !uncertain.Permit.Reused() { t.Fatal("the second prepare of an open reservation did not reuse it") } stored := harness.settle(ctx, t, gate, uncertain, outbound.SendResult{Outcome: outbound.MailOutcomeUnknown}, now.Add(time.Hour)) harness.now = now.Add(time.Hour) if retry := harness.prepare(ctx, t, gate, stored); !retry.Proceed() || !retry.Permit.Reused() { t.Fatalf("retry inside the window: proceed %t, reused %t", retry.Proceed(), retry.Permit.Reused()) } harness.assertUsage(ctx, t, account, now, 1, 1) harness.now = now.Add(resend.IdempotencyWindow + time.Hour) if late := harness.prepare(ctx, t, gate, stored); !late.Proceed() || late.Permit.Reused() { t.Fatalf("retry after the window: proceed %t, reused %t", late.Proceed(), late.Permit.Reused()) } harness.assertUsage(ctx, t, account, harness.now, 1, 2) var open, released, settled int err := pool.QueryRow(ctx, `SELECT count(*) FILTER (WHERE released_at IS NULL), count(*) FILTER (WHERE released_at IS NOT NULL), count(*) FILTER (WHERE settled_outcome IS NOT NULL) FROM mail_quota_reservations`).Scan(&open, &released, &settled) if err != nil || open != 2 || released != 1 || settled != 2 { t.Fatalf("journal: open %d, released %d, settled %d, %v; want 2, 1, 2", open, released, settled, err) } }) t.Run("the account sees its waiting mail and nobody else's", func(t *testing.T) { now := time.Date(2026, 10, 6, 18, 0, 0, 0, time.UTC) recipient := reset(t, now) gate := harness.gate(t, "resend", 1, 3000) account := mustProviderAccount(t, "resend") reader := notification.NewDeliveryStatusReader(harness.deliveries) if _, found, err := reader.LatestForUser(ctx, recipient.ID, domain.MailKindNotification); err != nil || found { t.Fatalf("LatestForUser() before any mail = %t, %v; want nothing", found, err) } harness.prepare(ctx, t, gate, harness.createDeliveries(ctx, t, recipient, account, 1)[0]) harness.now = now.Add(time.Minute) harness.prepare(ctx, t, gate, harness.createDeliveries(ctx, t, recipient, account, 1)[0]) status, found, err := reader.LatestForUser(ctx, recipient.ID, domain.MailKindNotification) midnight := time.Date(2026, 10, 7, 0, 0, 0, 0, time.UTC) if err != nil || !found || !status.WaitingForQuota() || !status.WaitingUntil.Equal(midnight) { t.Fatalf("LatestForUser() = %+v, %t, %v; want waiting until %s", status, found, err, midnight) } other := harness.createRecipientWithAddress(ctx, t, "someone.else@example.com") if _, found, err := reader.LatestForUser(ctx, other.ID, domain.MailKindNotification); err != nil || found { t.Fatalf("LatestForUser() for another account = %t, %v; want nothing", found, err) } if _, found, err := reader.LatestForUser(ctx, recipient.ID, domain.MailKindVerification); err != nil || found { t.Fatalf("LatestForUser() for another kind = %t, %v; want nothing", found, err) } }) t.Run("startup reports the usage and a renamed account", func(t *testing.T) { now := time.Date(2026, 10, 6, 9, 0, 0, 0, time.UTC) recipient := reset(t, now) oldLabel, err := domain.NewMailProviderAccount("resend", "old-label") if err != nil { t.Fatalf("NewMailProviderAccount() error = %v", err) } limits, err := domain.NewMailQuotaLimits(100, 3000) if err != nil { t.Fatalf("NewMailQuotaLimits() error = %v", err) } oldGate := notification.NewQuotaGate(oldLabel, limits, resend.IdempotencyWindow, harness.clock, slog.New(slog.NewJSONHandler(harness.logs, nil))) harness.prepare(ctx, t, oldGate, harness.createDeliveries(ctx, t, recipient, oldLabel, 1)[0]) harness.prepare(ctx, t, harness.gate(t, "resend", 100, 3000), harness.createDeliveries(ctx, t, recipient, mustProviderAccount(t, "resend"), 1)[0]) logs := &syncBuffer{} reader := postgresadapter.NewMailQuotaStore(pool).MailQuotas() if err := notification.ReportQuotaUsage(ctx, reader, mustProviderAccount(t, "resend"), limits, now, slog.New(slog.NewJSONHandler(logs, nil))); err != nil { t.Fatalf("ReportQuotaUsage() error = %v", err) } for _, want := range []string{`"account":"integration"`, `"day_used":1`, `"month_used":1`, `"other_accounts":["old-label"]`} { if !strings.Contains(logs.String(), want) { t.Fatalf("startup report lacks %s: %s", want, logs.String()) } } }) t.Run("the database refuses invalid usage rows", func(t *testing.T) { reset(t, time.Date(2026, 10, 6, 12, 0, 0, 0, time.UTC)) for constraint, statement := range map[string]string{ "mail_quota_usage_period_kind_known": "INSERT INTO mail_quota_usage VALUES ('resend', 'main', 'week', '2026-10-05', 0, NULL, now())", "mail_quota_usage_month_starts_on_day_one": "INSERT INTO mail_quota_usage VALUES ('resend', 'main', 'month', '2026-10-05', 0, NULL, now())", "mail_quota_usage_used_not_negative": "INSERT INTO mail_quota_usage VALUES ('resend', 'main', 'day', '2026-10-05', -1, NULL, now())", "mail_quota_usage_provider_account_format": "INSERT INTO mail_quota_usage VALUES ('resend', 'Main Account', 'day', '2026-10-05', 0, NULL, now())", "mail_quota_reservations_windows_match": "INSERT INTO mail_quota_reservations (id, delivery_id, provider, provider_account, day_start, month_start, recipients, reserved_at) " + "VALUES (gen_random_uuid(), gen_random_uuid(), 'resend', 'main', '2026-11-01', '2026-10-01', 1, now())", "mail_quota_reservations_outcome_known": "INSERT INTO mail_quota_reservations (id, delivery_id, provider, provider_account, day_start, month_start, recipients, reserved_at, settled_outcome, settled_at) " + "VALUES (gen_random_uuid(), gen_random_uuid(), 'resend', 'main', '2026-10-05', '2026-10-01', 1, now(), 'sent', now())", } { _, err := pool.Exec(ctx, statement) assertCheckViolation(t, err, constraint) } }) } func (harness *quotaHarness) clock() time.Time { return harness.now } // quotaStressRounds bounds the concurrency run; a deadlock shows up as a // 40P01 error after PostgreSQL's deadlock_timeout. const quotaStressRounds = 60 func newReservation(t *testing.T, account domain.MailProviderAccount, at time.Time) outbound.MailQuotaReservation { t.Helper() return outbound.MailQuotaReservation{ ID: uuid.Must(uuid.NewV7()), DeliveryID: uuid.Must(uuid.NewV7()), Account: account, Windows: domain.MailQuotaWindowsAt(at), Recipients: 1, ReservedAt: at, } } // reserveDirectly reserves through the repository, without a delivery row. func (harness *quotaHarness) reserveDirectly(ctx context.Context, t *testing.T, account domain.MailProviderAccount, limits domain.MailQuotaLimits, at time.Time) outbound.MailQuotaReservation { t.Helper() var reserved outbound.MailQuotaReservation err := harness.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { result, err := unit.MailQuotas().Reserve(ctx, outbound.MailQuotaReserveRequest{Reservation: newReservation(t, account, at), Limits: limits}) reserved = result.Reservation return err }) if err != nil { t.Fatalf("Reserve() error = %v", err) } return reserved } // quotaLockWaitTimeout bounds the wait for a writer to queue on a row lock. const quotaLockWaitTimeout = 10 * time.Second // waitForLockWaiters waits until want backends of this database wait for a // row lock. func (harness *quotaHarness) waitForLockWaiters(ctx context.Context, t *testing.T, want int) { t.Helper() deadline := time.Now().Add(quotaLockWaitTimeout) for { var waiting int err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM pg_stat_activity WHERE datname = current_database() AND wait_event_type = 'Lock'`).Scan(&waiting) if err != nil { t.Fatalf("count lock waiters: %v", err) } if waiting >= want { return } if time.Now().After(deadline) { t.Fatalf("%d backends wait for a lock, want %d", waiting, want) } time.Sleep(10 * time.Millisecond) } } // newPoolWithRuntimeParams opens a pool whose sessions use the given // PostgreSQL settings. func (env *testEnvironment) newPoolWithRuntimeParams(ctx context.Context, t *testing.T, params map[string]string) *pgxpool.Pool { t.Helper() poolConfig, err := pgxpool.ParseConfig(env.Config.DatabaseURL) if err != nil { t.Fatalf("parse bootstrap database URL: %v", err) } for key, value := range params { poolConfig.ConnConfig.RuntimeParams[key] = value } pool, err := pgxpool.NewWithConfig(ctx, poolConfig) if err != nil { t.Fatalf("create PostgreSQL pool: %v", err) } t.Cleanup(pool.Close) return pool } // runAtOnce starts every function at the same moment and returns their // errors in order. func runAtOnce(functions ...func() error) []error { errs := make([]error, len(functions)) start := make(chan struct{}) var group sync.WaitGroup for index, function := range functions { group.Go(func() { <-start errs[index] = function() }) } close(start) group.Wait() return errs } func (harness *quotaHarness) gate(t *testing.T, provider string, daily, monthly int64) *notification.QuotaGate { t.Helper() limits, err := domain.NewMailQuotaLimits(daily, monthly) if err != nil { t.Fatalf("NewMailQuotaLimits() error = %v", err) } // SMTP has no provider-side deduplication, so its retries count again. window := resend.IdempotencyWindow if provider == "smtp" { window = 0 } return notification.NewQuotaGate(mustProviderAccount(t, provider), limits, window, harness.clock, slog.New(slog.NewJSONHandler(harness.logs, nil))) } // gateFromConfig builds the gate from configuration as bootstrap will, so // the test covers the configured limits and not only the gate. func (harness *quotaHarness) gateFromConfig(t *testing.T, mail map[string]string) *notification.QuotaGate { t.Helper() settings, err := loadQuotaConfig(mail) if err != nil { t.Fatalf("LoadFromEnv() error = %v", err) } if settings.EmailAccount != quotaAccount { t.Fatalf("EmailAccount = %q, want %q", settings.EmailAccount, quotaAccount) } return harness.gate(t, string(settings.EmailProvider), int64(settings.EmailQuotaDaily), int64(settings.EmailQuotaMonthly)) } func loadQuotaConfig(mail map[string]string) (config.Config, error) { values := map[string]string{ "SEAWEEDFS_ACCESS_KEY": "test-access", "SEAWEEDFS_SECRET_KEY": "test-secret", "EMAIL_FROM": "no-reply@example.com", "EMAIL_ACCOUNT": quotaAccount, "APP_PUBLIC_URL": "http://localhost:8080", } for key, value := range mail { values[key] = value } return config.LoadFromEnv(func(key string) (string, bool) { value, ok := values[key] return value, ok }) } func mustProviderAccount(t *testing.T, provider string) domain.MailProviderAccount { t.Helper() account, err := domain.NewMailProviderAccount(provider, quotaAccount) if err != nil { t.Fatalf("NewMailProviderAccount() error = %v", err) } return account } func (harness *quotaHarness) createRecipientWithAddress(ctx context.Context, t *testing.T, address string) domain.User { t.Helper() hash, err := domain.NewPasswordHash(identityTestPasswordHash) if err != nil { t.Fatalf("NewPasswordHash() error = %v", err) } user, err := domain.NewUser(domain.Registration{ Email: mustEmail(t, address), PasswordHash: hash, Scenario: domain.ScenarioCandidate, RegisteredAt: harness.now, }) if err != nil { t.Fatalf("NewUser() error = %v", err) } if err := harness.recipients.identity.Users().Create(ctx, user); err != nil { t.Fatalf("create the recipient account: %v", err) } return user } // createDeliveries stores count pending deliveries pinned to account, due at // the current fake time. func (harness *quotaHarness) createDeliveries(ctx context.Context, t *testing.T, recipient domain.User, account domain.MailProviderAccount, count int) []domain.Delivery { t.Helper() content, err := domain.NewMailContent(domain.MailKindNotification, "notification.v1", "Синтетическое уведомление", "PRIVATE-BODY quota\n", "") if err != nil { t.Fatalf("NewMailContent() error = %v", err) } deliveries := make([]domain.Delivery, 0, count) for range count { delivery, err := domain.NewDelivery(domain.NewDeliveryInput{ ID: uuid.Must(uuid.NewV7()), RecipientUserID: recipient.ID, Recipient: recipient.Email, Content: content, ProviderAccount: account, CreatedAt: harness.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 delivery stored", created, err) } deliveries = append(deliveries, delivery) } return deliveries } func (harness *quotaHarness) prepare(ctx context.Context, t *testing.T, gate *notification.QuotaGate, delivery domain.Delivery) notification.SendDecision { t.Helper() var decision notification.SendDecision err := harness.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { var err error decision, err = gate.PrepareSend(ctx, unit, delivery) return err }) if err != nil { t.Fatalf("PrepareSend() error = %v", err) } return decision } // settle records the attempt and settles the quota in one transaction, as // the sending worker will. nextAttempt is the retry policy's choice for a // pending outcome; the quota decides it for quota_exhausted. func (harness *quotaHarness) settle( ctx context.Context, t *testing.T, gate *notification.QuotaGate, decision notification.SendDecision, result outbound.SendResult, nextAttempt time.Time, ) domain.Delivery { t.Helper() if !decision.Proceed() { t.Fatal("the send was not admitted") } err := harness.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { until, err := gate.SettleSend(ctx, unit, decision.Permit, result, nil) if err != nil { return err } if !until.IsZero() { nextAttempt = until } next, attempt, err := decision.Delivery.RecordAttempt(domain.DeliveryAttemptInput{ At: harness.now, Outcome: domain.DeliveryAttemptOutcome(result.Outcome), Rejection: domain.DeliveryRejection(result.Rejection), ProviderCode: string(result.ProviderCode), ProviderMessageID: result.ProviderMessageID, RetryAfter: result.RetryAfter, NextAttemptAt: nextAttempt, }) if err != nil { return err } return unit.Deliveries().RecordAttempt(ctx, next, attempt) }) if err != nil { t.Fatalf("settle the send: %v", err) } return harness.get(ctx, t, decision.Delivery.ID()) } // reserveConcurrently runs one PrepareSend per delivery at once and checks // that exactly admitted of them got a permit and the rest are stored as // waiting_quota until resetAt. func (harness *quotaHarness) reserveConcurrently( ctx context.Context, t *testing.T, gate *notification.QuotaGate, deliveries []domain.Delivery, admitted int, resetAt time.Time, ) { t.Helper() decisions := make([]notification.SendDecision, len(deliveries)) errs := make([]error, len(deliveries)) start := make(chan struct{}) var senders sync.WaitGroup for index, delivery := range deliveries { senders.Go(func() { <-start errs[index] = harness.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { var err error decisions[index], err = gate.PrepareSend(ctx, unit, delivery) return err }) }) } close(start) senders.Wait() proceeded := 0 for index, decision := range decisions { if errs[index] != nil { t.Fatalf("concurrent PrepareSend() error = %v", errs[index]) } if decision.Proceed() { proceeded++ continue } harness.assertWaiting(ctx, t, decision, deliveries[index].ID(), resetAt) } if proceeded != admitted { t.Fatalf("%d of %d concurrent sends were admitted, want exactly %d", proceeded, len(deliveries), admitted) } } func (harness *quotaHarness) get(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 } // assertWaiting checks the decision and the stored delivery: the status // that the operator and the later user-facing status read. func (harness *quotaHarness) assertWaiting(ctx context.Context, t *testing.T, decision notification.SendDecision, id uuid.UUID, resetAt time.Time) { t.Helper() if decision.Proceed() || !decision.ResetAt.Equal(resetAt) { t.Fatalf("decision: proceed %t, reset %s; want a wait until %s", decision.Proceed(), decision.ResetAt, resetAt) } stored := harness.get(ctx, t, id) if stored.Status() != domain.DeliveryStatusWaitingQuota || !stored.NextAttemptAt().Equal(resetAt) { t.Fatalf("stored delivery is %s due %s, want waiting_quota due %s", stored.Status(), stored.NextAttemptAt(), resetAt) } } func (harness *quotaHarness) assertUsage(ctx context.Context, t *testing.T, account domain.MailProviderAccount, at time.Time, day, month int64) { t.Helper() windows := domain.MailQuotaWindowsAt(at) for period, want := range map[domain.MailQuotaPeriod]int64{domain.MailQuotaPeriodDay: day, domain.MailQuotaPeriodMonth: month} { var used int64 err := harness.pool.QueryRow(ctx, ` SELECT coalesce(sum(used_recipients), 0) FROM mail_quota_usage WHERE provider = $1 AND provider_account = $2 AND period_kind = $3 AND period_start = $4`, account.Provider(), account.Account(), string(period), windows.Start(period).Format(time.DateOnly)).Scan(&used) if err != nil { t.Fatalf("read %s usage: %v", period, err) } if used != want { t.Fatalf("%s usage of %s at %s = %d, want %d", period, account.Provider(), windows.Start(period).Format(time.DateOnly), used, want) } } } func (harness *quotaHarness) assertLogsHoldNoPersonalData(t *testing.T) { t.Helper() harness.recipients.assertLogsHoldNoPersonalData(t) } func assertCheckViolation(t *testing.T, err error, constraint string) { t.Helper() var pgError *pgconn.PgError if !errors.As(err, &pgError) || pgError.Code != "23514" || pgError.ConstraintName != constraint { t.Fatalf("statement error = %v, want a check violation of %s", err, constraint) } }